Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): the Ask first menu and Allowed without asking (RFC-0007 AP.3, 2 of 3)
trohitg1e94a3f8d7fc
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 3c437b85..4a586f65 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -166,6 +166,8 @@ export interface WorkflowControlStatus {controller_workflow_id?: string | null;controller_run_id?: string | null;execution_control_version?: number;+ /** 1: what asks is the workflow's mode and the call's class (RFC-0007). */+ approval_wait_version?: number;last_resumed_at?: string | null;state: WorkflowControlState;revision: number;diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsxindex f8fa82b8..a91a42e9 100644--- a/client/src/features/chat/ChatPane.tsx+++ b/client/src/features/chat/ChatPane.tsx@@ -14,7 +14,9 @@* 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.+ * chip beside the box changes the rule for everything they send, or, where+ * the employee's generation asks by mode (RFC-0007 §4.2), the Ask first+ * menu picks the mode (composer/AskModeMenu.tsx).** Files go with a message where the chat allows them: Attach, a paste, or* a drop anywhere on the chat (DropOverlay), all through one@@ -51,6 +53,7 @@ import { cn } from '@/lib/utils';import { ApprovalsContext, type ApprovalsValue } from './approval/context';import { StandaloneApprovals } from './approval/StandaloneApprovals';import { AskFirstChip } from './composer/AskFirstChip';+import { AskModeMenu } from './composer/AskModeMenu';import { addAttachments } from './composer/attachments';import { DropOverlay } from './composer/DropOverlay';import { Greetings } from './composer/Greetings';@@ -66,7 +69,9 @@ import {useChatApprovals,useDecideApproval,useSetAskFirst,+ type AskMode,type DecideInput,+ type SetAskFirstResult,} from './data/approvals';import { useConversation } from './data/conversation';import { useChatWorkflowControl, useResumeChatGeneration } from './data/control';@@ -91,12 +96,22 @@ import { ChatThread } from './thread/ChatThread';import { TurnActionsContext, type TurnActions } from './thread/turnActions';import { branchRefusalText, feedbackThanks } from './turns/runCopy';+/** What a mode change tells the owner. */+const MODE_SET: Record<AskMode, string> = {+ outside: 'will ask before anything outside',+ everything: 'will ask before everything',+ money_only: 'will ask only before money and deletes',+};+export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandle> }) {const { sessionId, scope, persona, composer, notify, onSendRefused, onSent, onComposerChange, compact = false } = host;const { thread, turns, lane } = useConversation(sessionId, scope);const workflowId = sessionId === 'default' ? null : sessionId;const control = useChatWorkflowControl(workflowId, lane);const controlled = control?.execution_control_version === 1;+ // What asks is the mode and the call's class (RFC-0007): the Ask first+ // menu in place of the chip, and Allowed without asking.+ const byMode = control?.approval_wait_version === 1;const suspended = controlled && control.state === 'paused';const resuming = controlled && control.state === 'resuming';const resume = useResumeChatGeneration(control, () => notify('Couldn’t resume. Try again.', 'error'));@@ -319,8 +334,8 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand.filter((id) => !linked.has(id) && isOpenApproval(approvals.byId.get(id)!, now));}, [approvals, linked]);const approvalsValue = useMemo<ApprovalsValue>(- () => ({ approvals, name: persona.name, compact, decide, deciding }),- [approvals, persona.name, compact, decide, deciding],+ () => ({ approvals, name: persona.name, compact, decide, deciding, byMode }),+ [approvals, persona.name, compact, decide, deciding, byMode],);// Ctrl/Cmd+Enter sends the newest draft still waiting for the owner, never@@ -422,27 +437,32 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandworkflowId && chatContext?.web ? (<WebChip on={web} name={persona.name} compact={compact} onChange={(next) => useComposerStore.getState().setWeb(sessionId, next)} />) : null;+ const ruleChanged = (result: SetAskFirstResult) => {+ if (result.needsApply) notify(`Apply ${persona.name}’s changes for this to cover everything.`, 'info');+ else if (byMode && result.mode) notify(`${persona.name} ${MODE_SET[result.mode]}`, 'success');+ else notify(result.askFirst ? `${persona.name} will ask before sending` : `${persona.name} will send without asking`, 'success');+ };const askFirstChip =- workflowId && askFirstQuery.data ? (+ !workflowId || !askFirstQuery.data ? null+ : byMode ? (+ <AskModeMenu+ workflowId={workflowId}+ mode={askFirstQuery.data.mode}+ name={persona.name}+ compact={compact}+ disabled={setAskFirst.isPending}+ onChange={(next) => setAskFirst.mutate(next, { onSuccess: ruleChanged })}+ onError={(message) => notify(message, 'error')}+ />+ ) : (<AskFirstChipon={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');- else- notify(- result.askFirst ? `${persona.name} will ask before sending` : `${persona.name} will send without asking`,- 'success',- );- },- })- }+ onChange={(next) => setAskFirst.mutate(next, { onSuccess: ruleChanged })}/>- ) : null;+ );// The picker wraps the box wherever the host offers it, from the first// render, so the box isn't mounted again when the rows arrive; its button// shows once they have.diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsxindex bd2894bf..353a4115 100644--- a/client/src/features/chat/__tests__/approvals.test.tsx+++ b/client/src/features/chat/__tests__/approvals.test.tsx@@ -3,12 +3,15 @@* 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; a- * call that broke off midway offers Dismiss, never Send again.+ * asks before turning off; where the employee asks by mode, the Ask first+ * menu and its list of what is allowed without asking. 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';import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';const sendRequest = vi.fn();@@ -18,7 +21,9 @@ vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),}));+import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';import { resetChatRunStore } from '@/stores/chatRunStore';+import { useWorkflowControlStore } from '@/stores/workflowControlStore';import { approvalView } from '../approval/view';import { ChatPane } from '../ChatPane';import { isOpenApproval, optimistic, parseApproval, readApprovals, secondsLeft, type ChatApproval } from '../data/approvals';@@ -155,9 +160,24 @@ describe('the card says what happened', () => {// ----- in the chat ------let server: { approvals: Wire[]; askFirst: boolean | null; decisions: Wire[]; rule: Wire[] };+let server: {+ approvals: Wire[];+ askFirst: boolean | null;+ mode: string | null;+ revision: number;+ decisions: Wire[];+ rule: Wire[];+ allows: Wire[];+ money: Wire[];+};let client: QueryClient;+/** The employee's generation asks by mode (RFC-0007). */+function asksByMode() {+ const control = { state: 'running', revision: 1, generation: 1, execution_control_version: 1, approval_wait_version: 1, root_execution_id: 'g1' };+ useWorkflowControlStore.getState().replaceStatuses({ w1: normalizeWorkflowControlStatus(control, 'w1') });+}+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 };}@@ -183,7 +203,8 @@ function renderPane() {beforeEach(() => {resetChatRunStore();useComposerStore.setState({ drafts: {} });- server = { approvals: [summary()], askFirst: true, decisions: [], rule: [] };+ useWorkflowControlStore.setState({ statuses: {}, pending: {} });+ server = { approvals: [summary()], askFirst: true, mode: 'outside', revision: 0, decisions: [], rule: [], allows: [], money: [] };sendRequest.mockReset().mockImplementation(async (kind: string, data: Wire) => {switch (kind) {case 'chat_subscribe':@@ -193,10 +214,27 @@ beforeEach(() => {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 };+ return { success: true, ask_first: server.askFirst, mode: server.mode, revision: server.revision };case 'set_ask_first':server.rule.push(data);- return { success: true, ask_first: data.ask_first, revision: 1, replies_gated: true, needs_apply: false };+ server.mode = typeof data.mode === 'string' ? data.mode : data.ask_first ? 'outside' : 'money_only';+ server.askFirst = server.mode !== 'money_only';+ server.revision += 1;+ return { success: true, ask_first: server.askFirst, mode: server.mode, revision: server.revision, replies_gated: true, needs_apply: false };+ case 'list_approval_allows':+ return { success: true, workflow_id: 'w1', allows: server.allows, money: server.money };+ case 'add_approval_allow': {+ const added = { id: `a${server.allows.length + 10}`, label: 'Money switch', created_at: '2026-10-04T09:00:00Z' };+ server.allows = [...server.allows, added];+ server.money = server.money.map((option) =>+ option.node_type === data.node_type && option.operation === data.operation ? { ...option, allow_id: added.id } : option,+ );+ return { success: true, allow: added };+ }+ case 'remove_approval_allow':+ server.allows = server.allows.filter((rule) => rule.id !== data.allow_id);+ server.money = server.money.map((option) => (option.allow_id === data.allow_id ? { ...option, allow_id: null } : option));+ return { success: true };case 'decide_approval': {server.decisions.push(data);const current = server.approvals[0];@@ -291,6 +329,7 @@ describe('a draft in the chat', () => {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' })];+ asksByMode();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();@@ -300,6 +339,14 @@ describe('a draft in the chat', () => {expect(server.decisions).toEqual([]);});+ it('names no list of allowed calls where the employee has none', async () => {+ server.approvals = [summary({ channel: 'Google Calendar', action: 'Delete an event', body: '', editable: false, approval_class: 'money' })];+ renderPane();+ const card = (await screen.findByText('Maya wants to delete an event')).closest('[data-approval]') as HTMLElement;+ expect(within(card).getByText('Money or deletes')).toBeInTheDocument();+ expect(within(card).queryByText(/Allowed without asking/)).not.toBeInTheDocument();+ });+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;@@ -382,3 +429,89 @@ describe('a draft in the chat', () => {await waitFor(() => expect(server.rule).toEqual([{ workflow_id: 'w1', ask_first: false, expected_revision: 0 }]));});});++describe('Ask first by mode', () => {+ function renderByMode() {+ asksByMode();+ const pane = host();+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <ChatPane host={pane} />+ </QueryClientProvider>,+ );+ return pane;+ }++ it('picks the mode from a menu, and asks before asking less', async () => {+ const user = userEvent.setup();+ const pane = renderByMode();+ const menu = await screen.findByRole('button', { name: 'Ask first' });+ expect(menu).not.toHaveAttribute('aria-pressed');+ expect(menu).toHaveAttribute('title', 'Maya asks before anything outside');++ await user.click(menu);+ expect(await screen.findByRole('menuitemradio', { name: /^Before anything outside/ })).toHaveAttribute('aria-checked', 'true');+ expect(screen.getByRole('menuitemradio', { name: /^Before anything outside/ })).toHaveTextContent(+ 'Maya asks before it messages, posts, books, deploys or changes things in your apps.',+ );+ await user.click(screen.getByRole('menuitemradio', { name: /^Before everything/ }));+ await waitFor(() => expect(server.rule).toEqual([{ workflow_id: 'w1', mode: 'everything', expected_revision: 0 }]));+ await waitFor(() => expect(pane.notify).toHaveBeenCalledWith('Maya will ask before everything', 'success'));++ // Asking less asks first.+ await user.click(screen.getByRole('button', { name: 'Ask first' }));+ await user.click(await screen.findByRole('menuitemradio', { name: /^Only for money and deletes/ }));+ const confirm = await screen.findByRole('button', { name: 'Ask only for money and deletes' });+ expect(screen.getByText('Let Maya work without asking?')).toBeInTheDocument();+ expect(server.rule).toHaveLength(1);+ await user.click(confirm);+ await waitFor(() => expect(server.rule[1]).toEqual({ workflow_id: 'w1', mode: 'money_only', expected_revision: 1 }));+ await waitFor(() => expect(pane.notify).toHaveBeenCalledWith('Maya will ask only before money and deletes', 'success'));+ });++ it('keeps asking when the owner thinks again', async () => {+ const user = userEvent.setup();+ renderByMode();+ await user.click(await screen.findByRole('button', { name: 'Ask first' }));+ await user.click(await screen.findByRole('menuitemradio', { name: /^Only for money and deletes/ }));+ await user.click(await screen.findByRole('button', { name: 'Keep asking' }));+ await act(async () => {});+ expect(server.rule).toEqual([]);+ });++ it('lists what the employee does without asking, and switches money on and off', async () => {+ server.allows = [+ { id: 'a1', label: 'Shell', created_at: '2026-10-02T10:00:00Z' },+ { id: 'a2', label: 'Stripe', created_at: '2026-10-03T10:00:00Z' },+ ];+ server.money = [+ { node_type: 'stripeAction', operation: '', label: 'Stripe', allow_id: 'a2' },+ { node_type: 'googleCalendar', operation: 'delete', label: 'Google Calendar: delete', allow_id: null },+ ];+ const user = userEvent.setup();+ renderByMode();+ await user.click(await screen.findByRole('button', { name: 'Ask first' }));+ await user.click(await screen.findByRole('menuitem', { name: 'Allowed without asking…' }));+ const list = await screen.findByRole('dialog', { name: 'Allowed without asking' });+ // A money switch's own rule shows as its switch, not as a line.+ expect(await within(list).findByText('Shell')).toBeInTheDocument();+ expect(within(list).getByText(/added/)).toBeInTheDocument();+ expect(within(list).queryByRole('button', { name: 'Remove Stripe' })).not.toBeInTheDocument();+ expect(within(list).getByRole('switch', { name: 'Allow Stripe without asking' })).toBeChecked();+ expect(within(list).getByRole('switch', { name: 'Allow Google Calendar: delete without asking' })).not.toBeChecked();++ await user.click(within(list).getByRole('button', { name: 'Remove Shell' }));+ expect(await within(list).findByText('Nothing yet. When Maya asks, choose Always allow to add it here.')).toBeInTheDocument();+ expect(sendRequest).toHaveBeenCalledWith('remove_approval_allow', { workflow_id: 'w1', allow_id: 'a1' });++ await user.click(within(list).getByRole('switch', { name: 'Allow Google Calendar: delete without asking' }));+ await waitFor(() =>+ expect(sendRequest).toHaveBeenCalledWith('add_approval_allow', { workflow_id: 'w1', node_type: 'googleCalendar', operation: 'delete' }),+ );+ await waitFor(() => expect(within(list).getByRole('switch', { name: 'Allow Google Calendar: delete without asking' })).toBeChecked());++ await user.click(within(list).getByRole('switch', { name: 'Allow Stripe without asking' }));+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('remove_approval_allow', { workflow_id: 'w1', allow_id: 'a2' }));+ });+});diff --git a/client/src/features/chat/approval/ApprovalCard.tsx b/client/src/features/chat/approval/ApprovalCard.tsxindex f57343c0..e87536b5 100644--- a/client/src/features/chat/approval/ApprovalCard.tsx+++ b/client/src/features/chat/approval/ApprovalCard.tsx@@ -397,7 +397,7 @@ function DecideFooter({onSend: (always?: boolean) => void;onToggleEdit: () => void;}) {- const { decide, name } = useContext(ApprovalsContext)!;+ const { decide, name, byMode } = useContext(ApprovalsContext)!;const [declining, setDeclining] = useState(false);const [note, setNote] = useState('');const decline = () => decide({ approval, decision: 'discard', ...(note.trim() ? { note: note.trim() } : {}) });@@ -478,7 +478,7 @@ function DecideFooter({{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' && (+ {approval.approvalClass === 'money' && byMode && (<span className="w-full text-xs text-fg-muted">Money and deletes always ask unless you allow them under Allowed without asking.</span>)}</div>diff --git a/client/src/features/chat/approval/context.ts b/client/src/features/chat/approval/context.tsindex 4962d710..876d6c39 100644--- a/client/src/features/chat/approval/context.ts+++ b/client/src/features/chat/approval/context.ts@@ -15,6 +15,9 @@ export interface ApprovalsValue {decide: (input: DecideInput) => void;/** Drafts with a decision on its way to the server. */deciding: ReadonlySet<string>;+ /** The employee asks by mode (RFC-0007 §4.2): its Ask first menu lists+ * what it does without asking. */+ byMode: boolean;}export const ApprovalsContext = createContext<ApprovalsValue | null>(null);diff --git a/client/src/features/chat/composer/AllowedWithoutAsking.tsx b/client/src/features/chat/composer/AllowedWithoutAsking.tsxnew file mode 100644index 00000000..96dee75c--- /dev/null+++ b/client/src/features/chat/composer/AllowedWithoutAsking.tsx@@ -0,0 +1,120 @@+/**+ * "Allowed without asking…", from the Ask first menu (RFC-0007 §4.4, D19;+ * wording R5 §5): what the employee does without asking first, whatever+ * the mode. The rules the owner made with Always allow on a card, each with+ * Remove, and a switch for each of the employee's money tools, since a card+ * never offers Always allow for money. A change applies from the+ * employee's next call (data/allows.ts).+ */++import { Button } from '@/components/ui/button';+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Skeleton } from '@/components/ui/skeleton';+import { Switch } from '@/components/ui/switch';+import { useAddApprovalAllow, useApprovalAllows, useRemoveApprovalAllow } from '../data/allows';++export function AllowedWithoutAsking({+ workflowId,+ name,+ open,+ onOpenChange,+ onError,+}: {+ workflowId: string;+ name: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onError: (message: string) => void;+}) {+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="gap-5 sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Allowed without asking</DialogTitle>+ <DialogDescription>{name} does these without asking you first, whatever Ask me first says.</DialogDescription>+ </DialogHeader>+ {/* Mounted only while open, so every open reads the list again. */}+ <AllowList workflowId={workflowId} name={name} onError={onError} />+ </DialogContent>+ </Dialog>+ );+}++function added(createdAt: string | null): string | null {+ const date = createdAt ? new Date(createdAt) : null;+ return date && !Number.isNaN(date.getTime()) ? date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) : null;+}++function AllowList({ workflowId, name, onError }: { workflowId: string; name: string; onError: (message: string) => void }) {+ const query = useApprovalAllows(workflowId);+ const add = useAddApprovalAllow(workflowId, onError);+ const remove = useRemoveApprovalAllow(workflowId, onError);+ const busy = add.isPending || remove.isPending;++ if (query.isPending) return <Skeleton className="h-16 w-full rounded-card" />;+ if (query.isError) {+ return (+ <p className="m-0 flex items-center gap-2 text-sm text-fg-muted">+ Couldn’t load the list.+ <Button variant="quiet" size="sm" onClick={() => void query.refetch()} className="font-semibold">+ Try again+ </Button>+ </p>+ );+ }+ const { rules, money } = query.data;+ return (+ <div className="flex flex-col gap-5">+ {rules.length > 0 ? (+ <ul className="m-0 flex list-none flex-col p-0">+ {rules.map((rule) => {+ const when = added(rule.createdAt);+ return (+ <li key={rule.id} className="flex items-center gap-3 border-b border-border-default py-1.5 last:border-b-0">+ <span className="min-w-0 flex-1 text-sm text-fg-default">+ {rule.label}+ {when && <span className="text-xs text-fg-muted"> · added {when}</span>}+ </span>+ <Button+ variant="quiet"+ size="sm"+ disabled={busy}+ aria-label={`Remove ${rule.label}`}+ onClick={() => remove.mutate(rule.id)}+ className="font-semibold"+ >+ Remove+ </Button>+ </li>+ );+ })}+ </ul>+ ) : (+ <p className="m-0 text-sm text-fg-muted">Nothing yet. When {name} asks, choose Always allow to add it here.</p>+ )}+ {money.length > 0 && (+ <section aria-label="Money and deletes" className="flex flex-col gap-2">+ <h3 className="m-0 text-sm font-semibold text-fg-default">Money and deletes</h3>+ <p className="m-0 text-xs text-fg-muted">These always ask unless you switch them on here.</p>+ {money.map((option) => (+ <div key={`${option.nodeType}:${option.operation}`} className="flex items-center gap-3 py-1">+ <span className="min-w-0 flex-1 text-sm text-fg-default">{option.label}</span>+ <Switch+ tone="run"+ aria-label={`Allow ${option.label} without asking`}+ checked={option.allowId !== null}+ disabled={busy}+ onCheckedChange={(on) => {+ if (on) add.mutate(option);+ else if (option.allowId) remove.mutate(option.allowId);+ }}+ />+ </div>+ ))}+ </section>+ )}+ </div>+ );+}++export default AllowedWithoutAsking;diff --git a/client/src/features/chat/composer/AskModeMenu.tsx b/client/src/features/chat/composer/AskModeMenu.tsxnew file mode 100644index 00000000..90300635--- /dev/null+++ b/client/src/features/chat/composer/AskModeMenu.tsx@@ -0,0 +1,165 @@+/**+ * Ask first by mode (RFC-0007 §4.2; wording R5 §5), beside the message box+ * in place of the Ask first chip once the employee's generation asks by+ * mode: a chip that opens "Ask me first", the three modes with what each+ * means, and "Allowed without asking…", what the employee does unasked+ * (AllowedWithoutAsking). A choice changes the workflow's live rule+ * (`set_ask_first` with `mode`), with no restart; one that asks less than+ * now asks first.+ */++import { ShieldCheck } from 'lucide-react';+import { useState } from 'react';+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { cn } from '@/lib/utils';+import type { AskMode } from '../data/approvals';+import { AllowedWithoutAsking } from './AllowedWithoutAsking';++const MODES: readonly { id: AskMode; label: string; detail: (name: string) => string; title: (name: string) => string }[] = [+ {+ id: 'outside',+ label: 'Before anything outside',+ detail: (name) => `${name} asks before it messages, posts, books, deploys or changes things in your apps.`,+ title: (name) => `${name} asks before anything outside`,+ },+ {+ id: 'everything',+ label: 'Before everything',+ detail: () => 'Also before it changes its own files and notes.',+ title: (name) => `${name} asks before everything`,+ },+ {+ id: 'money_only',+ label: 'Only for money and deletes',+ detail: (name) => `${name} works on its own but asks before it spends money or deletes anything.`,+ title: (name) => `${name} asks only before money and deletes`,+ },+];++/** How much each mode asks: choosing one that asks less asks first. */+const RANK: Record<AskMode, number> = { money_only: 0, outside: 1, everything: 2 };++/** What a mode that asks less gives up. */+const ASKS_LESS: Record<Exclude<AskMode, 'everything'>, { title: (name: string) => string; detail: (name: string) => string; confirm: string }> = {+ outside: {+ title: (name) => `Let ${name} change its own files without asking?`,+ detail: (name) => `${name} will change its own files and notes straight away. It still asks before anything outside.`,+ confirm: 'Ask before anything outside',+ },+ money_only: {+ title: (name) => `Let ${name} work without asking?`,+ detail: (name) =>+ `Messages, posts, bookings and changes in your apps will go out straight away, without a card for you to check first. ${name} still asks before it spends money or deletes anything.`,+ confirm: 'Ask only for money and deletes',+ },+};++export function AskModeMenu({+ workflowId,+ mode,+ name,+ onChange,+ onError,+ disabled = false,+ compact = false,+}: {+ workflowId: string;+ /** null: no rule yet, so nothing asks. */+ mode: AskMode | null;+ name: string;+ onChange: (next: AskMode) => void;+ /** The list's errors. */+ onError: (message: string) => void;+ disabled?: boolean;+ compact?: boolean;+}) {+ // The mode that asks less stays set while its confirmation closes, so the+ // dialog keeps its words to the end.+ const [less, setLess] = useState<Exclude<AskMode, 'everything'> | null>(null);+ const [confirming, setConfirming] = useState(false);+ const [listOpen, setListOpen] = useState(false);+ const current = MODES.find((item) => item.id === mode);++ const choose = (value: string) => {+ const next = MODES.find((item) => item.id === value)?.id;+ if (!next || next === mode) return;+ if (mode && next !== 'everything' && RANK[next] < RANK[mode]) {+ setLess(next);+ setConfirming(true);+ } else onChange(next);+ };++ const copy = less ? ASKS_LESS[less] : null;+ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={disabled}>+ <Button+ variant="chip"+ size="sm"+ aria-label="Ask first"+ title={current ? current.title(name) : `${name} doesn’t ask first`}+ className={cn(+ 'h-6.5 gap-1.25 rounded-pill px-2.5 text-xs font-semibold text-fg-muted',+ current && 'border-action-config-border bg-action-config-soft text-action-config-ink',+ compact && 'h-6 px-2',+ )}+ >+ <ShieldCheck aria-hidden className="size-3.25" strokeWidth={2} />+ Ask first+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="start" sideOffset={8} className="w-(--w-chat-model-menu) max-w-[calc(100vw-2rem)]">+ <DropdownMenuLabel>Ask me first</DropdownMenuLabel>+ <DropdownMenuRadioGroup value={mode ?? ''} onValueChange={choose}>+ {MODES.map((item) => (+ <DropdownMenuRadioItem key={item.id} value={item.id} className="py-1.5">+ <span className="flex min-w-0 flex-col gap-px">+ <span className="font-medium">{item.label}</span>+ <span className="text-xs text-muted-foreground">{item.detail(name)}</span>+ </span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => setListOpen(true)}>Allowed without asking…</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <AlertDialog open={confirming} onOpenChange={setConfirming}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{copy?.title(name)}</AlertDialogTitle>+ <AlertDialogDescription>{copy?.detail(name)}</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep asking</AlertDialogCancel>+ <AlertDialogAction onClick={() => less && onChange(less)}>{copy?.confirm}</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ <AllowedWithoutAsking workflowId={workflowId} name={name} open={listOpen} onOpenChange={setListOpen} onError={onError} />+ </>+ );+}++export default AskModeMenu;diff --git a/client/src/features/chat/data/allows.ts b/client/src/features/chat/data/allows.tsnew file mode 100644index 00000000..a34fc691--- /dev/null+++ b/client/src/features/chat/data/allows.ts@@ -0,0 +1,106 @@+/**+ * The employee's always-allow rules (RFC-0007 §4.4), for "Allowed without+ * asking…" in the Ask first menu, as TanStack queries over+ * `list_approval_allows` / `add_approval_allow` / `remove_approval_allow`.+ *+ * - `useApprovalAllows(workflowId)`: the rules the owner made with Always+ * allow on a card, and a switch for each of the employee's money tools+ * and operations, on while a rule lets it run unasked.+ * - `useAddApprovalAllow` turns a money switch on; `useRemoveApprovalAllow`+ * takes a rule away, or turns a money switch off. Either applies from the+ * employee's next call.+ */++import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import { z } from 'zod';+import { useWebSocketActions } from '@/contexts/WebSocketContext';++export const approvalAllowsKey = (workflowId: string) => ['approvalAllows', workflowId] as const;++const ruleSchema = z+ .object({ id: z.string().min(1), label: z.string().catch(''), created_at: z.string().nullable().optional().catch(null) })+ .transform((raw) => ({ id: raw.id, label: raw.label, createdAt: raw.created_at ?? null }));++const moneySchema = z+ .object({+ node_type: z.string().min(1),+ operation: z.string().catch(''),+ label: z.string().catch(''),+ allow_id: z.string().nullable().optional().catch(null),+ })+ .transform((raw) => ({ nodeType: raw.node_type, operation: raw.operation, label: raw.label, allowId: raw.allow_id ?? null }));++export type ApprovalAllow = z.output<typeof ruleSchema>;+export type MoneySwitch = z.output<typeof moneySchema>;++export interface ApprovalAllows {+ /** Oldest first, without the money switches' own rules. */+ rules: ApprovalAllow[];+ money: MoneySwitch[];+}++function parseList<T>(schema: z.ZodType<T>, list: unknown): T[] {+ return (Array.isArray(list) ? list : []).flatMap((raw) => {+ const parsed = schema.safeParse(raw);+ return parsed.success ? [parsed.data] : [];+ });+}++type ListReply = { success?: boolean; allows?: unknown; money?: unknown; error?: string };++export function readApprovalAllows(reply: ListReply | undefined): ApprovalAllows {+ const money = parseList(moneySchema, reply?.money);+ const switches = new Set(money.flatMap((option) => (option.allowId ? [option.allowId] : [])));+ return { rules: parseList(ruleSchema, reply?.allows).filter((rule) => !switches.has(rule.id)), money };+}++export function useApprovalAllows(workflowId: string) {+ const { sendRequest, isReady } = useWebSocketActions();+ return useQuery<ApprovalAllows, Error>({+ queryKey: approvalAllowsKey(workflowId),+ queryFn: async () => {+ const reply = await sendRequest<ListReply>('list_approval_allows', { workflow_id: workflowId });+ if (reply?.success === false) throw new Error(reply.error || 'Could not load the list');+ return readApprovalAllows(reply);+ },+ enabled: isReady && Boolean(workflowId),+ // Cards add rules while the list is closed: look again on every open.+ refetchOnMount: 'always',+ staleTime: 0,+ });+}++type ChangeReply = { success?: boolean; error?: string } | undefined;++function useChangeAllows<T>(workflowId: string, send: (input: T) => Promise<ChangeReply>, onError?: (message: string) => void) {+ const queryClient = useQueryClient();+ return useMutation<void, Error, T>({+ mutationFn: async (input) => {+ const reply = await send(input);+ if (reply?.success === false) throw new Error('That didn’t change. Try again.');+ },+ onError: (error) => onError?.(error.message),+ onSettled: () => {+ void queryClient.invalidateQueries({ queryKey: approvalAllowsKey(workflowId) });+ },+ });+}++export function useAddApprovalAllow(workflowId: string, onError?: (message: string) => void) {+ const { sendRequest } = useWebSocketActions();+ return useChangeAllows<MoneySwitch>(+ workflowId,+ (option) =>+ sendRequest<ChangeReply>('add_approval_allow', { workflow_id: workflowId, node_type: option.nodeType, operation: option.operation }),+ onError,+ );+}++export function useRemoveApprovalAllow(workflowId: string, onError?: (message: string) => void) {+ const { sendRequest } = useWebSocketActions();+ return useChangeAllows<string>(+ workflowId,+ (allowId) => sendRequest<ChangeReply>('remove_approval_allow', { workflow_id: workflowId, allow_id: allowId }),+ onError,+ );+}diff --git a/client/src/features/chat/data/approvals.ts b/client/src/features/chat/data/approvals.tsindex 1fcaa9c2..0e577ed4 100644--- a/client/src/features/chat/data/approvals.ts+++ b/client/src/features/chat/data/approvals.ts@@ -12,7 +12,8 @@* 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.+ * - `useAskFirst` / `useSetAskFirst`: the workflow's live rule, Ask first+ * on or off, or the mode it asks in (RFC-0007 §4.2).* - `applyApprovalEvent`: an `approval_lifecycle` broadcast (identity only)* refetches the session's drafts.*/@@ -324,9 +325,21 @@ export function useDecideApproval(workflowId: string, onError?: (error: DecideEr});}+/** What the employee asks first about (RFC-0007 §4.2): anything outside+ * (sends and money), everything (its own changes too), or only money and+ * deletes. */+export type AskMode = 'outside' | 'everything' | 'money_only';++const ASK_MODES: readonly AskMode[] = ['outside', 'everything', 'money_only'];++const askModeOf = (value: unknown): AskMode | null => ((ASK_MODES as readonly unknown[]).includes(value) ? (value as AskMode) : null);+export interface AskFirst {/** null: the workflow has no rule (its tool calls are never held). */askFirst: boolean | null;+ /** The mode, or Ask first's meaning while the owner has chosen none;+ * null with no rule. */+ mode: AskMode | null;revision: number;}@@ -335,12 +348,14 @@ export function useAskFirst(workflowId: string | null) {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,- });+ const reply = await sendRequest<{ success?: boolean; ask_first?: unknown; mode?: 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,+ mode: askModeOf(reply?.mode),revision: typeof reply?.revision === 'number' ? reply.revision : 0,};},@@ -355,43 +370,56 @@ export interface SetAskFirstResult extends AskFirst {needsApply: boolean;}+/** Ask first on or off (the chip), or a mode (the mode menu). */+export type AskFirstChange = boolean | AskMode;++/** The rule a change makes: a mode also writes the Ask first it means, so a+ * generation that reads only Ask first keeps reading it. */+function changed(change: AskFirstChange): Pick<AskFirst, 'askFirst' | 'mode'> {+ if (typeof change === 'boolean') return { askFirst: change, mode: change ? 'outside' : 'money_only' };+ return { askFirst: change !== 'money_only', mode: change };+}+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) => {+ return useMutation<SetAskFirstResult, Error, AskFirstChange, { previous: AskFirst | undefined }>({+ mutationFn: async (change) => {const current = queryClient.getQueryData<AskFirst>(key);const reply = await sendRequest<{success?: boolean;error?: string;ask_first?: unknown;+ mode?: unknown;revision?: unknown;replies_gated?: unknown;needs_apply?: unknown;}>('set_ask_first', {workflow_id: workflowId,- ask_first: askFirst,+ ...(typeof change === 'boolean' ? { ask_first: change } : { mode: change }),...(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.');}+ const expected = changed(change);return {- askFirst: typeof reply?.ask_first === 'boolean' ? reply.ask_first : askFirst,+ askFirst: typeof reply?.ask_first === 'boolean' ? reply.ask_first : expected.askFirst,+ mode: askModeOf(reply?.mode) ?? expected.mode,revision: typeof reply?.revision === 'number' ? reply.revision : 0,repliesGated: reply?.replies_gated === true,needsApply: reply?.needs_apply === true,};},- onMutate: async (askFirst) => {+ onMutate: async (change) => {await queryClient.cancelQueries({ queryKey: key });const previous = queryClient.getQueryData<AskFirst>(key);- queryClient.setQueryData<AskFirst>(key, { askFirst, revision: previous?.revision ?? 0 });+ queryClient.setQueryData<AskFirst>(key, { ...changed(change), revision: previous?.revision ?? 0 });return { previous };},onSuccess: (result) => {- queryClient.setQueryData<AskFirst>(key, { askFirst: result.askFirst, revision: result.revision });+ queryClient.setQueryData<AskFirst>(key, { askFirst: result.askFirst, mode: result.mode, revision: result.revision });},onError: (error, _value, context) => {if (context) queryClient.setQueryData(key, context.previous);diff --git a/client/src/themes/base.css b/client/src/themes/base.cssindex 6fa91b33..896b2161 100644--- a/client/src/themes/base.css+++ b/client/src/themes/base.css@@ -205,7 +205,7 @@--dur-chip-pop: 360ms; /* an attachment chip arriving */--dur-pick: 260ms; /* the model picker's button settling after a pick */--dur-level-drag: 120ms; /* a level slider's knob while dragged (--dur-slow otherwise) */- --w-chat-model-menu: 320px; /* the model picker */+ --w-chat-model-menu: 320px; /* the model picker, and the Ask first menu */--h-chat-model-menu: 460px; /* ...at most; less on a short window */--shadow-knob: 0 1px 4px rgb(0 0 0 / 0.25); /* a level slider's knob *//* The Mobile tab's phone (design handoff "Workspace panel"): a dark bezeldiff --git a/server/services/deployment/control.py b/server/services/deployment/control.pyindex 1b6701cb..d165b967 100644--- a/server/services/deployment/control.py+++ b/server/services/deployment/control.py@@ -53,6 +53,9 @@ def serialize_control(control: Optional[WorkflowControlExecution]) -> Dict[str,"controller_workflow_id": control.controller_workflow_id,"controller_run_id": control.controller_run_id,"execution_control_version": int(manifest.get("execution_control_version", 0)),+ # 1: what asks is the mode and the class, and a chat run's held call+ # waits in its turn (RFC-0007); the chat shows the mode menu.+ "approval_wait_version": int(manifest.get("approval_wait_version", 0)),"last_resumed_at": manifest.get("last_resumed_at"),"state": state,"revision": control.revision,diff --git a/server/tests/services/approvals/test_modes.py b/server/tests/services/approvals/test_modes.pyindex 8b901452..d7dc5a3b 100644--- a/server/tests/services/approvals/test_modes.py+++ b/server/tests/services/approvals/test_modes.py@@ -181,6 +181,30 @@ async def test_a_graph_node_is_never_held(harness):assert await check("whatsappSend", WHATSAPP, parent_node_id=None) is tool_calls.RUN+async def test_the_control_status_says_whether_a_generation_asks_by_mode():+ # The chat shows the mode menu only where modes apply.+ from services.deployment.control import serialize_control++ control = SimpleNamespace(+ workflow_id="wf",+ generation=1,+ execution_id="e",+ root_execution_id="e",+ data_scope_id=None,+ controller_workflow_id=None,+ controller_run_id=None,+ status="running",+ revision=1,+ created_at=None,+ updated_at=None,+ terminal_reason=None,+ resource_manifest={"execution_control_version": 1, "approval_wait_version": 1},+ )+ assert serialize_control(control)["approval_wait_version"] == 1+ control.resource_manifest = {"execution_control_version": 1}+ assert serialize_control(control)["approval_wait_version"] == 0++async def test_the_ask_first_commands_read_and_set_the_mode(harness, monkeypatch):from services.approvals.handlers import handle_get_ask_first, handle_set_ask_first