Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): a message answers the call the turn waits on (RFC-0007 AP.3, 4 of 4)
trohitg3152dfd49885
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsxindex 4a16fb43..017b21a6 100644--- a/client/src/features/chat/ChatPane.tsx+++ b/client/src/features/chat/ChatPane.tsx@@ -16,7 +16,8 @@* (data/approvals.ts). Ctrl/Cmd+Enter sends the newest one; the Ask first* 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).+ * menu picks the mode (composer/AskModeMenu.tsx). While the answer waits on+ * a card, a message goes as the owner's answer to it instead (D3).** Files go with a message where the chat allows them: Attach, a paste, or* a drop anywhere on the chat (DropOverlay), all through one@@ -70,6 +71,7 @@ import {useChatApprovals,useDecideApproval,useSetAskFirst,+ waitsOnOwner,type AskMode,type DecideInput,type SetAskFirstResult,@@ -178,8 +180,18 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandconst feedback = useSetChatFeedback(sessionId, scope, () => notify('Your rating didn’t save. Try again.', 'error'));const changing = edit.isPending || regenerate.isPending || switchBranch.isPending;+ // What the employee wants to do and waits for the owner's OK on (cards).+ useApprovalEvents();+ const approvalsQuery = useChatApprovals(workflowId);+ const approvals = approvalsQuery.data ?? NO_APPROVALS;+const busy = send.isPending || lane !== null || changing;const stopping = lane?.state === 'stopping' || stop.isPending || (controlled && control.state === 'pausing');+ // The lane's run waits for the owner's OK on a call: a message goes as+ // the owner's answer instead, declining the call with its text as the+ // note (RFC-0007 D3; the server decides). Nothing else goes meanwhile.+ const replying = lane !== null && waitsOnOwner(approvals, lane.runId);+ const sendBusy = replying ? send.isPending || changing : busy;const editMutate = edit.mutate;const regenerateMutate = regenerate.mutate;@@ -220,17 +232,19 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandconst ready = Boolean(thread.data) && !choiceUnknown;const submit = () => {const store = useComposerStore.getState();- const box = useAttachmentStore.getState().boxes[sessionId] ?? [];+ // An answer to a waiting call goes alone: files wait in the box.+ const box = replying ? [] : (useAttachmentStore.getState().boxes[sessionId] ?? []);const hasText = Boolean((store.drafts[sessionId]?.text ?? '').trim());const hasFiles = box.some((item) => item.state === 'ready');- if (busy || !ready || box.some((item) => item.state === 'uploading') || !(hasText || hasFiles)) return;+ if (sendBusy || !ready || box.some((item) => item.state === 'uploading') || !(hasText || hasFiles)) return;const draft = store.takeForSend(sessionId);- const attachments = useAttachmentStore.getState().takeReady(sessionId);+ const attachments = replying ? [] : useAttachmentStore.getState().takeReady(sessionId);send.mutate({...draft,text: draft.text.trim(),...(attachments.length ? { attachments } : {}),...(options ? { options } : {}),+ ...(replying ? { declines: true } : {}),});};@@ -292,9 +306,6 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand// Drafts waiting for the owner: on the replies that made them, and the// rest (the employee's own work) after the conversation.- useApprovalEvents();- const approvalsQuery = useChatApprovals(workflowId);- const approvals = approvalsQuery.data ?? NO_APPROVALS;const askFirstQuery = useAskFirst(workflowId);const setAskFirst = useSetAskFirst(workflowId ?? '', (message) => notify(message, 'error'));const [deciding, setDeciding] = useState<ReadonlySet<string>>(() => new Set());@@ -540,7 +551,8 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandsessionId={sessionId}name={persona.name}ready={ready}- busy={busy}+ busy={sendBusy}+ replying={replying}onSend={submit}onStop={lane && !suspended && !resuming ? stopAnswer : undefined}onResume={suspended || resuming ? () => resume.mutate() : undefined}diff --git a/client/src/features/chat/__tests__/approvals.test.tsx b/client/src/features/chat/__tests__/approvals.test.tsxindex 64ab6ab2..1ff01bd2 100644--- a/client/src/features/chat/__tests__/approvals.test.tsx+++ b/client/src/features/chat/__tests__/approvals.test.tsx@@ -240,6 +240,9 @@ beforeEach(() => {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 'send_chat_message':+ // While the run waits on a card, a message answers it (RFC-0007 D3).+ return { success: true, message_id: null, run_id: null, declined: { run_id: 'r1', approval_ids: ['ap1'] }, delivery: 'now' };case 'list_approval_allows':return { success: true, workflow_id: 'w1', allows: server.allows, money: server.money };case 'add_approval_allow': {@@ -479,6 +482,27 @@ describe('a call its turn waits on', () => {expect(step).toHaveTextContent('Waiting for your OK');});+ it('a message meanwhile answers the call instead, on its card', async () => {+ server.messages = [row('m1', 'user', 'Tell Ana I’m late', { run_id: 'r1' })];+ server.activeRuns = [waitingRun];+ server.approvals = [summary({ waits: true })];+ renderPane();+ await screen.findByText('Maya wants to send a WhatsApp message');+ const box = screen.getByRole('textbox', { name: 'Message Maya' });+ expect(box).toHaveAttribute('placeholder', 'Tell Maya what to do instead…');+ // Stop while the box is empty, Send once something is written.+ const composer = box.closest('.chat-composer') as HTMLElement;+ expect(within(composer).getByRole('button', { name: 'Stop reply' })).toBeInTheDocument();+ fireEvent.change(box, { target: { value: 'Call her instead.' } });+ const send = within(composer).getByRole('button', { name: 'Send' });+ await waitFor(() => expect(send).toBeEnabled());+ fireEvent.click(send);+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('send_chat_message', expect.objectContaining({ message: 'Call her instead.' })));+ await act(async () => {});+ expect(screen.queryByText('Call her instead.')).not.toBeInTheDocument();+ expect(box).toHaveValue('');+ });+it('a draft the turn does not wait on leaves the turn as it was', async () => {server.messages = [row('m1', 'user', 'Tell Ana I’m late', { run_id: 'r1' })];server.activeRuns = [waitingRun];@@ -487,6 +511,12 @@ describe('a call its turn waits on', () => {const turn = card.closest('[data-turn="assistant"]') as HTMLElement;expect(within(turn).getAllByRole('status').some((node) => node.textContent === 'Thinking')).toBe(true);expect(turn.querySelector('[data-step="call_1"]')).toHaveAttribute('data-state', 'done');+ // Nothing goes while it answers.+ const box = screen.getByRole('textbox', { name: 'Message Maya' });+ const composer = box.closest('.chat-composer') as HTMLElement;+ fireEvent.change(box, { target: { value: 'Hello?' } });+ expect(within(composer).queryByRole('button', { name: 'Send' })).not.toBeInTheDocument();+ expect(within(composer).getByRole('button', { name: 'Stop reply' })).toBeInTheDocument();});it('is read however many newer cards there are', async () => {diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsxindex 5e621a59..ad077b00 100644--- a/client/src/features/chat/composer/Composer.tsx+++ b/client/src/features/chat/composer/Composer.tsx@@ -17,7 +17,9 @@** What is written lives in the composer store per conversation, so it* survives switching to another employee and back. While the employee is- * still answering the last message the box takes text but Send waits.+ * still answering the last message the box takes text but Send waits;+ * while it waits for the owner's OK on a call, a message goes as the+ * owner's answer instead (`replying`, RFC-0007 D3).*/import { ArrowUp, Mic, Play, Plus, Square } from 'lucide-react';@@ -62,6 +64,10 @@ export interface ComposerProps {resuming?: boolean;/** The answer is already stopping. */stopping?: boolean;+ /** The employee waits for the owner's OK on a call: a message declines+ * it, with its text as the note. Send shows while the box has text, and+ * files wait in the box. */+ replying?: boolean;compact: boolean;/** The text box, for the host's focus requests. */boxRef: RefObject<HTMLTextAreaElement | null>;@@ -99,6 +105,7 @@ export function Composer({onResume,resuming = false,stopping = false,+ replying = false,compact,boxRef,chips,@@ -123,7 +130,8 @@ export function Composer({const uploading = attachments.some((item) => item.state === 'uploading');const finished = attachments.some((item) => item.state === 'ready');- const canSend = ready && !disabled && !busy && !uploading && (draft.text.trim().length > 0 || finished);+ const typed = draft.text.trim().length > 0;+ const canSend = ready && !disabled && !busy && (replying ? typed : !uploading && (typed || finished));// The slash list: open while the box is one word starting with `/` that// begins a command, until Esc (for that text) or a pick.@@ -188,7 +196,20 @@ export function Composer({const iconSize = compact ? 'size-3.5' : 'size-4';const round = cn('shrink-0 rounded-full', compact ? 'size-7' : 'size-8.5');- const sendButton = onResume ? (+ const send = (+ <Button+ variant="invert"+ size="icon"+ disabled={!canSend}+ onClick={onSend}+ aria-label="Send"+ title={busy ? `${name} is still answering` : uploading && !replying ? 'Waiting for the files to upload' : 'Send (Enter)'}+ className={round}+ >+ <ArrowUp aria-hidden strokeWidth={2.25} className={iconSize} />+ </Button>+ );+ const sendButton = replying && typed ? send : onResume ? (<Button variant="invert" size="icon" disabled={resuming} onClick={onResume}aria-label={resuming ? 'Resuming' : 'Resume'} title="Resume from the next pending action" className={round}><Play aria-hidden fill="currentColor" className={iconSize} />@@ -206,17 +227,7 @@ export function Composer({<Square aria-hidden fill="currentColor" strokeWidth={0} className={compact ? 'size-2.75' : 'size-3'} /></Button>) : (- <Button- variant="invert"- size="icon"- disabled={!canSend}- onClick={onSend}- aria-label="Send"- title={busy ? `${name} is still answering` : uploading ? 'Waiting for the files to upload' : 'Send (Enter)'}- className={round}- >- <ArrowUp aria-hidden strokeWidth={2.25} className={iconSize} />- </Button>+ send);const attachButton = onAddFiles ? (<>@@ -280,7 +291,10 @@ export function Composer({onBlur={() => onFocusChange?.(false)}aria-label={`Message ${name}`}aria-autocomplete={commands.length ? 'list' : undefined}- placeholder={placeholder ?? (commands.length ? `Message ${name}… Type / for commands` : `Message ${name}…`)}+ placeholder={+ placeholder ??+ (replying ? `Tell ${name} what to do instead…` : commands.length ? `Message ${name}… Type / for commands` : `Message ${name}…`)+ }className={cn('max-h-(--h-chat-composer-max) overflow-hidden text-fg-default field-sizing-fixed',compact ? 'py-1 text-sm leading-normal' : 'py-1.5 text-md leading-normal',diff --git a/client/src/features/chat/data/send.ts b/client/src/features/chat/data/send.tsindex b263639a..ad1d4cdb 100644--- a/client/src/features/chat/data/send.ts+++ b/client/src/features/chat/data/send.ts@@ -23,6 +23,11 @@* off web search, and Home's model picker adds the model and the effort* (data/models.ts). A model that can't answer is refused with* `model_unavailable`, whose `detail` the owner reads.+ *+ * A message sent while the employee waits for the owner's OK on a call+ * (`declines`) may be taken as the owner's answer: the server declines the+ * call with the text as its note and saves no message (`declined`, RFC-0007+ * D3), so it shows on the call's card, never in the thread.*/import { useMutation, useQueryClient } from '@tanstack/react-query';@@ -38,7 +43,8 @@ import { chatThreadKey, type ThreadScope } from './thread';export type Delivery = 'now' | 'queued';export interface SendResult {- messageId: string;+ /** Null when the message answered a call the employee waited on. */+ messageId: string | null;runId: string | null;/** Null for the editor's chat with no workflow open. */delivery: Delivery | null;@@ -71,8 +77,10 @@ type SendReply = {error?: string;detail?: string;run_id?: string | null;- message_id?: string;+ message_id?: string | null;delivery?: string;+ /** It answered the calls a run waited on: `{run_id, approval_ids}`. */+ declined?: unknown;};/** What a message, an edit or a retry carries as `options`. */@@ -111,6 +119,9 @@ export type SendDraft = TakenDraft & {/** Finished uploads from the box. */attachments?: BoxAttachment[];options?: SendOptions;+ /** Sent while the employee waits for the owner's OK on a call: shown on+ * its card, not in the thread. */+ declines?: boolean;};function refsOf(attachments: readonly BoxAttachment[] | undefined) {@@ -160,17 +171,18 @@ export function useSendChatMessage(} catch {throw new ChatSendError('transport', { transport: true });}- if (reply?.success === false || !reply?.message_id) {+ if (reply?.success === false || !(reply?.message_id || reply?.declined)) {throw new ChatSendError(reply?.error || 'send_failed', { runId: reply?.run_id ?? null, detail: reply?.detail ?? null });}return {- messageId: reply.message_id,+ messageId: reply.message_id || null,runId: reply.run_id ?? null,delivery: reply.delivery === 'queued' ? 'queued' : reply.delivery === 'now' ? 'now' : null,};},- onMutate: async ({ text, clientMessageId, uiEvent, attachments }) => {+ onMutate: async ({ text, clientMessageId, uiEvent, attachments, declines }) => {await queryClient.cancelQueries({ queryKey: key });+ if (declines) return;const pending: ChatMessage = {id: localId(clientMessageId),legacyId: null,@@ -196,21 +208,26 @@ export function useSendChatMessage(onSuccess: (result, { clientMessageId, attachments }) => {// The files are on the server now: the box's thumbnails can go.for (const item of attachments ?? []) if (item.preview) URL.revokeObjectURL(item.preview);+ const { messageId, runId } = result;+ // It answered a waiting call: its card shows it, not the thread.+ if (messageId === null) {+ replace((messages) => messages.filter((message) => message.id !== localId(clientMessageId)));+ onSent?.();+ return;+ }replace((messages) =>// A resent message the server already had is in the thread as that// row: the local copy goes rather than show it twice.- messages.some((message) => message.id === result.messageId && !message.pending)+ messages.some((message) => message.id === messageId && !message.pending)? messages.filter((message) => message.id !== localId(clientMessageId)): messages.map((message) =>- message.id === localId(clientMessageId)- ? { ...message, id: result.messageId, runId: result.runId, pending: false }- : message,+ message.id === localId(clientMessageId) ? { ...message, id: messageId, runId, pending: false } : message,),);- if (result.runId) {+ if (runId) {useChatRunStore.getState().admit(sessionId, {- runId: result.runId,- userMessageId: result.messageId,+ runId,+ userMessageId: messageId,state: result.delivery === 'queued' ? 'queued' : 'pending',});}