Skip to content

Self-improving AI Employees for everyone

feat(chat): follow chat runs on the client

trohitg8428695091af
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 0eb9bf4e..8c000da3 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -34,6 +34,7 @@ import { startWebSocketHeartbeat } from '../lib/webSocketHeartbeat';
import { todoQueryKeyFromEvent } from '../lib/todoQuery';
import { AGENT_PHASE } from '../lib/agentPhases';
import { useCanvasDockStore } from '../stores/canvasDockStore';
+import { useChatRunStore } from '../stores/chatRunStore';
// Cycle note: lib/nodeSpec imports useWebSocketActions from this module. Safe in
// both evaluation orders because neither side calls the other's binding at
// module top level — `executionBudgetFor` only references it inside a body.
@@ -1220,6 +1221,13 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
break;
}
+ case 'chat_run_event': {
+ // A chat run's event (services/chat/hub.py), sent only to sockets
+ // that subscribed to its session. The store checks and orders it.
+ useChatRunStore.getState().receive(data);
+ break;
+ }
+
case 'canvas_updated': {
// CloudEvents-typed Canvas board change from
// server/nodes/tool/canvas/_events.py. Identity + revision only —
diff --git a/client/src/features/chat/__tests__/composerStore.test.ts b/client/src/features/chat/__tests__/composerStore.test.ts
new file mode 100644
index 00000000..5dd122e2
--- /dev/null
+++ b/client/src/features/chat/__tests__/composerStore.test.ts
@@ -0,0 +1,58 @@
+/**
+ * What the owner is writing, per conversation: switching away and back keeps
+ * it, sending takes it out of the box, and a send that did not go puts it
+ * back, keeping its id only when it may have reached the server (so sending
+ * it again is the same message).
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { useComposerStore } from '../state/composerStore';
+
+const store = () => useComposerStore.getState();
+
+beforeEach(() => useComposerStore.setState({ drafts: {} }));
+
+describe('composerStore', () => {
+ it('keeps a draft per conversation', () => {
+ store().setText('w1', 'For Maya');
+ store().setText('w2', 'For Leo');
+ expect(store().drafts.w1.text).toBe('For Maya');
+ expect(store().drafts.w2.text).toBe('For Leo');
+ });
+
+ it('takes the draft out of the box with a new id', () => {
+ store().setText('w1', 'Hello');
+ const taken = store().takeForSend('w1');
+ expect(taken.text).toBe('Hello');
+ expect(taken.clientMessageId).toEqual(expect.any(String));
+ expect(store().drafts.w1).toEqual({ text: '', clientMessageId: null });
+ });
+
+ it('puts back a refused send with a fresh id, and one lost in transit with its own', () => {
+ store().setText('w1', 'Hello');
+ const refused = store().takeForSend('w1');
+ store().restore('w1', refused, false);
+ expect(store().drafts.w1).toEqual({ text: 'Hello', clientMessageId: null });
+
+ const lost = store().takeForSend('w1');
+ store().restore('w1', lost, true);
+ expect(store().drafts.w1.clientMessageId).toBe(lost.clientMessageId);
+ expect(store().takeForSend('w1').clientMessageId).toBe(lost.clientMessageId);
+ });
+
+ it('never overwrites what the owner started writing meanwhile', () => {
+ store().setText('w1', 'Hello');
+ const taken = store().takeForSend('w1');
+ store().setText('w1', 'Something else');
+ store().restore('w1', taken, true);
+ expect(store().drafts.w1).toEqual({ text: 'Something else', clientMessageId: null });
+ });
+
+ it('forgets the id once the text changes', () => {
+ store().setText('w1', 'Hello');
+ const lost = store().takeForSend('w1');
+ store().restore('w1', lost, true);
+ store().setText('w1', 'Hello!');
+ expect(store().drafts.w1.clientMessageId).toBeNull();
+ });
+});
diff --git a/client/src/features/chat/data/runs.ts b/client/src/features/chat/data/runs.ts
new file mode 100644
index 00000000..e1d3e850
--- /dev/null
+++ b/client/src/features/chat/data/runs.ts
@@ -0,0 +1,147 @@
+/**
+ * Following a chat session's runs.
+ *
+ * `useChatRunSubscription(sessionId)` subscribes the socket to the session
+ * (`chat_subscribe`) whenever it is ready, so after every reconnect, and
+ * again whenever the run store asks for a fresh snapshot (a gap, a new
+ * server process, the hub's resync). Runs that ended while nobody watched
+ * are read once more (`get_chat_run`). The last component following a
+ * session unsubscribes it. A failed subscribe is retried with a growing
+ * delay.
+ *
+ * `useSessionRuns` / `useLaneRun` / `useRunsSubscribed` read the run store
+ * (stores/chatRunStore.ts). `useThreadRunReconcile` reads the runs a thread
+ * still calls live that ended before the subscription answered.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { isLiveRun, snapshotFromWire, type RunSnapshot } from '@/lib/agui/reduceRun';
+import { useChatRunStore } from '@/stores/chatRunStore';
+import type { ChatMessage } from './schemas';
+
+/** Delays before retrying a failed subscribe; the last one repeats. */
+const RETRY_DELAYS_MS = [1_000, 3_000, 10_000];
+
+const EMPTY_RUNS: Record<string, RunSnapshot> = Object.freeze({}) as Record<string, RunSnapshot>;
+
+/** How many mounted components follow each session. */
+const following = new Map<string, number>();
+
+type Reply = { success?: boolean; hub_epoch?: unknown; active_runs?: unknown; run?: unknown };
+
+export function useChatRunSubscription(sessionId: string | null): void {
+ const { sendRequest, isReady } = useWebSocketActions();
+ const resync = useChatRunStore((state) => (sessionId ? state.sessions[sessionId]?.resync ?? 0 : 0));
+ const [attempt, setAttempt] = useState(0);
+
+ useEffect(() => {
+ if (!sessionId) return;
+ following.set(sessionId, (following.get(sessionId) ?? 0) + 1);
+ return () => {
+ const left = (following.get(sessionId) ?? 1) - 1;
+ if (left > 0) {
+ following.set(sessionId, left);
+ return;
+ }
+ following.delete(sessionId);
+ sendRequest('chat_unsubscribe', { session_id: sessionId }).catch(() => undefined);
+ };
+ }, [sessionId, sendRequest]);
+
+ useEffect(() => {
+ if (!sessionId || !isReady) return;
+ let current = true;
+ let retry: ReturnType<typeof setTimeout> | undefined;
+ const failed = () => {
+ if (!current) return;
+ const delay = RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)];
+ retry = setTimeout(() => setAttempt((n) => n + 1), delay);
+ };
+ void (async () => {
+ try {
+ const reply = await sendRequest<Reply>('chat_subscribe', { session_id: sessionId });
+ if (!current) return;
+ if (reply?.success === false || typeof reply?.hub_epoch !== 'string') {
+ failed();
+ return;
+ }
+ const snapshots = Array.isArray(reply.active_runs)
+ ? reply.active_runs.flatMap((raw) => {
+ const run = snapshotFromWire(raw);
+ return run ? [run] : [];
+ })
+ : [];
+ const store = useChatRunStore.getState();
+ store.applySubscription(sessionId, reply.hub_epoch, snapshots);
+ for (const runId of useChatRunStore.getState().sessions[sessionId]?.stale ?? []) {
+ const one = await sendRequest<Reply>('get_chat_run', { run_id: runId });
+ const run = one?.success === false ? null : snapshotFromWire(one?.run);
+ if (current && run) useChatRunStore.getState().upsertRun(run);
+ }
+ } catch {
+ failed();
+ }
+ })();
+ return () => {
+ current = false;
+ if (retry !== undefined) clearTimeout(retry);
+ };
+ }, [sessionId, isReady, resync, attempt, sendRequest]);
+}
+
+/** A session's runs by id (live and recently ended). */
+export function useSessionRuns(sessionId: string | null): Record<string, RunSnapshot> {
+ return useChatRunStore((state) => (sessionId ? state.sessions[sessionId]?.runs ?? EMPTY_RUNS : EMPTY_RUNS));
+}
+
+/** The run holding the session's lane: the live run the owner's last
+ * message started (approved sends running as `resume` runs never hold it). */
+export function laneRun(runs: Record<string, RunSnapshot>): RunSnapshot | null {
+ let lane: RunSnapshot | null = null;
+ for (const run of Object.values(runs)) {
+ if (!isLiveRun(run) || run.kind === 'resume') continue;
+ if (!lane || (run.createdAt ?? run.startedAt ?? '') > (lane.createdAt ?? lane.startedAt ?? '')) lane = run;
+ }
+ return lane;
+}
+
+export function useLaneRun(sessionId: string | null): RunSnapshot | null {
+ const runs = useSessionRuns(sessionId);
+ return useMemo(() => laneRun(runs), [runs]);
+}
+
+/** Whether the session's subscription has answered (its runs are known). */
+export function useRunsSubscribed(sessionId: string | null): boolean {
+ return useChatRunStore((state) => (sessionId ? state.sessions[sessionId]?.subscribed ?? false : false));
+}
+
+/**
+ * Once the subscription has answered, a run the thread read as live but the
+ * store does not hold ended in between: read it once, so the thread shows
+ * how it ended (a failure keeps its line) instead of guessing.
+ */
+export function useThreadRunReconcile(sessionId: string | null, messages: readonly ChatMessage[] | undefined): void {
+ const { sendRequest } = useWebSocketActions();
+ const subscribed = useRunsSubscribed(sessionId);
+ const runs = useSessionRuns(sessionId);
+ const asked = useRef(new Set<string>());
+
+ useEffect(() => {
+ if (!sessionId || !subscribed || !messages) return;
+ for (const message of messages) {
+ const run = message.run;
+ if (!run || !isLiveRun(run) || runs[run.runId] || asked.current.has(run.runId)) continue;
+ asked.current.add(run.runId);
+ sendRequest<Reply>('get_chat_run', { run_id: run.runId })
+ .then((one) => {
+ const snapshot = one?.success === false ? null : snapshotFromWire(one?.run);
+ if (snapshot) useChatRunStore.getState().upsertRun(snapshot);
+ })
+ .catch(() => {
+ // The next thread read says how it ended.
+ asked.current.delete(run.runId);
+ });
+ }
+ }, [sessionId, subscribed, messages, runs, sendRequest]);
+}
diff --git a/client/src/features/chat/data/schemas.ts b/client/src/features/chat/data/schemas.ts
new file mode 100644
index 00000000..cb43031f
--- /dev/null
+++ b/client/src/features/chat/data/schemas.ts
@@ -0,0 +1,117 @@
+/**
+ * A chat thread as `get_chat_messages` sends it (docs-internal/chat_protocol.md,
+ * "Messages"), read into camelCase. Every field is read forgivingly: a reply
+ * from a server that predates a field still parses, and a row this client
+ * cannot show is dropped rather than failing the thread.
+ */
+
+import { z } from 'zod';
+import type { RunError, RunState } from '@/lib/agui/events';
+import { parseError } from '@/lib/agui/events';
+import { snapshotFromWire, type RunSnapshot } from '@/lib/agui/reduceRun';
+
+const RUN_STATES = ['queued', 'pending', 'running', 'stopping', 'finished', 'error', 'stopped'] as const;
+
+/** How the run a message started or answers ended (or is going). */
+export interface MessageRun {
+ runId: string;
+ state: RunState;
+ outcome: string | null;
+ error: RunError | null;
+}
+
+const messageRunSchema = z
+ .object({
+ run_id: z.string(),
+ state: z.enum(RUN_STATES).catch('finished'),
+ outcome: z.string().nullable().catch(null),
+ error: z.record(z.string(), z.unknown()).nullable().catch(null),
+ })
+ .transform(
+ (run): MessageRun => ({
+ runId: run.run_id,
+ state: run.state,
+ outcome: run.outcome,
+ error: run.error ? parseError(run.error) : null,
+ }),
+ );
+
+const messageSchema = z
+ .object({
+ id: z.union([z.number(), z.string()]).transform(String),
+ legacy_id: z.number().nullable().catch(null),
+ role: z.enum(['user', 'assistant']),
+ kind: z.string().catch('text'),
+ text: z.string().optional(),
+ message: z.string().catch(''),
+ timestamp: z.string().nullable().catch(null),
+ run_key: z.string().nullable().catch(null),
+ run_id: z.string().nullable().catch(null),
+ parent_id: z.string().nullable().catch(null),
+ status: z.string().catch('complete'),
+ attachments: z.array(z.unknown()).catch([]),
+ parts: z.record(z.string(), z.unknown()).catch({}),
+ client_message_id: z.string().nullable().catch(null),
+ run: messageRunSchema.nullable().catch(null),
+ })
+ .transform((row) => ({
+ id: row.id,
+ legacyId: row.legacy_id,
+ role: row.role,
+ kind: row.kind,
+ text: row.text ?? row.message,
+ timestamp: row.timestamp,
+ runKey: row.run_key,
+ runId: row.run_id,
+ parentId: row.parent_id,
+ status: row.status,
+ attachments: row.attachments,
+ parts: row.parts,
+ clientMessageId: row.client_message_id,
+ run: row.run,
+ }));
+
+export type ChatMessage = z.output<typeof messageSchema> & {
+ /** Sent from this tab and not confirmed by the server yet. */
+ pending?: boolean;
+};
+
+export interface ThreadState {
+ activeLeafId: string | null;
+ revision: number;
+}
+
+export interface ChatThreadData {
+ messages: ChatMessage[];
+ thread: ThreadState;
+ /** The session's live runs when the thread was read. */
+ activeRuns: RunSnapshot[];
+}
+
+/** The messages of a `get_chat_messages` reply, oldest first, dropping rows
+ * this client cannot show. */
+export function parseMessages(raw: unknown): ChatMessage[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((item) => {
+ const parsed = messageSchema.safeParse(item);
+ return parsed.success ? [parsed.data] : [];
+ });
+}
+
+const threadStateSchema = z
+ .object({
+ active_leaf_id: z.string().nullable().catch(null),
+ revision: z.number().catch(0),
+ })
+ .transform((thread): ThreadState => ({ activeLeafId: thread.active_leaf_id, revision: thread.revision }))
+ .catch({ activeLeafId: null, revision: 0 });
+
+export function parseThreadReply(reply: { messages?: unknown; thread?: unknown; active_runs?: unknown }): ChatThreadData {
+ const activeRuns = Array.isArray(reply.active_runs)
+ ? reply.active_runs.flatMap((raw) => {
+ const run = snapshotFromWire(raw);
+ return run ? [run] : [];
+ })
+ : [];
+ return { messages: parseMessages(reply.messages), thread: threadStateSchema.parse(reply.thread ?? {}), activeRuns };
+}
diff --git a/client/src/features/chat/data/send.ts b/client/src/features/chat/data/send.ts
new file mode 100644
index 00000000..5616d2e0
--- /dev/null
+++ b/client/src/features/chat/data/send.ts
@@ -0,0 +1,151 @@
+/**
+ * Sending the owner's message (`send_chat_message`) and clearing a
+ * conversation (`clear_chat_messages`), for every host.
+ *
+ * A message shows in the thread at once, marked pending, and becomes the
+ * saved row once the server answers (the refetch finds it by its
+ * `client_message_id`). The run it started is registered in the run store
+ * straight away, so the thread shows the employee working before the run's
+ * first event arrives. A refusal (`run_in_progress`, `not_running`,
+ * `save_failed`, ...) or a failure in transit takes the message back out
+ * and puts its text back in the box (composerStore `restore`, so a retry
+ * after a failure in transit is the same message); `onRefused` decides what
+ * to tell the owner (`ChatSendError`). Both run at the hook level, so they
+ * still happen when the owner has moved to another conversation meanwhile.
+ */
+
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { queryKeys } from '@/lib/queryConfig';
+import { useChatRunStore } from '@/stores/chatRunStore';
+import { useComposerStore, type TakenDraft } from '../state/composerStore';
+import type { ChatMessage, ChatThreadData } from './schemas';
+import { chatThreadKey, type ThreadScope } from './thread';
+
+export type Delivery = 'now' | 'queued';
+
+export interface SendResult {
+ messageId: string;
+ runId: string | null;
+ /** Null for the editor's chat with no workflow open. */
+ delivery: Delivery | null;
+}
+
+/** A send that did not go through. `transport`: it may or may not have
+ * reached the server, so a retry should reuse the same `client_message_id`. */
+export class ChatSendError extends Error {
+ readonly code: string;
+ readonly runId: string | null;
+ readonly transport: boolean;
+
+ constructor(code: string, { runId = null, transport = false }: { runId?: string | null; transport?: boolean } = {}) {
+ super(code);
+ this.name = 'ChatSendError';
+ this.code = code;
+ this.runId = runId;
+ this.transport = transport;
+ }
+}
+
+type SendReply = {
+ success?: boolean;
+ error?: string;
+ run_id?: string | null;
+ message_id?: string;
+ delivery?: string;
+};
+
+function localId(clientMessageId: string): string {
+ return `local:${clientMessageId}`;
+}
+
+export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefused?: (error: ChatSendError) => void) {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ const key = chatThreadKey(sessionId, scope);
+
+ const replace = (update: (messages: ChatMessage[]) => ChatMessage[]) =>
+ queryClient.setQueryData<ChatThreadData>(key, (data) => (data ? { ...data, messages: update(data.messages) } : data));
+
+ return useMutation<SendResult, ChatSendError, TakenDraft>({
+ mutationFn: async ({ text, clientMessageId }) => {
+ let reply: SendReply | undefined;
+ try {
+ reply = await sendRequest<SendReply>('send_chat_message', {
+ session_id: sessionId,
+ message: text,
+ role: 'user',
+ timestamp: new Date().toISOString(),
+ client_message_id: clientMessageId,
+ });
+ } catch {
+ throw new ChatSendError('transport', { transport: true });
+ }
+ if (reply?.success === false || !reply?.message_id) {
+ throw new ChatSendError(reply?.error || 'send_failed', { runId: reply?.run_id ?? null });
+ }
+ return {
+ messageId: reply.message_id,
+ runId: reply.run_id ?? null,
+ delivery: reply.delivery === 'queued' ? 'queued' : reply.delivery === 'now' ? 'now' : null,
+ };
+ },
+ onMutate: async ({ text, clientMessageId }) => {
+ await queryClient.cancelQueries({ queryKey: key });
+ const pending: ChatMessage = {
+ id: localId(clientMessageId),
+ legacyId: null,
+ role: 'user',
+ kind: 'text',
+ text,
+ timestamp: new Date().toISOString(),
+ runKey: null,
+ runId: null,
+ parentId: null,
+ status: 'complete',
+ attachments: [],
+ parts: {},
+ clientMessageId,
+ run: null,
+ pending: true,
+ };
+ replace((messages) => [...messages.filter((message) => message.id !== pending.id), pending]);
+ },
+ onSuccess: (result, { clientMessageId }) => {
+ replace((messages) =>
+ messages.map((message) =>
+ message.id === localId(clientMessageId)
+ ? { ...message, id: result.messageId, runId: result.runId, pending: false }
+ : message,
+ ),
+ );
+ if (result.runId) {
+ useChatRunStore.getState().admit(sessionId, {
+ runId: result.runId,
+ userMessageId: result.messageId,
+ state: result.delivery === 'queued' ? 'queued' : 'pending',
+ });
+ }
+ },
+ onError: (error, draft) => {
+ replace((messages) => messages.filter((message) => message.id !== localId(draft.clientMessageId)));
+ useComposerStore.getState().restore(sessionId, draft, error.transport);
+ onRefused?.(error);
+ },
+ // The refetch swaps the local copy for the saved row.
+ onSettled: () => queryClient.invalidateQueries({ queryKey: queryKeys.chatThread.bySession(sessionId).queryKey }),
+ });
+}
+
+/** "New conversation": clears the thread, and the employee's memory of it. */
+export function useClearChat(sessionId: string) {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ return useMutation<void, Error>({
+ mutationFn: async () => {
+ const reply = await sendRequest<{ success?: boolean; error?: string }>('clear_chat_messages', { session_id: sessionId });
+ if (reply?.success === false) throw new Error(reply.error || 'clear_failed');
+ },
+ onSettled: () => queryClient.invalidateQueries({ queryKey: queryKeys.chatThread.bySession(sessionId).queryKey }),
+ });
+}
diff --git a/client/src/features/chat/data/thread.ts b/client/src/features/chat/data/thread.ts
new file mode 100644
index 00000000..8a44a99a
--- /dev/null
+++ b/client/src/features/chat/data/thread.ts
@@ -0,0 +1,43 @@
+/**
+ * A chat session's thread (`get_chat_messages`), shared by every host.
+ *
+ * Scope `all` reads every generation (Home's employee page: a message from
+ * before a Start still shows); `live` reads the live generation only (the
+ * editor's chat pane). WebSocketContext invalidates the session's threads on
+ * `chat.updated`, after a runtime reset and when the socket reopens; a
+ * failed read is an error, never an empty thread.
+ */
+
+import { useQuery } from '@tanstack/react-query';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+import { STALE_TIME, queryKeys } from '@/lib/queryConfig';
+import { parseThreadReply, type ChatThreadData } from './schemas';
+
+export type ThreadScope = 'all' | 'live';
+
+/** The newest messages a thread shows. */
+export const THREAD_LIMIT = 200;
+
+export function chatThreadKey(sessionId: string, scope: ThreadScope) {
+ return [...queryKeys.chatThread.bySession(sessionId).queryKey, scope] as const;
+}
+
+export function useChatThread(sessionId: string | null, scope: ThreadScope) {
+ const { sendRequest, isReady } = useWebSocketActions();
+ return useQuery<ChatThreadData, Error>({
+ queryKey: chatThreadKey(sessionId ?? '', scope),
+ queryFn: async () => {
+ const reply = await sendRequest<{ success?: boolean; error?: string; messages?: unknown; thread?: unknown; active_runs?: unknown }>(
+ 'get_chat_messages',
+ { session_id: sessionId, limit: THREAD_LIMIT, all_generations: scope === 'all' },
+ );
+ if (reply?.success === false) throw new Error(reply.error || 'read_failed');
+ return parseThreadReply(reply ?? {});
+ },
+ enabled: isReady && Boolean(sessionId),
+ // Broadcasts keep it current. Opening a thread refetches only when one
+ // arrived while it was closed (it left the thread invalidated).
+ staleTime: STALE_TIME.FOREVER,
+ refetchOnMount: true,
+ });
+}
diff --git a/client/src/features/chat/state/composerStore.ts b/client/src/features/chat/state/composerStore.ts
new file mode 100644
index 00000000..cf85c1ed
--- /dev/null
+++ b/client/src/features/chat/state/composerStore.ts
@@ -0,0 +1,69 @@
+/**
+ * What the owner is writing, per chat session. It lives outside the chat's
+ * components, so switching to another employee and back keeps an unsent
+ * message.
+ *
+ * Sending takes the draft out of the box at once (`takeForSend`); a send that
+ * does not go through puts it back (`restore`), unless the owner has started
+ * another message meanwhile. A draft carries the `clientMessageId` that names
+ * its send: a send that failed in transit keeps it, so sending the same text
+ * again is the same message on the server (`send_chat_message` answers with
+ * the one it may already have saved). Editing the text forgets the id: it
+ * names that text, not the box.
+ */
+
+import { create } from 'zustand';
+
+export interface ComposerDraft {
+ text: string;
+ clientMessageId: string | null;
+}
+
+export type TakenDraft = ComposerDraft & { clientMessageId: string };
+
+interface ComposerState {
+ drafts: Record<string, ComposerDraft>;
+ setText: (sessionId: string, text: string) => void;
+ /** Empty the box and return what it held, with the id naming this send. */
+ takeForSend: (sessionId: string) => TakenDraft;
+ /** Put a draft that did not go through back, if the box is still empty.
+ * `keepId`: it failed in transit, so a retry is the same message. */
+ restore: (sessionId: string, draft: TakenDraft, keepId: boolean) => void;
+}
+
+const EMPTY: ComposerDraft = { text: '', clientMessageId: null };
+
+function newClientMessageId(): string {
+ return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
+ ? crypto.randomUUID()
+ : `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+export const useComposerStore = create<ComposerState>((set, get) => ({
+ drafts: {},
+
+ setText: (sessionId, text) =>
+ set((state) => {
+ const draft = state.drafts[sessionId] ?? EMPTY;
+ if (draft.text === text) return state;
+ return { drafts: { ...state.drafts, [sessionId]: { text, clientMessageId: null } } };
+ }),
+
+ takeForSend: (sessionId) => {
+ const draft = get().drafts[sessionId] ?? EMPTY;
+ const taken: TakenDraft = { text: draft.text, clientMessageId: draft.clientMessageId ?? newClientMessageId() };
+ set((state) => ({ drafts: { ...state.drafts, [sessionId]: EMPTY } }));
+ return taken;
+ },
+
+ restore: (sessionId, draft, keepId) =>
+ set((state) => {
+ if ((state.drafts[sessionId] ?? EMPTY).text.trim()) return state;
+ const restored: ComposerDraft = { text: draft.text, clientMessageId: keepId ? draft.clientMessageId : null };
+ return { drafts: { ...state.drafts, [sessionId]: restored } };
+ }),
+}));
+
+export function useComposerDraft(sessionId: string): ComposerDraft {
+ return useComposerStore((state) => state.drafts[sessionId] ?? EMPTY);
+}
diff --git a/client/src/lib/agui/__tests__/reduceRun.test.ts b/client/src/lib/agui/__tests__/reduceRun.test.ts
new file mode 100644
index 00000000..700ba86f
--- /dev/null
+++ b/client/src/lib/agui/__tests__/reduceRun.test.ts
@@ -0,0 +1,116 @@
+/**
+ * A chat run folded from its events: the handoff's Saturday booking run
+ * (steps, streamed text, a draft waiting for the owner, then the resume run
+ * that sent it), duplicates, and the snapshots the server sends.
+ */
+
+import { describe, expect, it } from 'vitest';
+import fixture from '@/features/chat/__fixtures__/saturday-booking.events.json';
+import { parseRunFrame, type RunEvent } from '../events';
+import { applyRunEvent, emptyRun, isLiveRun, replayRun, snapshotFromWire } from '../reduceRun';
+
+const frames = (fixture as { data: unknown }[]).map((item) => parseRunFrame(item.data));
+
+function eventsOf(runId: string): RunEvent[] {
+ return frames.filter((frame): frame is RunEvent => frame !== null && frame.type !== 'resync' && frame.runId === runId);
+}
+
+function envelope(suffix: string, data: Record<string, unknown>, seq = 1) {
+ return {
+ specversion: '1.0',
+ id: `r1:${seq}`,
+ source: 'opencompany://services/chat',
+ type: `com.opencompany.chat.run.${suffix}`,
+ subject: 'r1',
+ data: { workflow_id: 'w1', session_id: 'w1', run_id: 'r1', seq, hub_epoch: 'e1', ...data },
+ };
+}
+
+describe('parseRunFrame', () => {
+ it('reads every event of the handoff run', () => {
+ expect(frames.every((frame) => frame !== null)).toBe(true);
+ expect(frames[0]).toMatchObject({ type: 'started', runId: 'r_8f2a1c', sessionId: 'wf_salon', seq: 1, hubEpoch: 'e_fixture' });
+ });
+
+ it('refuses frames it cannot trust', () => {
+ expect(parseRunFrame(envelope('started', {}))).not.toBeNull();
+ expect(parseRunFrame({ ...envelope('started', {}), source: 'opencompany://elsewhere' })).toBeNull();
+ expect(parseRunFrame({ ...envelope('started', {}), type: 'com.opencompany.chat.updated' })).toBeNull();
+ expect(parseRunFrame({ ...envelope('started', {}), specversion: '0.3' })).toBeNull();
+ expect(parseRunFrame(envelope('started', { hub_epoch: undefined }))).toBeNull();
+ expect(parseRunFrame(envelope('started', { seq: 0 }, 0))).toBeNull();
+ expect(parseRunFrame(envelope('nonsense', {}))).toBeNull();
+ });
+});
+
+describe('applyRunEvent', () => {
+ it('folds the handoff run: steps, the reply text, and the draft that waits', () => {
+ const run = replayRun('r_8f2a1c', 'wf_salon', eventsOf('r_8f2a1c'));
+ expect(run).toMatchObject({
+ state: 'finished',
+ kind: 'message',
+ userMessageId: 'm_owner_1',
+ replyMessageId: 'a_r_8f2a1c',
+ seq: 29,
+ outcome: { type: 'interrupt', interrupts: [{ id: 'ap_1', reason: 'tool_call', toolCallId: 'call_8f2a1c' }] },
+ });
+ expect(run.steps.map((step) => [step.name, step.state, step.durationMs])).toEqual([
+ ['Checked Google Calendar', 'done', 640],
+ ['Read the WhatsApp thread with Priya', 'done', 640],
+ ['Compared stylist availability', 'done', 640],
+ ]);
+ expect(run.segments).toEqual([
+ { messageId: 'r_8f2a1c.1.1', text: 'Saturday is fairly full, but there’s a clean 2h 15m gap with Ana from 2:30pm.', final: true },
+ ]);
+ expect(isLiveRun(run)).toBe(false);
+ });
+
+ it('folds the resume run that sent the draft', () => {
+ const resume = eventsOf('r_8f2a1c').length;
+ const others = frames.slice(resume).filter((frame): frame is RunEvent => frame !== null && frame.type !== 'resync');
+ const run = replayRun(others[0].runId, 'wf_salon', others);
+ expect(run).toMatchObject({ kind: 'resume', parentRunId: 'r_8f2a1c', state: 'finished', outcome: { type: 'success' } });
+ });
+
+ it('changes nothing for an event it has already seen', () => {
+ const started = parseRunFrame(envelope('started', { kind: 'message' })) as RunEvent;
+ const once = applyRunEvent(emptyRun('r1', 'w1'), started);
+ expect(applyRunEvent(once, started)).toBe(once);
+ });
+
+ it('ends stopped when the run was stopped, and failed with the error', () => {
+ const base = applyRunEvent(emptyRun('r1', 'w1'), parseRunFrame(envelope('started', {})) as RunEvent);
+ const stopped = applyRunEvent(base, parseRunFrame(envelope('finished', { outcome: { type: 'stopped' } }, 2)) as RunEvent);
+ expect(stopped.state).toBe('stopped');
+ const failed = applyRunEvent(base, parseRunFrame(envelope('failed', { message: 'Calendar said no', code: 'run_failed', hint: 'Reconnect Google' }, 2)) as RunEvent);
+ expect(failed).toMatchObject({ state: 'error', error: { message: 'Calendar said no', code: 'run_failed', hint: 'Reconnect Google' } });
+ });
+});
+
+describe('snapshotFromWire', () => {
+ it('reads a run as the server sends it, the hint beside its error', () => {
+ const run = snapshotFromWire({
+ run_id: 'r1',
+ session_id: 'w1',
+ state: 'error',
+ seq: 4,
+ hub_epoch: 'e1',
+ error: 'Calendar said no',
+ error_code: 'run_failed',
+ result: { hint: 'Reconnect Google' },
+ steps: [{ step_id: 's1', name: 'Checked Google Calendar', state: 'failed' }],
+ });
+ expect(run).toMatchObject({
+ runId: 'r1',
+ state: 'error',
+ seq: 4,
+ error: { message: 'Calendar said no', code: 'run_failed', hint: 'Reconnect Google' },
+ steps: [{ stepId: 's1', name: 'Checked Google Calendar', state: 'failed' }],
+ });
+ });
+
+ it('names no run without an id and a session', () => {
+ expect(snapshotFromWire({ run_id: 'r1' })).toBeNull();
+ expect(snapshotFromWire('r1')).toBeNull();
+ });
+});
diff --git a/client/src/lib/agui/events.ts b/client/src/lib/agui/events.ts
new file mode 100644
index 00000000..33a224c3
--- /dev/null
+++ b/client/src/lib/agui/events.ts
@@ -0,0 +1,272 @@
+/**
+ * A chat run's events as the server sends them (docs-internal/chat_protocol.md).
+ *
+ * A `chat_run_event` frame's `data` is a CloudEvents envelope from
+ * `opencompany://services/chat` whose type is
+ * `com.opencompany.chat.run.<suffix>`, subject the run id and id
+ * `<run id>:<seq>`; the scope (`session_id`, `run_id`, `seq`, `hub_epoch`,
+ * `workflow_id`) is in `data`. `parseRunFrame` checks all of that and returns
+ * a typed event with camelCase fields, a session's resync request, or null.
+ *
+ * Fields beyond the scope are read one at a time: a field that cannot be read
+ * is left out, never the whole event. Suffixes later phases render
+ * (tool calls, activities, reasoning) come back as `unhandled`.
+ */
+
+export const RUN_SOURCE = 'opencompany://services/chat';
+export const RUN_TYPE_PREFIX = 'com.opencompany.chat.run.';
+
+export type RunKind = 'message' | 'edit' | 'regenerate' | 'action' | 'resume';
+export type RunState = 'queued' | 'pending' | 'running' | 'stopping' | 'finished' | 'error' | 'stopped';
+export type StepState = 'running' | 'done' | 'failed' | 'skipped';
+
+export interface RunInterrupt {
+ id: string;
+ reason: string;
+ message: string;
+ toolCallId?: string;
+ expiresAt?: string;
+}
+
+export interface RunOutcome {
+ type: 'success' | 'interrupt' | 'stopped';
+ interrupts: RunInterrupt[];
+}
+
+export interface RunResult {
+ replyMessageId?: string;
+ noReply?: boolean;
+}
+
+export interface RunError {
+ message: string;
+ code: string;
+ hint?: string;
+ requiresUserAction?: boolean;
+}
+
+export interface RunEventScope {
+ runId: string;
+ sessionId: string;
+ workflowId: string | null;
+ seq: number;
+ hubEpoch: string;
+ /** When the server published it (RFC 3339), or null. */
+ time: string | null;
+}
+
+/** What an event says beyond its scope, by type. */
+export type RunEventBody =
+ | {
+ type: 'started';
+ kind: RunKind;
+ parentRunId?: string;
+ userMessageId?: string;
+ replyMessageId?: string;
+ startedAt?: string;
+ }
+ | { type: 'finished'; outcome: RunOutcome; result: RunResult; durationMs: number; stepCount: number }
+ | { type: 'failed'; error: RunError }
+ | { type: 'step.started'; stepId: string; stepName: string; icon?: string }
+ | {
+ type: 'step.finished';
+ stepId: string;
+ stepName?: string;
+ state: Exclude<StepState, 'running'>;
+ detail?: string;
+ durationMs?: number;
+ narration?: string;
+ }
+ | { type: 'text.started'; messageId: string }
+ | { type: 'text.content'; messageId: string; delta: string }
+ | { type: 'text.ended'; messageId: string; final: boolean; replyMessageId?: string }
+ | { type: 'custom'; name: string; value: Record<string, unknown> }
+ | { type: 'unhandled'; suffix: string };
+
+export type RunEvent = RunEventScope & RunEventBody;
+
+/** The server dropped frames this socket could not keep up with: take a
+ * fresh snapshot of the session. */
+export interface ResyncRequest {
+ type: 'resync';
+ sessionId: string;
+ hubEpoch: string;
+}
+
+export type RunFrame = RunEvent | ResyncRequest;
+
+const RUN_KINDS: readonly RunKind[] = ['message', 'edit', 'regenerate', 'action', 'resume'];
+const FINISHED_STEP_STATES = ['done', 'failed', 'skipped'] as const;
+const OUTCOME_TYPES = ['success', 'interrupt', 'stopped'] as const;
+const UNHANDLED_SUFFIXES = new Set([
+ 'tool_call.started',
+ 'tool_call.args',
+ 'tool_call.ended',
+ 'tool_call.result',
+ 'activity.snapshot',
+ 'activity.delta',
+ 'reasoning.started',
+ 'reasoning.ended',
+]);
+
+type Data = Record<string, unknown>;
+
+function isRecord(value: unknown): value is Data {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function text(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+function count(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
+}
+
+function oneOf<T extends string>(value: unknown, options: readonly T[]): T | undefined {
+ return typeof value === 'string' && (options as readonly string[]).includes(value) ? (value as T) : undefined;
+}
+
+/** Copies only the keys whose values are set. */
+function defined<T extends object>(fields: T): T {
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as T;
+}
+
+function interrupts(raw: unknown): RunInterrupt[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((item) => {
+ if (!isRecord(item)) return [];
+ const id = text(item.id);
+ if (!id) return [];
+ return [
+ defined({
+ id,
+ reason: text(item.reason) ?? 'tool_call',
+ message: text(item.message) ?? '',
+ toolCallId: text(item.tool_call_id),
+ expiresAt: text(item.expires_at),
+ }),
+ ];
+ });
+}
+
+export function parseOutcome(raw: unknown): RunOutcome | null {
+ if (!isRecord(raw)) return null;
+ const type = oneOf(raw.type, OUTCOME_TYPES);
+ return type ? { type, interrupts: interrupts(raw.interrupts) } : null;
+}
+
+export function parseResult(raw: unknown): RunResult {
+ if (!isRecord(raw)) return {};
+ return defined({
+ replyMessageId: text(raw.reply_message_id),
+ noReply: raw.no_reply === true ? true : undefined,
+ });
+}
+
+export function parseError(raw: Data): RunError {
+ return defined({
+ message: text(raw.message) ?? 'The run failed.',
+ code: text(raw.code) ?? 'run_failed',
+ hint: text(raw.hint),
+ requiresUserAction: raw.requires_user_action === true ? true : undefined,
+ });
+}
+
+function eventFields(suffix: string, data: Data): RunEventBody | null {
+ switch (suffix) {
+ case 'started':
+ return defined({
+ type: 'started' as const,
+ kind: oneOf(data.kind, RUN_KINDS) ?? 'message',
+ parentRunId: text(data.parent_run_id),
+ userMessageId: text(data.user_message_id),
+ replyMessageId: text(data.reply_message_id),
+ startedAt: text(data.started_at),
+ });
+ case 'finished':
+ return {
+ type: 'finished',
+ outcome: parseOutcome(data.outcome) ?? { type: 'success', interrupts: [] },
+ result: parseResult(data.result),
+ durationMs: count(data.duration_ms) ?? 0,
+ stepCount: count(data.step_count) ?? 0,
+ };
+ case 'failed':
+ return { type: 'failed', error: parseError(data) };
+ case 'step.started': {
+ const stepId = text(data.step_id);
+ return stepId ? defined({ type: 'step.started' as const, stepId, stepName: text(data.step_name) ?? '', icon: text(data.icon) }) : null;
+ }
+ case 'step.finished': {
+ const stepId = text(data.step_id);
+ if (!stepId) return null;
+ return defined({
+ type: 'step.finished' as const,
+ stepId,
+ stepName: text(data.step_name),
+ state: oneOf(data.state, FINISHED_STEP_STATES) ?? 'done',
+ detail: text(data.detail),
+ durationMs: count(data.duration_ms),
+ narration: text(data.narration),
+ });
+ }
+ case 'text.started':
+ case 'text.content':
+ case 'text.ended': {
+ const messageId = text(data.message_id);
+ if (!messageId) return null;
+ if (suffix === 'text.started') return { type: 'text.started', messageId };
+ if (suffix === 'text.content') {
+ const delta = typeof data.delta === 'string' ? data.delta : '';
+ return delta ? { type: 'text.content', messageId, delta } : null;
+ }
+ return defined({
+ type: 'text.ended' as const,
+ messageId,
+ final: data.final === true,
+ replyMessageId: text(data.reply_message_id),
+ });
+ }
+ case 'custom': {
+ const name = text(data.name);
+ return name ? { type: 'custom', name, value: isRecord(data.value) ? data.value : {} } : null;
+ }
+ default:
+ return UNHANDLED_SUFFIXES.has(suffix) ? { type: 'unhandled', suffix } : null;
+ }
+}
+
+/** One `chat_run_event` frame's `data`, checked and typed; null when it is
+ * not a run event this client can trust. */
+export function parseRunFrame(raw: unknown): RunFrame | null {
+ if (!isRecord(raw) || raw.specversion !== '1.0' || raw.source !== RUN_SOURCE) return null;
+ const type = typeof raw.type === 'string' ? raw.type : '';
+ if (!type.startsWith(RUN_TYPE_PREFIX) || !isRecord(raw.data)) return null;
+ const suffix = type.slice(RUN_TYPE_PREFIX.length);
+ const data = raw.data;
+ const sessionId = text(data.session_id);
+ const hubEpoch = text(data.hub_epoch);
+ if (!sessionId || !hubEpoch) return null;
+
+ const runId = text(data.run_id);
+ if (!runId) {
+ // The only event without a run: the hub asking a lagging socket to resync.
+ return suffix === 'custom' && data.name === 'opencompany.resync' ? { type: 'resync', sessionId, hubEpoch } : null;
+ }
+ const seq = data.seq;
+ if (typeof seq !== 'number' || !Number.isInteger(seq) || seq < 1) return null;
+ if (raw.subject !== runId || raw.id !== `${runId}:${seq}`) return null;
+
+ const fields = eventFields(suffix, data);
+ if (!fields) return null;
+ const scope: RunEventScope = {
+ runId,
+ sessionId,
+ workflowId: typeof data.workflow_id === 'string' ? data.workflow_id : null,
+ seq,
+ hubEpoch,
+ time: text(raw.time) ?? null,
+ };
+ return { ...scope, ...fields } as RunEvent;
+}
diff --git a/client/src/lib/agui/reduceRun.ts b/client/src/lib/agui/reduceRun.ts
new file mode 100644
index 00000000..840d0f57
--- /dev/null
+++ b/client/src/lib/agui/reduceRun.ts
@@ -0,0 +1,267 @@
+/**
+ * A chat run's state, folded from its events (lib/agui/events.ts), the same
+ * way server/services/chat/reducer.py folds them, so a snapshot from
+ * `chat_subscribe` and a stream of events agree.
+ *
+ * `applyRunEvent` is pure and returns the run unchanged (the same object)
+ * for an event whose `seq` it has already seen. Gaps are the caller's to
+ * detect (stores/chatRunStore.ts asks for a fresh snapshot).
+ */
+
+import {
+ parseError,
+ parseOutcome,
+ parseResult,
+ type RunError,
+ type RunEvent,
+ type RunKind,
+ type RunOutcome,
+ type RunResult,
+ type RunState,
+ type StepState,
+} from './events';
+
+export interface RunStep {
+ stepId: string;
+ name: string;
+ state: StepState;
+ icon?: string;
+ detail?: string;
+ durationMs?: number;
+ narration?: string;
+}
+
+export interface RunSegment {
+ messageId: string;
+ text: string;
+ /** True for the reply, false for narration beside a tool call, null while
+ * it streams. */
+ final: boolean | null;
+}
+
+export interface RunSnapshot {
+ runId: string;
+ sessionId: string;
+ workflowId: string | null;
+ kind: RunKind;
+ state: RunState;
+ /** The newest event folded in; 0 before any. */
+ seq: number;
+ hubEpoch: string | null;
+ userMessageId: string | null;
+ replyMessageId: string | null;
+ parentRunId: string | null;
+ createdAt: string | null;
+ startedAt: string | null;
+ finishedAt: string | null;
+ steps: RunStep[];
+ segments: RunSegment[];
+ outcome: RunOutcome | null;
+ result: RunResult;
+ error: RunError | null;
+}
+
+export const LIVE_RUN_STATES: ReadonlySet<RunState> = new Set(['queued', 'pending', 'running', 'stopping']);
+
+export function isLiveRun(run: Pick<RunSnapshot, 'state'>): boolean {
+ return LIVE_RUN_STATES.has(run.state);
+}
+
+export function emptyRun(runId: string, sessionId: string): RunSnapshot {
+ return {
+ runId,
+ sessionId,
+ workflowId: null,
+ kind: 'message',
+ state: 'pending',
+ seq: 0,
+ hubEpoch: null,
+ userMessageId: null,
+ replyMessageId: null,
+ parentRunId: null,
+ createdAt: null,
+ startedAt: null,
+ finishedAt: null,
+ steps: [],
+ segments: [],
+ outcome: null,
+ result: {},
+ error: null,
+ };
+}
+
+const RUN_KINDS: readonly RunKind[] = ['message', 'edit', 'regenerate', 'action', 'resume'];
+const RUN_STATES: readonly RunState[] = ['queued', 'pending', 'running', 'stopping', 'finished', 'error', 'stopped'];
+const STEP_STATES: readonly StepState[] = ['running', 'done', 'failed', 'skipped'];
+
+type Data = Record<string, unknown>;
+
+function isRecord(value: unknown): value is Data {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function textOrNull(value: unknown): string | null {
+ return typeof value === 'string' && value.length > 0 ? value : null;
+}
+
+function optionalText(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
+}
+
+function oneOf<T extends string>(value: unknown, options: readonly T[], fallback: T): T {
+ return typeof value === 'string' && (options as readonly string[]).includes(value) ? (value as T) : fallback;
+}
+
+function wireSteps(raw: unknown): RunStep[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((item) => {
+ if (!isRecord(item)) return [];
+ const stepId = optionalText(item.step_id);
+ if (!stepId) return [];
+ const step: RunStep = { stepId, name: optionalText(item.name) ?? '', state: oneOf(item.state, STEP_STATES, 'done') };
+ const icon = optionalText(item.icon);
+ const detail = optionalText(item.detail);
+ const narration = optionalText(item.narration);
+ if (icon) step.icon = icon;
+ if (detail) step.detail = detail;
+ if (typeof item.duration_ms === 'number') step.durationMs = item.duration_ms;
+ if (narration) step.narration = narration;
+ return [step];
+ });
+}
+
+function wireSegments(raw: unknown): RunSegment[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.flatMap((item) => {
+ if (!isRecord(item)) return [];
+ const messageId = optionalText(item.message_id);
+ if (!messageId) return [];
+ return [{ messageId, text: typeof item.text === 'string' ? item.text : '', final: typeof item.final === 'boolean' ? item.final : null }];
+ });
+}
+
+/** A run as the server sends it (`chat_subscribe`'s `active_runs`,
+ * `get_chat_run`'s `run`); null when it names no run. */
+export function snapshotFromWire(raw: unknown): RunSnapshot | null {
+ if (!isRecord(raw)) return null;
+ const runId = optionalText(raw.run_id);
+ const sessionId = optionalText(raw.session_id);
+ if (!runId || !sessionId) return null;
+ const outcome = parseOutcome(raw.outcome);
+ return {
+ runId,
+ sessionId,
+ workflowId: textOrNull(raw.workflow_id),
+ kind: oneOf(raw.kind, RUN_KINDS, 'message'),
+ state: oneOf(raw.state, RUN_STATES, 'pending'),
+ seq: typeof raw.seq === 'number' && Number.isInteger(raw.seq) && raw.seq >= 0 ? raw.seq : 0,
+ hubEpoch: textOrNull(raw.hub_epoch),
+ userMessageId: textOrNull(raw.user_message_id),
+ replyMessageId: textOrNull(raw.reply_message_id),
+ parentRunId: textOrNull(raw.parent_run_id),
+ createdAt: textOrNull(raw.created_at),
+ startedAt: textOrNull(raw.started_at),
+ finishedAt: textOrNull(raw.finished_at),
+ steps: wireSteps(raw.steps),
+ segments: wireSegments(raw.segments),
+ outcome,
+ result: parseResult(raw.result),
+ // A failed run keeps its hint beside the error, in `result`.
+ error: optionalText(raw.error)
+ ? parseError({ ...(isRecord(raw.result) ? raw.result : {}), message: raw.error, code: raw.error_code })
+ : null,
+ };
+}
+
+function withStep(steps: RunStep[], stepId: string, update: (step: RunStep) => RunStep): RunStep[] {
+ const index = steps.findIndex((step) => step.stepId === stepId);
+ if (index === -1) return [...steps, update({ stepId, name: '', state: 'running' })];
+ return steps.map((step, i) => (i === index ? update(step) : step));
+}
+
+function withSegment(segments: RunSegment[], messageId: string, update: (segment: RunSegment) => RunSegment): RunSegment[] {
+ const index = segments.findIndex((segment) => segment.messageId === messageId);
+ if (index === -1) return [...segments, update({ messageId, text: '', final: null })];
+ return segments.map((segment, i) => (i === index ? update(segment) : segment));
+}
+
+/** `run` with `event` folded in. An event at or before the run's `seq` is a
+ * duplicate: the same object comes back. */
+export function applyRunEvent(run: RunSnapshot, event: RunEvent): RunSnapshot {
+ if (event.seq <= run.seq) return run;
+ const next: RunSnapshot = {
+ ...run,
+ seq: event.seq,
+ hubEpoch: event.hubEpoch,
+ sessionId: event.sessionId,
+ workflowId: event.workflowId ?? run.workflowId,
+ };
+ switch (event.type) {
+ case 'started':
+ return {
+ ...next,
+ state: run.state === 'stopping' ? 'stopping' : 'running',
+ kind: event.kind,
+ parentRunId: event.parentRunId ?? run.parentRunId,
+ userMessageId: event.userMessageId ?? run.userMessageId,
+ replyMessageId: event.replyMessageId ?? run.replyMessageId,
+ startedAt: event.startedAt ?? run.startedAt ?? event.time,
+ };
+ case 'finished':
+ return {
+ ...next,
+ state: event.outcome.type === 'stopped' ? 'stopped' : 'finished',
+ outcome: event.outcome,
+ result: event.result,
+ finishedAt: event.time ?? run.finishedAt,
+ };
+ case 'failed':
+ return { ...next, state: 'error', error: event.error, finishedAt: event.time ?? run.finishedAt };
+ case 'step.started':
+ return {
+ ...next,
+ steps: withStep(run.steps, event.stepId, (step) => ({
+ ...step,
+ name: event.stepName || step.name,
+ state: 'running',
+ ...(event.icon ? { icon: event.icon } : {}),
+ })),
+ };
+ case 'step.finished':
+ return {
+ ...next,
+ steps: withStep(run.steps, event.stepId, (step) => ({
+ ...step,
+ name: event.stepName || step.name,
+ state: event.state,
+ ...(event.detail !== undefined ? { detail: event.detail } : {}),
+ ...(event.durationMs !== undefined ? { durationMs: event.durationMs } : {}),
+ ...(event.narration !== undefined ? { narration: event.narration } : {}),
+ })),
+ };
+ case 'text.started':
+ return { ...next, segments: withSegment(run.segments, event.messageId, (segment) => segment) };
+ case 'text.content':
+ return { ...next, segments: withSegment(run.segments, event.messageId, (segment) => ({ ...segment, text: segment.text + event.delta })) };
+ case 'text.ended':
+ return {
+ ...next,
+ segments: withSegment(run.segments, event.messageId, (segment) => ({ ...segment, final: event.final })),
+ replyMessageId: event.replyMessageId ?? run.replyMessageId,
+ };
+ case 'custom':
+ if (event.name === 'opencompany.segment_discarded') {
+ const discarded = event.value.message_id;
+ return { ...next, segments: run.segments.filter((segment) => segment.messageId !== discarded) };
+ }
+ if (event.name === 'opencompany.stopping') return { ...next, state: 'stopping' };
+ return next;
+ case 'unhandled':
+ return next;
+ }
+}
+
+/** Fold a run's events, in order, from a run that has seen none. */
+export function replayRun(runId: string, sessionId: string, events: readonly RunEvent[]): RunSnapshot {
+ return events.reduce(applyRunEvent, emptyRun(runId, sessionId));
+}
diff --git a/client/src/stores/__tests__/chatRunStore.test.ts b/client/src/stores/__tests__/chatRunStore.test.ts
new file mode 100644
index 00000000..40ff1d04
--- /dev/null
+++ b/client/src/stores/__tests__/chatRunStore.test.ts
@@ -0,0 +1,107 @@
+/**
+ * The run store's ordering rules: frames fold in once per animation frame,
+ * by each run's `seq`; a duplicate changes nothing; a gap, an unknown run
+ * already under way or a new server epoch ask for a fresh snapshot and hold
+ * what arrives meanwhile; a snapshot names the runs that ended unseen.
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import { snapshotFromWire, type RunSnapshot } from '@/lib/agui/reduceRun';
+import { resetChatRunStore, useChatRunStore } from '../chatRunStore';
+
+function frame(seq: number, suffix: string, data: Record<string, unknown> = {}, runId = 'r1', hubEpoch = 'e1') {
+ return {
+ specversion: '1.0',
+ id: `${runId}:${seq}`,
+ source: 'opencompany://services/chat',
+ type: `com.opencompany.chat.run.${suffix}`,
+ subject: runId,
+ data: { workflow_id: 'w1', session_id: 'w1', run_id: runId, seq, hub_epoch: hubEpoch, ...data },
+ };
+}
+
+function receive(...frames: unknown[]) {
+ const store = useChatRunStore.getState();
+ for (const item of frames) store.receive(item);
+ store.flush();
+}
+
+function session() {
+ return useChatRunStore.getState().sessions.w1;
+}
+
+function snapshot(runId: string, state: string, seq: number, hubEpoch = 'e1'): RunSnapshot {
+ return snapshotFromWire({ run_id: runId, session_id: 'w1', state, seq, hub_epoch: hubEpoch })!;
+}
+
+beforeEach(() => resetChatRunStore());
+
+describe('chatRunStore', () => {
+ it('folds a run in order and ignores a frame it has seen', () => {
+ receive(frame(1, 'started', { kind: 'message' }), frame(2, 'text.content', { message_id: 's1', delta: 'Hi' }));
+ receive(frame(2, 'text.content', { message_id: 's1', delta: 'Hi' }));
+ expect(session().runs.r1).toMatchObject({ state: 'running', seq: 2, segments: [{ messageId: 's1', text: 'Hi' }] });
+ expect(session().syncing).toBe(false);
+ });
+
+ it('asks for a snapshot on a gap and folds the held frames after it', () => {
+ receive(frame(1, 'started'));
+ const before = session().resync;
+ receive(frame(3, 'text.content', { message_id: 's1', delta: ' there' }));
+ expect(session()).toMatchObject({ syncing: true, resync: before + 1 });
+ // More frames while the snapshot is on its way are held, not asked for again.
+ receive(frame(4, 'text.ended', { message_id: 's1', final: true }));
+ expect(session().resync).toBe(before + 1);
+
+ const fresh = { ...snapshot('r1', 'running', 2), segments: [{ messageId: 's1', text: 'Hi', final: null }] };
+ useChatRunStore.getState().applySubscription('w1', 'e1', [fresh]);
+ expect(session()).toMatchObject({ syncing: false, subscribed: true });
+ expect(session().runs.r1).toMatchObject({ seq: 4, segments: [{ messageId: 's1', text: 'Hi there', final: true }] });
+ });
+
+ it('asks for a snapshot for a run it joins half way, and for a new server', () => {
+ receive(frame(5, 'step.started', { step_id: 'a', step_name: 'Checked' }));
+ expect(session()).toMatchObject({ syncing: true, resync: 1 });
+
+ resetChatRunStore();
+ useChatRunStore.getState().applySubscription('w1', 'e1', []);
+ receive(frame(1, 'started', {}, 'r2', 'e2'));
+ expect(session()).toMatchObject({ syncing: true, resync: 1 });
+ });
+
+ it('names the live runs a snapshot no longer has', () => {
+ useChatRunStore.getState().admit('w1', { runId: 'r1', userMessageId: 'm1', state: 'pending' });
+ useChatRunStore.getState().applySubscription('w1', 'e1', [snapshot('r2', 'running', 1)]);
+ expect(session().stale).toEqual(['r1']);
+ useChatRunStore.getState().upsertRun({ ...snapshot('r1', 'finished', 6) });
+ expect(session().stale).toEqual([]);
+ expect(session().runs.r1.state).toBe('finished');
+ });
+
+ it('keeps the newer of two readings of one run', () => {
+ receive(frame(1, 'started'), frame(2, 'step.started', { step_id: 'a', step_name: 'Checked' }));
+ useChatRunStore.getState().applySubscription('w1', 'e1', [snapshot('r1', 'running', 1)]);
+ expect(session().runs.r1.seq).toBe(2);
+ });
+
+ it('registers the run a send admitted, once', () => {
+ const store = useChatRunStore.getState();
+ store.admit('w1', { runId: 'r1', userMessageId: 'm1', state: 'queued' });
+ expect(session().runs.r1).toMatchObject({ state: 'queued', userMessageId: 'm1' });
+ receive(frame(1, 'started'));
+ store.admit('w1', { runId: 'r1', userMessageId: 'm1', state: 'pending' });
+ expect(session().runs.r1.state).toBe('running');
+ });
+
+ it('asks for a snapshot when the hub dropped frames', () => {
+ receive(frame(1, 'started'));
+ receive({
+ specversion: '1.0',
+ id: 'resync',
+ source: 'opencompany://services/chat',
+ type: 'com.opencompany.chat.run.custom',
+ data: { session_id: 'w1', hub_epoch: 'e1', name: 'opencompany.resync' },
+ });
+ expect(session().syncing).toBe(true);
+ });
+});
diff --git a/client/src/stores/chatRunStore.ts b/client/src/stores/chatRunStore.ts
new file mode 100644
index 00000000..2bcf28c2
--- /dev/null
+++ b/client/src/stores/chatRunStore.ts
@@ -0,0 +1,196 @@
+/**
+ * Chat runs as they happen, per chat session (docs-internal/chat_protocol.md).
+ *
+ * WebSocketContext hands every `chat_run_event` frame to `receive`; the hook
+ * that subscribes a session (features/chat/data/runs.ts) applies the
+ * server's snapshots. Frames are folded in once per animation frame, so a
+ * burst of streamed text costs one store update.
+ *
+ * Ordering is the server's `seq`, per run:
+ * - a frame at or before a run's `seq` is a duplicate and changes nothing;
+ * - a gap, an unknown run that is already under way, a new `hub_epoch` (the
+ * server restarted) or the hub's resync frame mark the session `syncing`
+ * and bump `resync`: the subscription takes a fresh snapshot, and the
+ * frames that arrived meanwhile are held and folded in after it, skipping
+ * what the snapshot already covers.
+ *
+ * Nothing here talks to the socket.
+ */
+
+import { create } from 'zustand';
+import { parseRunFrame, type RunEvent, type RunFrame } from '@/lib/agui/events';
+import { applyRunEvent, emptyRun, isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';
+
+export interface SessionRuns {
+ /** The server process these runs' `seq` belongs to. */
+ hubEpoch: string | null;
+ runs: Record<string, RunSnapshot>;
+ /** Frames held while a fresh snapshot is on its way. */
+ held: RunEvent[];
+ /** Bumped to ask the subscription for a fresh snapshot. */
+ resync: number;
+ syncing: boolean;
+ /** A subscription snapshot has arrived: from then on these runs are the
+ * session's live runs, whatever an older thread read says. */
+ subscribed: boolean;
+ /** Runs live here but absent from the last snapshot: they ended unseen and
+ * need reading again (`get_chat_run`). */
+ stale: string[];
+}
+
+export interface AdmittedRun {
+ runId: string;
+ userMessageId: string;
+ state: 'pending' | 'queued';
+}
+
+interface ChatRunState {
+ sessions: Record<string, SessionRuns>;
+ /** Queue one `chat_run_event` frame's data; folded in on the next frame. */
+ receive: (raw: unknown) => void;
+ /** Fold queued frames in now. */
+ flush: () => void;
+ /** A session's snapshot from `chat_subscribe`. */
+ applySubscription: (sessionId: string, hubEpoch: string, snapshots: readonly RunSnapshot[]) => void;
+ /** One run read on its own (`get_chat_run`). */
+ upsertRun: (snapshot: RunSnapshot) => void;
+ /** The run a send just admitted, before its first event arrives. */
+ admit: (sessionId: string, run: AdmittedRun) => void;
+}
+
+const EMPTY_SESSION: SessionRuns = { hubEpoch: null, runs: {}, held: [], resync: 0, syncing: false, subscribed: false, stale: [] };
+
+function requestResync(session: SessionRuns, held?: RunEvent): SessionRuns {
+ return {
+ ...session,
+ held: held ? [...session.held, held] : session.held,
+ syncing: true,
+ resync: session.syncing ? session.resync : session.resync + 1,
+ };
+}
+
+function foldEvent(session: SessionRuns, event: RunEvent): SessionRuns {
+ if (session.syncing) return { ...session, held: [...session.held, event] };
+ if (session.hubEpoch !== null && session.hubEpoch !== event.hubEpoch) return requestResync(session, event);
+ const known = session.runs[event.runId];
+ const base = known ?? (event.seq === 1 ? emptyRun(event.runId, event.sessionId) : null);
+ if (!base) return requestResync(session, event);
+ if (event.seq <= base.seq) return session;
+ if (event.seq > base.seq + 1) return requestResync(session, event);
+ return {
+ ...session,
+ hubEpoch: session.hubEpoch ?? event.hubEpoch,
+ runs: { ...session.runs, [event.runId]: applyRunEvent(base, event) },
+ stale: session.stale.filter((runId) => runId !== event.runId),
+ };
+}
+
+function foldFrame(sessions: Record<string, SessionRuns>, frame: RunFrame): Record<string, SessionRuns> {
+ if (frame.type === 'resync') {
+ const session = sessions[frame.sessionId];
+ return session ? { ...sessions, [frame.sessionId]: requestResync(session) } : sessions;
+ }
+ const session = sessions[frame.sessionId] ?? EMPTY_SESSION;
+ const next = foldEvent(session, frame);
+ return next === session ? sessions : { ...sessions, [frame.sessionId]: next };
+}
+
+/** The newer of two readings of one run: a higher `seq` in the same epoch. */
+function newer(local: RunSnapshot | undefined, incoming: RunSnapshot): RunSnapshot {
+ return local && local.hubEpoch === incoming.hubEpoch && local.seq > incoming.seq ? local : incoming;
+}
+
+// Frames wait here for the next animation frame (a hidden page gets a
+// timer instead: browsers do not paint it).
+let queue: RunFrame[] = [];
+let scheduled = false;
+
+function schedule(flush: () => void): void {
+ if (scheduled) return;
+ scheduled = true;
+ const run = () => {
+ scheduled = false;
+ flush();
+ };
+ const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden';
+ if (!hidden && typeof requestAnimationFrame === 'function') requestAnimationFrame(run);
+ else setTimeout(run, 0);
+}
+
+export const useChatRunStore = create<ChatRunState>((set, get) => ({
+ sessions: {},
+
+ receive: (raw) => {
+ const frame = parseRunFrame(raw);
+ if (!frame) return;
+ queue.push(frame);
+ schedule(get().flush);
+ },
+
+ flush: () => {
+ if (queue.length === 0) return;
+ const frames = queue;
+ queue = [];
+ set((state) => {
+ let sessions = state.sessions;
+ for (const frame of frames) sessions = foldFrame(sessions, frame);
+ return sessions === state.sessions ? state : { sessions };
+ });
+ },
+
+ applySubscription: (sessionId, hubEpoch, snapshots) => {
+ get().flush();
+ set((state) => {
+ const previous = state.sessions[sessionId] ?? EMPTY_SESSION;
+ const runs: Record<string, RunSnapshot> = {};
+ for (const snapshot of snapshots) {
+ const incoming = { ...snapshot, hubEpoch };
+ runs[snapshot.runId] = newer(previous.runs[snapshot.runId], incoming);
+ }
+ const stale: string[] = [];
+ for (const [runId, local] of Object.entries(previous.runs)) {
+ if (runId in runs) continue;
+ runs[runId] = local;
+ if (isLiveRun(local)) stale.push(runId);
+ }
+ let session: SessionRuns = { hubEpoch, runs, held: [], resync: previous.resync, syncing: false, subscribed: true, stale };
+ for (const event of previous.held) session = foldEvent(session, event);
+ return { sessions: { ...state.sessions, [sessionId]: session } };
+ });
+ },
+
+ upsertRun: (snapshot) =>
+ set((state) => {
+ const session = state.sessions[snapshot.sessionId] ?? EMPTY_SESSION;
+ const run = newer(session.runs[snapshot.runId], snapshot);
+ return {
+ sessions: {
+ ...state.sessions,
+ [snapshot.sessionId]: {
+ ...session,
+ runs: { ...session.runs, [snapshot.runId]: run },
+ stale: session.stale.filter((runId) => runId !== snapshot.runId),
+ },
+ },
+ };
+ }),
+
+ admit: (sessionId, admitted) =>
+ set((state) => {
+ const session = state.sessions[sessionId] ?? EMPTY_SESSION;
+ if (session.runs[admitted.runId]) return state;
+ const run: RunSnapshot = {
+ ...emptyRun(admitted.runId, sessionId),
+ state: admitted.state,
+ userMessageId: admitted.userMessageId,
+ };
+ return { sessions: { ...state.sessions, [sessionId]: { ...session, runs: { ...session.runs, [admitted.runId]: run } } } };
+ }),
+}));
+
+/** Drop queued frames and every session (tests). */
+export function resetChatRunStore(): void {
+ queue = [];
+ scheduled = false;
+ useChatRunStore.setState({ sessions: {} });
+}