diff --git a/package.json b/package.json index 2ab00c400..4ac399a47 100644 --- a/package.json +++ b/package.json @@ -116,7 +116,7 @@ "@auth/drizzle-adapter": "^1.11.3", "@bitbaum/accountkit": "github:bitbaum/accountkit#v0.1.0", "@bitbaum/ai-kit": "^1.18.0", - "@bitbaum/chatkit": "github:bitbaum/chatkit#b30c843f7df714e496828d3958146d037cfe0f15", + "@bitbaum/chatkit": "github:bitbaum/chatkit#5f9d737bbc8590a661a9bb196914dca7e73dbf7f", "@bitbaum/mail-kit": "^0.1.1", "@dnd-kit/core": "^6.3.1", "@dnd-kit/sortable": "^10.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e189904d6..2b726dfab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -31,8 +31,8 @@ importers: specifier: ^1.18.0 version: 1.18.0(react@19.2.8) '@bitbaum/chatkit': - specifier: github:bitbaum/chatkit#b30c843f7df714e496828d3958146d037cfe0f15 - version: https://codeload.github.com/bitbaum/chatkit/tar.gz/b30c843f7df714e496828d3958146d037cfe0f15(react@19.2.8) + specifier: github:bitbaum/chatkit#5f9d737bbc8590a661a9bb196914dca7e73dbf7f + version: https://codeload.github.com/bitbaum/chatkit/tar.gz/5f9d737bbc8590a661a9bb196914dca7e73dbf7f(react@19.2.8) '@bitbaum/mail-kit': specifier: ^0.1.1 version: 0.1.1 @@ -398,9 +398,9 @@ packages: react: optional: true - '@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/b30c843f7df714e496828d3958146d037cfe0f15': - resolution: {gitHosted: true, integrity: sha512-Uy74cHWso/3UAOyutTdb9cDaMAbrq7TFWSno1NXD+cO35I9ayqUCdNSDJPR27XZsqoTIHIa/UG2oxmwEGHcX/A==, tarball: https://codeload.github.com/bitbaum/chatkit/tar.gz/b30c843f7df714e496828d3958146d037cfe0f15} - version: 0.3.0 + '@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/5f9d737bbc8590a661a9bb196914dca7e73dbf7f': + resolution: {gitHosted: true, integrity: sha512-ZxiUanxQ5owNd4kGDN7ZBe1wlRhl3taZUa9EFRJp2TKaGSYBWf7zWimI7ofYluWsvqjaWpy/f4yeKU7k2v/C2A==, tarball: https://codeload.github.com/bitbaum/chatkit/tar.gz/5f9d737bbc8590a661a9bb196914dca7e73dbf7f} + version: 0.3.1 engines: {node: '>=20'} peerDependencies: react: '>=18' @@ -5240,7 +5240,7 @@ snapshots: optionalDependencies: react: 19.2.8 - '@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/b30c843f7df714e496828d3958146d037cfe0f15(react@19.2.8)': + '@bitbaum/chatkit@https://codeload.github.com/bitbaum/chatkit/tar.gz/5f9d737bbc8590a661a9bb196914dca7e73dbf7f(react@19.2.8)': dependencies: react: 19.2.8 diff --git a/scripts/test/agent-tool-loop.ts b/scripts/test/agent-tool-loop.ts index 993a53dad..786c6256a 100644 --- a/scripts/test/agent-tool-loop.ts +++ b/scripts/test/agent-tool-loop.ts @@ -235,7 +235,7 @@ async function main() { }); assert.deepEqual(r.work, [ { kind: "note", text: "Checking who Elena is first." }, - { kind: "tool", name: "search_people", phase: "end", facts: 1 }, + { kind: "tool", name: "search_people", phase: "end", facts: 1, detail: 'query: "Elena"' }, ]); assert.equal(r.text, "Elena Weber SINGA Switzerland — whatsapp +41774730093 [F1]."); const noteAt = events.findIndex((e) => e.type === "note"); diff --git a/scripts/test/loki-work-trail.ts b/scripts/test/loki-work-trail.ts index 9ea94496d..ab12b9321 100644 --- a/scripts/test/loki-work-trail.ts +++ b/scripts/test/loki-work-trail.ts @@ -10,8 +10,10 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { + DETAIL_MAX_CHARS, applyNote, applyToolStep, + describeArgs, groupWork, readWork, summarizeTools, @@ -75,13 +77,22 @@ assert.deepEqual(noted, [ { kind: "note", text: "Found it — checking who owns it." }, ]); +// The command under a step: arguments as one short line, never `{}`. +assert.equal(describeArgs({ query: "Elena", limit: 5 }), 'query: "Elena", limit: 5'); +assert.equal(describeArgs({}), undefined); +assert.equal(describeArgs({ q: "" }), undefined); +assert.equal(describeArgs("nope"), undefined); +const long = describeArgs({ query: "x".repeat(200) })!; +assert.ok(long.length <= DETAIL_MAX_CHARS && long.endsWith("…"), "cut to one line"); +assert.equal(describeArgs({ q: "two\nlines" })!.includes("\n"), false, "one line"); + // Persisted meta: only finished steps and real notes; junk is ignored. assert.deepEqual( readWork({ work: [ { kind: "note", text: "x" }, { kind: "tool", name: "a", phase: "start" }, - { kind: "tool", name: "b", phase: "end", facts: 4 }, + { kind: "tool", name: "b", phase: "end", facts: 4, detail: 'q: "x"' }, { kind: "tool", name: "c", phase: "fail" }, null, "nope", @@ -90,10 +101,29 @@ assert.deepEqual( }), [ { kind: "note", text: "x" }, - { kind: "tool", name: "b", phase: "end", facts: 4 }, + { kind: "tool", name: "b", phase: "end", facts: 4, detail: 'q: "x"' }, { kind: "tool", name: "c", phase: "fail" }, ], ); + +// The queue: a send during a turn is taken, shown, and flushed after. +const workspace = readFileSync("src/components/loki/LokiWorkspace.tsx", "utf8"); +assert.match( + workspace, + /if \(sending && !dispatchOnly\) \{\s*setQueue/, + "a send while running is queued", +); +assert.match( + workspace, + /if \(sending \|\| stream\.error \|\| queue\.length === 0\) return;/, + "flushed only when the turn ended cleanly", +); +assert.match(workspace, /className="ui-loki-queue-item"/, "queued messages are shown"); +assert.match( + workspace, + / void; /** What an attachments-only send says. Omit and an empty text cannot send. */ attachmentOnlyText?: string; + /** Take the next message while a turn runs; the caller sends it after. */ + queue?: boolean; attach?: boolean; voice?: boolean; /** Offer the Loki model picker (chat turns). Off where the model is the diff --git a/src/components/loki/Composer.tsx b/src/components/loki/Composer.tsx index 5d0d7f708..26bceede5 100644 --- a/src/components/loki/Composer.tsx +++ b/src/components/loki/Composer.tsx @@ -45,6 +45,7 @@ export function LokiComposer({ dispatchHonesty = null, showStarters = true, draftKey, + queue = false, }: { disabled: boolean; sending: boolean; @@ -69,6 +70,8 @@ export function LokiComposer({ /** Where the draft is mirrored so a discarded tab gives it back (see * lib/loki/draft.ts). Omit and the draft lives in memory only. */ draftKey?: string; + /** Take the next message while a turn runs (the workspace queues it). */ + queue?: boolean; }) { const [text, setTextState] = useState(defaultText); // Restore once, on the client, after the server-rendered empty box: reading @@ -201,6 +204,7 @@ export function LokiComposer({ sending={sending} onStop={onStop} attachmentOnlyText={IMAGE_ONLY_DEFAULT} + queue={queue} modelPicker above={suggestions} header={scopeRow} diff --git a/src/components/loki/LokiWorkspace.tsx b/src/components/loki/LokiWorkspace.tsx index f7425d6b1..99e52c97b 100644 --- a/src/components/loki/LokiWorkspace.tsx +++ b/src/components/loki/LokiWorkspace.tsx @@ -1,12 +1,13 @@ "use client"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { PanelLeft, SquarePen } from "lucide-react"; import { getJson, postJson, deleteJson, throwApiError } from "@/lib/api/fetch"; import { useLokiStream } from "@/hooks/use-loki-stream"; import { resolveLokiProjectSelection } from "@/lib/loki/project-selection"; import { conversationIdFromParam } from "@/lib/loki/conversation-param"; +import { X } from "lucide-react"; import { clearLokiDraft, lokiDraftKey } from "@/lib/loki/draft"; import { rememberFleetProject } from "@/lib/fleet-context"; import { deriveExecutorHonestyLabel } from "@/lib/executor-honesty"; @@ -340,6 +341,24 @@ export function LokiWorkspace({ const stream = useLokiStream({ onMessage: handleMessage }); const sending = stream.sending; + /** + * Messages typed while a turn ran. The reference chat takes the next thought + * the moment it is finished being typed — "Queue a message…" — and sends it + * when the turn ends; refusing it until a spinner stops is the one place a + * chat makes the person wait on the machine. Sent in order, one per turn, + * through the same `send`, so a queued message is no different from a typed + * one by the time the server sees it. Held (not dropped) if the turn failed: + * the error and its Try again stand in front of it. + */ + type QueuedSend = { + id: number; + text: string; + choice: ModelChoice; + attachments: Attachment[]; + chatOnly?: boolean; + }; + const [queue, setQueue] = useState([]); + // Client-side project filter over the full list (deselect = show all). const visibleConversations = useMemo(() => { if (selectedProjects.length === 0) return conversations; @@ -410,6 +429,14 @@ export function LokiWorkspace({ const scopedProjects = opts.selectedProjectsOverride ?? selectedProjects; const dispatchOnly = opts.dispatchOnly ?? false; const chatOnly = opts.chatOnly ?? false; + if (sending && !dispatchOnly) { + setQueue((prev) => [ + ...prev, + { id: Date.now() + prev.length, text, choice, attachments, chatOnly }, + ]); + clearLokiDraft(lokiDraftKey(activeId)); + return; + } setError(null); setLastSent({ text, choice }); // The draft is leaving the composer. Clear it under the key it was written @@ -452,6 +479,19 @@ export function LokiWorkspace({ }); }; + // The turn ended: the next queued message goes. Through a ref, so the + // effect does not re-run on every render that recreates `send`. + const sendRef = useRef(send); + useEffect(() => { + sendRef.current = send; + }); + useEffect(() => { + if (sending || stream.error || queue.length === 0) return; + const [next, ...rest] = queue; + setQueue(rest); + void sendRef.current(next.text, next.choice, next.attachments, { chatOnly: next.chatOnly }); + }, [sending, stream.error, queue]); + /** * Re-ask the last question. * @@ -557,6 +597,26 @@ export function LokiWorkspace({ )} + {queue.length > 0 && ( +
+ Next: + {queue.map((q) => ( + + {q.text} + + + ))} +
+ )} + setFilterOpen(true)} disabled={false} sending={sending} + queue onStop={stream.stop} showStarters={isStart} dispatchHonesty={dispatchHonesty} diff --git a/src/components/loki/WorkTrail.tsx b/src/components/loki/WorkTrail.tsx index 7f1e2f55a..84e24610c 100644 --- a/src/components/loki/WorkTrail.tsx +++ b/src/components/loki/WorkTrail.tsx @@ -94,6 +94,7 @@ function ToolGroup({ tools, live }: { tools: WorkTool[]; live: boolean }) { )} {toolLabel(tool.name, tool.phase)} + {tool.detail && {tool.detail}} {tool.phase === "end" && ( {tool.facts ?? 0} {(tool.facts ?? 0) === 1 ? "record" : "records"} diff --git a/src/hooks/use-loki-stream.ts b/src/hooks/use-loki-stream.ts index 820b815a8..4df7dafaf 100644 --- a/src/hooks/use-loki-stream.ts +++ b/src/hooks/use-loki-stream.ts @@ -146,6 +146,7 @@ export function useLokiStream({ name: event.name, phase: event.phase, facts: event.facts, + detail: event.detail, }), }; }); diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts index 57d222cad..1abbbe3ca 100644 --- a/src/lib/agent/loop.ts +++ b/src/lib/agent/loop.ts @@ -34,7 +34,7 @@ * "answer with what you have" rather than to an error. */ import { assignFactIds, renderFacts, type Fact } from "@bitbaum/ai-kit/grounding"; -import type { WorkStep } from "@/lib/loki/work"; +import { describeArgs, type WorkStep } from "@/lib/loki/work"; import { trimFactsToBudget, mergeFactsWithCap, @@ -123,11 +123,11 @@ export type LokiTurnEvent = /** What the model said in a gathering round, kept as a working note (see * lib/loki/work.ts) rather than discarded by the `reset` that follows. */ | { type: "note"; text: string } - | { type: "tool"; name: string; phase: "start" } - | { type: "tool"; name: string; phase: "end"; facts: number } + | { type: "tool"; name: string; phase: "start"; detail?: string } + | { type: "tool"; name: string; phase: "end"; facts: number; detail?: string } // A failed tool is its own state, never "returned nothing" — the same // distinction the model is given in the note it receives. - | { type: "tool"; name: string; phase: "fail" } + | { type: "tool"; name: string; phase: "fail"; detail?: string } | { type: "status"; label: "verifying" }; /** A citation the UI can resolve — what [F8] or [D1] actually refers to. */ @@ -301,12 +301,14 @@ async function runToolCalls( } attempted.add(key); used.push(call.name); - emit({ type: "tool", name: call.name, phase: "start" }); + const detail = describeArgs(parsed.data); + emit({ type: "tool", name: call.name, phase: "start", detail }); try { const result = await tool.handler(parsed.data, ctx); facts.push(...result.facts); - emit({ type: "tool", name: call.name, phase: "end", facts: result.facts.length }); - work.push({ kind: "tool", name: call.name, phase: "end", facts: result.facts.length }); + const facts_ = result.facts.length; + emit({ type: "tool", name: call.name, phase: "end", facts: facts_, detail }); + work.push({ kind: "tool", name: call.name, phase: "end", facts: facts_, detail }); messages.push({ role: "user", content: @@ -317,8 +319,8 @@ async function runToolCalls( } catch (e) { // A failed tool must read as "unknown", never as "none" — otherwise the // model reports an outage as an empty result and the operator believes it. - emit({ type: "tool", name: call.name, phase: "fail" }); - work.push({ kind: "tool", name: call.name, phase: "fail" }); + emit({ type: "tool", name: call.name, phase: "fail", detail }); + work.push({ kind: "tool", name: call.name, phase: "fail", detail }); messages.push({ role: "user", content: `[tool ${call.name}] FAILED (${e instanceof Error ? e.message.slice(0, 80) : "error"}). Treat this as unknown, not as empty.`, diff --git a/src/lib/loki/stream.ts b/src/lib/loki/stream.ts index 7183d86fa..98511e2fb 100644 --- a/src/lib/loki/stream.ts +++ b/src/lib/loki/stream.ts @@ -48,7 +48,14 @@ export type LokiStreamEvent = * (lib/loki/work.ts), the narration between groups of tools. */ | { type: "note"; text: string } /** One tool, as it runs. `facts` is how many records it actually returned. */ - | { type: "tool"; name: string; phase: "start" | "end" | "fail"; facts?: number } + | { + type: "tool"; + name: string; + phase: "start" | "end" | "fail"; + facts?: number; + /** The call's arguments as one line (lib/loki/work.ts describeArgs). */ + detail?: string; + } /** Named waiting — what the turn is doing while no prose is arriving. */ | { type: "status"; label: LokiStatusLabel } /** The authoritative persisted turn. Replaces the preview; ends the stream. */ diff --git a/src/lib/loki/work.ts b/src/lib/loki/work.ts index a31c8f215..e6ce6e91a 100644 --- a/src/lib/loki/work.ts +++ b/src/lib/loki/work.ts @@ -32,6 +32,9 @@ export type WorkTool = { phase: "start" | "end" | "fail"; /** Records it returned. Only meaningful once `phase` is "end". */ facts?: number; + /** The call's arguments, one short line (`query: "Elena"`) — what the + * reference chat shows as the command under each step. */ + detail?: string; }; export type WorkNote = { kind: "note"; text: string }; export type WorkStep = WorkTool | WorkNote; @@ -80,6 +83,25 @@ export function applyNote(work: readonly WorkStep[], text: string): WorkStep[] { return [...work, { kind: "note", text }]; } +/** How long a step's detail line may be. One line on a phone. */ +export const DETAIL_MAX_CHARS = 80; + +/** + * A tool call's arguments as one short line: `query: "Elena", limit: 5`. + * Strings are quoted, nested values flattened to JSON, the whole thing cut + * to one line — it is the command under the step, not the record of it. + * Empty arguments are no detail at all rather than `{}`. + */ +export function describeArgs(args: unknown): string | undefined { + if (!args || typeof args !== "object" || Array.isArray(args)) return undefined; + const parts = Object.entries(args as Record) + .filter(([, v]) => v !== undefined && v !== null && v !== "") + .map(([k, v]) => `${k}: ${typeof v === "string" ? JSON.stringify(v) : JSON.stringify(v)}`); + if (parts.length === 0) return undefined; + const line = parts.join(", ").replace(/\s+/g, " "); + return line.length > DETAIL_MAX_CHARS ? `${line.slice(0, DETAIL_MAX_CHARS - 1)}…` : line; +} + /** The one-line summary of a finished tool group. "0 records" is a real and * useful answer — it is how an operator learns the tool ran and their data is * genuinely empty, rather than assuming it never ran. */ @@ -115,6 +137,7 @@ export function readWork(meta: Record | null | undefined): Work name: e.name, phase: e.phase, ...(typeof e.facts === "number" ? { facts: e.facts } : {}), + ...(typeof e.detail === "string" && e.detail ? { detail: e.detail } : {}), }); } }