feat(loki): suggested replies on every Loki chat — one tap sends the likely next message (#1115)

Adopts @bitbaum/chatkit 0.6.0 (bitbaum/chatkit#13, merged as 163c879).

- askLoki/runLokiTurn take `replies`: the model is asked for chatkit's
  quick_replies block, and it is taken out of every model reply as it
  arrives (loop rounds, retries, gateway and Groq fallbacks), so it never
  reaches a work note, the grounding verifier, or the stored answer.
  Replies return separately as body.replies.
- /loki: the messages route asks for replies and stores them in
  meta.replies; the thread shows them under the latest answer with
  chatkit's ChatReplies (the separate follow-ups call is now only the
  fallback for an answer that came without them).
- Terminal Loki rail: ChatThread gets onReply; replies hidden under a
  summary that already carries its own "→" steps.
- Floating assistant: /api/loki takes `replies`; buttons under the last
  answer.
- The live preview is stripped once, in useLokiStream, for every surface;
  plainTextForSpeech drops the block so it is never read aloud. MCP, voice
  and prompt runs do not ask for replies, and a stray block is still
  removed from their text.

Fixes found on the way:
- Floating assistant printed answers as raw text (asterisks, bare [F1]
  handles): now rendered as markdown with resolved citations; multi-line
  user turns keep their line breaks.
- /loki follow-up taps were sent on "Auto" instead of the model the
  operator last chose; the terminal rail's replies reuse its last choice.


Claude-Session: https://claude.ai/code/session_01Mg5wrkfw95JWfmAz8yRT1j

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
CatoandClaude authored and GitHub committed 2026-10-09 06:18:35 -07:00
1 parent 07b1fdee80
commit e52c65af80
15 files changed
+410 -107

No files matched your search

+1 -1
View File
@@ -118,7 +118,7 @@
"@auth/drizzle-adapter": "^1.11.3",
"@bitbaum/accountkit": "github:bitbaum/accountkit#v0.2.1",
"@bitbaum/ai-kit": "^1.20.1",
"@bitbaum/chatkit": "github:bitbaum/chatkit#70824785e86189704aeb7cc92c33bc198ad17cda",
"@bitbaum/chatkit": "github:bitbaum/chatkit#163c879163d22c6eb633314b3bd4e25712a01899",
"@bitbaum/mail-kit": "^0.1.1",
"@bitbaum/whenkit": "github:bitbaum/whenkit#v0.3.2",
"@dnd-kit/core": "^6.3.1",
+8 -13
View File
@@ -31,8 +31,8 @@ importers:
specifier: ^1.20.1
version: 1.20.1(react@19.3.0)
'@bitbaum/chatkit':
specifier: github:bitbaum/chatkit#70824785e86189704aeb7cc92c33bc198ad17cda
version: https://codeload.github.com/bitbaum/chatkit/tar.gz/70824785e86189704aeb7cc92c33bc198ad17cda(react@19.3.0)
specifier: github:bitbaum/chatkit#163c879163d22c6eb633314b3bd4e25712a01899
version: https://codeload.github.com/bitbaum/chatkit/tar.gz/163c879163d22c6eb633314b3bd4e25712a01899(react@19.3.0)
'@bitbaum/mail-kit':
specifier: ^0.1.1
version: 0.1.1
@@ -401,9 +401,9 @@ packages:
react:
optional: true
'@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/70824785e86189704aeb7cc92c33bc198ad17cda':
resolution: {gitHosted: true, integrity: sha512-pXQzKbAgHR/g5TcAESsYBFVkS/WAmy06SAHThY8aLXSVzL8qdhFU6+bHvekZdVPi0//dgFIkigS5tn5k3Oc2qw==, tarball: https://codeload.github.com/bitbaum/chatkit/tar.gz/70824785e86189704aeb7cc92c33bc198ad17cda}
version: 0.4.1
'@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/163c879163d22c6eb633314b3bd4e25712a01899':
resolution: {gitHosted: true, tarball: https://codeload.github.com/bitbaum/chatkit/tar.gz/163c879163d22c6eb633314b3bd4e25712a01899}
version: 0.6.0
engines: {node: '>=20'}
hasBin: true
peerDependencies:
@@ -418,7 +418,7 @@ packages:
engines: {node: '>=20'}
'@bitbaum/whenkit@https://codeload.github.com/bitbaum/whenkit/tar.gz/f5e0a24208187091c2ca792008cdd7695a19910f':
resolution: {gitHosted: true, tarball: https://codeload.github.com/bitbaum/whenkit/tar.gz/f5e0a24208187091c2ca792008cdd7695a19910f}
resolution: {gitHosted: true, integrity: sha512-y7wjFst8elmua4bfjhbRDw1U+qndxXeMXG32C5N8GokV3UIdGgO1LZYJFu0OrUftfvcgoERXJ7Nl6goITwarpA==, tarball: https://codeload.github.com/bitbaum/whenkit/tar.gz/f5e0a24208187091c2ca792008cdd7695a19910f}
version: 0.3.2
engines: {node: '>=20'}
peerDependencies:
@@ -4225,9 +4225,6 @@ packages:
peerDependencies:
pg: '>=8.0'
pg-protocol@1.16.0:
resolution: {integrity: sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==}
pg-protocol@1.16.1:
resolution: {integrity: sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==}
@@ -5217,7 +5214,7 @@ snapshots:
optionalDependencies:
react: 19.3.0
'@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/70824785e86189704aeb7cc92c33bc198ad17cda(react@19.3.0)':
'@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/163c879163d22c6eb633314b3bd4e25712a01899(react@19.3.0)':
dependencies:
react: 19.3.0
@@ -6476,7 +6473,7 @@ snapshots:
'@types/pg@8.23.1':
dependencies:
'@types/node': 26.6.4
pg-protocol: 1.16.0
pg-protocol: 1.16.1
pg-types: 2.2.0
'@types/react-dom@19.3.0(@types/react@19.3.0)':
@@ -8858,8 +8855,6 @@ snapshots:
dependencies:
pg: 8.23.1
pg-protocol@1.16.0: {}
pg-protocol@1.16.1: {}
pg-types@2.2.0:
+128
View File
@@ -0,0 +1,128 @@
/**
* Suggested replies (chatkit's `quick_replies` block) on every Loki chat.
* Run: npx tsx scripts/test/loki-suggested-replies.ts
*
* The model writes the replies at the end of its answer, so the one thing that
* must never happen is the block travelling WITH the answer: into the stored
* message (and from there into copy, save-to-memory, titles, previews and the
* next turn's history), into a work-trail note, or into speech. Env-independent:
* the model call and the seed are injected.
*/
import assert from "node:assert/strict";
import { REPLIES_INSTRUCTION } from "@bitbaum/chatkit";
import type { ModelTurn } from "../../src/lib/agent/llm";
import type { ToolRegistry } from "../../src/lib/agent/tools/registry";
import { runLokiTurn, type LokiTurnEvent } from "../../src/lib/agent/loop";
import { readReplies } from "../../src/lib/loki/replies";
import { plainTextForSpeech } from "../../src/lib/loki/speech-text";
const BLOCK = '\n\n```quick_replies\n["Yes, run it", "Show me the diff first", "Not now"]\n```';
const SEED = { facts: [], directives: [] };
const NO_TOOLS: ToolRegistry = {};
/** One scripted answer; records the system prompt each call was given. */
function model(text: string) {
const systems: string[] = [];
const fn = async (input: { messages: Array<{ role: string; content: string }> }) => {
systems.push(input.messages.find((m) => m.role === "system")?.content ?? "");
const turn: ModelTurn = { text, toolCalls: [], model: "stub", cutOff: null, usageTokens: 0 };
return turn;
};
return { fn: fn as never, systems };
}
async function main() {
// ── A chat turn asks for replies and gets them back APART from the text ────
{
const m = model(`The deploy is green.${BLOCK}`);
const r = await runLokiTurn({
userId: "u1",
message: "is it deployed?",
registry: NO_TOOLS,
seed: SEED,
callModel: m.fn,
replies: true,
});
assert.ok(m.systems[0].includes(REPLIES_INSTRUCTION), "a chat turn asks for replies");
assert.equal(r.text, "The deploy is green.", "the block never travels with the answer");
assert.deepEqual(r.replies, ["Yes, run it", "Show me the diff first", "Not now"]);
}
// ── Off (MCP, voice, prompt runs): not asked for, and stripped if sent anyway
{
const m = model(`The deploy is green.${BLOCK}`);
const r = await runLokiTurn({
userId: "u1",
message: "is it deployed?",
registry: NO_TOOLS,
seed: SEED,
callModel: m.fn,
});
assert.ok(!m.systems[0].includes("quick_replies"), "a non-chat caller is not asked");
assert.equal(r.text, "The deploy is green.", "an unasked-for block is still removed");
assert.deepEqual(r.replies, [], "and its replies are not handed to a caller with no buttons");
}
// ── A gathering round's note never carries the block ───────────────────────
{
let call = 0;
const fn = async (): Promise<ModelTurn> => {
call++;
return call === 1
? {
text: `Looking at the runs first.${BLOCK}`,
toolCalls: [{ id: "1", name: "probe", args: {} }],
model: "stub",
cutOff: null,
usageTokens: 0,
}
: { text: "All runs passed.", toolCalls: [], model: "stub", cutOff: null, usageTokens: 0 };
};
const { z } = await import("zod");
const { defineTool } = await import("../../src/lib/agent/tools/registry");
const registry: ToolRegistry = {
probe: defineTool({
name: "probe",
kind: "read",
description: "stub",
params: z.object({}),
example: "TOOL: probe\nARGS: {}",
handler: async () => ({ facts: [], note: "nothing new" }),
}),
};
const events: LokiTurnEvent[] = [];
const r = await runLokiTurn({
userId: "u1",
message: "how are the runs?",
registry,
seed: SEED,
callModel: fn as never,
replies: true,
onEvent: (e) => events.push(e),
});
const notes = r.work.filter((w) => w.kind === "note");
assert.equal(notes.length, 1);
assert.doesNotMatch(JSON.stringify(notes), /quick_replies/, "a stored note has no block");
assert.doesNotMatch(
JSON.stringify(events.filter((e) => e.type === "note")),
/quick_replies/,
"a streamed note has no block",
);
}
// ── Stored replies read back defensively ───────────────────────────────────
assert.deepEqual(readReplies({ replies: ["Yes", 3, "", "No"] }), ["Yes", "No"]);
assert.deepEqual(readReplies(null), []);
assert.deepEqual(readReplies({ replies: "Yes" }), [], "only an array is replies");
// ── Never spoken aloud ──────────────────────────────────────────────────────
const spoken = plainTextForSpeech(`The deploy is green.${BLOCK}`);
assert.equal(spoken, "The deploy is green.", "the block is neither read nor named as code");
console.log("loki-suggested-replies: ok");
}
main().catch((e) => {
console.error(e);
process.exit(1);
});
@@ -39,6 +39,7 @@ import {
import { injectPrompt } from "@/lib/inject-core";
import { askLoki } from "@/lib/loki-core";
import { pickProvenance } from "@/lib/loki/provenance";
import { readReplies } from "@/lib/loki/replies";
import { enqueueProposalFromMessage } from "@/lib/actions/enqueue-proposal";
import { ORCHESTRATION_ADAPTER_IDS, type AdapterId } from "@/lib/orchestration";
import {
@@ -631,6 +632,8 @@ async function chatReply(
: `agent:main:web:conv:${ctx.conversationId}`,
userId: ctx.userId,
model: ctx.model,
// This answer lands in a thread with reply buttons under it.
replies: true,
// The thread so far, so the primary path has the same continuity the
// gateway's session memory used to give only the fallback. Trimmed by
// the loop; only role + content cross this seam.
@@ -650,6 +653,11 @@ async function chatReply(
meta: {
...extraMeta,
projectKey: chatProject,
// What the person is likely to say next, as one-tap buttons under the
// latest answer. Kept apart from `content` so the stored answer — what
// is copied, spoken, saved to memory and fed back as history — never
// carries the block it came in.
...(readReplies(loki.body).length > 0 ? { replies: readReplies(loki.body) } : {}),
// Provenance — which brain, which model, what was retrieved, which
// tools ran, and whether the answer verified clean. Persisted whole:
// this used to keep `model` and `sources` and drop `grounding`, so a
+10 -1
View File
@@ -37,6 +37,10 @@ const AskLokiBody = z.object({
)
.max(12)
.optional(),
// The caller is a chat that shows suggested replies under the answer (the
// floating assistant). Off for one-shot callers such as a prompt run, where
// a row of buttons would have nowhere to send.
replies: z.boolean().default(false),
});
const PAGE_CONTEXT_MAX_CHARS = 2000;
@@ -95,7 +99,12 @@ export async function POST(req: NextRequest) {
// "nothing to queue this turn" and never blocks the reply. This is the queue's
// producer; the operator still approves every draft before it executes.
const [{ status, body }, queued] = await Promise.all([
askLoki(message, { sessionKey, userId, history: dataOrResp.history }),
askLoki(message, {
sessionKey,
userId,
history: dataOrResp.history,
replies: dataOrResp.replies,
}),
enqueueProposalFromMessage(userId, dataOrResp.message, new Date().toISOString()).catch(
() => null,
),
+4 -1
View File
@@ -558,7 +558,10 @@ export function LokiWorkspace({
onPickProject={dispatchWithProject}
onAnswerAnyway={answerWithoutProject}
onRetry={lastSent ? retryLast : undefined}
onFollowUp={(text) => void send(text)}
// A tapped reply goes on the model the operator last chose, as typing
// it would — it used to fall back to Auto, so a reply could be answered
// by a different model than the question it followed.
onFollowUp={(text) => void send(text, lastSent?.choice)}
// Inside the scroll, after the last turn: it is an action ON the
// exchange, and as a fixed row between thread and composer it took a
// permanent line of a phone screen from the conversation.
+12 -1
View File
@@ -2,7 +2,9 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { ArrowDown, Loader2, Square } from "lucide-react";
import { ChatReplies } from "@bitbaum/chatkit/react";
import { MarkdownText } from "@/components/ui/markdown-text";
import { readReplies } from "@/lib/loki/replies";
import { LOKI_STATUS_COPY } from "@/lib/loki/stream";
import type { LiveTurn } from "@/hooks/use-loki-stream";
import { FollowUps } from "./FollowUps";
@@ -132,6 +134,11 @@ export function Thread({
lastMessage === lastAssistant &&
(lastAssistant.kind ?? "chat") === "chat" &&
!!lastQuestion;
// The answer's own suggested replies (asked for in the same turn — see
// REPLIES_INSTRUCTION) win. The separate follow-ups call is the fallback for
// an answer that came without them: an older turn, or a brain that ignored
// the instruction. Never both — two rows of "what next" is a menu.
const replies = showFollowUps ? readReplies(lastAssistant.meta) : [];
return (
<div className="ui-loki-thread-wrap">
@@ -194,7 +201,11 @@ export function Thread({
</p>
)}
{showFollowUps && (
{showFollowUps && replies.length > 0 && (
<ChatReplies replies={replies} onPick={onFollowUp} />
)}
{showFollowUps && replies.length === 0 && (
<FollowUps
answerId={lastAssistant.id}
question={lastQuestion}
+94 -68
View File
@@ -13,6 +13,7 @@ import {
Wrench,
X,
} from "lucide-react";
import { ChatReplies } from "@bitbaum/chatkit/react";
import { readPageContext } from "@fleet/ai-forms/react";
import {
readAssistantContext,
@@ -30,7 +31,10 @@ import { postJson } from "@/lib/api/fetch";
import { LOKI_OPEN_EVENT } from "@/lib/client-events";
import { useEscapeToClose } from "@/hooks/use-escape-to-close";
import { ProvenanceFooter } from "@/components/loki/ProvenanceFooter";
import { citationsFrom } from "@/components/loki/footers";
import { MarkdownText } from "@/components/ui/markdown-text";
import { pickProvenance } from "@/lib/loki/provenance";
import { readReplies } from "@/lib/loki/replies";
/** Prior turns sent with an ask, and how much of each. Matches the loop's own trim. */
const HISTORY_TURNS = 8;
@@ -41,6 +45,8 @@ type Turn = {
text: string;
/** Provenance for a Loki turn — which model, what it read, whether it verified. */
meta?: Record<string, unknown>;
/** What the person is likely to say next — one tap sends it. */
replies?: string[];
};
/** Ceiling for the drawer composer's auto-grow. Smaller than the full-page
@@ -181,70 +187,83 @@ export function AskLokiButton() {
// depends on `workspaceKey` — not the whole `context` object — and the
// manual deps match what the compiler infers.
const workspaceKey = context?.workspaceKey ?? null;
const ask = useCallback(async () => {
const message = input.trim();
if (!message || asking) return;
setInput("");
setAskError(null);
setTurns((prev) => [...prev, { role: "user", text: message }]);
setAsking(true);
/** Send the box, or — when a suggested reply was tapped — exactly that
* reply, leaving whatever is half-typed in the box where it is. */
const ask = useCallback(
async (picked?: string) => {
const message = (picked ?? input).trim();
if (!message || asking) return;
if (picked === undefined) setInput("");
setAskError(null);
setTurns((prev) => [...prev, { role: "user", text: message }]);
setAsking(true);
// A form is open: write into it. Telling the user which fields to type in
// would be a worse answer than just filling them.
const form = activeForm?.getAssist();
if (form) {
try {
const result = await form.ask(message);
setTurns((prev) => [
...prev,
{ role: "loki", text: result.ok ? result.message : result.error },
]);
} finally {
setAsking(false);
}
return;
}
// A form is open: write into it. Telling the user which fields to type in
// would be a worse answer than just filling them.
const form = activeForm?.getAssist();
if (form) {
try {
const result = await form.ask(message);
setTurns((prev) => [
...prev,
{ role: "loki", text: result.ok ? result.message : result.error },
]);
const projectKey = workspaceKey;
// Send the heavy project context once per project thread per page life.
const includeContext = projectKey != null && sentContextRef.current !== projectKey;
// What the user can actually see, read from the rendered page — so the
// answer is grounded in this screen rather than in route metadata.
const pageContext = readPageContext();
// The panel's own transcript, so a follow-up has something to follow.
// These turns live in client state only — without sending them, "and the
// second one?" reached the model with no first one.
const history = turnsRef.current.slice(-HISTORY_TURNS).map((t) => ({
role: t.role === "loki" ? ("assistant" as const) : ("user" as const),
content: t.text.slice(0, HISTORY_CHARS),
}));
const res = await postJson("/api/loki", {
message,
...(pageContext ? { pageContext } : {}),
...(projectKey ? { projectKey, includeContext } : {}),
...(history.length > 0 ? { history } : {}),
replies: true,
});
const body = (await res.json()) as {
ok?: boolean;
text?: string;
error?: string;
} & Record<string, unknown>;
if (!res.ok || !body.ok || !body.text) {
setAskError(body.error ?? "Loki did not answer — try again.");
} else {
if (includeContext && projectKey) sentContextRef.current = projectKey;
setTurns((prev) => [
...prev,
{
role: "loki",
text: body.text!,
// The sources travel with the answer so its [F1] markers resolve
// to the records they name, as they do on /loki.
meta: { ...pickProvenance(body), sources: body.sources },
replies: readReplies(body),
},
]);
}
} catch {
setAskError("Loki is unreachable — network error.");
} finally {
setAsking(false);
}
return;
}
try {
const projectKey = workspaceKey;
// Send the heavy project context once per project thread per page life.
const includeContext = projectKey != null && sentContextRef.current !== projectKey;
// What the user can actually see, read from the rendered page — so the
// answer is grounded in this screen rather than in route metadata.
const pageContext = readPageContext();
// The panel's own transcript, so a follow-up has something to follow.
// These turns live in client state only — without sending them, "and the
// second one?" reached the model with no first one.
const history = turnsRef.current.slice(-HISTORY_TURNS).map((t) => ({
role: t.role === "loki" ? ("assistant" as const) : ("user" as const),
content: t.text.slice(0, HISTORY_CHARS),
}));
const res = await postJson("/api/loki", {
message,
...(pageContext ? { pageContext } : {}),
...(projectKey ? { projectKey, includeContext } : {}),
...(history.length > 0 ? { history } : {}),
});
const body = (await res.json()) as {
ok?: boolean;
text?: string;
error?: string;
} & Record<string, unknown>;
if (!res.ok || !body.ok || !body.text) {
setAskError(body.error ?? "Loki did not answer — try again.");
} else {
if (includeContext && projectKey) sentContextRef.current = projectKey;
setTurns((prev) => [
...prev,
{ role: "loki", text: body.text!, meta: pickProvenance(body) },
]);
}
} catch {
setAskError("Loki is unreachable — network error.");
} finally {
setAsking(false);
}
}, [input, asking, workspaceKey, activeForm]);
},
[input, asking, workspaceKey, activeForm],
);
// /loki IS the assistant; /terminal carries it as its Loki panel (rail or
// sheet). A floating second entry point there sat on the panel's own Send.
@@ -367,16 +386,23 @@ export function AskLokiButton() {
{turns.map((turn, i) => (
<div key={i} className={turn.role === "user" ? "text-right" : ""}>
<p
className={
turn.role === "user"
? "inline-block max-w-[90%] rounded-lg bg-surface-raised px-3 py-2 text-left text-sm text-text-primary"
: "whitespace-pre-wrap text-sm leading-relaxed text-text-secondary"
}
>
{turn.text}
</p>
{turn.role === "user" ? (
<p className="inline-block max-w-[90%] whitespace-pre-wrap rounded-lg bg-surface-raised px-3 py-2 text-left text-sm text-text-primary">
{turn.text}
</p>
) : (
// Rendered, not printed: an answer is markdown with [F1]
// citations, and this panel used to show the asterisks and
// the bare handles.
<MarkdownText text={turn.text} citations={citationsFrom(turn.meta ?? null)} />
)}
{turn.role === "loki" && <ProvenanceFooter meta={turn.meta ?? null} />}
{/* Under the latest answer only, and never while the next
turn is on its way — the same rule as every chat in the
fleet (chatkit's ChatThread). */}
{turn.role === "loki" && i === turns.length - 1 && !asking && turn.replies && (
<ChatReplies replies={turn.replies} onPick={(r) => void ask(r)} />
)}
</div>
))}
{asking && (
+11 -3
View File
@@ -295,9 +295,17 @@ export function TerminalLokiRail({
{(session.messages.length > 0 || session.live) && (
<div className="ui-term-loki-thread">
<ChatThread
messages={session.messages.map((m) =>
m.role === "assistant" ? { ...m, content: splitActions(m.content).body } : m,
)}
messages={session.messages.map((m) => {
if (m.role !== "assistant") return m;
const { body, actions } = splitActions(m.content);
// A summary's own "→" steps already say what to do next, one
// tap from Inject; a second row of replies under them would be
// a menu. Ordinary answers keep their suggested replies.
return actions.length > 0
? { ...m, content: body, replies: [] }
: { ...m, content: body };
})}
onReply={(text) => void session.reply(text)}
live={session.live ? { text: session.live.preview, status: liveStatus } : null}
stopped={session.stopped}
onStop={session.stop}
+11 -1
View File
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useRef, useState } from "react";
import { extractReplies } from "@bitbaum/chatkit";
import { readEventStream } from "@/lib/api/read-event-stream";
import type { LokiStatusLabel, LokiStreamEvent, WireMessage } from "@/lib/loki/stream";
import { applyNote, applyToolStep, type WorkStep } from "@/lib/loki/work";
@@ -115,7 +116,16 @@ export function useLokiStream({
switch (event.type) {
case "delta":
preview += event.text;
setLive((prev) => ({ ...(prev ?? EMPTY), preview, status: null }));
// The answer may end in a suggested-replies block. It is taken
// out here, once, for every surface that shows the preview —
// including while it is still half-written — so nobody watches
// raw JSON appear under an answer. The persisted turn carries
// the replies separately (meta.replies).
setLive((prev) => ({
...(prev ?? EMPTY),
preview: extractReplies(preview).text,
status: null,
}));
break;
case "reset":
preview = "";
+15 -1
View File
@@ -1,12 +1,13 @@
"use client";
import { useCallback, useState } from "react";
import { useCallback, useRef, useState } from "react";
import type { ChatMessageData } from "@bitbaum/chatkit/react";
import { postJson } from "@/lib/api/fetch";
import type { Attachment, ModelChoice } from "@/components/loki/types";
import { useLokiStream, type UseLokiStream } from "@/hooks/use-loki-stream";
import type { WireMessage } from "@/lib/loki/stream";
import { citationsFrom } from "@/components/loki/footers";
import { readReplies } from "@/lib/loki/replies";
export type SessionAsk = {
/** The thread so far, in chatkit's shape — rendered by ChatThread. */
@@ -24,6 +25,12 @@ export type SessionAsk = {
text: string,
opts?: { choice?: ModelChoice; attachments?: Attachment[]; shown?: string },
) => Promise<boolean>;
/**
* Send a suggested reply the person tapped: the same turn the composer
* sends, on the model they last chose, so a tap is never a quieter version
* of typing the words.
*/
reply: (text: string) => Promise<boolean>;
stop: () => void;
clearError: () => void;
};
@@ -53,6 +60,9 @@ export function useSessionAsk(project: string | null): SessionAsk {
role: "assistant",
content: message.content,
citations: citationsFrom(message.meta),
// Stored apart from the text by the messages route; chatkit's
// thread shows them under the latest answer.
replies: readReplies(message.meta),
},
]);
},
@@ -73,7 +83,10 @@ export function useSessionAsk(project: string | null): SessionAsk {
return body.conversation.id;
}, [conversationId, project]);
const lastChoice = useRef<ModelChoice | undefined>(undefined);
const ask: SessionAsk["ask"] = async (text, opts = {}) => {
if (opts.choice) lastChoice.current = opts.choice;
setError(null);
const convoId = await ensureConversation();
if (!convoId) return false;
@@ -101,6 +114,7 @@ export function useSessionAsk(project: string | null): SessionAsk {
stopped: stream.stopped,
error: error ?? stream.error,
ask,
reply: (text) => ask(text, { choice: lastChoice.current }),
stop: stream.stop,
clearError: () => {
setError(null);
+40 -7
View File
@@ -58,6 +58,7 @@ import { maxPromptBudgetTokens } from "@/config/chat-models";
import type { OwnModel } from "@/lib/own-model";
import type { RetrievedSource } from "@/lib/agent/context";
import { APP_NAME } from "@/config/brand";
import { REPLIES_INSTRUCTION, extractReplies } from "@bitbaum/chatkit";
import { looksLikePlan, ANSWER_ONLY } from "@/lib/loki/plan-as-answer";
// The concrete registry and the seed builder reach the database, and @/db
@@ -161,7 +162,13 @@ export type LoopSeed = {
};
export type LoopResult = {
/** The answer, with any suggested-replies block already taken out. */
text: string;
/**
* What the person is likely to say next (chatkit's suggested replies), when
* the turn asked for them and the model offered some. Empty otherwise.
*/
replies: string[];
facts: Fact[];
/** Resolved citations, so the transcript can render an id as its record. */
sources: CitationSource[];
@@ -338,6 +345,25 @@ async function runToolCalls(
return { facts, messages, used };
}
/** chatkit's suggested-replies ask, for a turn that lands in a chat with buttons. */
function repliesLine(wanted: boolean | undefined): string {
return wanted ? `\n\n${REPLIES_INSTRUCTION}` : "";
}
/**
* Take the suggested-replies block out of a model reply, as soon as it
* arrives — so it never reaches a note, the verifier or the stored answer.
* Done before grounding:
* the replies are what the person might say next, not claims about their
* records, and a repair pass (which rewrites by deletion, without the replies
* instruction) must not be what decides whether they survive. A block the
* caller did not ask for is still removed — it is never part of the answer.
*/
function takeReplies(text: string, wanted: boolean | undefined) {
const split = extractReplies(text);
return { text: split.text, replies: wanted ? split.replies : [] };
}
/**
* Run one Loki turn.
*
@@ -368,6 +394,9 @@ export async function runLokiTurn(input: {
* Ignored when the user brought their own model. Undefined = LOKI_MODEL.
*/
model?: string;
/** The answer lands in a chat with reply buttons: ask for chatkit's suggested
* replies (LoopResult.replies). Off for MCP, voice and prompt runs. */
replies?: boolean;
/** Injected in tests; defaults to the real provider call. */
callModel?: ModelCaller;
/** Present when someone is watching: stream the turn instead of buffering it. */
@@ -420,6 +449,8 @@ export async function runLokiTurn(input: {
const used: string[] = [];
const work: WorkStep[] = [];
let text = "";
// Suggested replies ride out of every model reply — see takeReplies.
let replies: string[] = [];
let model = "";
// The exact prompt the last round sent, kept so a reply that turns out to be
// a PLAN can be asked again with the instruction it showed it needed. Built
@@ -459,7 +490,7 @@ export async function runLokiTurn(input: {
// model handed tools will keep calling them, and the operator would get a
// dangling tool call instead of a reply.
const lastRound = answerNext || round === MAX_ROUNDS - 1;
const system = systemPrompt(advertised, !lastRound) + voiceLine;
const system = systemPrompt(advertised, !lastRound) + voiceLine + repliesLine(input.replies);
// Everything charged besides facts. It GROWS as the loop proceeds — the
// conversation carries each round's tool results — so the fit is recomputed
@@ -541,7 +572,7 @@ export async function runLokiTurn(input: {
})();
model = turn.model;
usageTokens += turn.usageTokens;
text = turn.text;
({ text, replies } = takeReplies(turn.text, input.replies));
cutOff = turn.cutOff ?? null;
if (turn.toolCalls.length === 0 || lastRound) break;
@@ -551,9 +582,10 @@ export async function runLokiTurn(input: {
// as an ANSWER (the next round replaces `text`) but it is not nothing: it
// is the narration the operator reads between groups of work, and the
// one thing a static spinner never gave them. Kept as a note, in order.
if (turn.text.trim()) {
work.push({ kind: "note", text: turn.text.trim() });
emit({ type: "note", text: turn.text.trim() });
// `text`, not `turn.text`: a note is never the place for a replies block.
if (text.trim()) {
work.push({ kind: "note", text: text.trim() });
emit({ type: "note", text: text.trim() });
}
const executed = await runToolCalls(turn.toolCalls, registry, ctx, attempted, emit, work);
@@ -610,7 +642,7 @@ export async function runLokiTurn(input: {
});
usageTokens += retry.usageTokens;
if (retry.text.trim() && (!retry.cutOff || retry.text.length > text.length)) {
text = retry.text;
({ text, replies } = takeReplies(retry.text, input.replies));
model = retry.model;
cutOff = retry.cutOff ?? null;
}
@@ -667,7 +699,7 @@ export async function runLokiTurn(input: {
// improvement, and an empty reply is worse than a plan — at least a plan
// shows the model understood the question.
if (retry.text.trim() && !looksLikePlan(retry.text)) {
text = retry.text;
({ text, replies } = takeReplies(retry.text, input.replies));
model = retry.model;
}
} catch (e) {
@@ -779,6 +811,7 @@ export async function runLokiTurn(input: {
text: cutOff
? `${text.trimEnd()}…\n\n_The answer was cut off. Ask "go on" for the rest._`
: text,
replies,
facts,
sources,
violations,
+46 -9
View File
@@ -53,6 +53,7 @@ import { APP_NAME } from "@/config/brand";
import { ECOSYSTEM, ORANGECAT_CAPABILITIES } from "@/config/ecosystem";
import { HTTP_TIMEOUT_LONG_MS } from "@/lib/constants/time";
import { looksLikePlan, ANSWER_ONLY } from "@/lib/loki/plan-as-answer";
import { REPLIES_INSTRUCTION, extractReplies } from "@bitbaum/chatkit";
const LOKI_SYSTEM_PROMPT =
`You are Loki, the assistant inside ${APP_NAME} — the operator's execution layer: the captain over their fleet of AI agents and projects, and the workspace holding the people, commitments and spending that work runs on. ` +
@@ -223,6 +224,14 @@ export type AskLokiOpts = {
* existed the picker's choice reached dispatched agents but never the chat
* turn itself, which always started at LOKI_MODEL. */
model?: string;
/**
* The answer lands in a chat that shows suggested replies under it. The
* model is asked for them, and they come back as `body.replies` — never
* inside `body.text`, which is what gets stored, copied, spoken and titled.
* Leave it off for anything that is not such a chat (MCP, voice, a prompt
* run): there the block would only be noise in the answer.
*/
replies?: boolean;
};
/**
@@ -281,6 +290,7 @@ export async function askLoki(message: string, opts?: AskLokiOpts): Promise<AskL
readOnly: opts?.readOnly,
operator,
model: opts?.model,
replies: opts?.replies,
});
// Booked whether or not the turn produced usable text: the tokens were
// spent either way, and only charging for successes would let a run of
@@ -303,6 +313,7 @@ export async function askLoki(message: string, opts?: AskLokiOpts): Promise<AskL
body: {
ok: true,
text: result.text,
replies: result.replies,
...provenance,
// Sent so the transcript can resolve [F8] to the record it names.
sources: result.sources,
@@ -377,6 +388,7 @@ async function askLokiOnOwnModel(
readOnly: opts.readOnly,
operator,
own,
replies: opts.replies,
});
if (!result.text.trim()) {
throw new Error("it returned an empty answer");
@@ -394,7 +406,13 @@ async function askLokiOnOwnModel(
logTurn({ ...provenance, userId: opts.userId, textLength: result.text.length });
return {
status: 200,
body: { ok: true, text: result.text, ...provenance, sources: result.sources },
body: {
ok: true,
text: result.text,
replies: result.replies,
...provenance,
sources: result.sources,
},
};
} catch (e) {
// Vendors usually mask a key they echo; the ones that don't must not have
@@ -455,7 +473,10 @@ async function askLokiViaGateway(
const background = grounded?.context
? `${LOKI_CAPABILITIES}\n\n---\n\n${grounded.context}`
: LOKI_CAPABILITIES;
const contextualMessage = `${background}\n\n---\n\n${message}`;
// The fallbacks have no system prompt of ours that every brain reads (the
// gateway never sees one), so the replies instruction rides in the message.
const repliesAsk = opts?.replies ? `\n\n---\n\n${REPLIES_INSTRUCTION}` : "";
const contextualMessage = `${background}${repliesAsk}\n\n---\n\n${message}`;
/**
* Check an answer and, if it makes unsupported claims, give the model exactly
@@ -505,11 +526,15 @@ async function askLokiViaGateway(
return { text, violations: first.violations };
}
/** The answer without its replies block, which is checked and stored apart. */
const answerOf = (text: string) => extractReplies(text);
const finish = (
text: string,
via: LokiVia,
model: string,
violations: Violation[],
replies: string[],
): AskLokiResult => {
const provenance: LokiProvenance = {
via,
@@ -522,7 +547,10 @@ async function askLokiViaGateway(
grounding: groundingMeta(facts.length, violations),
};
logTurn({ ...provenance, userId: opts?.userId, textLength: text.length });
return { status: 200, body: { ok: true, text, ...provenance } };
return {
status: 200,
body: { ok: true, text, replies: opts?.replies ? replies : [], ...provenance },
};
};
// Only the operator's turns may reach their own agent (see isOperatorTurn);
@@ -537,13 +565,20 @@ async function askLokiViaGateway(
// `</think>` block into the transcript: its agent runs whatever model it
// likes (gemini-flash-latest at the time), so reasoning output is not
// hypothetical here — it is the observed case.
const text = normaliseCitations(stripReasoning(res.text ?? "")).trim();
const answer = answerOf(normaliseCitations(stripReasoning(res.text ?? "")).trim());
const text = answer.text;
if (res.ok && !isUnusableGatewayText(text) && !looksLikeFleetEcho(text)) {
const checked = await groundOrRepair(text, async (repair) => {
const again = await askGatewayAgent(repair, { sessionKey: opts?.sessionKey });
return again.ok ? normaliseCitations(stripReasoning(again.text ?? "")) : "";
return again.ok ? answerOf(normaliseCitations(stripReasoning(again.text ?? ""))).text : "";
});
return finish(checked.text, "gateway", res.model ?? "openclaw/main", checked.violations);
return finish(
checked.text,
"gateway",
res.model ?? "openclaw/main",
checked.violations,
answer.replies,
);
}
const reason = !res.ok
? (res.error ?? "gateway error")
@@ -561,7 +596,9 @@ async function askLokiViaGateway(
// fallback path is a SMALLER model, so it is the path most likely to
// fabricate and the last one that should skip the check.
try {
const { text, model } = await callGroq(contextualMessage, voice, opts?.onEvent);
const first = await callGroq(contextualMessage, voice, opts?.onEvent);
const { model } = first;
const { text, replies } = answerOf(first.text);
// Same rationed pool as the tool loop, so it is booked too. `callGroqText`
// surfaces no usage count, so 0 books the estimate.
if (opts?.userId) await recordAiSpend(opts.userId, 0);
@@ -571,9 +608,9 @@ async function askLokiViaGateway(
`${contextualMessage}\n\n---\n\nYour previous answer:\n${text}\n\n---\n\n${repair}`,
voice,
);
return fixed;
return answerOf(fixed).text;
});
return finish(checked.text, "groq-fallback", model, checked.violations);
return finish(checked.text, "groq-fallback", model, checked.violations, replies);
} catch (e) {
const raw = e instanceof Error ? e.message : String(e);
const hint = /\b401\b|invalid.api.key/i.test(raw)
+16
View File
@@ -0,0 +1,16 @@
/**
* Suggested replies on a stored Loki answer.
*
* The model writes them in the same turn as the answer (chatkit's
* REPLIES_INSTRUCTION); the core takes them out of the text before anything
* is stored, and the messages route keeps them in `meta.replies`. So the
* stored `content` — what is copied, spoken, saved to memory, titled,
* previewed and fed back as history — never carries the block.
*
* Defensive like citationsFrom: meta is opaque and older turns have none.
*/
export function readReplies(meta: Record<string, unknown> | null | undefined): string[] {
const raw = meta?.replies;
if (!Array.isArray(raw)) return [];
return raw.filter((r): r is string => typeof r === "string" && r.trim().length > 0);
}
+6 -1
View File
@@ -1,3 +1,5 @@
import { extractReplies } from "@bitbaum/chatkit";
/**
* An answer as it should be READ ALOUD.
*
@@ -9,8 +11,11 @@
*/
export function plainTextForSpeech(markdown: string): string {
// Suggested replies are buttons, never words: a quick_replies block is
// dropped outright rather than announced as "(code)".
const prose = extractReplies(markdown).text;
return (
markdown
prose
// Fenced code is not prose; say that it is there rather than reading it.
.replace(/```[\s\S]*?```/g, " (code) ")
.replace(/`([^`]*)`/g, "$1")