Skip to content

Self-improving AI Employees for everyone

feat(chat): approval cards and the Ask first chip

trohitg64ee7f0a0a59
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsx
index 9444c161..86b30e4d 100644
--- a/client/src/features/chat/ChatPane.tsx
+++ b/client/src/features/chat/ChatPane.tsx
@@ -10,11 +10,30 @@
* going, whatever else arrives meanwhile, and the next message waits until
* it ends. Meanwhile Send is Stop, and Esc anywhere in the pane stops the
* answer too. A message that does not go comes back into the box.
+ *
+ * What the employee wants to send waits for the owner on a card: on the
+ * reply that made it, or after the conversation for the employee's own work
+ * (data/approvals.ts). Ctrl/Cmd+Enter sends the newest one; the Ask first
+ * chip beside the box changes the rule for everything they send.
*/
-import { useCallback, useImperativeHandle, useLayoutEffect, useMemo, useRef, type KeyboardEvent, type Ref } from 'react';
+import { useCallback, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type Ref } from 'react';
import { cn } from '@/lib/utils';
+import { ApprovalsContext, type ApprovalsValue } from './approval/context';
+import { StandaloneApprovals } from './approval/StandaloneApprovals';
+import { AskFirstChip } from './composer/AskFirstChip';
+import {
+ NO_APPROVALS,
+ isOpenApproval,
+ useApprovalEvents,
+ useAskFirst,
+ useChatApprovals,
+ useDecideApproval,
+ useSetAskFirst,
+ type DecideInput,
+} from './data/approvals';
import { useConversation } from './data/conversation';
+import { liveApprovalIds, savedApprovalIds } from './data/parts';
import { useSendChatMessage, type ChatSendError } from './data/send';
import { useStopChatRun } from './data/stop';
import { useUiStateSync } from './data/uiState';
@@ -104,13 +123,91 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
[sessionId],
);
+ // Drafts waiting for the owner: on the replies that made them, and the
+ // rest (the employee's own work) after the conversation.
+ const workflowId = sessionId === 'default' ? null : sessionId;
+ useApprovalEvents();
+ const approvalsQuery = useChatApprovals(workflowId);
+ const approvals = approvalsQuery.data ?? NO_APPROVALS;
+ const askFirstQuery = useAskFirst(workflowId);
+ const setAskFirst = useSetAskFirst(workflowId ?? '', (message) => notify(message, 'error'));
+ const [deciding, setDeciding] = useState<ReadonlySet<string>>(() => new Set());
+ const decideMutation = useDecideApproval(workflowId ?? '', (error) => notify(error.message, 'error'));
+ const decide = useCallback(
+ (input: DecideInput) => {
+ const id = input.approval.id;
+ setDeciding((current) => new Set(current).add(id));
+ decideMutation.mutate(input, {
+ onSettled: () =>
+ setDeciding((current) => {
+ const next = new Set(current);
+ next.delete(id);
+ return next;
+ }),
+ });
+ },
+ [decideMutation],
+ );
+ const linked = useMemo(() => {
+ const 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);
+ }
+ return ids;
+ }, [turns]);
+ const standalone = useMemo(() => {
+ const now = approvals.receivedAt + approvals.offsetMs;
+ return [...approvals.order]
+ .reverse()
+ .filter((id) => !linked.has(id) && isOpenApproval(approvals.byId.get(id)!, now));
+ }, [approvals, linked]);
+ const approvalsValue = useMemo<ApprovalsValue>(
+ () => ({ approvals, name: persona.name, askFirst: askFirstQuery.data?.askFirst ?? null, compact, decide, deciding }),
+ [approvals, persona.name, askFirstQuery.data?.askFirst, compact, decide, deciding],
+ );
+
+ // Ctrl/Cmd+Enter sends the newest draft still waiting for the owner.
+ const sendNewestDraft = () => {
+ const id = approvals.order.find((candidate) => approvals.byId.get(candidate)?.status === 'pending');
+ const approval = id ? approvals.byId.get(id) : undefined;
+ if (!approval || deciding.has(approval.id)) return false;
+ decide({ approval, decision: 'send' });
+ return true;
+ };
+
const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {
- if (event.key !== 'Escape' || event.defaultPrevented || !lane || stopping) return;
+ if (event.defaultPrevented) return;
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
+ if (sendNewestDraft()) event.preventDefault();
+ return;
+ }
+ if (event.key !== 'Escape' || !lane || stopping) return;
event.preventDefault();
stopAnswer();
};
+ const askFirst = askFirstQuery.data?.askFirst;
+ const chips =
+ workflowId && askFirstQuery.data ? (
+ <AskFirstChip
+ on={askFirst === true}
+ name={persona.name}
+ compact={compact}
+ disabled={setAskFirst.isPending}
+ onChange={(next) =>
+ setAskFirst.mutate(next, {
+ onSuccess: (result) => {
+ if (result.needsApply) notify(`Apply ${persona.name}’s changes for this to cover everything.`, 'info');
+ },
+ })
+ }
+ />
+ ) : null;
+
return (
+ <ApprovalsContext.Provider value={approvalsValue}>
<section aria-label={`Chat with ${persona.name}`} onKeyDown={onKeyDown} className="flex min-h-0 w-full flex-1 flex-col">
<ChatThread
persona={persona}
@@ -119,7 +216,14 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
error={thread.isError && !thread.data}
onRetry={() => void thread.refetch()}
top={host.top}
- afterThread={host.afterThread}
+ afterThread={
+ standalone.length > 0 || host.afterThread ? (
+ <>
+ <StandaloneApprovals ids={standalone} />
+ {host.afterThread}
+ </>
+ ) : null
+ }
emptyState={host.emptyState}
liveNote={host.liveNote}
compact={compact}
@@ -143,12 +247,14 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
stopping={stopping}
compact={compact}
boxRef={boxRef}
+ chips={chips}
/>
)}
{host.footnote && <p className="m-0 text-center text-xs text-fg-muted">{host.footnote}</p>}
</div>
</div>
</section>
+ </ApprovalsContext.Provider>
);
}
diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsx
new file mode 100644
index 00000000..f7754c3b
--- /dev/null
+++ b/client/src/features/chat/__tests__/approvals.test.tsx
@@ -0,0 +1,230 @@
+/**
+ * Drafts waiting for the owner in the chat, against a fake server: a card on
+ * the reply that made it (and the employee's own drafts after the
+ * conversation), Send with Undo while it can, an edit sent with Ctrl+Enter,
+ * Ctrl+Enter anywhere for the newest draft, and the Ask first chip, which
+ * asks before turning off. The card's copy says what really happened.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
+}));
+
+import { resetChatRunStore } from '@/stores/chatRunStore';
+import { approvalView } from '../approval/view';
+import { ChatPane } from '../ChatPane';
+import { isOpenApproval, optimistic, parseApproval, readApprovals, secondsLeft, type ChatApproval } from '../data/approvals';
+import type { ChatHost } from '../host';
+import { useComposerStore } from '../state/composerStore';
+import '../markdown/ReplyMarkdown';
+
+type Wire = Record<string, unknown>;
+
+const NOW = Date.parse('2026-10-04T09:00:00Z');
+
+function summary(patch: Wire = {}): Wire {
+ return {
+ approval_id: 'ap1',
+ workflow_id: 'w1',
+ kind: 'tool_call',
+ status: 'pending',
+ channel: 'WhatsApp',
+ action: 'Send a WhatsApp message',
+ recipient: '447700900123',
+ recipient_label: 'Ana',
+ body: 'Running late, there at 10.',
+ details: [],
+ created_at: '2026-10-04T08:59:00Z',
+ revision: 0,
+ max_length: 4096,
+ editable: true,
+ run_id: 'r1',
+ tool_call_id: 'call_1',
+ ...patch,
+ };
+}
+
+function approval(patch: Wire = {}): ChatApproval {
+ return parseApproval(summary(patch))!;
+}
+
+describe('the card says what happened', () => {
+ const view = (patch: Wire, options: { offsetMs?: number } = {}) =>
+ approvalView(approval(patch), { name: 'Maya', nowMs: NOW, offsetMs: options.offsetMs ?? 0, now: new Date(NOW) });
+
+ it('waits for the owner, then counts down the Undo window', () => {
+ const waiting = view({});
+ expect(waiting.title).toBe('Maya wants to send a WhatsApp message');
+ expect(waiting.pill).toEqual({ label: 'Needs your OK', tone: 'waiting', pulse: true });
+ expect(waiting.footer).toEqual({ kind: 'decide' });
+ expect(view({ status: 'approved', undo_until: '2026-10-04T09:00:04.2Z' }).footer).toEqual({ kind: 'undo', seconds: 5 });
+ // The server's clock is 3 s ahead: its window ends sooner here.
+ expect(view({ status: 'approved', undo_until: '2026-10-04T09:00:04.2Z' }, { offsetMs: 3000 }).footer).toEqual({ kind: 'undo', seconds: 2 });
+ expect(view({ status: 'approved', undo_until: '2026-10-04T08:59:59Z' }).footer).toEqual({ kind: 'sending' });
+ expect(view({ status: 'sending' }).footer).toEqual({ kind: 'sending' });
+ });
+
+ it('a gate’s draft for a paused employee goes on Resume', () => {
+ const paused = view({ kind: 'gate', status: 'approved', undo_until: '2026-10-04T08:59:59Z', deployment_state: 'paused' });
+ expect(paused.footer).toEqual({ kind: 'waiting', text: 'Sends when you resume Maya.' });
+ });
+
+ it('says it went only once it went', () => {
+ const sent = view({ status: 'sent', outcome: { certainty: 'sent', at: '2026-10-04T09:00:05Z' }, approved_by: 'auto' });
+ expect(sent.title).toBe('Message sent');
+ expect(sent.footer.kind === 'sent' && sent.footer.text).toMatch(/^Sent to Ana on WhatsApp at .+, without asking: Ask first was off\.$/);
+ const failed = view({ status: 'failed', outcome: { certainty: 'unknown', error: 'TimeoutError' } });
+ expect(failed.footer).toEqual({ kind: 'failed', text: 'It may have gone out: TimeoutError', unknown: true });
+ expect(view({ status: 'failed', outcome: { certainty: 'not_sent' } }).footer).toEqual({ kind: 'failed', text: 'It didn’t go out.', unknown: false });
+ expect(view({ status: 'expired' }).footer).toEqual({ kind: 'ended', text: 'It waited too long, so it was not sent.' });
+ expect(view({ status: 'cancelled' }).title).toBe('Draft cancelled');
+ });
+
+ it('a discarded draft can come back while its window lasts', () => {
+ const gate = view({ kind: 'gate', status: 'discarded', restore_until: '2026-10-04T09:00:03Z' });
+ expect(gate.footer).toEqual({ kind: 'discarded', text: 'Discarded. Maya won’t send this.', restoreSeconds: 3, canRestore: true });
+ const held = view({ status: 'discarded', restore_until: '2026-10-11T09:00:00Z' });
+ expect(held.footer).toMatchObject({ restoreSeconds: null, canRestore: true });
+ expect(view({ status: 'discarded', restore_until: '2026-10-04T08:00:00Z' }).footer).toMatchObject({ canRestore: false });
+ });
+
+ it('reads the list with the server’s clock, and moves at once on a decision', () => {
+ const read = readApprovals({ success: true, approvals: [summary(), summary(), { nope: 1 }], server_time: '2026-10-04T09:00:02Z' }, NOW);
+ expect(read.order).toEqual(['ap1']);
+ expect(read.offsetMs).toBe(2000);
+ expect(secondsLeft('2026-10-04T09:00:05Z', read.offsetMs, NOW)).toBe(3);
+ expect(isOpenApproval(approval({ status: 'approved', consumed_at: '2026-10-04T09:00:00Z' }), NOW)).toBe(false);
+ expect(optimistic(approval(), 'send', NOW, 0)).toMatchObject({ status: 'approved', undoUntil: '2026-10-04T09:00:05.000Z' });
+ expect(optimistic(approval({ status: 'approved' }), 'undo', NOW, 0)).toMatchObject({ status: 'pending', undoUntil: null });
+ });
+});
+
+// ----- in the chat -----
+
+let server: { approvals: Wire[]; askFirst: boolean | null; decisions: Wire[]; rule: Wire[] };
+let client: QueryClient;
+
+function row(id: string, role: 'user' | 'assistant', text: string, patch: Wire = {}): Wire {
+ return { id, role, text, message: text, timestamp: '2026-10-04T09:00:00Z', run_key: 'g1', ...patch };
+}
+
+const MESSAGES = [
+ row('m1', 'user', 'Tell Ana I’m late', { run_id: 'r1' }),
+ row('a_r1', 'assistant', 'I drafted a WhatsApp to Ana.', { run_id: 'r1', parts: { approvals: [{ approval_id: 'ap1', tool_call_id: 'call_1' }] } }),
+];
+
+function host(): ChatHost {
+ return { kind: 'home', sessionId: 'w1', scope: 'all', persona: { name: 'Maya', colorRole: 'agent' }, composer: 'send', notify: vi.fn() };
+}
+
+function renderPane() {
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(
+ <QueryClientProvider client={client}>
+ <ChatPane host={host()} />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ resetChatRunStore();
+ useComposerStore.setState({ drafts: {} });
+ server = { approvals: [summary()], askFirst: true, decisions: [], rule: [] };
+ 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: [] };
+ 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() };
+ case 'get_ask_first':
+ return { success: true, ask_first: server.askFirst, revision: 0 };
+ case 'set_ask_first':
+ server.rule.push(data);
+ return { success: true, ask_first: data.ask_first, revision: 1, replies_gated: true, needs_apply: false };
+ case 'decide_approval': {
+ server.decisions.push(data);
+ const current = server.approvals[0];
+ const next =
+ data.decision === 'send'
+ ? { ...current, status: 'approved', undo_until: new Date(Date.now() + 5000).toISOString(), revision: 1, ...(data.text ? { body: data.text } : {}) }
+ : data.decision === 'undo'
+ ? { ...current, status: 'pending', revision: 2 }
+ : current;
+ server.approvals = [next];
+ return { success: true, approval: next };
+ }
+ default:
+ return { success: true };
+ }
+ });
+});
+
+describe('a draft in the chat', () => {
+ it('shows on the reply that made it; Send, then Undo while it can', async () => {
+ renderPane();
+ const card = (await screen.findByText('Maya wants to send a WhatsApp message')).closest('[data-approval]') as HTMLElement;
+ const reply = screen.getByText('I drafted a WhatsApp to Ana.').closest('[data-turn="assistant"]') as HTMLElement;
+ expect(reply.contains(card)).toBe(true);
+ expect(within(card).getByText('Ask first is on, so nothing goes out until you send it.')).toBeInTheDocument();
+
+ fireEvent.click(within(card).getByRole('button', { name: /^Send$/ }));
+ await waitFor(() => expect(server.decisions).toHaveLength(1));
+ expect(server.decisions[0]).toMatchObject({ approval_id: 'ap1', decision: 'send' });
+ expect(server.decisions[0]).not.toHaveProperty('text');
+ const undo = await within(card).findByRole('button', { name: /Undo · \ds/ });
+ fireEvent.click(undo);
+ await waitFor(() => expect(server.decisions[1]).toMatchObject({ decision: 'undo' }));
+ expect(await within(card).findByRole('button', { name: /^Send$/ })).toBeInTheDocument();
+ // Every click carries its own key.
+ expect(server.decisions[0].decision_key).not.toBe(server.decisions[1].decision_key);
+ });
+
+ it('sends an edit with Ctrl+Enter', async () => {
+ renderPane();
+ const card = (await screen.findByText('Maya wants to send a WhatsApp message')).closest('[data-approval]') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Edit' }));
+ const box = within(card).getByRole('textbox', { name: 'Edit the draft' });
+ fireEvent.change(box, { target: { value: 'Running late, there at 10:15.' } });
+ fireEvent.keyDown(box, { key: 'Enter', ctrlKey: true });
+ await waitFor(() => expect(server.decisions).toHaveLength(1));
+ expect(server.decisions[0]).toMatchObject({ decision: 'send', text: 'Running late, there at 10:15.' });
+ });
+
+ it('Ctrl+Enter anywhere in the chat sends the newest draft', async () => {
+ renderPane();
+ await screen.findByText('Maya wants to send a WhatsApp message');
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Message Maya' }), { key: 'Enter', ctrlKey: true });
+ await waitFor(() => expect(server.decisions).toHaveLength(1));
+ expect(server.decisions[0]).toMatchObject({ approval_id: 'ap1', decision: 'send' });
+ });
+
+ it('shows the employee’s own drafts after the conversation', async () => {
+ server.approvals = [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('Maya wants to send a message')).toBeInTheDocument();
+ expect(within(own).getByText('Yes, Saturday at 10 works.')).toBeInTheDocument();
+ });
+
+ it('asks before turning Ask first off', async () => {
+ renderPane();
+ const chip = await screen.findByRole('button', { name: 'Ask first' });
+ expect(chip).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.click(chip);
+ const confirm = await screen.findByRole('button', { name: 'Turn off Ask first' });
+ expect(server.rule).toEqual([]);
+ await act(async () => {
+ fireEvent.click(confirm);
+ });
+ await waitFor(() => expect(server.rule).toEqual([{ workflow_id: 'w1', ask_first: false, expected_revision: 0 }]));
+ });
+});
diff --git a/client/src/features/chat/approval/ApprovalCard.tsx b/client/src/features/chat/approval/ApprovalCard.tsx
new file mode 100644
index 00000000..2f0ceefe
--- /dev/null
+++ b/client/src/features/chat/approval/ApprovalCard.tsx
@@ -0,0 +1,416 @@
+/**
+ * A draft waiting for the owner's OK, in the chat (design handoff chat,
+ * "Approval card"): who it goes to, through which app, the message as it
+ * will go, and Discard / Edit / Send. After Send it says when it goes, with
+ * Undo while it can; then that it went (or did not, with Try again). A
+ * discarded draft can be restored while its window lasts. Ctrl/Cmd+Enter in
+ * the edit box sends it.
+ *
+ * The draft itself lives on the server (data/approvals.ts); the card holds
+ * only the edit in progress. `chat-approval` is the theme hook.
+ */
+
+import { Check, Link2, Loader2, MessageCircle, Pause, Pencil, RotateCcw, Send, ShieldCheck, Undo2 } from 'lucide-react';
+import { useContext, useEffect, useId, useLayoutEffect, useState, type KeyboardEvent } from 'react';
+import { ActionButton } from '@/components/ui/action-button';
+import { Button } from '@/components/ui/button';
+import { Textarea } from '@/components/ui/textarea';
+import { cn } from '@/lib/utils';
+import type { ChatApproval } from '../data/approvals';
+import { ApprovalsContext } from './context';
+import { approvalView, needsTicks, type CardTone, type CardView } from './view';
+
+const PILL_TONE: Record<CardTone, string> = {
+ waiting: 'border-action-config-border bg-action-config-soft text-action-config-ink',
+ sending: 'border-action-run-border bg-action-run-soft text-action-run-ink',
+ sent: 'border-action-run-border bg-action-run-soft text-action-run-ink',
+ muted: 'border-border-default bg-bg-hover text-fg-muted',
+ failed: 'border-action-stop-border bg-action-stop-soft text-action-stop-ink',
+};
+
+const DOT_TONE: Record<CardTone, string> = {
+ waiting: 'bg-action-config-ink',
+ sending: 'bg-action-run-ink',
+ sent: 'bg-action-run-ink',
+ muted: 'bg-fg-faint',
+ failed: 'bg-action-stop-ink',
+};
+
+const FRAME: Record<CardTone, string> = {
+ waiting: 'border-action-config-border ring-[3px] ring-action-config-soft',
+ sending: 'border-action-run-border',
+ sent: 'border-action-run-border',
+ muted: 'border-border-default',
+ failed: 'border-action-stop-border',
+};
+
+const HEAD: Record<CardTone, string> = {
+ waiting: 'bg-action-config-soft',
+ sending: 'bg-action-run-soft',
+ sent: 'bg-action-run-soft',
+ muted: '',
+ failed: 'bg-action-stop-soft',
+};
+
+function isMac(): boolean {
+ return typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent || '');
+}
+
+/** The time the card reads: taken again whenever the draft moves, and
+ * every second while a countdown is on screen. */
+function useCardNow(revision: number, ticking: boolean): number {
+ const [now, setNow] = useState(() => Date.now());
+ useLayoutEffect(() => {
+ setNow(Date.now());
+ }, [revision, ticking]);
+ useEffect(() => {
+ if (!ticking) return;
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, [ticking]);
+ return now;
+}
+
+export function ApprovalCard({ approvalId, className }: { approvalId: string; className?: string }) {
+ const shared = useContext(ApprovalsContext);
+ const approval = shared?.approvals.byId.get(approvalId);
+ if (!shared || !approval) return null;
+ return <Card approval={approval} className={className} />;
+}
+
+function Card({ approval, className }: { approval: ChatApproval; className?: string }) {
+ const shared = useContext(ApprovalsContext)!;
+ const { approvals, name, askFirst, compact, decide, deciding } = shared;
+ const [editing, setEditing] = useState(false);
+ const [text, setText] = useState(approval.body);
+ const [subject, setSubject] = useState(approval.subject ?? '');
+ const busy = deciding.has(approval.id);
+ const boxId = useId();
+
+ // A draft that left "pending" ends any edit; a new body (the server's)
+ // shows when not editing.
+ useEffect(() => {
+ if (approval.status !== 'pending') setEditing(false);
+ }, [approval.status]);
+ useEffect(() => {
+ if (!editing) {
+ setText(approval.body);
+ setSubject(approval.subject ?? '');
+ }
+ }, [approval.body, approval.subject, editing]);
+
+ const [ticking, setTicking] = useState(false);
+ const now = useCardNow(approval.revision, ticking);
+ const view: CardView = approvalView(approval, { name, nowMs: now, offsetMs: approvals.offsetMs, editing });
+ const countdown = needsTicks(view);
+ useEffect(() => setTicking(countdown), [countdown]);
+
+ const edited = text.trim() !== approval.body.trim() || (subject.trim() || null) !== (approval.subject ?? null);
+ const tooLong = text.length > approval.maxLength;
+ const canSend = approval.status === 'pending' && !busy && text.trim().length > 0 && !tooLong;
+
+ const send = () => {
+ if (!canSend) return;
+ decide({
+ approval,
+ decision: 'send',
+ ...(edited ? { text: text.trim() } : {}),
+ ...(edited && approval.subject !== null ? { subject: subject.trim() } : {}),
+ });
+ };
+
+ const onBoxKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault();
+ event.stopPropagation();
+ send();
+ }
+ };
+
+ const to = approval.recipientLabel || approval.recipient || 'them';
+ const linked = approval.uiPartId !== null && approval.status === 'pending' && !edited;
+
+ return (
+ <div
+ data-approval={approval.id}
+ data-status={approval.status}
+ className={cn(
+ 'chat-approval flex w-full max-w-136 flex-col overflow-hidden rounded-card border bg-bg-panel shadow-card transition-[border-color,box-shadow] duration-(--dur-slow)',
+ FRAME[view.tone],
+ className,
+ )}
+ >
+ <div className={cn('flex items-center gap-2.5 border-b border-border-default px-3.5 py-2.75 transition-colors duration-(--dur-slow)', HEAD[view.tone])}>
+ <span
+ aria-hidden
+ className="grid size-7.5 flex-none place-items-center rounded-lg border border-node-tool-border bg-action-run-soft text-action-run-ink"
+ >
+ <MessageCircle className="size-3.75" strokeWidth={1.9} />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <span className="text-sm font-semibold text-fg-default">{view.title}</span>
+ <span className="truncate text-xs text-fg-muted">{view.sub}</span>
+ </div>
+ <span className={cn('flex h-6 flex-none items-center gap-1.5 rounded-pill border px-2.25 text-xs font-medium whitespace-nowrap', PILL_TONE[view.pill.tone])}>
+ <span aria-hidden className={cn('size-1.5 rounded-full', DOT_TONE[view.pill.tone], view.pill.pulse && 'opencompany-pip-pulse')} />
+ {view.pill.label}
+ </span>
+ </div>
+
+ <div className={cn('flex flex-col gap-2.5', compact ? 'p-3' : 'p-3.5')}>
+ <div className="flex items-center gap-2 text-xs text-fg-muted">
+ <span aria-hidden className="grid size-5.5 flex-none place-items-center rounded-full bg-action-stop-soft text-2xs font-semibold text-action-stop-ink">
+ {(to.charAt(0) || '?').toUpperCase()}
+ </span>
+ <span className="min-w-0 truncate">
+ To <span className="font-medium text-fg-default">{to}</span>
+ <span className="text-fg-faint"> · {approval.channel}</span>
+ </span>
+ {linked && (
+ <span className="ml-auto flex items-center gap-1.25 font-mono text-2xs font-medium text-action-tools-ink">
+ <Link2 aria-hidden className="size-2.75" strokeWidth={2.2} />
+ Linked to the form above
+ </span>
+ )}
+ </div>
+
+ {editing ? (
+ <div className="flex flex-col gap-1.5">
+ {approval.subject !== null && (
+ <input
+ value={subject}
+ onChange={(event) => setSubject(event.target.value)}
+ aria-label="Subject"
+ className="h-8 rounded-lg border border-action-tools-border bg-bg-input px-3 text-sm text-fg-default outline-none"
+ />
+ )}
+ <Textarea
+ id={boxId}
+ value={text}
+ onChange={(event) => setText(event.target.value)}
+ onKeyDown={onBoxKeyDown}
+ rows={3}
+ aria-label="Edit the draft"
+ autoFocus
+ className="min-h-21 resize-y border-action-tools-border bg-bg-input text-base leading-normal ring-[3px] ring-node-agent-soft"
+ />
+ <span className={cn('self-end font-mono text-2xs font-medium', tooLong ? 'text-action-stop-ink' : 'text-fg-faint')}>
+ {text.length} / {approval.maxLength}
+ </span>
+ </div>
+ ) : (
+ <div className="flex justify-end">
+ <div
+ className={cn(
+ 'flex max-w-[92%] flex-col gap-1 rounded-[14px_4px_14px_14px] border px-3 pt-2.25 pb-1.5 transition-[background-color,border-color,opacity] duration-(--dur-slow)',
+ view.bubble === 'sent' ? 'border-action-run-border bg-action-run-soft' : 'border-border-default bg-bg-elevated',
+ view.bubble === 'struck' && 'opacity-55',
+ )}
+ >
+ {approval.subject && <span className="text-xs font-semibold text-fg-default">{approval.subject}</span>}
+ <span className={cn('text-base leading-normal whitespace-pre-wrap text-fg-default', view.bubble === 'struck' && 'line-through')}>
+ {approval.body || '(no message)'}
+ </span>
+ <span className="flex items-center gap-1 self-end text-2xs text-fg-faint">
+ {view.when}
+ {view.bubble === 'sent' && <Check aria-hidden className="size-3 text-action-save-ink" strokeWidth={2.4} />}
+ </span>
+ </div>
+ </div>
+ )}
+
+ {approval.details.length > 0 && (
+ <dl className="m-0 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
+ {approval.details.map((row) => (
+ <div key={row.label} className="contents">
+ <dt className="text-fg-faint">{row.label}</dt>
+ <dd className="m-0 min-w-0 truncate text-fg-default">{row.value}</dd>
+ </div>
+ ))}
+ </dl>
+ )}
+
+ {view.reassure && (
+ <span className="flex items-center gap-1.5 text-xs text-fg-faint">
+ <ShieldCheck aria-hidden className="size-3" strokeWidth={2} />
+ {askFirst ? 'Ask first is on, so nothing goes out until you send it.' : 'Nothing goes out until you send it.'}
+ </span>
+ )}
+ </div>
+
+ <Footer view={view} approval={approval} busy={busy} editing={editing} canSend={canSend} onSend={send} onToggleEdit={() => setEditing((on) => !on)} />
+ </div>
+ );
+}
+
+function Footer({
+ view,
+ approval,
+ busy,
+ editing,
+ canSend,
+ onSend,
+ onToggleEdit,
+}: {
+ view: CardView;
+ approval: ChatApproval;
+ busy: boolean;
+ editing: boolean;
+ canSend: boolean;
+ onSend: () => void;
+ onToggleEdit: () => void;
+}) {
+ const { decide } = useContext(ApprovalsContext)!;
+ const footer = view.footer;
+ const bar = 'flex flex-wrap items-center gap-2 border-t border-border-default px-3.5 py-2.5';
+
+ if (footer.kind === 'decide') {
+ return (
+ <div className={cn(bar, 'bg-bg-app')}>
+ <Button
+ variant="quiet"
+ size="sm"
+ disabled={busy}
+ onClick={() => decide({ approval, decision: 'discard' })}
+ className="font-semibold hover:bg-action-stop-soft hover:text-action-stop-ink"
+ >
+ Discard
+ </Button>
+ {approval.editable && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy}
+ aria-pressed={editing}
+ onClick={onToggleEdit}
+ className={cn('gap-1.5 font-semibold', editing && 'border-action-tools-border bg-action-tools-soft text-action-tools-ink')}
+ >
+ <Pencil aria-hidden className="size-3.25" />
+ {editing ? 'Done' : 'Edit'}
+ </Button>
+ )}
+ <span aria-hidden className="ml-auto flex items-center font-mono text-2xs font-medium text-fg-faint">
+ <kbd className="rounded-sm border border-border-default bg-bg-panel px-1.25 py-px font-[inherit]">{isMac() ? '⌘ ↵' : 'Ctrl ↵'}</kbd>
+ </span>
+ <ActionButton intent="run" disabled={!canSend} onClick={onSend} className="gap-1.75">
+ <Send aria-hidden className="size-3.25" />
+ Send
+ </ActionButton>
+ </div>
+ );
+ }
+ if (footer.kind === 'undo') {
+ return (
+ <div className={cn(bar, 'bg-bg-app text-xs text-fg-muted')} aria-live="off">
+ <Loader2 aria-hidden className="opencompany-spinner size-3.5 text-action-run-ink" />
+ <span className="flex-1">Sends in {footer.seconds}s</span>
+ <Button variant="outline" size="sm" disabled={busy} onClick={() => decide({ approval, decision: 'undo' })} className="gap-1.5 font-semibold tabular-nums">
+ <Undo2 aria-hidden className="size-3.25" />
+ Undo · {footer.seconds}s
+ </Button>
+ </div>
+ );
+ }
+ if (footer.kind === 'sending') {
+ return (
+ <div className={cn(bar, 'bg-bg-app text-xs text-fg-muted')} role="status">
+ <Loader2 aria-hidden className="opencompany-spinner size-3.5 text-action-run-ink" />
+ Sending on {approval.channel}…
+ </div>
+ );
+ }
+ if (footer.kind === 'waiting') {
+ return (
+ <div className={cn(bar, 'bg-bg-app text-xs text-fg-muted')} role="status">
+ <Pause aria-hidden className="size-3.5" />
+ {footer.text}
+ </div>
+ );
+ }
+ if (footer.kind === 'sent') {
+ return (
+ <div className={cn(bar, 'bg-action-run-soft')} role="status">
+ <span aria-hidden className="grid size-5 flex-none place-items-center rounded-full border border-action-run-border bg-action-run-soft">
+ <Check className="opencompany-draw size-2.75 text-action-run-ink" strokeWidth={3} />
+ </span>
+ <span className="min-w-0 flex-1 text-xs text-fg-default">{footer.text}</span>
+ </div>
+ );
+ }
+ if (footer.kind === 'discarded') {
+ return (
+ <div className={cn(bar, 'bg-bg-app')}>
+ <span className="min-w-0 flex-1 text-xs text-fg-muted">{footer.text}</span>
+ {footer.canRestore && (
+ <Button variant="outline" size="sm" disabled={busy} onClick={() => decide({ approval, decision: 'restore' })} className="gap-1.5 font-semibold tabular-nums">
+ <RotateCcw aria-hidden className="size-3.25" />
+ {footer.restoreSeconds !== null ? `Restore · ${footer.restoreSeconds}s` : 'Restore'}
+ </Button>
+ )}
+ </div>
+ );
+ }
+ if (footer.kind === 'failed') {
+ return <FailedFooter className={bar} text={footer.text} unknown={footer.unknown} busy={busy} onRetry={(confirm) => decide({ approval, decision: 'retry', confirm })} />;
+ }
+ return (
+ <div className={cn(bar, 'bg-bg-app')}>
+ <span className="text-xs text-fg-muted">{footer.text}</span>
+ </div>
+ );
+}
+
+/** A send that did not go: Try again. One that broke off may have gone,
+ * so sending it again asks once more first. */
+function FailedFooter({
+ className,
+ text,
+ unknown,
+ busy,
+ onRetry,
+}: {
+ className: string;
+ text: string;
+ unknown: boolean;
+ busy: boolean;
+ onRetry: (confirm: boolean) => void;
+}) {
+ const [confirming, setConfirming] = useState(false);
+ if (confirming) {
+ return (
+ <div className={cn(className, 'bg-action-stop-soft')}>
+ <span className="min-w-0 flex-1 text-xs text-fg-default">It may already have gone out. Send it again anyway?</span>
+ <Button variant="quiet" size="sm" onClick={() => setConfirming(false)} className="font-semibold">
+ Keep it
+ </Button>
+ <ActionButton
+ intent="stop"
+ disabled={busy}
+ onClick={() => {
+ setConfirming(false);
+ onRetry(true);
+ }}
+ >
+ Send again
+ </ActionButton>
+ </div>
+ );
+ }
+ return (
+ <div className={cn(className, 'bg-action-stop-soft')}>
+ <span className="min-w-0 flex-1 text-xs text-fg-default">{text}</span>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy}
+ onClick={() => (unknown ? setConfirming(true) : onRetry(false))}
+ className="gap-1.5 font-semibold"
+ >
+ <RotateCcw aria-hidden className="size-3.25" />
+ {unknown ? 'Send again' : 'Try again'}
+ </Button>
+ </div>
+ );
+}
+
+export default ApprovalCard;
diff --git a/client/src/features/chat/approval/StandaloneApprovals.tsx b/client/src/features/chat/approval/StandaloneApprovals.tsx
new file mode 100644
index 00000000..2b7a3506
--- /dev/null
+++ b/client/src/features/chat/approval/StandaloneApprovals.tsx
@@ -0,0 +1,21 @@
+/**
+ * Drafts waiting for the owner that no reply in view made (design handoff
+ * chat, "StandaloneApprovalRow"): replies to customers the employee drafted
+ * in its own work, or a draft whose reply is out of view. Oldest first,
+ * after the conversation.
+ */
+
+import { ApprovalCard } from './ApprovalCard';
+
+export function StandaloneApprovals({ ids }: { ids: readonly string[] }) {
+ if (ids.length === 0) return null;
+ return (
+ <section aria-label="Drafts waiting for you" className="flex flex-col gap-3">
+ {ids.map((id) => (
+ <ApprovalCard key={id} approvalId={id} />
+ ))}
+ </section>
+ );
+}
+
+export default StandaloneApprovals;
diff --git a/client/src/features/chat/approval/context.ts b/client/src/features/chat/approval/context.ts
new file mode 100644
index 00000000..d4e1ecce
--- /dev/null
+++ b/client/src/features/chat/approval/context.ts
@@ -0,0 +1,22 @@
+/**
+ * What a chat's approval cards share (set by ChatPane): the session's drafts,
+ * who answers, the Ask first rule, and how to decide a draft. A card outside
+ * a chat renders nothing.
+ */
+
+import { createContext } from 'react';
+import type { ChatApprovals, DecideInput } from '../data/approvals';
+
+export interface ApprovalsValue {
+ approvals: ChatApprovals;
+ /** Who drafted them ("Maya wants to send ..."). */
+ name: string;
+ /** The workflow's live rule; null when it has none. */
+ askFirst: boolean | null;
+ compact: boolean;
+ decide: (input: DecideInput) => void;
+ /** Drafts with a decision on its way to the server. */
+ deciding: ReadonlySet<string>;
+}
+
+export const ApprovalsContext = createContext<ApprovalsValue | null>(null);
diff --git a/client/src/features/chat/approval/view.ts b/client/src/features/chat/approval/view.ts
new file mode 100644
index 00000000..67eead82
--- /dev/null
+++ b/client/src/features/chat/approval/view.ts
@@ -0,0 +1,188 @@
+/**
+ * What an approval card says in each state (design handoff chat,
+ * "Approval card"), as plain data so the copy is testable on its own:
+ *
+ * - pending (and editing): "{name} wants to send a WhatsApp message", Needs
+ * your OK, Discard / Edit / Send;
+ * - approved, inside the Undo window: Sending, "Sends in Ns" with Undo;
+ * - sending: Sending, a spinner;
+ * - sent (and a gate's draft once it went through): Sent, with when and to
+ * whom, and whether Ask first was off;
+ * - discarded: Discarded, with Restore while it can;
+ * - failed: not sent, or may have gone (the call broke off), with Try again;
+ * - expired, cancelled: why it never went.
+ *
+ * Copy says what really happens: a draft is "sent" only once it went.
+ */
+
+import { timeLabel } from '../thread/timeLabel';
+import { secondsLeft, type ChatApproval } from '../data/approvals';
+
+export type CardTone = 'waiting' | 'sending' | 'sent' | 'muted' | 'failed';
+
+export type CardFooter =
+ | { kind: 'decide' }
+ | { kind: 'undo'; seconds: number }
+ | { kind: 'sending' }
+ /** Approved, and its run waits for Resume before it goes. */
+ | { kind: 'waiting'; text: string }
+ | { kind: 'sent'; text: string }
+ | { kind: 'discarded'; text: string; restoreSeconds: number | null; canRestore: boolean }
+ | { kind: 'failed'; text: string; unknown: boolean }
+ | { kind: 'ended'; text: string };
+
+export interface CardView {
+ title: string;
+ sub: string;
+ pill: { label: string; tone: CardTone; pulse: boolean };
+ /** The card's frame: a ring while it waits for the owner. */
+ tone: CardTone;
+ /** How the message preview reads. */
+ bubble: 'draft' | 'sent' | 'struck';
+ /** The small line inside the preview. */
+ when: string;
+ footer: CardFooter;
+ /** "Ask first is on, so nothing goes out until you send it." */
+ reassure: boolean;
+}
+
+function lowerFirst(text: string): string {
+ return text ? text.charAt(0).toLowerCase() + text.slice(1) : text;
+}
+
+function nouns(approval: ChatApproval): { sent: string; failed: string } {
+ const action = (approval.action ?? '').toLowerCase();
+ if (action.includes('email')) return { sent: 'Email sent', failed: 'Email not sent' };
+ if (action.includes('invite')) return { sent: 'Invites sent', failed: 'Invites not sent' };
+ if (action.includes('share')) return { sent: 'File shared', failed: 'File not shared' };
+ return { sent: 'Message sent', failed: 'Message not sent' };
+}
+
+export interface ViewOptions {
+ name: string;
+ nowMs: number;
+ offsetMs: number;
+ editing?: boolean;
+ now?: Date;
+}
+
+export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, editing = false, now = new Date(nowMs) }: ViewOptions): CardView {
+ const to = approval.recipientLabel || approval.recipient || 'them';
+ const channel = approval.channel || 'the app';
+ const drafted = timeLabel(approval.createdAt, now);
+ const sub = drafted ? `${channel} · drafted ${/\d/.test(drafted.charAt(0)) ? 'at ' : ''}${drafted}` : channel;
+ const noun = nouns(approval);
+ const action = approval.action ? lowerFirst(approval.action) : 'send a message';
+
+ switch (approval.status) {
+ case 'pending':
+ return {
+ title: `${name} wants to ${action}`,
+ sub,
+ pill: editing ? { label: 'Editing', tone: 'waiting', pulse: false } : { label: 'Needs your OK', tone: 'waiting', pulse: true },
+ tone: 'waiting',
+ bubble: 'draft',
+ when: 'Draft',
+ footer: { kind: 'decide' },
+ reassure: true,
+ };
+ case 'approved': {
+ if (approval.consumedAt === null) {
+ const seconds = secondsLeft(approval.undoUntil, offsetMs, nowMs);
+ const paused = approval.kind === 'gate' && (approval.deploymentState === 'paused' || approval.deploymentState === 'pausing');
+ const footer: CardFooter =
+ seconds > 0 ? { kind: 'undo', seconds } : paused ? { kind: 'waiting', text: `Sends when you resume ${name}.` } : { kind: 'sending' };
+ return {
+ title: `${name} is sending it`,
+ sub,
+ pill: { label: paused && seconds === 0 ? 'Waiting' : 'Sending', tone: 'sending', pulse: !(paused && seconds === 0) },
+ tone: 'sending',
+ bubble: 'draft',
+ when: 'Sending',
+ footer,
+ reassure: false,
+ };
+ }
+ const at = timeLabel(approval.consumedAt, now);
+ return sentView(approval, noun.sent, sub, to, channel, at);
+ }
+ case 'sending':
+ return {
+ title: `${name} is sending it`,
+ sub,
+ pill: { label: 'Sending', tone: 'sending', pulse: true },
+ tone: 'sending',
+ bubble: 'draft',
+ when: 'Sending',
+ footer: { kind: 'sending' },
+ reassure: false,
+ };
+ case 'sent':
+ return sentView(approval, noun.sent, sub, to, channel, timeLabel(approval.outcome?.at ?? approval.consumedAt, now));
+ case 'discarded': {
+ const restoreSeconds = approval.kind === 'gate' ? secondsLeft(approval.restoreUntil, offsetMs, nowMs) : null;
+ const canRestore = approval.kind === 'gate' ? (restoreSeconds ?? 0) > 0 : secondsLeft(approval.restoreUntil, offsetMs, nowMs) > 0;
+ return {
+ title: 'Draft discarded',
+ sub,
+ pill: { label: 'Discarded', tone: 'muted', pulse: false },
+ tone: 'muted',
+ bubble: 'struck',
+ when: 'Not sent',
+ footer: { kind: 'discarded', text: `Discarded. ${name} won’t send this.`, restoreSeconds, canRestore },
+ reassure: false,
+ };
+ }
+ case 'failed': {
+ const unknown = approval.outcome?.certainty === 'unknown';
+ const why = approval.outcome?.error ? `: ${approval.outcome.error}` : '.';
+ return {
+ title: noun.failed,
+ sub,
+ pill: { label: unknown ? 'May have sent' : 'Didn’t send', tone: 'failed', pulse: false },
+ tone: 'failed',
+ bubble: 'draft',
+ when: 'Not sent',
+ footer: { kind: 'failed', text: unknown ? `It may have gone out${why}` : `It didn’t go out${why}`, unknown },
+ reassure: false,
+ };
+ }
+ case 'expired':
+ return endedView('Draft expired', 'Expired', sub, 'It waited too long, so it was not sent.');
+ case 'cancelled':
+ return endedView('Draft cancelled', 'Cancelled', sub, 'Not sent: the conversation it belonged to ended.');
+ }
+}
+
+function sentView(approval: ChatApproval, title: string, sub: string, to: string, channel: string, at: string): CardView {
+ const when = at ? ` at ${at}` : '';
+ const auto = approval.approvedBy === 'auto' ? ', without asking: Ask first was off' : '';
+ return {
+ title,
+ sub,
+ pill: { label: 'Sent', tone: 'sent', pulse: false },
+ tone: 'sent',
+ bubble: 'sent',
+ when: at || 'Sent',
+ footer: { kind: 'sent', text: `Sent to ${to} on ${channel}${when}${auto}.` },
+ reassure: false,
+ };
+}
+
+function endedView(title: string, label: string, sub: string, text: string): CardView {
+ return {
+ title,
+ sub,
+ pill: { label, tone: 'muted', pulse: false },
+ tone: 'muted',
+ bubble: 'struck',
+ when: 'Not sent',
+ footer: { kind: 'ended', text },
+ reassure: false,
+ };
+}
+
+/** Whether the card needs a tick every second (a countdown on screen). */
+export function needsTicks(view: CardView): boolean {
+ return view.footer.kind === 'undo' || (view.footer.kind === 'discarded' && view.footer.restoreSeconds !== null && view.footer.canRestore);
+}
diff --git a/client/src/features/chat/composer/AskFirstChip.tsx b/client/src/features/chat/composer/AskFirstChip.tsx
new file mode 100644
index 00000000..61ec3883
--- /dev/null
+++ b/client/src/features/chat/composer/AskFirstChip.tsx
@@ -0,0 +1,74 @@
+/**
+ * Ask first, beside the message box (design handoff chat, "Composer"): while
+ * it is on, anything the employee would send to someone waits for the
+ * owner's OK on a card in the chat. It changes the workflow's live rule
+ * (`set_ask_first`), with no restart. Turning it off asks first, since from
+ * then on messages go without a card to stop them.
+ */
+
+import { ShieldCheck } from 'lucide-react';
+import { useState } from 'react';
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@/components/ui/alert-dialog';
+import { Toggle } from '@/components/ui/toggle';
+import { cn } from '@/lib/utils';
+
+export function AskFirstChip({
+ on,
+ name,
+ onChange,
+ disabled = false,
+ compact = false,
+}: {
+ on: boolean;
+ name: string;
+ onChange: (next: boolean) => void;
+ disabled?: boolean;
+ compact?: boolean;
+}) {
+ const [confirming, setConfirming] = useState(false);
+ return (
+ <>
+ <Toggle
+ variant="chips"
+ size="sm"
+ pressed={on}
+ disabled={disabled}
+ onPressedChange={(next) => (next ? onChange(true) : setConfirming(true))}
+ aria-label="Ask first"
+ title={on ? `${name} asks you before sending anything` : `${name} sends without asking`}
+ className={cn(
+ 'gap-1.25 data-[state=on]:border-action-config-border data-[state=on]:bg-action-config-soft data-[state=on]:text-action-config-ink',
+ compact && 'h-6 px-2',
+ )}
+ >
+ <ShieldCheck aria-hidden className="size-3.25" strokeWidth={2} />
+ Ask first
+ </Toggle>
+ <AlertDialog open={confirming} onOpenChange={setConfirming}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Let {name} send without asking?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Messages, emails and invites {name} writes will go out straight away, without a card for you to check first.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep asking</AlertDialogCancel>
+ <AlertDialogAction onClick={() => onChange(false)}>Turn off Ask first</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+export default AskFirstChip;
diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsx
index 636e4b8c..f653703c 100644
--- a/client/src/features/chat/composer/Composer.tsx
+++ b/client/src/features/chat/composer/Composer.tsx
@@ -12,7 +12,7 @@
*/
import { ArrowUp, Square } from 'lucide-react';
-import type { KeyboardEvent, RefObject } from 'react';
+import type { KeyboardEvent, ReactNode, RefObject } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { isSendKey } from '@/lib/composerKeys';
@@ -35,9 +35,11 @@ export interface ComposerProps {
compact: boolean;
/** The text box, for the host's focus requests. */
boxRef: RefObject<HTMLTextAreaElement | null>;
+ /** Chips beside the button (Ask first). */
+ chips?: ReactNode;
}
-export function Composer({ sessionId, name, ready, busy, onSend, onStop, stopping = false, compact, boxRef }: ComposerProps) {
+export function Composer({ sessionId, name, ready, busy, onSend, onStop, stopping = false, compact, boxRef, chips }: ComposerProps) {
const draft = useComposerDraft(sessionId);
const setText = useComposerStore((state) => state.setText);
useAutoGrow(boxRef, draft.text);
@@ -97,7 +99,17 @@ export function Composer({ sessionId, name, ready, busy, onSend, onStop, stoppin
compact ? 'py-1 text-sm leading-normal' : 'py-1.5 text-md leading-normal',
)}
/>
- {compact ? button : <div className="flex items-center justify-end gap-1.5">{button}</div>}
+ {compact ? (
+ <div className="flex shrink-0 items-center gap-1.5">
+ {chips}
+ {button}
+ </div>
+ ) : (
+ <div className="flex items-center gap-1.5">
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">{chips}</div>
+ {button}
+ </div>
+ )}
</div>
);
}
diff --git a/client/src/features/chat/data/approvals.ts b/client/src/features/chat/data/approvals.ts
new file mode 100644
index 00000000..20b52604
--- /dev/null
+++ b/client/src/features/chat/data/approvals.ts
@@ -0,0 +1,392 @@
+/**
+ * What the employee wants to send and waits for the owner's OK, and the Ask
+ * first rule (docs-internal/chat_protocol.md, "Approvals"), as TanStack
+ * queries over `list_approvals` / `decide_approval` / `get_ask_first` /
+ * `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.
+ * - `useDecideApproval(workflowId)`: send, undo, discard, restore, retry.
+ * The card moves at once and comes back if the server refuses; every click
+ * carries a fresh `decision_key`, so a replayed request acts once. Errors
+ * reach the owner through the hook (`onError`), never the click.
+ * - `useAskFirst` / `useSetAskFirst`: the workflow's live rule.
+ * - `applyApprovalEvent`: an `approval_lifecycle` broadcast (identity only)
+ * refetches the session's drafts.
+ */
+
+import { useEffect } from 'react';
+import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';
+import { z } from 'zod';
+import { useWebSocketActions } from '@/contexts/WebSocketContext';
+
+export const chatApprovalsKey = (workflowId: string) => ['chatApprovals', workflowId] as const;
+export const askFirstKey = (workflowId: string) => ['askFirst', workflowId] as const;
+
+export type ApprovalStatus = 'pending' | 'approved' | 'sending' | 'sent' | 'failed' | 'discarded' | 'expired' | 'cancelled';
+
+const STATUSES: readonly ApprovalStatus[] = ['pending', 'approved', 'sending', 'sent', 'failed', 'discarded', 'expired', 'cancelled'];
+
+const optionalText = z
+ .string()
+ .nullable()
+ .optional()
+ .catch(undefined)
+ .transform((value) => (typeof value === 'string' && value ? value : null));
+
+const summarySchema = z
+ .object({
+ approval_id: z.string().min(1),
+ workflow_id: z.string().catch(''),
+ kind: z.enum(['gate', 'tool_call']).catch('gate'),
+ status: z.enum(STATUSES as [ApprovalStatus, ...ApprovalStatus[]]).catch('pending'),
+ channel: z.string().catch(''),
+ action: optionalText,
+ recipient: z.string().catch(''),
+ recipient_label: z.string().catch(''),
+ subject: optionalText,
+ body: z.string().catch(''),
+ context_excerpt: optionalText,
+ details: z.array(z.object({ label: z.string(), value: z.string() })).catch([]),
+ created_at: optionalText,
+ expires_at: optionalText,
+ revision: z.number().catch(0),
+ max_length: z.number().int().positive().catch(20000),
+ editable: z.boolean().catch(false),
+ approved_by: z.enum(['owner', 'auto']).optional().catch(undefined),
+ edited: z.boolean().optional().catch(undefined),
+ undo_until: optionalText,
+ restore_until: optionalText,
+ consumed_at: optionalText,
+ outcome: z
+ .object({
+ certainty: z.enum(['sent', 'not_sent', 'unknown']).catch('unknown'),
+ error: z.string().optional().catch(undefined),
+ at: z.string().optional().catch(undefined),
+ })
+ .optional()
+ .catch(undefined),
+ run_id: optionalText,
+ tool_call_id: optionalText,
+ ui_part_id: optionalText,
+ deployment_state: optionalText,
+ })
+ .transform((raw) => ({
+ id: raw.approval_id,
+ workflowId: raw.workflow_id,
+ kind: raw.kind,
+ status: raw.status,
+ channel: raw.channel,
+ action: raw.action,
+ recipient: raw.recipient,
+ recipientLabel: raw.recipient_label || raw.recipient,
+ subject: raw.subject,
+ body: raw.body,
+ contextExcerpt: raw.context_excerpt,
+ details: raw.details,
+ createdAt: raw.created_at,
+ expiresAt: raw.expires_at,
+ revision: raw.revision,
+ maxLength: raw.max_length,
+ editable: raw.editable,
+ approvedBy: raw.approved_by ?? null,
+ edited: raw.edited === true,
+ undoUntil: raw.undo_until,
+ restoreUntil: raw.restore_until,
+ consumedAt: raw.consumed_at,
+ outcome: raw.outcome ? { certainty: raw.outcome.certainty, error: raw.outcome.error ?? null, at: raw.outcome.at ?? null } : null,
+ runId: raw.run_id,
+ toolCallId: raw.tool_call_id,
+ uiPartId: raw.ui_part_id,
+ deploymentState: raw.deployment_state,
+ }));
+
+export type ChatApproval = z.output<typeof summarySchema>;
+
+export function parseApproval(raw: unknown): ChatApproval | null {
+ const parsed = summarySchema.safeParse(raw);
+ return parsed.success ? parsed.data : null;
+}
+
+export interface ChatApprovals {
+ byId: ReadonlyMap<string, ChatApproval>;
+ /** Newest first. */
+ order: readonly string[];
+ /** The server's clock minus this one's, in ms. */
+ offsetMs: number;
+ /** When this list arrived (this clock). */
+ receivedAt: number;
+}
+
+export const NO_APPROVALS: ChatApprovals = { byId: new Map(), order: [], offsetMs: 0, receivedAt: 0 };
+
+/** Still the owner's to act on, or on its way. */
+export function isOpenApproval(approval: ChatApproval, nowMs: number): boolean {
+ switch (approval.status) {
+ case 'pending':
+ case 'sending':
+ case 'failed':
+ return true;
+ case 'approved':
+ return approval.consumedAt === null;
+ case 'discarded':
+ return approval.restoreUntil !== null && Date.parse(approval.restoreUntil) > nowMs;
+ default:
+ 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;
+ const end = Date.parse(until);
+ if (Number.isNaN(end)) return 0;
+ return Math.max(0, Math.ceil((end - (nowMs + offsetMs)) / 1000));
+}
+
+type ListReply = { success?: boolean; approvals?: unknown; server_time?: string; error?: string };
+
+export function readApprovals(reply: ListReply | undefined, receivedAt: number): ChatApprovals {
+ const list = Array.isArray(reply?.approvals) ? reply.approvals : [];
+ const byId = new Map<string, ChatApproval>();
+ const order: string[] = [];
+ for (const raw of list) {
+ const approval = parseApproval(raw);
+ if (!approval || byId.has(approval.id)) continue;
+ byId.set(approval.id, approval);
+ order.push(approval.id);
+ }
+ const serverMs = reply?.server_time ? Date.parse(reply.server_time) : Number.NaN;
+ return { byId, order, offsetMs: Number.isNaN(serverMs) ? 0 : serverMs - receivedAt, receivedAt };
+}
+
+export function useChatApprovals(workflowId: string | null) {
+ const { sendRequest, isReady } = useWebSocketActions();
+ 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());
+ },
+ enabled: isReady && Boolean(workflowId),
+ // Runs make drafts while no chat is open: always look again on open.
+ refetchOnMount: 'always',
+ staleTime: 0,
+ });
+}
+
+export type Decision = 'send' | 'undo' | 'discard' | 'restore' | 'retry';
+
+export interface DecideInput {
+ approval: ChatApproval;
+ decision: Decision;
+ text?: string;
+ subject?: string;
+ confirm?: boolean;
+}
+
+export class DecideError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+const DECIDE_ERRORS: Record<string, string> = {
+ already_decided: 'That draft was already handled.',
+ expired: 'That draft expired before it was sent.',
+ cancelled: 'That draft was cancelled.',
+ too_late: 'Too late: it has already gone.',
+ approval_conflict: 'That draft changed meanwhile. Look again.',
+ send_unavailable: 'Nothing can send it right now. Try again in a moment.',
+ not_found: 'That draft is gone.',
+ invalid_request: 'That can’t be sent as it is.',
+};
+
+export function decisionKey(): string {
+ try {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
+ } catch {
+ // Not a secure context.
+ }
+ return `k-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
+}
+
+/** What the card shows while the server answers. */
+export function optimistic(approval: ChatApproval, decision: Decision, nowMs: number, offsetMs: number): ChatApproval {
+ const serverNow = nowMs + offsetMs;
+ const soon = (seconds: number) => new Date(serverNow + seconds * 1000).toISOString();
+ switch (decision) {
+ case 'send':
+ case 'retry':
+ return { ...approval, status: 'approved', undoUntil: soon(5), outcome: null };
+ case 'undo':
+ case 'restore':
+ return { ...approval, status: 'pending', undoUntil: null, restoreUntil: null };
+ case 'discard':
+ return { ...approval, status: 'discarded', restoreUntil: approval.kind === 'gate' ? soon(5) : approval.expiresAt };
+ }
+}
+
+type DecideReply = { success?: boolean; error?: string; detail?: string; approval?: unknown };
+
+function replace(data: ChatApprovals | undefined, approval: ChatApproval): ChatApprovals | undefined {
+ if (!data) return data;
+ const byId = new Map(data.byId);
+ byId.set(approval.id, approval);
+ const order = data.order.includes(approval.id) ? data.order : [approval.id, ...data.order];
+ return { ...data, byId, order };
+}
+
+export function useDecideApproval(workflowId: string, onError?: (error: DecideError, input: DecideInput) => void) {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ const key = chatApprovalsKey(workflowId);
+ return useMutation<ChatApproval | null, DecideError, DecideInput, { previous: ChatApprovals | undefined }>({
+ mutationFn: async ({ approval, decision, text, subject, confirm }) => {
+ let reply: DecideReply | undefined;
+ try {
+ reply = await sendRequest<DecideReply>('decide_approval', {
+ approval_id: approval.id,
+ decision,
+ decision_key: decisionKey(),
+ ...(text !== undefined ? { text } : {}),
+ ...(subject !== undefined ? { subject } : {}),
+ ...(confirm ? { confirm: true } : {}),
+ });
+ } catch {
+ throw new DecideError('transport', 'That didn’t reach the server. Try again.');
+ }
+ const current = parseApproval(reply?.approval);
+ if (reply?.success === false) {
+ if (current) queryClient.setQueryData<ChatApprovals>(key, (data) => replace(data, current));
+ const code = reply.error || 'failed';
+ throw new DecideError(code, reply.detail || DECIDE_ERRORS[code] || 'That didn’t work. Try again.');
+ }
+ return current;
+ },
+ onMutate: async ({ approval, decision }) => {
+ await queryClient.cancelQueries({ queryKey: key });
+ const previous = queryClient.getQueryData<ChatApprovals>(key);
+ const offsetMs = previous?.offsetMs ?? 0;
+ queryClient.setQueryData<ChatApprovals>(key, (data) => replace(data, optimistic(approval, decision, Date.now(), offsetMs)));
+ return { previous };
+ },
+ onSuccess: (approval) => {
+ if (approval) queryClient.setQueryData<ChatApprovals>(key, (data) => replace(data, approval));
+ },
+ onError: (error, input, context) => {
+ // The refusal carried the draft as it is: keep that. Otherwise put
+ // the card back.
+ if (context && error.code === 'transport') queryClient.setQueryData(key, context.previous);
+ onError?.(error, input);
+ },
+ onSettled: () => {
+ void queryClient.invalidateQueries({ queryKey: key });
+ },
+ });
+}
+
+export interface AskFirst {
+ /** null: the workflow has no rule (its tool calls are never held). */
+ askFirst: boolean | null;
+ revision: number;
+}
+
+export function useAskFirst(workflowId: string | null) {
+ const { sendRequest, isReady } = useWebSocketActions();
+ return useQuery<AskFirst, Error>({
+ queryKey: askFirstKey(workflowId ?? ''),
+ queryFn: async () => {
+ const reply = await sendRequest<{ success?: boolean; ask_first?: unknown; revision?: unknown; error?: string }>('get_ask_first', {
+ workflow_id: workflowId,
+ });
+ if (reply?.success === false) throw new Error(reply.error || 'Could not read Ask first');
+ return {
+ askFirst: typeof reply?.ask_first === 'boolean' ? reply.ask_first : null,
+ revision: typeof reply?.revision === 'number' ? reply.revision : 0,
+ };
+ },
+ enabled: isReady && Boolean(workflowId),
+ refetchOnMount: 'always',
+ staleTime: 0,
+ });
+}
+
+export interface SetAskFirstResult extends AskFirst {
+ repliesGated: boolean;
+ needsApply: boolean;
+}
+
+export function useSetAskFirst(workflowId: string, onError?: (message: string) => void) {
+ const { sendRequest } = useWebSocketActions();
+ const queryClient = useQueryClient();
+ const key = askFirstKey(workflowId);
+ return useMutation<SetAskFirstResult, Error, boolean, { previous: AskFirst | undefined }>({
+ mutationFn: async (askFirst) => {
+ const current = queryClient.getQueryData<AskFirst>(key);
+ const reply = await sendRequest<{
+ success?: boolean;
+ error?: string;
+ ask_first?: unknown;
+ revision?: unknown;
+ replies_gated?: unknown;
+ needs_apply?: unknown;
+ }>('set_ask_first', {
+ workflow_id: workflowId,
+ ask_first: askFirst,
+ ...(current ? { expected_revision: current.revision } : {}),
+ });
+ if (reply?.success === false) {
+ throw new Error(reply.error === 'rule_conflict' ? 'Ask first changed meanwhile. Look again.' : 'Couldn’t change Ask first. Try again.');
+ }
+ return {
+ askFirst: typeof reply?.ask_first === 'boolean' ? reply.ask_first : askFirst,
+ revision: typeof reply?.revision === 'number' ? reply.revision : 0,
+ repliesGated: reply?.replies_gated === true,
+ needsApply: reply?.needs_apply === true,
+ };
+ },
+ onMutate: async (askFirst) => {
+ await queryClient.cancelQueries({ queryKey: key });
+ const previous = queryClient.getQueryData<AskFirst>(key);
+ queryClient.setQueryData<AskFirst>(key, { askFirst, revision: previous?.revision ?? 0 });
+ return { previous };
+ },
+ onSuccess: (result) => {
+ queryClient.setQueryData<AskFirst>(key, { askFirst: result.askFirst, revision: result.revision });
+ },
+ onError: (error, _value, context) => {
+ if (context) queryClient.setQueryData(key, context.previous);
+ onError?.(error.message);
+ },
+ onSettled: () => {
+ void queryClient.invalidateQueries({ queryKey: key });
+ },
+ });
+}
+
+interface ApprovalEnvelope {
+ specversion?: string;
+ type?: string;
+ data?: { workflow_id?: string; approval_id?: string } | null;
+}
+
+/** Apply one `approval_lifecycle` envelope. Exported for tests. */
+export function applyApprovalEvent(queryClient: QueryClient, event: ApprovalEnvelope): void {
+ if (!event || event.specversion !== '1.0') return;
+ const workflowId = event.data?.workflow_id;
+ if (!workflowId) return;
+ void queryClient.invalidateQueries({ queryKey: chatApprovalsKey(workflowId) });
+}
+
+/** Keep a chat's drafts current while it is mounted. */
+export function useApprovalEvents(): void {
+ const queryClient = useQueryClient();
+ const { addEventListener } = useWebSocketActions();
+ useEffect(() => addEventListener('approval_lifecycle', (data) => applyApprovalEvent(queryClient, data)), [addEventListener, queryClient]);
+}
diff --git a/client/src/features/chat/data/parts.ts b/client/src/features/chat/data/parts.ts
index 07a8fb38..15310002 100644
--- a/client/src/features/chat/data/parts.ts
+++ b/client/src/features/chat/data/parts.ts
@@ -81,3 +81,17 @@ export function liveUiParts(activities: readonly RunActivity[] | undefined): UiP
: [],
);
}
+
+/** The drafts a saved reply names (`parts.approvals`), in order, once each. */
+export function savedApprovalIds(parts: Record<string, unknown> | null | undefined): string[] {
+ const raw = parts?.approvals;
+ if (!Array.isArray(raw)) return [];
+ const ids = raw.flatMap((item) => (isRecord(item) && typeof item.approval_id === 'string' && item.approval_id ? [item.approval_id] : []));
+ return [...new Set(ids)];
+}
+
+/** The drafts a run made so far (its `approval` activities). */
+export function liveApprovalIds(activities: readonly RunActivity[] | undefined): string[] {
+ const ids = (activities ?? []).flatMap((activity) => (activity.activityType === 'approval' ? [activity.messageId] : []));
+ return [...new Set(ids)];
+}
diff --git a/client/src/features/chat/turns/AssistantTurn.tsx b/client/src/features/chat/turns/AssistantTurn.tsx
index a34c1f31..826cb596 100644
--- a/client/src/features/chat/turns/AssistantTurn.tsx
+++ b/client/src/features/chat/turns/AssistantTurn.tsx
@@ -1,8 +1,9 @@
/**
* The employee's side of a turn (design handoff chat, "Assistant row"):
* their avatar on the left and, with no bubble, in order: what they did on
- * the way (the steps disclosure), what they said in markdown, and any
- * interface they showed (GeneratedUiBlock).
+ * the way (the steps disclosure), what they said in markdown, any interface
+ * they showed (GeneratedUiBlock), and anything they want to send, waiting for
+ * the owner (ApprovalCard).
*
* While their run works the avatar spins its ring; skeleton lines stand in
* for text that has not come yet; the answer streams in with a caret after
@@ -20,7 +21,8 @@ import { Suspense, lazy, useMemo, type ReactNode } from 'react';
import { isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';
import type { UiStateChange } from '@/lib/jsonRender/uiState';
import { cn } from '@/lib/utils';
-import { savedFollowups, savedSources, savedUiParts, type SourceItem, type UiPart } from '../data/parts';
+import { ApprovalCard } from '../approval/ApprovalCard';
+import { liveApprovalIds, savedApprovalIds, savedFollowups, savedSources, savedUiParts, type SourceItem, type UiPart } from '../data/parts';
import type { ChatMessage } from '../data/schemas';
import type { ChatUiActions } from '../genui/actions';
import type { ChatPersona } from '../host';
@@ -112,6 +114,11 @@ export function AssistantTurn({
const failure = run?.state === 'error' ? failureLines(run.error, persona.name) : null;
const saved = message ? savedUiParts(message.parts) : NO_UI;
const interfaces = saved.length > 0 ? saved : liveUi;
+ // 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],
+ );
// Only under the latest answer, once it is done.
const followups = message && latest && !live && onFollowUp ? savedFollowups(message.parts) : [];
const citations = useMemo<CitationInfo>(() => {
@@ -159,6 +166,9 @@ export function AssistantTurn({
onStateChange={onUiStateChange}
/>
))}
+ {approvals.map((id) => (
+ <ApprovalCard key={id} approvalId={id} />
+ ))}
{live && run && (
<StatusLine
label={liveLabel(run, streaming)}
diff --git a/client/src/features/home/__tests__/drafts.test.tsx b/client/src/features/home/__tests__/drafts.test.tsx
index d4f9145c..18ff58d0 100644
--- a/client/src/features/home/__tests__/drafts.test.tsx
+++ b/client/src/features/home/__tests__/drafts.test.tsx
@@ -1,150 +1,40 @@
/**
- * Drafts on the employee's page: Send and Discard take the draft away at once
- * and bring it back if the server refuses, an edit must fit the channel,
- * each click carries its own decision key, and a new draft says so.
+ * Home hears about drafts an employee made in its own work: a toast names
+ * the employee; a draft made answering the owner in the chat (it names a
+ * chat run) shows in the chat instead, so it gets none.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-
-const sendRequest = vi.fn();
-
-vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
- useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
-}));
+import { QueryClient } from '@tanstack/react-query';
vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
-import { applyApprovalLifecycle, approvalsKey, type Approval } from '../approvals/data';
+import { applyApprovalLifecycle } from '../approvals/data';
import { EMPLOYEES_QUERY_KEY } from '../data/employees';
-import { DraftsSection } from '../employee/DraftsSection';
import { pillToast } from '../ui/pillToast';
-const draft: Approval = {
- approval_id: 'a1',
- workflow_id: 'w1',
- node_id: 'n',
- status: 'pending',
- channel: 'WhatsApp',
- channel_label: 'WhatsApp',
- recipient: '447700900123',
- recipient_label: 'Priya',
- body: 'Yes! Saturday at 10 works.',
- context_excerpt: 'Can I book Saturday?',
- created_at: null,
- revision: 0,
- max_length: 40,
-};
-
-function renderSection(paused = false) {
- const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
- let decided = false;
- sendRequest.mockImplementation(async (type: string) => {
- if (type === 'decide_approval') {
- decided = true;
- return { success: true };
- }
- // Like the server: a decided draft is no longer pending.
- return { success: true, approvals: decided ? [] : [draft] };
- });
- render(
- <QueryClientProvider client={client}>
- <DraftsSection workflowId="w1" employeeName="Maya" paused={paused} />
- </QueryClientProvider>,
- );
- return client;
-}
-
beforeEach(() => {
- sendRequest.mockReset();
vi.mocked(pillToast).mockClear();
});
-describe('DraftsSection', () => {
- it('shows the draft as it will go out', async () => {
- renderSection();
- expect(await screen.findByText('Yes! Saturday at 10 works.')).toBeInTheDocument();
- expect(screen.getByText('to Priya')).toBeInTheDocument();
- expect(screen.getByText(/Can I book Saturday/)).toBeInTheDocument();
- });
-
- it('sends with a fresh decision key and takes the draft away at once', async () => {
- const client = renderSection();
- fireEvent.click(await screen.findByRole('button', { name: 'Send' }));
- await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('decide_approval', expect.objectContaining({ approval_id: 'a1', decision: 'send' })));
- const call = sendRequest.mock.calls.find(([type]) => type === 'decide_approval')!;
- expect(call[1].decision_key).toEqual(expect.any(String));
- expect(call[1]).not.toHaveProperty('text');
- expect(client.getQueryData<Approval[]>(approvalsKey('w1'))?.length ?? 0).toBe(0);
- });
-
- it('puts the draft back when the server refuses', async () => {
- const client = renderSection();
- await screen.findByRole('button', { name: 'Discard' });
- sendRequest.mockImplementation(async (type: string) =>
- type === 'decide_approval' ? { success: false, error: 'expired' } : { success: true, approvals: [draft] },
- );
- await act(async () => {
- fireEvent.click(screen.getByRole('button', { name: 'Discard' }));
- });
- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('That draft expired before it was sent.', { tone: 'error' }));
- expect(client.getQueryData<Approval[]>(approvalsKey('w1'))?.[0]?.approval_id).toBe('a1');
- });
-
- it('sends an edit only when it fits', async () => {
- renderSection();
- fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
- const box = screen.getByRole('textbox', { name: 'Edit the draft' });
- fireEvent.change(box, { target: { value: 'x'.repeat(41) } });
- expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();
- fireEvent.change(box, { target: { value: ' Saturday at 11 instead? ' } });
- fireEvent.click(screen.getByRole('button', { name: 'Send' }));
- await waitFor(() =>
- expect(sendRequest).toHaveBeenCalledWith('decide_approval', expect.objectContaining({ text: 'Saturday at 11 instead?' })),
- );
- });
-
- it('says a paused employee sends on resume', async () => {
- renderSection(true);
- expect(await screen.findByText('Sends when you resume Maya.')).toBeInTheDocument();
- });
-
- // The card leaves the page the moment the owner decides, before the
- // server answers; the confirmation must still show.
- it('confirms a send after the card has gone', async () => {
- renderSection();
- fireEvent.click(await screen.findByRole('button', { name: 'Send' }));
- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Sent to Priya'));
- expect(screen.queryByRole('button', { name: 'Send' })).toBeNull();
- });
-
- it('confirms a discard after the card has gone', async () => {
- renderSection();
- fireEvent.click(await screen.findByRole('button', { name: 'Discard' }));
- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Draft discarded', { tone: 'info' }));
- });
-
- it('says a send waits for Resume when the server holds it', async () => {
- renderSection(true);
- sendRequest.mockImplementation(async (type: string) =>
- type === 'decide_approval' ? { success: true, will_send_on_resume: true } : { success: true, approvals: [] },
- );
- fireEvent.click(await screen.findByRole('button', { name: 'Send' }));
- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Sends when you resume Maya'));
- });
-});
-
describe('applyApprovalLifecycle', () => {
- it('refetches the list and announces a new draft by the employee name', () => {
+ it('announces a new draft by the employee name, once', () => {
const client = new QueryClient();
client.setQueryData(EMPLOYEES_QUERY_KEY, [{ workflow_id: 'w1', name: 'Maya' }]);
- const invalidate = vi.spyOn(client, 'invalidateQueries');
applyApprovalLifecycle(client, { specversion: '1.0', type: 'com.opencompany.approval.requested', data: { workflow_id: 'w1', approval_id: 'a1' } });
- expect(invalidate).toHaveBeenCalledWith({ queryKey: approvalsKey('w1') });
expect(pillToast).toHaveBeenCalledWith('Maya has a draft for you to check', { tone: 'info' });
applyApprovalLifecycle(client, { specversion: '1.0', type: 'com.opencompany.approval.decided', data: { workflow_id: 'w1' } });
expect(pillToast).toHaveBeenCalledTimes(1);
});
+
+ it('leaves a draft made in the chat to the chat', () => {
+ const client = new QueryClient();
+ applyApprovalLifecycle(client, {
+ specversion: '1.0',
+ type: 'com.opencompany.approval.requested',
+ data: { workflow_id: 'w1', approval_id: 'a1', run_id: 'r_1' },
+ });
+ applyApprovalLifecycle(client, { specversion: '0.3', type: 'com.opencompany.approval.requested', data: { workflow_id: 'w1' } });
+ expect(pillToast).not.toHaveBeenCalled();
+ });
});
diff --git a/client/src/features/home/__tests__/employeeView.test.tsx b/client/src/features/home/__tests__/employeeView.test.tsx
index 564d31fd..4e18c6ff 100644
--- a/client/src/features/home/__tests__/employeeView.test.tsx
+++ b/client/src/features/home/__tests__/employeeView.test.tsx
@@ -233,8 +233,9 @@ describe('EmployeeView', () => {
type === 'list_approvals' ? { success: true, approvals: [draft] } : { success: true, messages: [] },
);
renderPage(summary({ status: 'working', talk: TALK_ON, pending_approvals: 1 }, { state: 'running' }));
- const drafts = await screen.findByRole('region', { name: 'Waiting for you' });
+ const drafts = await screen.findByRole('region', { name: 'Drafts waiting for you' });
expect(drafts).toHaveTextContent('Yes! Saturday at 10 works.');
+ expect(drafts).toHaveTextContent('Maya wants to send a message');
expect(screen.getByRole('region', { name: 'Chat with Maya' })).toContainElement(drafts);
});
diff --git a/client/src/features/home/approvals/data.ts b/client/src/features/home/approvals/data.ts
index e2b4a633..3c4109ca 100644
--- a/client/src/features/home/approvals/data.ts
+++ b/client/src/features/home/approvals/data.ts
@@ -1,171 +1,32 @@
/**
- * Drafts waiting for the owner (the approval step), as TanStack queries over
- * `list_approvals` / `decide_approval`.
- *
- * - `useApprovalsQuery(workflowId)`: one employee's pending drafts.
- * - `useDecideApproval()`: Send or Discard. The draft leaves the list at
- * once and comes back if the server refuses; every click carries a fresh
- * `decision_key`, so a replayed request settles the draft only once. The
- * confirmation toast belongs to the hook, not to the click: the card has
- * already left the page when the answer arrives, and TanStack drops a
- * per-call callback whose component unmounted.
- * - `useApprovalLifecycle()`: `approval_lifecycle` broadcasts (identity
- * only) refetch the affected list, and a new draft says so in a toast.
+ * Home's side of drafts waiting for the owner: a toast when an employee
+ * drafts something in its own work (`approval_lifecycle` "requested"), so the
+ * owner hears about it whichever page is open. The drafts themselves, and
+ * deciding them, live in the chat (features/chat/data/approvals.ts); a draft
+ * made answering the owner in the chat (it names a chat run) shows there at
+ * once, so it gets no toast.
*/
import { useEffect } from 'react';
-import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';
-import { z } from 'zod';
+import { useQueryClient, type QueryClient } from '@tanstack/react-query';
import { useWebSocketActions } from '@/contexts/WebSocketContext';
-import { EMPLOYEES_QUERY_KEY, invalidateEmployees } from '../data/employees';
+import { EMPLOYEES_QUERY_KEY } from '../data/employees';
import type { EmployeeSummary } from '../data/schemas';
import { pillToast } from '../ui/pillToast';
-export const approvalsKey = (workflowId: string) => ['approvals', workflowId] as const;
-
-export const approvalSchema = z.object({
- approval_id: z.string().min(1),
- workflow_id: z.string(),
- node_id: z.string().catch(''),
- status: z.string().catch('pending'),
- channel: z.string().catch(''),
- channel_label: z.string().catch(''),
- recipient: z.string().catch(''),
- recipient_label: z.string().catch(''),
- subject: z.string().optional().catch(undefined),
- body: z.string().catch(''),
- context_excerpt: z.string().optional().catch(undefined),
- created_at: z.string().nullable().catch(null),
- expires_at: z.string().nullable().optional().catch(null),
- revision: z.number().catch(0),
- max_length: z.number().int().positive().catch(20000),
- deployment_state: z.string().nullable().optional().catch(null),
-});
-export type Approval = z.infer<typeof approvalSchema>;
-
-export function parseApprovals(raw: unknown): Approval[] {
- if (!Array.isArray(raw)) return [];
- return raw.flatMap((item) => {
- const parsed = approvalSchema.safeParse(item);
- return parsed.success ? [parsed.data] : [];
- });
-}
-
-export function useApprovalsQuery(workflowId: string | null) {
- const { sendRequest, isReady } = useWebSocketActions();
- return useQuery<Approval[], Error>({
- queryKey: approvalsKey(workflowId ?? ''),
- queryFn: async () => {
- const response = await sendRequest<{ success?: boolean; approvals?: unknown; error?: string }>('list_approvals', {
- workflow_id: workflowId,
- status: 'pending',
- });
- if (response?.success === false) throw new Error(response.error || 'Could not load the drafts');
- return parseApprovals(response?.approvals);
- },
- enabled: isReady && Boolean(workflowId),
- staleTime: 10_000,
- // Drafts arrive while the card is closed; always look again on open.
- refetchOnMount: 'always',
- });
-}
-
-export type Decision = 'send' | 'discard';
-
-export interface DecideInput {
- approval: Approval;
- decision: Decision;
- text?: string;
- /** Names the employee in "Sends when you resume {name}". */
- employeeName?: string;
-}
-
-const DECIDE_ERRORS: Record<string, string> = {
- already_decided: 'That draft was already handled.',
- expired: 'That draft expired before it was sent.',
- cancelled: 'That draft was cancelled.',
- not_found: 'That draft is gone.',
- invalid_request: "That can't be sent as it is.",
-};
-
-function decisionKey(): string {
- try {
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
- } catch {
- // Not a secure context.
- }
- return `k-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
-}
-
-export function useDecideApproval() {
- const { sendRequest } = useWebSocketActions();
- const queryClient = useQueryClient();
- return useMutation<
- { will_send_on_resume?: boolean },
- Error,
- DecideInput,
- { previous: Approval[] | undefined; key: readonly string[] }
- >({
- mutationFn: async ({ approval, decision, text }) => {
- const response = await sendRequest<{ success?: boolean; error?: string; detail?: string; will_send_on_resume?: boolean }>(
- 'decide_approval',
- {
- approval_id: approval.approval_id,
- decision,
- decision_key: decisionKey(),
- ...(decision === 'send' && text !== undefined ? { text } : {}),
- },
- );
- if (response?.success === false) {
- throw new Error(response.detail || DECIDE_ERRORS[response.error ?? ''] || 'That did not work. Try again.');
- }
- return response ?? {};
- },
- onMutate: async ({ approval }) => {
- const key = approvalsKey(approval.workflow_id);
- await queryClient.cancelQueries({ queryKey: key });
- const previous = queryClient.getQueryData<Approval[]>(key);
- queryClient.setQueryData<Approval[]>(key, (list) => list?.filter((item) => item.approval_id !== approval.approval_id));
- return { previous, key };
- },
- onSuccess: (result, { approval, decision, employeeName }) => {
- if (decision === 'discard') {
- pillToast('Draft discarded', { tone: 'info' });
- } else if (result.will_send_on_resume) {
- pillToast(`Sends when you resume ${employeeName || 'the employee'}`);
- } else {
- pillToast(`Sent to ${approval.recipient_label || approval.recipient}`);
- }
- },
- onError: (error, _input, context) => {
- if (context) queryClient.setQueryData(context.key, context.previous);
- pillToast(error.message, { tone: 'error' });
- },
- onSettled: (_data, _error, { approval }) => {
- void queryClient.invalidateQueries({ queryKey: approvalsKey(approval.workflow_id) });
- invalidateEmployees(queryClient);
- },
- });
-}
-
interface ApprovalEnvelope {
specversion?: string;
type?: string;
- data?: { workflow_id?: string; approval_id?: string } | null;
+ data?: { workflow_id?: string; approval_id?: string; run_id?: string } | null;
}
/** Apply one `approval_lifecycle` envelope. Exported for tests. */
export function applyApprovalLifecycle(queryClient: QueryClient, event: ApprovalEnvelope): void {
if (!event || event.specversion !== '1.0') return;
const workflowId = event.data?.workflow_id;
- if (!workflowId) return;
- void queryClient.invalidateQueries({ queryKey: approvalsKey(workflowId) });
- if (event.type?.endsWith('.requested')) {
- const employee = queryClient
- .getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)
- ?.find((item) => item.workflow_id === workflowId);
- pillToast(`${employee?.name ?? 'An employee'} has a draft for you to check`, { tone: 'info' });
- }
+ if (!workflowId || !event.type?.endsWith('.requested') || event.data?.run_id) return;
+ const employee = queryClient.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.find((item) => item.workflow_id === workflowId);
+ pillToast(`${employee?.name ?? 'An employee'} has a draft for you to check`, { tone: 'info' });
}
export function useApprovalLifecycle(): void {
diff --git a/client/src/features/home/employee/DraftsSection.tsx b/client/src/features/home/employee/DraftsSection.tsx
deleted file mode 100644
index 61fd5fa8..00000000
--- a/client/src/features/home/employee/DraftsSection.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * "Waiting for you" on the employee's page: every draft the employee holds
- * for approval, as the message will go out, with Discard, Edit and Send.
- *
- * Send delivers the draft (or the edited text) through the channel it
- * names; while the employee is paused it goes out when they resume.
- * An edit must fit the channel's limit and cannot be empty.
- */
-
-import { useState } from 'react';
-import { ActionButton } from '@/components/ui/action-button';
-import { Button } from '@/components/ui/button';
-import { Textarea } from '@/components/ui/textarea';
-import { cn } from '@/lib/utils';
-import { useApprovalsQuery, useDecideApproval, type Approval } from '../approvals/data';
-import { DraftMessagePreview } from '../genui';
-import { MicroLabel } from '../ui/primitives';
-
-function DraftCard({ approval, employeeName, paused }: { approval: Approval; employeeName: string; paused: boolean }) {
- const decide = useDecideApproval();
- const [editing, setEditing] = useState(false);
- const [text, setText] = useState(approval.body);
- const trimmed = text.trim();
- const tooLong = trimmed.length > approval.max_length;
- const busy = decide.isPending;
-
- const send = () => decide.mutate({ approval, decision: 'send', text: editing ? trimmed : undefined, employeeName });
-
- return (
- <div data-approval={approval.approval_id} className="flex flex-col gap-2.5">
- {approval.context_excerpt && (
- <p className="m-0 line-clamp-2 text-sm text-fg-muted">
- <span className="font-medium text-fg-default">{approval.recipient_label || approval.recipient}:</span> {approval.context_excerpt}
- </p>
- )}
- {editing ? (
- <div className="flex flex-col gap-1.5">
- <Textarea
- value={text}
- onChange={(event) => setText(event.target.value)}
- aria-label="Edit the draft"
- rows={4}
- className="min-h-24 resize-y bg-bg-app"
- />
- <span className={cn('self-end font-mono text-2xs', tooLong ? 'text-status-attention-ink' : 'text-fg-muted')}>
- {trimmed.length} / {approval.max_length}
- </span>
- </div>
- ) : (
- <DraftMessagePreview
- channel={approval.channel_label}
- to={approval.recipient_label || approval.recipient}
- subject={approval.subject}
- body={approval.body}
- />
- )}
- <div className="flex flex-wrap items-center gap-2">
- <Button
- variant="quiet"
- disabled={busy}
- onClick={() => decide.mutate({ approval, decision: 'discard', employeeName })}
- className="h-8.5 rounded-row border-border-default px-3.5 font-semibold text-fg-default"
- >
- Discard
- </Button>
- <Button
- variant="quiet"
- disabled={busy}
- onClick={() => {
- setEditing((on) => !on);
- setText(approval.body);
- }}
- className="h-8.5 rounded-row border-border-default px-3.5 font-semibold text-fg-default"
- >
- {editing ? 'Cancel edit' : 'Edit'}
- </Button>
- <ActionButton intent="run" disabled={busy || !trimmed || tooLong} onClick={send} className="ml-auto h-8.5 rounded-row px-4">
- {busy ? 'Sending…' : 'Send'}
- </ActionButton>
- </div>
- {paused && <p className="m-0 text-xs text-fg-muted">Sends when you resume {employeeName}.</p>}
- </div>
- );
-}
-
-export function DraftsSection({ workflowId, employeeName, paused }: { workflowId: string; employeeName: string; paused: boolean }) {
- const { data: approvals } = useApprovalsQuery(workflowId);
- if (!approvals || approvals.length === 0) return null;
- return (
- <section aria-label="Waiting for you" className="flex w-full flex-col gap-3 rounded-card border border-status-waiting-border bg-status-waiting-fill p-4">
- <MicroLabel className="text-status-waiting-ink">Waiting for you</MicroLabel>
- <div className="flex flex-col gap-5">
- {approvals.map((approval) => (
- <DraftCard key={approval.approval_id} approval={approval} employeeName={employeeName} paused={paused} />
- ))}
- </div>
- </section>
- );
-}
-
-export default DraftsSection;
diff --git a/client/src/features/home/employee/EmployeeChat.tsx b/client/src/features/home/employee/EmployeeChat.tsx
index ec059b01..ba4cdd44 100644
--- a/client/src/features/home/employee/EmployeeChat.tsx
+++ b/client/src/features/home/employee/EmployeeChat.tsx
@@ -3,9 +3,10 @@
* over the session whose id is their workflow id, with Home around it.
*
* - The thread scrolls under the header with the orb as its first item (and
- * a new hire's notes under it); the drafts waiting for the owner follow
- * the conversation; the line under the message box says whether they ask
- * before sending anything.
+ * a new hire's notes under it); what they want to send waits for the
+ * owner on cards in the chat (features/chat), with the Ask first chip
+ * beside the box; the line under the box says whether they ask before
+ * sending anything.
* - The message box follows their control state the way the server does: a
* message goes at once while they run, waits for Resume while they are
* paused, and cannot be sent otherwise. Above it, what to act on: Resume or
@@ -29,7 +30,6 @@ import { HireNotice } from '../hire/HireNotice';
import { OrbSlot } from '../orb/OrbSlot';
import { useHomeStore } from '../state/homeStore';
import { pillToast } from '../ui/pillToast';
-import { DraftsSection } from './DraftsSection';
import { PendingChangesNotice } from './PendingChangesNotice';
import { PrimaryActionButton } from './PrimaryActionButton';
import { TurnOnTalk } from './TurnOnTalk';
@@ -109,7 +109,6 @@ export function EmployeeChat({
const liveNote = useRetryNote(workflowId, employee.talk.agent_node_id, lane !== null && lane.state !== 'queued');
const mode = talkMode(employee.control);
const composer: ComposerMode = employee.talk.state !== 'on' || mode === 'start' ? 'closed' : mode;
- const paused = employee.control.state === 'paused' || employee.control.state === 'pausing';
const onSendRefused = (code: string) => {
if (code === 'not_running') {
@@ -139,7 +138,6 @@ export function EmployeeChat({
<HireNotice workflowId={workflowId} />
</div>
),
- afterThread: <DraftsSection workflowId={workflowId} employeeName={name} paused={paused} />,
footnote: employee.asks_first
? `${name} asks before sending anything on your behalf.`
: `${name} doesn’t ask before sending anything on your behalf.`,
diff --git a/client/src/features/home/header/NewConversationButton.tsx b/client/src/features/home/header/NewConversationButton.tsx
index 28f84224..40ffb9b4 100644
--- a/client/src/features/home/header/NewConversationButton.tsx
+++ b/client/src/features/home/header/NewConversationButton.tsx
@@ -49,7 +49,7 @@ export function NewConversationButton({ employee }: { employee: EmployeeSummary
<AlertDialogHeader>
<AlertDialogTitle>Start a new conversation with {name}?</AlertDialogTitle>
<AlertDialogDescription>
- This clears the conversation, and {name} forgets it too.
+ This clears the conversation, and {name} forgets it too. Drafts from it still waiting for you are dropped.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>