Files
archie/ui/src/chat/state.ts
T
sam 074ebbd931
deploy / plan (push) Failing after 1s
deploy / gate (push) Skipped
deploy / archied-image (push) Skipped
deploy / agent-image (push) Skipped
deploy / dist-zip (push) Skipped
fix(chat): keep long turns alive, record and log why a turn failed (#1813)
2026-11-08 23:03:04 +11:00

790 lines
26 KiB
TypeScript

import { onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { randomUUID } from "@/lib/uuid";
import { channelID } from "./channel";
import { matchesFor } from "./commands";
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 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";
}
/** 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;
/** A question the turn waits on until the operator answers it. */
ask?: 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[];
}
/** One question of a questionnaire ask. */
export 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;
}
/**
* 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 {
type?: string;
text: string;
session_id?: string;
ask?: ChatAsk;
}
/** 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("");
/**
* 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): Promise<boolean> {
const ask = streamingTurn.value?.ask;
if (!ask) return false;
try {
await api.chatAnswer(ask.id, answer);
} catch (err) {
askError.value = (err as Error).message || "Could not send the answer";
return false;
}
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[]>([]);
export const composerText = ref("");
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("");
export const commandSpecs = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<ChatCommandSpec[]>([]);
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
/**
* 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;
// 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();
}
export async function refreshSessions(): Promise<void> {
const data = await api.chatSessions<
ChatSelectorData & { sessions?: ChatSession[] }
>();
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]) {
// 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);
}
}
/**
* 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.
*/
async function sendCommand(
text: string,
): Promise<{ reply: string; session_id: string }> {
const response = await api.chatStream({
channel_id: channelID(),
source_id: randomUUID(),
text,
page: currentPage(),
});
if (!response.body) throw new Error("the chat stream returned no body");
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let reply = "";
let session = "";
let finished = false;
for (;;) {
const { value, done } = await reader.read();
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) 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 || "";
}
}
if (done) break;
}
if (!finished) throw new Error("chat stream ended before completion");
return { reply, 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;
messages.value = [];
streamingTurn.value = null;
queuedMessages.value = [];
isLoadingSession.value = true;
sessionError.value = "";
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;
} catch (err) {
if (isCurrentSession(id))
sessionError.value =
(err as Error).message || "Could not load session messages";
} finally {
if (isCurrentSession(id)) isLoadingSession.value = false;
}
}
// 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<ChatMessage[]> {
const [msgs, turns] = await Promise.all([
api.chatMessages<ChatMessage[]>(id),
api.chatTurns<ChatTurnView[]>(id),
]);
const byAssistantMessage = new Map<string, ChatTurnView>();
for (const turn of turns || []) {
const assistantID = turn.assistant_message_id || turn.AssistantMessageID;
if (assistantID) byAssistantMessage.set(assistantID, turn);
}
return (msgs || []).map((message) => {
const messageID = message.message_id || message.MessageID;
const turn = messageID ? byAssistantMessage.get(messageID) : undefined;
return turn
? { ...message, tool_calls: turn.tool_calls || turn.ToolCalls || [] }
: message;
});
}
/**
* 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 = await readTranscript(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;
}
/** One recorded turn, as GET /api/chat/sessions/{id}/turns returns it. */
interface ChatTurnView {
assistant_message_id?: string;
AssistantMessageID?: string;
tool_calls?: ChatToolCall[];
ToolCalls?: ChatToolCall[];
}
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 = (err as Error).message || "Session action failed";
}
}
// 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 = `Model update failed: ${(err as Error).message || err}`;
}
}
/** 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;
}
export function newChat(): void {
void sendMessage({ textOverride: "/new" });
}
/** 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. */
export 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;
}
/** Opens the palette for the slash word the caret sits in, or closes it. */
export function syncCommandMenu(value: string, caret: number): void {
const matches = matchesFor(commandSpecs.value, value, caret);
if (matches.length) {
commandMatches.value = matches;
commandSelection.value = 0;
isCommandMenuOpen.value = true;
return;
}
isCommandMenuOpen.value = false;
commandMatches.value = [];
}
export function closeCommandMenu(): void {
isCommandMenuOpen.value = false;
}
export function moveCommandSelection(delta: number): void {
const length = commandMatches.value.length;
if (!length) return;
commandSelection.value = (commandSelection.value + delta + length) % length;
}
/** The page the operator asked from, so an answer can be about what they saw. */
function currentPage(): string {
return location.pathname + location.search || "/";
}
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 rawValue =
explicitText !== undefined ? explicitText : composerText.value;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue);
if (!text) return;
if (isSending.value) {
// 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) composerText.value = "";
closeCommandMenu();
return;
}
closeCommandMenu();
isSending.value = true;
statusText.value = isRetry ? "Retrying…" : "Thinking…";
if (!isRetry) {
messages.value = [...messages.value, { from: "web", text }];
// A queued or command send must not clear what is being typed.
if (explicitText === undefined) composerText.value = "";
}
// 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") {
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 && text.trim() === "/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: `Could not check for updates: ${(err as Error).message}` },
];
statusText.value = "Ready";
} finally {
isSending.value = false;
}
return;
}
let activeTools: ChatToolCall[] = [];
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry };
askError.value = "";
let streamedText = "";
let finished = false;
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;
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;
await turnHooks.before?.();
const response = await api.chatStream(
{
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
voice: turn.voice,
},
{ signal: ctrl.signal },
);
const body = response.body;
if (!body) throw new Error("the chat stream returned no body");
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;
}
// 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;
if (event.type === "delta") {
streamedText += event.text;
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, text: streamedText }
: 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") {
activeTools = [...activeTools, event];
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, tools: activeTools }
: null;
}
if (event.type === "ask" && event.ask) {
clearTimeout(timeoutId);
askError.value = "";
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, ask: event.ask }
: 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("chat stream ended before completion");
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 },
];
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 = `Could not refresh the session list: ${(err as Error).message || err}`;
});
} 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 },
];
activeTools = [];
}
if (failed.name === "AbortError" && !timedOut) {
streamingTurn.value = {
text: "Turn stopped.",
tools: activeTools,
isError: false,
turn,
isRetry,
};
statusText.value = "Stopped";
} else {
streamingTurn.value = {
text: `Unable to complete that turn: ${
timedOut
? `no activity for ${STREAM_TIMEOUT_MS / 60000} minutes${lastStep(activeTools)}`
: failed.message || failed
}`,
tools: activeTools,
isError: true,
turn: turn ? retryChatTurn(turn) : undefined,
isRetry,
};
statusText.value = "Error. Retry available.";
}
} 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;
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…";
if (currentSession.value) {
void api.chatCancel(currentSession.value).catch((err) => {
sessionError.value = `Could not stop the turn: ${(err as Error).message || err}`;
});
}
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 = err.message || "Chat 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" },
});
}