Skip to content

Self-improving AI Employees for everyone

feat(chat): the approval card under modes and rules (RFC-0007 AP.3, 1 of 3)

trohitg4568fc7e65ec
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsx
index c22cea98..f8fa82b8 100644
--- a/client/src/features/chat/ChatPane.tsx
+++ b/client/src/features/chat/ChatPane.tsx
@@ -291,6 +291,7 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
decideMutation.mutate(input, {
onSuccess: () => {
if (input.decision === 'send') onSent?.('draft');
+ if (input.always && input.approval.always) notify(`Always allowed: ${input.approval.always.label}`, 'success');
},
onSettled: () =>
setDeciding((current) => {
@@ -300,7 +301,7 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
}),
});
},
- [decideMutation, onSent],
+ [decideMutation, onSent, notify],
);
const linked = useMemo(() => {
const ids = new Set<string>();
@@ -322,11 +323,12 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
[approvals, persona.name, compact, decide, deciding],
);
- // Ctrl/Cmd+Enter sends the newest draft still waiting for the owner.
+ // Ctrl/Cmd+Enter sends the newest draft still waiting for the owner, never
+ // one that spends money or deletes.
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;
+ if (!approval || deciding.has(approval.id) || approval.approvalClass === 'money') return false;
decide({ approval, decision: 'send' });
return true;
};
diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsx
index d9f6bd1f..bd2894bf 100644
--- a/client/src/features/chat/__tests__/approvals.test.tsx
+++ b/client/src/features/chat/__tests__/approvals.test.tsx
@@ -80,7 +80,7 @@ describe('the card says what happened', () => {
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\.$/);
+ expect(sent.footer.kind === 'sent' && sent.footer.text).toMatch(/^Sent to Ana on WhatsApp at .+, without asking\.$/);
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 });
@@ -110,14 +110,38 @@ describe('the card says what happened', () => {
expect(optimistic(approval(effect), 'dismiss', NOW, 0)).toMatchObject({ status: 'cancelled' });
});
- it('a discarded draft can come back while its window lasts', () => {
+ it('a declined 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(gate.footer).toEqual({ kind: 'discarded', text: 'Declined. Maya won’t send this.', note: null, restoreSeconds: 3, canRestore: true });
+ const held = view({ status: 'discarded', restore_until: '2026-10-11T09:00:00Z', note: 'Ask Sam first.' });
+ expect(held.footer).toMatchObject({ restoreSeconds: null, canRestore: true, note: 'Ask Sam first.' });
expect(view({ status: 'discarded', restore_until: '2026-10-04T08:00:00Z' }).footer).toMatchObject({ canRestore: false });
});
+ it('a call with no message to show says what it does, not what it sends', () => {
+ const shell: Wire = { channel: 'Shell', action: 'Use Shell', recipient: '', recipient_label: '', body: '', editable: false, generic: true };
+ const asking = view({ ...shell, approval_class: 'send' });
+ expect([asking.title, asking.preview]).toEqual(['Maya wants to use Shell', 'none']);
+ expect(view({ ...shell, status: 'sending' }).pill.label).toBe('Running');
+ const done = view({ ...shell, status: 'sent', outcome_labels: { sent: 'Done', failed: 'Not done' }, outcome: { certainty: 'sent' } });
+ expect([done.title, done.pill.label, done.footer]).toEqual(['Done', 'Done', { kind: 'sent', text: 'Done.' }]);
+ expect(view({ ...shell, status: 'failed', outcome: { certainty: 'unknown' } }).footer).toEqual({ kind: 'failed', text: 'It may have happened.', unknown: true });
+ expect(view({ ...shell, status: 'expired' }).footer).toEqual({ kind: 'ended', text: 'It waited too long, so it did not run.' });
+ expect(view({ ...shell, status: 'discarded' }).footer).toMatchObject({ text: 'Declined. Maya won’t do this.' });
+ // A spec'd message keeps its preview.
+ expect(view({}).preview).toBe('message');
+ });
+
+ it('a call its turn waits on gets no Undo or Restore, and runs on Resume', () => {
+ const waits = approval({ waits: true });
+ expect(optimistic(waits, 'send', NOW, 0)).toMatchObject({ status: 'approved', undoUntil: null });
+ expect(optimistic(waits, 'discard', NOW, 0)).toMatchObject({ status: 'discarded', restoreUntil: null });
+ // A retry makes it a draft again.
+ expect(optimistic(approval({ waits: true, status: 'failed' }), 'retry', NOW, 0)).toMatchObject({ waits: false, undoUntil: '2026-10-04T09:00:05.000Z' });
+ const paused = view({ waits: true, status: 'approved', deployment_state: 'paused' });
+ expect(paused.footer).toEqual({ kind: 'waiting', text: 'Sends when you resume Maya.' });
+ });
+
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']);
@@ -213,13 +237,67 @@ describe('a draft in the chat', () => {
expect(server.decisions[0].decision_key).not.toBe(server.decisions[1].decision_key);
});
- it('sends a call that has no message to edit as it is', async () => {
- server.approvals = [summary({ channel: 'Custom connector', action: 'Use a connector tool', recipient: '', recipient_label: '', body: '', editable: false })];
+ it('allows a call that has no message as it is, showing what it runs with', async () => {
+ server.approvals = [
+ summary({
+ channel: 'Custom connector',
+ action: 'Use a connector tool',
+ recipient: '',
+ recipient_label: '',
+ body: '',
+ editable: false,
+ details: [{ label: 'query', value: 'pricing for the Pro plan' }],
+ approval_class: 'send',
+ }),
+ ];
renderPane();
const card = (await screen.findByText('Maya wants to use a connector tool')).closest('[data-approval]') as HTMLElement;
- fireEvent.click(within(card).getByRole('button', { name: /^Send$/ }));
+ expect(card).not.toHaveTextContent('To them');
+ expect(card).not.toHaveTextContent('(no message)');
+ expect(within(card).getByText('pricing for the Pro plan')).toBeInTheDocument();
+ expect(within(card).getByText('Reaches out')).toBeInTheDocument();
+ fireEvent.click(within(card).getByRole('button', { name: /^Allow$/ }));
await waitFor(() => expect(server.decisions).toHaveLength(1));
expect(server.decisions[0]).toMatchObject({ approval_id: 'ap1', decision: 'send' });
+ expect(server.decisions[0]).not.toHaveProperty('always');
+ });
+
+ it('Always allow sends the call and saves the rule the card offers', async () => {
+ server.approvals = [summary({ waits: true, always: { label: 'Send a WhatsApp message to 447700900123', scope: 'recipient' } })];
+ const pane = host();
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <ChatPane host={pane} />
+ </QueryClientProvider>,
+ );
+ const card = (await screen.findByText('Maya wants to send a WhatsApp message')).closest('[data-approval]') as HTMLElement;
+ fireEvent.click(within(card).getByRole('button', { name: 'Always allow Send a WhatsApp message to 447700900123' }));
+ await waitFor(() => expect(server.decisions).toHaveLength(1));
+ expect(server.decisions[0]).toMatchObject({ decision: 'send', always: true });
+ await waitFor(() => expect(pane.notify).toHaveBeenCalledWith('Always allowed: Send a WhatsApp message to 447700900123', 'success'));
+ });
+
+ it('declines with a note for the employee; Ctrl+Enter in the note declines', 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: 'Decline' }));
+ const note = within(card).getByRole('textbox', { name: 'Tell Maya what to do instead' });
+ fireEvent.change(note, { target: { value: 'Call Ana instead.' } });
+ fireEvent.keyDown(note, { key: 'Enter', ctrlKey: true });
+ await waitFor(() => expect(server.decisions).toHaveLength(1));
+ expect(server.decisions[0]).toMatchObject({ decision: 'discard', note: 'Call Ana instead.' });
+ });
+
+ it('a money request names itself, and Ctrl+Enter never allows it', async () => {
+ server.approvals = [summary({ channel: 'Stripe', action: 'Run a Stripe command', body: '', editable: false, approval_class: 'money' })];
+ renderPane();
+ const card = (await screen.findByText('Maya wants to run a Stripe command')).closest('[data-approval]') as HTMLElement;
+ expect(within(card).getByText('Money or deletes')).toBeInTheDocument();
+ expect(within(card).getByText(/Money and deletes always ask/)).toBeInTheDocument();
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Message Maya' }), { key: 'Enter', ctrlKey: true });
+ await act(async () => {});
+ expect(server.decisions).toEqual([]);
});
it('sends an edit with Ctrl+Enter', async () => {
@@ -249,12 +327,12 @@ describe('a draft in the chat', () => {
expect(within(own).getByText('Yes, Saturday at 10 works.')).toBeInTheDocument();
});
- it('announces a discarded draft once, not its Restore countdown', async () => {
+ it('announces a declined draft once, not its Restore countdown', async () => {
const restore = new Date(Date.now() + 60_000).toISOString();
server.approvals = [summary({ approval_id: 'g1', kind: 'gate', run_id: null, tool_call_id: null, status: 'discarded', restore_until: restore })];
renderPane();
const own = await screen.findByRole('region', { name: 'Drafts waiting for you' });
- expect(within(own).getByRole('status')).toHaveTextContent('Discarded. Maya won’t send this.');
+ expect(within(own).getByRole('status')).toHaveTextContent('Declined. Maya won’t send this.');
expect(within(own).getByRole('button', { name: /^Restore/ })).toHaveAttribute('aria-live', 'off');
});
diff --git a/client/src/features/chat/approval/ApprovalCard.tsx b/client/src/features/chat/approval/ApprovalCard.tsx
index 3b0b73b5..f57343c0 100644
--- a/client/src/features/chat/approval/ApprovalCard.tsx
+++ b/client/src/features/chat/approval/ApprovalCard.tsx
@@ -1,11 +1,14 @@
/**
* 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. A call that broke off midway (an `effect` row) has
- * no message: it says what was tried, and offers Dismiss only.
+ * will go, what kind of call it is, and Decline (with a note for the
+ * employee) / Edit / Always allow (the rule the server offers) / Send. After
+ * Send it says when it goes, with Undo while it can; then that it went (or
+ * did not, with Try again). A declined draft can be restored while its
+ * window lasts. Ctrl/Cmd+Enter in the edit box sends it. A call with no
+ * message to show (a tool with no spec) shows what it runs with and offers
+ * Allow; a call that broke off midway (an `effect` row) says what was tried,
+ * and offers Dismiss only.
*
* The draft itself lives on the server (data/approvals.ts); the card holds
* only the edit in progress. `chat-approval` is the theme hook.
@@ -19,7 +22,7 @@ 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';
+import { approvalView, classLabel, 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',
@@ -111,13 +114,14 @@ function Card({ approval, className }: { approval: ChatApproval; className?: str
// A draft with no message to edit (a tool call) sends as it is.
const canSend = approval.status === 'pending' && !busy && !tooLong && (!approval.editable || text.trim().length > 0);
- const send = () => {
+ const send = (always = false) => {
if (!canSend) return;
decide({
approval,
decision: 'send',
...(edited ? { text: text.trim() } : {}),
...(edited && approval.subject !== null ? { subject: subject.trim() } : {}),
+ ...(always ? { always: true } : {}),
});
};
@@ -131,8 +135,10 @@ function Card({ approval, className }: { approval: ChatApproval; className?: str
const to = approval.recipientLabel || approval.recipient || 'them';
const linked = approval.uiPartId !== null && approval.status === 'pending' && !edited;
- // A call that broke off midway has no recipient and no message to show.
- const message = approval.kind !== 'effect';
+ // A call with no message to show (a tool with no spec, a call that broke
+ // off midway): no recipient line and no bubble; its lines say what it runs.
+ const message = view.preview === 'message';
+ const kind = approval.status === 'pending' ? classLabel(approval) : null;
return (
<div
@@ -155,6 +161,9 @@ function Card({ approval, className }: { approval: ChatApproval; className?: str
<span className="text-sm font-semibold text-fg-default">{view.title}</span>
<span className="truncate text-xs text-fg-muted">{view.sub}</span>
</div>
+ {kind && (
+ <span className={cn('flex h-6 flex-none items-center rounded-pill border px-2.25 text-xs font-medium whitespace-nowrap', PILL_TONE.muted)}>{kind}</span>
+ )}
<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}
@@ -233,7 +242,8 @@ function Card({ approval, className }: { approval: ChatApproval; className?: str
{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>
+ {/* Without a message, the lines are the call: shown whole (the server cuts each). */}
+ <dd className={cn('m-0 min-w-0 text-fg-default', message ? 'truncate' : 'break-words whitespace-pre-wrap')}>{row.value}</dd>
</div>
))}
</dl>
@@ -260,7 +270,8 @@ function Footer({
busy: boolean;
editing: boolean;
canSend: boolean;
- onSend: () => void;
+ /** Send this one; ``always``: and save the rule the card offers. */
+ onSend: (always?: boolean) => void;
onToggleEdit: () => void;
}) {
const { decide } = useContext(ApprovalsContext)!;
@@ -268,39 +279,7 @@ function 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>
- );
+ return <DecideFooter className={bar} view={view} approval={approval} busy={busy} editing={editing} canSend={canSend} onSend={onSend} onToggleEdit={onToggleEdit} />;
}
if (footer.kind === 'undo') {
return (
@@ -318,7 +297,7 @@ function Footer({
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}…
+ {view.preview === 'message' ? `Sending on ${approval.channel}…` : 'Running…'}
</div>
);
}
@@ -343,8 +322,9 @@ function Footer({
if (footer.kind === 'discarded') {
return (
<div className={cn(bar, 'bg-bg-app')}>
- <span className="min-w-0 flex-1 text-xs text-fg-muted" role="status">
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5 text-xs text-fg-muted" role="status">
{footer.text}
+ {footer.note && <span className="line-clamp-3 break-words whitespace-pre-wrap text-fg-default">You said: “{footer.note}”</span>}
</span>
{footer.canRestore && (
// Its countdown ticks every second: never announced.
@@ -364,7 +344,16 @@ function Footer({
);
}
if (footer.kind === 'failed') {
- return <FailedFooter className={bar} text={footer.text} unknown={footer.unknown} busy={busy} onRetry={(confirm) => decide({ approval, decision: 'retry', confirm })} />;
+ return (
+ <FailedFooter
+ className={bar}
+ text={footer.text}
+ unknown={footer.unknown}
+ message={view.preview === 'message'}
+ busy={busy}
+ onRetry={(confirm) => decide({ approval, decision: 'retry', confirm })}
+ />
+ );
}
if (footer.kind === 'effect') {
return (
@@ -386,27 +375,141 @@ function Footer({
);
}
+/** A request still waiting for the owner: Decline (with an optional note
+ * for the employee), Edit, Always allow (when the card offers a rule), and
+ * Send, or Allow for a call with no message. */
+function DecideFooter({
+ className,
+ view,
+ approval,
+ busy,
+ editing,
+ canSend,
+ onSend,
+ onToggleEdit,
+}: {
+ className: string;
+ view: CardView;
+ approval: ChatApproval;
+ busy: boolean;
+ editing: boolean;
+ canSend: boolean;
+ onSend: (always?: boolean) => void;
+ onToggleEdit: () => void;
+}) {
+ const { decide, name } = useContext(ApprovalsContext)!;
+ const [declining, setDeclining] = useState(false);
+ const [note, setNote] = useState('');
+ const decline = () => decide({ approval, decision: 'discard', ...(note.trim() ? { note: note.trim() } : {}) });
+
+ if (declining) {
+ const onNoteKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ // Never the chat's Ctrl/Cmd+Enter, which allows the newest request.
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!busy) decline();
+ }
+ };
+ return (
+ <div className={cn(className, 'flex-col items-stretch bg-bg-app')}>
+ <Textarea
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ onKeyDown={onNoteKeyDown}
+ rows={2}
+ autoFocus
+ aria-label={`Tell ${name} what to do instead`}
+ placeholder={`Tell ${name} what to do instead (optional)`}
+ className="min-h-16 resize-y bg-bg-input text-sm"
+ />
+ <div className="flex items-center justify-end gap-2">
+ <Button variant="quiet" size="sm" onClick={() => setDeclining(false)} className="font-semibold">
+ Back
+ </Button>
+ <ActionButton intent="stop" disabled={busy} onClick={decline}>
+ Decline
+ </ActionButton>
+ </div>
+ </div>
+ );
+ }
+ const always = approval.always;
+ return (
+ <div className={cn(className, 'bg-bg-app')}>
+ <Button
+ variant="quiet"
+ size="sm"
+ disabled={busy}
+ onClick={() => setDeclining(true)}
+ className="font-semibold hover:bg-action-stop-soft hover:text-action-stop-ink"
+ >
+ Decline
+ </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>
+ )}
+ {always && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={!canSend}
+ title={`Always allow ${always.label}`}
+ onClick={() => onSend(true)}
+ className="max-w-64 min-w-0 font-semibold"
+ >
+ <span className="truncate">Always allow {always.label}</span>
+ </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">
+ {view.preview === 'message' ? <Send aria-hidden className="size-3.25" /> : <Check aria-hidden className="size-3.25" />}
+ {view.preview === 'message' ? 'Send' : 'Allow'}
+ </ActionButton>
+ {approval.approvalClass === 'money' && (
+ <span className="w-full text-xs text-fg-muted">Money and deletes always ask unless you allow them under Allowed without asking.</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,
+ message,
busy,
onRetry,
}: {
className: string;
text: string;
unknown: boolean;
+ /** A message: it "goes out"; otherwise it "runs". */
+ message: boolean;
busy: boolean;
onRetry: (confirm: boolean) => void;
}) {
const [confirming, setConfirming] = useState(false);
+ const again = message ? 'Send again' : 'Run again';
if (confirming) {
return (
<div className={cn(className, 'bg-action-stop-soft')}>
<span className="min-w-0 flex-1 text-xs text-fg-default" role="status">
- It may already have gone out. Send it again anyway?
+ {message ? 'It may already have gone out. Send it again anyway?' : 'It may already have happened. Run it again anyway?'}
</span>
<Button variant="quiet" size="sm" onClick={() => setConfirming(false)} className="font-semibold">
Keep it
@@ -419,7 +522,7 @@ function FailedFooter({
onRetry(true);
}}
>
- Send again
+ {again}
</ActionButton>
</div>
);
@@ -437,7 +540,7 @@ function FailedFooter({
className="gap-1.5 font-semibold"
>
<RotateCcw aria-hidden className="size-3.25" />
- {unknown ? 'Send again' : 'Try again'}
+ {unknown ? again : 'Try again'}
</Button>
</div>
);
diff --git a/client/src/features/chat/approval/view.ts b/client/src/features/chat/approval/view.ts
index 7e72563e..c0cbc8bc 100644
--- a/client/src/features/chat/approval/view.ts
+++ b/client/src/features/chat/approval/view.ts
@@ -3,19 +3,24 @@
* "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;
+ * your OK, Decline / Edit / Always allow / Send (Allow for a call with no
+ * message to show);
+ * - approved, inside the Undo window: Sending, "Sends in Ns" with Undo (none
+ * for a call its turn waits on);
* - 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;
+ * whom, and whether it went without asking;
+ * - discarded: Declined, with what the owner said, and Restore while it can;
* - failed: not sent, or may have gone (the call broke off), with Try again;
* - expired, cancelled: why it never went;
* - an `effect` row (a call that broke off midway, not a send): "{name}
* tried to …", May have happened, with Dismiss only; Dismissed once
* dismissed.
*
- * Copy says what really happens: a draft is "sent" only once it went.
+ * A card with no message to show (a tool with no spec, or a call that sends
+ * no message) previews nothing and says "done" or "run" where a message
+ * says "sent". Copy says what really happens: a draft is "sent" only once it
+ * went.
*/
import { timeLabel } from '../thread/timeLabel';
@@ -30,7 +35,8 @@ export type CardFooter =
/** 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 }
+ /** Declined, with what the owner said, if anything. */
+ | { kind: 'discarded'; text: string; note: string | null; restoreSeconds: number | null; canRestore: boolean }
| { kind: 'failed'; text: string; unknown: boolean }
/** It broke off midway: the owner checks, then dismisses it. */
| { kind: 'effect'; text: string }
@@ -42,6 +48,9 @@ export interface CardView {
pill: { label: string; tone: CardTone; pulse: boolean };
/** The card's frame: a ring while it waits for the owner. */
tone: CardTone;
+ /** What the card previews: the message as it goes, or nothing (its lines
+ * say what the call runs with). */
+ preview: 'message' | 'none';
/** How the message preview reads. */
bubble: 'draft' | 'sent' | 'struck';
/** The small line inside the preview. */
@@ -69,6 +78,8 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
const sub = drafted ? `${channel} · drafted ${/\d/.test(drafted.charAt(0)) ? 'at ' : ''}${drafted}` : channel;
const noun = approval.outcomeLabels;
const action = approval.action ? lowerFirst(approval.action) : 'send a message';
+ const preview = hasMessage(approval) ? 'message' : 'none';
+ const message = preview === 'message';
switch (approval.status) {
case 'pending':
@@ -77,6 +88,7 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
sub,
pill: editing ? { label: 'Editing', tone: 'waiting', pulse: false } : { label: 'Needs your OK', tone: 'waiting', pulse: true },
tone: 'waiting',
+ preview,
bubble: 'draft',
when: 'Draft',
footer: { kind: 'decide' },
@@ -84,78 +96,107 @@ export function approvalView(approval: ChatApproval, { name, nowMs, offsetMs, ed
case 'approved': {
if (approval.consumedAt === null) {
const seconds = secondsLeft(approval.undoUntil, offsetMs, nowMs);
- const paused = approval.kind === 'gate' && (approval.deploymentState === 'paused' || approval.deploymentState === 'pausing');
+ // Its run waits for Resume: a gate's draft, or a call its turn waits on.
+ const paused =
+ (approval.kind === 'gate' || approval.waits) && (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' };
+ seconds > 0 ? { kind: 'undo', seconds }
+ : paused ? { kind: 'waiting', text: `${message ? 'Sends' : 'Runs'} when you resume ${name}.` }
+ : { kind: 'sending' };
return {
- title: `${name} is sending it`,
+ title: `${name} is ${message ? 'sending' : 'doing'} it`,
sub,
- pill: { label: paused && seconds === 0 ? 'Waiting' : 'Sending', tone: 'sending', pulse: !(paused && seconds === 0) },
+ pill: { label: paused && seconds === 0 ? 'Waiting' : message ? 'Sending' : 'Running', tone: 'sending', pulse: !(paused && seconds === 0) },
tone: 'sending',
+ preview,
bubble: 'draft',
when: 'Sending',
footer,
};
}
const at = timeLabel(approval.consumedAt, now);
- return sentView(approval, noun.sent, sub, to, channel, at);
+ return sentView(approval, noun.sent, sub, to, channel, at, preview);
}
case 'sending':
return {
- title: `${name} is sending it`,
+ title: `${name} is ${message ? 'sending' : 'doing'} it`,
sub,
- pill: { label: 'Sending', tone: 'sending', pulse: true },
+ pill: { label: message ? 'Sending' : 'Running', tone: 'sending', pulse: true },
tone: 'sending',
+ preview,
bubble: 'draft',
when: 'Sending',
footer: { kind: 'sending' },
};
case 'sent':
- return sentView(approval, noun.sent, sub, to, channel, timeLabel(approval.outcome?.at ?? approval.consumedAt, now));
+ return sentView(approval, noun.sent, sub, to, channel, timeLabel(approval.outcome?.at ?? approval.consumedAt, now), preview);
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',
+ title: 'Declined',
sub,
- pill: { label: 'Discarded', tone: 'muted', pulse: false },
+ pill: { label: 'Declined', tone: 'muted', pulse: false },
tone: 'muted',
+ preview,
bubble: 'struck',
when: 'Not sent',
- footer: { kind: 'discarded', text: `Discarded. ${name} won’t send this.`, restoreSeconds, canRestore },
+ footer: { kind: 'discarded', text: `Declined. ${name} won’t ${message ? 'send' : 'do'} this.`, note: approval.note, restoreSeconds, canRestore },
};
}
case 'failed': {
const unknown = approval.outcome?.certainty === 'unknown';
const why = approval.outcome?.error ? `: ${approval.outcome.error}` : '.';
+ const label = unknown ? (message ? 'May have sent' : 'May have happened') : message ? 'Didn’t send' : 'Didn’t run';
+ const text = unknown ? `It may have ${message ? 'gone out' : 'happened'}${why}` : `It didn’t ${message ? 'go out' : 'run'}${why}`;
return {
title: noun.failed,
sub,
- pill: { label: unknown ? 'May have sent' : 'Didn’t send', tone: 'failed', pulse: false },
+ pill: { label, tone: 'failed', pulse: false },
tone: 'failed',
+ preview,
bubble: 'draft',
when: 'Not sent',
- footer: { kind: 'failed', text: unknown ? `It may have gone out${why}` : `It didn’t go out${why}`, unknown },
+ footer: { kind: 'failed', text, unknown },
};
}
case 'expired':
- return endedView('Draft expired', 'Expired', sub, 'It waited too long, so it was not sent.');
+ return endedView(
+ message ? 'Draft expired' : 'Request expired',
+ 'Expired',
+ sub,
+ `It waited too long, so it ${message ? 'was not sent' : 'did not run'}.`,
+ preview,
+ );
case 'cancelled':
- return endedView('Draft cancelled', 'Cancelled', sub, 'Not sent: the conversation it belonged to ended.');
+ return endedView(
+ message ? 'Draft cancelled' : 'Request cancelled',
+ 'Cancelled',
+ sub,
+ `Not ${message ? 'sent' : 'run'}: the conversation it belonged to ended.`,
+ preview,
+ );
}
}
-function sentView(approval: ChatApproval, title: string, sub: string, to: string, channel: string, at: string): CardView {
+/** Whether the card has a message to preview: a gate's draft, or a spec'd
+ * call with a message or an editable one. */
+function hasMessage(approval: ChatApproval): boolean {
+ return approval.kind === 'gate' || (!approval.generic && (approval.editable || approval.body !== ''));
+}
+
+function sentView(approval: ChatApproval, title: string, sub: string, to: string, channel: string, at: string, preview: CardView['preview']): CardView {
const when = at ? ` at ${at}` : '';
- const auto = approval.approvedBy === 'auto' ? ', without asking: Ask first was off' : '';
+ const auto = approval.approvedBy === 'auto' ? ', without asking' : '';
return {
title,
sub,
- pill: { label: 'Sent', tone: 'sent', pulse: false },
+ pill: { label: preview === 'message' ? 'Sent' : 'Done', tone: 'sent', pulse: false },
tone: 'sent',
+ preview,
bubble: 'sent',
when: at || 'Sent',
- footer: { kind: 'sent', text: `Sent to ${to} on ${channel}${when}${auto}.` },
+ footer: { kind: 'sent', text: preview === 'message' ? `Sent to ${to} on ${channel}${when}${auto}.` : `Done${when}${auto}.` },
};
}
@@ -165,31 +206,48 @@ function effectView(approval: ChatApproval, name: string, channel: string, now:
const at = timeLabel(approval.createdAt, now);
const sub = at ? `${channel} · ${/\d/.test(at.charAt(0)) ? 'at ' : ''}${at}` : channel;
const title = `${name} tried to ${approval.action ? lowerFirst(approval.action) : `use ${channel}`}`;
- if (approval.status === 'cancelled') return endedView(title, 'Dismissed', sub, 'Dismissed.');
+ if (approval.status === 'cancelled') return endedView(title, 'Dismissed', sub, 'Dismissed.', 'none');
const error = approval.outcome?.error;
return {
title,
sub,
pill: { label: 'May have happened', tone: 'failed', pulse: false },
tone: 'failed',
+ preview: 'none',
bubble: 'draft',
when: '',
footer: { kind: 'effect', text: `It broke off midway${error ? ` (${error})` : ''}, so it may have happened.` },
};
}
-function endedView(title: string, label: string, sub: string, text: string): CardView {
+function endedView(title: string, label: string, sub: string, text: string, preview: CardView['preview']): CardView {
return {
title,
sub,
pill: { label, tone: 'muted', pulse: false },
tone: 'muted',
+ preview,
bubble: 'struck',
when: 'Not sent',
footer: { kind: 'ended', text },
};
}
+/** The class pill of a request card (RFC-0007 §4.5), or null: a read never
+ * asks. */
+export function classLabel(approval: ChatApproval): string | null {
+ switch (approval.approvalClass) {
+ case 'write':
+ return 'Makes changes';
+ case 'send':
+ return 'Reaches out';
+ case 'money':
+ return 'Money or deletes';
+ default:
+ return null;
+ }
+}
+
/** 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/data/approvals.ts b/client/src/features/chat/data/approvals.ts
index d7922c57..1fcaa9c2 100644
--- a/client/src/features/chat/data/approvals.ts
+++ b/client/src/features/chat/data/approvals.ts
@@ -75,6 +75,16 @@ const summarySchema = z
tool_call_id: optionalText,
ui_part_id: optionalText,
deployment_state: optionalText,
+ // What the held call may do (RFC-0007 §4.1), and whether its tool has no
+ // spec (the card shows what it runs with, not a message).
+ approval_class: z.enum(['read', 'write', 'send', 'money']).nullable().optional().catch(null),
+ generic: z.boolean().optional().catch(undefined),
+ // Its employee's turn waits on it: no Undo after Allow, no Restore after
+ // Decline (RFC-0007 §4.6).
+ waits: z.boolean().optional().catch(undefined),
+ // The always-allow rule the card offers, or null.
+ always: z.object({ label: z.string(), scope: z.string() }).nullable().optional().catch(null),
+ note: optionalText,
})
.transform((raw) => ({
id: raw.approval_id,
@@ -106,6 +116,12 @@ const summarySchema = z
toolCallId: raw.tool_call_id,
uiPartId: raw.ui_part_id,
deploymentState: raw.deployment_state,
+ approvalClass: raw.approval_class ?? null,
+ generic: raw.generic === true,
+ waits: raw.waits === true,
+ always: raw.always ?? null,
+ /** What the owner told the employee on declining. */
+ note: raw.note,
}));
export type ChatApproval = z.output<typeof summarySchema>;
@@ -191,6 +207,10 @@ export interface DecideInput {
text?: string;
subject?: string;
confirm?: boolean;
+ /** With send: also save the always-allow rule the card offers. */
+ always?: boolean;
+ /** With discard: what the employee should do instead. */
+ note?: string;
}
export class DecideError extends Error {
@@ -228,13 +248,16 @@ export function optimistic(approval: ChatApproval, decision: Decision, nowMs: nu
const soon = (seconds: number) => new Date(serverNow + seconds * 1000).toISOString();
switch (decision) {
case 'send':
+ // A call its turn waits on runs at once: no Undo.
+ return { ...approval, status: 'approved', undoUntil: approval.waits ? null : soon(5), outcome: null };
case 'retry':
- return { ...approval, status: 'approved', undoUntil: soon(5), outcome: null };
+ // A retried call is a draft again, whoever made it.
+ return { ...approval, status: 'approved', undoUntil: soon(5), outcome: null, waits: false };
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 };
+ return { ...approval, status: 'discarded', restoreUntil: approval.waits ? null : approval.kind === 'gate' ? soon(5) : approval.expiresAt };
case 'dismiss':
return { ...approval, status: 'cancelled' };
}
@@ -255,7 +278,7 @@ export function useDecideApproval(workflowId: string, onError?: (error: DecideEr
const queryClient = useQueryClient();
const key = chatApprovalsKey(workflowId);
return useMutation<ChatApproval | null, DecideError, DecideInput, { previous: ChatApprovals | undefined }>({
- mutationFn: async ({ approval, decision, text, subject, confirm }) => {
+ mutationFn: async ({ approval, decision, text, subject, confirm, always, note }) => {
let reply: DecideReply | undefined;
try {
reply = await sendRequest<DecideReply>('decide_approval', {
@@ -265,6 +288,8 @@ export function useDecideApproval(workflowId: string, onError?: (error: DecideEr
...(text !== undefined ? { text } : {}),
...(subject !== undefined ? { subject } : {}),
...(confirm ? { confirm: true } : {}),
+ ...(always ? { always: true } : {}),
+ ...(note ? { note } : {}),
});
} catch {
throw new DecideError('transport', 'That didn’t reach the server. Try again.');