diff --git a/internal/app/archie/api.go b/internal/app/archie/api.go index 5a08adb3c..bce4c83db 100644 --- a/internal/app/archie/api.go +++ b/internal/app/archie/api.go @@ -7,6 +7,7 @@ import ( "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/chat" "github.com/samcharles93/archie-core/modules/connectors" @@ -34,6 +35,7 @@ type apiModules struct { engine *runs.Engine chat *chat.Module drafts *drafts.Module + live *hub.Hub } func (m apiModules) register(api huma.API) { @@ -50,7 +52,7 @@ func (m apiModules) register(api huma.API) { m.engine.Register(api, orgID, m.hear, m.judge, m.allow) m.drafts.Register(api) m.chat.Register(api) - dashboard.Register(api) + dashboard.Register(api, m.live) } // Document returns the API's OpenAPI document as YAML. It makes the same @@ -63,7 +65,7 @@ func Document() ([]byte, error) { settings: settings, conns: &connectors.Module{}, system: &system.Module{}, tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{}, policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{}, - engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{}, + engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{}, live: hub.New(), }.register(api) return api.OpenAPI().YAML() } diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 9c4204258..69d495f8f 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -115,6 +115,7 @@ func Run(ctx context.Context, configPath string) error { apiModules{ settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies, hear: hear, judge: judge, engine: engine, chat: talk, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies), + live: live, }.register(api) dashboard.Routes(mux, ui.DistDirFS) diff --git a/modules/dashboard/stream.go b/modules/dashboard/stream.go index 3823b5cea..6a1829b8b 100644 --- a/modules/dashboard/stream.go +++ b/modules/dashboard/stream.go @@ -9,18 +9,27 @@ import ( "github.com/danielgtaylor/huma/v2" "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/internal/platform/hub" + "github.com/samcharles93/archie-core/modules/governance" ) // keepalive is how often an idle stream writes a comment, so proxies keep // the connection open and the browser notices one that died. const keepalive = 25 * time.Second +// chatTopic is the hub topic the chat module publishes when an action a +// conversation held settles after its turn ended. +const chatTopic = "chat" + +// chatOutcome is the frame the dashboard re-reads the open conversation on. +const chatOutcome = `data: {"topic":"tasks","data":{"kind":"chat_outcome"}}` + "\n\n" + // Register adds the dashboard's live stream: the one EventSource the SPA -// keeps open, framing each update as `data: {"topic":…,"data":…}`. Nothing -// this binary publishes has a dashboard reader yet, so the stream carries -// only keepalives; it still tells the connection indicator the server is -// up, and a reconnect still makes every mounted page re-read. -func Register(api huma.API) { +// keeps open, framing each update as `data: {"topic":…,"data":…}`. A settled +// chat action is the only update with a dashboard reader; a turn's own reply +// streams from the chat API. Keepalives tell the connection indicator the +// server is up, and a reconnect makes every mounted page re-read. +func Register(api huma.API, h *hub.Hub) { huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "stream-dashboard", Method: http.MethodGet, Path: "/api/stream", Summary: "Stream live dashboard updates", Tags: []string{"Dashboard"}, @@ -28,33 +37,50 @@ func Register(api huma.API) { Description: "Server-sent events: one data frame of {\"topic\", \"data\"} per update, and a keepalive comment while idle", Content: map[string]*huma.MediaType{"text/event-stream": {Schema: &huma.Schema{Type: huma.TypeString}}}, }}, - }), stream) + }), func(ctx context.Context, _ *struct{}) (*huma.StreamResponse, error) { + // Chat is an administrator's; nobody else hears that it changed. + var chat <-chan hub.Note + stop := func() {} + if p, _ := governance.PrincipalFromContext(ctx); p.InstanceAdmin() { + chat, stop = h.Subscribe(chatTopic) + } + return &huma.StreamResponse{Body: func(hc huma.Context) { + defer stop() + serve(hc, chat) + }}, nil + }) } -func stream(_ context.Context, _ *struct{}) (*huma.StreamResponse, error) { - return &huma.StreamResponse{Body: func(hc huma.Context) { - w := hc.BodyWriter() - flusher, ok := w.(http.Flusher) - if !ok { - hc.SetStatus(http.StatusInternalServerError) +func serve(hc huma.Context, chat <-chan hub.Note) { + w := hc.BodyWriter() + flusher, ok := w.(http.Flusher) + if !ok { + hc.SetStatus(http.StatusInternalServerError) + return + } + hc.SetHeader("Content-Type", "text/event-stream") + hc.SetHeader("Cache-Control", "no-store") + hc.SetStatus(http.StatusOK) + flusher.Flush() + tick := time.NewTicker(keepalive) + defer tick.Stop() + for { + frame := ": keepalive\n\n" + select { + case <-hc.Context().Done(): + return + case <-tick.C: + case _, ok := <-chat: + if !ok { + // The hub dropped a reader that fell behind; it reconnects + // and re-reads. + return + } + frame = chatOutcome + } + if _, err := fmt.Fprint(w, frame); err != nil { return } - hc.SetHeader("Content-Type", "text/event-stream") - hc.SetHeader("Cache-Control", "no-store") - hc.SetStatus(http.StatusOK) flusher.Flush() - tick := time.NewTicker(keepalive) - defer tick.Stop() - for { - select { - case <-hc.Context().Done(): - return - case <-tick.C: - if _, err := fmt.Fprint(w, ": keepalive\n\n"); err != nil { - return - } - flusher.Flush() - } - } - }}, nil + } } diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index cf7d7c222..2a106b343 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -610,12 +610,12 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[ p, _ := PrincipalFromContext(ctx) sections := map[string]bool{} for _, name := range []string{ - "settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", + "settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "chat", } { sections[name] = p.InstanceAdmin() } for _, name := range []string{ - "home", "tasks", "work_requests", "chat", "logs", "skills", "curators", "channels", + "home", "tasks", "work_requests", "logs", "skills", "curators", "channels", "captures", "mappings", "bindings", "workflow_editor", "extension_catalogue", "model_aliases", "system_status", "task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles", "org", "org_members", "org_agents", "org_workspaces", "org_policies", "org_denials", "org_audit", "org_usage", "org_config", diff --git a/ui/src/App.vue b/ui/src/App.vue index 18c4c6c91..ad6a95d2f 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -121,7 +121,7 @@ watch(() => accounts.status?.user, (user) => { - + @@ -146,7 +146,7 @@ watch(() => accounts.status?.user, (user) => { - + diff --git a/ui/src/chat/ChatAskCard.vue b/ui/src/chat/ChatAskCard.vue index dafda83f4..1518ce78f 100644 --- a/ui/src/chat/ChatAskCard.vue +++ b/ui/src/chat/ChatAskCard.vue @@ -7,9 +7,9 @@ import { Input } from "@/components/ui/input"; import { Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item"; import { ReadError } from "@/components/ui/read-error"; import ChatQuestionnaire from "./ChatQuestionnaire.vue"; -import { answerAsk, askError, type ChatAsk } from "./state"; +import { answerAsk, askError, askErrorID, type ChatAsk } from "./state"; -defineProps<{ ask: ChatAsk }>(); +const props = defineProps<{ ask: ChatAsk }>(); const reply = ref(""); // The last answer tried, so a failed send can be retried from the error. @@ -17,7 +17,7 @@ const lastAnswer = ref(""); async function answer(value: string): Promise { lastAnswer.value = value; - return answerAsk(value); + return answerAsk(value, props.ask); } async function sendReply(): Promise { @@ -33,7 +33,7 @@ function retry(): void { - + @@ -45,7 +45,7 @@ function retry(): void { Deny - Always this session + Always this session Approve diff --git a/ui/src/chat/ChatSessionActions.vue b/ui/src/chat/ChatSessionActions.vue index c59915cc6..a91f923ef 100644 --- a/ui/src/chat/ChatSessionActions.vue +++ b/ui/src/chat/ChatSessionActions.vue @@ -7,6 +7,7 @@ import { Pencil, RotateCw, Shrink, + Trash2, Undo2, } from "@lucide/vue"; import { ref } from "vue"; @@ -33,7 +34,10 @@ import { describeError } from "@/lib/api"; import ChatSettings from "./ChatSettings.vue"; import { currentSession, + deleteSession, + hasCommand, messages, + renameSession, runSessionCommand, useEscapeLayer, } from "./state"; @@ -99,7 +103,21 @@ function prompt(command: string, message: string): void { function submitPrompt(): void { const value = promptValue.value.trim(); promptOpen.value = false; - if (value) void runSessionCommand(`${promptCommand.value} ${value}`); + if (!value) return; + // Renaming is the chat API's own; other prompts are server commands. + if (promptCommand.value === "/title") void renameSession(value); + else void runSessionCommand(`${promptCommand.value} ${value}`); +} + +const confirmDelete = ref(false); +useEscapeLayer(confirmDelete); +function askDelete(): void { + open.value = false; + confirmDelete.value = true; +} +function remove(): void { + confirmDelete.value = false; + void deleteSession(); } @@ -129,6 +147,7 @@ function submitPrompt(): void { Retry Rename Branch Copy as Markdown + Delete @@ -185,4 +214,13 @@ function submitPrompt(): void { + (confirmDelete = v)"> + + Delete this conversation? + + Cancel + Delete + + + diff --git a/ui/src/chat/ChatSettings.vue b/ui/src/chat/ChatSettings.vue index 507ac33ee..b69770a60 100644 --- a/ui/src/chat/ChatSettings.vue +++ b/ui/src/chat/ChatSettings.vue @@ -34,12 +34,16 @@ const groups = computed(() => { ? entries : [["", selectorData.value.models || []] as [string, string[]]]; }); +// The model is chosen here only when the server offers a choice. +const choosable = computed(() => groups.value.some(([, models]) => models.length)); {{ statusText }} + {{ selectorData.model_error }} diff --git a/ui/src/chat/ChatTranscript.vue b/ui/src/chat/ChatTranscript.vue index 17dcbd48c..83dc91d6e 100644 --- a/ui/src/chat/ChatTranscript.vue +++ b/ui/src/chat/ChatTranscript.vue @@ -51,6 +51,7 @@ function parts(message: ChatMessage, index: number) { update: message.update, choose: message.choose, error: !!message.error, + approvals: message.approvals || [], }; } @@ -84,6 +85,7 @@ const rows = computed(() => { update: undefined, choose: undefined, error: turn.isError, + approvals: turn.approvals || [], live: true, reasoning: turn.reasoning ?? "", // Nothing said and nothing reasoned yet: the turn may still be thinking, @@ -133,6 +135,7 @@ const rows = computed(() => { :thinking-pending="row.thinkingPending" :error="row.error" > + ; voice_available?: boolean; + /** Why no model can answer, when none can. */ + model_error?: string; } /** @@ -171,10 +178,13 @@ export interface ChatSelectorData { * string "undefined" into the transcript on a turn whose reply is empty. */ interface ChatStreamFrame extends ChatToolCall { + seq?: number; type?: string; text: string; - session_id?: string; ask?: ChatAsk; + // An approval frame: an action the turn held for people to answer. + request_id?: string; + action?: string; } /** A turn that never settles must not hold the composer closed forever. */ @@ -183,6 +193,8 @@ let rearmTimeout: (() => void) | null = null; // A failed answer keeps the question card up; the failure shows on the card. export const askError = ref(""); +/** The question askError belongs to. */ +export const askErrorID = ref(""); /** * answerAsk sends the operator's answer to the question the turn waits on. @@ -190,15 +202,25 @@ export const askError = ref(""); * then, and only then. On failure the question stays, askError carries the * message for the card, and the caller's answer stays filled in for a retry. */ -export async function answerAsk(answer: string): Promise { - const ask = streamingTurn.value?.ask; +export async function answerAsk(answer: string, ask = streamingTurn.value?.ask): Promise { if (!ask) return false; try { - await api.chatAnswer(ask.id, answer); + if (ask.via !== "approvals") throw new Error(errors.chat.ask.unsupported); + await api.answerApproval(ask.id, answer === "approve"); } catch (err) { askError.value = describeError(err, errors.chat.ask.answer); + askErrorID.value = ask.id; return false; } + if (ask.via === "approvals") { + // The answered card leaves; what the action did comes back with the turn. + const answered = (asks?: ChatAsk[]) => asks?.filter((a) => a.id !== ask.id); + messages.value = messages.value.map((m) => (m.approvals ? { ...m, approvals: answered(m.approvals) } : m)); + if (streamingTurn.value) streamingTurn.value = { ...streamingTurn.value, approvals: answered(streamingTurn.value.approvals) }; + askError.value = ""; + void reloadTranscript(); + return true; + } streamingTurn.value = streamingTurn.value ? { ...streamingTurn.value, ask: undefined } : null; askError.value = ""; rearmTimeout?.(); @@ -301,6 +323,8 @@ export function escapeOwnedByLayer(): boolean { } let activeController: AbortController | null = null; +// The turn the active controller is reading, once the server has it. +let activeTurnID = ""; // Bumped on every conversation switch: a turn started in an earlier // conversation is detached and must not write into the one now open. @@ -313,9 +337,7 @@ function abortActiveTurn(): void { } async function refreshSessions(): Promise { - const data = await api.chatSessions< - ChatSelectorData & { sessions?: ChatSession[] } - >(); + const data: ChatSelectorData & { sessions?: ChatSession[] } = await api.chatSessions(); const sessionList = data.sessions || []; sessions.value = sessionList; selectorData.value = data; @@ -328,36 +350,57 @@ async function refreshSessions(): Promise { : item, ); - if (!currentSession.value && sessionList[0]) { + if (!currentSession.value && sessionList[0] && !startedFresh) { // The assignment above is readable here immediately, so the first // conversation is selected from the shared state with no data passed in. await selectSession(sessionList[0].session_id); } } +/** Whether the server accepts a slash command; the controls for one it doesn't are hidden. */ +export function hasCommand(command: string): boolean { + return commandSpecs.value.some((spec) => spec.command === command); +} + +// Set by "New chat": the conversation is created with its first message, so +// until then nothing reopens an older one. +let startedFresh = false; + +/** The open conversation, created on the server when there is none yet. */ +async function ensureSession(): Promise { + if (currentSession.value) return currentSession.value; + const created = await api.chatCreateSession(); + // The unsent text and tags typed into the new chat stay with it. + drafts.value = { ...drafts.value, [created.session_id]: drafts.value[""] ?? "" }; + tagDrafts.value = { ...tagDrafts.value, [created.session_id]: tagDrafts.value[""] ?? [] }; + currentSession.value = created.session_id; + startedFresh = false; + sessions.value = [created, ...sessions.value]; + return created.session_id; +} + /** - * Sends a server command over the chat stream, the same path as any message, - * and reads the stream to its end. Resolves with the reply and the session the - * server reports. + * Reads a turn's recorded events from the server-sent stream until it ends, + * handing each frame to onFrame. Resolves with the last frame: done, error or + * cancelled. A stream that closes before one of those is a failure. */ -async function sendCommand( - text: string, -): Promise<{ reply: string; session_id: string }> { - const response = await api.chatStream({ - channel_id: channelID(), - source_id: randomUUID(), - text, - page: sentPage(), - }); - if (!response.body) throw new Error(errors.chat.stream.noBody); - const reader = response.body.getReader(); +async function readTurn( + turnID: string, + signal: AbortSignal | undefined, + onFrame: (frame: ChatStreamFrame) => void, + onBytes: () => void = () => {}, +): Promise { + const response = await api.chatTurnEvents(turnID, 0, { signal }); + const body = response.body; + if (!body) throw new Error(errors.chat.stream.noBody); + const reader = body.getReader(); const decoder = new TextDecoder(); let buffer = ""; - let reply = ""; - let session = ""; - let finished = false; + // Drained to completion: a turn that ends without a terminal frame is a + // failed turn rather than a short one. for (;;) { const { value, done } = await reader.read(); + if (!done) onBytes(); buffer += decoder.decode(value || new Uint8Array(), { stream: !done }); const frames = buffer.split("\n\n"); buffer = frames.pop() || ""; @@ -365,18 +408,32 @@ async function sendCommand( const line = frame.split("\n").find((part) => part.startsWith("data: ")); if (!line) continue; const event = JSON.parse(line.slice(6)) as ChatStreamFrame; - if (event.session_id) session = event.session_id; - if (event.type === "error") throw new Error(event.text); - if (event.type === "delta") reply += event.text; - if (event.type === "done") { - finished = true; - if (!reply) reply = event.text || ""; + onFrame(event); + if (event.type === "done" || event.type === "error" || event.type === "cancelled") { + await reader.cancel().catch(() => {}); + return event; } } - if (done) break; + if (done) throw new Error(errors.chat.stream.endedEarly); } - if (!finished) throw new Error(errors.chat.stream.endedEarly); - return { reply, session_id: session }; +} + +/** + * Sends a server command as a message of the open conversation and reads its + * reply. Only commands the server lists are offered, so this runs only against + * a server that answers them. + */ +async function sendCommand( + text: string, +): Promise<{ reply: string; session_id: string }> { + const session = await ensureSession(); + const turn = await api.chatSend(session, { text, page: sentPage() }); + let reply = ""; + const last = await readTurn(turn.id, undefined, (event) => { + if (event.type === "delta") reply += event.text; + }); + if (last.type === "error") throw new Error(last.text); + return { reply: reply || last.text || "", session_id: session }; } export async function selectSession(id: string): Promise { @@ -386,6 +443,7 @@ export async function selectSession(id: string): Promise { sessionEpoch++; abortActiveTurn(); currentSession.value = id; + startedFresh = false; messages.value = []; streamingTurn.value = null; queuedMessages.value = []; @@ -394,11 +452,16 @@ export async function selectSession(id: string): Promise { askError.value = ""; try { - // Resuming is the server's own command, so the transcript read below is of - // a conversation the server considers current rather than a stale one. - await sendCommand(`/resume ${id}`); - const transcript = await readTranscript(id); - if (isCurrentSession(id)) messages.value = transcript; + const turns = await api.chatTurns(id); + if (!isCurrentSession(id)) return; + const last = turns.at(-1); + const open = last && (last.state === "queued" || last.state === "running") ? last : undefined; + // A turn still being answered is followed live rather than shown half done. + messages.value = transcriptOf(open ? turns.slice(0, -1) : turns); + if (open) { + messages.value = [...messages.value, { from: "web", text: open.text, message_id: `${open.id}:in` }]; + void sendMessage({ follow: open.id, textOverride: open.text }); + } } catch (err) { if (isCurrentSession(id)) sessionError.value = describeError(err, errors.chat.session.loadMessages); @@ -407,44 +470,74 @@ export async function selectSession(id: string): Promise { } } -// readTranscript reads a conversation's messages with each reply's tool calls. -// Tool calls belong to the turn, not the message, so a reopened conversation -// gets its transcript back with the evidence in place. -async function readTranscript(id: string): Promise { - const [msgs, turns] = await Promise.all([ - api.chatMessages(id), - api.chatTurns(id), +/** The turns as the transcript shows them: each message, then what answered it. */ +function transcriptOf(turns: ChatTurnRecord[]): ChatMessage[] { + return turns.flatMap((turn): ChatMessage[] => [ + { from: "web", text: turn.text, message_id: `${turn.id}:in` }, + replyOf(turn), ]); - const byAssistantMessage = new Map(); - // A failed or stopped turn records no reply, so what happened follows the - // message it was answering. - const failedByInput = new Map(); - for (const turn of turns || []) { - const assistantID = turn.assistant_message_id || turn.AssistantMessageID; - if (assistantID) byAssistantMessage.set(assistantID, turn); - else if ((turn.status === "failed" || turn.status === "cancelled") && turn.input_message_id) - failedByInput.set(turn.input_message_id, turn); +} + +function replyOf(turn: ChatTurnRecord): ChatMessage { + const end = Array.from(turn.reply).length; + const settled = new Map(turn.actions.map((a) => [a.request_id, a])); + const tools: ChatToolCall[] = [ + ...turn.tool_calls, + // Pages opened and answered approvals carry no offset; they follow the reply. + ...turn.navigate.map((n) => ({ ...n, text_offset: end })), + ...turn.approvals.flatMap((a) => { + const done = settled.get(a.request_id); + if (!done) return []; + return [{ + name: a.action, + text: done.result ? `${done.state}: ${done.result}` : done.state, + failed: !["approved", "running", "succeeded"].includes(done.state), + text_offset: end, + }]; + }), + ]; + const message: ChatMessage = { + from: "assistant", + message_id: `${turn.id}:out`, + text: turn.reply, + tool_calls: tools, + approvals: turn.approvals.filter((a) => !settled.has(a.request_id)).map(askOf), + }; + if (turn.state === "failed") return { ...message, text: turn.reply || turn.error || errors.chat.turn.failed, error: !turn.reply }; + if (turn.state === "cancelled") return { ...message, text: turn.reply || "Stopped before replying." }; + return message; +} + +function askOf(a: { request_id?: string; action?: string; summary?: string }): ChatAsk { + return { id: a.request_id ?? "", kind: "approval", prompt: a.action ?? "", detail: a.summary, via: "approvals" }; +} + +/** Renames the open conversation. */ +export async function renameSession(title: string): Promise { + const id = currentSession.value; + if (!id) return; + try { + const renamed = await api.chatRenameSession(id, title); + sessions.value = sessions.value.map((s) => (s.session_id === id ? renamed : s)); + } catch (err) { + sessionError.value = describeError(err, errors.chat.session.command); } - return (msgs || []).flatMap((message) => { - const messageID = message.message_id || message.MessageID; - const turn = messageID ? byAssistantMessage.get(messageID) : undefined; - const failed = messageID ? failedByInput.get(messageID) : undefined; - if (failed) - return [ - message, - { - from: "assistant", - text: - failed.status === "cancelled" - ? "Stopped before replying." - : failed.error || errors.chat.turn.failed, - error: failed.status !== "cancelled", - tool_calls: failed.tool_calls || [], - }, - ]; - return turn - ? { ...message, tool_calls: turn.tool_calls || turn.ToolCalls || [] } - : message; +} + +/** Deletes the open conversation and opens the next one. */ +export async function deleteSession(): Promise { + const id = currentSession.value; + if (!id) return; + try { + await api.chatDeleteSession(id); + } catch (err) { + sessionError.value = describeError(err, errors.chat.session.delete); + return; + } + newChat(); + startedFresh = false; + await refreshSessions().catch((err) => { + sessionError.value = errors.chat.session.refreshList(describeError(err, errors.common.unknown)); }); } @@ -459,7 +552,7 @@ export async function reloadTranscript(): Promise { const stopped = streamingTurn.value?.text === "Turn stopped."; if (!id || (streamingTurn.value && !stopped)) return; try { - const transcript = await readTranscript(id); + const transcript = transcriptOf(await api.chatTurns(id)); if (isCurrentSession(id) && (!streamingTurn.value || streamingTurn.value.text === "Turn stopped.")) { messages.value = transcript; if (stopped) streamingTurn.value = null; @@ -475,17 +568,6 @@ function isCurrentSession(id: string): boolean { return currentSession.value === id; } -/** One recorded turn, as GET /api/chat/sessions/{id}/turns returns it. */ -interface ChatTurnView { - input_message_id?: string; - status?: string; - error?: string; - assistant_message_id?: string; - AssistantMessageID?: string; - tool_calls?: ChatToolCall[]; - ToolCalls?: ChatToolCall[]; -} - export async function runSessionCommand(command: string): Promise { if (!currentSession.value) return; try { @@ -527,8 +609,17 @@ export function setTurnHooks(hooks: typeof turnHooks): void { turnHooks = hooks; } +/** Opens an empty conversation; the server creates it with its first message. */ export function newChat(): void { - void sendMessage({ textOverride: "/new" }); + sessionEpoch++; + abortActiveTurn(); + startedFresh = true; + currentSession.value = ""; + messages.value = []; + streamingTurn.value = null; + queuedMessages.value = []; + sessionError.value = ""; + askError.value = ""; } /** Messages sent while a turn runs, oldest first; each goes when the turn before it ends. */ @@ -595,6 +686,7 @@ export function syncCommandMenu(value: string, caret: number): void { // The list is read when # is first typed, so it is never older than the // moment the operator reached for it. if ( + tasksBacked() && detectTrigger(value, caret)?.trigger === "#" && (!isCommandMenuOpen.value || menuTrigger.value !== "#") ) { @@ -604,8 +696,15 @@ export function syncCommandMenu(value: string, caret: number): void { renderMenu(); } +// # attaches a task, which needs the server's task list; without one the +// trigger is plain text. +function tasksBacked(): boolean { + return useSessionStore().sections?.tasks !== false; +} + function renderMenu(): void { - const found = detectTrigger(lastInput.value, lastInput.caret); + const trigger = detectTrigger(lastInput.value, lastInput.caret); + const found = trigger?.trigger === "#" && !tasksBacked() ? null : trigger; let matches: Completion[] = []; if (found?.trigger === "/") { matches = commandCompletions(commandSpecs.value, found.query); @@ -691,7 +790,9 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { : typed; const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue); if (!text) return; - if (isSending.value) { + const follow = retryOpts?.follow; + // Following a turn already sent never queues: it is the turn being waited on. + if (isSending.value && !follow) { // A message typed during a turn waits for it; a retry has nothing to // wait for. A voice clip queues too, so it is not dropped. if (isRetry) return; @@ -709,15 +810,15 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { isSending.value = true; statusText.value = isRetry ? "Retrying…" : "Thinking…"; - if (!isRetry) { + if (!isRetry && !follow) { messages.value = [...messages.value, { from: "web", text }]; // A queued or command send must not clear what is being typed. if (explicitText === undefined) clearDraft(); } // A bare /model offers its choices as buttons, as Telegram does; with an - // argument it goes to the gateway like any command. - if (!isRetry && text.trim() === "/model") { + // argument it goes to the server like any command. + if (!isRetry && !follow && text.trim() === "/model" && hasCommand("/model")) { messages.value = [...messages.value, { from: "assistant", text: "", choose: "model" }]; isSending.value = false; statusText.value = "Ready"; @@ -725,7 +826,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { } // /update answers here, where the panel can offer Install like Telegram does. - if (!isRetry && text.trim() === "/update") { + if (!isRetry && !follow && text.trim() === "/update" && hasCommand("/update")) { try { const update = await api.updateSnapshot(); messages.value = [...messages.value, { from: "assistant", text: "", update }]; @@ -743,12 +844,12 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { } let activeTools: ChatToolCall[] = []; + let approvals: ChatAsk[] = []; streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry, reasoning: "" }; askError.value = ""; let streamedText = ""; let streamedReasoning = ""; - let finished = false; let timedOut = false; let detached = false; let timeoutId: ReturnType | undefined; @@ -758,6 +859,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { const ctrl = new AbortController(); controller = ctrl; activeController = ctrl; + activeTurnID = follow ?? ""; const arm = () => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { @@ -768,51 +870,25 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { arm(); // The clock stops while a question waits on the operator. rearmTimeout = arm; - await turnHooks.before?.(); - - const response = await api.chatStream( - { - channel_id: channelID(), - source_id: turn.sourceID, - text: turn.text, - page: sentPage(), - voice: turn.voice, - }, - { signal: ctrl.signal }, - ); - const body = response.body; - if (!body) throw new Error(errors.chat.stream.noBody); - - const reader = body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; - - // Drained to completion: the stream is read until the reader reports done, - // and a turn that ends without a `done` frame is a failed turn rather than - // a short one. Reading only some frames leaves the producer writing into a - // stream nobody collects. - for (;;) { - const { value, done } = await reader.read(); - if (epoch !== sessionEpoch) { - // Detached by a conversation switch mid-turn: stop reading and write - // nothing into the conversation now open. - detached = true; - await reader.cancel().catch(() => {}); - return; + if (!follow) { + await turnHooks.before?.(); + const session = await ensureSession(); + const sent = await api.chatSend(session, { text: turn.text, page: sentPage(), page_label: pageTag.value?.label }); + if (activeController === ctrl) activeTurnID = sent.id; + // Stopped while the message was on its way: the turn exists now, so stop it. + if (ctrl.signal.aborted) { + void api.chatCancelTurn(sent.id).catch(() => {}); + throw new DOMException("stopped", "AbortError"); } - // Any bytes, including the server's keepalive, show the turn is alive; - // a question waiting on the operator stops the clock until answered. - if (!done && !streamingTurn.value?.ask) arm(); - buffer += decoder.decode(value || new Uint8Array(), { stream: !done }); - const frames = buffer.split("\n\n"); - buffer = frames.pop() || ""; - for (const frame of frames) { - const line = frame - .split("\n") - .find((part) => part.startsWith("data: ")); - if (!line) continue; - const event = JSON.parse(line.slice(6)) as ChatStreamFrame; - if (event.session_id) currentSession.value = event.session_id; + } + + const last = await readTurn( + activeTurnID, + ctrl.signal, + (event) => { + // Detached by a conversation switch mid-turn: write nothing into the + // conversation now open. + if (epoch !== sessionEpoch) throw new DOMException("detached", "AbortError"); if (event.type === "delta") { streamedText += event.text; streamingTurn.value = streamingTurn.value @@ -832,28 +908,29 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { // is one more thing the turn did, and it renders as a chip rather than // a tool line. if (event.type === "tool" || event.type === "navigate") { - activeTools = [...activeTools, event]; + const at = event.type === "navigate" ? { text_offset: Array.from(streamedText).length } : {}; + activeTools = [...activeTools, { ...event, ...at }]; streamingTurn.value = streamingTurn.value ? { ...streamingTurn.value, tools: activeTools } : null; } - if (event.type === "ask" && event.ask) { - clearTimeout(timeoutId); - askError.value = ""; + // A held action does not stop the turn: its card waits in the reply. + if (event.type === "approval" && event.request_id) { + approvals = [...approvals, askOf(event)]; streamingTurn.value = streamingTurn.value - ? { ...streamingTurn.value, ask: event.ask } + ? { ...streamingTurn.value, approvals } : null; } - if (event.type === "done") { - finished = true; - if (!streamedText) streamedText = event.text || ""; - } - if (event.type === "error") throw new Error(event.text); - } - if (done) break; - } - - if (!finished) throw new Error(errors.chat.stream.endedEarly); + }, + () => { + // Any bytes, including the server's keepalive, show the turn is alive. + if (epoch === sessionEpoch) arm(); + }, + ); + if (epoch !== sessionEpoch) throw new DOMException("detached", "AbortError"); + if (last.type === "error") throw new Error(last.text); + if (last.type === "cancelled") throw new DOMException("stopped", "AbortError"); + if (!streamedText) streamedText = last.text || ""; if (epoch === sessionEpoch) { // /new opens an empty conversation, so the window clears instead of @@ -863,7 +940,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { ? [] : [ ...messages.value, - { from: "assistant", text: streamedText, tool_calls: activeTools }, + { from: "assistant", text: streamedText, tool_calls: activeTools, approvals }, ]; streamingTurn.value = null; } @@ -884,7 +961,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { if (streamedText) { messages.value = [ ...messages.value, - { from: "assistant", text: streamedText, tool_calls: activeTools }, + { from: "assistant", text: streamedText, tool_calls: activeTools, approvals }, ]; activeTools = []; } @@ -921,6 +998,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise { // the conversation now open. if (controller && activeController === controller) { activeController = null; + activeTurnID = ""; isSending.value = false; if (detached) statusText.value = "Ready"; } @@ -935,12 +1013,17 @@ function lastStep(tools: ChatToolCall[]): string { export function stopTurn(): void { statusText.value = "Stopping…"; - if (currentSession.value) { - void api.chatCancel(currentSession.value).catch((err) => { - sessionError.value = errors.chat.turn.stop(describeError(err, errors.common.unknown)); - }); + const id = activeTurnID; + // Without a turn yet, the abort stops the send; with one, the server stops + // it and the stream ends on its cancelled event, keeping what was said. + if (!id) { + abortActiveTurn(); + return; } - abortActiveTurn(); + void api.chatCancelTurn(id).catch((err) => { + sessionError.value = errors.chat.turn.stop(describeError(err, errors.common.unknown)); + abortActiveTurn(); + }); } /** diff --git a/ui/src/chat/turn.ts b/ui/src/chat/turn.ts index 40f8f3feb..8b3a61f9b 100644 --- a/ui/src/chat/turn.ts +++ b/ui/src/chat/turn.ts @@ -24,6 +24,8 @@ export interface RetryOptions { textOverride?: string; turn?: ChatTurn; voice?: ChatTurn["voice"]; + /** A turn the server already has: follow its stream instead of sending. */ + follow?: string; } // resolveTurn decides what to send: a real retry descriptor's original turn, diff --git a/ui/src/copy/errors/chat.ts b/ui/src/copy/errors/chat.ts index 25fe2baa5..d422a096a 100644 --- a/ui/src/copy/errors/chat.ts +++ b/ui/src/copy/errors/chat.ts @@ -3,6 +3,7 @@ export const chat = { ask: { answer: "Could not send the answer", + unsupported: "This question can't be answered here", }, composer: { microphoneUnavailable: (detail: string) => `Microphone unavailable: ${detail}`, @@ -12,6 +13,7 @@ export const chat = { loadMessages: "Could not load session messages", refreshList: (detail: string) => `Could not refresh the session list: ${detail}`, command: "Session action failed", + delete: "Could not delete the conversation", model: (detail: string) => `Model update failed: ${detail}`, nothingToCopy: "Nothing to copy", copyFailed: (detail: string) => `Not copied: ${detail}`, diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index e5c777cc6..509f83457 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -515,34 +515,77 @@ export const api = { request(`/api/sources/${encodeURIComponent(path)}/secret`, { method: "POST", }), - chatSessions: () => request("/api/chat/sessions"), - chatAnswer: (id: string, answer: string) => - request("/api/chat/answer", { method: "POST", body: { id, answer } }), - chatMessages: (id: string) => - request(`/api/chat/sessions/${encodeURIComponent(id)}/messages`), - chatTurns: (id: string) => - request(`/api/chat/sessions/${encodeURIComponent(id)}/turns`), - chatCancel: (sessionID: string) => - request("/api/chat/cancel", { - method: "POST", - body: { session_id: sessionID }, - }), + chatSessions: () => request("/api/chat/sessions"), + chatCreateSession: () => request("/api/chat/sessions", { method: "POST" }), + chatRenameSession: (id: string, title: string) => + request(`/api/chat/sessions/${encodeURIComponent(id)}`, { method: "PATCH", body: { title } }), + chatDeleteSession: (id: string) => + request(`/api/chat/sessions/${encodeURIComponent(id)}`, { method: "DELETE", parse: false }), + chatTurns: (id: string) => request(`/api/chat/sessions/${encodeURIComponent(id)}/turns`), + chatSend: (id: string, body: { text: string; page?: string; page_label?: string }) => + request(`/api/chat/sessions/${encodeURIComponent(id)}/turns`, { method: "POST", body }), + chatCancelTurn: (id: string) => + request(`/api/chat/turns/${encodeURIComponent(id)}/cancel`, { method: "POST" }), // A server-sent event stream cannot be parsed as JSON and outlives a normal // request, so the caller owns the abort controller and the timeout, and - // reads the body itself. Only the URL, headers, and failure shape are shared. - chatStream: (payload: unknown, opts: { signal?: AbortSignal } = {}) => - send("/api/chat/stream", { - method: "POST", - headers: { - Accept: "text/event-stream", - "Content-Type": "application/json", - "X-Archie-CSRF": "1", - }, - body: JSON.stringify(payload), + // reads the body itself. `after` is the last event seq already read. + chatTurnEvents: (id: string, after: number, opts: { signal?: AbortSignal } = {}) => + send(`/api/chat/turns/${encodeURIComponent(id)}/events${after ? qs({ after }) : ""}`, { + headers: { Accept: "text/event-stream" }, signal: opts.signal, }), }; +/** GET /api/chat/sessions: the conversations and the model that answers. */ +export interface ChatSessions { + sessions: ChatSessionView[]; + active_model?: string; + model_error?: string; +} + +export interface ChatSessionView { + session_id: string; + title: string; + created_at: string; + updated_at: string; +} + +/** One turn of a conversation, with what it did, as the chat API records it. */ +export interface ChatTurnRecord { + id: string; + session_id: string; + seq: number; + state: "queued" | "running" | "succeeded" | "failed" | "cancelled"; + text: string; + page?: string; + page_label?: string; + reply: string; + reasoning?: string; + error?: string; + tool_calls: { id: string; name: string; parameters: string; text: string; failed?: boolean; duration_ms: number; text_offset: number }[]; + approvals: ChatApprovalRecord[]; + actions: ChatActionRecord[]; + navigate: { path: string; label: string }[]; + created_at: string; + finished_at?: string; +} + +/** An action judgement held in a chat turn and put to people. */ +export interface ChatApprovalRecord { + request_id: string; + action: string; + summary: string; + level: string; + deadline: string; +} + +/** What became of a held action once its approval was answered. */ +export interface ChatActionRecord { + request_id: string; + state: string; + result?: string; +} + export interface Run { id: string; workflow: string; diff --git a/ui/test/chat-more-menu.test.ts b/ui/test/chat-more-menu.test.ts index 2f60c4a1e..fd8c5d126 100644 --- a/ui/test/chat-more-menu.test.ts +++ b/ui/test/chat-more-menu.test.ts @@ -27,15 +27,12 @@ const PAGE_MOCK = `(() => { const url = typeof input === "string" ? input : input.url; const json = (body, type = "application/json") => Promise.resolve(new Response(typeof body === "string" ? body : JSON.stringify(body), { status: 200, headers: { "Content-Type": type } })); - if (url.includes("/api/chat/stream")) { - window.__archieSent.push(JSON.parse(init.body).text); - return json('data: {"type":"delta","text":"ok","session_id":"s1"}\\n\\ndata: {"type":"done","text":"ok","session_id":"s1"}\\n\\n', "text/event-stream"); - } + if (url.includes("/api/chat/")) window.__archieSent.push((init?.method || "GET") + " " + url.replace(location.origin, "") + (init?.body ? " " + init.body : "")); if (url.includes("/api/auth/status")) return json({ setup_required: false, user: { id: "u1", display_name: "Operator", kind: "operator" }, oidc: false, public_url: location.origin + "/", instance: "archie" }); if (url.includes("/api/chat/sessions")) - return json({ providers: ["test"], models: ["test-model"], models_by_provider: { test: ["test-model"] }, active_provider: "test", active_model: "test-model", commands: ["/retry", "/undo", "/title", "/branch", "/compress"], voice_available: false, sessions: [{ session_id: "s1", title: "Test session", created_at: "2026-01-01T00:00:00Z" }] }); - if (url.includes("/turns")) return json({ turns: [] }); + return json({ active_model: "test-model", sessions: [{ session_id: "s1", title: "Test session", created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" }] }); + if (url.includes("/turns")) return json([]); if (url.includes("/health")) return json({ status: "ok" }); if (url.includes("/api/")) return json({}); return realFetch(input, init); @@ -203,8 +200,8 @@ test("chat More menu opens on screen and its items run", { timeout: 90000 }, asy return false; })()`).then((expanded: unknown) => assert.equal(expanded, true, "the chat dock expanded and rendered the More button")); - // Pick the open conversation first, so the menu's commands have a - // session to act on (selectSession itself streams /resume s1). + // Pick the open conversation first, so the menu's actions have a + // session to act on. await cdp.evaluate(`(() => { document.querySelector('button[aria-label="Conversations"]').click(); })()`); @@ -215,9 +212,10 @@ test("chat More menu opens on screen and its items run", { timeout: 90000 }, asy })()`); await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - for (let i = 0; i < 40 && !window.__archieSent.includes("/resume s1"); i++) await sleep(250); - return window.__archieSent.includes("/resume s1"); - })()`).then((selected: unknown) => assert.equal(selected, true, "selecting the conversation opened it on the server")); + const read = () => window.__archieSent.includes("GET /api/chat/sessions/s1/turns"); + for (let i = 0; i < 40 && !read(); i++) await sleep(250); + return read(); + })()`).then((selected: unknown) => assert.equal(selected, true, "selecting the conversation read its turns")); // Hover the More button: the tooltip keeps its accessible name. const moreBox = await cdp.evaluate(`(() => { const r = document.querySelector('button[aria-label="More"]').getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`); @@ -249,22 +247,20 @@ test("chat More menu opens on screen and its items run", { timeout: 90000 }, asy assert.equal(opened.exists, true, "clicking More opens the popover"); assert.equal(opened.ariaExpanded, "true"); assert.equal(opened.inViewport, true, `the menu must render on screen, got ${JSON.stringify(opened.rect)}`); - for (const item of ["Retry", "Undo", "Rename", "Branch", "Preview compression", "Copy as Markdown"]) { + for (const item of ["Rename", "Copy as Markdown", "Delete"]) { assert.ok(opened.text.includes(item), `the menu lists ${item}`); } + // A server that lists no slash commands gets none of their buttons. + for (const item of ["Retry", "Undo", "Branch", "Preview compression"]) { + assert.ok(!opened.text.includes(item), `the menu hides ${item}`); + } - // Run Retry from the menu: the command goes over the chat stream and - // the menu closes. + // Run Copy as Markdown from the menu: the menu closes. await cdp.evaluate(`(() => { - const retry = [...document.querySelectorAll('[data-slot="popover-content"] button')].find((el) => el.innerText.includes("Retry")); - if (retry) retry.click(); + const copy = [...document.querySelectorAll('[data-slot="popover-content"] button')].find((el) => el.innerText.includes("Copy as Markdown")); + if (copy) copy.click(); })()`); - await cdp.evaluate(`(async () => { - const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - for (let i = 0; i < 40 && !window.__archieSent.includes("/retry"); i++) await sleep(250); - return window.__archieSent.includes("/retry"); - })()`).then((sent: unknown) => assert.equal(sent, true, `Retry sends /retry over the chat stream, got ${JSON.stringify(sent)}`)); - const afterRetry = await cdp.evaluate(`(async () => { + const afterCopy = await cdp.evaluate(`(async () => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); for (let i = 0; i < 40; i++) { const pop = document.querySelector('[data-slot="popover-content"]'); @@ -277,9 +273,9 @@ test("chat More menu opens on screen and its items run", { timeout: 90000 }, asy dockStillThere: !!document.querySelector('button[aria-label="More"]'), }; })()`); - assert.equal(afterRetry.popoverClosed, true, "running a command closes the menu"); - assert.equal(afterRetry.ariaExpanded, "false"); - assert.equal(afterRetry.dockStillThere, true); + assert.equal(afterCopy.popoverClosed, true, "running an action closes the menu"); + assert.equal(afterCopy.ariaExpanded, "false"); + assert.equal(afterCopy.dockStillThere, true); // Reopen and use Rename: the labelled dialog opens from the menu. await cdp.evaluate(`(() => { document.querySelector('button[aria-label="More"]').click(); })()`); @@ -295,12 +291,26 @@ test("chat More menu opens on screen and its items run", { timeout: 90000 }, asy })()`); assert.ok(dialog && dialog.includes("Session title"), `Rename opens the session-title dialog, got ${JSON.stringify(dialog)}`); - // Cancel the dialog, reopen the menu, then Escape: it dismisses the menu - // but leaves the conversation open. + // Submit a title: it is saved through the chat API. await cdp.evaluate(`(() => { - const cancel = [...document.querySelectorAll('[role="dialog"] button')].find((el) => el.innerText.trim() === "Cancel"); - if (cancel) cancel.click(); + const input = document.querySelector('[role="dialog"] input'); + input.value = "Renamed"; + input.dispatchEvent(new Event("input", { bubbles: true })); })()`); + await new Promise((r) => setTimeout(r, 300)); + await cdp.evaluate(`(() => { + const ok = [...document.querySelectorAll('[role="dialog"] button')].find((el) => el.innerText.trim() === "OK"); + if (ok) ok.click(); + })()`); + await cdp.evaluate(`(async () => { + const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + const sent = () => window.__archieSent.includes('PATCH /api/chat/sessions/s1 {"title":"Renamed"}'); + for (let i = 0; i < 40 && !sent(); i++) await sleep(250); + return sent(); + })()`).then((sent: unknown) => assert.equal(sent, true, "Rename saves the title through the chat API")); + + // Reopen the menu, then Escape: it dismisses the menu but leaves the + // conversation open. await new Promise((r) => setTimeout(r, 800)); await cdp.evaluate(`(() => { document.querySelector('button[aria-label="More"]').click(); })()`); await new Promise((r) => setTimeout(r, 1000)); diff --git a/ui/test/chat-thinking.test.ts b/ui/test/chat-thinking.test.ts index 7c3e154f1..71a9d71c0 100644 --- a/ui/test/chat-thinking.test.ts +++ b/ui/test/chat-thinking.test.ts @@ -15,6 +15,8 @@ const apiStub = "export const api = new Proxy({}, { get: (_, p) => globalThis.__archieChatTestApi[p] });" + "export function describeError(err, fallback) { return err instanceof Error && err.message ? err.message : fallback; }", ); +const sessionStub = + "data:text/javascript," + encodeURIComponent("export function useSessionStore() { return { sections: null }; }"); const routerStub = "data:text/javascript," + encodeURIComponent( @@ -26,6 +28,7 @@ register( const SRC = ${JSON.stringify(pathToFileURL(srcRoot + "/").href)}; export async function resolve(specifier, context, next) { if (specifier === "@/lib/api") return { url: ${JSON.stringify(apiStub)}, shortCircuit: true }; + if (specifier === "@/stores/session") return { url: ${JSON.stringify(sessionStub)}, shortCircuit: true }; if (specifier === "@/router") return { url: ${JSON.stringify(routerStub)}, shortCircuit: true }; if (specifier === "@/copy/errors") return { url: SRC + "copy/errors/index.ts", shortCircuit: true }; if (specifier.startsWith("@/")) return { url: SRC + specifier.slice(2) + ".ts", shortCircuit: true }; @@ -40,7 +43,6 @@ register( interface Frame { type: string; text?: string; - session_id?: string; } /** One SSE body: each frame as the server writes it, `data: {...}\n\n`. */ @@ -55,14 +57,14 @@ function sseBody(frames: Frame[]): ReadableStream { }); } -const started = { type: "started", session_id: "s1" }; - -// The stream stub: chatStream answers with the given frames, sessions reads -// back an empty list so the finished turn does not trigger a reload. +// The stream stub: the turn's events answer with the given frames, sessions +// reads back an empty list so the finished turn does not trigger a reload. function stubApi(frames: Frame[]): void { (globalThis as Record).__archieChatTestApi = { - chatStream: () => ({ body: sseBody(frames) }), - chatSessions: () => ({ sessions: [], commands: [] }), + chatCreateSession: () => ({ session_id: "s1", title: "" }), + chatSend: () => ({ id: "t1" }), + chatTurnEvents: () => ({ body: sseBody(frames) }), + chatSessions: () => ({ sessions: [] }), }; } @@ -70,7 +72,6 @@ const state = await import("../src/chat/state.ts"); test("reasoning frames accumulate on the live turn as its thinking", async () => { stubApi([ - started, { type: "reasoning", text: "considering " }, { type: "reasoning", text: "the request" }, { type: "error", text: "provider exploded" }, @@ -84,10 +85,9 @@ test("reasoning frames accumulate on the live turn as its thinking", async () => test("reasoning never leaks into the reply text", async () => { stubApi([ - started, { type: "reasoning", text: "secret chain of thought" }, { type: "delta", text: "Hello" }, - { type: "done", text: "Hello", session_id: "s1" }, + { type: "done", text: "Hello" }, ]); await state.sendMessage({ textOverride: "hi" }); assert.equal(state.streamingTurn.value, null); @@ -97,7 +97,7 @@ test("reasoning never leaks into the reply text", async () => { }); test("a turn without reasoning frames completes normally", async () => { - stubApi([started, { type: "delta", text: "Hi" }, { type: "done", text: "Hi", session_id: "s1" }]); + stubApi([{ type: "delta", text: "Hi" }, { type: "done", text: "Hi" }]); await state.sendMessage({ textOverride: "hey" }); assert.equal(state.streamingTurn.value, null); assert.equal(state.messages.value.at(-1)?.text, "Hi");