From e52c65af80f19f4e36668d6c50a6061ba80dc8ed Mon Sep 17 00:00:00 2001 From: Cato <41178744+catomean@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:18:35 -0700 Subject: [PATCH] =?UTF-8?q?feat(loki):=20suggested=20replies=20on=20every?= =?UTF-8?q?=20Loki=20chat=20=E2=80=94=20one=20tap=20sends=20the=20likely?= =?UTF-8?q?=20next=20message=20(#1115)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- package.json | 2 +- pnpm-lock.yaml | 21 +-- scripts/test/loki-suggested-replies.ts | 128 ++++++++++++++ .../api/conversations/[id]/messages/route.ts | 8 + src/app/api/loki/route.ts | 11 +- src/components/loki/LokiWorkspace.tsx | 5 +- src/components/loki/Thread.tsx | 13 +- src/components/shell/AskLokiButton.tsx | 162 ++++++++++-------- src/components/terminal/TerminalLokiRail.tsx | 14 +- src/hooks/use-loki-stream.ts | 12 +- src/hooks/use-session-ask.ts | 16 +- src/lib/agent/loop.ts | 47 ++++- src/lib/loki-core.ts | 55 +++++- src/lib/loki/replies.ts | 16 ++ src/lib/loki/speech-text.ts | 7 +- 15 files changed, 410 insertions(+), 107 deletions(-) create mode 100644 scripts/test/loki-suggested-replies.ts create mode 100644 src/lib/loki/replies.ts diff --git a/package.json b/package.json index 44bda1fea..469a43a8e 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e9239e0d..d18342460 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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: diff --git a/scripts/test/loki-suggested-replies.ts b/scripts/test/loki-suggested-replies.ts new file mode 100644 index 000000000..c5deca438 --- /dev/null +++ b/scripts/test/loki-suggested-replies.ts @@ -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 => { + 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); +}); diff --git a/src/app/api/conversations/[id]/messages/route.ts b/src/app/api/conversations/[id]/messages/route.ts index 1fca54c75..283bffc56 100644 --- a/src/app/api/conversations/[id]/messages/route.ts +++ b/src/app/api/conversations/[id]/messages/route.ts @@ -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 diff --git a/src/app/api/loki/route.ts b/src/app/api/loki/route.ts index 8d78c9000..0c79c54d3 100644 --- a/src/app/api/loki/route.ts +++ b/src/app/api/loki/route.ts @@ -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, ), diff --git a/src/components/loki/LokiWorkspace.tsx b/src/components/loki/LokiWorkspace.tsx index 5fc4fb94e..f70399c2e 100644 --- a/src/components/loki/LokiWorkspace.tsx +++ b/src/components/loki/LokiWorkspace.tsx @@ -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. diff --git a/src/components/loki/Thread.tsx b/src/components/loki/Thread.tsx index ce0dfe7e1..ab449571e 100644 --- a/src/components/loki/Thread.tsx +++ b/src/components/loki/Thread.tsx @@ -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 (
@@ -194,7 +201,11 @@ export function Thread({

)} - {showFollowUps && ( + {showFollowUps && replies.length > 0 && ( + + )} + + {showFollowUps && replies.length === 0 && ( ; + /** 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; + 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; - 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) => (
-

- {turn.text} -

+ {turn.role === "user" ? ( +

+ {turn.text} +

+ ) : ( + // Rendered, not printed: an answer is markdown with [F1] + // citations, and this panel used to show the asterisks and + // the bare handles. + + )} {turn.role === "loki" && } + {/* 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 && ( + void ask(r)} /> + )}
))} {asking && ( diff --git a/src/components/terminal/TerminalLokiRail.tsx b/src/components/terminal/TerminalLokiRail.tsx index 6f937cf44..750109e17 100644 --- a/src/components/terminal/TerminalLokiRail.tsx +++ b/src/components/terminal/TerminalLokiRail.tsx @@ -295,9 +295,17 @@ export function TerminalLokiRail({ {(session.messages.length > 0 || session.live) && (
- 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} diff --git a/src/hooks/use-loki-stream.ts b/src/hooks/use-loki-stream.ts index 23ce621e3..c1f7dc407 100644 --- a/src/hooks/use-loki-stream.ts +++ b/src/hooks/use-loki-stream.ts @@ -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 = ""; diff --git a/src/hooks/use-session-ask.ts b/src/hooks/use-session-ask.ts index 08a88646a..9c680c0b0 100644 --- a/src/hooks/use-session-ask.ts +++ b/src/hooks/use-session-ask.ts @@ -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; + /** + * 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; 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(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); diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts index 3178d632e..2079b5b0c 100644 --- a/src/lib/agent/loop.ts +++ b/src/lib/agent/loop.ts @@ -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, diff --git a/src/lib/loki-core.ts b/src/lib/loki-core.ts index e1f6fb5f7..cda8ea917 100644 --- a/src/lib/loki-core.ts +++ b/src/lib/loki-core.ts @@ -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 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( // `` 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) diff --git a/src/lib/loki/replies.ts b/src/lib/loki/replies.ts new file mode 100644 index 000000000..5664215a7 --- /dev/null +++ b/src/lib/loki/replies.ts @@ -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 | 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); +} diff --git a/src/lib/loki/speech-text.ts b/src/lib/loki/speech-text.ts index 6968da35c..54eac4b27 100644 --- a/src/lib/loki/speech-text.ts +++ b/src/lib/loki/speech-text.ts @@ -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")