Files
archie/ui/src/chat/state.ts
T

963 lines
34 KiB
TypeScript

import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { errors } from "@/copy/errors";
import { api, describeError, type ChatTurnRecord } from "@/lib/api";
import { router } from "@/router";
import { answerApproval } from "@/runs/answer";
import {
resolveTurn,
retryChatTurn,
type ChatTurn,
type RetryOptions,
} from "./turn";
/**
* The chat panel's shared state.
*
* The launcher and the panel are separate components and the panel survives a
* navigation, so the conversation lives in a module rather than in either one.
* Everything the server answers with is read here; the components decide how it
* looks.
*/
/** One web conversation, as GET /api/chat/sessions lists it. */
export interface ChatSession {
session_id: string;
title?: string;
branch_name?: string;
created_at?: string;
}
/** One slash command the server will accept. */
export interface ChatCommandSpec {
command: string;
usage?: string;
description?: string;
}
/** A task the operator can attach to a message as context. */
export interface TaskRef {
id: number | string;
title?: string;
status?: string;
}
/**
* A tool the assistant called. A live frame names the tool in `tool` and
* carries its outcome in `text`; a recorded turn uses `name` and `summary`.
*/
export interface ChatToolCall {
id?: string;
name?: string;
tool?: string;
parameters?: string;
summary?: string;
text?: string;
failed?: boolean;
duration_ms?: number;
/** Runes of reply text before the call: where in the reply it happened. */
text_offset?: number;
/** A dashboard_navigate result: the page to route to, instead of a tool line. */
path?: string;
label?: string;
// The same view reaches the browser from more than one composition, so an
// outcome may arrive under either spelling. `err`/`Err` is also how a failed
// call reports itself: it is a result, not a missing one.
Name?: string;
Parameters?: string;
Summary?: string;
Err?: string;
err?: string;
}
/**
* One attachment a message carried, as a recorded transcript serves it. The
* bytes are turn-scoped and never reach a browser, so this is metadata only;
* `url` is present exactly when the attachment itself carried one, and a
* platform file id never appears here because it is a handle, not an address.
*/
export interface ChatMedia {
type: string;
file_name?: string;
mime_type?: string;
file_size?: number;
width?: number;
height?: number;
duration?: number;
url?: string;
}
/** One message in the transcript, from either side. */
export interface ChatMessage {
from?: string;
text?: string;
// Attachments only ever arrive in the served transcript, never from this
// browser's composer, so unlike the fields below this one has no second
// spelling to read.
media?: ChatMedia[];
tool_calls?: ChatToolCall[];
// The same view reaches the browser from more than one composition, so both
// spellings are read rather than assuming one serialiser.
From?: string;
Text?: string;
ToolCalls?: ChatToolCall[];
message_id?: string;
MessageID?: string;
/** An update check answered in the panel, with its install actions. */
update?: ChatUpdate;
/** A bare /model, answered with its choices. */
choose?: "model";
/** A reply standing in for a turn that failed; the bubble shows it as an error. */
error?: boolean;
/** Actions the turn held for approval that nobody has answered yet. */
approvals?: ChatAsk[];
}
/** The update snapshot /update shows, and whether this host can install it. */
export interface ChatUpdate {
snapshot: unknown;
available: unknown[];
can_install: boolean;
}
/** A turn in flight: what it is showing, and what to resend if it fails. */
export interface StreamingTurn {
text: string;
tools: ChatToolCall[];
isError: boolean;
turn?: ChatTurn;
isRetry: boolean;
/** The model's thinking so far, streamed on `reasoning` frames. */
reasoning?: string;
/** A question the turn waits on until the operator answers it. */
ask?: ChatAsk;
/** Actions the turn held for approval so far. */
approvals?: ChatAsk[];
}
/** An approval, clarify or picker question from a running turn. */
export interface ChatAsk {
id: string;
kind: "approval" | "clarify" | "picker" | "questionnaire";
prompt: string;
detail?: string;
choices?: { id: string; label: string }[];
questions?: ChatQuestion[];
/** Answered through the approvals API: approve or deny, nothing session-wide. */
via?: "approvals";
}
/** One question of a questionnaire ask. */
interface ChatQuestion {
name: string;
title: string;
description?: string;
multiple?: boolean;
required?: boolean;
allow_other?: boolean;
choices?: { value: string; label: string; description?: string }[];
}
/** Everything the selectors on the panel read, from one sessions read. */
export interface ChatSelectorData {
providers?: string[];
models?: string[];
models_by_provider?: Record<string, string[]>;
active_provider?: string;
active_model?: string;
commands?: Array<ChatCommandSpec | string>;
voice_available?: boolean;
/** Why no model can answer, when none can. */
model_error?: string;
}
/**
* One `data: {...}` frame of the chat stream. The server always emits `text`,
* empty or not: the browser concatenates it, so a missing key would put the
* string "undefined" into the transcript on a turn whose reply is empty.
*/
interface ChatStreamFrame extends ChatToolCall {
seq?: number;
type?: string;
text: 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. */
const STREAM_TIMEOUT_MS = 120000;
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.
* Resolves true only when the answer was accepted: the question is cleared
* 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, ask = streamingTurn.value?.ask): Promise<boolean> {
if (!ask) return false;
try {
if (ask.via !== "approvals") throw new Error(errors.chat.ask.unsupported);
await 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?.();
return true;
}
export const sessions = ref<ChatSession[]>([]);
export const currentSession = ref("");
export const messages = ref<ChatMessage[]>([]);
const drafts = ref<Record<string, string>>({});
/** Whether the chat dock shows the conversation; the dock, Ctrl+/ and the topbar button share it. */
export const dockExpanded = ref(false);
/** A suggested prompt the pointer or focus rests on, previewed as the composer placeholder. */
export const placeholderHint = ref("");
/** The unsent text of the open conversation; each conversation keeps its own. */
export const composerText = computed({
get: () => drafts.value[currentSession.value] ?? "",
set: (value: string) => {
drafts.value = { ...drafts.value, [currentSession.value]: value };
},
});
const tagDrafts = ref<Record<string, TaskRef[]>>({});
/** The tasks attached to the unsent message; each conversation keeps its own. */
export const taskTags = computed(() => tagDrafts.value[currentSession.value] ?? []);
export function addTaskTag(task: TaskRef): void {
if (taskTags.value.some((tag) => tag.id === task.id)) return;
tagDrafts.value = { ...tagDrafts.value, [currentSession.value]: [...taskTags.value, task] };
}
export function removeTaskTag(id: TaskRef["id"]): void {
tagDrafts.value = {
...tagDrafts.value,
[currentSession.value]: taskTags.value.filter((tag) => tag.id !== id),
};
}
function clearDraft(): void {
composerText.value = "";
removeAllTags();
}
function removeAllTags(): void {
tagDrafts.value = { ...tagDrafts.value, [currentSession.value]: [] };
}
/** The message as sent: the typed text, then the tasks it is about. */
function withTaskContext(text: string): string {
if (!taskTags.value.length) return text;
const refs = taskTags.value
.map((task) => `#${task.id}${task.title ? ` ${task.title}` : ""}`)
.join("; ");
return `${text}\n\nContext, tasks: ${refs}`;
}
export const statusText = ref("Ready");
export const isSending = ref(false);
export const isLoadingSession = ref(false);
// A failed conversation load: shown in the transcript itself, with a Retry,
// rather than in the settings popover where statusText renders.
export const sessionError = ref("");
export const streamingTurn = ref<StreamingTurn | null>(null);
export const selectorData = ref<ChatSelectorData>({});
export const selectedModel = ref("");
/** Whether a chat model is configured, so a prompt sent now can be answered. */
export const chatModelReady = computed(() => !!selectorData.value.active_model);
export const commandSpecs = ref<ChatCommandSpec[]>([]);
/**
* How many layers inside the panel currently own Escape -- an open popover, a
* select inside one.
*
* The panel's own Escape defers to them. Dismissing a menu must not also throw
* away the conversation the menu was opened over, and a layer that dismissed
* both would make the panel impossible to keep open while consulting it.
*/
const openLayers = ref(0);
/** Registers a toggleable layer inside the panel, for as long as it is mounted. */
export function useEscapeLayer(open: Ref<boolean>): void {
watch(open, (isOpen) => {
openLayers.value += isOpen ? 1 : -1;
});
onUnmounted(() => {
if (open.value) openLayers.value -= 1;
});
}
export function escapeOwnedByLayer(): boolean {
return openLayers.value > 0;
}
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.
let sessionEpoch = 0;
// The send path holds a stream loop that outlives the click that started it; a
// module-level controller is what a Stop, or an unmount, aborts.
function abortActiveTurn(): void {
activeController?.abort();
}
async function refreshSessions(): Promise<void> {
const data: ChatSelectorData & { sessions?: ChatSession[] } = await api.chatSessions();
const sessionList = data.sessions || [];
sessions.value = sessionList;
selectorData.value = data;
selectedModel.value = data.active_model || "";
commandSpecs.value = (data.commands || []).map((item) =>
typeof item === "string"
? { command: item, usage: item, description: "" }
: item,
);
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<string> {
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;
}
/**
* 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 readTurn(
turnID: string,
signal: AbortSignal | undefined,
onFrame: (frame: ChatStreamFrame) => void,
onBytes: () => void = () => {},
): Promise<ChatStreamFrame> {
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 = "";
// 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() || "";
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;
onFrame(event);
if (event.type === "done" || event.type === "error" || event.type === "cancelled") {
await reader.cancel().catch(() => {});
return event;
}
}
if (done) throw new Error(errors.chat.stream.endedEarly);
}
}
/**
* 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<void> {
if (!id) return;
// Switching conversation detaches the running turn: abort its stream and
// bump the epoch so its late writes land nowhere.
sessionEpoch++;
abortActiveTurn();
currentSession.value = id;
startedFresh = false;
messages.value = [];
streamingTurn.value = null;
queuedMessages.value = [];
isLoadingSession.value = true;
sessionError.value = "";
askError.value = "";
try {
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);
} finally {
if (isCurrentSession(id)) isLoadingSession.value = false;
}
}
/** 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),
]);
}
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<void> {
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);
}
}
/** Deletes the open conversation and opens the next one. */
export async function deleteSession(): Promise<void> {
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));
});
}
/**
* Re-reads the open conversation, so a message the server added (a finished
* task's outcome) appears. A turn in flight owns the transcript, so a reload
* waits for the next one.
*/
export async function reloadTranscript(): Promise<void> {
const id = currentSession.value;
// A stopped turn is terminal, not in flight: it must not block reloads.
const stopped = streamingTurn.value?.text === "Turn stopped.";
if (!id || (streamingTurn.value && !stopped)) return;
try {
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;
}
} catch {
// The next outcome or reopening the conversation reads it again.
}
}
// A later selection owns the loading flag: a slow read for an earlier one must
// not clear it.
function isCurrentSession(id: string): boolean {
return currentSession.value === id;
}
export async function runSessionCommand(command: string): Promise<void> {
if (!currentSession.value) return;
try {
statusText.value = "Working…";
const result = await sendCommand(command);
if (result.session_id) currentSession.value = result.session_id;
statusText.value = result.reply || "Session updated";
await refreshSessions();
if (result.session_id || currentSession.value) {
await selectSession(result.session_id || currentSession.value);
}
} catch (err) {
statusText.value = describeError(err, errors.chat.session.command);
}
}
// Rename and branch take a value the server has no form for; the caller opens
// a labelled Dialog for it (see ChatSessionActions).
export async function setModel(model: string): Promise<void> {
if (!model) return;
const previous = selectedModel.value;
try {
const result = await sendCommand(`/model ${model}`);
selectedModel.value = model;
statusText.value = result.reply || "Model updated";
await refreshSessions();
} catch (err) {
// The selector keeps the model the server still has, and the failure is
// shown in the transcript, not only in status text.
selectedModel.value = previous;
sessionError.value = errors.chat.session.model(describeError(err, errors.common.unknown));
}
}
/** What a page that edits something Archie can change runs around a turn: save first, reload after. */
let turnHooks: { before?: () => Promise<void>; after?: () => void } = {};
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 {
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. */
export const queuedMessages = ref<string[]>([]);
/** A voice clip recorded while a turn runs, sent when it ends. */
const queuedVoice = ref<{ data: string; mime_type: string } | null>(null);
// A turn that ended, stopped included, sends the next queued message. A failed
// one holds the queue so nothing overtakes its retry.
watch(isSending, (sending) => {
if (sending || streamingTurn.value?.isError) return;
if (queuedMessages.value.length) {
const [next, ...rest] = queuedMessages.value;
queuedMessages.value = rest;
void sendMessage({ textOverride: next });
return;
}
const voice = queuedVoice.value;
if (voice) {
queuedVoice.value = null;
void sendMessage({ textOverride: "🎤 Voice message", voice });
}
});
export function removeQueued(index: number): void {
queuedMessages.value = queuedMessages.value.filter((_, i) => i !== index);
}
/** Moves a queued message back into the composer, after anything already typed. */
export function editQueued(index: number): void {
const text = queuedMessages.value[index];
if (text === undefined) return;
removeQueued(index);
composerText.value = composerText.value.trim() ? `${composerText.value}\n${text}` : text;
}
/** The page the operator is on, without the hash the server never sees. */
function currentPage(): string {
return router.currentRoute.value.fullPath.split("#")[0] || "/";
}
// The page whose tag the operator removed. Navigating elsewhere shows the tag
// again, so the dismissal never outlives the page it was made on.
const clearedPage = ref("");
watch(currentPage, () => {
clearedPage.value = "";
});
/** What the next message is about, named for the tag above the composer. */
export const pageTag = computed(() => {
const page = currentPage();
if (page === clearedPage.value) return null;
const route = router.currentRoute.value;
const label =
route.name === "task-detail"
? `Task #${route.params.id}`
: route.name === "workflow"
? `Workflow ${route.params.id}`
: typeof route.meta.label === "string"
? route.meta.label
: page;
return { page, label };
});
export function clearPageTag(): void {
clearedPage.value = currentPage();
}
/** The page sent with a message: the tag's page, or none once it is cleared. */
function sentPage(): string | undefined {
return pageTag.value?.page;
}
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
// The conversation this turn belongs to; a switch bumps sessionEpoch and
// detaches the turn, so its writes stop landing.
const epoch = sessionEpoch;
const explicitText = retryOpts?.textOverride;
const typed = explicitText !== undefined ? explicitText : composerText.value;
const rawValue =
explicitText === undefined && !retryOpts?.turn && typed.trim()
? withTaskContext(typed.trim())
: typed;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue);
if (!text) return;
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;
if (retryOpts?.voice) {
queuedVoice.value = retryOpts.voice;
return;
}
queuedMessages.value = [...queuedMessages.value, text];
if (explicitText === undefined) clearDraft();
return;
}
isSending.value = true;
statusText.value = isRetry ? "Retrying…" : "Thinking…";
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 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";
return;
}
// /update answers here, where the panel can offer Install like Telegram does.
if (!isRetry && !follow && text.trim() === "/update" && hasCommand("/update")) {
try {
const update = await api.updateSnapshot<ChatUpdate>();
messages.value = [...messages.value, { from: "assistant", text: "", update }];
statusText.value = "Ready";
} catch (err) {
messages.value = [
...messages.value,
{ from: "assistant", text: errors.chat.update.check(describeError(err, errors.common.unknown)) },
];
statusText.value = "Ready";
} finally {
isSending.value = false;
}
return;
}
let activeTools: ChatToolCall[] = [];
let approvals: ChatAsk[] = [];
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry, reasoning: "" };
askError.value = "";
let streamedText = "";
let streamedReasoning = "";
let timedOut = false;
let detached = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | null = null;
try {
const ctrl = new AbortController();
controller = ctrl;
activeController = ctrl;
activeTurnID = follow ?? "";
const arm = () => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timedOut = true;
ctrl.abort();
}, STREAM_TIMEOUT_MS);
};
arm();
// The clock stops while a question waits on the operator.
rearmTimeout = arm;
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");
}
}
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
? { ...streamingTurn.value, text: streamedText }
: null;
}
// The model's thinking streams ahead of the answer on its own frame
// kind; it accumulates like the text, but renders as the live turn's
// thinking trace rather than as reply text.
if (event.type === "reasoning") {
streamedReasoning += event.text;
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, reasoning: streamedReasoning }
: null;
}
// A navigate result is appended to the same list as the tool calls: it
// 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") {
const at = event.type === "navigate" ? { text_offset: Array.from(streamedText).length } : {};
activeTools = [...activeTools, { ...event, ...at }];
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, tools: activeTools }
: null;
}
// 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, approvals }
: null;
}
},
() => {
// 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
// carrying the old one with a confirmation under it.
messages.value =
!isRetry && text.trim() === "/new"
? []
: [
...messages.value,
{ from: "assistant", text: streamedText, tool_calls: activeTools, approvals },
];
streamingTurn.value = null;
}
statusText.value = "Ready";
// The turn succeeded; a failed session-list refresh is reported on its
// own and must not turn into a "retry this turn" error.
await refreshSessions().catch((err) => {
sessionError.value = errors.chat.session.refreshList(describeError(err, errors.common.unknown));
});
} catch (err) {
// A detached turn (conversation switched mid-turn) writes nothing.
if (epoch !== sessionEpoch) {
detached = true;
return;
}
const failed = err as Error;
// What already streamed is kept; the stop or failure note follows it.
if (streamedText) {
messages.value = [
...messages.value,
{ from: "assistant", text: streamedText, tool_calls: activeTools, approvals },
];
activeTools = [];
}
if (failed.name === "AbortError" && !timedOut) {
streamingTurn.value = {
text: "Turn stopped.",
tools: activeTools,
isError: false,
turn,
isRetry,
reasoning: streamedReasoning,
};
statusText.value = "Stopped";
} else {
streamingTurn.value = {
text: timedOut
? errors.chat.stream.timedOut(`${STREAM_TIMEOUT_MS / 60000} minutes${lastStep(activeTools)}`)
: failed instanceof TypeError
? errors.common.network
: describeError(failed, errors.chat.turn.failed),
tools: activeTools,
isError: true,
turn: turn ? retryChatTurn(turn) : undefined,
isRetry,
reasoning: streamedReasoning,
};
statusText.value = errors.chat.turn.failedStatus;
}
} finally {
clearTimeout(timeoutId);
rearmTimeout = null;
// Only the turn that still owns the controller clears the sending flag: a
// detached turn must not unlock the composer for a turn already running in
// the conversation now open.
if (controller && activeController === controller) {
activeController = null;
activeTurnID = "";
isSending.value = false;
if (detached) statusText.value = "Ready";
}
turnHooks.after?.();
}
}
function lastStep(tools: ChatToolCall[]): string {
const last = tools.filter((tool) => tool.name || tool.tool).at(-1);
return last ? `, last step: ${last.name || last.tool}` : "";
}
export function stopTurn(): void {
statusText.value = "Stopping…";
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;
}
void api.chatCancelTurn(id).catch((err) => {
sessionError.value = errors.chat.turn.stop(describeError(err, errors.common.unknown));
abortActiveTurn();
});
}
/**
* Owns the first sessions read and the teardown of an in-flight turn for the
* panel's lifetime. The panel is mounted once beside the outlet and stays
* mounted while it is closed, so opening it is a prop change rather than a
* mount and the conversation survives a navigation.
*/
export function useChat(): void {
onMounted(() => {
refreshSessions().catch((err: Error) => {
statusText.value = describeError(err, errors.chat.session.unavailable);
});
});
onUnmounted(() => {
abortActiveTurn();
});
}
/** sendVoice sends a recorded clip as a turn; the server transcribes it. */
export async function sendVoice(clip: Blob): Promise<void> {
const bytes = new Uint8Array(await clip.arrayBuffer());
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
await sendMessage({
textOverride: "🎤 Voice message",
voice: { data: btoa(binary), mime_type: clip.type || "audio/webm" },
});
}