Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): the "May have happened" card for calls that broke off (RFC-0006 1b.1c)
trohitg4e0f1675732b
diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsxindex c9d7ca1d..d9f6bd1f 100644--- a/client/src/features/chat/__tests__/approvals.test.tsx+++ b/client/src/features/chat/__tests__/approvals.test.tsx@@ -3,7 +3,8 @@* 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.+ * asks before turning off. The card's copy says what really happened; a+ * call that broke off midway offers Dismiss, never Send again.*/import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -93,6 +94,22 @@ describe('the card says what happened', () => {expect(view({ ...labels, status: 'failed' }).title).toBe('Email not sent');});+ it('a call that broke off says it may have happened, until dismissed', () => {+ const effect: Wire = { kind: 'effect', status: 'failed', channel: 'Shell', action: 'Run command', recipient: '', recipient_label: '', body: '', editable: false };+ expect(approval(effect).kind).toBe('effect');+ const broke = view({ ...effect, outcome: { certainty: 'unknown', error: 'WorkerShutdown' } });+ expect(broke.title).toBe('Maya tried to run command');+ expect(broke.sub).toMatch(/^Shell · at .+$/);+ expect(broke.pill).toEqual({ label: 'May have happened', tone: 'failed', pulse: false });+ expect(broke.footer).toEqual({ kind: 'effect', text: 'It broke off midway (WorkerShutdown), so it may have happened.' });+ expect(view({ ...effect, outcome: { certainty: 'unknown' } }).footer).toEqual({ kind: 'effect', text: 'It broke off midway, so it may have happened.' });+ const dismissed = view({ ...effect, status: 'cancelled' });+ expect(dismissed.title).toBe('Maya tried to run command');+ expect(dismissed.pill.label).toBe('Dismissed');+ expect(dismissed.footer).toEqual({ kind: 'ended', text: 'Dismissed.' });+ expect(optimistic(approval(effect), 'dismiss', NOW, 0)).toMatchObject({ status: '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 });@@ -164,7 +181,9 @@ beforeEach(() => {? { ...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;+ : data.decision === 'dismiss'+ ? { ...current, status: 'cancelled', revision: 3 }+ : current;server.approvals = [next];return { success: true, approval: next };}@@ -246,6 +265,32 @@ describe('a draft in the chat', () => {expect(await within(card).findByText('It didn’t go out.')).toHaveAttribute('role', 'status');});+ it('a call that broke off offers Dismiss, never Send again', async () => {+ server.approvals = [+ summary({+ kind: 'effect',+ status: 'failed',+ channel: 'Shell',+ action: 'Run command',+ recipient: '',+ recipient_label: '',+ body: '',+ editable: false,+ outcome: { certainty: 'unknown' },+ }),+ ];+ renderPane();+ const card = (await screen.findByText('Maya tried to run command')).closest('[data-approval]') as HTMLElement;+ expect(card).not.toHaveTextContent('To them');+ expect(card).not.toHaveTextContent('(no message)');+ expect(within(card).queryByRole('button', { name: /again/ })).not.toBeInTheDocument();+ fireEvent.click(within(card).getByRole('button', { name: 'Dismiss' }));+ await waitFor(() => expect(server.decisions).toHaveLength(1));+ expect(server.decisions[0]).toMatchObject({ approval_id: 'ap1', decision: 'dismiss' });+ expect(await within(card).findByText('Dismissed')).toBeInTheDocument();+ expect(within(card).queryByRole('button', { name: 'Dismiss' })).not.toBeInTheDocument();+ });+it('asks before turning Ask first off', async () => {renderPane();const chip = await screen.findByRole('button', { name: 'Ask first' });diff --git a/client/src/features/chat/approval/ApprovalCard.tsx b/client/src/features/chat/approval/ApprovalCard.tsxindex da8769d7..3b0b73b5 100644--- a/client/src/features/chat/approval/ApprovalCard.tsx+++ b/client/src/features/chat/approval/ApprovalCard.tsx@@ -4,13 +4,14 @@* 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 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.** 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, Undo2 } from 'lucide-react';+import { Check, Link2, Loader2, MessageCircle, Pause, Pencil, RotateCcw, Send, Undo2, X } 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';@@ -130,6 +131,8 @@ function Card({ approval, className }: { approval: ChatApproval; className?: strconst 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';return (<div@@ -158,79 +161,85 @@ function Card({ approval, className }: { approval: ChatApproval; className?: str</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>+ {(message || approval.details.length > 0) && (+ <div className={cn('flex flex-col gap-2.5', compact ? 'p-3' : 'p-3.5')}>+ {message && (+ <>+ <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',+ {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.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>- )}- </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>+ )}+ </div>+ )}<Footer view={view} approval={approval} busy={busy} editing={editing} canSend={canSend} onSend={send} onToggleEdit={() => setEditing((on) => !on)} /></div>@@ -357,6 +366,19 @@ 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 })} />;}+ if (footer.kind === 'effect') {+ return (+ <div className={cn(bar, 'bg-action-stop-soft')}>+ <span className="min-w-0 flex-1 text-xs text-fg-default" role="status">+ {footer.text}+ </span>+ <Button variant="outline" size="sm" disabled={busy} onClick={() => decide({ approval, decision: 'dismiss' })} className="gap-1.5 font-semibold">+ <X aria-hidden className="size-3.25" />+ Dismiss+ </Button>+ </div>+ );+ }return (<div className={cn(bar, 'bg-bg-app')}><span className="text-xs text-fg-muted">{footer.text}</span>diff --git a/client/src/features/chat/approval/view.ts b/client/src/features/chat/approval/view.tsindex 2b0c46a8..7e72563e 100644--- a/client/src/features/chat/approval/view.ts+++ b/client/src/features/chat/approval/view.ts@@ -10,7 +10,10 @@* 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.+ * - 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.*/@@ -29,6 +32,8 @@ export type CardFooter =| { kind: 'sent'; text: string }| { kind: 'discarded'; text: string; 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 }| { kind: 'ended'; text: string };export interface CardView {@@ -59,6 +64,7 @@ export interface ViewOptions {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';+ if (approval.kind === 'effect') return effectView(approval, name, channel, now);const drafted = timeLabel(approval.createdAt, now);const sub = drafted ? `${channel} · drafted ${/\d/.test(drafted.charAt(0)) ? 'at ' : ''}${drafted}` : channel;const noun = approval.outcomeLabels;@@ -153,6 +159,25 @@ function sentView(approval: ChatApproval, title: string, sub: string, to: string};}+/** A call that broke off midway, so it may have happened. Nothing runs it+ * again from here: the owner checks, then dismisses the card. */+function effectView(approval: ChatApproval, name: string, channel: string, now: Date): CardView {+ 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.');+ const error = approval.outcome?.error;+ return {+ title,+ sub,+ pill: { label: 'May have happened', tone: 'failed', pulse: false },+ tone: 'failed',+ 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 {return {title,diff --git a/client/src/features/chat/data/approvals.ts b/client/src/features/chat/data/approvals.tsindex bf3c1ca9..d7922c57 100644--- a/client/src/features/chat/data/approvals.ts+++ b/client/src/features/chat/data/approvals.ts@@ -7,7 +7,8 @@* - `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.+ * - `useDecideApproval(workflowId)`: send, undo, discard, restore, retry,+ * dismiss.* 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.@@ -39,7 +40,9 @@ const summarySchema = z.object({approval_id: z.string().min(1),workflow_id: z.string().catch(''),- kind: z.enum(['gate', 'tool_call']).catch('gate'),+ // gate: an app reply an Approval node holds; tool_call: an employee's+ // held call; effect: a call that broke off midway and may have happened.+ kind: z.enum(['gate', 'tool_call', 'effect']).catch('gate'),status: z.enum(STATUSES as [ApprovalStatus, ...ApprovalStatus[]]).catch('pending'),channel: z.string().catch(''),action: optionalText,@@ -180,7 +183,7 @@ export function useChatApprovals(workflowId: string | null) {});}-export type Decision = 'send' | 'undo' | 'discard' | 'restore' | 'retry';+export type Decision = 'send' | 'undo' | 'discard' | 'restore' | 'retry' | 'dismiss';export interface DecideInput {approval: ChatApproval;@@ -232,6 +235,8 @@ export function optimistic(approval: ChatApproval, decision: Decision, nowMs: nureturn { ...approval, status: 'pending', undoUntil: null, restoreUntil: null };case 'discard':return { ...approval, status: 'discarded', restoreUntil: approval.kind === 'gate' ? soon(5) : approval.expiresAt };+ case 'dismiss':+ return { ...approval, status: 'cancelled' };}}