Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(chat): one chat for Home's employee page and the editor's console
trohitgcdcf295d4bfa
diff --git a/CLAUDE.md b/CLAUDE.mdindex 50e12f00..a11a6770 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[UI Migration Plan](./docs-internal/ARCHIVE/ui_migration_plan.md)** | *Archived.* antd → shadcn/ui migration completion log (Waves 1–10). Current state lives in [Frontend Architecture](./docs-internal/frontend_architecture.md) and [Theme System](./docs-internal/theme_system.md). || **[Temporal Cleanup & Resilience Plan (Waves 15-18)](./docs-internal/ARCHIVE/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md)** | *Archived — all four waves shipped.* 15 dead-code retirement (Redis-Streams branch in event_waiter, APScheduler cron stack, orphaned `connection_status` factory), 16 per-queue task routing (`TemporalWorkerPool`), 17 resilience hardening (cron `catchup_window`, SDK interceptors, `DEPLOYMENT_MODE`, periodic heartbeats; the one-shot LLM-step retry it records was later reverted to unlimited-with-backoff), 18 worker performance tuning. Current settings live in [Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md). || **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |-| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (only their name above the conversation; Pause is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (read-only under "ask me first" through the tool's `ask_first_params`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. |+| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (the shared chat, `features/chat`, with the employee named in the header beside New conversation; Pause is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (read-only under "ask me first" through the tool's `ask_first_params`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written through `services/chat_thread.py` and, for the owner's messages and their chat runs, `services/chat/ledger.py` (see [Chat Protocol](./docs-internal/chat_protocol.md)); the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. || **[Chat Protocol](./docs-internal/chat_protocol.md)** | The wire contract between the chat runtime (`server/services/chat/`) and the shared chat UI: AG-UI's event model on the existing WebSocket, snake_case, in the CloudEvents envelope. A message a deployed chat trigger will answer starts a **chat run** admitted with it in one reserved write transaction (`Database.reserved_session`, SQLite `BEGIN IMMEDIATE`): one live run per session (the lane, also a partial unique index; a second send answers `run_in_progress`), idempotent `client_message_id`, claimed and finished by the MachinaWorkflow that answers it behind `machina-chat-run-v1` (the run id is trusted only from an event whose source is `opencompany://services/chat`; `run_scope` rides every node context; only the claimant finishes), the reply saved as `a_<run id>` by `chatReply`, every message appended after the session's active leaf (`chat_threads`) so concurrent writes never fork the thread. `chat_run_event` frames reach only sockets that passed `chat_subscribe`'s owner check (`services/chat/hub.py`: per-run `seq`, `hub_epoch`, bounded per-socket queues with a resync), never the status broadcast. A watchdog (`services/chat/watchdog.py`, started by `main.py`) ends runs nothing will finish (`not_delivered`, `timed_out`, `interrupted`). Lists every event, handler, part and error code, including the ones later phases build. || **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `AppShell` on both screens, while the tab is hidden or the window is blurred; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 inline SVG glyph strings across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. || **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), 12-theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 12 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/themes/). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). |@@ -949,34 +949,20 @@ The app has two screens, and a Normal / Dev switch moves between them:- **Themes**: Home shows only the two base themes. [`app/ShellThemeProvider.tsx`](./client/src/app/ShellThemeProvider.tsx) passes `baseOnly` to `ThemeProvider` while Home is showing, so a chosen stylized theme appears as its family's base (Atomic as light, Cyber as dark) and applies again in Dev mode; the choice itself is never overwritten. `useTheme().theme` is the theme on the page, `chosenTheme` the user's pick. index.html's pre-paint script applies the same rule so Home's first frame is not stylized.### Console Panel-The Console Panel provides a resizable bottom panel with three sections: Chat (AI conversation), Console (node execution logs), and Terminal (server logs). **Hybrid layout (design-handoff)**: split view (default) docks Chat as a resizable pane beside the Console/Terminal tabs so chat and logs stay simultaneously visible during agent runs; tab mode makes Chat the first of three tabs. Toggled via the Columns2 button in the tab row; persisted in `consolePrefs.splitView` (default `true` — existing users see no change). One shared `chatSection` JSX serves both layouts so the per-theme `chat-msg*` decoration co-classes survive.+The Console Panel provides a resizable bottom panel with three sections: Chat (AI conversation), Console (node execution logs), and Terminal (server logs). **Hybrid layout (design-handoff)**: split view (default) docks Chat as a resizable pane beside the Console/Terminal tabs so chat and logs stay simultaneously visible during agent runs; tab mode makes Chat the first of three tabs. Toggled via the Columns2 button in the tab row; persisted in `consolePrefs.splitView` (default `true` — existing users see no change). Both layouts render one `ConsoleChat` ([components/ui/ConsoleChat.tsx](./client/src/components/ui/ConsoleChat.tsx)): the shared chat ([features/chat](./client/src/features/chat/), the same `ChatPane` as Home's employee page) in its compact form, over the open workflow's chat session showing the live generation only. Its turns carry the per-theme `chat-msg*` hooks, and the console's font size applies to the conversation.#### Features- **Resizable**: Drag handle at top to resize (vertical) + chat-pane divider (horizontal, split view), persisted to localStorage- **Hybrid Chat placement**: docked split pane (default) or first tab — `consolePrefs.splitView`- **Tabs**: Chat (tab mode only) / Console / Terminal-- **Chat Section**: Send messages to Chat Trigger nodes, view conversation history; `chatFocusRequest` switches to the Chat tab before focusing when in tab mode+- **Chat Section**: Send messages to the workflow's chat triggers and follow the runs they start (Working… until the run ends, failures inline; [Chat Protocol](./docs-internal/chat_protocol.md#client)); Clear clears the chat and what its agents remember of it; `chatFocusRequest` switches to the Chat tab before focusing the message box (through the pane's `focusComposer` handle) when in tab mode- **Console Section**: View and filter node execution logs-#### Node Selector Dropdowns-When multiple chatTrigger or console nodes exist in the workflow, dropdowns appear to select which node to target:--| Selector | Location | Behavior |-|----------|----------|----------|-| Chat Trigger | Chat section header | Select which chatTrigger node receives messages. "All" broadcasts to all triggers |-| Console | Console section controls | Filter logs to show only output from selected console node |+#### Console Selector+When the workflow has several console nodes, a dropdown in the Console section's controls filters the logs to one of them (`isConsoleSink` uiHint, with a type-string fallback). There is no chat-trigger selector: a message goes to every chat trigger of the open workflow whose filter accepts the session.**Implementation** (`client/src/components/ui/ConsolePanel.tsx`):```typescript-// Workflow nodes that participate in this panel -- uiHint first, type-string fallback.-const chatTriggerNodes = useMemo(() =>- nodes.filter(n => {- const def = n.type ? resolveNodeDescription(n.type) : undefined;- return def?.uiHints?.isChatTrigger- ?? (n.type ? ['chatTrigger'].includes(n.type) : false);- }),- [nodes]-);const consoleNodes = useMemo(() =>nodes.filter(n => {const def = n.type ? resolveNodeDescription(n.type) : undefined;@@ -985,9 +971,6 @@ const consoleNodes = useMemo(() =>}),[nodes]);--// State for selected nodes-const [selectedChatTriggerId, setSelectedChatTriggerId] = useState<string>('');const [selectedConsoleId, setSelectedConsoleId] = useState<string>('');```@@ -1048,6 +1031,7 @@ Console logs are persisted to SQLite database and loaded on page refresh.| File | Description ||------|-------------|| `client/src/components/ui/ConsolePanel.tsx` | Main panel component with chat/console/terminal tabs |+| `client/src/components/ui/ConsoleChat.tsx` | The Chat pane: the shared chat (`features/chat`), compact, over the open workflow's session || `server/models/database.py` | ChatMessage and ConsoleLog SQLModel definitions || `server/core/database.py` | Chat message and console log CRUD methods || `server/routers/websocket.py` | WebSocket handlers for console operations |@@ -2792,7 +2776,7 @@ This function:- **Telegram inbound content types**: `_format_message` extracts detail dicts for all 11 types via the `_CONTENT_PROBES` / `_DETAIL_EXTRACTORS` tables, plus a normalized `media` block (`kind` / `file_id` / `mime_type` / `file_name` / …) that downstream nodes read instead of branching per type; MIME and filename are synthesised where Telegram omits them. **Probe order is load-bearing**: Telegram sets `message.document` on animation messages too, so `animation` and `video_note` must be probed before `document` and `video` or every GIF classifies as a document. The trigger never downloads — media travels as a `file_id`, never bytes or base64, because node results are persisted, broadcast, and replayed into the LLM conversation every turn.- **Google OAuth scope expansion**: Google's authorisation server legitimately returns a wider scope set than requested when the OAuth Client's "Data Access" page lists extra scopes (commonly `cloud-platform`) or when `include_granted_scopes` replays a previously-granted scope. `oauthlib` does strict set-equality and aborts with `Warning: Scope has changed`. As of 2026 (`google-auth-oauthlib` 1.2.4, `oauthlib` upstream issue #562 still open), no constructor flag, context manager, or `expected_scopes` argument exists — the documented relief is the env var. `server/nodes/google/_oauth.py` sets `OAUTHLIB_RELAX_TOKEN_SCOPE=1` via `os.environ.setdefault` BEFORE the `google_auth_oauthlib.flow` import (oauthlib reads it once at parameters-module import; request-time setting races under uvicorn workers), paired with `warnings.filterwarnings(message=r"Scope has changed.*")` to keep the operator log clean. Long-term root cause: audit the Cloud Console Data Access page and remove `cloud-platform` if no handler uses it.- **Code-executor error mapping** (`pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`): wrap user-code execution and sidecar calls in `try/except`. Python: detect `ImportError("__import__ not found")` (the LLM tried `import X` against the sandboxed builtins) and surface the pre-injected names list (`math, json, datetime, timedelta, re, random, Counter, defaultdict`) plus the suggestion to use `process_manager` for unsupported modules; other exceptions get formatted as `<ErrorName> at line N: <message>` (line N walked from `<string>` frame in the traceback) plus any captured stdout. JS/TS: detect `aiohttp.ClientConnectorError` / the spawn `RuntimeError` (bun missing or `dist/index.js` not built) and surface "JavaScript executor is unavailable (bun sidecar at <NODEJS_EXECUTOR_URL>). Fall back to python_executor for similar logic." All raise `NodeUserError` so the framework logs one WARN line — no aiohttp/CreateProcessW noise in the operator log.-- **Workflow-scoped chat + console history**: chat messages persist with `chat_messages.session_id == <workflow_id>` (or `"default"` when no workflow is open); console logs persist with `console_logs.workflow_id`. Backend `database.get_console_logs(limit, workflow_id=None)` and `clear_console_logs(workflow_id=None)` filter by workflow when given. `handle_clear_console_logs` broadcasts `console_logs_cleared` carrying the `workflow_id` so the existing frontend filter in `WebSocketContext` keeps other workflows' panels intact. Frontend reads `currentWorkflow.id` via the documented Zustand escape hatch (`useAppStore.getState().currentWorkflow?.id`) at call time for `clearChatMessages` / `clearConsoleLogs` / `sendChatMessage` so the callbacks don't re-create on every workflow switch. A dedicated `useEffect([currentWorkflowId, isReady])` resets local `chatMessages` / `consoleLogs` and refetches both when the user opens / switches workflow. Incoming `console_log` broadcasts are filtered by `currentWorkflow.id` so a parallel run on another workflow never bleeds into the active panel. Legacy logs without `workflow_id` still surface (transition guard).+- **Workflow-scoped chat + console history**: chat messages persist with `chat_messages.session_id == <workflow_id>` (or `"default"` when no workflow is open); console logs persist with `console_logs.workflow_id`. Backend `database.get_console_logs(limit, workflow_id=None)` and `clear_console_logs(workflow_id=None)` filter by workflow when given. `handle_clear_console_logs` broadcasts `console_logs_cleared` carrying the `workflow_id` so the existing frontend filter in `WebSocketContext` keeps other workflows' panels intact. Frontend reads `currentWorkflow.id` via the documented Zustand escape hatch (`useAppStore.getState().currentWorkflow?.id`) at call time for `clearChatMessages` / `clearConsoleLogs` / `sendChatMessage` so the callbacks don't re-create on every workflow switch. A dedicated `useEffect([currentWorkflowId, isReady])` resets local `chatMessages` / `consoleLogs` and refetches both when the user opens / switches workflow. Incoming `console_log` broadcasts are filtered by `currentWorkflow.id` so a parallel run on another workflow never bleeds into the active panel. Legacy logs without `workflow_id` still surface (transition guard). The console's Chat pane no longer reads the context's `chatMessages` (it is the shared chat, `features/chat`, reading `get_chat_messages` through TanStack Query); the get-started checklist (`hooks/useGetStarted.ts`) still does, until it moves too.- **Auto-derived `isConfigNode` uiHint**: `_derive_auto_ui_hints(group)` in `services/plugin/base.py` automatically sets `uiHints.isConfigNode: True` on any plugin whose `group` tuple contains `memory` or `tool` (centralized as `_CONFIG_NODE_GROUPS = frozenset({"memory", "tool"})`). Explicit `cls.ui_hints` always wins (merge order: auto first, then `dict.update`). Frontend `InputSection.tsx` consumes the flag via `definition?.uiHints?.isConfigNode === true` — the old `groups.includes('memory') || groups.includes('tool')` heuristic is gone. Pytest invariant `test_ui_hints_only_carry_known_flags` locks the flag name. Adding a new auxiliary node type costs zero per-plugin code; opting out costs one line (`ui_hints = {"isConfigNode": False}`).- **`isMasterSkillEditor` uiHint replaces `node.type === 'masterSkill'` checks**: the frontend callsites (`useAutoSkillEdges.ts` constant + edge filter, `MiddleSection.tsx` × 3; Dashboard's component-dispatch branch went with the unused `ToolkitNode`, because masterSkill declares `component_kind = "tool"` and renders through SquareNode) read `getCachedNodeSpec(type)?.uiHints?.isMasterSkillEditor === true` instead of comparing the type string. The `MasterSkillNode` plugin already declared the hint — no backend change. Renaming the plugin's `type` is now a single backend edit followed by a NodeSpec deploy; the frontend never needs to know the string.- **`outputMode: "terminal"` uiHint — spec-driven CLI output rendering**: the output panel (`components/output/OutputPanel.tsx`, the active renderer — `ui/OutputDisplayPanel.tsx` is legacy/unimported) renders string responses through ReactMarkdown by default, which whitespace-collapses CLI text. CLI-wrapper plugins (`githubAction`, `vercelAction`, `shell`) declare `ui_hints = {"outputMode": "terminal"}`; the panel resolves the spec via `useNodeSpec(selectedNode?.type)` and renders their text in a `<pre>` on the per-theme `--code-*` surface, routes wholly-JSON strings to the JSON tree via the shared `tryParseJson` (`utils/formatters.ts`), and surfaces object/array `result` payloads (server-side-parsed CLI JSON; arrays survive `unwrap` un-peeled) in the Response section. Pair with the `_shape` convention: parsed JSON in `result` OR text in `stdout` — never both — empty keys omitted. Locked by `client/src/components/__tests__/OutputPanel.test.tsx` (render tests: real `\n`/`\t` preserved) + the uiHints known-set in `test_node_spec.py`. Cache note: nodeSpecs are session-sticky (`staleTime: FOREVER`, revision-busted at page load) — after a backend restart a hard browser reload is needed before new uiHints reach an open canvas.diff --git a/client/eslint.config.js b/client/eslint.config.jsindex 6463d6a0..99e48930 100644--- a/client/eslint.config.js+++ b/client/eslint.config.js@@ -6,6 +6,7 @@ import tseslint from 'typescript-eslint'const GENUI_PRIVATE ='Import the setup-screen pipeline from features/home/genui (its index) only; its modules are private to that folder.'+const CHAT_PRIVATE = 'Import the chat from features/chat (its index) only; its modules are private to that folder.'export default tseslint.config({ ignores: ['dist'] },@@ -87,13 +88,22 @@ export default tseslint.config(// Normal mode's setup-screen pipeline (catalogue, parser, normalizer,// renderer, draft store) is private to its folder: everything else// imports it through features/home/genui/index.ts. Only that folder is- // caught: the shared json-render glue (lib/jsonRender) and other- // generated-UI folders (features/chat/genui) are free to import.+ // caught: the shared json-render glue (lib/jsonRender) is free to import.+ // The shared chat (features/chat) is private the same way: its index is+ // its public surface, and its own files reach each other relatively.{files: ['src/**/*.{ts,tsx}'],ignores: ['src/features/home/genui/**'],rules: {- 'no-restricted-imports': ['error', { patterns: [{ group: ['**/home/genui/*'], message: GENUI_PRIVATE }] }],+ 'no-restricted-imports': [+ 'error',+ {+ patterns: [+ { group: ['**/home/genui/*'], message: GENUI_PRIVATE },+ { group: ['**/features/chat/*'], message: CHAT_PRIVATE },+ ],+ },+ ],},},// Home's own folders reach it relatively ("../genui/catalog"), which the@@ -101,6 +111,24 @@ export default tseslint.config({files: ['src/features/home/**/*.{ts,tsx}'],ignores: ['src/features/home/genui/**'],+ rules: {+ 'no-restricted-imports': [+ 'error',+ {+ patterns: [+ { group: ['**/home/genui/*'], message: GENUI_PRIVATE },+ { regex: '^(?:\\./|(?:\\.\\./)+)genui/', message: GENUI_PRIVATE },+ { group: ['**/features/chat/*'], message: CHAT_PRIVATE },+ ],+ },+ ],+ },+ },+ // Tests may set up the chat's internals (its stores, its lazy markdown);+ // they keep the setup-screen rule.+ {+ files: ['src/**/__tests__/**/*.{ts,tsx}', 'src/**/*.test.{ts,tsx}'],+ ignores: ['src/features/home/genui/**'],rules: {'no-restricted-imports': ['error',diff --git a/client/src/components/__tests__/ConsolePanel.focus.test.tsx b/client/src/components/__tests__/ConsolePanel.focus.test.tsxindex ed742291..db73fa42 100644--- a/client/src/components/__tests__/ConsolePanel.focus.test.tsx+++ b/client/src/components/__tests__/ConsolePanel.focus.test.tsx@@ -8,25 +8,31 @@import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest';import { render, screen, act } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';// Full-module replace of the WS context (importActual+spread is broken under// React 19 — see CredentialsModal.test.tsx). ConsolePanel destructures:-// consoleLogs, clearConsoleLogs, terminalLogs, clearTerminalLogs,-// sendChatMessage, chatMessages, clearChatMessages. lib/nodeSpec (imported-// transitively) also pulls useWebSocket but only calls it inside hooks that-// this test never mounts.+// consoleLogs, clearConsoleLogs, terminalLogs, clearTerminalLogs; the Chat+// pane (the shared chat) reads its thread and runs through+// useWebSocketActions. lib/nodeSpec (imported transitively) also pulls+// useWebSocket but only calls it inside hooks that this test never mounts.const wsMock = {consoleLogs: [] as unknown[],terminalLogs: [] as unknown[],- chatMessages: [] as unknown[],- sendChatMessage: vi.fn().mockResolvedValue(undefined),clearConsoleLogs: vi.fn(),clearTerminalLogs: vi.fn(),- clearChatMessages: vi.fn(),+};+const actionsMock = {+ isReady: true,+ sendRequest: vi.fn(async (type: string) =>+ type === 'chat_subscribe' ? { success: true, hub_epoch: 'e1', active_runs: [] } : { success: true, messages: [] },+ ),+ addEventListener: () => () => {},};vi.mock('../../contexts/WebSocketContext', () => ({useWebSocket: () => wsMock,+ useWebSocketActions: () => actionsMock,}));import ConsolePanel from '../ui/ConsolePanel';@@ -61,7 +67,14 @@ beforeEach(() => {});const renderPanel = (isOpen: boolean) =>- render(<ConsolePanel isOpen={isOpen} onToggle={vi.fn()} nodes={[]} />);+ render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <ConsolePanel isOpen={isOpen} onToggle={vi.fn()} nodes={[]} />+ </QueryClientProvider>,+ );++/** The Chat pane's message box (no workflow open: it talks to "Workflow"). */+const chatBox = () => screen.getByRole('textbox', { name: 'Message Workflow' });// ---------------------------------------------------------------------------@@ -71,13 +84,13 @@ describe('ConsolePanel chat focus', () => {await act(async () => {await flushAnimationFrame();});- const input = screen.getByPlaceholderText('Type a message...');+ const input = chatBox();expect(input).not.toHaveFocus();});it('focuses the chat input when chatFocusRequest increments while open', async () => {renderPanel(true);- const input = screen.getByPlaceholderText('Type a message...');+ const input = chatBox();expect(input).not.toHaveFocus();act(() => {@@ -92,7 +105,7 @@ describe('ConsolePanel chat focus', () => {it('focuses again on a subsequent increment after focus moved elsewhere', async () => {renderPanel(true);- const input = screen.getByPlaceholderText('Type a message...');+ const input = chatBox();act(() => {useAppStore.getState().requestChatFocus();@@ -103,7 +116,7 @@ describe('ConsolePanel chat focus', () => {expect(input).toHaveFocus();act(() => {- (input as HTMLInputElement).blur();+ (input as HTMLTextAreaElement).blur();});expect(input).not.toHaveFocus();@@ -118,7 +131,7 @@ describe('ConsolePanel chat focus', () => {it('does not focus when the panel is closed', async () => {renderPanel(false);- const input = screen.getByPlaceholderText('Type a message...');+ const input = chatBox();act(() => {useAppStore.getState().requestChatFocus();@@ -151,7 +164,7 @@ describe('ConsolePanel chat focus (tab mode)', () => {it('renders Chat as a tab and no chat input while another tab is active', () => {renderPanel(true);expect(screen.getByRole('button', { name: 'Chat' })).toBeInTheDocument();- expect(screen.queryByPlaceholderText('Type a message...')).not.toBeInTheDocument();+ expect(screen.queryByRole('textbox', { name: 'Message Workflow' })).not.toBeInTheDocument();});it('switches to the Chat tab and focuses the input on a focus request', async () => {@@ -164,7 +177,7 @@ describe('ConsolePanel chat focus (tab mode)', () => {await flushAnimationFrame();});- const input = screen.getByPlaceholderText('Type a message...');+ const input = chatBox();expect(input).toHaveFocus();});});diff --git a/client/src/components/catalog/presentation.ts b/client/src/components/catalog/presentation.tsindex e53d0cd0..87d6070d 100644--- a/client/src/components/catalog/presentation.ts+++ b/client/src/components/catalog/presentation.ts@@ -9,3 +9,9 @@ export const AVATAR_CLASS: Record<ColorRole, string> = {trigger: 'bg-node-trigger-fill border-node-trigger-edge text-node-trigger-ink',workflow: 'bg-node-workflow-fill border-node-workflow-edge text-node-workflow-ink',};++/** An avatar's letter: the first letter of the name, "?" when empty. */+export function initialOf(name: string): string {+ const letter = Array.from(name.trim())[0];+ return letter ? letter.toLocaleUpperCase() : '?';+}diff --git a/client/src/components/ui/ConsoleChat.tsx b/client/src/components/ui/ConsoleChat.tsxnew file mode 100644index 00000000..de7664b1--- /dev/null+++ b/client/src/components/ui/ConsoleChat.tsx@@ -0,0 +1,89 @@+/**+ * The editor's Chat pane in the console panel: the shared chat+ * (features/chat), compact, over the open workflow's chat session+ * (`default` with no workflow open), showing the live generation only.+ * A message goes to the workflow's chat triggers; Clear clears the chat and+ * what the workflow's agents remember of it.+ *+ * The console's font size applies to the conversation. The `chat` panel+ * hook stays on ConsolePanel's root; the turns carry `chat-msg-user` /+ * `chat-msg-bot` for the stylized themes.+ */++import type { Ref } from 'react';+import { toast } from 'sonner';+import { ActionButton } from '@/components/ui/action-button';+import { Badge } from '@/components/ui/badge';+import { ChatPane, useChatThread, useClearChat, type ChatPaneHandle, type NotifyTone } from '@/features/chat';+import { useAppStore } from '../../store/useAppStore';++const SEND_REFUSED: Record<string, { message: string; tone: NotifyTone }> = {+ // Nothing listens while the workflow is stopped, so the server saved nothing.+ not_running: { message: 'Start this workflow to chat with it.', tone: 'error' },+ // One answer at a time per conversation; the text is back in the box.+ run_in_progress: { message: 'The workflow is still answering your last message.', tone: 'info' },+};++function notify(message: string, tone: NotifyTone) {+ if (tone === 'error') toast.error(message);+ else if (tone === 'success') toast.success(message);+ else toast.info(message);+}++export function ConsoleChat({ fontSize, ref }: { fontSize: number; ref?: Ref<ChatPaneHandle> }) {+ const sessionId = useAppStore((s) => s.currentWorkflow?.id || 'default');+ const workflowName = useAppStore((s) => s.currentWorkflow?.name ?? '');+ const thread = useChatThread(sessionId, 'live');+ const clear = useClearChat(sessionId);+ const count = thread.data?.messages.length ?? 0;++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex min-h-[32px] items-center justify-between border-b border-border-default bg-bg-elevated px-3 py-1.5">+ <span className="flex items-center gap-1.5 font-display text-sm font-semibold tracking-[var(--type-tracking-display)] text-fg-default [text-transform:var(--type-uppercase)]">+ Chat+ {count > 0 && (+ <Badge variant="success" className="text-xs">+ {count}+ </Badge>+ )}+ </span>+ {count > 0 && (+ <ActionButton+ intent="stop"+ disabled={clear.isPending}+ onClick={() => clear.mutate(undefined, { onError: () => notify('The chat could not be cleared. Try again.', 'error') })}+ title="Clear the chat, and what the agent remembers of it"+ className="h-6 px-2 text-xs"+ >+ Clear+ </ActionButton>+ )}+ </div>+ <div style={{ fontSize }} className="flex min-h-0 flex-1 flex-col">+ <ChatPane+ key={sessionId}+ ref={ref}+ host={{+ kind: 'dev',+ sessionId,+ scope: 'live',+ persona: { name: workflowName || 'Workflow', colorRole: 'agent' },+ composer: 'send',+ emptyState: (+ <p className="m-0 py-6 text-center text-xs text-muted-foreground">Send a message to trigger chatTrigger nodes</p>+ ),+ notify,+ onSendRefused: (code) => {+ const refused = SEND_REFUSED[code] ?? { message: 'Your message didn’t send. Try again.', tone: 'error' as const };+ notify(refused.message, refused.tone);+ },+ compact: true,+ }}+ />+ </div>+ </div>+ );+}++export default ConsoleChat;diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsxindex 3a2e2ed1..dcdf6876 100644--- a/client/src/components/ui/ConsolePanel.tsx+++ b/client/src/components/ui/ConsolePanel.tsx@@ -1,9 +1,10 @@/*** Console Panel - n8n-style debug output panel with chat input*- * Displays console log entries from Console nodes during workflow execution.- * Includes chat input section for triggering chatTrigger nodes.- * Shows in a collapsible bottom bar section with clear and filter options.+ * Displays console log entries from Console nodes during workflow execution,+ * beside the Chat pane (ConsoleChat: the chat shared with Home, talking to+ * the open workflow's chat triggers). Shows in a collapsible bottom bar+ * section with clear and filter options.** Design-handoff hybrid layout: split view (default) docks Chat as a* resizable pane beside the Console/Terminal tabs; tab mode makes Chat@@ -20,8 +21,7 @@ import remarkBreaks from 'remark-breaks';import { z } from 'zod';import Prism from 'prismjs';import 'prismjs/components/prism-json';-import { ChevronDown, Columns2, Send } from 'lucide-react';-import { toast } from 'sonner';+import { ChevronDown, Columns2 } from 'lucide-react';import { useWebSocket, ConsoleLogEntry } from '../../contexts/WebSocketContext';import { Input } from '@/components/ui/input';import { Button } from '@/components/ui/button';@@ -35,10 +35,11 @@ import {SelectValue,} from '@/components/ui/select';import { cn } from '@/lib/utils';-import { CHAT_MARKDOWN_COMPONENTS } from '@/features/chat';+import { useChatThread, type ChatPaneHandle } from '@/features/chat';import { resolveNodeDescription } from '../../lib/nodeSpec';import { useAppStore } from '../../store/useAppStore';import { usePanelResize } from '../../hooks/usePanelResize';+import { ConsoleChat } from './ConsoleChat';// ---------------------------------------------------------------------------// Persisted prefs (localStorage)@@ -107,17 +108,12 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({minHeight = 80,nodes = [],}) => {- const { consoleLogs, clearConsoleLogs, terminalLogs, clearTerminalLogs, sendChatMessage, chatMessages, clearChatMessages } = useWebSocket();+ const { consoleLogs, clearConsoleLogs, terminalLogs, clearTerminalLogs } = useWebSocket();+ // The open workflow's chat (ConsoleChat reads the same thread).+ const chatSessionId = useAppStore((s) => s.currentWorkflow?.id || 'default');+ const chatCount = useChatThread(chatSessionId, 'live').data?.messages.length ?? 0;- // Workflow nodes that participate in this panel.- const chatTriggerNodes = useMemo(() =>- nodes.filter(n => {- const def = n.type ? resolveNodeDescription(n.type) : undefined;- return def?.uiHints?.isChatTrigger- ?? (n.type ? ['chatTrigger'].includes(n.type) : false);- }),- [nodes]- );+ // Console nodes in the workflow, for the console filter.const consoleNodes = useMemo(() =>nodes.filter(n => {const def = n.type ? resolveNodeDescription(n.type) : undefined;@@ -127,7 +123,6 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({[nodes]);- const [selectedChatTriggerId, setSelectedChatTriggerId] = useState<string>('');const [selectedConsoleId, setSelectedConsoleId] = useState<string>('');const [filter, setFilter] = useState('');const [terminalFilter, setTerminalFilter] = useState('');@@ -148,8 +143,7 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({const activeTab = splitView && consoleTab === 'chat' ? 'console' : consoleTab;const logsEndRef = useRef<HTMLDivElement>(null);- const chatEndRef = useRef<HTMLDivElement>(null);- const chatInputRef = useRef<HTMLInputElement>(null);+ const chatRef = useRef<ChatPaneHandle>(null);// Focus the chat input when requested (onboarding handoff, checklist).// Each request is consumed once so later manual panel toggles don't@@ -159,15 +153,13 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({useEffect(() => {if (chatFocusRequest === handledFocusRequestRef.current || !isOpen) return;handledFocusRequestRef.current = chatFocusRequest;- // In tab mode the chat input only exists while the Chat tab is+ // In tab mode the chat's message box only exists while the Chat tab is// active — switch to it before focusing.if (!splitView) setPref('consoleTab', 'chat');- const frame = requestAnimationFrame(() => chatInputRef.current?.focus());+ const frame = requestAnimationFrame(() => chatRef.current?.focusComposer());return () => cancelAnimationFrame(frame);}, [chatFocusRequest, isOpen, splitView, setPref]);- const [chatInput, setChatInput] = useState('');- const [isSending, setIsSending] = useState(false);const containerRef = useRef<HTMLDivElement>(null);const verticalResize = usePanelResize({@@ -269,42 +261,9 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({}}, [filteredLogs.length, autoScroll, isOpen]);- useEffect(() => {- if (isOpen && chatEndRef.current) {- chatEndRef.current.scrollIntoView({ behavior: 'smooth' });- }- }, [chatMessages?.length, isOpen]);-// ------------------------------ Actions ------------------------------const handleClearConsole = useCallback(() => clearConsoleLogs(), [clearConsoleLogs]);- const handleClearChat = useCallback(() => clearChatMessages(), [clearChatMessages]);-- const handleSendChat = useCallback(async () => {- const message = chatInput.trim();- if (!message || isSending) return;- setIsSending(true);- try {- await sendChatMessage(message, selectedChatTriggerId || undefined);- setChatInput('');- } catch (error) {- // Nothing listens while the workflow is stopped, so the server saved nothing.- if (error instanceof Error && error.message === 'not_running') toast.error('Start this workflow to chat with it.');- // One answer at a time per conversation; the text stays in the box.- else if (error instanceof Error && error.message === 'run_in_progress') toast.info('The workflow is still answering your last message.');- else console.error('Failed to send chat message:', error);- } finally {- setIsSending(false);- }- }, [chatInput, isSending, sendChatMessage, selectedChatTriggerId]);-- const handleChatKeyDown = useCallback((e: React.KeyboardEvent) => {- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault();- handleSendChat();- }- }, [handleSendChat]);-// ------------------------------ Formatting ------------------------------const formatTimestamp = useCallback((timestamp: string) => {@@ -357,132 +316,8 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({// ------------------------------ Render ------------------------------- // One chat implementation for both layouts: the split-view docked pane- // and the Chat tab. The `chat-msg` / `chat-msg-user` / `chat-msg-bot`- // co-classes are the design-handoff structural hooks per-theme CSS- // decorates — they must survive any relocation of this block.- const chatSection = (- <>- {/* Header */}- <div className="flex min-h-[32px] items-center justify-between border-b border-border-default bg-bg-elevated px-3 py-1.5">- <div className="flex items-center gap-2">- <span className="flex items-center gap-1.5 font-display text-sm font-semibold tracking-[var(--type-tracking-display)] text-fg-default [text-transform:var(--type-uppercase)]">- Chat- {chatMessages && chatMessages.length > 0 && (- <Badge variant="success" className="text-xs">{chatMessages.length}</Badge>- )}- </span>- {chatTriggerNodes.length > 0 && (- <Select- value={selectedChatTriggerId || '__all__'}- onValueChange={(v) => setSelectedChatTriggerId(v === '__all__' ? '' : v)}- >- <SelectTrigger- className="h-6 max-w-[120px] text-xs"- onClick={(e) => e.stopPropagation()}- title="Select chatTrigger node to target"- >- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="__all__">All Triggers</SelectItem>- {chatTriggerNodes.map(node => (- <SelectItem key={node.id} value={node.id}>- {node.data?.label || node.id}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- </div>- {chatMessages && chatMessages.length > 0 && (- <Button- variant="outline"- size="xs"- onClick={handleClearChat}- title="Clear the chat, and what the agent remembers of it"- className="border-destructive/40 text-destructive hover:bg-destructive/10"- >- Clear- </Button>- )}- </div>-- {/* Messages */}- <div- data-scrollable- style={{ fontSize: consoleFontSize }}- className="flex-1 overflow-auto px-4 py-3"- >- {(!chatMessages || chatMessages.length === 0) ? (- <div className="flex h-full items-center justify-center p-6 text-center text-xs text-muted-foreground">- Send a message to trigger chatTrigger nodes- </div>- ) : (- <div className="flex flex-col gap-1">- {chatMessages.map((msg, index) => {- const isUser = msg.role === 'user';- return (- <div- key={`${msg.timestamp}-${index}`}- className={cn(- // `chat-msg` + `chat-msg-user` / `chat-msg-bot`- // co-classes activate per-theme bubble decorations- // (Renaissance: gold-foil user / vellum bot with- // ✦ marker; Cyber: > USER:: / < NODE:: prefixes- // with neon glow; etc.).- 'chat-msg max-w-[80%] px-3 py-2 break-words',- isUser- ? 'chat-msg-user mr-0 ml-auto rounded-l-xl rounded-tr-xl rounded-br-sm bg-node-agent-soft'- : 'chat-msg-bot mr-auto ml-0 rounded-r-xl rounded-tl-xl rounded-bl-sm border border-border-default bg-bg-elevated'- )}- >- {isUser ? (- <pre className="m-0 leading-tight font-[inherit] text-[length:inherit] whitespace-pre-wrap break-words text-foreground">- {msg.message}- </pre>- ) : (- <div className="chat-markdown text-sm leading-snug text-foreground">- <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={CHAT_MARKDOWN_COMPONENTS}>- {msg.message}- </ReactMarkdown>- </div>- )}- <div className="mt-0.5 text-xs text-muted-foreground">- {formatTimestamp(msg.timestamp)}- </div>- </div>- );- })}- <div ref={chatEndRef} />- </div>- )}- </div>-- {/* Input */}- <div className="flex items-center gap-2 border-t border-border-default bg-bg-elevated px-4 py-2.5">- <Input- ref={chatInputRef}- type="text"- placeholder="Type a message..."- value={chatInput}- onChange={(e) => setChatInput(e.target.value)}- onKeyDown={handleChatKeyDown}- disabled={isSending}- className="flex-1"- />- <Button- variant="default"- size="sm"- onClick={handleSendChat}- disabled={isSending || !chatInput.trim()}- >- <Send className="h-3.5 w-3.5" />- {isSending ? '...' : 'Send'}- </Button>- </div>- </>- );+ // One chat for both layouts: the split-view docked pane and the Chat tab.+ const chatSection = <ConsoleChat ref={chatRef} fontSize={consoleFontSize} />;return (// `chat` co-class is the design-handoff structural hook for per-theme@@ -523,9 +358,9 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({/><span className="flex items-center gap-1.5 font-display text-sm font-semibold tracking-[var(--type-tracking-display)] text-fg-default [text-transform:var(--type-uppercase)]">Chat / Console- {(consoleLogs.length > 0 || (chatMessages && chatMessages.length > 0)) && (+ {(consoleLogs.length > 0 || chatCount > 0) && (<Badge variant="secondary" className="text-xs">- {consoleLogs.length + (chatMessages?.length || 0)}+ {consoleLogs.length + chatCount}</Badge>)}</span>@@ -583,8 +418,8 @@ const ConsolePanel: React.FC<ConsolePanelProps> = ({)}>Chat- {chatMessages && chatMessages.length > 0 && (- <Badge variant="success" className="ml-1 px-1 text-xs">{chatMessages.length}</Badge>+ {chatCount > 0 && (+ <Badge variant="success" className="ml-1 px-1 text-xs">{chatCount}</Badge>)}</button>)}diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsxnew file mode 100644index 00000000..cd11f5ab--- /dev/null+++ b/client/src/features/chat/ChatPane.tsx@@ -0,0 +1,82 @@+/**+ * The chat shared by Home's employee page and Dev's console Chat pane+ * (design handoff chat/): the conversation, scrolling on its own, and under+ * it the dock with the host's notices, the message box and a footnote. The+ * host (`ChatHost`) says who answers, whether a message can go now and what+ * sits around the conversation; the chat owns the rest.+ *+ * The turns follow the session's runs (docs-internal/chat_protocol.md):+ * "Working…" shows while the run a message started is going, whatever+ * else arrives meanwhile, and the next message waits until it ends. A+ * message that does not go comes back into the box.+ */++import { useCallback, useImperativeHandle, useRef, type Ref } from 'react';+import { cn } from '@/lib/utils';+import { useConversation } from './data/conversation';+import { useSendChatMessage, type ChatSendError } from './data/send';+import { Composer } from './composer/Composer';+import type { ChatHost, ChatPaneHandle } from './host';+import { useComposerStore } from './state/composerStore';+import { ChatThread } from './thread/ChatThread';++export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHandle> }) {+ const { sessionId, scope, persona, composer, notify, onSendRefused, compact = false } = host;+ const { thread, turns, lane } = useConversation(sessionId, scope);+ const boxRef = useRef<HTMLTextAreaElement>(null);+ useImperativeHandle(ref, () => ({ focusComposer: () => boxRef.current?.focus() }), []);++ const onRefused = useCallback(+ (error: ChatSendError) => {+ if (onSendRefused) onSendRefused(error.code);+ else notify('Your message didn’t send. Try again.', 'error');+ },+ [notify, onSendRefused],+ );+ const send = useSendChatMessage(sessionId, scope, onRefused);+ const busy = send.isPending || lane !== null;++ const submit = () => {+ const store = useComposerStore.getState();+ if (busy || !thread.data || !(store.drafts[sessionId]?.text ?? '').trim()) return;+ const draft = store.takeForSend(sessionId);+ send.mutate({ ...draft, text: draft.text.trim() });+ };++ return (+ <section aria-label={`Chat with ${persona.name}`} className="flex min-h-0 w-full flex-1 flex-col">+ <ChatThread+ persona={persona}+ turns={turns}+ loading={thread.isPending}+ error={thread.isError && !thread.data}+ onRetry={() => void thread.refetch()}+ top={host.top}+ afterThread={host.afterThread}+ emptyState={host.emptyState}+ liveNote={host.liveNote}+ compact={compact}+ onScrolledChange={host.onScrolledChange}+ />+ <div className={cn('relative flex-none', compact ? 'border-t border-border-default px-3 py-2' : 'px-6 pb-3')}>+ <div className={cn('mx-auto flex w-full flex-col', compact ? 'gap-2' : 'max-w-(--w-chat-column) gap-2.5')}>+ {host.notices}+ {composer !== 'closed' && (+ <Composer+ sessionId={sessionId}+ name={persona.name}+ ready={Boolean(thread.data)}+ busy={busy}+ onSend={submit}+ compact={compact}+ boxRef={boxRef}+ />+ )}+ {host.footnote && <p className="m-0 text-center text-xs text-fg-muted">{host.footnote}</p>}+ </div>+ </div>+ </section>+ );+}++export default ChatPane;diff --git a/client/src/features/chat/__tests__/chatPane.test.tsx b/client/src/features/chat/__tests__/chatPane.test.tsxnew file mode 100644index 00000000..881580e9--- /dev/null+++ b/client/src/features/chat/__tests__/chatPane.test.tsx@@ -0,0 +1,237 @@+/**+ * The shared chat against a fake server: it follows the session's runs+ * (subscribing while mounted), shows a message at once and the employee+ * working until the run ends, holds the next message until then, says why a+ * run failed, waits for Resume, and puts a message that did not go back in+ * the box, where it survives leaving the conversation.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';++const sendRequest = vi.fn();++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));++import { resetChatRunStore, useChatRunStore } from '@/stores/chatRunStore';+import { ChatPane } from '../ChatPane';+import type { ChatHost } from '../host';+import { useComposerStore } from '../state/composerStore';+// Loaded up front so the turns' lazy markdown resolves from the module cache.+import '../markdown/ReplyMarkdown';++type Wire = Record<string, unknown>;+let server: { messages: Wire[]; send: Wire; activeRuns: Wire[] };+let client: QueryClient;++function row(id: string, role: 'user' | 'assistant', text: string, patch: Wire = {}): Wire {+ return { id, role, text, message: text, timestamp: '2026-10-03T09:00:00Z', run_key: 'g1', ...patch };+}++function frame(seq: number, suffix: string, data: Wire = {}, runId = 'r1') {+ return {+ specversion: '1.0',+ id: `${runId}:${seq}`,+ source: 'opencompany://services/chat',+ type: `com.opencompany.chat.run.${suffix}`,+ subject: runId,+ data: { workflow_id: 'w1', session_id: 'w1', run_id: runId, seq, hub_epoch: 'e1', ...data },+ };+}++function runEvents(...frames: unknown[]) {+ act(() => {+ const store = useChatRunStore.getState();+ for (const item of frames) store.receive(item);+ store.flush();+ });+}++async function threadUpdated() {+ await act(async () => {+ await client.invalidateQueries({ queryKey: ['chatThread'] });+ });+}++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()) {+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const view = (next: ChatHost) => (+ <QueryClientProvider client={client}>+ <ChatPane host={next} />+ </QueryClientProvider>+ );+ const utils = render(view(chat));+ return { ...utils, rerender: (next: ChatHost) => utils.rerender(view(next)) };+}++function box() {+ return screen.getByRole('textbox', { name: 'Message Maya' });+}++function type(text: string) {+ fireEvent.change(box(), { target: { value: text } });+}++/** Write a message once the conversation has loaded (until then it cannot go). */+async function write(text: string) {+ type(text);+ await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled());+}++beforeEach(() => {+ resetChatRunStore();+ useComposerStore.setState({ drafts: {} });+ server = { messages: [], send: { success: true, message_id: 'm1', run_id: 'r1', delivery: 'now' }, activeRuns: [] };+ 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: server.activeRuns };+ case 'get_chat_messages':+ return { success: true, messages: server.messages, thread: { active_leaf_id: null, revision: 1 }, active_runs: server.activeRuns };+ case 'send_chat_message':+ if (server.send.success !== false) {+ server.messages = [...server.messages, row(String(server.send.message_id), 'user', String(data.message), {+ run_id: server.send.run_id,+ client_message_id: data.client_message_id,+ })];+ }+ return server.send;+ default:+ return { success: true };+ }+ });+});++describe('ChatPane', () => {+ it('follows the session while it is open and reads the thread for its scope', async () => {+ const { unmount } = renderPane(host({ scope: 'live' }));+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('chat_subscribe', { session_id: 'w1' }));+ expect(sendRequest).toHaveBeenCalledWith('get_chat_messages', { session_id: 'w1', limit: 200, all_generations: false });+ await waitFor(() => expect(useChatRunStore.getState().sessions.w1?.subscribed).toBe(true));+ unmount();+ expect(sendRequest).toHaveBeenCalledWith('chat_unsubscribe', { session_id: 'w1' });+ });++ it('shows a message at once and the employee working until the run ends', async () => {+ renderPane();+ await waitFor(() => expect(useChatRunStore.getState().sessions.w1?.subscribed).toBe(true));+ await write(' Any bookings today? ');+ fireEvent.keyDown(box(), { key: 'Enter' });++ expect(box()).toHaveValue('');+ expect(await screen.findByText('Any bookings today?')).toBeInTheDocument();+ await waitFor(() =>+ expect(sendRequest).toHaveBeenCalledWith(+ 'send_chat_message',+ expect.objectContaining({ message: 'Any bookings today?', session_id: 'w1', client_message_id: expect.any(String) }),+ ),+ );+ expect(await screen.findByText('Working…')).toBeInTheDocument();+ // The next message waits for this answer.+ type('And tomorrow?');+ expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();++ runEvents(frame(1, 'started', { kind: 'message', user_message_id: 'm1' }));+ expect(screen.getByText('Working…')).toBeInTheDocument();+ server.messages = [...server.messages, row('a_r1', 'assistant', 'Two, at **10** and at 3.', { run_id: 'r1' })];+ runEvents(frame(2, 'finished', { outcome: { type: 'success' }, result: { reply_message_id: 'a_r1' } }));+ await threadUpdated();++ expect(await screen.findByText('10', { selector: 'strong' })).toBeInTheDocument();+ expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled();+ expect(screen.getAllByText('Any bookings today?')).toHaveLength(1);+ });++ it('says why a run failed, with what to do about it', async () => {+ server.messages = [row('m1', 'user', 'Book Priya in', { run_id: 'r1' })];+ server.activeRuns = [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }];+ renderPane();+ expect(await screen.findByText('Working…')).toBeInTheDocument();+ runEvents(frame(2, 'failed', { message: 'Calendar said no', code: 'run_failed', hint: 'Reconnect Google' }));+ expect(screen.getByText('Maya couldn’t answer.')).toBeInTheDocument();+ expect(screen.getByText('Calendar said no')).toBeInTheDocument();+ expect(screen.getByText('Reconnect Google')).toBeInTheDocument();+ expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ });++ it('shows how an earlier run ended after a reload', async () => {+ server.messages = [+ row('m1', 'user', 'Anyone there?', {+ run_id: 'r1',+ run: { run_id: 'r1', state: 'error', outcome: null, error: { message: 'x', code: 'not_delivered' } },+ }),+ ];+ renderPane();+ expect(await screen.findByText('Maya didn’t pick up this message.')).toBeInTheDocument();+ });++ it('waits for Resume when the message was queued', async () => {+ server.send = { success: true, message_id: 'm1', run_id: 'r1', delivery: 'queued' };+ renderPane(host({ composer: 'queue' }));+ await write('Call me back');+ fireEvent.keyDown(box(), { key: 'Enter' });+ expect(await screen.findByText('Waiting for you to resume Maya.')).toBeInTheDocument();+ expect(screen.queryByText('Working…')).not.toBeInTheDocument();++ runEvents(frame(1, 'started', { kind: 'message' }));+ expect(await screen.findByText('Working…')).toBeInTheDocument();+ });++ it('puts a message that did not go back in the box, and lets the host say why', async () => {+ server.send = { success: false, error: 'not_running' };+ const onSendRefused = vi.fn();+ renderPane(host({ onSendRefused }));+ await write('Hello?');+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ await waitFor(() => expect(onSendRefused).toHaveBeenCalledWith('not_running'));+ expect(box()).toHaveValue('Hello?');+ expect(screen.getByRole('log', { name: 'Conversation with Maya' })).not.toHaveTextContent('Hello?');+ });++ it('tells the owner a send failed when the host does not', async () => {+ sendRequest.mockImplementation(async (kind: string) => {+ if (kind === 'send_chat_message') throw new Error('socket closed');+ if (kind === 'chat_subscribe') return { success: true, hub_epoch: 'e1', active_runs: [] };+ return { success: true, messages: [] };+ });+ const chat = host();+ renderPane(chat);+ await write('Hello?');+ fireEvent.keyDown(box(), { key: 'Enter' });+ await waitFor(() => expect(chat.notify).toHaveBeenCalledWith('Your message didn’t send. Try again.', 'error'));+ // It may have reached the server: sending it again is the same message.+ expect(useComposerStore.getState().drafts.w1).toEqual({ text: 'Hello?', clientMessageId: expect.any(String) });+ });++ it('has no message box while nothing can read messages', async () => {+ renderPane(host({ composer: 'closed', notices: <p>Start Maya first.</p> }));+ expect(await screen.findByText('Start Maya first.')).toBeInTheDocument();+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument();+ });++ it('keeps an unsent message when the conversation is opened again', async () => {+ const { unmount } = renderPane();+ type('Half a thought');+ unmount();+ renderPane();+ expect(box()).toHaveValue('Half a thought');+ });+});diff --git a/client/src/features/chat/__tests__/copy.test.ts b/client/src/features/chat/__tests__/copy.test.tsnew file mode 100644index 00000000..6a77cdfd--- /dev/null+++ b/client/src/features/chat/__tests__/copy.test.ts@@ -0,0 +1,77 @@+/**+ * What a turn says: when a message was written, why a run did not answer,+ * and what a working run is doing.+ */++import { describe, expect, it } from 'vitest';+import { emptyRun } from '@/lib/agui/reduceRun';+import { timeLabel } from '../thread/timeLabel';+import { failureLines, liveLabel, streamedText } from '../turns/runCopy';++describe('timeLabel', () => {+ const now = new Date(2026, 8, 28, 15, 30);+ const time = (date: Date) => date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });++ it('gives the time today and says yesterday', () => {+ const morning = new Date(2026, 8, 28, 9, 5);+ expect(timeLabel(morning.toISOString(), now)).toBe(time(morning));+ const lastNight = new Date(2026, 8, 27, 22, 40);+ expect(timeLabel(lastNight.toISOString(), now)).toBe(`Yesterday, ${time(lastNight)}`);+ });++ it('names the weekday within a week, else the date', () => {+ const monday = new Date(2026, 8, 22, 10, 0);+ expect(timeLabel(monday.toISOString(), now)).toBe(`${monday.toLocaleDateString(undefined, { weekday: 'long' })}, ${time(monday)}`);+ const earlier = new Date(2026, 7, 3, 10, 0);+ expect(timeLabel(earlier.toISOString(), now)).toBe(+ `${earlier.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}, ${time(earlier)}`,+ );+ const lastYear = new Date(2025, 11, 31, 10, 0);+ expect(timeLabel(lastYear.toISOString(), now)).toContain(lastYear.getFullYear().toString());+ });++ it('says nothing for a time it cannot read', () => {+ expect(timeLabel(null, now)).toBe('');+ expect(timeLabel('yesterday-ish', now)).toBe('');+ });+});++describe('failureLines', () => {+ it('names the employee when no answer came', () => {+ expect(failureLines({ message: 'The employee did not pick up this message.', code: 'not_delivered' }, 'Maya')).toEqual({+ headline: 'Maya didn’t pick up this message.',+ detail: null,+ });+ expect(failureLines({ message: 'x', code: 'timed_out' }, 'Maya').headline).toBe('Maya took too long to answer.');+ expect(failureLines({ message: 'x', code: 'interrupted' }, 'Maya').headline).toBe('Maya stopped before answering.');+ });++ it('keeps the server’s message for anything else', () => {+ expect(failureLines({ message: 'Spending cap reached.', code: 'run_failed' }, 'Maya')).toEqual({+ headline: 'Maya couldn’t answer.',+ detail: 'Spending cap reached.',+ });+ expect(failureLines(null, 'Maya')).toEqual({ headline: 'Maya couldn’t answer.', detail: null });+ });+});++describe('a working run', () => {+ it('says what it is doing', () => {+ const working = { ...emptyRun('r1', 'w1'), state: 'running' as const };+ expect(liveLabel(working, false)).toBe('Working…');+ expect(liveLabel(working, true)).toBe('Writing…');+ expect(liveLabel({ ...working, state: 'stopping' }, true)).toBe('Stopping…');+ });++ it('shows the reply it streamed, not its narration', () => {+ const run = {+ ...emptyRun('r1', 'w1'),+ segments: [+ { messageId: 'n', text: 'Let me look.', final: false },+ { messageId: 'a', text: 'Two bookings', final: null },+ ],+ };+ expect(streamedText(run)).toBe('Two bookings');+ expect(streamedText(null)).toBe('');+ });+});diff --git a/client/src/features/chat/__tests__/model.test.ts b/client/src/features/chat/__tests__/model.test.tsnew file mode 100644index 00000000..c45f81e5--- /dev/null+++ b/client/src/features/chat/__tests__/model.test.ts@@ -0,0 +1,146 @@+/**+ * The rows a thread draws: which reading of a run wins, where a run's state+ * shows, which failures stay quiet, and the keys that keep one element from+ * the message sent to the saved row, and from the run's turn to its answer.+ */++import { describe, expect, it } from 'vitest';+import { emptyRun, type RunSnapshot } from '@/lib/agui/reduceRun';+import type { ChatMessage, MessageRun } from '../data/schemas';+import { buildTurns, knownRuns } from '../thread/model';++function message(id: string, role: 'user' | 'assistant', patch: Partial<ChatMessage> = {}): ChatMessage {+ return {+ id,+ legacyId: null,+ role,+ kind: 'text',+ text: `${role} ${id}`,+ timestamp: '2026-10-03T09:00:00Z',+ runKey: 'g1',+ runId: null,+ parentId: null,+ status: 'complete',+ attachments: [],+ parts: {},+ clientMessageId: null,+ run: null,+ ...patch,+ };+}++function run(runId: string, patch: Partial<RunSnapshot> = {}): RunSnapshot {+ return { ...emptyRun(runId, 'w1'), ...patch };+}++const messageRun = (runId: string, state: MessageRun['state'], error: MessageRun['error'] = null): MessageRun => ({+ runId,+ state,+ outcome: state === 'finished' ? 'success' : null,+ error,+});++function shape(turns: ReturnType<typeof buildTurns>) {+ return turns.map((turn) =>+ turn.kind === 'divider'+ ? 'divider'+ : turn.kind === 'user'+ ? `user:${turn.message.id}`+ : `assistant:${turn.message?.id ?? '-'}:${turn.run ? turn.run.state : '-'}`,+ );+}++describe('knownRuns', () => {+ const failed = message('m1', 'user', { runId: 'r1', run: messageRun('r1', 'error', { message: 'No', code: 'run_failed' }) });+ const live = message('m2', 'user', { runId: 'r2', run: messageRun('r2', 'running') });++ it('prefers the run store over what a message said', () => {+ const runs = knownRuns('w1', [failed], { r1: run('r1', { state: 'finished' }) }, true);+ expect(runs.r1.state).toBe('finished');+ });++ it('believes the thread read until the subscription answers', () => {+ const active = run('r3', { state: 'running' });+ const before = knownRuns('w1', [live], {}, false, [active]);+ expect(Object.keys(before).sort()).toEqual(['r2', 'r3']);+ expect(before.r2.userMessageId).toBe('m2');++ // Afterwards a run the store does not hold as live is not live.+ const after = knownRuns('w1', [live, failed], {}, true, [active]);+ expect(Object.keys(after)).toEqual(['r1']);+ expect(after.r1).toMatchObject({ state: 'error', error: { message: 'No' } });+ });+});++describe('buildTurns', () => {+ it('draws a divider where the employee restarted', () => {+ const turns = buildTurns(+ [message('m1', 'user'), message('a1', 'assistant'), message('m2', 'user', { runKey: 'g2' }), message('m3', 'user', { runKey: null })],+ {},+ );+ expect(shape(turns)).toEqual(['user:m1', 'assistant:a1:-', 'divider', 'user:m2', 'user:m3']);+ });++ it('keeps a sent message one element when its saved row arrives', () => {+ const local = message('local:c1', 'user', { clientMessageId: 'c1', pending: true });+ const saved = message('m1', 'user', { clientMessageId: 'c1' });+ expect(buildTurns([local], {})[0].key).toBe('user:c1');+ const both = buildTurns([saved, local], {});+ expect(shape(both)).toEqual(['user:m1']);+ expect(both[0].key).toBe('user:c1');+ });++ it('shows a working run on its own turn, then its answer takes that turn', () => {+ const user = message('m1', 'user', { runId: 'r1' });+ const working = buildTurns([user], { r1: run('r1', { state: 'running' }) });+ expect(shape(working)).toEqual(['user:m1', 'assistant:-:running']);+ expect(working[1].key).toBe('run:r1');++ const answered = buildTurns([user, message('a1', 'assistant', { runId: 'r1' })], { r1: run('r1', { state: 'finished' }) });+ expect(shape(answered)).toEqual(['user:m1', 'assistant:a1:-']);+ expect(answered[1].key).toBe('run:r1');+ });++ it('shows a run still going on its last answer', () => {+ const turns = buildTurns(+ [message('m1', 'user', { runId: 'r1' }), message('a1', 'assistant', { runId: 'r1' }), message('a2', 'assistant', { runId: 'r1' })],+ { r1: run('r1', { state: 'running' }) },+ );+ expect(shape(turns)).toEqual(['user:m1', 'assistant:a1:-', 'assistant:a2:running']);+ expect(turns.map((turn) => turn.key)).toEqual(['user:m1', 'run:r1', 'reply:a2']);+ });++ it('keeps a failure where the answer would be, unless an answer came after all', () => {+ const user = message('m1', 'user', { runId: 'r1' });+ const failed = run('r1', { state: 'error', error: { message: 'No', code: 'run_failed' } });+ expect(shape(buildTurns([user], { r1: failed }))).toEqual(['user:m1', 'assistant:-:error']);++ const timedOut = run('r1', { state: 'error', error: { message: 'Slow', code: 'timed_out' } });+ expect(shape(buildTurns([user], { r1: timedOut }))).toEqual(['user:m1', 'assistant:-:error']);+ expect(shape(buildTurns([user, message('a1', 'assistant', { runId: 'r1' })], { r1: timedOut }))).toEqual(['user:m1', 'assistant:a1:-']);+ });++ it('says nothing for a run its conversation took with it', () => {+ const user = message('m1', 'user', { runId: 'r1' });+ const cleared = run('r1', { state: 'error', error: { message: 'Cleared', code: 'cleared' } });+ expect(shape(buildTurns([user], { r1: cleared }))).toEqual(['user:m1']);+ });++ it('shows a finished run only while its streamed answer is on the way', () => {+ const user = message('m1', 'user', { runId: 'r1' });+ const streamed = run('r1', { state: 'finished', segments: [{ messageId: 's1', text: 'Two bookings.', final: true }] });+ expect(shape(buildTurns([user], { r1: streamed }))).toEqual(['user:m1', 'assistant:-:finished']);+ expect(shape(buildTurns([user], { r1: run('r1', { state: 'finished' }) }))).toEqual(['user:m1']);+ const quiet = run('r1', { state: 'finished', result: { noReply: true }, segments: [{ messageId: 's1', text: 'x', final: true }] });+ expect(shape(buildTurns([user], { r1: quiet }))).toEqual(['user:m1']);+ });++ it('puts a live run whose messages are out of view last, and drops an ended one', () => {+ const turns = buildTurns([message('m9', 'user')], {+ r1: run('r1', { state: 'running', createdAt: '2026-10-03T09:02:00Z' }),+ r0: run('r0', { state: 'queued', createdAt: '2026-10-03T09:01:00Z' }),+ r2: run('r2', { state: 'error', error: { message: 'Old', code: 'run_failed' } }),+ });+ expect(shape(turns)).toEqual(['user:m9', 'assistant:-:queued', 'assistant:-:running']);+ });+});diff --git a/client/src/features/chat/composer/Composer.tsx b/client/src/features/chat/composer/Composer.tsxnew file mode 100644index 00000000..d3c759f9--- /dev/null+++ b/client/src/features/chat/composer/Composer.tsx@@ -0,0 +1,84 @@+/**+ * The message box (design handoff chat, "Composer"): a text box that grows+ * with what is written, up to `--h-chat-composer-max`, then scrolls; and+ * Send. Enter sends, Shift+Enter starts a new line, and the Enter that+ * confirms an input method's composition never sends (lib/composerKeys).+ *+ * 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 } from 'lucide-react';+import type { KeyboardEvent, 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 { useComposerDraft, useComposerStore } from '../state/composerStore';++export interface ComposerProps {+ sessionId: string;+ name: string;+ /** The conversation has loaded, so a message can go after it. */+ ready: boolean;+ /** A message is on its way, or the employee is still answering one. */+ busy: boolean;+ onSend: () => void;+ compact: boolean;+ /** The text box, for the host's focus requests. */+ boxRef: RefObject<HTMLTextAreaElement | null>;+}++export function Composer({ sessionId, name, ready, busy, onSend, compact, boxRef }: ComposerProps) {+ const draft = useComposerDraft(sessionId);+ const setText = useComposerStore((state) => state.setText);+ useAutoGrow(boxRef, draft.text);+ const canSend = ready && !busy && draft.text.trim().length > 0;++ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (!isSendKey(event)) return;+ event.preventDefault();+ if (canSend) onSend();+ };++ const send = (+ <Button+ variant="invert"+ size="icon"+ disabled={!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')}+ >+ <ArrowUp aria-hidden strokeWidth={2.25} className={compact ? 'size-3.5' : 'size-4'} />+ </Button>+ );++ return (+ <div+ 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',+ )}+ >+ <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}…`}+ 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',+ )}+ />+ {compact ? send : <div className="flex items-center justify-end gap-1.5">{send}</div>}+ </div>+ );+}diff --git a/client/src/features/chat/data/conversation.ts b/client/src/features/chat/data/conversation.tsnew file mode 100644index 00000000..ff5bb36a--- /dev/null+++ b/client/src/features/chat/data/conversation.ts@@ -0,0 +1,40 @@+/**+ * A conversation as the chat draws it: the thread read, the session's runs+ * at their freshest, the turns (thread/model.ts), and the run holding the+ * lane. Subscribes the session's run events while mounted.+ */++import { useMemo } from 'react';+import type { RunSnapshot } from '@/lib/agui/reduceRun';+import { buildTurns, knownRuns, type ChatTurn } from '../thread/model';+import { laneRun, useChatRunSubscription, useRunsSubscribed, useSessionRuns, useThreadRunReconcile } from './runs';+import type { ChatMessage } from './schemas';+import { useChatThread, type ThreadScope } from './thread';++const NO_MESSAGES: readonly ChatMessage[] = [];++export interface Conversation {+ thread: ReturnType<typeof useChatThread>;+ turns: ChatTurn[];+ /** The live run the owner's last message started: while there is one, the+ * next message waits for it. */+ lane: RunSnapshot | null;+}++export function useConversation(sessionId: string, scope: ThreadScope): Conversation {+ useChatRunSubscription(sessionId);+ const thread = useChatThread(sessionId, scope);+ const messages = thread.data?.messages ?? NO_MESSAGES;+ const activeRuns = thread.data?.activeRuns;+ useThreadRunReconcile(sessionId, thread.data?.messages);+ const store = useSessionRuns(sessionId);+ const subscribed = useRunsSubscribed(sessionId);++ const runs = useMemo(+ () => knownRuns(sessionId, messages, store, subscribed, activeRuns),+ [sessionId, messages, store, subscribed, activeRuns],+ );+ const turns = useMemo(() => buildTurns(messages, runs), [messages, runs]);+ const lane = useMemo(() => laneRun(runs), [runs]);+ return { thread, turns, lane };+}diff --git a/client/src/features/chat/host.ts b/client/src/features/chat/host.tsnew file mode 100644index 00000000..121cc213--- /dev/null+++ b/client/src/features/chat/host.ts@@ -0,0 +1,69 @@+/**+ * What a host gives the chat (ChatPane): Home's employee page and Dev's+ * console Chat pane. The chat owns the thread, the turns and the message+ * box; the host owns everything around them (who answers, whether a message+ * can go now, what to act on, how to tell the owner something).+ */++import type { ReactNode } from 'react';+import type { ColorRole } from '@/components/catalog/presentation';+import type { ThreadScope } from './data/thread';++export type ChatHostKind = 'home' | 'dev';++/** Who answers in this chat. */+export interface ChatPersona {+ name: string;+ colorRole: ColorRole;+}++/**+ * The message box:+ * - `send`: a message goes to them now;+ * - `queue`: it waits until they are resumed;+ * - `closed`: nothing can read it, so there is no box (the host's notices+ * say why and offer what to do).+ */+export type ComposerMode = 'send' | 'queue' | 'closed';++export type NotifyTone = 'info' | 'success' | 'error';++export interface ChatHost {+ kind: ChatHostKind;+ /** The chat session: the workflow id, or `default` with none open. */+ sessionId: string;+ scope: ThreadScope;+ persona: ChatPersona;+ composer: ComposerMode;+ /** Above the box, while there is something to act on (Start, Apply, Help+ * in browser). */+ notices?: ReactNode;+ /** The first item of the thread's scroll area (Home: the orb). */+ top?: ReactNode;+ /** After the conversation, inside the scroll area (Home: the drafts+ * waiting for the owner). */+ afterThread?: ReactNode;+ /** In place of the conversation while it has no message. */+ emptyState?: ReactNode;+ /** One line under the box. */+ footnote?: ReactNode;+ /** A short message for the owner (Home: the pill toast; Dev: a toast). */+ notify: (message: string, tone: NotifyTone) => void;+ /** A message did not go: the server's code (`not_running`,+ * `run_in_progress`, `save_failed`, ...; `transport` when it may not have+ * reached the server). Its text is back in the box. Without this the+ * owner hears that it did not send. */+ onSendRefused?: (code: string) => void;+ /** Said on the working turn's status line (Home: the agent waiting to+ * retry after a failed attempt). */+ liveNote?: string | null;+ /** The thread left its top, or came back to it (Home's header border). */+ onScrolledChange?: (scrolled: boolean) => void;+ /** The console pane: denser type and spacing. */+ compact?: boolean;+}++/** What a host can ask of a mounted chat. */+export interface ChatPaneHandle {+ focusComposer: () => void;+}diff --git a/client/src/features/chat/index.ts b/client/src/features/chat/index.tsindex eda51bdc..5948921a 100644--- a/client/src/features/chat/index.ts+++ b/client/src/features/chat/index.ts@@ -4,6 +4,11 @@* inside.*/+export { ChatPane } from './ChatPane';+export type { ChatHost, ChatHostKind, ChatPaneHandle, ChatPersona, ComposerMode, NotifyTone } from './host';+export { useClearChat } from './data/send';+export { useLaneRun } from './data/runs';+export { useChatThread, type ThreadScope } from './data/thread';export { CHAT_MARKDOWN_COMPONENTS } from './markdown/components';export { SafeImage } from './markdown/SafeImage';export { isWorkspaceImage } from './markdown/workspaceImage';diff --git a/client/src/features/chat/markdown/ReplyMarkdown.tsx b/client/src/features/chat/markdown/ReplyMarkdown.tsxnew file mode 100644index 00000000..56acc385--- /dev/null+++ b/client/src/features/chat/markdown/ReplyMarkdown.tsx@@ -0,0 +1,69 @@+/**+ * An answer's text as markdown: paragraphs, lists, quotes, tables, and code+ * blocks in the theme's syntax colours (`.chat-markdown .token.*`). Its own+ * chunk: the thread loads it lazily, so the markdown stack stays out of the+ * first load. Links open in a new tab, and images from outside the workspace+ * wait for the owner (CHAT_MARKDOWN_COMPONENTS).+ */++import Prism from 'prismjs';+import 'prismjs/components/prism-bash';+import 'prismjs/components/prism-json';+import 'prismjs/components/prism-markdown';+import 'prismjs/components/prism-python';+import 'prismjs/components/prism-typescript';+import 'prismjs/components/prism-yaml';+import ReactMarkdown, { type Components } from 'react-markdown';+import remarkBreaks from 'remark-breaks';+import remarkGfm from 'remark-gfm';+import { cn } from '@/lib/utils';+import { CHAT_MARKDOWN_COMPONENTS } from './components';++const REMARK_PLUGINS = [remarkGfm, remarkBreaks];++/** The names a fence uses for a language Prism knows by another. */+const LANGUAGE_ALIASES: Record<string, string> = {+ js: 'javascript',+ jsx: 'javascript',+ ts: 'typescript',+ tsx: 'typescript',+ py: 'python',+ sh: 'bash',+ shell: 'bash',+ zsh: 'bash',+ yml: 'yaml',+ md: 'markdown',+ html: 'markup',+ xml: 'markup',+ svg: 'markup',+};++/** A fenced block in a language Prism knows gets its colours; inline code+ * (which never has a language class) and anything else stays as written.+ * Prism escapes the text it tokenizes, so its markup is safe to insert. */+const CodeBlock: Components['code'] = ({ node: _node, className, children, ...props }) => {+ const fence = /(?:^|\s)language-([\w-]+)/.exec(className ?? '')?.[1]?.toLowerCase();+ const language = fence ? (LANGUAGE_ALIASES[fence] ?? fence) : undefined;+ const grammar = language ? Prism.languages[language] : undefined;+ if (!language || !grammar || typeof children !== 'string') {+ return (+ <code className={className} {...props}>+ {children}+ </code>+ );+ }+ const html = Prism.highlight(children.replace(/\n$/, ''), grammar, language);+ return <code className={className} {...props} dangerouslySetInnerHTML={{ __html: html }} />;+};++const COMPONENTS: Components = { ...CHAT_MARKDOWN_COMPONENTS, code: CodeBlock };++export default function ReplyMarkdown({ text, className }: { text: string; className?: string }) {+ return (+ <div className={cn('chat-markdown min-w-0', className)}>+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={COMPONENTS}>+ {text}+ </ReactMarkdown>+ </div>+ );+}diff --git a/client/src/features/chat/thread/ChatAvatar.tsx b/client/src/features/chat/thread/ChatAvatar.tsxnew file mode 100644index 00000000..2caee4e6--- /dev/null+++ b/client/src/features/chat/thread/ChatAvatar.tsx@@ -0,0 +1,26 @@+/**+ * The answering employee's avatar beside their turns: their initial in+ * their role colour, and a spinning ring while they work (design handoff+ * chat, "Streaming": the live ring).+ */++import { AVATAR_CLASS, initialOf } from '@/components/catalog/presentation';+import { cn } from '@/lib/utils';+import type { ChatPersona } from '../host';++export function ChatAvatar({ persona, live = false, compact = false }: { persona: ChatPersona; live?: boolean; compact?: boolean }) {+ return (+ <span aria-hidden className={cn('relative shrink-0', compact ? 'size-6' : '-mt-0.5 size-7.5')}>+ {live && <span data-live-ring className="opencompany-live-ring absolute -inset-0.75 rounded-full" />}+ <span+ className={cn(+ 'absolute inset-0 grid place-items-center rounded-full border font-semibold',+ AVATAR_CLASS[persona.colorRole],+ compact ? 'text-2xs' : 'text-xs',+ )}+ >+ {initialOf(persona.name)}+ </span>+ </span>+ );+}diff --git a/client/src/features/chat/thread/ChatThread.tsx b/client/src/features/chat/thread/ChatThread.tsxnew file mode 100644index 00000000..f0ce7452--- /dev/null+++ b/client/src/features/chat/thread/ChatThread.tsx@@ -0,0 +1,226 @@+/**+ * The conversation's scroll area (design handoff chat, "Thread"): the+ * host's top slot (Home: the orb), the turns in a centred column, and what+ * the host shows after them.+ *+ * - **Sticks to the bottom.** While the newest turn is in view, anything+ * that grows the thread (a new turn, text arriving, a markdown chunk+ * loading) keeps it in view. Scrolled up, it stays put and a "Jump to+ * latest" button counts what arrived meanwhile; sending a message always+ * scrolls down to it. Opening the thread starts at the newest turn.+ * - New turns rise in (`chat-rise`), never the ones already there on open.+ * - The turns are a log, so a screen reader hears new ones.+ */++import { ArrowDown } from 'lucide-react';+import { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { animate } from '@/lib/motion';+import { prefersReducedMotion } from '@/lib/useReducedMotion';+import { cn } from '@/lib/utils';+import type { ChatPersona } from '../host';+import { AssistantTurn } from '../turns/AssistantTurn';+import { UserTurn } from '../turns/UserTurn';+import type { ChatTurn } from './model';++/** Closer to the bottom than this counts as at the bottom. */+const STICK_PX = 48;+/** Scrolled further than this, the host draws its header border. */+const SCROLLED_PX = 6;++function RestartDivider({ name }: { name: string }) {+ return (+ <div className="flex items-center gap-3 text-xs text-fg-muted">+ <span aria-hidden className="h-px flex-1 bg-border-default" />+ <span className="text-center">{name} restarted — they start fresh from here</span>+ <span aria-hidden className="h-px flex-1 bg-border-default" />+ </div>+ );+}++export interface ChatThreadProps {+ persona: ChatPersona;+ turns: readonly ChatTurn[];+ loading: boolean;+ error: boolean;+ onRetry: () => void;+ top?: ReactNode;+ afterThread?: ReactNode;+ emptyState?: ReactNode;+ liveNote?: string | null;+ compact: boolean;+ onScrolledChange?: (scrolled: boolean) => void;+}++export function ChatThread({+ persona,+ turns,+ loading,+ error,+ onRetry,+ top,+ afterThread,+ emptyState,+ liveNote,+ compact,+ onScrolledChange,+}: ChatThreadProps) {+ const scrollRef = useRef<HTMLDivElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);+ const atBottom = useRef(true);+ const scrolled = useRef(false);+ const [unread, setUnread] = useState(0);+ const [away, setAway] = useState(false);++ const toBottom = useCallback((smooth: boolean) => {+ const scroller = scrollRef.current;+ if (!scroller) return;+ atBottom.current = true;+ setAway(false);+ setUnread(0);+ if (smooth && !prefersReducedMotion()) scroller.scrollTo?.({ top: scroller.scrollHeight, behavior: 'smooth' });+ else scroller.scrollTop = scroller.scrollHeight;+ }, []);++ // Only scrolling up leaves the bottom: the positions a smooth scroll down+ // passes through on its way there do not.+ const lastTop = useRef(0);+ const onScroll = () => {+ const scroller = scrollRef.current;+ if (!scroller) return;+ const top = scroller.scrollTop;+ if (scroller.scrollHeight - top - scroller.clientHeight <= STICK_PX) {+ atBottom.current = true;+ setAway(false);+ setUnread(0);+ } else if (top < lastTop.current) {+ atBottom.current = false;+ setAway(true);+ }+ lastTop.current = top;+ const isScrolled = top > SCROLLED_PX;+ if (isScrolled !== scrolled.current) {+ scrolled.current = isScrolled;+ onScrolledChange?.(isScrolled);+ }+ };++ // Whatever grows the thread keeps the newest turn in view while it is.+ useLayoutEffect(() => {+ const content = contentRef.current;+ const scroller = scrollRef.current;+ if (!content || !scroller || typeof ResizeObserver === 'undefined') return;+ const observer = new ResizeObserver(() => {+ if (atBottom.current) scroller.scrollTop = scroller.scrollHeight;+ });+ observer.observe(content);+ return () => observer.disconnect();+ }, []);++ // Turns that arrive: rise in; the owner's own message scrolls down to it;+ // anything else counts as unread while the thread is scrolled up.+ const shownKeys = useRef<Set<string> | null>(null);+ useLayoutEffect(() => {+ if (loading) return;+ const keys = new Set(turns.map((turn) => turn.key));+ const previous = shownKeys.current;+ shownKeys.current = keys;+ if (previous === null) {+ toBottom(false);+ return;+ }+ const added = turns.filter((turn) => !previous.has(turn.key) && turn.kind !== 'divider');+ if (added.length === 0) return;+ const elements = new Map(+ Array.from(contentRef.current?.querySelectorAll<HTMLElement>('[data-turn-key]') ?? []).map((element) => [element.dataset.turnKey, element]),+ );+ added.forEach((turn, index) => {+ animate(elements.get(turn.key), [{ opacity: 0, transform: 'translateY(12px)' }, { opacity: 1, transform: 'none' }], {+ duration: 'chat-rise',+ easing: 'spring',+ delay: 60 + index * 70,+ });+ });+ if (added.some((turn) => turn.kind === 'user')) toBottom(true);+ else if (!atBottom.current) setUnread((count) => count + added.length);+ }, [turns, loading, toBottom]);++ const now = new Date();+ const lastTurn = turns.at(-1)?.key;++ return (+ <div className="relative flex min-h-0 flex-1 flex-col">+ <div ref={scrollRef} onScroll={onScroll} data-scrollable className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">+ <div+ ref={contentRef}+ className={cn(+ 'mx-auto flex w-full flex-col',+ compact ? 'gap-4 px-3 py-3' : 'max-w-(--w-chat-column) gap-7 px-6 pt-7 pb-8',+ )}+ >+ {top}+ {loading && (+ <div aria-busy className="flex flex-col gap-4">+ <Skeleton className="h-10 w-3/5 self-end rounded-draft" />+ <Skeleton className="h-16 w-4/5 rounded-card" />+ </div>+ )}+ {error && (+ <div className="flex flex-col items-center gap-2 py-6 text-center">+ <p className="m-0 text-sm text-fg-default">Couldn’t load the conversation.</p>+ <Button variant="quiet" onClick={onRetry} className="border-border-default text-fg-default">+ Try again+ </Button>+ </div>+ )}+ {!loading && !error && turns.length === 0 && emptyState}+ <div+ role="log"+ aria-live="polite"+ aria-label={`Conversation with ${persona.name}`}+ className={cn('flex flex-col', compact ? 'gap-4' : 'gap-7', turns.length === 0 && 'hidden')}+ >+ {turns.map((turn) => {+ if (turn.kind === 'divider') return <RestartDivider key={turn.key} name={persona.name} />;+ const latest = turn.key === lastTurn;+ return (+ <div key={turn.key} data-turn-key={turn.key}>+ {turn.kind === 'user' ? (+ <UserTurn message={turn.message} now={now} latest={latest} compact={compact} />+ ) : (+ <AssistantTurn+ message={turn.message}+ run={turn.run}+ persona={persona}+ now={now}+ latest={latest}+ compact={compact}+ liveNote={liveNote}+ />+ )}+ </div>+ );+ })}+ </div>+ {afterThread}+ </div>+ </div>+ {!compact && <span aria-hidden className="pointer-events-none absolute inset-x-0 bottom-0 h-7 bg-linear-to-b from-transparent to-bg-app" />}+ <Button+ variant="quiet"+ onClick={() => toBottom(true)}+ aria-label={unread > 0 ? `Jump to latest, ${unread} new` : 'Jump to latest'}+ tabIndex={away ? 0 : -1}+ aria-hidden={!away}+ className={cn(+ 'absolute bottom-3 left-1/2 z-10 h-8.5 min-w-8.5 -translate-x-1/2 gap-1.5 rounded-pill border-border-default bg-bg-elevated px-2.5 text-xs text-fg-default shadow-card-hover transition-[opacity,translate] duration-(--dur-slow)',+ away ? 'translate-y-0 opacity-100' : 'pointer-events-none translate-y-2 opacity-0',+ )}+ >+ <ArrowDown aria-hidden className="size-3.75" strokeWidth={2.2} />+ {unread > 0 && <span>{unread} new</span>}+ </Button>+ </div>+ );+}diff --git a/client/src/features/chat/thread/model.ts b/client/src/features/chat/thread/model.tsnew file mode 100644index 00000000..fa38481b--- /dev/null+++ b/client/src/features/chat/thread/model.ts@@ -0,0 +1,155 @@+/**+ * The rows a chat thread draws, from the saved messages and the session's+ * runs (docs-internal/chat_protocol.md). Pure, so every rule here is tested+ * without rendering.+ *+ * - **Runs.** `knownRuns` picks, per run, the freshest reading: the run store+ * (live events) over what a message said when the thread was read. Until+ * the session's subscription has answered, the thread's own `active_runs`+ * stand in for the store; after that the store alone says which runs are+ * live, and a message that still calls its run live is not believed (the+ * run ended before the subscription; `useThreadRunReconcile` reads it).+ * - **Turns.** One per message, in order, with a divider wherever the+ * employee restarted between two messages (their generation, `runKey`,+ * changed). A run that is going, failed or was stopped shows on its last+ * answer, or, before it has answered, on a turn of its own right after its+ * last message (a live run whose messages are out of view goes last).+ * - **Keys.** A message sent from this tab keeps its key when the saved row+ * replaces it (both carry its `clientMessageId`), and a run's first answer+ * has the key the run's own turn had, so the text it streamed and the+ * saved reply are one element.+ */++import { emptyRun, isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';+import type { ChatMessage, MessageRun } from '../data/schemas';++export type ChatTurn =+ | { kind: 'divider'; key: string }+ | { kind: 'user'; key: string; message: ChatMessage }+ | {+ kind: 'assistant';+ key: string;+ /** The saved answer; null while the run has not posted one. */+ message: ChatMessage | null;+ /** The run whose state this turn shows (working, failed, stopped):+ * set on the run's last turn only. */+ run: RunSnapshot | null;+ };++/** Run failures that are not news: the conversation itself went away. */+const SILENT_FAILURES: ReadonlySet<string> = new Set(['reset', 'cleared']);+/** Failures that only say no answer came; an answer that landed after all+ * makes them wrong. */+const NO_ANSWER_FAILURES: ReadonlySet<string> = new Set(['not_delivered', 'timed_out', 'interrupted']);++function fromMessage(message: ChatMessage, run: MessageRun, sessionId: string): RunSnapshot {+ return {+ ...emptyRun(run.runId, sessionId),+ state: run.state,+ userMessageId: message.role === 'user' ? message.id : null,+ outcome: run.outcome === 'success' || run.outcome === 'interrupt' || run.outcome === 'stopped'+ ? { type: run.outcome, interrupts: [] }+ : null,+ error: run.error,+ };+}++/**+ * Every run the thread refers to, by id, at its freshest.+ * `synced`: the session's subscription has answered, so `store` knows every+ * live run. `threadActive`: the live runs the thread read reported.+ */+export function knownRuns(+ sessionId: string,+ messages: readonly ChatMessage[],+ store: Readonly<Record<string, RunSnapshot>>,+ synced: boolean,+ threadActive: readonly RunSnapshot[] = [],+): Record<string, RunSnapshot> {+ const runs: Record<string, RunSnapshot> = {};+ if (!synced) for (const run of threadActive) runs[run.runId] = run;+ for (const message of messages) {+ const run = message.run;+ if (!run || runs[run.runId] || store[run.runId]) continue;+ // Live by the thread's reading, but the subscription does not have it:+ // it ended in between, and how is not known yet.+ if (synced && isLiveRun(run)) continue;+ runs[run.runId] = fromMessage(message, run, sessionId);+ }+ return { ...runs, ...store };+}++/** Whether a run's state is worth a line in the thread. */+function shows(run: RunSnapshot, answered: boolean): boolean {+ if (isLiveRun(run)) return true;+ if (run.state === 'error') {+ const code = run.error?.code ?? '';+ return !SILENT_FAILURES.has(code) && !(answered && NO_ANSWER_FAILURES.has(code));+ }+ if (run.state === 'stopped') return true;+ // Finished: only while its answer is still on the way to the thread.+ if (answered || run.result.noReply) return false;+ return run.segments.some((segment) => segment.final !== false && segment.text.length > 0);+}++function runOrder(run: RunSnapshot): string {+ return run.createdAt ?? run.startedAt ?? '';+}++export function buildTurns(messages: readonly ChatMessage[], runs: Readonly<Record<string, RunSnapshot>>): ChatTurn[] {+ // A message sent from this tab, once its saved row is in the thread.+ const saved = new Set(messages.flatMap((message) => (!message.pending && message.clientMessageId ? [message.clientMessageId] : [])));+ const visible = messages.filter((message) => !(message.pending && message.clientMessageId && saved.has(message.clientMessageId)));++ const lastIndex = new Map<string, number>();+ const lastAnswer = new Map<string, number>();+ visible.forEach((message, index) => {+ if (!message.runId) return;+ lastIndex.set(message.runId, index);+ if (message.role === 'assistant') lastAnswer.set(message.runId, index);+ });++ const showing = new Set(+ Object.values(runs).flatMap((run) => (shows(run, lastAnswer.has(run.runId)) ? [run.runId] : [])),+ );+ const placed = new Set<string>();+ const keyed = new Set<string>();+ const turns: ChatTurn[] = [];+ let generation: string | null = null;++ visible.forEach((message, index) => {+ if (generation && message.runKey && message.runKey !== generation) {+ turns.push({ kind: 'divider', key: `divider:${message.id}` });+ }+ if (message.runKey) generation = message.runKey;+ const runId = message.runId;++ if (message.role === 'user') {+ turns.push({ kind: 'user', key: `user:${message.clientMessageId ?? message.id}`, message });+ if (runId && showing.has(runId) && !lastAnswer.has(runId) && lastIndex.get(runId) === index) {+ turns.push({ kind: 'assistant', key: `run:${runId}`, message: null, run: runs[runId] });+ placed.add(runId);+ keyed.add(runId);+ }+ return;+ }++ // A run's first answer takes the key its own turn had.+ let key = `reply:${message.id}`;+ if (runId && !keyed.has(runId)) {+ key = `run:${runId}`;+ keyed.add(runId);+ }+ const last = Boolean(runId && lastAnswer.get(runId) === index);+ const run = runId && last && showing.has(runId) ? runs[runId] : null;+ if (run) placed.add(run.runId);+ turns.push({ kind: 'assistant', key, message, run });+ });++ const unplaced = [...showing]+ .map((runId) => runs[runId])+ .filter((run) => !placed.has(run.runId) && isLiveRun(run))+ .sort((a, b) => runOrder(a).localeCompare(runOrder(b)));+ for (const run of unplaced) turns.push({ kind: 'assistant', key: `run:${run.runId}`, message: null, run });+ return turns;+}diff --git a/client/src/features/chat/thread/timeLabel.ts b/client/src/features/chat/thread/timeLabel.tsnew file mode 100644index 00000000..4e46ad88--- /dev/null+++ b/client/src/features/chat/thread/timeLabel.ts@@ -0,0 +1,25 @@+/**+ * When a message was written, the way a person says it: the time today,+ * "Yesterday, 9:41 AM", the weekday within a week, else the date. Empty when+ * the timestamp cannot be read.+ */++const DAY_MS = 86_400_000;++function startOfDay(date: Date): number {+ return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();+}++export function timeLabel(timestamp: string | null, now: Date = new Date()): string {+ if (!timestamp) return '';+ const date = new Date(timestamp);+ if (Number.isNaN(date.getTime())) return '';+ const time = date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });+ // Rounded: a day with a clock change is 23 or 25 hours long.+ const days = Math.round((startOfDay(now) - startOfDay(date)) / DAY_MS);+ if (days <= 0) return time;+ if (days === 1) return `Yesterday, ${time}`;+ if (days < 7) return `${date.toLocaleDateString(undefined, { weekday: 'long' })}, ${time}`;+ const year = date.getFullYear() === now.getFullYear() ? undefined : 'numeric';+ return `${date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year })}, ${time}`;+}diff --git a/client/src/features/chat/turns/AssistantTurn.tsx b/client/src/features/chat/turns/AssistantTurn.tsxnew file mode 100644index 00000000..0e826ec0--- /dev/null+++ b/client/src/features/chat/turns/AssistantTurn.tsx@@ -0,0 +1,112 @@+/**+ * The employee's side of a turn (design handoff chat, "Assistant row"):+ * their avatar on the left and, with no bubble, what they said in markdown.+ * While their run works the avatar spins its ring and skeleton lines stand+ * in for text that has not come yet, with a status line under; a run that+ * waits for Resume, failed or was stopped says so where its answer would be.+ *+ * `chat-msg chat-msg-bot` (on the text only) is the theme hook the stylized+ * themes paint as a bubble.+ */++import { CircleAlert, Pause, Square } from 'lucide-react';+import { Suspense, lazy, type ReactNode } from 'react';+import { isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';+import { cn } from '@/lib/utils';+import type { ChatMessage } from '../data/schemas';+import type { ChatPersona } from '../host';+import { ChatAvatar } from '../thread/ChatAvatar';+import { timeLabel } from '../thread/timeLabel';+import { failureLines, liveLabel, streamedText } from './runCopy';+import { StatusLine } from './StatusLine';+import { TurnMeta } from './TurnMeta';++// Its own chunk: the markdown stack stays out of the first load.+const ReplyMarkdown = lazy(() => import('../markdown/ReplyMarkdown'));++function Thinking() {+ return (+ <div aria-hidden data-thinking className="flex flex-col gap-2.25 pt-0.5">+ <span className="opencompany-shimmer h-3 w-[78%] rounded-md" />+ <span className="opencompany-shimmer h-3 w-[92%] rounded-md [animation-delay:120ms]" />+ <span className="opencompany-shimmer h-3 w-[54%] rounded-md [animation-delay:240ms]" />+ </div>+ );+}++function Note({ icon, tone = 'muted', children }: { icon: 'alert' | 'pause' | 'stop'; tone?: 'muted' | 'alert'; children: ReactNode }) {+ const Icon = icon === 'alert' ? CircleAlert : icon === 'pause' ? Pause : Square;+ return (+ <div className="flex items-start gap-2 text-sm">+ <Icon aria-hidden className={cn('mt-0.75 size-3.5 shrink-0', tone === 'alert' ? 'text-action-stop-ink' : 'text-fg-faint')} />+ <div className="flex min-w-0 flex-col gap-0.5 text-fg-muted">{children}</div>+ </div>+ );+}++export function AssistantTurn({+ message,+ run,+ persona,+ now,+ latest,+ compact,+ liveNote,+}: {+ message: ChatMessage | null;+ run: RunSnapshot | null;+ persona: ChatPersona;+ now: Date;+ latest: boolean;+ compact: boolean;+ /** Said on the status line while the run works (an automatic retry). */+ liveNote?: string | null;+}) {+ const queued = run?.state === 'queued';+ const live = Boolean(run && isLiveRun(run) && !queued);+ const text = message ? message.text : streamedText(run);+ const failure = run?.state === 'error' ? failureLines(run.error, persona.name) : null;++ return (+ <div+ data-turn="assistant"+ data-message={message?.id}+ data-run={run?.runId}+ aria-busy={live || undefined}+ className={cn('chat-turn-bot group/turn flex items-start', compact ? 'gap-2.5' : 'gap-3.5')}+ >+ <ChatAvatar persona={persona} live={live} compact={compact} />+ <div className="flex min-w-0 flex-1 flex-col gap-2.5">+ {live && !text && <Thinking />}+ {text && (+ <div className={cn('chat-msg chat-msg-bot text-fg-default wrap-anywhere', compact ? 'leading-normal' : 'text-md leading-relaxed')}>+ <Suspense fallback={<p className="m-0 whitespace-pre-wrap">{text}</p>}>+ <ReplyMarkdown text={text} />+ </Suspense>+ </div>+ )}+ {live && run && (+ <StatusLine label={liveLabel(run, Boolean(text))} note={liveNote} compact={compact} />+ )}+ {queued && (+ <Note icon="pause">+ <p className="m-0">Waiting for you to resume {persona.name}.</p>+ </Note>+ )}+ {run?.state === 'stopped' && (+ <Note icon="stop">+ <p className="m-0">You stopped this reply.</p>+ </Note>+ )}+ {failure && (+ <Note icon="alert" tone="alert">+ <p className="m-0 text-fg-default">{failure.headline}</p>+ {failure.detail && <p className="m-0">{failure.detail}</p>}+ {run?.error?.hint && <p className="m-0">{run.error.hint}</p>}+ </Note>+ )}+ {message && <TurnMeta shown={latest}>{timeLabel(message.timestamp, now)}</TurnMeta>}+ </div>+ </div>+ );+}diff --git a/client/src/features/chat/turns/StatusLine.tsx b/client/src/features/chat/turns/StatusLine.tsxnew file mode 100644index 00000000..bd7fe835--- /dev/null+++ b/client/src/features/chat/turns/StatusLine.tsx@@ -0,0 +1,21 @@+/**+ * What a working employee is doing, under their turn (design handoff chat,+ * "Streaming": three dots and a label). A status region, so a screen reader+ * hears it change.+ */++import { cn } from '@/lib/utils';++export function StatusLine({ label, note, compact = false }: { label: string; note?: string | null; compact?: boolean }) {+ return (+ <div role="status" className={cn('flex min-w-0 items-center gap-2 font-mono text-xs text-fg-faint', compact && 'text-2xs')}>+ <span aria-hidden className="opencompany-dots flex shrink-0 gap-0.75">+ <span className="size-1 rounded-full bg-action-tools-ink" />+ <span className="size-1 rounded-full bg-action-tools-ink" />+ <span className="size-1 rounded-full bg-action-tools-ink" />+ </span>+ <span className="shrink-0 text-fg-muted">{label}</span>+ {note && <span className="min-w-0 truncate font-body">{note}</span>}+ </div>+ );+}diff --git a/client/src/features/chat/turns/TurnMeta.tsx b/client/src/features/chat/turns/TurnMeta.tsxnew file mode 100644index 00000000..2ea113be--- /dev/null+++ b/client/src/features/chat/turns/TurnMeta.tsx@@ -0,0 +1,24 @@+/**+ * The line under a turn: when it was written. Faint until the turn is+ * hovered or focused (design handoff chat: the hover bar); always shown on+ * touch screens, on the newest turn, and while it says something that+ * matters now ("Sending…").+ */++import type { ReactNode } from 'react';+import { cn } from '@/lib/utils';++export function TurnMeta({ children, shown = false, className }: { children: ReactNode; shown?: boolean; className?: string }) {+ if (!children) return null;+ return (+ <div+ className={cn(+ 'flex h-6 items-center gap-1 px-1.5 text-xs text-fg-faint transition-opacity duration-(--dur-default)',+ shown ? 'opacity-100' : 'opacity-0 group-focus-within/turn:opacity-100 group-hover/turn:opacity-100 pointer-coarse:opacity-100',+ className,+ )}+ >+ {children}+ </div>+ );+}diff --git a/client/src/features/chat/turns/UserTurn.tsx b/client/src/features/chat/turns/UserTurn.tsxnew file mode 100644index 00000000..a5e6239c--- /dev/null+++ b/client/src/features/chat/turns/UserTurn.tsx@@ -0,0 +1,26 @@+/**+ * The owner's message: a bubble on the right (design handoff chat,+ * "Thread"), with when they sent it under it. `chat-msg chat-msg-user` is+ * the theme hook the stylized themes paint.+ */++import { cn } from '@/lib/utils';+import type { ChatMessage } from '../data/schemas';+import { timeLabel } from '../thread/timeLabel';+import { TurnMeta } from './TurnMeta';++export function UserTurn({ message, now, latest, compact }: { message: ChatMessage; now: Date; latest: boolean; compact: boolean }) {+ return (+ <div data-turn="user" data-message={message.id} className="chat-turn-user group/turn flex flex-col items-end gap-1.5">+ <p+ className={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',+ compact ? 'px-3 py-2 leading-normal' : 'px-4 py-2.5 text-md leading-normal',+ )}+ >+ {message.text}+ </p>+ <TurnMeta shown={latest || message.pending}>{message.pending ? 'Sending…' : timeLabel(message.timestamp, now)}</TurnMeta>+ </div>+ );+}diff --git a/client/src/features/chat/turns/runCopy.ts b/client/src/features/chat/turns/runCopy.tsnew file mode 100644index 00000000..32f79db4--- /dev/null+++ b/client/src/features/chat/turns/runCopy.ts@@ -0,0 +1,41 @@+/**+ * What a turn says about its run, kept apart from the component so the+ * component file exports components only (react-refresh) and the wording is+ * testable on its own.+ */++import type { RunError } from '@/lib/agui/events';+import type { RunSnapshot } from '@/lib/agui/reduceRun';++/** What a run that has not answered streamed so far: its reply text, not+ * the narration beside its tool calls. */+export function streamedText(run: RunSnapshot | null): string {+ if (!run) return '';+ return run.segments+ .filter((segment) => segment.final !== false)+ .map((segment) => segment.text)+ .join('\n\n')+ .trim();+}++/** A failed run in the owner's words: the server's codes for a message+ * nobody answered get a sentence naming the employee; any other failure+ * keeps the server's own message as the detail. */+export function failureLines(error: RunError | null, name: string): { headline: string; detail: string | null } {+ switch (error?.code) {+ case 'not_delivered':+ return { headline: `${name} didn’t pick up this message.`, detail: null };+ case 'timed_out':+ return { headline: `${name} took too long to answer.`, detail: null };+ case 'interrupted':+ return { headline: `${name} stopped before answering.`, detail: null };+ default:+ return { headline: `${name} couldn’t answer.`, detail: error?.message || null };+ }+}++/** The status line's label while a run works. */+export function liveLabel(run: RunSnapshot, hasText: boolean): string {+ if (run.state === 'stopping') return 'Stopping…';+ return hasText ? 'Writing…' : 'Working…';+}diff --git a/client/src/features/home/HomeShell.tsx b/client/src/features/home/HomeShell.tsxindex cd48fe3c..51797dce 100644--- a/client/src/features/home/HomeShell.tsx+++ b/client/src/features/home/HomeShell.tsx@@ -10,16 +10,18 @@* shared credentials dialog. Switching views scrolls to the top and plays* the view swap.*- * The scrolling area is a column the view fills at least, so an employee's- * page can pin its message box to the bottom however short the conversation.+ * Hiring scrolls as one page. An employee's page is the chat, which scrolls+ * its conversation itself above its message box, so it gets a column that+ * does not scroll; it reports when its conversation has left the top, for+ * the header's border.*/import { useLayoutEffect, useRef, useState } from 'react';import { animate } from '@/lib/motion';-import { cn } from '@/lib/utils';import { useShellDialogsStore, type CredentialsIntent } from '@/stores/shellDialogsStore';import { useApprovalLifecycle } from './approvals/data';import { useEmployeeLifecycle, useEmployeesQuery } from './data/employees';+import type { EmployeeSummary } from './data/schemas';import { EmployeeView } from './employee/EmployeeView';import { HomeHeader } from './header/HomeHeader';import { HireView } from './hire/HireView';@@ -33,32 +35,20 @@ import { WorkspaceDock } from './workspace/WorkspaceDock';/** Scrolled further than this, the header draws its bottom border. */const HEADER_BORDER_AFTER_PX = 6;-function useViewTitle(): string {+/** The employee on screen, from the team list (null while hiring, or+ * until the list has them). */+function useViewEmployee(): EmployeeSummary | null {const view = useHomeStore((s) => s.view);const { data: employees } = useEmployeesQuery();- if (view.kind !== 'employee') return 'New employee';- return employees?.find((employee) => employee.workflow_id === view.workflowId)?.name ?? 'Employee';-}--/** Whether the employee on screen asks before sending anything. */-function AsksFirstNote({ workflowId }: { workflowId: string }) {- const { data: employees } = useEmployeesQuery();- const employee = employees?.find((item) => item.workflow_id === workflowId);- if (!employee) return null;- return (- <p className="m-0 pt-2 text-center text-xs text-fg-muted">- {employee.asks_first- ? `${employee.name} asks before sending anything on your behalf.`- : `${employee.name} doesn’t ask before sending anything on your behalf.`}- </p>- );+ if (view.kind !== 'employee') return null;+ return employees?.find((employee) => employee.workflow_id === view.workflowId) ?? null;}export default function HomeShell() {useEmployeeLifecycle();useApprovalLifecycle();const view = useHomeStore((s) => s.view);- const title = useViewTitle();+ const employee = useViewEmployee();const openCredentials = useShellDialogsStore((s) => s.openCredentials);const openConnect = (providerId: string, intent: CredentialsIntent = 'connect') => {spikeOrb(SPIKE.connect);@@ -90,29 +80,30 @@ export default function HomeShell() {<HomeSidebar /><main className="relative flex min-w-0 flex-1 flex-col"><OrbStage />- <HomeHeader title={title} scrolled={scrolled} />- <div- ref={scrollRef}- onScroll={(event) => setScrolled(event.currentTarget.scrollTop > HEADER_BORDER_AFTER_PX)}- className="relative z-10 flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto"- >- {/* An employee's page ends at its pinned message box and one line under it. */}+ <HomeHeader+ title={view.kind === 'employee' ? employee?.name ?? 'Employee' : 'New employee'}+ employee={employee}+ scrolled={scrolled}+ />+ {view.kind === 'employee' ? (+ <div className="relative z-10 flex min-h-0 flex-1 flex-col">+ <div ref={viewRef} key={viewKey} className="flex min-h-0 w-full flex-1 flex-col">+ <EmployeeView workflowId={view.workflowId} onConnect={openConnect} onScrolledChange={setScrolled} />+ </div>+ </div>+ ) : (<div- className={cn(- 'mx-auto flex w-full max-w-(--w-home-content) flex-1 flex-col items-center px-6 pt-2',- view.kind === 'employee' ? 'pb-3' : 'pb-10',- )}+ ref={scrollRef}+ onScroll={(event) => setScrolled(event.currentTarget.scrollTop > HEADER_BORDER_AFTER_PX)}+ className="relative z-10 flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto">- <div ref={viewRef} key={viewKey} className="flex w-full flex-1 flex-col items-center">- {view.kind === 'employee' ? (- <EmployeeView workflowId={view.workflowId} onConnect={openConnect} />- ) : (+ <div className="mx-auto flex w-full max-w-(--w-home-content) flex-1 flex-col items-center px-6 pt-2 pb-10">+ <div ref={viewRef} key={viewKey} className="flex w-full flex-1 flex-col items-center"><HireView onConnect={openConnect} />- )}+ </div></div>- {view.kind === 'employee' && <AsksFirstNote workflowId={view.workflowId} />}</div>- </div>+ )}</main><WorkspaceDock onConnect={openConnect} /><HomeSettings onConnect={openConnect} />diff --git a/client/src/features/home/__tests__/composer.test.tsx b/client/src/features/home/__tests__/composer.test.tsxindex e44c5919..5c662fba 100644--- a/client/src/features/home/__tests__/composer.test.tsx+++ b/client/src/features/home/__tests__/composer.test.tsx@@ -10,7 +10,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { fireEvent, render, screen } from '@testing-library/react';import { ThemeProvider } from '@/contexts/ThemeContext';import { Composer, type ComposerProps } from '../hire/Composer';-import { createLabel, isSendKey } from '../hire/composerKeys';+import { createLabel } from '../hire/composerKeys';import { greetingFor } from '../hire/greeting';import { HireNotice } from '../hire/HireNotice';import { TemplateChips } from '../hire/TemplateChips';@@ -37,20 +37,6 @@ function setup(overrides: Partial<ComposerProps> = {}) {return { props, box: screen.getByRole('textbox') };}-describe('isSendKey', () => {- it('sends on a plain Enter only', () => {- expect(isSendKey({ key: 'Enter', shiftKey: false })).toBe(true);- expect(isSendKey({ key: 'Enter', shiftKey: true })).toBe(false);- expect(isSendKey({ key: 'a', shiftKey: false })).toBe(false);- });-- it('never sends the Enter that confirms an IME composition', () => {- expect(isSendKey({ key: 'Enter', shiftKey: false, nativeEvent: { isComposing: true } })).toBe(false);- expect(isSendKey({ key: 'Enter', shiftKey: false, keyCode: 229 })).toBe(false);- expect(isSendKey({ key: 'Enter', shiftKey: false, nativeEvent: { keyCode: 229 } })).toBe(false);- });-});-describe('Composer', () => {it('sends with Enter and keeps Shift+Enter for a new line', () => {const { props, box } = setup();diff --git a/client/src/features/home/__tests__/employeeChat.test.tsx b/client/src/features/home/__tests__/employeeChat.test.tsxnew file mode 100644index 00000000..8d2d4479--- /dev/null+++ b/client/src/features/home/__tests__/employeeChat.test.tsx@@ -0,0 +1,341 @@+/**+ * Talking to an employee on their page (EmployeeChat over the shared chat):+ * the thread (every generation, with a divider at each restart), sending+ * (taken back with the owner's words when the server refuses it), the+ * employee working until their run ends, a retry on the status line, one+ * message waiting while paused, the box giving way to Start, the footnote+ * on asking first, Turn on Talk, and Apply.+ */++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';++const sendRequest = vi.fn();++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));++vi.mock('../../../app/useShellActions', () => ({ enterDev: vi.fn() }));+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));++import { WORKFLOW_CONTROL_REQUEST_TIMEOUT, normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';+import { useComposerStore } from '@/features/chat/state/composerStore';+import { resetChatRunStore, useChatRunStore } from '@/stores/chatRunStore';+import { useNodeStatusStore } from '@/stores/nodeStatusStore';+import { EMPLOYEES_QUERY_KEY, employeeDetailKey, removeEmployee, useEmployeesQuery } from '../data/employees';+import { presentEmployee } from '../data/presentation';+import { parseEmployee, type EmployeeSummary } from '../data/schemas';+import { EmployeeChat } from '../employee/EmployeeChat';+import type { EmployeeControl } from '../employee/useEmployeeControl';+import { pillToast } from '../ui/pillToast';+// Loaded up front so the turns' lazy markdown resolves from the module cache.+import '@/features/chat/markdown/ReplyMarkdown';++const AGENT = 'w1:talk';+type Wire = Record<string, unknown>;++function employee(patch: Record<string, unknown> = {}, state = 'running'): EmployeeSummary {+ return parseEmployee({+ workflow_id: 'w1',+ name: 'Maya',+ role: 'Receptionist',+ status: state === 'running' ? 'working' : state === 'paused' ? 'paused' : 'ready',+ talk: { state: 'on', agent_node_id: AGENT },+ control: normalizeWorkflowControlStatus({ generation: 1, revision: 4, state }, 'w1'),+ ...patch,+ })!;+}++function controlFor(summary: EmployeeSummary): EmployeeControl {+ const view = presentEmployee(summary);+ return { view, label: view.primary.kind === 'resume' ? 'Resume' : 'Start', busy: false, act: vi.fn() };+}++let server: { messages: Wire[]; send: Wire };+let client: QueryClient;++function TeamSubscription() {+ useEmployeesQuery();+ return null;+}++function renderChat(summary: EmployeeSummary) {+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ client.setQueryData(EMPLOYEES_QUERY_KEY, [summary]);+ client.setQueryData(employeeDetailKey(summary.workflow_id), summary);+ const view = (next: EmployeeSummary) => (+ <QueryClientProvider client={client}>+ <TeamSubscription />+ <EmployeeChat employee={next} control={controlFor(next)} />+ </QueryClientProvider>+ );+ const utils = render(view(summary));+ return { rerender: (next: EmployeeSummary) => utils.rerender(view(next)) };+}++function row(id: number, role: 'user' | 'assistant', message: string, patch: Wire = {}): Wire {+ return { id, role, message, timestamp: new Date(2026, 8, 28, 9, id).toISOString(), run_key: 'g1', ...patch };+}++function frame(seq: number, suffix: string, data: Wire = {}, runId = 'r1') {+ return {+ specversion: '1.0',+ id: `${runId}:${seq}`,+ source: 'opencompany://services/chat',+ type: `com.opencompany.chat.run.${suffix}`,+ subject: runId,+ data: { workflow_id: 'w1', session_id: 'w1', run_id: runId, seq, hub_epoch: 'e1', ...data },+ };+}++function runEvents(...frames: unknown[]) {+ act(() => {+ const store = useChatRunStore.getState();+ for (const item of frames) store.receive(item);+ store.flush();+ });+}++async function write(text: string) {+ fireEvent.change(await screen.findByRole('textbox', { name: 'Message Maya' }), { target: { value: text } });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled());+}++beforeEach(() => {+ resetChatRunStore();+ useComposerStore.setState({ drafts: {} });+ useNodeStatusStore.setState({ allStatuses: {} });+ vi.mocked(pillToast).mockClear();+ server = { messages: [], send: { success: true, message_id: 'm_new', run_id: 'r1', delivery: 'now' } };+ sendRequest.mockReset().mockImplementation(async (type: string, data: Wire) => {+ if (type === 'chat_subscribe') return { success: true, hub_epoch: 'e1', active_runs: [] };+ if (type === 'get_chat_messages') return { success: true, messages: server.messages };+ if (type === 'send_chat_message') {+ if (server.send.success !== false) {+ server.messages = [...server.messages, row(server.messages.length + 1, 'user', String(data.message), { run_id: server.send.run_id })];+ }+ return server.send;+ }+ return { success: true };+ });+});++describe('the thread', () => {+ it('reads every generation and marks the restart', async () => {+ server.messages = [+ row(1, 'user', 'Morning!'),+ row(2, 'assistant', 'Hi! Two **bookings** today, see [the calendar](https://example.com/cal).'),+ row(3, 'user', 'Still there?', { run_key: 'g2' }),+ ];+ renderChat(employee());+ expect(await screen.findByText('Still there?')).toBeInTheDocument();+ expect(sendRequest).toHaveBeenCalledWith('get_chat_messages', { session_id: 'w1', limit: 200, all_generations: true });+ expect(screen.getByText('Maya restarted — they start fresh from here')).toBeInTheDocument();+ // An answer is markdown, and its links leave the conversation open.+ expect(await screen.findByText('bookings', { selector: 'strong' })).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'the calendar' })).toHaveAttribute('target', '_blank');+ });++ it('starts as just the message box, with whether they ask first under it', async () => {+ renderChat(employee({ asks_first: true }));+ expect(await screen.findByRole('textbox', { name: 'Message Maya' })).toHaveValue('');+ expect(screen.getByRole('log', { name: 'Conversation with Maya' })).toBeEmptyDOMElement();+ expect(screen.getByText('Maya asks before sending anything on your behalf.')).toBeInTheDocument();+ });+});++describe('sending', () => {+ it('works until the run ends, whatever else lands meanwhile', async () => {+ renderChat(employee());+ await write('Any bookings today?');+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Message Maya' }), { key: 'Enter' });+ expect(await screen.findByText('Working…')).toBeInTheDocument();++ // A routine report from another run does not end the wait (Talk bug 9).+ server.messages = [...server.messages, row(8, 'assistant', 'Daily summary: all quiet.', { run_id: 'r0' })];+ await act(async () => {+ await client.invalidateQueries({ queryKey: ['chatThread'] });+ });+ expect(await screen.findByText('Daily summary: all quiet.')).toBeInTheDocument();+ expect(screen.getByText('Working…')).toBeInTheDocument();++ runEvents(frame(1, 'started'), frame(2, 'finished', { outcome: { type: 'success' } }));+ server.messages = [...server.messages, row(9, 'assistant', 'Two, at 10 and at 3.', { run_id: 'r1' })];+ await act(async () => {+ await client.invalidateQueries({ queryKey: ['chatThread'] });+ });+ expect(await screen.findByText('Two, at 10 and at 3.')).toBeInTheDocument();+ expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ });++ it('says on the status line when the employee will retry', async () => {+ server.messages = [row(1, 'user', 'Hello', { run_id: 'r1' })];+ sendRequest.mockImplementation(async (type: string) =>+ type === 'chat_subscribe'+ ? { success: true, hub_epoch: 'e1', active_runs: [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }] }+ : { success: true, messages: server.messages },+ );+ act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {+ status: 'executing', data: { phase: 'retry_wait', retry_message: 'Gemini is temporarily unavailable.' },+ }));+ renderChat(employee());+ expect(await screen.findByText('Gemini is temporarily unavailable. Retrying automatically…')).toBeInTheDocument();+ act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, { status: 'executing' }));+ expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();+ });++ it('takes a refused message back, keeps the text and says they are not running', async () => {+ server.send = { success: false, error: 'not_running' };+ renderChat(employee());+ await write('Hello?');+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya isn’t running. Start them first.', { tone: 'error' }));+ expect(screen.getByRole('log', { name: 'Conversation with Maya' })).not.toHaveTextContent('Hello?');+ expect(screen.getByRole('textbox', { name: 'Message Maya' })).toHaveValue('Hello?');+ expect(screen.queryByText('Working…')).not.toBeInTheDocument();+ });++ it('keeps a message the employee cannot take yet, saying they are still working', async () => {+ server.send = { success: false, error: 'run_in_progress', run_id: 'r0' };+ renderChat(employee());+ await write('And Sunday?');+ fireEvent.click(screen.getByRole('button', { name: 'Send' }));++ await waitFor(() =>+ expect(pillToast).toHaveBeenCalledWith('Maya is still working on your last message. Send this once they answer.', { tone: 'info' }),+ );+ expect(screen.getByRole('textbox', { name: 'Message Maya' })).toHaveValue('And Sunday?');+ });++ it('lets one message wait while the employee is paused', async () => {+ server.send = { success: true, message_id: 'm_new', run_id: 'r1', delivery: 'queued' };+ const { rerender } = renderChat(employee({}, 'paused'));+ expect(await screen.findByText('Maya is paused. They’ll read your message when you resume them.')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Resume' })).toBeInTheDocument();++ await write('Call me back');+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Message Maya' }), { key: 'Enter' });+ expect(await screen.findByText('Your message is waiting. Maya will read it when you resume them.')).toBeInTheDocument();+ expect(screen.getByText('Waiting for you to resume Maya.')).toBeInTheDocument();+ fireEvent.change(screen.getByRole('textbox', { name: 'Message Maya' }), { target: { value: 'One more' } });+ expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();++ // Resumed: the waiting message goes to them now.+ rerender(employee({}, 'running'));+ runEvents(frame(1, 'started'));+ expect(await screen.findByText('Working…')).toBeInTheDocument();+ });++ it('gives the box to Start while the employee is not running', async () => {+ renderChat(employee({}, 'never_started'));+ expect(await screen.findByText('Maya isn’t running, so they can’t read messages right now.')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();+ expect(screen.queryByRole('textbox', { name: 'Message Maya' })).not.toBeInTheDocument();+ });++ it('notes an employee whose setup cannot answer', async () => {+ renderChat(employee({ talk: { state: 'unsupported', agent_node_id: null } }));+ expect(await screen.findByText('You can’t message Maya here. Their setup has no way to answer you.')).toBeInTheDocument();+ expect(screen.queryByRole('textbox', { name: 'Message Maya' })).not.toBeInTheDocument();+ });++ it('still offers their main action without Talk (Talk bug 7)', async () => {+ renderChat(employee({ talk: { state: 'off', agent_node_id: null } }, 'never_started'));+ expect(await screen.findByText('Maya isn’t running.')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Turn on Talk' })).toBeInTheDocument();+ });+});++describe('Turn on Talk', () => {+ it('confirms, mentioning the drafts a restart throws away, then turns Talk on', async () => {+ const user = userEvent.setup();+ const off = employee({ talk: { state: 'off', agent_node_id: null }, pending_approvals: 2 });+ const fromDatabase = employee({ revision: 10, talk: { state: 'on', agent_node_id: AGENT } });+ sendRequest.mockImplementation(async (type: string) =>+ type === 'enable_employee_talk'+ ? { success: true, employee: { ...off, control: undefined, talk: { state: 'on', agent_node_id: AGENT }, revision: 9 } }+ : type === 'list_employees'+ ? { success: true, employees: [fromDatabase] }+ : type === 'chat_subscribe'+ ? { success: true, hub_epoch: 'e1', active_runs: [] }+ : { success: true, messages: [] },+ );+ renderChat(off);+ expect(screen.queryByRole('textbox', { name: 'Message Maya' })).not.toBeInTheDocument();++ await user.click(screen.getByRole('button', { name: 'Turn on Talk' }));+ const dialog = await screen.findByRole('alertdialog');+ expect(dialog).toHaveTextContent('Maya has 2 drafts waiting for you. Restarting throws them away, so check them first.');+ await user.click(screen.getByRole('button', { name: 'Turn on Talk' }));++ await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Talk is on. Say hello to Maya.'));+ const [, payload, timeout] = sendRequest.mock.calls.find(([type]) => type === 'enable_employee_talk')!;+ expect(payload).toEqual({ workflow_id: 'w1', idempotency_key: expect.any(String) });+ expect(timeout).toBe(WORKFLOW_CONTROL_REQUEST_TIMEOUT);+ expect(client.getQueryState(employeeDetailKey('w1'))?.isInvalidated).toBe(true);+ await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 10, talk: { state: 'on' } }));+ expect(sendRequest).toHaveBeenCalledWith('list_employees', {});+ });+});++describe('Apply', () => {+ function applyServer(apply: (resolve: (value: unknown) => void) => unknown, employees: () => unknown[]) {+ sendRequest.mockImplementation((type: string) => {+ if (type === 'apply_employee_changes') return new Promise((resolve) => apply(resolve));+ if (type === 'list_employees') return Promise.resolve({ success: true, employees: employees() });+ if (type === 'chat_subscribe') return Promise.resolve({ success: true, hub_epoch: 'e1', active_runs: [] });+ return Promise.resolve({ success: true, messages: [] });+ });+ }++ it('restarts the employee on the latest setup', async () => {+ const summary = employee({ pending_changes: true });+ const fromDatabase = employee({ pending_changes: false, revision: 14 });+ applyServer((resolve) => resolve({ success: true, employee: { ...summary, control: undefined, pending_changes: false, revision: 12 } }), () => [fromDatabase]);+ renderChat(summary);+ expect(await screen.findByText(/Maya has new abilities for this conversation\./)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));+ await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya restarted with the new abilities.'));+ expect(sendRequest).toHaveBeenCalledWith(+ 'apply_employee_changes',+ { workflow_id: 'w1', idempotency_key: expect.any(String) },+ WORKFLOW_CONTROL_REQUEST_TIMEOUT,+ );+ await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 14, pending_changes: false }));+ expect(sendRequest).toHaveBeenCalledWith('list_employees', {});+ });++ it('refreshes database state when the restart fails instead of merging its response summary', async () => {+ const summary = employee({ pending_changes: true });+ const fromDatabase = employee({ pending_changes: true, revision: 15 }, 'ready');+ applyServer(+ (resolve) => resolve({ success: false, error: 'restart_failed', employee: { ...summary, control: { state: 'ready' }, revision: 13 } }),+ () => [fromDatabase],+ );+ renderChat(summary);+ fireEvent.click(await screen.findByRole('button', { name: 'Apply' }));+ await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya couldn’t restart. Try starting them again.', { tone: 'error' }));+ await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 15, control: { state: 'ready' } }));+ expect(sendRequest).toHaveBeenCalledWith('list_employees', {});+ });++ it('does not recreate a deleted employee when an earlier Apply response arrives', async () => {+ const summary = employee({ pending_changes: true });+ let finish!: (response: unknown) => void;+ applyServer((resolve) => { finish = resolve; }, () => []);+ renderChat(summary);+ fireEvent.click(await screen.findByRole('button', { name: 'Apply' }));+ await waitFor(() => expect(finish).toBeTypeOf('function'));+ await act(async () => { removeEmployee(client, 'w1'); });+ await act(async () => { finish({ success: true, employee: { ...summary, revision: 99 } }); });+ await waitFor(() => expect(sendRequest.mock.calls.filter(([type]) => type === 'list_employees')).toHaveLength(2));+ expect(client.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([]);+ expect(client.getQueryData(employeeDetailKey('w1'))).toBeUndefined();+ });+});diff --git a/client/src/features/home/__tests__/employeeView.test.tsx b/client/src/features/home/__tests__/employeeView.test.tsxindex 19dd7291..564d31fd 100644--- a/client/src/features/home/__tests__/employeeView.test.tsx+++ b/client/src/features/home/__tests__/employeeView.test.tsx@@ -1,6 +1,7 @@/**- * The employee page: only their name above the conversation. Their main- * action shows above the message box while they cannot read messages+ * The employee page: the conversation, with their name in the header (not+ * on the page). Their main action shows above the message box while they+ * cannot read messages* (Connect goes to the provider's connect dialog, Resume sends the* summary's revision and says "Resuming…" until the summary shows them* running, never flashing "Resume" again in between), never the reason@@ -84,7 +85,7 @@ beforeEach(() => {});describe('EmployeeView', () => {- it('shows only their name above the conversation while they work', () => {+ it('keeps the page to the conversation while they work', () => {actions.sendRequest.mockResolvedValue({ success: true, messages: [] });const whatsapp = { app_id: 'whatsapp', provider_id: 'whatsapp', name: 'WhatsApp', connected: true, supported: true };renderPage(@@ -93,7 +94,7 @@ describe('EmployeeView', () => {{ state: 'running' },),);- expect(screen.getByRole('heading', { name: 'Maya' })).toBeInTheDocument();+ expect(screen.queryByRole('heading', { name: 'Maya' })).not.toBeInTheDocument();expect(screen.getByRole('textbox', { name: 'Message Maya' })).toBeInTheDocument();for (const name of ['Pause', 'Resume', 'Start', 'Watch live']) {expect(screen.queryByRole('button', { name })).not.toBeInTheDocument();@@ -185,7 +186,7 @@ describe('EmployeeView', () => {actions.sendRequest.mockResolvedValue({ success: true, messages: [] });actions.startEmployee.mockReturnValue(new Promise(() => {}));renderPage(summary({ status: 'ready', talk: TALK_ON }, { state: 'never_started', revision: 3 }));- const talk = await screen.findByRole('region', { name: 'Talk with Maya' });+ const talk = await screen.findByRole('region', { name: 'Chat with Maya' });expect(talk).toHaveTextContent('Maya isn’t running, so they can’t read messages right now.');expect(screen.queryByRole('textbox', { name: 'Message Maya' })).not.toBeInTheDocument();@@ -234,13 +235,13 @@ describe('EmployeeView', () => {renderPage(summary({ status: 'working', talk: TALK_ON, pending_approvals: 1 }, { state: 'running' }));const drafts = await screen.findByRole('region', { name: 'Waiting for you' });expect(drafts).toHaveTextContent('Yes! Saturday at 10 works.');- expect(screen.getByRole('region', { name: 'Talk with Maya' })).toContainElement(drafts);+ expect(screen.getByRole('region', { name: 'Chat with Maya' })).toContainElement(drafts);});it('notes when the employee cannot take messages', () => {renderPage(summary({ status: 'working' }, { state: 'running' }));expect(screen.getByText('You can’t message Maya here. Their setup has no way to answer you.')).toBeInTheDocument();- expect(actions.sendRequest).not.toHaveBeenCalledWith('get_chat_messages', expect.anything());+ expect(screen.queryByRole('textbox', { name: 'Message Maya' })).not.toBeInTheDocument();});it('says so when the employee is gone', async () => {diff --git a/client/src/features/home/__tests__/homeHeader.test.tsx b/client/src/features/home/__tests__/homeHeader.test.tsxindex 8932d42f..c167920b 100644--- a/client/src/features/home/__tests__/homeHeader.test.tsx+++ b/client/src/features/home/__tests__/homeHeader.test.tsx@@ -1,37 +1,95 @@/**- * The Home header's Normal/Dev switch: on an employee's page Dev opens that- * employee's workflow (the card has no menu for it); elsewhere Dev shows+ * The Home header: on an employee's page it says who they are (name, role+ * and apps, status) and offers New conversation, which asks first; the+ * Normal/Dev switch opens that employee's workflow there, and elsewhere* what the editor last had.*/import { beforeEach, describe, expect, it, vi } from 'vitest';-import { fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { ReactNode } from 'react';+const sendRequest = vi.fn();++vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),+}));vi.mock('../../../app/useShellActions', () => ({ enterDev: vi.fn(), enterNormal: vi.fn() }));vi.mock('../../../app/ShellModeSwitch', () => ({ useShellMode: () => 'normal' }));vi.mock('../workspace/WorkspaceButton', () => ({ WorkspaceButton: () => null }));vi.mock('../header/ThemeButton', () => ({ ThemeButton: () => null }));+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));+import { normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';import { enterDev } from '../../../app/useShellActions';+import { parseEmployee } from '../data/schemas';import { HomeHeader } from '../header/HomeHeader';import { useHomeStore } from '../state/homeStore';+const maya = parseEmployee({+ workflow_id: 'w1',+ name: 'Maya',+ role: 'Receptionist',+ status: 'working',+ talk: { state: 'on', agent_node_id: 'w1:talk' },+ apps: [+ { app_id: 'whatsapp', provider_id: 'whatsapp', name: 'WhatsApp', connected: true },+ { app_id: 'calendar', provider_id: 'google', name: 'Google Calendar', connected: true },+ ],+ control: normalizeWorkflowControlStatus({ generation: 1, revision: 2, state: 'running' }, 'w1'),+})!;++function wrap(children: ReactNode) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={client}>{children}</QueryClientProvider>);+}+describe('HomeHeader', () => {beforeEach(() => {vi.mocked(enterDev).mockClear();+ sendRequest.mockReset().mockResolvedValue({ success: true });useHomeStore.setState({ sidebarOpen: true });});+ it('says who is on screen', () => {+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);+ expect(screen.getByRole('heading', { name: 'Maya' })).toBeInTheDocument();+ expect(screen.getByText('Receptionist · WhatsApp, Google Calendar')).toBeInTheDocument();+ expect(screen.getByText('Working')).toBeInTheDocument();+ });++ it('starts a new conversation once the owner confirms', async () => {+ const user = userEvent.setup();+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);+ await user.click(screen.getByRole('button', { name: 'New conversation' }));+ expect(await screen.findByRole('alertdialog')).toHaveTextContent('This clears the conversation, and Maya forgets it too.');+ expect(sendRequest).not.toHaveBeenCalledWith('clear_chat_messages', expect.anything());+ await user.click(screen.getByRole('button', { name: 'New conversation' }));+ await waitFor(() => expect(sendRequest).toHaveBeenCalledWith('clear_chat_messages', { session_id: 'w1' }));+ });++ it('offers no new conversation without a talk line', () => {+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });+ wrap(<HomeHeader title="Maya" employee={{ ...maya, talk: { state: 'off', agent_node_id: null } }} scrolled={false} />);+ expect(screen.queryByRole('button', { name: 'New conversation' })).not.toBeInTheDocument();+ });+it('opens the employee on screen in Dev mode', () => {useHomeStore.setState({ view: { kind: 'employee', workflowId: 'w1' } });- render(<HomeHeader title="Maya" scrolled={false} />);+ wrap(<HomeHeader title="Maya" employee={maya} scrolled={false} />);fireEvent.click(screen.getByRole('radio', { name: 'Dev' }));expect(enterDev).toHaveBeenCalledWith({ workflowId: 'w1' });});it('opens what the editor last had from the hire view', () => {useHomeStore.setState({ view: { kind: 'hire' } });- render(<HomeHeader title="New employee" scrolled={false} />);+ wrap(<HomeHeader title="New employee" employee={null} scrolled={false} />);+ expect(screen.getByRole('heading', { name: 'New employee' })).toBeInTheDocument();fireEvent.click(screen.getByRole('radio', { name: 'Dev' }));expect(enterDev).toHaveBeenCalledWith({ workflowId: undefined });});diff --git a/client/src/features/home/__tests__/talk.test.tsx b/client/src/features/home/__tests__/talk.test.tsxdeleted file mode 100644index 026c3a34..00000000--- a/client/src/features/home/__tests__/talk.test.tsx+++ /dev/null@@ -1,436 +0,0 @@-/**- * Talking to an employee on their page: the thread (every generation, with a- * divider at each restart), sending (shown at once, taken back when the- * server refuses), "Working…" until the answer lands, one message queued- * while paused, suggestions, Turn on Talk, and Apply. The reply wait's- * fallbacks are checked on the hook itself.- */--import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';--const sendRequest = vi.fn();--vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),- useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),-}));--vi.mock('../../../app/useShellActions', () => ({ enterDev: vi.fn() }));-vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));--import { WORKFLOW_CONTROL_REQUEST_TIMEOUT, normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';-import { useNodeStatusStore } from '@/stores/nodeStatusStore';-import { EMPLOYEES_QUERY_KEY, employeeDetailKey, removeEmployee, useEmployeesQuery } from '../data/employees';-import { presentEmployee } from '../data/presentation';-import { parseEmployee, type EmployeeSummary } from '../data/schemas';-import {- PICKUP_WAIT_MS,- REPLY_WAIT_MS,- SETTLE_WAIT_MS,- THREAD_LIMIT,- threadKey,- useReplyWait,- type ThreadMessage,-} from '../data/talk';-import { EmployeeTalk } from '../employee/EmployeeTalk';-import type { EmployeeControl } from '../employee/useEmployeeControl';-import { pillToast } from '../ui/pillToast';-// Loaded up front so the thread's lazy markdown resolves from the module cache.-import '../employee/ThreadMarkdown';--const AGENT = 'w1:talk';--function employee(patch: Record<string, unknown> = {}, state = 'running'): EmployeeSummary {- return parseEmployee({- workflow_id: 'w1',- name: 'Maya',- role: 'Receptionist',- status: state === 'running' ? 'working' : state === 'paused' ? 'paused' : 'ready',- talk: { state: 'on', agent_node_id: AGENT },- control: normalizeWorkflowControlStatus({ generation: 1, revision: 4, state }, 'w1'),- ...patch,- })!;-}--function controlFor(summary: EmployeeSummary): EmployeeControl {- const view = presentEmployee(summary);- return { view, label: view.primary.kind === 'resume' ? 'Resume' : 'Start', busy: false, act: vi.fn() };-}--let server: { messages: Record<string, unknown>[]; send: Record<string, unknown> };-let client: QueryClient;--function TeamSubscription() {- useEmployeesQuery();- return null;-}--function renderTalk(summary: EmployeeSummary) {- client = new QueryClient({ defaultOptions: { queries: { retry: false } } });- client.setQueryData(EMPLOYEES_QUERY_KEY, [summary]);- client.setQueryData(employeeDetailKey(summary.workflow_id), summary);- const view = (next: EmployeeSummary) => (- <QueryClientProvider client={client}>- <TeamSubscription />- <EmployeeTalk employee={next} control={controlFor(next)} />- </QueryClientProvider>- );- const utils = render(view(summary));- return { rerender: (next: EmployeeSummary) => utils.rerender(view(next)) };-}--function row(id: number, role: 'user' | 'assistant', message: string, runKey = 'g1') {- return { id, role, message, timestamp: new Date(2026, 8, 28, 9, id).toISOString(), run_key: runKey };-}--/** What `chat.updated` does: the thread refetches. */-async function chatUpdated() {- await act(async () => {- await client.invalidateQueries({ queryKey: threadKey('w1') });- });-}--function setAgentStatus(status: 'executing' | 'success') {- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, { status }));-}--beforeEach(() => {- useNodeStatusStore.setState({ allStatuses: {} });- vi.mocked(pillToast).mockClear();- server = { messages: [], send: { success: true, delivery: 'now' } };- sendRequest.mockReset().mockImplementation(async (type: string, data: Record<string, unknown>) => {- if (type === 'get_chat_messages') return { success: true, messages: server.messages };- if (type === 'send_chat_message') {- if (server.send.success !== false) server.messages = [...server.messages, row(server.messages.length + 1, 'user', String(data.message))];- return server.send;- }- return { success: true };- });-});--describe('the thread', () => {- it('reads every generation and marks the restart', async () => {- server.messages = [- row(1, 'user', 'Morning!'),- row(2, 'assistant', 'Hi! Two **bookings** today, see [the calendar](https://example.com/cal).'),- row(3, 'user', 'Still there?', 'g2'),- ];- renderTalk(employee());- expect(await screen.findByText('Still there?')).toBeInTheDocument();- expect(sendRequest).toHaveBeenCalledWith('get_chat_messages', { session_id: 'w1', limit: THREAD_LIMIT, all_generations: true });- expect(screen.getByText('Maya restarted — they start fresh from here')).toBeInTheDocument();- // An answer is markdown, and its links leave the conversation open.- expect(await screen.findByText('bookings', { selector: 'strong' })).toBeInTheDocument();- expect(screen.getByRole('link', { name: 'the calendar' })).toHaveAttribute('target', '_blank');- });-- it('starts as just the message box', async () => {- renderTalk(employee());- expect(await screen.findByRole('textbox', { name: 'Message Maya' })).toHaveValue('');- expect(screen.getByRole('log', { name: 'Conversation with Maya' })).toBeEmptyDOMElement();- expect(screen.queryByRole('button', { name: 'What are you working on?' })).not.toBeInTheDocument();- });-});--describe('sending', () => {- it('shows a retry on reopening Talk and clears it on the next attempt', async () => {- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {- status: 'executing', data: { phase: 'retry_wait', retry_message: 'Gemini is temporarily unavailable.' },- }));- renderTalk(employee());- expect(await screen.findByRole('status')).toHaveTextContent('Gemini is temporarily unavailable. Retrying automatically…');- expect(screen.queryByText('No answer from Maya yet.')).not.toBeInTheDocument();- setAgentStatus('executing');- expect(screen.queryByText(/Retrying automatically/)).not.toBeInTheDocument();- });-- it('shows the node failure and hint without waiting for another model answer', async () => {- renderTalk(employee());- const box = await screen.findByRole('textbox', { name: 'Message Maya' });- fireEvent.change(box, { target: { value: 'Hello' } });- fireEvent.keyDown(box, { key: 'Enter' });- await screen.findByText('Hello');- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {- status: 'error', data: { error: 'Spending cap reached.', hint: 'Review billing before resuming.' },- }));- expect(screen.getByRole('alert')).toHaveTextContent('Spending cap reached. Review billing before resuming.');- expect(screen.queryByText('Working…')).not.toBeInTheDocument();- expect(screen.queryByText('No answer from Maya yet.')).not.toBeInTheDocument();- });-- it('shows the message at once and thinks until the answer lands', async () => {- renderTalk(employee());- const box = await screen.findByRole('textbox', { name: 'Message Maya' });- fireEvent.change(box, { target: { value: ' Any bookings today? ' } });- fireEvent.keyDown(box, { key: 'Enter' });-- expect(box).toHaveValue('');- expect(screen.getByText('Working…')).toBeInTheDocument();- expect(await screen.findByText('Any bookings today?')).toBeInTheDocument();- await waitFor(() =>- expect(sendRequest).toHaveBeenCalledWith(- 'send_chat_message',- expect.objectContaining({ message: 'Any bookings today?', role: 'user', session_id: 'w1', timestamp: expect.any(String) }),- ),- );-- // The box holds while the answer is on its way.- fireEvent.change(box, { target: { value: 'And tomorrow?' } });- expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();-- setAgentStatus('executing');- server.messages = [...server.messages, row(9, 'assistant', 'Two, at 10 and at 3.')];- await chatUpdated();- expect(await screen.findByText('Two, at 10 and at 3.')).toBeInTheDocument();- await waitFor(() => expect(screen.queryByText('Working…')).not.toBeInTheDocument());- expect(screen.getByRole('button', { name: 'Send' })).toBeEnabled();- expect(screen.getAllByText('Any bookings today?')).toHaveLength(1);- });-- it('takes a refused message back and keeps the text', async () => {- server.send = { success: false, error: 'not_running' };- renderTalk(employee());- const box = await screen.findByRole('textbox', { name: 'Message Maya' });- fireEvent.change(box, { target: { value: 'Hello?' } });- fireEvent.click(screen.getByRole('button', { name: 'Send' }));-- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya isn’t running. Start them first.', { tone: 'error' }));- expect(screen.getByRole('log', { name: 'Conversation with Maya' })).not.toHaveTextContent('Hello?');- expect(box).toHaveValue('Hello?');- expect(screen.queryByText('Working…')).not.toBeInTheDocument();- });-- it('keeps a message the employee cannot take yet, saying they are still working', async () => {- server.send = { success: false, error: 'run_in_progress' };- renderTalk(employee());- const box = await screen.findByRole('textbox', { name: 'Message Maya' });- fireEvent.change(box, { target: { value: 'And Sunday?' } });- fireEvent.click(screen.getByRole('button', { name: 'Send' }));-- await waitFor(() =>- expect(pillToast).toHaveBeenCalledWith('Maya is still working on your last message. Send this once they answer.', { tone: 'info' }),- );- expect(screen.getByRole('log', { name: 'Conversation with Maya' })).not.toHaveTextContent('And Sunday?');- expect(box).toHaveValue('And Sunday?');- });-- it('lets one message wait while the employee is paused', async () => {- server.send = { success: true, delivery: 'queued' };- const paused = employee({}, 'paused');- const { rerender } = renderTalk(paused);- expect(await screen.findByText('Maya is paused. They’ll read your message when you resume them.')).toBeInTheDocument();- expect(screen.getByRole('button', { name: 'Resume' })).toBeInTheDocument();-- const box = screen.getByRole('textbox', { name: 'Message Maya' });- fireEvent.change(box, { target: { value: 'Call me back' } });- fireEvent.keyDown(box, { key: 'Enter' });- expect(await screen.findByText('Your message is waiting. Maya will read it when you resume them.')).toBeInTheDocument();- expect(screen.queryByText('Working…')).not.toBeInTheDocument();- fireEvent.change(box, { target: { value: 'One more' } });- expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();-- // Resumed: the waiting message goes to them now.- rerender(employee({}, 'running'));- expect(await screen.findByText('Working…')).toBeInTheDocument();- });-- it('gives the box to Start while the employee is not running', async () => {- renderTalk(employee({}, 'never_started'));- expect(await screen.findByText('Maya isn’t running, so they can’t read messages right now.')).toBeInTheDocument();- expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();- expect(screen.queryByRole('textbox', { name: 'Message Maya' })).not.toBeInTheDocument();- // No box to fill, so no suggestions.- expect(screen.queryByRole('button', { name: 'What are you working on?' })).not.toBeInTheDocument();- });-});--describe('Turn on Talk', () => {- it('confirms, mentioning the drafts a restart throws away, then turns Talk on', async () => {- const user = userEvent.setup();- const off = employee({ talk: { state: 'off', agent_node_id: null }, pending_approvals: 2 });- const fromDatabase = employee({ revision: 10, talk: { state: 'on', agent_node_id: AGENT } });- sendRequest.mockImplementation(async (type: string) =>- type === 'enable_employee_talk'- ? { success: true, employee: { ...off, control: undefined, talk: { state: 'on', agent_node_id: AGENT }, revision: 9 } }- : type === 'list_employees'- ? { success: true, employees: [fromDatabase] }- : { success: true, messages: [] },- );- renderTalk(off);- expect(sendRequest).not.toHaveBeenCalledWith('get_chat_messages', expect.anything());-- await user.click(screen.getByRole('button', { name: 'Turn on Talk' }));- const dialog = await screen.findByRole('alertdialog');- expect(dialog).toHaveTextContent('Maya has 2 drafts waiting for you. Restarting throws them away, so check them first.');- await user.click(screen.getByRole('button', { name: 'Turn on Talk' }));-- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Talk is on. Say hello to Maya.'));- const [, payload, timeout] = sendRequest.mock.calls.find(([type]) => type === 'enable_employee_talk')!;- expect(payload).toEqual({ workflow_id: 'w1', idempotency_key: expect.any(String) });- expect(timeout).toBe(WORKFLOW_CONTROL_REQUEST_TIMEOUT);- expect(client.getQueryState(employeeDetailKey('w1'))?.isInvalidated).toBe(true);- await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 10, talk: { state: 'on' } }));- expect(sendRequest).toHaveBeenCalledWith('list_employees', {});- });-});--describe('Apply', () => {- it('restarts the employee on the latest setup', async () => {- const summary = employee({ pending_changes: true });- const fromDatabase = employee({ pending_changes: false, revision: 14 });- sendRequest.mockImplementation(async (type: string) =>- type === 'apply_employee_changes'- ? { success: true, employee: { ...summary, control: undefined, pending_changes: false, revision: 12 } }- : type === 'list_employees'- ? { success: true, employees: [fromDatabase] }- : { success: true, messages: [] },- );- renderTalk(summary);- expect(await screen.findByText(/Maya has new abilities for this conversation\./)).toBeInTheDocument();- fireEvent.click(screen.getByRole('button', { name: 'Apply' }));- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya restarted with the new abilities.'));- expect(sendRequest).toHaveBeenCalledWith(- 'apply_employee_changes',- { workflow_id: 'w1', idempotency_key: expect.any(String) },- WORKFLOW_CONTROL_REQUEST_TIMEOUT,- );- await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 14, pending_changes: false }));- expect(sendRequest).toHaveBeenCalledWith('list_employees', {});- });-- it('refreshes database state when the restart fails instead of merging its response summary', async () => {- const summary = employee({ pending_changes: true });- const fromDatabase = employee({ pending_changes: true, revision: 15 }, 'ready');- sendRequest.mockImplementation(async (type: string) =>- type === 'apply_employee_changes'- ? { success: false, error: 'restart_failed', employee: { ...summary, control: { state: 'ready' }, revision: 13 } }- : type === 'list_employees'- ? { success: true, employees: [fromDatabase] }- : { success: true, messages: [] },- );- renderTalk(summary);- fireEvent.click(await screen.findByRole('button', { name: 'Apply' }));- await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya couldn’t restart. Try starting them again.', { tone: 'error' }));- await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 15, control: { state: 'ready' } }));- expect(sendRequest).toHaveBeenCalledWith('list_employees', {});- });-- it('does not recreate a deleted employee when an earlier Apply response arrives', async () => {- const summary = employee({ pending_changes: true });- let finish!: (response: unknown) => void;- sendRequest.mockImplementation((type: string) => {- if (type === 'apply_employee_changes') return new Promise((resolve) => { finish = resolve; });- if (type === 'list_employees') return Promise.resolve({ success: true, employees: [] });- return Promise.resolve({ success: true, messages: [] });- });- renderTalk(summary);- fireEvent.click(await screen.findByRole('button', { name: 'Apply' }));- await waitFor(() => expect(finish).toBeTypeOf('function'));- await act(async () => { removeEmployee(client, 'w1'); });- await act(async () => { finish({ success: true, employee: { ...summary, revision: 99 } }); });- await waitFor(() => expect(sendRequest.mock.calls.filter(([type]) => type === 'list_employees')).toHaveLength(2));- expect(client.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([]);- expect(client.getQueryData(employeeDetailKey('w1'))).toBeUndefined();- });-});--describe('useReplyWait', () => {- const reply: ThreadMessage = { id: '7', role: 'assistant', message: 'Done', timestamp: null, run_key: 'g1' };-- beforeEach(() => {- vi.useFakeTimers();- });-- afterEach(() => {- vi.useRealTimers();- });-- it('keeps waiting through provider backoff, then allows time for the next attempt', () => {- let messages: ThreadMessage[] = [];- const { result, rerender } = renderHook(() => useReplyWait('w1', AGENT, messages));- act(() => result.current.begin());- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {- status: 'executing', data: { phase: 'retry_wait', retry_message: 'Gemini is rate-limiting requests.' },- }));- act(() => vi.advanceTimersByTime(REPLY_WAIT_MS * 2));- expect(result.current).toMatchObject({ waiting: true, unanswered: false, retryMessage: 'Gemini is rate-limiting requests.' });- setAgentStatus('executing');- act(() => vi.advanceTimersByTime(REPLY_WAIT_MS - 1));- expect(result.current).toMatchObject({ waiting: true, retryMessage: null });- messages = [reply];- rerender();- expect(result.current).toMatchObject({ waiting: false, unanswered: false, retryMessage: null });- });-- it('replaces a temporary throttle with actionable quota failure', () => {- const { result } = renderHook(() => useReplyWait('w1', AGENT, []));- act(() => result.current.begin());- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {- status: 'executing', data: { phase: 'retry_wait', retry_message: 'Waiting for Gemini.' },- }));- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, {- status: 'error', data: { error: 'Daily quota exhausted.', hint: 'Resume after quota resets.' },- }));- expect(result.current).toMatchObject({ waiting: false, unanswered: false, retryMessage: null,- failure: { error: 'Daily quota exhausted.', hint: 'Resume after quota resets.' } });- });-- it('ignores an old failure when a new message begins', () => {- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, { status: 'error', data: { error: 'Old failure' } }));- const { result } = renderHook(() => useReplyWait('w1', AGENT, []));- act(() => result.current.begin());- expect(result.current).toMatchObject({ waiting: true, failure: null });- act(() => useNodeStatusStore.getState().setStatus('w1', AGENT, { status: 'error', data: { error: 'New failure', hint: 'Fix the key' } }));- expect(result.current).toMatchObject({ waiting: false, unanswered: false, failure: { error: 'New failure', hint: 'Fix the key' } });- act(() => result.current.begin());- expect(result.current.failure).toBeNull();- });-- it('gives up when the agent never picks the message up', () => {- const { result } = renderHook(() => useReplyWait('w1', AGENT, []));- act(() => result.current.begin());- act(() => vi.advanceTimersByTime(PICKUP_WAIT_MS - 1));- expect(result.current.waiting).toBe(true);- act(() => vi.advanceTimersByTime(1));- expect(result.current).toMatchObject({ waiting: false, unanswered: true });- });-- it('waits as long as the agent works, and ends with the answer', () => {- let messages: ThreadMessage[] = [];- const { result, rerender } = renderHook(() => useReplyWait('w1', AGENT, messages));- act(() => result.current.begin());- setAgentStatus('executing');- act(() => vi.advanceTimersByTime(PICKUP_WAIT_MS * 2));- expect(result.current.waiting).toBe(true);-- // Finished: the answer has a moment to reach the thread.- setAgentStatus('success');- act(() => vi.advanceTimersByTime(SETTLE_WAIT_MS - 1));- expect(result.current.waiting).toBe(true);- messages = [reply];- rerender();- expect(result.current).toMatchObject({ waiting: false, unanswered: false });- });-- it('stops soon after the agent finishes without an answer', () => {- const { result } = renderHook(() => useReplyWait('w1', AGENT, [reply]));- act(() => result.current.begin());- setAgentStatus('executing');- setAgentStatus('success');- act(() => vi.advanceTimersByTime(SETTLE_WAIT_MS));- expect(result.current).toMatchObject({ waiting: false, unanswered: true });- });-- it('never waits past the limit, and ignores the answer already there', () => {- const { result } = renderHook(() => useReplyWait('w1', AGENT, [reply]));- act(() => result.current.begin());- setAgentStatus('executing');- act(() => vi.advanceTimersByTime(REPLY_WAIT_MS - 1));- expect(result.current.waiting).toBe(true);- act(() => vi.advanceTimersByTime(1));- expect(result.current.waiting).toBe(false);- });-});diff --git a/client/src/features/home/__tests__/thread.test.ts b/client/src/features/home/__tests__/thread.test.tsdeleted file mode 100644index a464450e..00000000--- a/client/src/features/home/__tests__/thread.test.ts+++ /dev/null@@ -1,79 +0,0 @@-/**- * The thread's data: rows the server sends are parsed forgivingly, a- * divider marks every restart between two messages, the newest answer is- * what a send waits to change, and times read the way a person says them.- */--import { describe, expect, it } from 'vitest';-import { latestReplyId, parseThread, threadRows, timeLabel, type ThreadMessage } from '../data/talk';--function message(id: string, role: 'user' | 'assistant', run_key: string | null): ThreadMessage {- return { id, role, message: `${role} ${id}`, timestamp: null, run_key };-}--describe('parseThread', () => {- it('keeps the order and drops rows it cannot show', () => {- const parsed = parseThread([- { id: 1, role: 'user', message: 'Hi', timestamp: '2026-09-28T09:00:00+00:00', run_key: 'g1' },- { id: 2, role: 'system', message: 'hidden' },- { role: 'assistant', message: 'no id' },- { id: '3', role: 'assistant', message: 'Hello!', timestamp: 42, run_key: 7 },- ]);- expect(parsed).toEqual([- { id: '1', role: 'user', message: 'Hi', timestamp: '2026-09-28T09:00:00+00:00', run_key: 'g1' },- { id: '3', role: 'assistant', message: 'Hello!', timestamp: null, run_key: null },- ]);- expect(parseThread({ messages: [] })).toEqual([]);- });-});--describe('threadRows', () => {- it('draws a divider where the generation changes', () => {- const rows = threadRows([message('1', 'user', 'g1'), message('2', 'assistant', 'g1'), message('3', 'user', 'g2')]);- expect(rows.map((row) => (row.kind === 'restart' ? '|' : row.message.id))).toEqual(['1', '2', '|', '3']);- });-- it('never draws one for a message of unknown generation', () => {- const rows = threadRows([message('1', 'user', null), message('2', 'user', 'g1'), { ...message('3', 'user', null), pending: true }]);- expect(rows.every((row) => row.kind === 'message')).toBe(true);- // Unknown in between: the next known generation still compares to the last known one.- const skipped = threadRows([message('1', 'user', 'g1'), message('2', 'user', null), message('3', 'assistant', 'g2')]);- expect(skipped.map((row) => row.kind)).toEqual(['message', 'message', 'restart', 'message']);- });-});--describe('latestReplyId', () => {- it('is the newest answer, whatever came after it', () => {- expect(latestReplyId([message('1', 'assistant', 'g1'), message('2', 'user', 'g1')])).toBe('1');- expect(latestReplyId([message('1', 'user', 'g1')])).toBeNull();- expect(latestReplyId(undefined)).toBeNull();- });-});--describe('timeLabel', () => {- const now = new Date(2026, 8, 28, 15, 30);- const time = (date: Date) => date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });-- it('gives the time today and says yesterday', () => {- const morning = new Date(2026, 8, 28, 9, 5);- expect(timeLabel(morning.toISOString(), now)).toBe(time(morning));- const lastNight = new Date(2026, 8, 27, 22, 40);- expect(timeLabel(lastNight.toISOString(), now)).toBe(`Yesterday, ${time(lastNight)}`);- });-- it('names the weekday within a week, else the date', () => {- const monday = new Date(2026, 8, 22, 10, 0);- expect(timeLabel(monday.toISOString(), now)).toBe(`${monday.toLocaleDateString(undefined, { weekday: 'long' })}, ${time(monday)}`);- const earlier = new Date(2026, 7, 3, 10, 0);- expect(timeLabel(earlier.toISOString(), now)).toBe(- `${earlier.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}, ${time(earlier)}`,- );- const lastYear = new Date(2025, 11, 31, 10, 0);- expect(timeLabel(lastYear.toISOString(), now)).toContain(lastYear.getFullYear().toString());- });-- it('says nothing for a time it cannot read', () => {- expect(timeLabel(null, now)).toBe('');- expect(timeLabel('yesterday-ish', now)).toBe('');- });-});diff --git a/client/src/features/home/data/presentation.ts b/client/src/features/home/data/presentation.tsindex 3b33ef41..8a34f1af 100644--- a/client/src/features/home/data/presentation.ts+++ b/client/src/features/home/data/presentation.ts@@ -165,6 +165,19 @@ export function talkNoticeText(mode: TalkMode, name: string, queued = false): st}}+/** The line beside their main action for an employee who cannot take+ * messages here at all (Talk off or unsupported): only their state. */+export function stateNoticeText(mode: TalkMode, name: string): string | null {+ switch (mode) {+ case 'send':+ return null;+ case 'queue':+ return `${name} is paused.`;+ case 'start':+ return `${name} isn’t running.`;+ }+}+/** Said before anything that restarts an employee (Turn on Talk, Apply): a* restart cancels the drafts waiting for the owner. */export function restartDraftsWarning(name: string, drafts: number): string {@@ -196,10 +209,4 @@ export const STATUS_DOT_CLASS: Record<StatusTone, string> = {live: 'bg-node-trigger opencompany-pip-pulse',};-export { AVATAR_CLASS } from '@/components/catalog/presentation';--/** The avatar's letter: the first letter of the name, "?" when empty. */-export function initialOf(name: string): string {- const letter = Array.from(name.trim())[0];- return letter ? letter.toLocaleUpperCase() : '?';-}+export { AVATAR_CLASS, initialOf } from '@/components/catalog/presentation';diff --git a/client/src/features/home/data/talk.ts b/client/src/features/home/data/talk.tsindex a88712ef..af652edc 100644--- a/client/src/features/home/data/talk.ts+++ b/client/src/features/home/data/talk.ts@@ -1,290 +1,22 @@/**- * Talking to an employee on its page, over the chat session whose id is the- * employee's workflow id:+ * Home's side of talking to an employee. The conversation itself is the+ * shared chat (features/chat); this is what only an employee has:*- * - `useTalkThread(workflowId)`: the conversation (`get_chat_messages` with- * `all_generations`, so a message from before a Start shows too), the- * newest 200 messages. A Reset clears the thread on the server.- * WebSocketContext invalidates it on `chat.updated`, on a runtime reset- * and when the socket reopens.- * - `useSendTalkMessage(workflowId)`: `send_chat_message`. The message shows- * at once and leaves again if the server refuses it (`not_running`: it- * saved nothing); the response's `delivery` says whether it went now or- * waits for Resume.- * - `useReplyWait(...)`: "Working…" after a send. It follows the talk- * agent's node status (`useNodeStatusStore` directly, like `useLiveTask`:- * the editor's hooks see only the workflow open in Dev mode), with- * fallbacks for an agent that never picks the message up or never ends.* - `useEnableTalk()` / `useApplyChanges()`: Turn on Talk and Apply. Both* restart the employee, so they wait as long as Start does, then refresh* the team from the database.- * - Pure helpers the thread renders from: restart dividers, time labels.+ * - `useRetryNote(...)`: while the talk agent waits to retry after a failed+ * attempt, what it said, for the chat's status line. It reads the agent's+ * node status (`useNodeStatusStore` directly, like `useLiveTask`: the+ * editor's hooks see only the workflow open in Dev mode).*/-import { useCallback, useEffect, useState } from 'react';-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { z } from 'zod';+import { useCallback } from 'react';+import { useMutation, useQueryClient } from '@tanstack/react-query';import { WORKFLOW_CONTROL_REQUEST_TIMEOUT, useWebSocketActions } from '@/contexts/WebSocketContext';-import { STALE_TIME, queryKeys } from '@/lib/queryConfig';import { useNodeStatusStore } from '@/stores/nodeStatusStore';import { refreshEmployee } from './employees';-/** The newest messages the thread shows. */-export const THREAD_LIMIT = 200;-/** How long the talk agent has to pick a message up. */-export const PICKUP_WAIT_MS = 30_000;-/** Time without fresh progress before "Working…" expires, excluding retry waits. */-export const REPLY_WAIT_MS = 180_000;-/** Once the agent stops, how long its answer has to reach the thread. */-export const SETTLE_WAIT_MS = 5_000;--export const threadKey = (workflowId: string) => queryKeys.chatThread.bySession(workflowId).queryKey;--const threadMessageSchema = z.object({- id: z.union([z.number(), z.string()]).transform((id) => String(id)),- role: z.enum(['user', 'assistant']),- message: z.string(),- timestamp: z.string().nullable().catch(null),- /** The generation the message was written in; it changes at each restart. */- run_key: z.string().nullable().catch(null),-});--export interface ThreadMessage extends z.infer<typeof threadMessageSchema> {- /** Sent from this tab; the server has not confirmed it yet. */- pending?: boolean;-}--/** A thread from the server, oldest first, dropping rows it cannot show. */-export function parseThread(raw: unknown): ThreadMessage[] {- if (!Array.isArray(raw)) return [];- return raw.flatMap((item) => {- const parsed = threadMessageSchema.safeParse(item);- return parsed.success ? [parsed.data] : [];- });-}--export type ThreadRow = { kind: 'message'; message: ThreadMessage } | { kind: 'restart'; key: string };--/** The thread with a divider wherever the employee restarted between two- * messages. A message whose generation is unknown (written before rows were- * stamped, or not saved yet) never draws one. */-export function threadRows(messages: readonly ThreadMessage[]): ThreadRow[] {- const rows: ThreadRow[] = [];- let previous: string | null = null;- for (const message of messages) {- if (previous && message.run_key && message.run_key !== previous) {- rows.push({ kind: 'restart', key: `restart-${message.id}` });- }- if (message.run_key) previous = message.run_key;- rows.push({ kind: 'message', message });- }- return rows;-}--/** The newest answer's id, or null. Another one after a send means the send- * was answered. */-export function latestReplyId(messages: readonly ThreadMessage[] | undefined): string | null {- if (!messages) return null;- for (let i = messages.length - 1; i >= 0; i -= 1) {- if (messages[i].role === 'assistant') return messages[i].id;- }- return null;-}--const DAY_MS = 86_400_000;--function startOfDay(date: Date): number {- return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();-}--/** When a message was written, the way a person says it: the time today,- * "Yesterday, 9:41 AM", the weekday within a week, else the date. Empty- * when the timestamp cannot be read. */-export function timeLabel(timestamp: string | null, now: Date = new Date()): string {- if (!timestamp) return '';- const date = new Date(timestamp);- if (Number.isNaN(date.getTime())) return '';- const time = date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });- // Rounded: a day with a clock change is 23 or 25 hours long.- const days = Math.round((startOfDay(now) - startOfDay(date)) / DAY_MS);- if (days <= 0) return time;- if (days === 1) return `Yesterday, ${time}`;- if (days < 7) return `${date.toLocaleDateString(undefined, { weekday: 'long' })}, ${time}`;- const year = date.getFullYear() === now.getFullYear() ? undefined : 'numeric';- return `${date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year })}, ${time}`;-}--// ----- the conversation -------export function useTalkThread(workflowId: string) {- const { sendRequest, isReady } = useWebSocketActions();- return useQuery<ThreadMessage[], Error>({- queryKey: threadKey(workflowId),- queryFn: async () => {- const response = await sendRequest<{ success?: boolean; messages?: unknown; error?: string }>('get_chat_messages', {- session_id: workflowId,- limit: THREAD_LIMIT,- all_generations: true,- });- if (response?.success === false) throw new Error(response.error || 'Could not load the conversation');- return parseThread(response?.messages);- },- enabled: isReady && Boolean(workflowId),- // Broadcasts keep it current. Opening the page refetches only when one- // arrived while it was closed (it left the thread invalidated).- staleTime: STALE_TIME.FOREVER,- refetchOnMount: true,- });-}--/** Where a sent message went: to the employee now, or waiting for Resume. */-export type Delivery = 'now' | 'queued';--/** Numbers the messages shown before the server has saved them. */-let localSequence = 0;--export function useSendTalkMessage(workflowId: string) {- const { sendRequest } = useWebSocketActions();- const queryClient = useQueryClient();- const key = threadKey(workflowId);- return useMutation<Delivery, Error, string, { localId: string }>({- mutationFn: async (text) => {- const response = await sendRequest<{ success?: boolean; error?: string; delivery?: string }>('send_chat_message', {- message: text,- role: 'user',- session_id: workflowId,- timestamp: new Date().toISOString(),- });- if (response?.success === false) throw new Error(response.error || 'send_failed');- return response?.delivery === 'queued' ? 'queued' : 'now';- },- onMutate: async (text) => {- await queryClient.cancelQueries({ queryKey: key });- const localId = `local-${(localSequence += 1)}`;- const local: ThreadMessage = {- id: localId,- role: 'user',- message: text,- timestamp: new Date().toISOString(),- run_key: null,- pending: true,- };- queryClient.setQueryData<ThreadMessage[]>(key, (list) => [...(list ?? []), local]);- return { localId };- },- onSuccess: (_delivery, _text, context) => {- queryClient.setQueryData<ThreadMessage[]>(key, (list) =>- list?.map((message) => (message.id === context.localId ? { ...message, pending: false } : message)),- );- },- onError: (_error, _text, context) => {- if (!context) return;- queryClient.setQueryData<ThreadMessage[]>(key, (list) => list?.filter((message) => message.id !== context.localId));- },- // The refetch swaps the local copy for the saved row.- onSettled: () => {- void queryClient.invalidateQueries({ queryKey: key });- },- });-}--// ----- waiting for the answer -------interface Wait {- since: number;- /** Ignore an error left over from a previous message. */- initialStatus: object | undefined;- /** The newest answer when the message went out; another one answers it. */- repliedTo: string | null;- /** The agent has been seen working. */- working: boolean;- /** The agent stopped; its answer may still be on its way to the thread. */- settling: boolean;-}--export interface ReplyWait {- /** "Working…": the message box holds until this clears. */- waiting: boolean;- /** The last wait ended with no answer. */- unanswered: boolean;- failure: { error: string; hint?: string } | null;- retryMessage: string | null;- /** A message just went to the agent. */- begin: () => void;- /** It did not after all (refused, or waiting for Resume). */- cancel: () => void;-}--export function useReplyWait(- workflowId: string,- agentNodeId: string | null,- messages: readonly ThreadMessage[] | undefined,-): ReplyWait {- const [wait, setWait] = useState<Wait | null>(null);- const [unanswered, setUnanswered] = useState(false);- const [failure, setFailure] = useState<ReplyWait['failure']>(null);- const nodeStatus = useNodeStatusStore(- useCallback(- (state) => (agentNodeId ? state.allStatuses[workflowId]?.[agentNodeId] : undefined),- [workflowId, agentNodeId],- ),- );- const status = nodeStatus?.status;- const retryMessage = status === 'executing'- && nodeStatus?.data?.phase === 'retry_wait'- && (!wait || nodeStatus !== wait.initialStatus)- && typeof nodeStatus.data.retry_message === 'string'- ? nodeStatus.data.retry_message : null;- const replyId = latestReplyId(messages);-- // An answer ends the wait. The agent working, then stopping, settles it.- useEffect(() => {- if (status === 'executing') setFailure(null);- if (!wait) return;- if (replyId !== wait.repliedTo) {- setWait(null);- setUnanswered(false);- setFailure(null);- } else if (status === 'error' && nodeStatus !== wait.initialStatus && typeof nodeStatus?.data?.error === 'string') {- setFailure({- error: nodeStatus.data.error,- hint: typeof nodeStatus.data.hint === 'string' ? nodeStatus.data.hint : undefined,- });- setWait(null);- setUnanswered(false);- } else if (status === 'executing') {- if (!wait.working || wait.settling) setWait({ ...wait, working: true, settling: false });- } else if (wait.working && !wait.settling) {- setWait({ ...wait, settling: true });- }- }, [wait, status, nodeStatus, replyId]);-- // A known retry wait is active work. Resume the fallback timer when the- // next attempt starts, so backoff cannot consume the time to answer.- useEffect(() => {- if (!wait || retryMessage) return;- const left = wait.settling- ? SETTLE_WAIT_MS- : wait.working ? REPLY_WAIT_MS : PICKUP_WAIT_MS - (Date.now() - wait.since);- const timer = window.setTimeout(() => {- setWait(null);- setUnanswered(true);- }, Math.max(0, left));- return () => window.clearTimeout(timer);- }, [wait, nodeStatus, retryMessage]);-- const begin = useCallback(() => {- const initialStatus = agentNodeId ? useNodeStatusStore.getState().allStatuses[workflowId]?.[agentNodeId] : undefined;- setWait({ since: Date.now(), initialStatus, repliedTo: latestReplyId(messages), working: false, settling: false });- setUnanswered(false);- setFailure(null);- }, [messages, workflowId, agentNodeId]);- const cancel = useCallback(() => setWait(null), []);- return { waiting: wait !== null, unanswered, failure, retryMessage, begin, cancel };-}--// ----- Turn on Talk, Apply ------/** Both restart the employee on the server. Refresh the queries afterwards,* including failures that may have changed the employee before failing.* Every click sends its own idempotency key. Errors carry the server's code. */@@ -313,3 +45,17 @@ export function useEnableTalk() {export function useApplyChanges() {return useEmployeeChange('apply_employee_changes');}++/** "{why} Retrying automatically…" while the talk agent waits to try again;+ * null otherwise, and whenever no run of theirs is going (`live`). */+export function useRetryNote(workflowId: string, agentNodeId: string | null, live: boolean): string | null {+ const status = useNodeStatusStore(+ useCallback(+ (state) => (agentNodeId ? state.allStatuses[workflowId]?.[agentNodeId] : undefined),+ [workflowId, agentNodeId],+ ),+ );+ if (!live || status?.status !== 'executing' || status.data?.phase !== 'retry_wait') return null;+ const message = status.data.retry_message;+ return typeof message === 'string' && message ? `${message} Retrying automatically…` : null;+}diff --git a/client/src/features/home/employee/EmployeeChat.tsx b/client/src/features/home/employee/EmployeeChat.tsxnew file mode 100644index 00000000..ec059b01--- /dev/null+++ b/client/src/features/home/employee/EmployeeChat.tsx@@ -0,0 +1,155 @@+/**+ * Talking to an employee on their page: the shared chat (features/chat)+ * over the session whose id is their workflow id, with Home around it.+ *+ * - The thread scrolls under the header with the orb as its first item (and+ * a new hire's notes under it); the drafts waiting for the owner follow+ * the conversation; the line under the message box says whether they ask+ * before sending anything.+ * - The message box follows their control state the way the server does: a+ * message goes at once while they run, waits for Resume while they are+ * paused, and cannot be sent otherwise. Above it, what to act on: Resume or+ * Start (or connect what they are missing), Apply while saved changes wait+ * for a restart, Help in browser while they wait for the owner there, and+ * why a run of failures paused them.+ * - Without a talk line, Turn on Talk offers to add one; an employee whose+ * setup cannot answer gets a note instead of the box.+ */++import { Monitor } from 'lucide-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 { invalidateEmployees } from '../data/employees';+import { stateNoticeText, talkMode, talkNoticeText } from '../data/presentation';+import type { EmployeeSummary } from '../data/schemas';+import { useRetryNote } from '../data/talk';+import { HireNotice } from '../hire/HireNotice';+import { OrbSlot } from '../orb/OrbSlot';+import { useHomeStore } from '../state/homeStore';+import { pillToast } from '../ui/pillToast';+import { DraftsSection } from './DraftsSection';+import { PendingChangesNotice } from './PendingChangesNotice';+import { PrimaryActionButton } from './PrimaryActionButton';+import { TurnOnTalk } from './TurnOnTalk';+import type { EmployeeControl } from './useEmployeeControl';++/** The agent is waiting for the owner in the browser (it called `request_user`). */+function BrowserNotice({ employee }: { employee: EmployeeSummary }) {+ const openWorkspace = useHomeStore((s) => s.openWorkspace);+ const setWorkspaceTab = useHomeStore((s) => s.setWorkspaceTab);+ return (+ <div className="flex flex-wrap items-center gap-3">+ <p className="m-0 min-w-50 flex-1 text-sm text-fg-muted">{employee.task?.text || `${employee.name} needs you in the browser.`}</p>+ <ActionButton+ intent="tools"+ onClick={() => {+ openWorkspace(employee.workflow_id);+ setWorkspaceTab('browser');+ }}+ className="h-9 gap-2 rounded-row px-3.5"+ >+ <Monitor aria-hidden className="size-3.5" />+ Help in browser+ </ActionButton>+ </div>+ );+}++/** Why the circuit breaker paused them: the failure that kept repeating. */+function failurePauseText(employee: EmployeeSummary): string | null {+ if (employee.control.pause_reason !== 'failures') return null;+ return employee.control.pause_detail || (employee.task?.label === 'Paused' ? employee.task.text : null) || null;+}++function Notices({ employee, control, queued }: { employee: EmployeeSummary; control: EmployeeControl; queued: boolean }) {+ const { name } = employee;+ const mode = talkMode(employee.control);+ const failure = mode === 'queue' ? failurePauseText(employee) : null;+ // Their main action shows whether or not they can take messages here.+ const notice = employee.talk.state === 'on' ? talkNoticeText(mode, name, queued) : stateNoticeText(mode, name);+ return (+ <>+ {failure && (+ <Alert variant="destructive">+ <AlertDescription>{failure}</AlertDescription>+ </Alert>+ )}+ {employee.pending_changes && <PendingChangesNotice employee={employee} />}+ {employee.browser_request && <BrowserNotice employee={employee} />}+ {employee.talk.state === 'off' && <TurnOnTalk employee={employee} />}+ {employee.talk.state === 'unsupported' && (+ <p className="m-0 w-full rounded-card border border-border-default bg-bg-panel px-4 py-3 text-center text-sm text-fg-muted">+ You can’t message {name} here. Their setup has no way to answer you.+ </p>+ )}+ {notice && (+ <div className="flex flex-wrap items-center gap-3">+ <p className="m-0 min-w-50 flex-1 text-sm text-fg-muted">{notice}</p>+ <PrimaryActionButton control={control} />+ </div>+ )}+ </>+ );+}++export function EmployeeChat({+ employee,+ control,+ onScrolledChange,+}: {+ employee: EmployeeSummary;+ control: EmployeeControl;+ onScrolledChange?: (scrolled: boolean) => void;+}) {+ const queryClient = useQueryClient();+ const { workflow_id: workflowId, name } = employee;+ const lane = useLaneRun(workflowId);+ const liveNote = useRetryNote(workflowId, employee.talk.agent_node_id, lane !== null && lane.state !== 'queued');+ const mode = talkMode(employee.control);+ const composer: ComposerMode = employee.talk.state !== 'on' || mode === 'start' ? 'closed' : mode;+ const paused = employee.control.state === 'paused' || employee.control.state === 'pausing';++ const onSendRefused = (code: string) => {+ if (code === 'not_running') {+ invalidateEmployees(queryClient);+ pillToast(`${name} isn’t running. Start them first.`, { tone: 'error' });+ } else if (code === 'run_in_progress') {+ // One answer at a time: the server refuses a second message while+ // the employee is still working on the last one.+ pillToast(`${name} is still working on your last message. Send this once they answer.`, { tone: 'info' });+ } else {+ pillToast('Your message didn’t send. Try again.', { tone: 'error' });+ }+ };++ return (+ <ChatPane+ host={{+ kind: 'home',+ sessionId: workflowId,+ scope: 'all',+ persona: { name, colorRole: employee.color_role },+ composer,+ notices: <Notices employee={employee} control={control} queued={lane?.state === 'queued'} />,+ top: (+ <div className="flex flex-col items-center gap-4">+ <OrbSlot size="employee" />+ <HireNotice workflowId={workflowId} />+ </div>+ ),+ afterThread: <DraftsSection workflowId={workflowId} employeeName={name} paused={paused} />,+ footnote: employee.asks_first+ ? `${name} asks before sending anything on your behalf.`+ : `${name} doesn’t ask before sending anything on your behalf.`,+ notify: (message, tone) => pillToast(message, { tone }),+ onSendRefused,+ liveNote,+ onScrolledChange,+ }}+ />+ );+}++export default EmployeeChat;diff --git a/client/src/features/home/employee/EmployeeTalk.tsx b/client/src/features/home/employee/EmployeeTalk.tsxdeleted file mode 100644index c4f931c5..00000000--- a/client/src/features/home/employee/EmployeeTalk.tsx+++ /dev/null@@ -1,316 +0,0 @@-/**- * Talking to an employee, under their name: the conversation, and a message- * box pinned to the bottom of the page.- *- * - The thread is the conversation since the employee last started: a- * restart clears it on the server, as the employee forgets it too. A- * message left from before a Start (a test run in Dev mode) sits above a- * divider saying they started fresh. Replies, questions and routine- * reports all land in it, and `drafts` (the ones waiting for the owner's- * OK) follow the messages.- * - While the employee runs, a message goes to them at once, and- * "Working…" holds the box until they answer (useReplyWait); overlapping- * runs would each save over the other's conversation. While they are- * paused, one message waits for Resume and then the box holds. Otherwise- * the box gives way to their main action (Start, or what they are- * missing). While they wait for the owner in the browser, a line above- * the box says so beside Help in browser.- * - Without a talk line, TurnOnTalk offers to add one; an employee whose- * setup cannot answer gets a note.- */--import { ArrowUp, Monitor } from 'lucide-react';-import { Suspense, lazy, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';-import { useQueryClient } from '@tanstack/react-query';-import { ActionButton } from '@/components/ui/action-button';-import { Alert, AlertDescription } from '@/components/ui/alert';-import { Button } from '@/components/ui/button';-import { Skeleton } from '@/components/ui/skeleton';-import { Textarea } from '@/components/ui/textarea';-import { prefersReducedMotion } from '@/lib/useReducedMotion';-import { cn } from '@/lib/utils';-import { invalidateEmployees } from '../data/employees';-import { talkMode, talkNoticeText } from '../data/presentation';-import type { EmployeeSummary } from '../data/schemas';-import { threadRows, timeLabel, useReplyWait, useSendTalkMessage, useTalkThread, type ThreadMessage } from '../data/talk';-import { isSendKey } from '../hire/composerKeys';-import { useHomeStore } from '../state/homeStore';-import { pillToast } from '../ui/pillToast';-import { Avatar } from '../ui/primitives';-import { useAutoGrow } from '../ui/useAutoGrow';-import { PendingChangesNotice } from './PendingChangesNotice';-import { PrimaryActionButton } from './PrimaryActionButton';-import { TurnOnTalk } from './TurnOnTalk';-import type { EmployeeControl } from './useEmployeeControl';--// Its own chunk: the markdown stack stays out of Home's first load.-const ThreadMarkdown = lazy(() => import('./ThreadMarkdown'));--/** Lines up an answer's time under its text, past the avatar. */-const PAST_AVATAR = 'pl-10.5';--/*- * One bubble for both sides of the conversation: the same raised surface,- * border and type in every theme. Only the side (the owner's on the right,- * the employee's on the left beside their avatar) and the corner that- * points at the speaker differ. `chat-msg-user` / `chat-msg-bot` are the- * theme hooks the editor's chat pane carries too.- */-const BUBBLE =- 'chat-msg min-w-0 max-w-4/5 border border-border-default bg-bg-elevated px-3.5 py-2.5 text-md leading-normal break-words';-const MINE = 'chat-msg-user rounded-l-card rounded-br-card rounded-tr-sm text-fg-default';-const THEIRS = 'chat-msg-bot rounded-r-card rounded-bl-card rounded-tl-sm';--function MessageRow({ message, employee, now }: { message: ThreadMessage; employee: EmployeeSummary; now: Date }) {- const mine = message.role === 'user';- const time = message.pending ? 'Sending…' : timeLabel(message.timestamp, now);- return (- <div data-message={message.id} className={cn('flex flex-col gap-1', mine ? 'items-end' : 'items-start')}>- {mine ? (- <p className={cn('m-0 whitespace-pre-wrap', BUBBLE, MINE)}>{message.message}</p>- ) : (- <div className="flex w-full items-start gap-3">- <Avatar name={employee.name} colorRole={employee.color_role} size="sm" />- <div className={cn(BUBBLE, THEIRS, 'text-fg-default')}>- <Suspense fallback={<p className="m-0 whitespace-pre-wrap">{message.message}</p>}>- <ThreadMarkdown text={message.message} />- </Suspense>- </div>- </div>- )}- {time && <span className={cn('text-xs text-fg-muted', !mine && PAST_AVATAR)}>{time}</span>}- </div>- );-}--function RestartDivider({ name }: { name: string }) {- return (- <div className="flex items-center gap-3 py-1 text-xs text-fg-muted">- <span aria-hidden className="h-px flex-1 bg-border-default" />- <span className="text-center">{name} restarted — they start fresh from here</span>- <span aria-hidden className="h-px flex-1 bg-border-default" />- </div>- );-}--function TalkBox({- name,- value,- onChange,- onSend,- canSend,-}: {- name: string;- value: string;- onChange: (value: string) => void;- onSend: () => void;- canSend: boolean;-}) {- const boxRef = useRef<HTMLTextAreaElement>(null);- useAutoGrow(boxRef, value);-- // Enter sends, Shift+Enter is a new line; while the box holds, Enter waits.- const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {- if (!isSendKey(event)) return;- event.preventDefault();- if (canSend) onSend();- };-- return (- <div className="flex w-full items-end gap-2 rounded-composer border border-border-default bg-bg-panel py-2 pr-2 pl-4 shadow-float transition-colors duration-(--dur-slow) focus-within:border-border-strong">- <Textarea- ref={boxRef}- variant="bare"- rows={1}- value={value}- onChange={(event) => onChange(event.target.value)}- onKeyDown={onKeyDown}- aria-label={`Message ${name}`}- placeholder={`Message ${name}…`}- className="max-h-(--h-composer-max) overflow-hidden py-1.5 text-md leading-normal text-fg-default field-sizing-fixed"- />- <Button variant="invert" size="icon" disabled={!canSend} onClick={onSend} aria-label="Send" title="Send" className="shrink-0 rounded-full">- <ArrowUp aria-hidden strokeWidth={2.25} />- </Button>- </div>- );-}--/** The agent is waiting for the owner in the browser (it called `request_user`). */-function BrowserNotice({ employee }: { employee: EmployeeSummary }) {- const openWorkspace = useHomeStore((s) => s.openWorkspace);- const setWorkspaceTab = useHomeStore((s) => s.setWorkspaceTab);- return (- <div className="flex flex-wrap items-center gap-3">- <p className="m-0 min-w-50 flex-1 text-sm text-fg-muted">{employee.task?.text || `${employee.name} needs you in the browser.`}</p>- <ActionButton- intent="tools"- onClick={() => {- openWorkspace(employee.workflow_id);- setWorkspaceTab('browser');- }}- className="h-9 gap-2 rounded-row px-3.5"- >- <Monitor aria-hidden className="size-3.5" />- Help in browser- </ActionButton>- </div>- );-}--function Conversation({ employee, control, drafts }: { employee: EmployeeSummary; control: EmployeeControl; drafts?: ReactNode }) {- const { workflow_id: workflowId, name } = employee;- const queryClient = useQueryClient();- const thread = useTalkThread(workflowId);- const messages = thread.data;- const send = useSendTalkMessage(workflowId);- const { waiting, unanswered, failure, retryMessage, begin, cancel } = useReplyWait(workflowId, employee.talk.agent_node_id, messages);- const mode = talkMode(employee.control);- const [draft, setDraft] = useState('');- const [queued, setQueued] = useState(false);- const endRef = useRef<HTMLDivElement>(null);-- // A message that waited for Resume reaches the employee when they run- // again; a reset drops it.- useEffect(() => {- if (!queued || mode === 'queue') return;- setQueued(false);- if (mode === 'send') begin();- }, [queued, mode, begin]);-- // Keep the newest message in view as the conversation grows. Opening the- // page leaves its top (the name) in view.- const lastId = messages?.at(-1)?.id ?? null;- const shownLast = useRef<string | null | undefined>(undefined);- useLayoutEffect(() => {- if (!messages) return;- const previous = shownLast.current;- shownLast.current = lastId;- if (previous === undefined || previous === lastId) return;- endRef.current?.scrollIntoView?.({ behavior: prefersReducedMotion() ? 'auto' : 'smooth', block: 'end' });- }, [messages, lastId]);-- const text = draft.trim();- const holding = waiting || queued || send.isPending;- const canSend = text.length > 0 && !holding && messages !== undefined;-- const submit = () => {- if (!canSend) return;- setDraft('');- const goesNow = mode === 'send';- if (goesNow) begin();- send.mutate(text, {- onSuccess: (delivery) => {- if (delivery === 'queued') {- cancel();- setQueued(true);- } else if (!goesNow) {- begin();- }- },- onError: (error) => {- cancel();- setDraft((current) => current || text);- if (error.message === 'not_running') invalidateEmployees(queryClient);- if (error.message === 'run_in_progress') {- // One answer at a time: the server refuses a second message while- // the employee is still working on the last one.- pillToast(`${name} is still working on your last message. Send this once they answer.`, { tone: 'info' });- return;- }- pillToast(error.message === 'not_running' ? `${name} isn’t running. Start them first.` : 'Your message didn’t send. Try again.', {- tone: 'error',- });- },- });- };-- const rows = messages ? threadRows(messages) : [];- const notice = talkNoticeText(mode, name, queued);- const failureText = mode === 'queue' && employee.control.pause_reason === 'failures'- ? employee.control.pause_detail || (employee.task?.label === 'Paused' ? employee.task.text : null)- : failure ? [failure.error, failure.hint].filter(Boolean).join(' ') : null;- const now = new Date();-- return (- <section aria-label={`Talk with ${name}`} className="flex w-full flex-1 flex-col">- {thread.isPending ? (- <div aria-busy className="flex flex-col gap-3 py-2">- <Skeleton className="h-10 w-3/5 self-end rounded-card" />- <Skeleton className="h-16 w-4/5 rounded-card" />- </div>- ) : (- thread.isError && (- <div className="flex flex-col items-center gap-2 py-6 text-center">- <p className="m-0 text-sm text-fg-default">Couldn’t load the conversation.</p>- <Button variant="quiet" onClick={() => void thread.refetch()} className="border-border-default text-fg-default">- Try again- </Button>- </div>- )- )}- <div className="flex flex-col gap-4">- {/* A log: screen readers announce new messages and "Working…". */}- <div role="log" aria-live="polite" aria-label={`Conversation with ${name}`} className="flex flex-col gap-4">- {rows.map((row) =>- row.kind === 'restart' ? (- <RestartDivider key={row.key} name={name} />- ) : (- <MessageRow key={row.message.id} message={row.message} employee={employee} now={now} />- ),- )}- {(waiting || retryMessage) && (- <div className="flex items-start gap-3">- <Avatar name={name} colorRole={employee.color_role} size="sm" />- <p role="status" className={cn('m-0', BUBBLE, THEIRS, 'text-fg-muted')}>- {retryMessage ? `${retryMessage} Retrying automatically…` : 'Working…'}- </p>- </div>- )}- {unanswered && !waiting && !retryMessage && !failureText && <p className={cn('m-0 text-xs text-fg-muted', PAST_AVATAR)}>No answer from {name} yet.</p>}- </div>- {drafts}- </div>- <div className="sticky bottom-0 z-10 mt-auto flex flex-col gap-2.5 bg-bg-app pt-4 pb-3">- {failureText && <Alert variant="destructive"><AlertDescription>{failureText}</AlertDescription></Alert>}- {employee.pending_changes && <PendingChangesNotice employee={employee} />}- {employee.browser_request && <BrowserNotice employee={employee} />}- {notice && (- <div className="flex flex-wrap items-center gap-3">- <p className="m-0 min-w-50 flex-1 text-sm text-fg-muted">{notice}</p>- <PrimaryActionButton control={control} />- </div>- )}- {mode !== 'start' && <TalkBox name={name} value={draft} onChange={setDraft} onSend={submit} canSend={canSend} />}- </div>- <div ref={endRef} aria-hidden />- </section>- );-}--export function EmployeeTalk({- employee,- control,- drafts,-}: {- employee: EmployeeSummary;- control: EmployeeControl;- /** The drafts waiting for the owner, shown after the messages. */- drafts?: ReactNode;-}) {- if (employee.talk.state === 'on') return <Conversation employee={employee} control={control} drafts={drafts} />;- return (- <div className="flex w-full flex-col gap-4">- {drafts}- {employee.talk.state === 'off' ? (- <TurnOnTalk employee={employee} />- ) : (- <p className="m-0 w-full rounded-card border border-border-default bg-bg-panel px-4 py-3 text-center text-sm text-fg-muted">- You can’t message {employee.name} here. Their setup has no way to answer you.- </p>- )}- </div>- );-}--export default EmployeeTalk;diff --git a/client/src/features/home/employee/EmployeeView.tsx b/client/src/features/home/employee/EmployeeView.tsxindex 82d33eb2..11c5069b 100644--- a/client/src/features/home/employee/EmployeeView.tsx+++ b/client/src/features/home/employee/EmployeeView.tsx@@ -1,14 +1,14 @@/**- * One employee's page (design handoff "Employee view"): their name under- * the orb, then the conversation with them (EmployeeTalk), whose message- * box stays pinned to the bottom of the page. Only a new hire's notes- * (HireNotice) ever sit between the two.+ * One employee's page (design handoff chat): the conversation with them+ * (EmployeeChat) fills the page under the header, which names them; the+ * orb sits at the top of the conversation, and a new hire's notes+ * (HireNotice) under it.*- * What to act on lives in the conversation, and only while there is- * something to do: the drafts to check after the messages; above the- * message box, their main action while they cannot read messages (Resume,- * Start, or connect what they are missing; useEmployeeControl) and Help in- * browser while they wait for the owner there. Pausing them is the+ * What to act on lives above the message box, and only while there is+ * something to do: their main action while they cannot read messages+ * (Resume, Start, or connect what they are missing; useEmployeeControl),+ * Apply, and Help in browser while they wait for the owner there; the+ * drafts to check follow the conversation. Pausing them is the* Workspace's, which the header's Workspace pill opens on the employee on* screen; the header's Dev switch opens their workflow.*/@@ -19,12 +19,10 @@ import { Skeleton } from '@/components/ui/skeleton';import { useEmployeeDetailQuery, useEmployeesQuery } from '../data/employees';import { useLiveTask } from '../data/liveTask';import type { EmployeeSummary } from '../data/schemas';-import { HireNotice } from '../hire/HireNotice';import { OrbSlot } from '../orb/OrbSlot';import { SPIKE, spikeOrb } from '../orb/orb';import { useHomeStore } from '../state/homeStore';-import { DraftsSection } from './DraftsSection';-import { EmployeeTalk } from './EmployeeTalk';+import { EmployeeChat } from './EmployeeChat';import { useEmployeeControl } from './useEmployeeControl';/** The orb stirs when their work moves on (design handoff "Live work"). */@@ -39,27 +37,30 @@ function useTaskSpike(employee: EmployeeSummary): void {}, [text]);}-function EmployeePage({ employee, onConnect }: { employee: EmployeeSummary; onConnect: (providerId: string) => void }) {+function EmployeePage({+ employee,+ onConnect,+ onScrolledChange,+}: {+ employee: EmployeeSummary;+ onConnect: (providerId: string) => void;+ onScrolledChange?: (scrolled: boolean) => void;+}) {const control = useEmployeeControl(employee, onConnect);useTaskSpike(employee);- const paused = employee.control.state === 'paused' || employee.control.state === 'pausing';- return (- <section aria-label={employee.name} className="flex w-full max-w-(--w-employee-card) flex-1 flex-col items-center gap-4">- <div className="flex flex-col items-center gap-2">- <OrbSlot size="employee" />- <h2 className="text-center text-title font-semibold tracking-[-0.02em] break-words text-fg-default">{employee.name}</h2>- </div>- <HireNotice workflowId={employee.workflow_id} />- <EmployeeTalk- employee={employee}- control={control}- drafts={<DraftsSection workflowId={employee.workflow_id} employeeName={employee.name} paused={paused} />}- />- </section>- );+ return <EmployeeChat employee={employee} control={control} onScrolledChange={onScrolledChange} />;}-export function EmployeeView({ workflowId, onConnect }: { workflowId: string; onConnect: (providerId: string) => void }) {+export function EmployeeView({+ workflowId,+ onConnect,+ onScrolledChange,+}: {+ workflowId: string;+ onConnect: (providerId: string) => void;+ /** The conversation left its top, or came back (the header's border). */+ onScrolledChange?: (scrolled: boolean) => void;+}) {const list = useEmployeesQuery();const fromList = list.data?.find((e) => e.workflow_id === workflowId) ?? null;// Only when the list has no row for it (just hired, or the list failed).@@ -71,14 +72,14 @@ export function EmployeeView({ workflowId, onConnect }: { workflowId: string; onif (!employee) {if (list.isPending || (detailId !== null && detail.isPending)) {return (- <section aria-busy className="flex w-full max-w-(--w-employee-card) flex-col items-center gap-2">+ <section aria-busy className="flex w-full flex-col items-center gap-4 px-6 pt-7"><OrbSlot size="employee" />- <Skeleton className="h-7 w-44 rounded-row" />+ <Skeleton className="h-10 w-full max-w-(--w-chat-column) rounded-card" /></section>);}return (- <section className="flex w-full max-w-(--w-employee-card) flex-col items-center gap-3 pt-16 text-center">+ <section className="flex w-full flex-col items-center gap-3 px-6 pt-16 text-center"><p className="m-0 text-md text-fg-default">{detail.isError ? 'Couldn’t load this employee.' : 'This employee is no longer on the team.'}</p>@@ -96,7 +97,7 @@ export function EmployeeView({ workflowId, onConnect }: { workflowId: string; on);}- return <EmployeePage employee={employee} onConnect={onConnect} />;+ return <EmployeePage employee={employee} onConnect={onConnect} onScrolledChange={onScrolledChange} />;}export default EmployeeView;diff --git a/client/src/features/home/employee/ThreadMarkdown.tsx b/client/src/features/home/employee/ThreadMarkdown.tsxdeleted file mode 100644index 0d3ccb6b..00000000--- a/client/src/features/home/employee/ThreadMarkdown.tsx+++ /dev/null@@ -1,23 +0,0 @@-/**- * An employee's message in the thread, as markdown (lists, links, bold),- * in the type and colour of the bubble around it. Its own chunk: the talk- * thread loads it lazily, so the markdown stack stays out of Home's first- * load. Links open in a new tab, and images from outside the workspace wait- * for the owner (CHAT_MARKDOWN_COMPONENTS).- */--import ReactMarkdown from 'react-markdown';-import remarkBreaks from 'remark-breaks';-import remarkGfm from 'remark-gfm';--import { CHAT_MARKDOWN_COMPONENTS } from '@/features/chat';--export default function ThreadMarkdown({ text }: { text: string }) {- return (- <div className="chat-markdown min-w-0">- <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]} components={CHAT_MARKDOWN_COMPONENTS}>- {text}- </ReactMarkdown>- </div>- );-}diff --git a/client/src/features/home/header/HomeHeader.tsx b/client/src/features/home/header/HomeHeader.tsxindex ba79fc64..8f953d6e 100644--- a/client/src/features/home/header/HomeHeader.tsx+++ b/client/src/features/home/header/HomeHeader.tsx@@ -1,9 +1,11 @@/**- * Normal mode's header (design handoff "Main header"): with the sidebar- * collapsed, an open button and the logo; the view's title; the Workspace- * pill, the Normal/Dev switch (on an employee's page, Dev opens their- * workflow) and the theme button. The bottom border appears only once the- * content has scrolled, so the hero reads as one surface.+ * Normal mode's header (design handoff "Main header"; chat "Header"): with+ * the sidebar collapsed, an open button and the logo. Then the view: while+ * hiring, its title; on an employee's page, who they are (avatar, name,+ * role and apps, their status) and New conversation. At the end the+ * Workspace pill, the Normal/Dev switch (on an employee's page, Dev opens+ * their workflow) and the theme button. The bottom border appears only once+ * the content has scrolled, so the hero reads as one surface.*/import { PanelLeft } from 'lucide-react';@@ -11,11 +13,38 @@ import { OcLogo } from '@/components/brand/Logo';import { ModeToggle } from '@/components/shell/ModeToggle';import { Button } from '@/components/ui/button';import { cn } from '@/lib/utils';+import { useWorkflowControlPending } from '@/stores/workflowControlStore';+import { presentEmployee } from '../data/presentation';+import type { EmployeeSummary } from '../data/schemas';import { useHomeStore } from '../state/homeStore';+import { Avatar, StatusPill } from '../ui/primitives';import { WorkspaceButton } from '../workspace/WorkspaceButton';+import { NewConversationButton } from './NewConversationButton';import { ThemeButton } from './ThemeButton';-export function HomeHeader({ title, scrolled }: { title: string; scrolled: boolean }) {+/** "Receptionist · WhatsApp, Google Calendar". */+function subtitleOf(employee: EmployeeSummary): string {+ const apps = employee.apps.map((app) => app.name).join(', ');+ return [employee.role, apps].filter(Boolean).join(' · ');+}++function Identity({ employee }: { employee: EmployeeSummary }) {+ const pending = useWorkflowControlPending(employee.workflow_id);+ const { pill, pulse } = presentEmployee(employee, pending);+ const subtitle = subtitleOf(employee);+ return (+ <div className="flex min-w-0 items-center gap-2.5 px-1">+ <Avatar name={employee.name} colorRole={employee.color_role} size="sm" />+ <div className="flex min-w-0 flex-col">+ <h2 className="m-0 truncate text-base font-semibold text-fg-default">{employee.name}</h2>+ {subtitle && <span className="truncate text-xs text-fg-muted">{subtitle}</span>}+ </div>+ <StatusPill tone={pill.tone} label={pill.label} pulse={pulse} size="compact" />+ </div>+ );+}++export function HomeHeader({ title, employee, scrolled }: { title: string; employee: EmployeeSummary | null; scrolled: boolean }) {const sidebarOpen = useHomeStore((s) => s.sidebarOpen);const toggleSidebar = useHomeStore((s) => s.toggleSidebar);const logoPulse = useHomeStore((s) => s.logoPulse);@@ -37,8 +66,9 @@ export function HomeHeader({ title, scrolled }: { title: string; scrolled: boole<span aria-hidden className="h-5 w-px bg-border-default" /></>)}- <h2 className="truncate px-1.5 text-lead font-semibold text-fg-default">{title}</h2>+ {employee ? <Identity employee={employee} /> : <h2 className="truncate px-1.5 text-lead font-semibold text-fg-default">{title}</h2>}<div className="ml-auto flex shrink-0 items-center gap-2">+ {employee && employee.talk.state === 'on' && <NewConversationButton employee={employee} />}<WorkspaceButton /><ModeToggle workflowId={employeeId} /><ThemeButton />diff --git a/client/src/features/home/header/NewConversationButton.tsx b/client/src/features/home/header/NewConversationButton.tsxnew file mode 100644index 00000000..28f84224--- /dev/null+++ b/client/src/features/home/header/NewConversationButton.tsx@@ -0,0 +1,65 @@+/**+ * New conversation, in the header of an employee's page (design handoff+ * chat, "Header"). It clears the conversation and what the employee+ * remembers of it (`clear_chat_messages`), so it asks first.+ */++import { SquarePen } from 'lucide-react';+import { useState } from 'react';+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@/components/ui/alert-dialog';+import { Button } from '@/components/ui/button';+import { useClearChat } from '@/features/chat';+import type { EmployeeSummary } from '../data/schemas';+import { pillToast } from '../ui/pillToast';++export function NewConversationButton({ employee }: { employee: EmployeeSummary }) {+ const [confirming, setConfirming] = useState(false);+ const clear = useClearChat(employee.workflow_id);+ const { name } = employee;++ const start = () =>+ clear.mutate(undefined, {+ onError: () => pillToast('That did not work. Try again.', { tone: 'error' }),+ });++ return (+ <>+ <Button+ variant="quiet"+ onClick={() => setConfirming(true)}+ disabled={clear.isPending}+ title="New conversation"+ aria-label="New conversation"+ className="h-8 gap-1.75 rounded-lg px-2.5 text-sm"+ >+ <SquarePen aria-hidden className="size-4" strokeWidth={1.75} />+ <span className="hidden lg:inline">New conversation</span>+ </Button>+ <AlertDialog open={confirming} onOpenChange={setConfirming}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Start a new conversation with {name}?</AlertDialogTitle>+ <AlertDialogDescription>+ This clears the conversation, and {name} forgets it too.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Not now</AlertDialogCancel>+ <AlertDialogAction onClick={start}>New conversation</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+}++export default NewConversationButton;diff --git a/client/src/features/home/hire/Composer.tsx b/client/src/features/home/hire/Composer.tsxindex 1fd5a7c2..93b166c6 100644--- a/client/src/features/home/hire/Composer.tsx+++ b/client/src/features/home/hire/Composer.tsx@@ -14,12 +14,13 @@ import { ArrowRight } from 'lucide-react';import { useEffect, useRef, type KeyboardEvent } from 'react';import { Button } from '@/components/ui/button';import { Textarea } from '@/components/ui/textarea';+import { isSendKey } from '@/lib/composerKeys';import { animate } from '@/lib/motion';+import { useAutoGrow } from '@/lib/useAutoGrow';import { prefersReducedMotion } from '@/lib/useReducedMotion';import { cn } from '@/lib/utils';import { AppMark } from '../ui/primitives';-import { useAutoGrow } from '../ui/useAutoGrow';-import { createLabel, isSendKey } from './composerKeys';+import { createLabel } from './composerKeys';export interface ComposerApp {id: string;diff --git a/client/src/features/home/hire/composerKeys.ts b/client/src/features/home/hire/composerKeys.tsindex ba8c5840..84488b09 100644--- a/client/src/features/home/hire/composerKeys.ts+++ b/client/src/features/home/hire/composerKeys.ts@@ -1,25 +1,9 @@/**- * The composer's key and label rules, kept apart from the component so the- * component file exports components only (react-refresh) and the rules are- * testable on their own.+ * The hire composer's label rule, kept apart from the component so the+ * component file exports components only (react-refresh) and the rule is+ * testable on its own. Which Enter sends is lib/composerKeys.ts.*/-import type { KeyboardEvent } from 'react';--type SendKeyEvent = Pick<KeyboardEvent, 'key' | 'shiftKey'> & {- keyCode?: number;- nativeEvent?: { isComposing?: boolean; keyCode?: number };-};--/** True for the Enter that should send: not Shift+Enter, and not the Enter- * that confirms an IME composition (`isComposing`, or keyCode 229 on- * engines that report the composition that way). */-export function isSendKey(event: SendKeyEvent): boolean {- if (event.key !== 'Enter' || event.shiftKey) return false;- if (event.nativeEvent?.isComposing) return false;- return (event.keyCode ?? event.nativeEvent?.keyCode) !== 229;-}-export function createLabel(working: boolean, refining: boolean): string {if (working) return 'Creating…';return refining ? 'Update' : 'Create employee';diff --git a/client/src/features/home/ui/primitives.tsx b/client/src/features/home/ui/primitives.tsxindex 96f40511..11fbbcb3 100644--- a/client/src/features/home/ui/primitives.tsx+++ b/client/src/features/home/ui/primitives.tsx@@ -71,6 +71,8 @@ export function StatusDot({ tone, pulse = false, className }: { tone: StatusToneconst PILL_SIZE = {md: 'h-7.5 px-3 text-sm',+ /** Beside a name (the employee page's header). */+ compact: 'h-6 px-2.25 text-xs',/** The Workspace header's mono micro pill. */sm: 'h-5.5 px-2 font-mono text-2xs tracking-label uppercase',} as const;diff --git a/client/src/index.css b/client/src/index.cssindex 02d81f1d..d9fe7863 100644--- a/client/src/index.css+++ b/client/src/index.css@@ -652,6 +652,10 @@ html.oc-theme-fade *::after {border-top: 1px solid var(--border-default);margin: 12px 0;}+/* The stylized themes paint a reply (.chat-msg-bot) as a glowing or tinted+ * bubble; code blocks and tables inside keep their own surfaces unglowed. */+.chat-msg-bot pre,+.chat-msg-bot table { text-shadow: none; }/* ============================================================================* Syntax-highlighting palette — used by react-simple-code-editor + thediff --git a/client/src/lib/__tests__/composerKeys.test.ts b/client/src/lib/__tests__/composerKeys.test.tsnew file mode 100644index 00000000..7998620f--- /dev/null+++ b/client/src/lib/__tests__/composerKeys.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { isSendKey } from '../composerKeys';++describe('isSendKey', () => {+ it('sends on a plain Enter only', () => {+ expect(isSendKey({ key: 'Enter', shiftKey: false })).toBe(true);+ expect(isSendKey({ key: 'Enter', shiftKey: true })).toBe(false);+ expect(isSendKey({ key: 'a', shiftKey: false })).toBe(false);+ });++ it('leaves Ctrl, Cmd and Alt with Enter to other shortcuts', () => {+ expect(isSendKey({ key: 'Enter', shiftKey: false, ctrlKey: true })).toBe(false);+ expect(isSendKey({ key: 'Enter', shiftKey: false, metaKey: true })).toBe(false);+ expect(isSendKey({ key: 'Enter', shiftKey: false, altKey: true })).toBe(false);+ });++ it('never sends the Enter that confirms an IME composition', () => {+ expect(isSendKey({ key: 'Enter', shiftKey: false, nativeEvent: { isComposing: true } })).toBe(false);+ expect(isSendKey({ key: 'Enter', shiftKey: false, keyCode: 229 })).toBe(false);+ expect(isSendKey({ key: 'Enter', shiftKey: false, nativeEvent: { keyCode: 229 } })).toBe(false);+ });+});diff --git a/client/src/lib/composerKeys.ts b/client/src/lib/composerKeys.tsnew file mode 100644index 00000000..140cb2c1--- /dev/null+++ b/client/src/lib/composerKeys.ts@@ -0,0 +1,26 @@+/**+ * The key rule every message box shares (the hire composer, the chat+ * composer): which Enter sends. Kept apart from the components so their+ * files export components only (react-refresh) and the rule is testable on+ * its own.+ */++import type { KeyboardEvent } from 'react';++type SendKeyEvent = Pick<KeyboardEvent, 'key' | 'shiftKey'> &+ Partial<Pick<KeyboardEvent, 'ctrlKey' | 'metaKey' | 'altKey'>> & {+ keyCode?: number;+ nativeEvent?: { isComposing?: boolean; keyCode?: number };+ };++/** True for the Enter that should send: a plain Enter, not Shift+Enter (a+ * new line), not Ctrl/Meta/Alt+Enter (the chat's Ctrl/Cmd+Enter belongs to+ * the newest draft waiting for the owner), and not the Enter that confirms+ * an IME composition (`isComposing`, or keyCode 229 on engines that report+ * the composition that way). */+export function isSendKey(event: SendKeyEvent): boolean {+ if (event.key !== 'Enter' || event.shiftKey) return false;+ if (event.ctrlKey || event.metaKey || event.altKey) return false;+ if (event.nativeEvent?.isComposing) return false;+ return (event.keyCode ?? event.nativeEvent?.keyCode) !== 229;+}diff --git a/client/src/features/home/ui/useAutoGrow.ts b/client/src/lib/useAutoGrow.tssimilarity index 93%rename from client/src/features/home/ui/useAutoGrow.tsrename to client/src/lib/useAutoGrow.tsindex 508e37d4..33945482 100644--- a/client/src/features/home/ui/useAutoGrow.ts+++ b/client/src/lib/useAutoGrow.ts@@ -1,8 +1,8 @@/*** Grow a textarea with its text up to its CSS max-height, then scroll.* Runs on every value change, so text set from outside (a template, a- * suggestion) sizes the box too. Shared by the hire composer and the- * message box on an employee's page.+ * suggestion) sizes the box too. Shared by the hire composer and the chat+ * composer.*/import { useLayoutEffect, type RefObject } from 'react';diff --git a/client/src/themes/atomic.css b/client/src/themes/atomic.cssindex 08763292..5836e248 100644--- a/client/src/themes/atomic.css+++ b/client/src/themes/atomic.css@@ -241,7 +241,7 @@/* Chat */:root[data-theme="atomic"] .chat-msg { border-radius: 14px 4px 14px 4px; border-width: 2px; }:root[data-theme="atomic"] .chat-msg-user { background: var(--mustard); color: var(--slate); border-color: var(--slate); }-:root[data-theme="atomic"] .chat-msg-bot { background: var(--turquoise); color: var(--bg-elevated); border-color: var(--slate); }+:root[data-theme="atomic"] .chat-msg-bot { padding: 8px 12px; background: var(--turquoise); color: var(--bg-elevated); border-color: var(--slate); }/* Status bar */:root[data-theme="atomic"] .statusbar {diff --git a/client/src/themes/cyber.css b/client/src/themes/cyber.cssindex b9e3a77b..c66ab1a4 100644--- a/client/src/themes/cyber.css+++ b/client/src/themes/cyber.css@@ -722,6 +722,7 @@}:root[data-theme="cyber"] .chat-msg-user::before { content: '> USER:: '; opacity: 0.6; }:root[data-theme="cyber"] .chat-msg-bot {+ padding: 8px 12px;background: rgba(29, 217, 229, 0.08);color: var(--neon-cyan);border: 1px solid var(--neon-cyan);diff --git a/client/src/themes/edo.css b/client/src/themes/edo.cssindex dbcd6313..ecf7c7f9 100644--- a/client/src/themes/edo.css+++ b/client/src/themes/edo.css@@ -233,7 +233,7 @@/* Chat */:root[data-theme="edo"] .chat-msg { border-radius: 0; }:root[data-theme="edo"] .chat-msg-user { background: transparent; border: 1px solid var(--accent); }-:root[data-theme="edo"] .chat-msg-bot { background: var(--bg-elevated); border-left: 3px solid var(--sumi); border-top: none; border-right: none; border-bottom: none; }+:root[data-theme="edo"] .chat-msg-bot { padding: 8px 12px; background: var(--bg-elevated); border-left: 3px solid var(--sumi); border-top: none; border-right: none; border-bottom: none; }/* Status bar */:root[data-theme="edo"] .statusbar {diff --git a/client/src/themes/greek.css b/client/src/themes/greek.cssindex 512dc769..5eb64862 100644--- a/client/src/themes/greek.css+++ b/client/src/themes/greek.css@@ -275,7 +275,7 @@/* Chat */:root[data-theme="greek"] .chat-msg { border-radius: 0; }:root[data-theme="greek"] .chat-msg-user { background: var(--info-soft); border: 2px solid var(--accent); }-:root[data-theme="greek"] .chat-msg-bot { background: var(--bg-elevated); border: 2px solid var(--border-default); }+:root[data-theme="greek"] .chat-msg-bot { padding: 8px 12px; background: var(--bg-elevated); border: 2px solid var(--border-default); }/* Status bar */:root[data-theme="greek"] .statusbar {diff --git a/client/src/themes/plague.css b/client/src/themes/plague.cssindex 94a11242..87828463 100644--- a/client/src/themes/plague.css+++ b/client/src/themes/plague.css@@ -239,7 +239,7 @@/* CHAT */:root[data-theme="plague"] .chat-msg-user { background: var(--danger-soft); border: 1px solid var(--accent); border-radius: 0; }-:root[data-theme="plague"] .chat-msg-bot { background: var(--linen); border: 1px solid var(--crow); border-radius: 0; }+:root[data-theme="plague"] .chat-msg-bot { padding: 8px 12px; background: var(--linen); border: 1px solid var(--crow); border-radius: 0; }/* STATUS BAR */:root[data-theme="plague"] .statusbar {diff --git a/client/src/themes/renaissance.css b/client/src/themes/renaissance.cssindex abf1bc9b..ab5b5d7f 100644--- a/client/src/themes/renaissance.css+++ b/client/src/themes/renaissance.css@@ -617,6 +617,7 @@border: 1px solid var(--border-strong);}:root[data-theme="renaissance"] .chat-msg-bot {+ padding: 8px 12px;background: var(--bg-elevated);border: 1px solid var(--border-default);position: relative;diff --git a/client/src/themes/rot.css b/client/src/themes/rot.cssindex 78238c4b..df589df1 100644--- a/client/src/themes/rot.css+++ b/client/src/themes/rot.css@@ -233,7 +233,7 @@/* CHAT */:root[data-theme="rot"] .chat-msg-user { background: var(--success-soft); border: 1px solid var(--accent); }-:root[data-theme="rot"] .chat-msg-bot { background: var(--bg-elevated); border-left: 2px solid var(--candle); }+:root[data-theme="rot"] .chat-msg-bot { padding: 8px 12px; background: var(--bg-elevated); border-left: 2px solid var(--candle); }/* STATUS BAR */:root[data-theme="rot"] .statusbar {diff --git a/client/src/themes/steampunk.css b/client/src/themes/steampunk.cssindex 259a6ebe..a059dad3 100644--- a/client/src/themes/steampunk.css+++ b/client/src/themes/steampunk.css@@ -252,7 +252,7 @@/* Chat */:root[data-theme="steampunk"] .chat-msg-user { background: rgba(216,168,72,0.16); border: 1px solid var(--accent); color: var(--accent); }-:root[data-theme="steampunk"] .chat-msg-bot { background: var(--bg-elevated); border: 1px solid var(--copper); }+:root[data-theme="steampunk"] .chat-msg-bot { padding: 8px 12px; background: var(--bg-elevated); border: 1px solid var(--copper); }/* Status bar — gauge readout */:root[data-theme="steampunk"] .statusbar {diff --git a/client/src/themes/surveillance.css b/client/src/themes/surveillance.cssindex d0b1c0ab..94dd7cf1 100644--- a/client/src/themes/surveillance.css+++ b/client/src/themes/surveillance.css@@ -253,7 +253,7 @@/* CHAT */:root[data-theme="surveillance"] .chat-msg { border-radius: 0; }:root[data-theme="surveillance"] .chat-msg-user { background: var(--bg-panel); border: 1px solid var(--primary); }-:root[data-theme="surveillance"] .chat-msg-bot { background: var(--bg-elevated); border-left: 3px solid var(--phosphor); border-top: 1px solid var(--border-default); border-right: 1px solid var(--border-default); border-bottom: 1px solid var(--border-default); }+:root[data-theme="surveillance"] .chat-msg-bot { padding: 8px 12px; background: var(--bg-elevated); border-left: 3px solid var(--phosphor); border-top: 1px solid var(--border-default); border-right: 1px solid var(--border-default); border-bottom: 1px solid var(--border-default); }/* STATUS BAR */:root[data-theme="surveillance"] .statusbar {diff --git a/client/src/themes/wasteland.css b/client/src/themes/wasteland.cssindex 79de5925..e17c33b1 100644--- a/client/src/themes/wasteland.css+++ b/client/src/themes/wasteland.css@@ -237,7 +237,7 @@/* CHAT */:root[data-theme="wasteland"] .chat-msg { border-radius: 0; }:root[data-theme="wasteland"] .chat-msg-user { background: var(--info-soft); border: 1px solid var(--accent); }-:root[data-theme="wasteland"] .chat-msg-bot { background: var(--bg-elevated); border: 1px solid var(--rust); }+:root[data-theme="wasteland"] .chat-msg-bot { padding: 8px 12px; background: var(--bg-elevated); border: 1px solid var(--rust); }/* STATUS BAR */:root[data-theme="wasteland"] .statusbar {diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.mdindex cd68a792..0946cc75 100644--- a/docs-internal/chat_protocol.md+++ b/docs-internal/chat_protocol.md@@ -8,14 +8,15 @@ event model and ordering ([events](https://docs.ag-ui.com/concepts/events),snake_case fields in the repo's CloudEvents envelope (`services/events/envelope.py`), never as literal camelCaseAG-UI JSON.-Status: being built on `feature/chat-genui`; the design and the owner's decisions are in the plan recorded at+Status: being built in phases on `main`; the design and the owner's decisions are in the plan recorded at`~/.claude/plans/analyze-the-new-generative-zazzy-cosmos.md`. Change this document in the same commit as any changeto the shapes below, and bump `protocol_version` (returned by `get_chat_messages`) when an existing field changesmeaning.Built so far: runs and their storage, the lifecycle events (`started`, `finished`, `failed`), subscriptions,-`get_chat_messages` v2, `get_chat_run`, the watchdog and the MachinaWorkflow patch (see [Runs](#runs)). Every other-event, handler and part below is the contract the later phases build to.+`get_chat_messages` v2 (with each message's `run`), `get_chat_run`, the watchdog and the MachinaWorkflow patch (see+[Runs](#runs)), and the shared chat UI on both hosts (see [Client](#client)). Every other event, handler and part+below is the contract the later phases build to.## Concepts@@ -168,7 +169,8 @@ summary adds `kind` (`gate` or `tool_call`), `node_type`, `tool_name`, `tool_cal```{id, legacy_id, role, kind, text, message, timestamp, run_key, run_id, parent_id, status, attachments,- parts, feedback, siblings: {index, count, ids}, editable, client_message_id?}+ parts, feedback, siblings: {index, count, ids}, editable, client_message_id?,+ run?: {run_id, state, outcome, error?: {message, code, hint?}}}```- `id` is the message's stable id (`m_…` for the owner's, `a_<run id>` for a run's reply; rows saved before chat@@ -176,6 +178,9 @@ summary adds `kind` (`gate` or `tool_call`), `node_type`, `tool_name`, `tool_cal- `message` equals `text`; it is kept for older readers.- `client_message_id` is echoed on the owner's messages that carried one, so an optimistic row and its saved rowkeep one key.+- `run` says how the run a message started (or answers) stood when the thread was read: its `state`, `outcome`, and+ for a failed run the error with the hint the run recorded. It is how a reload still shows that a message went+ unanswered; while the session is subscribed, the run's events are fresher (see [Client](#client)).- Until branches land, `siblings` always holds the message alone and `editable` is false.- `kind`: `text`, `report` (Post to Talk: no parent, not editable), `action` (a button press), `notice`.- `status`: `complete`, `stopped`, `error`.@@ -254,6 +259,38 @@ Approvals are joined live from the approvals store; the part only names them.ends the runs nothing will finish (codes above). A pending run's wait (`runs.pickup_timeout_s`) counts from thelater of its creation and the server's start.+## Client++`client/src/features/chat/` is the shared chat; only its `index.ts` is public (an ESLint rule keeps the rest+private, tests excepted). Hosts give it a `ChatHost` (`host.ts`): the session and scope, who answers, whether the+message box sends now, waits for Resume or is closed, and what sits around the conversation (notices, a top slot, a+slot after the thread, a footnote, how to tell the owner something). Home's employee page (`EmployeeChat`) and the+editor's console pane (`ConsoleChat`, compact, scope `live`) are the two hosts.++- **Run events** reach `stores/chatRunStore.ts` through one `case 'chat_run_event'` in `WebSocketContext.tsx`.+ `lib/agui/events.ts` checks each frame (source, type prefix, `subject`, `id` = `<run id>:<seq>`, scope fields) and+ `lib/agui/reduceRun.ts` folds it, the same way `services/chat/reducer.py` does. Frames are folded once per+ animation frame. Per run: a duplicate `seq` changes nothing; a gap, an unknown run already past `seq` 1, a new+ `hub_epoch` or the hub's resync frame mark the session `syncing`, hold what arrives meanwhile, and ask for a fresh+ snapshot, after which the held frames fold in and the ones the snapshot covers drop out.+- **Subscribing** (`data/runs.ts`): a mounted chat subscribes its session whenever the socket is ready (so again+ after every reconnect) and whenever the store asks for a snapshot, retrying a failed subscribe after 1, 3, then+ every 10 seconds; the last chat following a session unsubscribes it. Runs the store held as live that a snapshot+ no longer lists ended unseen and are read once with `get_chat_run`. Until the first snapshot the thread's own+ `active_runs` stand in; after it the store alone says which runs are live, and a message whose `run` still reads+ live is read with `get_chat_run` (`useThreadRunReconcile`).+- **Turns** (`thread/model.ts`): one per message with a divider where `run_key` changes. A run that is going,+ failed or was stopped shows on its last answer, or on a turn of its own right after its last message before it+ has answered (a live run whose messages are out of view goes last). Failures whose code only says no answer came+ (`not_delivered`, `timed_out`, `interrupted`) disappear once an answer lands; `reset` and `cleared` never show. A+ message sent from this tab and its saved row share a key (its `client_message_id`), and a run's first answer takes+ the key its run's turn had, so neither remounts.+- **Sending** (`data/send.ts`): the message shows at once; the server's answer admits its run into the store+ (`queued` or `pending`), so the employee shows working before the run's first event. While the lane is held, Send+ waits. A refused or failed send takes the message out of the thread and puts its text back in the box+ (`state/composerStore.ts`, a draft per session that survives switching conversations); after a failure in transit+ the draft keeps its `client_message_id`, so sending it again is the same message.+## Notes to the employeeThings the employee should learn on its next turn are queued in `chat_notes` and prepended to that turn's userdiff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex bd66d81a..9860a22c 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -63,6 +63,14 @@ client/src/│ ├── shellTransition.ts # The fade-out / swap choreography│ └── useModeShortcut.ts / useCurrentWorkflowSync.ts / usePageActivitySync.ts / useUIDefaultsOnce.ts│+├── features/chat/ # The chat shared by Home's employee page and Dev's console Chat pane+│ │ # (docs-internal/chat_protocol.md#client); only its index.ts is importable (ESLint)+│ ├── ChatPane.tsx / host.ts # The pane, and the ChatHost contract its hosts fill in+│ ├── data/ # Thread query (scope all/live), run subscription, send / clear, conversation+│ ├── state/ # composerStore: what the owner is writing, per session+│ ├── thread/ # model.ts (turns from messages + runs, pure), ChatThread (stick to bottom)+│ └── turns/ composer/ markdown/ # UserTurn / AssistantTurn / StatusLine, the message box, ReplyMarkdown+│├── features/home/ # Normal mode (see docs-internal/normal_mode.md)│ ├── HomeShell.tsx # Sidebar + header + current view + Workspace dock + Settings + orb stage│ ├── sidebar/ header/ hire/ employee/ settings/ approvals/ data/ state/ ui/@@ -87,7 +95,7 @@ client/src/│ │ ├── sonner.tsx # Patched to read ThemeContext (not next-themes)│ │ ├── ApiKeyInput.tsx # Composite: input + eye toggle + save/delete buttons│ │ ├── SettingsPanel.tsx # Shadcn Switch + Slider + Input-│ │ ├── ConsolePanel.tsx # Chat + console + terminal + output+│ │ ├── ConsolePanel.tsx # Chat (ConsoleChat, the shared chat) + console + terminal + output│ │ └── TopToolbar.tsx # File menu + model picker + action buttons│ ││ ├── Modal.tsx (src/components/ui/Modal.tsx)@@ -210,6 +218,7 @@ client/src/│ │ # 1 ms under reduced motion or a hidden page, no loops then│ ├── pageActivity.ts / useReducedMotion.ts # Whether anyone can see the page; the motion preference│ ├── debouncedInvalidate.ts # Trailing-edge query invalidation (broadcast bursts)+│ ├── agui/ # Chat run events: events.ts (checks and types a frame), reduceRun.ts (folds a run)│ ├── jsonRender/ # Generated-UI glue around json-render (hire setup screen, chat replies):│ │ # sanitize (no prototype paths; no watch/repeat/slots/$computed/confirm),│ │ # guard (props through the catalogue schema, live-only entrance),@@ -218,6 +227,7 @@ client/src/├── schemas/workflowSchema.ts # Structural pre-flight for workflow export (backend is the schema authority)├── stores/│ ├── nodeStatusStore.ts # Per-workflow node statuses (slice-subscribed Zustand)+│ ├── chatRunStore.ts # Chat runs per session, folded from `chat_run_event` once per animation frame│ ├── canvasDockStore.ts # Docked Canvas sidebar state│ ├── workflowControlStore.ts # Mirror of workflow control statuses for Home (written from WebSocketContext)│ ├── shellDialogsStore.ts # Settings / Credentials dialog flags (lifted out of Dashboard)@@ -578,7 +588,7 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]| `isCanvasPanel` | `MiddleSection`, `CanvasDock` | Render the pushed-content Canvas board instead of the plain params list. Declared by `canvas`. Double duty: the docked canvas sidebar also uses this flag to FIND Canvas nodes in the graph (`resolveNodeDescription(type)?.uiHints?.isCanvasPanel`) — never the type string. Pairs with an explicit `isConfigNode: False` because the `tool` group would auto-derive `True` while the node's `input-main` is real dataflow. See [canvas_node.md](./canvas_node.md). || `isBrowserPanel` | `MiddleSection`, `CanvasDock` (also the server's `graph_index`) | Show the node's live browser (`BrowserWorkspace`) above its parameters. Declared by `browser`. The Dev dock and Home's employee summary also use it to FIND Browser nodes in a graph, never the type string. See [browser_workspace.md](./browser_workspace.md). || `showLocationPanel` | `LocationParameterPanel` | Special-case panel for nodes with map preview |-| `isChatTrigger` | `ConsolePanel` | This node is a chat-message target |+| `isChatTrigger` | (none) | This node is a chat-message target. No client reader since the console's trigger selector went: the Chat pane sends to every chat trigger of the open workflow. || `isConsoleSink` | `ConsolePanel` | This node consumes console output (filter source) || `hasSkills` | Agent panels | Connect the connected-skills section || `isConfigNode` | `InputSection`, `OutputPanel` | This node is auxiliary configuration — its panel inherits the parent's main inputs instead of showing direct upstream connections. **Auto-derived on the backend** by `_derive_auto_ui_hints` in [`server/services/plugin/base.py`](../server/services/plugin/base.py): plugins whose `group` tuple contains `memory` or `tool` get this for free. Explicit `cls.ui_hints` always wins. |diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex 8d098561..edb2353b 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -68,12 +68,12 @@ is the reference.| `sidebar/`, `header/` | The team list, New employee, the profile row; the view title, the Workspace pill, the mode toggle (on an employee's page, Dev opens their workflow) and the theme button || `hire/` | The hero, the composer, the template chips, the hire notice (`HireNotice.tsx`), and the starter bundles (`starters.json`), which the chips and Settings > Plugins both read || `genui/` | The setup draft under the composer, and the hire itself, from a setup or a starter (below) |-| `employee/` | One employee's page, which is the conversation with them: only their name under a small orb, then Talk (below). What to act on shows in the conversation only while there is something to do: the drafts waiting for the owner after the messages, and above the message box their main action while they can't read messages (Resume, Start, or connect what is missing; `useEmployeeControl`, `PrimaryActionButton`) or Help in browser while they wait there. It never says why they stopped. Pausing them, and watching them work, is the Workspace's: the header's Workspace pill opens it on the employee on screen, and its header carries the same main action |+| `employee/` | One employee's page, which is the conversation with them (`EmployeeChat` over the shared chat, Talk below); the header names them. What to act on shows only while there is something to do: the drafts waiting for the owner after the conversation, and above the message box their main action while they can't read messages (Resume, Start, or connect what is missing; `useEmployeeControl`, `PrimaryActionButton`) or Help in browser while they wait there. Pausing them, and watching them work, is the Workspace's: the header's Workspace pill opens it on the employee on screen, and its header carries the same main action || `connectAI/` | The guided Connect an AI model dialog (below) || `workspace/` | The Workspace dock (below), its header pill, and its Canvas tab, which loads in its own chunk || `settings/` | Settings pages (Profile, Billing, Skills, Connectors, Plugins). Catalog primitives live in `components/catalog`; Connectors embeds the shared `components/credentials/CredentialsBrowser`. Provider dialogs belong to AppShell. || `approvals/` | The drafts query, the decide mutation (optimistic), the approval broadcast listener |-| `data/` | zod-parsed queries for employees, connectors and the profile; `employeeCache.ts`, the team's query keys and `removeEmployee` (shared with the app store's delete); `talk.ts`, the thread and its mutations; `presentation.ts` maps server state to pills, actions and the message box's mode without deriving new rules |+| `data/` | zod-parsed queries for employees, connectors and the profile; `employeeCache.ts`, the team's query keys and `removeEmployee` (shared with the app store's delete); `talk.ts`, Turn on Talk, Apply and the retry note (the thread itself is the shared chat's); `presentation.ts` maps server state to pills, actions and the message box's mode without deriving new rules || `orb/` | The 3D orb (below) || `ui/` | Small shared pieces (avatar, status dot and pill, app mark), the pill toast, and `useAutoGrow` (the composer's and the message box's growing text area) || `state/homeStore.ts` | UI state only: the view, the sidebar, Settings, the Connect an AI model dialog, the last hire's notice, the Workspace dock, one-shot glow and pulse signals |@@ -421,59 +421,78 @@ will finish. The wire contract is [chat_protocol.md](./chat_protocol.md).### On the employee's page-[employee/EmployeeTalk.tsx](../client/src/features/home/employee/EmployeeTalk.tsx)-sits under the name: the thread, then a message box pinned to the bottom of-the page (`HomeShell`'s scroll area is a column the view fills). Its queries-and mutations are in [data/talk.ts](../client/src/features/home/data/talk.ts).+[employee/EmployeeChat.tsx](../client/src/features/home/employee/EmployeeChat.tsx)+is the page: the shared chat ([features/chat](../client/src/features/chat/),+the same `ChatPane` the editor's console Chat pane uses) with Home around it.+The header names the employee instead of the page (`HomeHeader`: avatar,+name, role and apps, the status pill, and New conversation), and `HomeShell`+gives the page a column that does not scroll: the conversation scrolls on its+own above the message box, and tells the shell when it has left the top so the+header draws its border. Turn on Talk and Apply are in+[data/talk.ts](../client/src/features/home/data/talk.ts); the thread, runs,+sending and drafts belong to the chat (wire and client rules in+[chat_protocol.md](./chat_protocol.md#client)).- **The thread** is `get_chat_messages` with `all_generations: true` (the- newest `THREAD_LIMIT` messages): the conversation since the employee last- started, since a Reset clears it (see [Turn on Talk and Apply](#turn-on-talk-and-apply)).- Where a message's `run_key` (its generation) differs from the one before- (a message left from before a Start, such as a test run in Dev mode), a- divider reads "{Name} restarted — they start fresh from here". Both sides- are one bubble, the same raised surface, border and type in every theme;- only the side (the owner's on the right, answers on the left beside the- avatar) and the corner that points at the speaker differ. Answers render- as markdown (`ThreadMarkdown`, in its own chunk). The bubbles carry- `chat-msg-user` / `chat-msg-bot`, the theme hooks the editor's chat pane- uses too. Times, "Working…" and the divider share the body font. An empty- thread is just the box. The list is an `aria-live` log. It refetches on- `chat.updated`, after a runtime reset, and when the socket reopens. The- drafts waiting for the owner's OK follow the messages (`EmployeeTalk`'s- `drafts`).+ newest 200 messages): the conversation since the employee last started,+ since a Reset clears it (see [Turn on Talk and Apply](#turn-on-talk-and-apply)).+ The orb sits at its top (`min(96px, 14vh)`), a new hire's notes under it.+ Where a message's `run_key` (its generation) differs from the one before (a+ message left from before a Start, such as a test run in Dev mode), a divider+ reads "{Name} restarted — they start fresh from here". The owner's messages+ are bubbles on the right; answers have no bubble, beside the employee's+ avatar on the left, as markdown (`ReplyMarkdown`, in its own chunk, with the+ theme's code colours). The turns are an `aria-live` log; the thread starts+ at the newest turn and stays there while new ones arrive, and scrolled up a+ "Jump to latest" button counts them. It refetches on `chat.updated`, after a+ runtime reset, and when the socket reopens. The drafts waiting for the+ owner's OK follow the conversation (the host's `afterThread`).+- **Working** follows the run the message started, not timers: from the+ moment the server admits it, the avatar spins its ring and skeleton lines+ stand where the answer will be, with "Working…" under them, until that run+ ends, whatever else lands meanwhile (a routine report does not end it). A+ run that failed says so where the answer would be ("{Name} didn't pick up+ this message.", "…took too long to answer.", or "{Name} couldn't answer."+ with the error and its hint), also after a reload; a late answer replaces a+ failure that only said none came. While the talk agent waits to retry after+ a failed attempt, its retry message sits on the status line+ (`useRetryNote`, from the agent's node status).- **The box** follows the control state the way `send_chat_message` does(`talkMode` in `presentation.ts`):- *send* (running, starting, resuming): a message shows at once- ("Sending…") and goes to the employee. "Working…" then holds the box- until an answer arrives. `useReplyWait` follows the talk agent's node- status in `nodeStatusStore` (for any workflow, not only the one open in- Dev mode) and gives up after `PICKUP_WAIT_MS` if the agent never starts,- `REPLY_WAIT_MS` while it works, or `SETTLE_WAIT_MS` after it stops, then- says "No answer from {Name} yet." Holding the box matters: overlapping- runs would each save over the other's conversation.+ ("Sending…") and goes to the employee; Send then waits until the run+ ends, since overlapping runs would each save over the other's+ conversation (the server refuses a second message with+ `run_in_progress`).- *queue* (paused, pausing): one message waits for Resume ("Your message is- waiting…"), and the box holds until the employee runs again.+ waiting…" above the box, "Waiting for you to resume {Name}." in the+ thread), and Send waits until it has been answered.- *start* (never started, ready, resetting, failed): no box; a line says- they can't read messages, beside their main action (Start, or what they- are missing), which the Workspace header offers too.+ they can't read messages, beside their main action (Start, Start again,+ or what they are missing), which the Workspace header offers too.- While the agent waits for the owner in the browser, the server's linefor it ("Needs you to sign in to a site in the browser") sits above the- box beside Help in browser.- - A refused message leaves the thread and its text goes back in the box;- `not_running` (the state moved meanwhile) says "{Name} isn't running" and- refetches the team.+ box beside Help in browser; after a run of failures paused them, why.+ - What the owner writes is kept per conversation, so switching to another+ employee and back keeps it. A refused message leaves the thread and its+ text goes back in the box: `not_running` (the state moved meanwhile) says+ "{Name} isn't running" and refetches the team; `run_in_progress` says+ they are still working on the last message.+- **New conversation** (the header) asks first, then clears the thread and+ what the employee remembers of it (`clear_chat_messages`).- **Turn on Talk**: an employee whose `talk.state` is `off` (hired before- Talk, or built in Dev mode) shows Turn on Talk instead of the thread. An- `AlertDialog` confirms first, since it restarts them, and says so when drafts- are waiting (a restart cancels them). `unsupported` gets a note that their- setup has no way to answer.+ Talk, or built in Dev mode) shows Turn on Talk where the box would be. An+ `AlertDialog` confirms first, since it restarts them, and says so when+ drafts are waiting (a restart cancels them). `unsupported` gets a note that+ their setup has no way to answer. Either way their main action still shows+ while they are not running, beside a line that says only their state+ ("{Name} isn't running.", "{Name} is paused."; `stateNoticeText`).- **Pending changes**: while `pending_changes` is true, a notice above the boxreads "{Name} has new abilities for this conversation. Apply to make thempart of all their work (restarts {name} and clears this conversation)."Its Apply (`ActionButton intent="config"`) calls`apply_employee_changes`.-- **Asking first**: under the page, a line says whether the employee asks+- **Asking first**: under the box, a line says whether the employee asksbefore sending anything on the owner's behalf (the summary's `asks_first`).### The talk line@@ -770,8 +789,10 @@ history). Talk and growing a saved employee: `tests/services/employees/``tests/services/test_workflow_deletion_shutdown.py`,`tests/services/test_workflow_context_archive_outbox.py` (a late save or readcannot re-create a deleted workflow). Client:-`features/home/**/__tests__` (including `talk.test.tsx`, `thread.test.ts`,-`connectAI.test.tsx`), `app/__tests__`,+`features/home/**/__tests__` (including `employeeChat.test.tsx`,+`homeHeader.test.tsx`, `connectAI.test.tsx`), `features/chat/__tests__` (the+shared chat: turns, drafts, the pane against a fake server),+`stores/__tests__/chatRunStore.test.ts`, `lib/agui/__tests__`, `app/__tests__`,`contexts/__tests__/themePrePaint.test.ts`,`contexts/__tests__/webSocketActions.test.tsx` (`chat.updated`, the editorchat's rollback), `lib/__tests__/workflowOps.test.ts` anddiff --git a/docs-internal/theme_system.md b/docs-internal/theme_system.mdindex efd1aaba..622da390 100644--- a/docs-internal/theme_system.md+++ b/docs-internal/theme_system.md@@ -326,7 +326,8 @@ Wave 15 added structural classNames across the React tree so the handoff CSS sel| Top toolbar | `.toolbar` | TopToolbar || Sidebar | `.sidebar` | WorkflowSidebar || Component palette | `.palette` | ComponentPalette |-| Console / chat panel | `.chat`, `.chat-msg`, `.chat-msg-user`, `.chat-msg-bot` | ConsolePanel |+| Console / chat panel | `.chat` | ConsolePanel (root) |+| Chat turns (Home and Dev) | `.chat-msg .chat-msg-user` on the owner's bubble; `.chat-msg .chat-msg-bot` on a reply's text only; `.chat-turn-user`, `.chat-turn-bot` on each turn; `.chat-composer` on the message box | features/chat (`UserTurn`, `AssistantTurn`, `Composer`) || Status bar | `.statusbar`, `.pip` (connection dot) | StatusBar || Modal | `.modal`, `.modal-frame`, `.modal-head` | Modal || Collapsible section | `.cat`, `.cat-head`, `.cat-body` | CollapsibleSection |@@ -345,6 +346,8 @@ Wave 15 added structural classNames across the React tree so the handoff CSS selThe `.selected` co-class is bound to React Flow's `selected` prop on every canvas node component, activating per-theme selection effects (Cyber `cyber-blink`, Edo hanko seal, Renaissance wax-seal stamp, etc.).+A reply has no bubble in light and dark (design handoff chat): only the owner's message is one. Each stylized theme still paints `.chat-msg-bot` as a bubble, so its rule carries the padding the bare reply lacks (`padding: 8px 12px`); `index.css` keeps the code blocks and tables inside such a bubble free of the theme's text glow.+### Decorative content per theme| Theme | Panel textures | Canvas decoration | Node pseudo overlay | Keyframes |diff --git a/server/tests/test_frontend_no_node_type_copies.py b/server/tests/test_frontend_no_node_type_copies.pyindex 96fc66a4..13b02e32 100644--- a/server/tests/test_frontend_no_node_type_copies.py+++ b/server/tests/test_frontend_no_node_type_copies.py@@ -139,7 +139,6 @@ _BASELINE_VIOLATIONS = frozenset(("client/src/components/parameterPanel/TaskManagerPanel.tsx", "ai_employee"),("client/src/components/parameterPanel/TeamMonitorPanel.tsx", "orchestrator_agent"),("client/src/components/parameterPanel/TeamMonitorPanel.tsx", "ai_employee"),- ("client/src/components/ui/ConsolePanel.tsx", "chatTrigger"),})