Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): attachments, voice, slash commands and a Web chip in the composer
trohitg0b8952ca6373
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex e3081064..29a671b8 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -367,6 +367,8 @@ const DashboardContent: React.FC = () => {// Console panel visibility from store (database-backed)const consolePanelVisible = useAppStore((state) => state.consolePanelVisible);const toggleConsolePanelVisible = useAppStore((state) => state.toggleConsolePanelVisible);+ const setConsolePanelVisible = useAppStore((state) => state.setConsolePanelVisible);+ const requestChatFocus = useAppStore((state) => state.requestChatFocus);// Context menu state for node right-clickconst [contextMenu, setContextMenu] = React.useState<{@@ -1366,6 +1368,10 @@ const DashboardContent: React.FC = () => {toggleSidebar,toggleComponentPalette,toggleConsolePanel: toggleConsolePanelVisible,+ focusChat: () => {+ setConsolePanelVisible(true);+ requestChatFocus();+ },}}/>diff --git a/client/src/components/ui/CommandPaletteHost.tsx b/client/src/components/ui/CommandPaletteHost.tsxindex da763025..fd7e75c5 100644--- a/client/src/components/ui/CommandPaletteHost.tsx+++ b/client/src/components/ui/CommandPaletteHost.tsx@@ -26,6 +26,7 @@ import {PanelLeftClose,PanelRightClose,Terminal,+ MessageSquare,Palette as PaletteIcon,Download,Upload,@@ -54,6 +55,9 @@ export interface CommandPaletteHandlers {toggleSidebar: () => void;toggleComponentPalette: () => void;toggleConsolePanel: () => void;+ /** Open the console's Chat and put the cursor in its message box (the+ * editor's way to what ⌘K does on Home, where ⌘K is the palette). */+ focusChat?: () => void;}const THEME_LABEL: Record<ThemeName, string> = {@@ -192,6 +196,9 @@ export const CommandPaletteHost: React.FC<Props> = ({ open, onOpenChange, handleicon: KeyRound,onRun: handlers.openCredentials,},+ ...(handlers.focusChat+ ? [{ id: 'open.chat', label: 'Focus Chat', group: 'Open', icon: MessageSquare, onRun: handlers.focusChat }]+ : []),// ── View toggles ───────────────────────────────────────────────{diff --git a/client/src/components/ui/command.tsx b/client/src/components/ui/command.tsxnew file mode 100644index 00000000..34f8c8d0--- /dev/null+++ b/client/src/components/ui/command.tsx@@ -0,0 +1,95 @@+import * as React from "react"+import { Command as CommandPrimitive } from "cmdk"++import { cn } from "@/lib/utils"++/*+ * Command — a filterable list of actions (shadcn, over cmdk, on the repo's+ * tokens). cmdk supplies the listbox semantics, the selected item and+ * keyboard movement while focus is inside the list. A list driven from+ * another field (a message box's slash menu) keeps focus in that field:+ * it controls `value` and filters itself (`shouldFilter={false}`).+ */+function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {+ return (+ <CommandPrimitive+ data-slot="command"+ className={cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", className)}+ {...props}+ />+ )+}++function CommandInput({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Input>) {+ return (+ <div data-slot="command-input-wrapper" className="flex h-9 items-center gap-2 border-b border-border-default px-3">+ <CommandPrimitive.Input+ data-slot="command-input"+ className={cn(+ "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden placeholder:text-fg-faint disabled:cursor-not-allowed disabled:opacity-50",+ className+ )}+ {...props}+ />+ </div>+ )+}++function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {+ return (+ <CommandPrimitive.List+ data-slot="command-list"+ className={cn("max-h-75 scroll-py-1 overflow-x-hidden overflow-y-auto", className)}+ {...props}+ />+ )+}++function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {+ return <CommandPrimitive.Empty data-slot="command-empty" className="py-6 text-center text-sm text-fg-muted" {...props} />+}++function CommandGroup({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Group>) {+ return (+ <CommandPrimitive.Group+ data-slot="command-group"+ className={cn(+ "overflow-hidden p-1 text-fg-default [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-fg-muted",+ className+ )}+ {...props}+ />+ )+}++function CommandSeparator({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Separator>) {+ return <CommandPrimitive.Separator data-slot="command-separator" className={cn("-mx-1 h-px bg-border-default", className)} {...props} />+}++function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) {+ return (+ <CommandPrimitive.Item+ data-slot="command-item"+ className={cn(+ "menu-pop-item relative flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[selected=true]:bg-bg-hover data-[selected=true]:text-fg-default [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-fg-muted",+ className+ )}+ {...props}+ />+ )+}++function CommandShortcut({ className, ...props }: React.ComponentProps<"span">) {+ return <span data-slot="command-shortcut" className={cn("ml-auto text-xs tracking-widest text-fg-muted", className)} {...props} />+}++export {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator,+ CommandShortcut,+}diff --git a/client/src/components/ui/popover.tsx b/client/src/components/ui/popover.tsxnew file mode 100644index 00000000..275aba79--- /dev/null+++ b/client/src/components/ui/popover.tsx@@ -0,0 +1,46 @@+import * as React from "react"+import { Popover as PopoverPrimitive } from "radix-ui"++import { cn } from "@/lib/utils"++/*+ * Popover — floating content anchored to a trigger or an anchor (shadcn,+ * on the repo's tokens). Radix supplies placement, collision handling,+ * focus management and dismissal. `menu-pop` is the design-handoff hook+ * the stylized themes decorate, as on the dropdown menu.+ */+function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {+ return <PopoverPrimitive.Root data-slot="popover" {...props} />+}++function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />+}++function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {+ return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />+}++function PopoverContent({+ className,+ align = "center",+ sideOffset = 4,+ ...props+}: React.ComponentProps<typeof PopoverPrimitive.Content>) {+ return (+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Content+ data-slot="popover-content"+ align={align}+ sideOffset={sideOffset}+ className={cn(+ "menu-pop z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 motion-reduce:animate-none",+ className+ )}+ {...props}+ />+ </PopoverPrimitive.Portal>+ )+}++export { Popover, PopoverAnchor, PopoverContent, PopoverTrigger }diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsxindex d38bc3e6..4cecd688 100644--- a/client/src/features/chat/ChatPane.tsx+++ b/client/src/features/chat/ChatPane.tsx@@ -16,6 +16,12 @@* (data/approvals.ts). Ctrl/Cmd+Enter sends the newest one; the Ask first* chip beside the box changes the rule for everything they send.*+ * Files go with a message where the chat allows them: Attach, a paste, or+ * a drop anywhere on the chat (DropOverlay), all through one+ * `addAttachments` (composer/attachments.ts). The box also dictates, offers+ * slash commands and, in an empty chat, suggestions (data/chatContext.ts),+ * and the Web chip keeps the employee off web search for the next messages.+ ** The owner can change the conversation (data/branches.ts, TurnActions):* edit one of their messages in place (ArrowUp in an empty box edits the* last one), try the latest answer again, move between the versions of a@@ -23,11 +29,26 @@* on its way or the employee is answering; a refusal says why.*/-import { useCallback, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type Ref } from 'react';+import {+ useCallback,+ useImperativeHandle,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+ type DragEvent,+ type KeyboardEvent,+ type Ref,+} from 'react';import { cn } from '@/lib/utils';import { ApprovalsContext, type ApprovalsValue } from './approval/context';import { StandaloneApprovals } from './approval/StandaloneApprovals';import { AskFirstChip } from './composer/AskFirstChip';+import { addAttachments } from './composer/attachments';+import { DropOverlay } from './composer/DropOverlay';+import { Suggestions } from './composer/Suggestions';+import { WebChip } from './composer/WebChip';+import { canRecord, useChatContext, useDictation, type ChatCommand } from './data/chatContext';import {NO_APPROVALS,isOpenApproval,@@ -53,6 +74,7 @@ import { useUiStateSync } from './data/uiState';import { Composer } from './composer/Composer';import { asksWhatItSays, type ChatUiActions } from './genui/actions';import type { ChatHost, ChatPaneHandle } from './host';+import { useAttachmentStore } from './state/attachmentStore';import { newClientMessageId, useComposerStore } from './state/composerStore';import { ChatThread } from './thread/ChatThread';import { TurnActionsContext, type TurnActions } from './thread/turnActions';@@ -136,9 +158,19 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandconst submit = () => {const store = useComposerStore.getState();- if (busy || !thread.data || !(store.drafts[sessionId]?.text ?? '').trim()) return;+ const box = useAttachmentStore.getState().boxes[sessionId] ?? [];+ const hasText = Boolean((store.drafts[sessionId]?.text ?? '').trim());+ const hasFiles = box.some((item) => item.state === 'ready');+ if (busy || !thread.data || box.some((item) => item.state === 'uploading') || !(hasText || hasFiles)) return;const draft = store.takeForSend(sessionId);- send.mutate({ ...draft, text: draft.text.trim() });+ const attachments = useAttachmentStore.getState().takeReady(sessionId);+ const web = store.web[sessionId];+ send.mutate({+ ...draft,+ text: draft.text.trim(),+ ...(attachments.length ? { attachments } : {}),+ ...(web === false ? { options: { web: false } } : {}),+ });};const stopAnswer = () => {@@ -261,8 +293,70 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandstopAnswer();};+ // What the box offers here: files, dictation, commands, Web.+ const contextQuery = useChatContext(sessionId);+ const chatContext = contextQuery.data;+ const dictationQuery = useDictation(sessionId, Boolean(workflowId) && composer === 'send' && canRecord());+ const web = useComposerStore((state) => state.web[sessionId] !== false);+ const addFiles = useCallback(+ (files: File[]) => {+ if (!workflowId) return;+ void addAttachments(sessionId, workflowId, files).then((problem) => {+ if (problem) notify(problem, 'info');+ });+ },+ [sessionId, workflowId, notify],+ );+ const filesAllowed = Boolean(workflowId && chatContext?.attachments && composer !== 'closed');+ const fillBox = useCallback(+ (command: ChatCommand) => {+ useComposerStore.getState().setText(sessionId, command.fill);+ requestAnimationFrame(() => {+ const box = boxRef.current;+ if (!box) return;+ box.focus();+ box.setSelectionRange(command.fill.length, command.fill.length);+ });+ },+ [sessionId],+ );+ const suggestions = useMemo(() => (chatContext?.commands ?? []).filter((command) => command.suggest), [chatContext]);++ // A drop anywhere on the chat adds the files, as Attach does.+ const [dragging, setDragging] = useState(false);+ const dragDepth = useRef(0);+ const carriesFiles = (event: DragEvent<HTMLElement>) => Array.from(event.dataTransfer?.types ?? []).includes('Files');+ const dropHandlers = filesAllowed+ ? {+ onDragEnter: (event: DragEvent<HTMLElement>) => {+ if (!carriesFiles(event)) return;+ event.preventDefault();+ dragDepth.current += 1;+ setDragging(true);+ },+ onDragOver: (event: DragEvent<HTMLElement>) => {+ if (carriesFiles(event)) event.preventDefault();+ },+ onDragLeave: () => {+ dragDepth.current = Math.max(0, dragDepth.current - 1);+ if (dragDepth.current === 0) setDragging(false);+ },+ onDrop: (event: DragEvent<HTMLElement>) => {+ if (!carriesFiles(event)) return;+ event.preventDefault();+ dragDepth.current = 0;+ setDragging(false);+ addFiles(Array.from(event.dataTransfer.files));+ },+ }+ : {};+const askFirst = askFirstQuery.data?.askFirst;- const chips =+ const webChip =+ workflowId && chatContext?.web ? (+ <WebChip on={web} name={persona.name} compact={compact} onChange={(next) => useComposerStore.getState().setWeb(sessionId, next)} />+ ) : null;+ const askFirstChip =workflowId && askFirstQuery.data ? (<AskFirstChipon={askFirst === true}@@ -278,11 +372,24 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand}/>) : null;+ const chips =+ webChip || askFirstChip ? (+ <>+ {webChip}+ {askFirstChip}+ </>+ ) : null;return (<ApprovalsContext.Provider value={approvalsValue}><TurnActionsContext.Provider value={turnActions}>- <section aria-label={`Chat with ${persona.name}`} onKeyDown={onKeyDown} className="flex min-h-0 w-full flex-1 flex-col">+ <section+ aria-label={`Chat with ${persona.name}`}+ onKeyDown={onKeyDown}+ {...dropHandlers}+ className="relative flex min-h-0 w-full flex-1 flex-col"+ >+ {dragging && <DropOverlay name={persona.name} />}<ChatThreadpersona={persona}turns={turns}@@ -298,7 +405,16 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand</>) : null}- emptyState={host.emptyState}+ emptyState={+ composer === 'send' && suggestions.length > 0 ? (+ <div className="flex flex-col items-center gap-4">+ {host.emptyState}+ <Suggestions items={suggestions} onPick={fillBox} />+ </div>+ ) : (+ host.emptyState+ )+ }liveNote={host.liveNote}compact={compact}canStop={composer !== 'closed'}@@ -324,6 +440,9 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandboxRef={boxRef}chips={chips}onEditLast={editLast}+ onAddFiles={filesAllowed ? addFiles : undefined}+ dictation={workflowId && dictationQuery.data ? { workflowId, notify } : null}+ commands={chatContext?.commands}/>)}{host.footnote && <p className="m-0 text-center text-xs text-fg-muted">{host.footnote}</p>}diff --git a/client/src/features/chat/__tests__/composer.test.tsx b/client/src/features/chat/__tests__/composer.test.tsxnew file mode 100644index 00000000..cd636911--- /dev/null+++ b/client/src/features/chat/__tests__/composer.test.tsx@@ -0,0 +1,273 @@+/**+ * The message box's extras against a fake server: Attach, a paste and a drop+ * add files the same way (CLAUDE.md rule 9: the drop has a pointer+ * alternative reaching the same state), files alone are a message and wait+ * for their uploads, slash commands fill the box, Web off goes with the next+ * message, suggestions fill an empty chat's box, and dictation puts its text+ * in the box.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';++const sendRequest = vi.fn();+const upload = vi.fn();++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));+vi.mock('@/lib/workspaceUpload', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/lib/workspaceUpload')>()),+ uploadToWorkspace: (file: File, workflowId: string) => upload(file, workflowId),+}));++import { resetChatRunStore } from '@/stores/chatRunStore';+import { ChatPane } from '../ChatPane';+import type { ChatHost } from '../host';+import { useAttachmentStore } from '../state/attachmentStore';+import { useComposerStore } from '../state/composerStore';+import '../markdown/ReplyMarkdown';++type Wire = Record<string, unknown>;+let server: { messages: Wire[]; context: Wire; dictation: boolean };++const ref = (name: string, mime = 'text/plain') => ({+ kind: mime.startsWith('image/') ? 'image' : 'file',+ path: `uploads/${name}`,+ workflow_id: 'w1',+ filename: name,+ mime_type: mime,+ size_bytes: 2048,+ url: `/api/workspace/w1/files/uploads/${name}`,+});++function host(patch: Partial<ChatHost> = {}): ChatHost {+ return { kind: 'home', sessionId: 'w1', scope: 'all', persona: { name: 'Maya', colorRole: 'agent' }, composer: 'send', notify: vi.fn(), ...patch };+}++function renderPane(chat: ChatHost = host()) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <QueryClientProvider client={client}>+ <ChatPane host={chat} />+ </QueryClientProvider>,+ );+ return chat;+}++function requests(kind: string): Wire[] {+ return sendRequest.mock.calls.filter(([name]) => name === kind).map(([, data]) => data as Wire);+}++const box = () => screen.getByRole('textbox', { name: 'Message Maya' });++/** The box's files without what differs between adds (ids, thumbnails). */+function boxState() {+ return (useAttachmentStore.getState().boxes.w1 ?? []).map(({ name, size, mime, state, ref: stored, error }) => ({ name, size, mime, state, ref: stored, error }));+}++beforeEach(() => {+ // cmdk scrolls the highlighted command into view; jsdom has no layout.+ if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = () => undefined;+ resetChatRunStore();+ useComposerStore.setState({ drafts: {}, web: {} });+ useAttachmentStore.setState({ boxes: {} });+ upload.mockReset().mockImplementation(async (file: File) => ref(file.name, file.type || 'text/plain'));+ server = {+ messages: [],+ context: {+ success: true,+ commands: [+ { command: '/schedule', description: 'Check a day in the calendar', fill: 'What does tomorrow look like?', suggest: true },+ { command: '/summarize', description: 'Summarize this conversation', fill: 'Summarize what we’ve agreed so far.', suggest: false },+ ],+ capabilities: { attachments: true, web: true },+ limits: { max_attachments: 6 },+ },+ dictation: false,+ };+ sendRequest.mockReset().mockImplementation(async (kind: string, data: Wire) => {+ switch (kind) {+ case 'chat_subscribe':+ return { success: true, session_id: data.session_id, hub_epoch: 'e1', active_runs: [] };+ case 'get_chat_messages':+ return { success: true, messages: server.messages, thread: { active_leaf_id: null, revision: 1 }, active_runs: [] };+ case 'get_chat_context':+ return server.context;+ case 'dictation_status':+ return { success: true, available: server.dictation };+ case 'transcribe_audio':+ return { success: true, text: 'Send reminders for tomorrow' };+ case 'send_chat_message':+ return { success: true, message_id: 'm1', run_id: 'r1', delivery: 'now' };+ default:+ return { success: true };+ }+ });+});++describe('adding files', () => {+ const file = () => new File(['a,b'], 'prices.txt', { type: 'text/plain' });++ async function viaPicker() {+ const input = document.querySelector('input[type="file"]') as HTMLInputElement;+ fireEvent.change(input, { target: { files: [file()] } });+ }+ async function viaPaste() {+ fireEvent.paste(box(), { clipboardData: { files: [file()], types: ['Files'] } });+ }+ async function viaDrop() {+ const pane = screen.getByRole('region', { name: 'Chat with Maya' });+ fireEvent.dragEnter(pane, { dataTransfer: { files: [file()], types: ['Files'] } });+ expect(screen.getByText('Drop files for Maya')).toBeInTheDocument();+ fireEvent.drop(pane, { dataTransfer: { files: [file()], types: ['Files'] } });+ expect(screen.queryByText('Drop files for Maya')).not.toBeInTheDocument();+ }++ it.each([+ ['the picker', viaPicker],+ ['a paste', viaPaste],+ ['a drop', viaDrop],+ ])('adds the same file through %s', async (_how, add) => {+ renderPane();+ await screen.findByRole('button', { name: 'Attach files' });+ await add();+ await waitFor(() => expect(boxState()[0]?.state).toBe('ready'));+ expect(boxState()).toEqual([{ name: 'prices.txt', size: 3, mime: 'text/plain', state: 'ready', ref: ref('prices.txt'), error: null }]);+ expect(upload).toHaveBeenCalledWith(expect.any(File), 'w1');+ expect(screen.getByRole('button', { name: 'Remove prices.txt' })).toBeInTheDocument();+ });++ it('sends files alone, as paths, once they have uploaded', async () => {+ let finish: (value: unknown) => void = () => undefined;+ upload.mockImplementation(() => new Promise((resolve) => (finish = resolve)));+ renderPane();+ await screen.findByRole('button', { name: 'Attach files' });+ await act(async () => {+ fireEvent.change(document.querySelector('input[type="file"]') as HTMLInputElement, { target: { files: [file()] } });+ });+ expect(screen.getByRole('status', { name: 'Uploading prices.txt' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();+ await act(async () => finish(ref('prices.txt')));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ await waitFor(() => expect(requests('send_chat_message')).toHaveLength(1));+ expect(requests('send_chat_message')[0]).toMatchObject({ message: '', attachments: [{ path: 'uploads/prices.txt' }] });+ expect(boxState()).toEqual([]);+ });++ it('shows the files a message carried, and no bubble for files alone', async () => {+ server.messages = [+ { id: 'm1', role: 'user', text: '', message: '', timestamp: '2026-10-04T09:00:00Z', attachments: [ref('shelf.png', 'image/png'), ref('prices.txt')] },+ ];+ renderPane();+ const files = await screen.findByRole('list', { name: 'Attached files' });+ expect(within(files).getByRole('img', { name: 'shelf.png' })).toHaveAttribute('src', expect.stringContaining('/api/workspace/w1/files/uploads/shelf.png'));+ expect(within(files).getByText('prices.txt')).toBeInTheDocument();+ expect(document.querySelector('.chat-msg-user')).toBeNull();+ });+});++describe('commands, Web and suggestions', () => {+ it('fills the box from a slash command', async () => {+ renderPane();+ await screen.findByPlaceholderText(/Type \/ for commands/);+ fireEvent.change(box(), { target: { value: '/' } });+ const list = await screen.findByRole('listbox', { name: 'Commands' });+ expect(within(list).getAllByRole('option').map((option) => option.textContent)).toEqual([+ '/scheduleCheck a day in the calendar',+ '/summarizeSummarize this conversation',+ ]);+ fireEvent.keyDown(box(), { key: 'ArrowDown' });+ // The box controls the list and names the highlighted command.+ expect(box()).toHaveAttribute('aria-controls', list.id);+ expect(box()).toHaveAttribute('aria-activedescendant', within(list).getAllByRole('option')[1].id);+ fireEvent.keyDown(box(), { key: 'Enter' });+ expect(box()).toHaveValue('Summarize what we’ve agreed so far.');+ expect(box()).not.toHaveAttribute('aria-activedescendant');+ expect(screen.queryByRole('listbox', { name: 'Commands' })).not.toBeInTheDocument();+ expect(requests('send_chat_message')).toHaveLength(0);+ });++ it('closes the list with Esc, and shows none for what matches nothing', async () => {+ renderPane();+ await screen.findByPlaceholderText(/Type \/ for commands/);+ fireEvent.change(box(), { target: { value: '/sch' } });+ await screen.findByRole('listbox', { name: 'Commands' });+ fireEvent.keyDown(box(), { key: 'Escape' });+ expect(screen.queryByRole('listbox', { name: 'Commands' })).not.toBeInTheDocument();+ fireEvent.change(box(), { target: { value: '/nothing' } });+ expect(screen.queryByRole('listbox', { name: 'Commands' })).not.toBeInTheDocument();+ });++ it('sends with Web off until it is turned back on', async () => {+ renderPane();+ const web = await screen.findByRole('button', { name: 'Web' });+ expect(web).toHaveAttribute('aria-pressed', 'true');+ fireEvent.click(web);+ fireEvent.change(box(), { target: { value: 'What did we sell?' } });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled());+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));+ await waitFor(() => expect(requests('send_chat_message')).toHaveLength(1));+ expect(requests('send_chat_message')[0]).toMatchObject({ options: { web: false } });+ });++ it('suggests what to ask in an empty chat', async () => {+ renderPane();+ fireEvent.click(await screen.findByRole('button', { name: /Check a day in the calendar/ }));+ expect(box()).toHaveValue('What does tomorrow look like?');+ });++ it('offers nothing of this where the chat allows none', async () => {+ server.context = { success: true, commands: [], capabilities: { attachments: false, web: false }, limits: { max_attachments: 6 } };+ renderPane();+ await screen.findByPlaceholderText(/^Message Maya…$/);+ expect(screen.queryByRole('button', { name: 'Attach files' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Web' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Dictate' })).not.toBeInTheDocument();+ });+});++describe('dictation', () => {+ it('records, turns it into text and puts it in the box', async () => {+ server.dictation = true;+ const stop = vi.fn();+ class FakeRecorder {+ static isTypeSupported = () => true;+ mimeType = 'audio/webm';+ state = 'inactive';+ ondataavailable: ((event: { data: Blob }) => void) | null = null;+ onstop: (() => void) | null = null;+ start() {+ this.state = 'recording';+ }+ stop() {+ this.state = 'inactive';+ stop();+ this.ondataavailable?.({ data: new Blob(['audio'], { type: 'audio/webm' }) });+ this.onstop?.();+ }+ }+ const track = { stop: vi.fn() };+ vi.stubGlobal('MediaRecorder', FakeRecorder);+ Object.defineProperty(navigator, 'mediaDevices', {+ value: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [track] }) },+ configurable: true,+ });+ vi.stubGlobal('AudioContext', undefined);+ upload.mockImplementation(async (file: File) => ref(file.name, 'audio/webm'));++ useComposerStore.getState().setText('w1', 'Please');+ renderPane();+ fireEvent.click(await screen.findByRole('button', { name: 'Dictate' }));+ expect(await screen.findByLabelText('Recording time')).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Use dictation' }));+ await waitFor(() => expect(box()).toHaveValue('Please Send reminders for tomorrow'));+ expect(stop).toHaveBeenCalled();+ expect(track.stop).toHaveBeenCalled();+ expect(requests('transcribe_audio')[0]).toMatchObject({ session_id: 'w1', path: expect.stringMatching(/^uploads\/dictation-\d+\.webm$/) });+ vi.unstubAllGlobals();+ });+});diff --git a/client/src/features/chat/composer/AttachmentChips.tsx b/client/src/features/chat/composer/AttachmentChips.tsxnew file mode 100644index 00000000..7bb6d088--- /dev/null+++ b/client/src/features/chat/composer/AttachmentChips.tsx@@ -0,0 +1,64 @@+/**+ * The files in the message box (design handoff chat, "Composer"): an image+ * as a thumbnail, any other file as a chip with its type, name and size,+ * each with Remove. One still uploading shows a spinner; one that failed+ * says why, and Remove takes it out.+ */++import { Loader2, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import type { BoxAttachment } from '../state/attachmentStore';+import { extensionLabel, sizeLabel } from './attachments';++function RemoveButton({ name, onRemove }: { name: string; onRemove: () => void }) {+ return (+ <Button+ variant="quiet"+ size="icon-xs"+ onClick={onRemove}+ aria-label={`Remove ${name}`}+ className="absolute -top-1.5 -right-1.5 size-5 rounded-full border border-border-default bg-bg-panel"+ >+ <X aria-hidden className="size-3" strokeWidth={2.2} />+ </Button>+ );+}++export function AttachmentChips({ items, onRemove }: { items: readonly BoxAttachment[]; onRemove: (id: string) => void }) {+ if (items.length === 0) return null;+ return (+ <ul aria-label="Attached files" className="m-0 flex list-none flex-wrap gap-2 p-0">+ {items.map((item) => (+ <li key={item.id} className="relative" title={item.error ?? item.name}>+ {item.preview && item.state !== 'failed' ? (+ <img src={item.preview} alt={item.name} className="block size-14 rounded-lg border border-border-default object-cover" />+ ) : (+ <span+ className={cn(+ 'flex h-12 max-w-55 items-center gap-2.5 rounded-lg border bg-bg-panel py-0 pr-3.5 pl-2',+ item.state === 'failed' ? 'border-action-stop-border' : 'border-border-default',+ )}+ >+ <span className="grid size-8 shrink-0 place-items-center rounded-md bg-action-config-soft font-mono text-2xs font-semibold text-action-config-ink">+ {extensionLabel(item.name)}+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-sm font-medium text-fg-default">{item.name}</span>+ <span className={cn('truncate font-mono text-2xs', item.state === 'failed' ? 'text-action-stop-ink' : 'text-fg-faint')}>+ {item.state === 'failed' ? item.error : sizeLabel(item.size)}+ </span>+ </span>+ </span>+ )}+ {item.state === 'uploading' && (+ <span role="status" aria-label={`Uploading ${item.name}`} className="absolute inset-0 grid place-items-center rounded-lg bg-bg-scrim-soft">+ <Loader2 aria-hidden className="size-4 animate-spin text-fg-muted" />+ </span>+ )}+ <RemoveButton name={item.name} onRemove={() => onRemove(item.id)} />+ </li>+ ))}+ </ul>+ );+}diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsxindex 10833f9c..572f376e 100644--- a/client/src/features/chat/composer/Composer.tsx+++ b/client/src/features/chat/composer/Composer.tsx@@ -6,19 +6,36 @@* method's composition never sends (lib/composerKeys). Esc stops an answer* (ChatPane); ArrowUp in an empty box edits the owner's last message.*+ * Where the chat allows them: files (Attach, a paste, or a drop on the chat,+ * all through `onAddFiles`), shown above the text as they upload; a+ * microphone that dictates into the box (composer/VoiceRecorder.tsx); and+ * slash commands, a list that opens while the box holds one word starting+ * with `/` (composer/SlashMenu.tsx). A message can be files alone; Send+ * waits while one is still uploading.+ ** 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.*/-import { ArrowUp, Square } from 'lucide-react';-import type { KeyboardEvent, ReactNode, RefObject } from 'react';+import { ArrowUp, Mic, Plus, Square } from 'lucide-react';+import { useId, useRef, useState, type ClipboardEvent, type KeyboardEvent, type ReactNode, type RefObject } from 'react';import { Button } from '@/components/ui/button';import { Textarea } from '@/components/ui/textarea';import { isSendKey } from '@/lib/composerKeys';import { useAutoGrow } from '@/lib/useAutoGrow';import { cn } from '@/lib/utils';+import type { ChatCommand } from '../data/chatContext';+import type { NotifyTone } from '../host';+import { useAttachmentStore, useBoxAttachments } from '../state/attachmentStore';import { useComposerDraft, useComposerStore } from '../state/composerStore';+import { AttachmentChips } from './AttachmentChips';+import { filesOf } from './attachments';+import { matchCommands, slashQuery } from './slash';+import { SlashMenu } from './SlashMenu';+import { VoiceRecorder } from './VoiceRecorder';++const NO_COMMANDS: readonly ChatCommand[] = [];export interface ComposerProps {sessionId: string;@@ -35,26 +52,93 @@ export interface ComposerProps {compact: boolean;/** The text box, for the host's focus requests. */boxRef: RefObject<HTMLTextAreaElement | null>;- /** Chips beside the button (Ask first). */+ /** Chips beside the button (Web, Ask first). */chips?: ReactNode;/** ArrowUp in an empty box: edit the owner's last message. False when* there is none to edit, so the key does what it always does. */onEditLast?: () => boolean;+ /** Files can go with a message: Attach and a paste add them here. */+ onAddFiles?: (files: File[]) => void;+ /** Dictation, where a speech provider can turn a recording into text. */+ dictation?: { workflowId: string; notify: (message: string, tone: NotifyTone) => void } | null;+ /** The slash commands the box offers. */+ commands?: readonly ChatCommand[];}-export function Composer({ sessionId, name, ready, busy, onSend, onStop, stopping = false, compact, boxRef, chips, onEditLast }: ComposerProps) {+export function Composer({+ sessionId,+ name,+ ready,+ busy,+ onSend,+ onStop,+ stopping = false,+ compact,+ boxRef,+ chips,+ onEditLast,+ onAddFiles,+ dictation = null,+ commands = NO_COMMANDS,+}: ComposerProps) {const draft = useComposerDraft(sessionId);const setText = useComposerStore((state) => state.setText);+ const attachments = useBoxAttachments(sessionId);+ const fileRef = useRef<HTMLInputElement>(null);+ const listId = useId();+ const [recording, setRecording] = useState(false);useAutoGrow(boxRef, draft.text);- const canSend = ready && !busy && draft.text.trim().length > 0;++ const uploading = attachments.some((item) => item.state === 'uploading');+ const finished = attachments.some((item) => item.state === 'ready');+ const canSend = ready && !busy && !uploading && (draft.text.trim().length > 0 || 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.+ const query = slashQuery(draft.text);+ const items = query === null ? NO_COMMANDS : matchCommands(commands, query);+ const [dismissed, setDismissed] = useState<string | null>(null);+ const [active, setActive] = useState(0);+ const [lastQuery, setLastQuery] = useState(query);+ if (query !== lastQuery) {+ setLastQuery(query);+ setActive(0);+ }+ const menuOpen = !recording && items.length > 0 && dismissed !== draft.text;+ const highlighted = Math.min(active, Math.max(0, items.length - 1));++ const pick = (command: ChatCommand) => {+ setText(sessionId, command.fill);+ setDismissed(command.fill);+ requestAnimationFrame(() => {+ const box = boxRef.current;+ if (!box) return;+ box.focus();+ box.setSelectionRange(command.fill.length, command.fill.length);+ });+ };const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {- if (- event.key === 'ArrowUp' &&- !draft.text &&- !(event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) &&- onEditLast?.()- ) {+ const plain = !(event.shiftKey || event.ctrlKey || event.metaKey || event.altKey);+ if (menuOpen) {+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {+ event.preventDefault();+ const step = event.key === 'ArrowDown' ? 1 : -1;+ setActive((highlighted + step + items.length) % items.length);+ return;+ }+ if ((event.key === 'Enter' || event.key === 'Tab') && plain && !event.nativeEvent.isComposing) {+ event.preventDefault();+ pick(items[highlighted]);+ return;+ }+ if (event.key === 'Escape') {+ event.preventDefault();+ setDismissed(draft.text);+ return;+ }+ }+ if (event.key === 'ArrowUp' && !draft.text && plain && onEditLast?.()) {event.preventDefault();return;}@@ -63,8 +147,16 @@ export function Composer({ sessionId, name, ready, busy, onSend, onStop, stoppinif (canSend) onSend();};+ const onPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {+ const files = filesOf(event.clipboardData);+ if (!onAddFiles || files.length === 0) return;+ event.preventDefault();+ onAddFiles(files);+ };+const iconSize = compact ? 'size-3.5' : 'size-4';- const button = onStop ? (+ const round = cn('shrink-0 rounded-full', compact ? 'size-7' : 'size-8.5');+ const sendButton = onStop ? (<Buttonvariant="invert"size="icon"@@ -72,7 +164,7 @@ export function Composer({ sessionId, name, ready, busy, onSend, onStop, stoppinonClick={onStop}aria-label={stopping ? 'Stopping' : 'Stop reply'}title={stopping ? 'Stopping…' : 'Stop (Esc)'}- className={cn('shrink-0 rounded-full', compact ? 'size-7' : 'size-8.5')}+ className={round}><Square aria-hidden fill="currentColor" strokeWidth={0} className={compact ? 'size-2.75' : 'size-3'} /></Button>@@ -83,45 +175,120 @@ export function Composer({ sessionId, name, ready, busy, onSend, onStop, stoppindisabled={!canSend}onClick={onSend}aria-label="Send"- title={busy ? `${name} is still answering` : 'Send (Enter)'}- className={cn('shrink-0 rounded-full', compact ? 'size-7' : 'size-8.5')}+ 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>);+ const attachButton = onAddFiles ? (+ <>+ <input+ ref={fileRef}+ type="file"+ multiple+ hidden+ onChange={(event) => {+ const files = filesOf(event.target);+ event.target.value = '';+ if (files.length) onAddFiles(files);+ }}+ />+ <Button+ variant="quiet"+ size="icon"+ disabled={recording}+ onClick={() => fileRef.current?.click()}+ aria-label="Attach files"+ title="Attach files"+ className={cn(round, 'border-border-default')}+ >+ <Plus aria-hidden className={iconSize} strokeWidth={2} />+ </Button>+ </>+ ) : null;+ const micButton =+ dictation && !recording && !onStop ? (+ <Button variant="quiet" size="icon" onClick={() => setRecording(true)} aria-label="Dictate" title="Dictate" className={round}>+ <Mic aria-hidden className={iconSize} strokeWidth={1.9} />+ </Button>+ ) : null;- return (- <div+ const box = recording && dictation ? (+ <VoiceRecorder+ sessionId={sessionId}+ workflowId={dictation.workflowId}+ compact={compact}+ notify={dictation.notify}+ onClose={() => {+ setRecording(false);+ requestAnimationFrame(() => boxRef.current?.focus());+ }}+ onText={(text) => {+ const current = useComposerStore.getState().drafts[sessionId]?.text ?? '';+ setText(sessionId, current.trim() ? `${current.trimEnd()} ${text}` : text);+ }}+ />+ ) : (+ <Textarea+ ref={boxRef}+ variant="bare"+ rows={1}+ value={draft.text}+ onChange={(event) => setText(sessionId, event.target.value)}+ onKeyDown={onKeyDown}+ onPaste={onPaste}+ aria-label={`Message ${name}`}+ aria-autocomplete={commands.length ? 'list' : undefined}+ placeholder={commands.length ? `Message ${name}… Type / for commands` : `Message ${name}…`}className={cn(- 'chat-composer relative flex border border-border-default bg-bg-panel transition-colors duration-(--dur-slow) focus-within:border-border-strong',- compact ? 'items-end gap-2 rounded-lg py-1.5 pr-1.5 pl-3' : 'flex-col gap-2 rounded-card py-2.5 pr-2.5 pb-2 pl-3.5 shadow-modal',+ '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',)}+ />+ );+ const files = <AttachmentChips items={attachments} onRemove={(id) => useAttachmentStore.getState().remove(sessionId, id)} />;++ return (+ <SlashMenu+ open={menuOpen}+ listId={listId}+ items={items}+ active={highlighted}+ boxRef={boxRef}+ onPick={pick}+ onActive={setActive}+ onDismiss={() => setDismissed(draft.text)}>- <Textarea- ref={boxRef}- variant="bare"- rows={1}- value={draft.text}- onChange={(event) => setText(sessionId, event.target.value)}- onKeyDown={onKeyDown}- aria-label={`Message ${name}`}- placeholder={`Message ${name}…`}+ <divclassName={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',+ 'chat-composer relative flex border border-border-default bg-bg-panel transition-colors duration-(--dur-slow) focus-within:border-border-strong',+ compact ? 'flex-col gap-1.5 rounded-lg py-1.5 pr-1.5 pl-3' : 'flex-col gap-2 rounded-card py-2.5 pr-2.5 pb-2 pl-3.5 shadow-modal',)}- />- {compact ? (- <div className="flex shrink-0 items-center gap-1.5">- {chips}- {button}- </div>- ) : (- <div className="flex items-center gap-1.5">- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">{chips}</div>- {button}- </div>- )}- </div>+ >+ {attachments.length > 0 && <div className="pt-1">{files}</div>}+ {compact ? (+ <div className="flex items-end gap-2">+ <div className="min-w-0 flex-1">{box}</div>+ <div className="flex shrink-0 items-center gap-1.5">+ {attachButton}+ {chips}+ {micButton}+ {!recording && sendButton}+ </div>+ </div>+ ) : (+ <>+ {box}+ <div className="flex items-center gap-1.5">+ {attachButton}+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">{chips}</div>+ {micButton}+ {!recording && sendButton}+ </div>+ </>+ )}+ </div>+ </SlashMenu>);}diff --git a/client/src/features/chat/composer/DropOverlay.tsx b/client/src/features/chat/composer/DropOverlay.tsxnew file mode 100644index 00000000..0304031a--- /dev/null+++ b/client/src/features/chat/composer/DropOverlay.tsx@@ -0,0 +1,24 @@+/**+ * What covers the chat while files are dragged over it (design handoff chat,+ * "Drop overlay"): a dashed frame saying the files go to the employee. It+ * only shows; ChatPane takes the drop and adds the files the way the Attach+ * button does (composer/attachments.ts).+ */++import { Upload } from 'lucide-react';+import { MAX_ATTACHMENTS } from './attachments';++export function DropOverlay({ name }: { name: string }) {+ return (+ <div+ aria-hidden+ className="pointer-events-none absolute inset-2.5 z-20 grid place-items-center rounded-xl border-2 border-dashed border-action-tools-border bg-bg-scrim-soft backdrop-blur-(--blur-scrim)"+ >+ <div className="flex flex-col items-center gap-2 text-center">+ <Upload aria-hidden className="size-7 text-action-tools-ink" strokeWidth={1.75} />+ <span className="text-md font-semibold text-fg-default">Drop files for {name}</span>+ <span className="text-sm text-fg-muted">Documents, photos and spreadsheets, up to {MAX_ATTACHMENTS} at a time</span>+ </div>+ </div>+ );+}diff --git a/client/src/features/chat/composer/SlashMenu.tsx b/client/src/features/chat/composer/SlashMenu.tsxnew file mode 100644index 00000000..946af1e6--- /dev/null+++ b/client/src/features/chat/composer/SlashMenu.tsx@@ -0,0 +1,86 @@+/**+ * Slash commands (design handoff chat, "Composer": `/`). A draft that is a+ * single word starting with `/` opens a list of the commands it begins,+ * above the message box; ArrowUp and ArrowDown move, Enter or Tab puts the+ * command's text in the box, Esc closes it (until the draft changes). Focus+ * stays in the box: the list is the popup it controls (`aria-controls`), and+ * the highlighted option is its `aria-activedescendant`. cmdk names its list+ * and options itself, so both ids are read from the list once it has drawn.+ */++import { useLayoutEffect, type ReactNode, type RefObject } from 'react';+import { Command, CommandItem, CommandList } from '@/components/ui/command';+import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';+import type { ChatCommand } from '../data/chatContext';++export function SlashMenu({+ open,+ listId,+ items,+ active,+ boxRef,+ onPick,+ onActive,+ onDismiss,+ children,+}: {+ open: boolean;+ listId: string;+ items: readonly ChatCommand[];+ /** The highlighted command's index. */+ active: number;+ /** The message box: the combobox whose popup this is. */+ boxRef: RefObject<HTMLTextAreaElement | null>;+ onPick: (command: ChatCommand) => void;+ onActive: (index: number) => void;+ onDismiss: () => void;+ /** The message box the list opens above. */+ children: ReactNode;+}) {+ const shown = open && items.length > 0;+ const selected = items[active]?.command ?? '';++ useLayoutEffect(() => {+ const box = boxRef.current;+ if (!box) return;+ const holder = shown ? document.getElementById(listId) : null;+ const list = holder?.querySelector<HTMLElement>('[cmdk-list]');+ // By position: cmdk marks its selection a render later than this.+ const option = holder?.querySelectorAll<HTMLElement>('[cmdk-item]')[active];+ if (list?.id) box.setAttribute('aria-controls', list.id);+ else box.removeAttribute('aria-controls');+ if (option?.id) box.setAttribute('aria-activedescendant', option.id);+ else box.removeAttribute('aria-activedescendant');+ });++ return (+ <Popover open={shown} onOpenChange={(next) => !next && onDismiss()}>+ <PopoverAnchor asChild>{children}</PopoverAnchor>+ <PopoverContent+ side="top"+ align="start"+ sideOffset={8}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ className="w-(--radix-popover-trigger-width) max-w-105 p-1"+ >+ <Command id={listId} shouldFilter={false} value={selected} label="Commands">+ <CommandList label="Commands">+ {items.map((item, index) => (+ <CommandItem+ key={item.command}+ value={item.command}+ onSelect={() => onPick(item)}+ onMouseEnter={() => onActive(index)}+ className="flex-col items-start gap-0.5"+ >+ <span className="font-mono text-sm font-medium text-fg-default">{item.command}</span>+ {item.description && <span className="text-xs text-fg-muted">{item.description}</span>}+ </CommandItem>+ ))}+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ );+}diff --git a/client/src/features/chat/composer/Suggestions.tsx b/client/src/features/chat/composer/Suggestions.tsxnew file mode 100644index 00000000..a82dfab9--- /dev/null+++ b/client/src/features/chat/composer/Suggestions.tsx@@ -0,0 +1,33 @@+/**+ * What to ask, in an empty chat: the slash commands marked `suggest`+ * (get_chat_context), each a card that puts its text in the message box for+ * the owner to finish or send.+ */++import { CornerDownLeft } from 'lucide-react';+import type { ChatCommand } from '../data/chatContext';++export function Suggestions({ items, onPick }: { items: readonly ChatCommand[]; onPick: (command: ChatCommand) => void }) {+ if (items.length === 0) return null;+ return (+ <ul aria-label="Suggestions" className="m-0 grid w-full max-w-130 list-none grid-cols-1 gap-2 p-0 sm:grid-cols-2">+ {items.map((item) => (+ <li key={item.command}>+ <button+ type="button"+ onClick={() => onPick(item)}+ className="flex h-full w-full flex-col items-start gap-1 rounded-card border border-border-default bg-bg-panel px-3.5 py-3 text-left transition-[border-color,background-color] duration-(--dur-default) hover:border-border-strong hover:bg-bg-hover"+ >+ <span className="text-sm font-semibold text-fg-default">{item.description || item.command}</span>+ <span className="flex items-center gap-1.5 text-xs text-fg-muted">+ <CornerDownLeft aria-hidden className="size-3" strokeWidth={2} />+ {item.fill}+ </span>+ </button>+ </li>+ ))}+ </ul>+ );+}++export default Suggestions;diff --git a/client/src/features/chat/composer/VoiceRecorder.tsx b/client/src/features/chat/composer/VoiceRecorder.tsxnew file mode 100644index 00000000..89a4f589--- /dev/null+++ b/client/src/features/chat/composer/VoiceRecorder.tsx@@ -0,0 +1,190 @@+/**+ * Dictating into the message box (design handoff chat, "Composer": voice).+ * While it records, a blinking dot, the time and the microphone's level+ * stand where the text was, with Cancel and Use dictation. Use stops the+ * recording, uploads it into the workflow's workspace and has it turned+ * into text (`transcribe_audio`, which deletes the recording); the text goes+ * into the box after what was already written. A recording stops by itself+ * after `MAX_RECORDING_MS`. No microphone (denied, absent) or a failed+ * transcription says so and leaves the box as it was.+ */++import { Check, Loader2, X } from 'lucide-react';+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';+import { Button } from '@/components/ui/button';+import { useWebSocketActions } from '@/contexts/WebSocketContext';+import { uploadToWorkspace } from '@/lib/workspaceUpload';+import { cn } from '@/lib/utils';+import { transcribe } from '../data/chatContext';+import type { NotifyTone } from '../host';++/** A recording stops by itself after this long. */+const MAX_RECORDING_MS = 3 * 60 * 1000;+const BARS = 36;+const LEVEL_MS = 110;++function clock(ms: number): string {+ const seconds = Math.floor(ms / 1000);+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;+}++export function VoiceRecorder({+ sessionId,+ workflowId,+ compact,+ onText,+ onClose,+ notify,+}: {+ sessionId: string;+ workflowId: string;+ compact: boolean;+ onText: (text: string) => void;+ onClose: () => void;+ notify: (message: string, tone: NotifyTone) => void;+}) {+ const { sendRequest } = useWebSocketActions();+ const [elapsed, setElapsed] = useState(0);+ const [levels, setLevels] = useState<number[]>(() => Array(BARS).fill(4));+ const [busy, setBusy] = useState(false);+ const recorder = useRef<MediaRecorder | null>(null);+ const chunks = useRef<Blob[]>([]);+ const release = useRef<() => void>(() => undefined);+ const finish = useRef<(use: boolean) => void>(() => undefined);++ const stopAll = useCallback(() => {+ release.current();+ release.current = () => undefined;+ }, []);++ useEffect(() => {+ let cancelled = false;+ let timer = 0;+ (async () => {+ let stream: MediaStream;+ try {+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ } catch {+ notify('Allow the microphone to dictate.', 'error');+ onClose();+ return;+ }+ if (cancelled) {+ stream.getTracks().forEach((track) => track.stop());+ return;+ }+ const type = typeof MediaRecorder.isTypeSupported === 'function' && MediaRecorder.isTypeSupported('audio/webm') ? 'audio/webm' : '';+ const media = new MediaRecorder(stream, type ? { mimeType: type } : undefined);+ media.ondataavailable = (event) => {+ if (event.data.size > 0) chunks.current.push(event.data);+ };+ media.start();+ recorder.current = media;+ let context: AudioContext | null = null;+ let analyser: AnalyserNode | null = null;+ try {+ context = new AudioContext();+ analyser = context.createAnalyser();+ analyser.fftSize = 256;+ context.createMediaStreamSource(stream).connect(analyser);+ } catch {+ analyser = null;+ }+ const samples = analyser ? new Uint8Array(analyser.frequencyBinCount) : null;+ const started = Date.now();+ timer = window.setInterval(() => {+ const now = Date.now() - started;+ setElapsed(now);+ if (analyser && samples) {+ analyser.getByteTimeDomainData(samples);+ let peak = 0;+ for (const sample of samples) peak = Math.max(peak, Math.abs(sample - 128));+ setLevels((current) => [...current.slice(1), 4 + Math.round((peak / 128) * 22)]);+ }+ if (now >= MAX_RECORDING_MS) finish.current(true);+ }, LEVEL_MS);+ release.current = () => {+ window.clearInterval(timer);+ if (media.state !== 'inactive') media.stop();+ stream.getTracks().forEach((track) => track.stop());+ void context?.close().catch(() => undefined);+ };+ })();+ return () => {+ cancelled = true;+ window.clearInterval(timer);+ release.current();+ };+ }, [notify, onClose]);++ // Read through a ref, so the recording's own timer (auto-stop) and the+ // buttons reach the current one.+ useLayoutEffect(() => {+ finish.current = (use: boolean) => {+ const media = recorder.current;+ if (!use || !media) {+ stopAll();+ onClose();+ return;+ }+ if (busy) return;+ setBusy(true);+ media.onstop = async () => {+ const type = media.mimeType || 'audio/webm';+ const file = new File(chunks.current, `dictation-${Date.now()}.${type.includes('ogg') ? 'ogg' : 'webm'}`, { type });+ try {+ const ref = await uploadToWorkspace(file, workflowId);+ const text = (await transcribe(sendRequest, sessionId, ref.path)).trim();+ if (text) onText(text);+ else notify('Nothing was heard. Try again closer to the microphone.', 'info');+ } catch {+ notify('Couldn’t turn that into text. Try again.', 'error');+ } finally {+ onClose();+ }+ };+ stopAll();+ };+ });++ return (+ <div className={cn('flex items-center gap-3', compact ? 'h-8' : 'h-10.25')}>+ {busy ? (+ <span role="status" className="flex items-center gap-2 text-sm text-fg-muted">+ <Loader2 aria-hidden className="size-3.5 animate-spin" />+ Turning it into text…+ </span>+ ) : (+ <>+ <span aria-hidden className="size-2 shrink-0 rounded-full bg-action-stop-ink motion-safe:animate-[opencompany-pip-blink_1.2s_infinite]" />+ <span className="min-w-9.5 font-mono text-sm text-fg-default" aria-label="Recording time">+ {clock(elapsed)}+ </span>+ <div aria-hidden className="flex h-7 min-w-0 flex-1 items-center gap-0.75 overflow-hidden">+ {levels.map((height, index) => (+ <span+ key={index}+ className="max-w-1 min-w-0.5 flex-1 rounded-sm bg-fg-muted transition-[height] duration-(--dur-fast)"+ style={{ height }}+ />+ ))}+ </div>+ </>+ )}+ <Button variant="quiet" size="icon" disabled={busy} onClick={() => finish.current(false)} aria-label="Cancel dictation" title="Cancel" className="shrink-0 rounded-full">+ <X aria-hidden className="size-3.75" strokeWidth={2.2} />+ </Button>+ <Button+ variant="quiet"+ size="icon"+ disabled={busy}+ onClick={() => finish.current(true)}+ aria-label="Use dictation"+ title="Use dictation"+ className="shrink-0 rounded-full bg-action-run-soft text-action-run-ink hover:bg-action-run-hover"+ >+ <Check aria-hidden className="size-3.75" strokeWidth={2.4} />+ </Button>+ </div>+ );+}diff --git a/client/src/features/chat/composer/WebChip.tsx b/client/src/features/chat/composer/WebChip.tsxnew file mode 100644index 00000000..b3a00fd9--- /dev/null+++ b/client/src/features/chat/composer/WebChip.tsx@@ -0,0 +1,32 @@+/**+ * Web, beside the message box (design handoff chat, "Composer"): while it is+ * off, the employee answers the next messages without searching the web+ * (`options.web: false`; the server leaves its search tools out for those+ * runs). Shown only when the employee has a search tool.+ */++import { Globe } from 'lucide-react';+import { Toggle } from '@/components/ui/toggle';+import { cn } from '@/lib/utils';++export function WebChip({ on, name, onChange, compact = false }: { on: boolean; name: string; onChange: (next: boolean) => void; compact?: boolean }) {+ return (+ <Toggle+ variant="chips"+ size="sm"+ pressed={on}+ onPressedChange={onChange}+ aria-label="Web"+ title={on ? `${name} may search the web` : `${name} answers without searching the web`}+ className={cn(+ 'gap-1.25 data-[state=on]:border-action-save-border data-[state=on]:bg-action-save-soft data-[state=on]:text-action-save-ink',+ compact && 'h-6 px-2',+ )}+ >+ <Globe aria-hidden className="size-3.25" strokeWidth={1.9} />+ Web+ </Toggle>+ );+}++export default WebChip;diff --git a/client/src/features/chat/composer/attachments.ts b/client/src/features/chat/composer/attachments.tsnew file mode 100644index 00000000..e50b536d--- /dev/null+++ b/client/src/features/chat/composer/attachments.ts@@ -0,0 +1,78 @@+/**+ * Adding files to a chat's message box: the file picker, a paste and a drop+ * all call `addAttachments`, so each reaches the same box the same way (a+ * drop needs a pointer alternative that does what it does: the picker,+ * CLAUDE.md rule 9). Each file goes into the box at once, marked uploading,+ * and is uploaded into the workflow's workspace (lib/workspaceUpload: under+ * `uploads/`, at most 25 MB); the box shows a failure on its chip. At most+ * `MAX_ATTACHMENTS` per message, the server's limit too.+ */++import { MEDIA_MAX_UPLOAD_BYTES, uploadToWorkspace } from '@/lib/workspaceUpload';+import type { WorkspaceFileRef } from '@/types/workspaceFiles';+import { newClientMessageId } from '../state/composerStore';+import { useAttachmentStore, type BoxAttachment } from '../state/attachmentStore';++/** The most files one message carries (`services/chat/attachments.py`). */+export const MAX_ATTACHMENTS = 6;++export type Upload = (file: File, workflowId: string) => Promise<WorkspaceFileRef>;++const defaultUpload: Upload = async (file, workflowId) => (await uploadToWorkspace(file, workflowId)) as WorkspaceFileRef;++/** Add files to the box; returns what could not be added and why. */+export async function addAttachments(+ sessionId: string,+ workflowId: string,+ files: readonly File[],+ upload: Upload = defaultUpload,+): Promise<string | null> {+ const store = useAttachmentStore.getState();+ const room = MAX_ATTACHMENTS - (store.boxes[sessionId]?.length ?? 0);+ const taken = files.slice(0, Math.max(0, room));+ const items: BoxAttachment[] = taken.map((file) => {+ const tooLarge = file.size > MEDIA_MAX_UPLOAD_BYTES;+ return {+ id: newClientMessageId(),+ name: file.name || 'pasted file',+ size: file.size,+ mime: file.type || 'application/octet-stream',+ state: tooLarge ? 'failed' : 'uploading',+ ref: null,+ error: tooLarge ? `Larger than ${MEDIA_MAX_UPLOAD_BYTES / (1024 * 1024)} MB` : null,+ preview:+ !tooLarge && file.type.startsWith('image/') && typeof URL.createObjectURL === 'function' ? URL.createObjectURL(file) : null,+ };+ });+ if (items.length) store.add(sessionId, items);+ await Promise.all(+ items.map(async (item, index) => {+ if (item.state !== 'uploading') return;+ try {+ const ref = await upload(taken[index], workflowId);+ useAttachmentStore.getState().update(sessionId, item.id, { state: 'ready', ref });+ } catch (error) {+ const message = error instanceof Error && error.message ? error.message : 'Upload failed';+ useAttachmentStore.getState().update(sessionId, item.id, { state: 'failed', error: message });+ }+ }),+ );+ return files.length > taken.length ? `Up to ${MAX_ATTACHMENTS} files go with one message.` : null;+}++/** The files a clipboard or a drop carries. */+export function filesOf(list: { files?: FileList | null } | null | undefined): File[] {+ return list?.files ? Array.from(list.files) : [];+}++/** The size as the chip says it. */+export function sizeLabel(bytes: number): string {+ if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+ return `${Math.max(1, Math.round(bytes / 1024))} KB`;+}++/** The file's extension, as its chip's badge (`PDF`, `CSV`). */+export function extensionLabel(name: string): string {+ const dot = name.lastIndexOf('.');+ return (dot > 0 ? name.slice(dot + 1) : 'file').slice(0, 4).toUpperCase();+}diff --git a/client/src/features/chat/composer/slash.ts b/client/src/features/chat/composer/slash.tsnew file mode 100644index 00000000..f1907622--- /dev/null+++ b/client/src/features/chat/composer/slash.ts@@ -0,0 +1,18 @@+/**+ * Which slash commands a draft asks for (composer/SlashMenu.tsx). Kept apart+ * from the component so its file exports components only (react-refresh)+ * and the rule is testable on its own.+ */++import type { ChatCommand } from '../data/chatContext';++/** The command a draft starts, lower-cased without its `/`; null when it+ * is not one word starting with `/`. */+export function slashQuery(text: string): string | null {+ return text.startsWith('/') && !/\s/.test(text) ? text.slice(1).toLowerCase() : null;+}++/** The commands that begin with what was typed. */+export function matchCommands(commands: readonly ChatCommand[], query: string): ChatCommand[] {+ return commands.filter((command) => command.command.slice(1).toLowerCase().startsWith(query));+}diff --git a/client/src/features/chat/data/chatContext.ts b/client/src/features/chat/data/chatContext.tsnew file mode 100644index 00000000..e5a29c2a--- /dev/null+++ b/client/src/features/chat/data/chatContext.ts@@ -0,0 +1,104 @@+/**+ * What a chat's message box offers (`get_chat_context`): slash commands (the+ * generic ones and those the employee's apps add; the ones marked `suggest`+ * also show as suggestions in an empty chat), whether files can be attached+ * (a workflow's chat), whether the Web chip has search to turn off, and the+ * limits. Dictation (`dictation_status`): whether a recording can be turned+ * into text, which needs a speech provider's key; `transcribe` sends one.+ */++import { useQuery } from '@tanstack/react-query';+import { z } from 'zod';+import { useWebSocketActions } from '@/contexts/WebSocketContext';++export interface ChatCommand {+ command: string;+ description: string;+ fill: string;+ suggest: boolean;+}++export interface ChatContext {+ commands: ChatCommand[];+ attachments: boolean;+ web: boolean;+ maxAttachments: number;+}++const commandSchema = z+ .object({+ command: z.string().regex(/^\/[a-z0-9-]{1,30}$/),+ description: z.string().catch(''),+ fill: z.string().catch(''),+ suggest: z.boolean().catch(false),+ })+ .transform((command): ChatCommand => command);++const contextSchema = z+ .object({+ commands: z.array(z.unknown()).catch([]),+ capabilities: z.object({ attachments: z.boolean().catch(false), web: z.boolean().catch(false) }).catch({ attachments: false, web: false }),+ limits: z.object({ max_attachments: z.number().int().positive().catch(6) }).catch({ max_attachments: 6 }),+ })+ .transform(+ (raw): ChatContext => ({+ commands: raw.commands.flatMap((item) => {+ const parsed = commandSchema.safeParse(item);+ return parsed.success ? [parsed.data] : [];+ }),+ attachments: raw.capabilities.attachments,+ web: raw.capabilities.web,+ maxAttachments: raw.limits.max_attachments,+ }),+ );++export const NO_CHAT_CONTEXT: ChatContext = { commands: [], attachments: false, web: false, maxAttachments: 6 };++export function parseChatContext(reply: unknown): ChatContext {+ const parsed = contextSchema.safeParse(reply);+ return parsed.success ? parsed.data : NO_CHAT_CONTEXT;+}++export function useChatContext(sessionId: string) {+ const { sendRequest, isReady } = useWebSocketActions();+ return useQuery<ChatContext, Error>({+ queryKey: ['chatContext', sessionId],+ enabled: isReady && Boolean(sessionId),+ staleTime: 60_000,+ queryFn: async () => {+ const reply = await sendRequest<{ success?: boolean; error?: string }>('get_chat_context', { session_id: sessionId });+ if (reply?.success === false) throw new Error(reply.error || 'read_failed');+ return parseChatContext(reply);+ },+ });+}++/** Whether the owner can dictate in this chat. */+export function useDictation(sessionId: string, enabled: boolean) {+ const { sendRequest, isReady } = useWebSocketActions();+ return useQuery<boolean, Error>({+ queryKey: ['dictation', sessionId],+ enabled: enabled && isReady && Boolean(sessionId),+ staleTime: 60_000,+ queryFn: async () => {+ const reply = await sendRequest<{ success?: boolean; available?: boolean }>('dictation_status', { session_id: sessionId });+ return reply?.success !== false && reply?.available === true;+ },+ });+}++/** Turn a recording uploaded to the chat (`uploads/...`) into text. */+export async function transcribe(+ sendRequest: <T>(type: string, data?: Record<string, unknown>) => Promise<T>,+ sessionId: string,+ path: string,+): Promise<string> {+ const reply = await sendRequest<{ success?: boolean; error?: string; text?: string }>('transcribe_audio', { session_id: sessionId, path });+ if (!reply || reply.success === false) throw new Error(reply?.error || 'transcribe_failed');+ return typeof reply.text === 'string' ? reply.text : '';+}++/** Whether this browser can record from a microphone at all. */+export function canRecord(): boolean {+ return typeof window !== 'undefined' && typeof window.MediaRecorder === 'function' && Boolean(navigator.mediaDevices?.getUserMedia);+}diff --git a/client/src/features/chat/data/send.ts b/client/src/features/chat/data/send.tsindex 06c62728..ada335b1 100644--- a/client/src/features/chat/data/send.ts+++ b/client/src/features/chat/data/send.ts@@ -12,12 +12,18 @@* after a failure in transit is the same message); `onRefused` decides what* to tell the owner (`ChatSendError`). Both run at the hook level, so they* still happen when the owner has moved to another conversation meanwhile.+ *+ * Files from the box (state/attachmentStore.ts) go as the paths their+ * uploads returned; the server rebuilds them. A send that does not go+ * through puts them back in the box too. `options.web: false` keeps the+ * employee off web search for this message.*/import { useMutation, useQueryClient } from '@tanstack/react-query';import { useWebSocketActions } from '@/contexts/WebSocketContext';import { queryKeys } from '@/lib/queryConfig';import { useChatRunStore } from '@/stores/chatRunStore';+import { useAttachmentStore, type BoxAttachment } from '../state/attachmentStore';import { useComposerStore, type TakenDraft } from '../state/composerStore';import type { ChatMessage, ChatThreadData } from './schemas';import { chatThreadKey, type ThreadScope } from './thread';@@ -66,7 +72,16 @@ export interface UiEventSend {/** What one send carries: the text shown as the owner's message, and for a* button press, the press. */-export type SendDraft = TakenDraft & { uiEvent?: UiEventSend };+export type SendDraft = TakenDraft & {+ uiEvent?: UiEventSend;+ /** Finished uploads from the box. */+ attachments?: BoxAttachment[];+ options?: { web: boolean };+};++function refsOf(attachments: readonly BoxAttachment[] | undefined) {+ return (attachments ?? []).flatMap((item) => (item.ref ? [item.ref] : []));+}function localId(clientMessageId: string): string {return `local:${clientMessageId}`;@@ -81,7 +96,7 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefuqueryClient.setQueryData<ChatThreadData>(key, (data) => (data ? { ...data, messages: update(data.messages) } : data));return useMutation<SendResult, ChatSendError, SendDraft>({- mutationFn: async ({ text, clientMessageId, uiEvent }) => {+ mutationFn: async ({ text, clientMessageId, uiEvent, attachments, options }) => {let reply: SendReply | undefined;try {reply = await sendRequest<SendReply>('send_chat_message', {@@ -90,6 +105,8 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefurole: 'user',timestamp: new Date().toISOString(),client_message_id: clientMessageId,+ ...(attachments?.length ? { attachments: refsOf(attachments).map((ref) => ({ path: ref.path })) } : {}),+ ...(options ? { options } : {}),...(uiEvent? {ui_event: {@@ -113,7 +130,7 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefudelivery: reply.delivery === 'queued' ? 'queued' : reply.delivery === 'now' ? 'now' : null,};},- onMutate: async ({ text, clientMessageId, uiEvent }) => {+ onMutate: async ({ text, clientMessageId, uiEvent, attachments }) => {await queryClient.cancelQueries({ queryKey: key });const pending: ChatMessage = {id: localId(clientMessageId),@@ -126,7 +143,7 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefurunId: null,parentId: null,status: 'complete',- attachments: [],+ attachments: refsOf(attachments),parts: {},clientMessageId,run: null,@@ -137,7 +154,9 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefu};replace((messages) => [...messages.filter((message) => message.id !== pending.id), pending]);},- onSuccess: (result, { clientMessageId }) => {+ 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);replace((messages) =>messages.map((message) =>message.id === localId(clientMessageId)@@ -157,6 +176,7 @@ export function useSendChatMessage(sessionId: string, scope: ThreadScope, onRefureplace((messages) => messages.filter((message) => message.id !== localId(draft.clientMessageId)));// A button press is not the owner's writing: nothing goes back in the box.if (!draft.uiEvent) useComposerStore.getState().restore(sessionId, draft, error.transport);+ if (draft.attachments?.length) useAttachmentStore.getState().restore(sessionId, draft.attachments);onRefused?.(error);},// The refetch swaps the local copy for the saved row.diff --git a/client/src/features/chat/state/attachmentStore.ts b/client/src/features/chat/state/attachmentStore.tsnew file mode 100644index 00000000..8a0ffed9--- /dev/null+++ b/client/src/features/chat/state/attachmentStore.ts@@ -0,0 +1,81 @@+/**+ * Files waiting in a chat's message box, per session (design handoff chat,+ * "Composer"), beside the text in composerStore. Each is uploaded into the+ * workflow's workspace as soon as it is added (composer/attachments.ts); a+ * message carries the references of the ones that finished. Sending takes+ * them out of the box (`take`), and a send that does not go through puts+ * them back (`restore`).+ */++import { create } from 'zustand';+import type { WorkspaceFileRef } from '@/types/workspaceFiles';++export interface BoxAttachment {+ id: string;+ name: string;+ size: number;+ mime: string;+ state: 'uploading' | 'ready' | 'failed';+ /** What the upload returned, once it has. */+ ref: WorkspaceFileRef | null;+ error: string | null;+ /** An object URL for an image's thumbnail while it is in the box. */+ preview: string | null;+}++interface AttachmentState {+ boxes: Record<string, BoxAttachment[]>;+ add: (sessionId: string, items: BoxAttachment[]) => void;+ update: (sessionId: string, id: string, patch: Partial<BoxAttachment>) => void;+ remove: (sessionId: string, id: string) => void;+ /** Empty the box and return what it held. */+ take: (sessionId: string) => BoxAttachment[];+ /** Take the finished uploads for a send; the rest (still uploading,+ * failed) stay in the box. */+ takeReady: (sessionId: string) => BoxAttachment[];+ /** Put attachments a send did not take back, ahead of any added since. */+ restore: (sessionId: string, items: BoxAttachment[]) => void;+}++const NONE: BoxAttachment[] = [];++function revoke(item: BoxAttachment): void {+ if (item.preview && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(item.preview);+}++export const useAttachmentStore = create<AttachmentState>((set, get) => ({+ boxes: {},+ add: (sessionId, items) =>+ set((state) => ({ boxes: { ...state.boxes, [sessionId]: [...(state.boxes[sessionId] ?? NONE), ...items] } })),+ update: (sessionId, id, patch) =>+ set((state) => {+ const box = state.boxes[sessionId];+ if (!box?.some((item) => item.id === id)) return state;+ return { boxes: { ...state.boxes, [sessionId]: box.map((item) => (item.id === id ? { ...item, ...patch } : item)) } };+ }),+ remove: (sessionId, id) =>+ set((state) => {+ const box = state.boxes[sessionId] ?? NONE;+ const gone = box.find((item) => item.id === id);+ if (!gone) return state;+ revoke(gone);+ return { boxes: { ...state.boxes, [sessionId]: box.filter((item) => item.id !== id) } };+ }),+ take: (sessionId) => {+ const box = get().boxes[sessionId] ?? NONE;+ if (box.length) set((state) => ({ boxes: { ...state.boxes, [sessionId]: NONE } }));+ return box;+ },+ takeReady: (sessionId) => {+ const box = get().boxes[sessionId] ?? NONE;+ const ready = box.filter((item) => item.state === 'ready' && item.ref);+ if (ready.length) set((state) => ({ boxes: { ...state.boxes, [sessionId]: box.filter((item) => !ready.includes(item)) } }));+ return ready;+ },+ restore: (sessionId, items) =>+ set((state) => ({ boxes: { ...state.boxes, [sessionId]: [...items, ...(state.boxes[sessionId] ?? NONE)] } })),+}));++export function useBoxAttachments(sessionId: string): BoxAttachment[] {+ return useAttachmentStore((state) => state.boxes[sessionId] ?? NONE);+}diff --git a/client/src/features/chat/state/composerStore.ts b/client/src/features/chat/state/composerStore.tsindex 387f43ed..b15aec54 100644--- a/client/src/features/chat/state/composerStore.ts+++ b/client/src/features/chat/state/composerStore.ts@@ -23,6 +23,10 @@ export type TakenDraft = ComposerDraft & { clientMessageId: string };interface ComposerState {drafts: Record<string, ComposerDraft>;+ /** Per session, whether the next message lets the employee search the+ * web (the Web chip; on unless turned off). */+ web: Record<string, boolean>;+ setWeb: (sessionId: string, on: boolean) => void;setText: (sessionId: string, text: string) => void;/** Empty the box and return what it held, with the id naming this send. */takeForSend: (sessionId: string) => TakenDraft;@@ -42,6 +46,9 @@ export function newClientMessageId(): string {export const useComposerStore = create<ComposerState>((set, get) => ({drafts: {},+ web: {},++ setWeb: (sessionId, on) => set((state) => ({ web: { ...state.web, [sessionId]: on } })),setText: (sessionId, text) =>set((state) => {diff --git a/client/src/features/chat/turns/MessageAttachments.tsx b/client/src/features/chat/turns/MessageAttachments.tsxnew file mode 100644index 00000000..ec3a7616--- /dev/null+++ b/client/src/features/chat/turns/MessageAttachments.tsx@@ -0,0 +1,46 @@+/**+ * The files the owner sent with a message (design handoff chat, "Thread"):+ * images as thumbnails that open full size, other files as chips with their+ * type, name and size that download. They come from the workflow's+ * workspace (the same-origin workspace route), so nothing remote loads.+ */++import { buildApiUrl } from '@/config/api';+import { isWorkspaceFileRef, type WorkspaceFileRef } from '@/types/workspaceFiles';+import { extensionLabel, sizeLabel } from '../composer/attachments';++export function MessageAttachments({ attachments }: { attachments: readonly unknown[] }) {+ const refs = attachments.filter((item): item is WorkspaceFileRef => isWorkspaceFileRef(item) && Boolean(item.url));+ if (refs.length === 0) return null;+ return (+ <ul aria-label="Attached files" className="m-0 flex max-w-[85%] list-none flex-wrap justify-end gap-2 p-0">+ {refs.map((ref) => {+ const href = buildApiUrl(ref.url ?? '');+ const image = ref.kind === 'image' || (ref.mime_type ?? '').startsWith('image/');+ return (+ <li key={ref.path}>+ {image ? (+ <a href={href} target="_blank" rel="noreferrer" className="block" title={ref.filename}>+ <img src={href} alt={ref.filename} className="block h-22.5 w-30 rounded-xl border border-border-default object-cover" />+ </a>+ ) : (+ <a+ href={href}+ download={ref.filename}+ className="flex h-12 max-w-55 items-center gap-2.5 rounded-xl border border-border-default bg-bg-panel py-0 pr-3.5 pl-2 text-fg-default no-underline hover:bg-bg-hover"+ >+ <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-action-config-soft font-mono text-2xs font-semibold text-action-config-ink">+ {extensionLabel(ref.filename)}+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-sm font-medium">{ref.filename}</span>+ {typeof ref.size_bytes === 'number' && <span className="font-mono text-2xs text-fg-faint">{sizeLabel(ref.size_bytes)}</span>}+ </span>+ </a>+ )}+ </li>+ );+ })}+ </ul>+ );+}diff --git a/client/src/features/chat/turns/UserTurn.tsx b/client/src/features/chat/turns/UserTurn.tsxindex 07486948..b5460cf5 100644--- a/client/src/features/chat/turns/UserTurn.tsx+++ b/client/src/features/chat/turns/UserTurn.tsx@@ -5,6 +5,9 @@* pointer, in a quieter pill. `chat-msg chat-msg-user` is the theme hook the* stylized themes paint.*+ * Files sent with it show above it (images as thumbnails, other files as+ * chips); a message that is only files has no bubble.+ ** Under it, the hover bar: when they sent it, ‹ 1 / 2 › between their edits* of it, Edit (it opens in place; sending the edit starts a new branch of* the conversation), and Copy. Edit shows only where the server allows it@@ -19,6 +22,7 @@ import { timeLabel } from '../thread/timeLabel';import { useTurnActions } from '../thread/turnActions';import { TurnMeta } from './TurnMeta';import { useCopied } from './useCopied';+import { MessageAttachments } from './MessageAttachments';import { UserEditBox } from './UserEditBox';import { VersionStepper } from './VersionStepper';@@ -28,9 +32,11 @@ export function UserTurn({ message, now, latest, compact }: { message: ChatMessaconst pressed = message.kind === 'action';const editing = Boolean(actions && actions.editingId === message.id);const canEdit = Boolean(actions && message.editable && !pressed && !message.pending);+ const hasText = message.text.trim().length > 0;return (<div data-turn="user" data-message={message.id} className="chat-turn-user group/turn flex flex-col items-end gap-1.5">+ {message.attachments.length > 0 && <MessageAttachments attachments={message.attachments} />}{editing && actions ? (<UserEditBoxinitial={message.text}@@ -50,7 +56,7 @@ export function UserTurn({ message, now, latest, compact }: { message: ChatMessa<span className="sr-only">Pressed </span><span className="font-medium text-fg-default">{message.text}</span></p>- ) : (+ ) : !hasText ? null : (<pclassName={cn('chat-msg chat-msg-user m-0 max-w-[85%] rounded-draft rounded-br-sm border border-border-default bg-bg-elevated whitespace-pre-wrap text-fg-default wrap-anywhere',@@ -81,7 +87,7 @@ export function UserTurn({ message, now, latest, compact }: { message: ChatMessa<Pencil aria-hidden className="size-3.5" strokeWidth={1.9} /></Button>)}- {!pressed && (+ {!pressed && hasText && (<Buttonvariant="quiet"size="icon-sm"diff --git a/client/src/features/home/__tests__/employeeChat.test.tsx b/client/src/features/home/__tests__/employeeChat.test.tsxindex 3ffe6452..33d2f408 100644--- a/client/src/features/home/__tests__/employeeChat.test.tsx+++ b/client/src/features/home/__tests__/employeeChat.test.tsx@@ -146,6 +146,14 @@ describe('the thread', () => {expect(screen.getByRole('log', { name: 'Conversation with Maya' })).toBeEmptyDOMElement();expect(screen.getByText('Maya asks before sending anything on your behalf.')).toBeInTheDocument();});++ it('puts the cursor in the message box on Cmd/Ctrl+K', async () => {+ renderChat(employee());+ const box = await screen.findByRole('textbox', { name: 'Message Maya' });+ expect(box).not.toHaveFocus();+ fireEvent.keyDown(window, { key: 'k', ctrlKey: true });+ expect(box).toHaveFocus();+ });});describe('sending', () => {diff --git a/client/src/features/home/employee/EmployeeChat.tsx b/client/src/features/home/employee/EmployeeChat.tsxindex 7ebb1a88..9e6fadb6 100644--- a/client/src/features/home/employee/EmployeeChat.tsx+++ b/client/src/features/home/employee/EmployeeChat.tsx@@ -17,13 +17,15 @@* setup cannot answer gets a note instead of the box.* - A document they wrote opens from its card in the reply on the* Workspace's Canvas tab, at that version.+ * - Cmd/Ctrl+K puts the cursor in the message box.*/import { Monitor } from 'lucide-react';+import { useEffect, useRef } from 'react';import { useQueryClient } from '@tanstack/react-query';import { ActionButton } from '@/components/ui/action-button';import { Alert, AlertDescription } from '@/components/ui/alert';-import { ChatPane, useLaneRun, type ComposerMode } from '@/features/chat';+import { ChatPane, useLaneRun, type ChatPaneHandle, type ComposerMode } from '@/features/chat';import { invalidateEmployees } from '../data/employees';import { stateNoticeText, talkMode, talkNoticeText } from '../data/presentation';import type { EmployeeSummary } from '../data/schemas';@@ -112,6 +114,19 @@ export function EmployeeChat({const mode = talkMode(employee.control);const composer: ComposerMode = employee.talk.state !== 'on' || mode === 'start' ? 'closed' : mode;+ // Cmd/Ctrl+K puts the cursor in the message box (on Home only: in the+ // editor it opens the command palette, which has Focus Chat).+ const pane = useRef<ChatPaneHandle>(null);+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key.toLowerCase() !== 'k' || !(event.metaKey || event.ctrlKey) || event.shiftKey || event.altKey) return;+ event.preventDefault();+ pane.current?.focusComposer();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);+const onSendRefused = (code: string) => {if (code === 'not_running') {invalidateEmployees(queryClient);@@ -127,6 +142,7 @@ export function EmployeeChat({return (<ChatPane+ ref={pane}host={{kind: 'home',sessionId: workflowId,