Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): cards stay on the run that waits for them (RFC-0007 AP.3, 3 of 4)
trohitg22d767faec93
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsxindex a91a42e9..4a16fb43 100644--- a/client/src/features/chat/ChatPane.tsx+++ b/client/src/features/chat/ChatPane.tsx@@ -64,6 +64,7 @@ import { canRecord, useChatContext, useDictation, type ChatCommand } from './datimport {NO_APPROVALS,isOpenApproval,+ turnApprovalIds,useApprovalEvents,useAskFirst,useChatApprovals,@@ -83,7 +84,6 @@ import {type ChatBranchError,} from './data/branches';import { useChatChoice, useChatModels } from './data/models';-import { liveApprovalIds, savedApprovalIds } from './data/parts';import { sendOptions, useSendChatMessage, type ChatSendError } from './data/send';import { useStopChatRun } from './data/stop';import { useUiStateSync } from './data/uiState';@@ -322,11 +322,10 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandconst ids = new Set<string>();for (const turn of turns) {if (turn.kind !== 'assistant') continue;- for (const id of savedApprovalIds(turn.message?.parts)) ids.add(id);- for (const id of liveApprovalIds(turn.run?.activities)) ids.add(id);+ for (const id of turnApprovalIds(turn.message, turn.run, approvals)) ids.add(id);}return ids;- }, [turns]);+ }, [turns, approvals]);const standalone = useMemo(() => {const now = approvals.receivedAt + approvals.offsetMs;return [...approvals.order]diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsxindex 353a4115..64ab6ab2 100644--- a/client/src/features/chat/__tests__/approvals.test.tsx+++ b/client/src/features/chat/__tests__/approvals.test.tsx@@ -161,7 +161,11 @@ describe('the card says what happened', () => {// ----- in the chat -----let server: {+ messages: Wire[];+ activeRuns: Wire[];approvals: Wire[];+ /** Open rows older than the newest 100. */+ older: Wire[];askFirst: boolean | null;mode: string | null;revision: number;@@ -204,15 +208,30 @@ beforeEach(() => {resetChatRunStore();useComposerStore.setState({ drafts: {} });useWorkflowControlStore.setState({ statuses: {}, pending: {} });- server = { approvals: [summary()], askFirst: true, mode: 'outside', revision: 0, decisions: [], rule: [], allows: [], money: [] };+ server = {+ messages: MESSAGES,+ activeRuns: [],+ approvals: [summary()],+ older: [],+ askFirst: true,+ mode: 'outside',+ revision: 0,+ decisions: [],+ rule: [],+ allows: [],+ money: [],+ };sendRequest.mockReset().mockImplementation(async (kind: string, data: Wire) => {switch (kind) {case 'chat_subscribe':- return { success: true, session_id: data.session_id, hub_epoch: 'e1', active_runs: [] };+ return { success: true, session_id: data.session_id, hub_epoch: 'e1', active_runs: server.activeRuns };case 'get_chat_messages':- return { success: true, messages: MESSAGES, thread: { active_leaf_id: null, revision: 1 }, active_runs: [] };- case 'list_approvals':- return { success: true, approvals: server.approvals, server_time: new Date().toISOString() };+ return { success: true, messages: server.messages, thread: { active_leaf_id: null, revision: 1 }, active_runs: server.activeRuns };+ case 'list_approvals': {+ const open = server.approvals.filter((approval) => ['pending', 'approved', 'sending', 'failed'].includes(String(approval.status)));+ const approvals = data.status === 'open' ? [...open, ...server.older] : server.approvals;+ return { success: true, approvals, server_time: new Date().toISOString() };+ }case 'get_ask_first':return { success: true, ask_first: server.askFirst, mode: server.mode, revision: server.revision };case 'set_ask_first':@@ -430,6 +449,56 @@ describe('a draft in the chat', () => {});});+describe('a call its turn waits on', () => {+ // The run waits on the owner; a restart lost what it announced live, so+ // only the card's run links them.+ const waitingRun: Wire = {+ run_id: 'r1',+ workflow_id: 'w1',+ session_id: 'w1',+ state: 'running',+ seq: 3,+ hub_epoch: 'e1',+ steps: [{ step_id: 'call_1', name: 'Send a WhatsApp message', state: 'done', detail: 'Waiting for your OK' }],+ };++ it('stays on its turn, which says it waits for the owner', async () => {+ server.messages = [row('m1', 'user', 'Tell Ana I’m late', { run_id: 'r1' })];+ server.activeRuns = [waitingRun];+ server.approvals = [summary({ waits: true })];+ renderPane();+ const card = (await screen.findByText('Maya wants to send a WhatsApp message')).closest('[data-approval]') as HTMLElement;+ const turn = card.closest('[data-turn="assistant"]') as HTMLElement;+ expect(turn).toHaveAttribute('data-run', 'r1');+ expect(screen.queryByRole('region', { name: 'Drafts waiting for you' })).not.toBeInTheDocument();+ expect(within(turn).getAllByRole('status').some((node) => node.textContent === 'Waiting for your OK')).toBe(true);+ expect(turn.querySelector('[data-thinking]')).toBeNull();+ // Its step waits too, until the card is decided.+ const step = turn.querySelector('[data-step="call_1"]') as HTMLElement;+ expect(step).toHaveAttribute('data-state', 'running');+ expect(step).toHaveTextContent('Waiting for your OK');+ });++ it('a draft the turn does not wait on leaves the turn as it was', async () => {+ server.messages = [row('m1', 'user', 'Tell Ana I’m late', { run_id: 'r1' })];+ server.activeRuns = [waitingRun];+ renderPane();+ const card = (await screen.findByText('Maya wants to send a WhatsApp message')).closest('[data-approval]') as HTMLElement;+ const turn = card.closest('[data-turn="assistant"]') as HTMLElement;+ expect(within(turn).getAllByRole('status').some((node) => node.textContent === 'Thinking')).toBe(true);+ expect(turn.querySelector('[data-step="call_1"]')).toHaveAttribute('data-state', 'done');+ });++ it('is read however many newer cards there are', async () => {+ server.approvals = [];+ server.older = [summary({ approval_id: 'g1', kind: 'gate', run_id: null, tool_call_id: null, action: null, body: 'Yes, Saturday at 10 works.' })];+ renderPane();+ const own = await screen.findByRole('region', { name: 'Drafts waiting for you' });+ expect(within(own).getByText('Yes, Saturday at 10 works.')).toBeInTheDocument();+ expect(sendRequest).toHaveBeenCalledWith('list_approvals', { workflow_id: 'w1', status: 'open', limit: 100 });+ });+});+describe('Ask first by mode', () => {function renderByMode() {asksByMode();diff --git a/client/src/features/chat/__tests__/copy.test.ts b/client/src/features/chat/__tests__/copy.test.tsindex a2de5d52..ce0df541 100644--- a/client/src/features/chat/__tests__/copy.test.ts+++ b/client/src/features/chat/__tests__/copy.test.ts@@ -6,7 +6,8 @@import { describe, expect, it } from 'vitest';import { emptyRun, type RunSnapshot, type RunStep } from '@/lib/agui/reduceRun';import { timeLabel } from '../thread/timeLabel';-import { failureLines, liveLabel, liveText, stepDetail, workLabel, writingRate } from '../turns/runCopy';+import { parseApproval } from '../data/approvals';+import { approvalStep, failureLines, liveLabel, liveText, stepDetail, workLabel, writingRate } from '../turns/runCopy';describe('timeLabel', () => {const now = new Date(2026, 8, 28, 15, 30);@@ -61,6 +62,7 @@ describe('a working run', () => {expect(liveLabel(working, false)).toBe('Thinking');expect(liveLabel(working, true)).toBe('Writing');expect(liveLabel({ ...working, state: 'stopping' }, true)).toBe('Stopping…');+ expect(liveLabel(working, false, true)).toBe('Waiting for your OK');});it('says how fast the answer comes, once a second has passed', () => {@@ -104,6 +106,22 @@ describe('working steps', () => {expect(stepDetail(step('a', 'done', '3 events on Saturday'))).toBe('3 events on Saturday');expect(stepDetail(step('a', 'done'))).toBeNull();expect(stepDetail(step('a', 'failed', 'quota'))).toBe('Failed · quota');- expect(stepDetail(step('a', 'skipped', 'x'))).toBe('Skipped');+ expect(stepDetail(step('a', 'skipped'))).toBe('Skipped');+ expect(stepDetail(step('a', 'skipped', 'You declined'))).toBe('You declined');+ });++ it('a call its turn waits on follows its card', () => {+ const held = step('call_1', 'done', 'Waiting for your OK');+ const card = (patch: Record<string, unknown>) =>+ parseApproval({ approval_id: 'ap1', status: 'pending', waits: true, outcome_labels: { sent: 'Done', failed: 'Not done' }, ...patch })!;+ expect(approvalStep(held, card({}))).toMatchObject({ state: 'running', detail: 'Waiting for your OK' });+ expect(approvalStep(held, card({ status: 'approved' }))).toMatchObject({ state: 'running', detail: 'Allowed' });+ expect(approvalStep(held, card({ status: 'sent' }))).toMatchObject({ state: 'done', detail: 'Done' });+ expect(approvalStep(held, card({ status: 'failed', outcome: { certainty: 'not_sent', error: 'quota' } }))).toMatchObject({+ state: 'failed',+ detail: 'quota',+ });+ expect(approvalStep(held, card({ status: 'discarded' }))).toMatchObject({ state: 'skipped', detail: 'You declined' });+ expect(approvalStep(held, card({ status: 'expired' }))).toMatchObject({ state: 'skipped', detail: 'No answer in time' });});});diff --git a/client/src/features/chat/data/approvals.ts b/client/src/features/chat/data/approvals.tsindex 0e577ed4..f1e9dc51 100644--- a/client/src/features/chat/data/approvals.ts+++ b/client/src/features/chat/data/approvals.ts@@ -5,8 +5,10 @@* `set_ask_first`.** - `useChatApprovals(workflowId)`: the session's recent drafts by id, open- * and settled (a reply's cards read theirs here), and how far the server's- * clock is from this one, so countdowns end when the server's windows do.+ * and settled, and every open one however old (a reply's cards read theirs+ * here), and how far the server's clock is from this one, so countdowns+ * end when the server's windows do. `turnApprovalIds` says which cards a+ * turn shows, and `waitsOnOwner` whether a run waits for the owner's OK.* - `useDecideApproval(workflowId)`: send, undo, discard, restore, retry,* dismiss.* The card moves at once and comes back if the server refuses; every click@@ -22,6 +24,9 @@ import { useEffect } from 'react';import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';import { z } from 'zod';import { useWebSocketActions } from '@/contexts/WebSocketContext';+import type { RunSnapshot } from '@/lib/agui/reduceRun';+import { liveApprovalIds, savedApprovalIds } from './parts';+import type { ChatMessage } from './schemas';export const chatApprovalsKey = (workflowId: string) => ['chatApprovals', workflowId] as const;export const askFirstKey = (workflowId: string) => ['askFirst', workflowId] as const;@@ -160,6 +165,24 @@ export function isOpenApproval(approval: ChatApproval, nowMs: number): boolean {}}+/** The cards a turn shows: those its saved reply names and its run+ * announced, then, while the turn holds its run, any other the run made,+ * oldest first. A call can wait for days, longer than the server keeps a+ * run's activities, so the run keeps its cards (RFC-0007 §4.7). */+export function turnApprovalIds(message: ChatMessage | null, run: RunSnapshot | null, approvals: ChatApprovals): string[] {+ const ids = new Set([...savedApprovalIds(message?.parts), ...liveApprovalIds(run?.activities)]);+ if (run) for (const id of [...approvals.order].reverse()) if (approvals.byId.get(id)?.runId === run.runId) ids.add(id);+ return [...ids];+}++/** Whether a run waits for the owner's OK on one of its calls (RFC-0007+ * §4.6). */+export function waitsOnOwner(approvals: ChatApprovals, runId: string | null | undefined): boolean {+ if (!runId) return false;+ for (const approval of approvals.byId.values()) if (approval.runId === runId && approval.waits && approval.status === 'pending') return true;+ return false;+}+/** Seconds left until `until` on the server's clock, never below 0. */export function secondsLeft(until: string | null, offsetMs: number, nowMs = Date.now()): number {if (!until) return 0;@@ -189,9 +212,16 @@ export function useChatApprovals(workflowId: string | null) {return useQuery<ChatApprovals, Error>({queryKey: chatApprovalsKey(workflowId ?? ''),queryFn: async () => {- const reply = await sendRequest<ListReply>('list_approvals', { workflow_id: workflowId, status: 'recent', limit: 100 });- if (reply?.success === false) throw new Error(reply.error || 'Could not load the drafts');- return readApprovals(reply, Date.now());+ // The newest 100, and every one still open: a call can wait for days+ // behind newer ones (RFC-0007 §4.7). An open one not among the newest+ // is older than all of them, so it goes last.+ const [recent, open] = await Promise.all(+ (['recent', 'open'] as const).map((status) => sendRequest<ListReply>('list_approvals', { workflow_id: workflowId, status, limit: 100 })),+ );+ const failed = [recent, open].find((reply) => reply?.success === false);+ if (failed) throw new Error(failed.error || 'Could not load the drafts');+ const rows = (reply: ListReply | undefined) => (Array.isArray(reply?.approvals) ? reply.approvals : []);+ return readApprovals({ ...recent, approvals: [...rows(recent), ...rows(open)] }, Date.now());},enabled: isReady && Boolean(workflowId),// Runs make drafts while no chat is open: always look again on open.diff --git a/client/src/features/chat/turns/AssistantTurn.tsx b/client/src/features/chat/turns/AssistantTurn.tsxindex 34896b47..8e517a92 100644--- a/client/src/features/chat/turns/AssistantTurn.tsx+++ b/client/src/features/chat/turns/AssistantTurn.tsx@@ -10,24 +10,26 @@* it; and a status line says "Thinking" or "Writing · N tok/s" and that Esc* stops it. Text written beside tool calls shows muted until the answer* replaces it. A run that waits for Resume, failed or was stopped says so- * where its answer would be.+ * where its answer would be. While the run waits for the owner's OK on a+ * call, the status line says so, and that call's step follows its card+ * (RFC-0007 §4.7).** `chat-msg chat-msg-bot` (on the text only) is the theme hook Atomic* paints as a bubble.*/import { CircleAlert, Pause, RotateCcw, Square } from 'lucide-react';-import { Suspense, lazy, useMemo, type ReactNode } from 'react';+import { Suspense, lazy, useContext, useMemo, type ReactNode } from 'react';import { Button } from '@/components/ui/button';import { isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';import type { UiStateChange } from '@/lib/jsonRender/uiState';import { cn } from '@/lib/utils';import { ApprovalCard } from '../approval/ApprovalCard';+import { ApprovalsContext } from '../approval/context';+import { NO_APPROVALS, turnApprovalIds, waitsOnOwner, type ChatApproval } from '../data/approvals';import {- liveApprovalIds,liveArtifacts,mergeArtifacts,- savedApprovalIds,savedArtifacts,savedFollowups,savedSources,@@ -50,7 +52,7 @@ import { ArtifactCard } from './ArtifactCard';import { GeneratedUiBlock } from './GeneratedUiBlock';import { FollowUps } from './FollowUps';import { ReplyActions } from './ReplyActions';-import { failureLines, liveLabel, liveText } from './runCopy';+import { approvalStep, failureLines, liveLabel, liveText } from './runCopy';import { SourceChips } from './SourceChips';import { StatusLine } from './StatusLine';import { StepsDisclosure } from './StepsDisclosure';@@ -168,11 +170,28 @@ export function AssistantTurn({() => mergeArtifacts(savedArtifacts(message?.parts), liveArtifacts(run?.activities)),[message?.parts, run?.activities],);- // The drafts it made: named on the saved reply, or arriving with the run.- const approvals = useMemo(- () => [...new Set([...savedApprovalIds(message?.parts), ...liveApprovalIds(run?.activities)])],- [message?.parts, run?.activities],- );+ // The drafts it made: named on the saved reply, arriving with the run, or+ // made by the run it holds.+ const known = useContext(ApprovalsContext)?.approvals ?? NO_APPROVALS;+ const approvals = useMemo(() => turnApprovalIds(message, run, known), [message, run, known]);+ const waiting = live && waitsOnOwner(known, run?.runId);+ // A call its turn waits on: its step follows its card.+ const steps = useMemo(() => {+ if (!work) return null;+ const byCall = new Map<string, ChatApproval>();+ for (const id of approvals) {+ const approval = known.byId.get(id);+ if (approval?.waits && approval.toolCallId) byCall.set(approval.toolCallId, approval);+ }+ if (byCall.size === 0) return work;+ return {+ ...work,+ steps: work.steps.map((step) => {+ const approval = byCall.get(step.stepId);+ return approval ? approvalStep(step, approval) : step;+ }),+ };+ }, [work, approvals, known]);// Only under the latest answer, once it is done, not stopped, and while// the owner is not writing something else.const drafting = useDrafting();@@ -197,8 +216,8 @@ export function AssistantTurn({><ChatAvatar persona={persona} live={live} compact={compact} /><div className="flex min-w-0 flex-1 flex-col gap-2.5">- {work && <StepsDisclosure work={suspended ? { ...work, live: false } : work} compact={compact} />}- {live && !text && <Thinking />}+ {steps && <StepsDisclosure work={suspended ? { ...steps, live: false } : steps} compact={compact} />}+ {live && !text && !waiting && <Thinking />}{text && (<divdata-narration={narration || undefined}@@ -234,7 +253,7 @@ export function AssistantTurn({{live && run && (<StatusLinelabel={controlled && control.state === 'pausing' ? 'Stopping…'- : controlled && control.state === 'resuming' ? 'Resuming…' : liveLabel(run, streaming)}+ : controlled && control.state === 'resuming' ? 'Resuming…' : liveLabel(run, streaming, waiting)}rate={rate}note={liveNote}stopHint={canStop && run.state !== 'stopping' && !(controlled && control.state !== 'running')}diff --git a/client/src/features/chat/turns/runCopy.ts b/client/src/features/chat/turns/runCopy.tsindex c3d3cd4e..0cd79b57 100644--- a/client/src/features/chat/turns/runCopy.ts+++ b/client/src/features/chat/turns/runCopy.ts@@ -6,6 +6,7 @@import type { RunError } from '@/lib/agui/events';import type { RunSnapshot, RunStep } from '@/lib/agui/reduceRun';+import type { ChatApproval } from '../data/approvals';/** The text a run that has not posted its answer shows. */export interface LiveText {@@ -52,12 +53,37 @@ export function failureLines(error: RunError | null, name: string): { headline:}/** The status line's label while a run works (design handoff: "Thinking"- * until text comes, then "Writing"). */-export function liveLabel(run: RunSnapshot, writing: boolean): string {+ * until text comes, then "Writing"; "Waiting for your OK" while it waits on+ * a call, RFC-0007 §4.7). */+export function liveLabel(run: RunSnapshot, writing: boolean, waiting = false): string {if (run.state === 'stopping') return 'Stopping…';+ if (waiting) return 'Waiting for your OK';return writing ? 'Writing' : 'Thinking';}+/** The step of a call its turn waits on, as the call stands now: the+ * server ends the step when it holds the call and never reports it again+ * (RFC-0007 §4.7). */+export function approvalStep(step: RunStep, approval: ChatApproval): RunStep {+ switch (approval.status) {+ case 'pending':+ return { ...step, state: 'running', detail: 'Waiting for your OK' };+ case 'approved':+ case 'sending':+ return { ...step, state: 'running', detail: 'Allowed' };+ case 'sent':+ return { ...step, state: 'done', detail: approval.outcomeLabels.sent };+ case 'failed':+ return { ...step, state: 'failed', detail: approval.outcome?.error ?? undefined };+ case 'discarded':+ return { ...step, state: 'skipped', detail: 'You declined' };+ case 'expired':+ return { ...step, state: 'skipped', detail: 'No answer in time' };+ case 'cancelled':+ return { ...step, state: 'skipped', detail: 'Cancelled' };+ }+}+/** "· 42 tok/s": how fast the answer is coming, a token counted as four* characters; null before a second has passed. */export function writingRate(characters: number, elapsedMs: number): string | null {@@ -83,7 +109,7 @@ export function workLabel(steps: readonly RunStep[], live: boolean, durationMs:/** What a step says under its name. */export function stepDetail(step: RunStep): string | null {- if (step.state === 'skipped') return 'Skipped';+ if (step.state === 'skipped') return step.detail || 'Skipped';if (step.state === 'failed') return step.detail ? `Failed · ${step.detail}` : 'Failed';return step.detail ?? null;}