Skip to content

Self-improving AI Employees for everyone

docs(chat): generated UI, notes, follow-ups and sources

trohitg32252dbbe91b
diff --git a/CLAUDE.md b/CLAUDE.md
index b5917f6f..f32af1cf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,7 +14,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[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 (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`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Lists every event, handler, part and error code, including the ones later phases build. |
+| **[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`). The agent wired into Reply in Chat (`answers_chat_run`) streams its answer as `text.*` events (`services/chat/stream.py`, activity input only, no workflow patch), its tool calls show as steps (`services/chat/steps.py`; label from the plugin's `chat_step`), and `stop_chat_run` stops a run cooperatively: its LLM step polls the run and returns what was shown, unstarted tools are skipped, the reply is saved `stopped`, and the watchdog cancels a run still stopping after `runs.stop_grace_s`. Generated UI: the `show_ui` tool (`chatUi`) is checked against `config/chat_genui_catalog.json` (`services/genui/spec.py`; refused with every reason so the model retries), saved as a run part, streamed as `activity.*` RFC 6902 patches and sealed into the reply (`services/chat/parts.py`); `chat_ui_state` keeps what the owner set, and a button press comes back as `send_chat_message{ui_event}` -> a `[ui-event]` turn. The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py`), what the owner set reaches its next turn as a `[ui-state]` note (`chat_notes`, `services/chat/notes.py`: claimed by the payload, told when the run answered), a trailing `<followups>` block becomes `parts.followups`, and a `chat_sources` tool's results are numbered per conversation for `[n]` citations (`services/chat/sources.py`). 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). |
| **[Schema Source of Truth RFC](./docs-internal/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |
diff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.md
index 98cdf224..9df3eb97 100644
--- a/docs-internal/chat_protocol.md
+++ b/docs-internal/chat_protocol.md
@@ -16,8 +16,9 @@ meaning.
Built so far: runs and their storage, the lifecycle events (`started`, `finished`, `failed`), subscriptions,
`get_chat_messages` v2 (with each message's `run`), `get_chat_run`, the watchdog and the MachinaWorkflow patch (see
[Runs](#runs)); the answer streaming as text events, working steps and Stop (see [Streaming, steps and
-Stop](#streaming-steps-and-stop)); 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.
+Stop](#streaming-steps-and-stop)); generated UI in replies with its state and button presses (see [Generated
+UI](#generated-ui)); 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
@@ -124,6 +125,7 @@ All are WebSocket request/response handlers with snake_case payloads. Failures a
| `chat_unsubscribe` | `{session_id}` | `{success, session_id, hub_epoch}` |
| `get_chat_run` | `{run_id}` | `{success, run: RunSnapshot}`, or `not_found` |
| `stop_chat_run` | `{run_id}` | `{success, run_id, state: "stopping" \| "stopped"}`; `not_stoppable` (with `state`) for a run that ended otherwise |
+| `chat_ui_state` | `{session_id, part_id, changes: [{path, value}]}` (at most 32; the last value per path wins) | `{success, part_id, state_revision}`; `not_found`, `invalid_request` |
| `edit_chat_message` | `{message_id, text, attachments?, expected_revision}` | `{success, message_id, run_id}` |
| `regenerate_chat_reply` | `{message_id, expected_revision}` | `{success, run_id}` |
| `switch_chat_branch` | `{message_id, target_id, expected_revision}` | `{success, thread}` |
@@ -137,9 +139,10 @@ and run the first call created, and dispatches nothing again.
**RunSnapshot** is the state the client reducer would hold after replaying the run's events
(`server/services/chat/reducer.py` folds them the same way):
`{run_id, session_id, workflow_id, kind, state, seq, hub_epoch, user_message_id, reply_message_id, parent_run_id,
-created_at, started_at, finished_at, steps, segments: [{message_id, text, final}], activities, interrupts, outcome,
-result, error, error_code}`. `state` is `queued`, `pending`, `running`, `stopping`, `finished`, `error` or `stopped`.
-A snapshot read after a server restart has its steps but no text segments (text is stored with the reply).
+created_at, started_at, finished_at, steps, segments: [{message_id, text, final}], activities: [{message_id,
+activity_type, content, patches}], interrupts, outcome, result, error, error_code}`. `state` is `queued`, `pending`,
+`running`, `stopping`, `finished`, `error` or `stopped`. A snapshot read after a server restart has its steps but no
+text segments or activities (those are stored with the reply).
### Approvals (`server/services/approvals/handlers.py`)
@@ -160,7 +163,6 @@ summary adds `kind` (`gate` or `tool_call`), `node_type`, `tool_name`, `tool_cal
| Handler | Owner | Request | Response |
|---|---|---|---|
-| `chat_ui_state` | `nodes/chat/chat_ui` | `{workflow_id, part_id, delta: [{op: "replace" \| "add", path, value}], base_revision}` | `{success, state_revision}` or `stale` |
| `canvas_versions` | `nodes/tool/canvas` | `{workflow_id, node_id, item_id}` | `{success, versions: [{version, title, created_at, source, size_bytes}], latest}` |
| `canvas_version` | `nodes/tool/canvas` | `{workflow_id, node_id, item_id, version}` | `{success, item_id, version, title, content, language, created_at, filename}` |
| `transcribe_audio` | `nodes/speech` | `{workflow_id, audio: FileRef, language?}` | `{success, text, provider, model, duration_seconds}` |
@@ -196,10 +198,10 @@ sources, follow-ups.
```
parts: {
steps?: {duration_ms, items: [{step_id, name, state, detail?, duration_ms?}]},
- ui?: [{part_id, ui_id, title?, spec, state, state_revision, elements}],
+ ui?: [{part_id, spec, state, state_revision, elements}],
artifacts?: [{workflow_id, canvas_node_id, item_id, version, title, format}],
approvals?: [{approval_id, tool_call_id?}],
- sources?: [{n, display, label, detail?, url?, kind, cited}],
+ sources?: [{n, title, url, detail?}],
followups?: [string],
stopped?: true
}
@@ -207,19 +209,36 @@ parts: {
Approvals are joined live from the approvals store; the part only names them.
+A run's tools record parts on the run as they go (`chat_run_parts`, keyed so a retried activity writes the same
+row; `services/chat/parts.py`). Reply in Chat saves its reply with the parts recorded so far, and the run's end seals
+any later ones into it, creating an empty-text reply when the run showed an interface but wrote nothing (sources
+alone make none: they show only where a reply cites them); the end is published after the seal, so its
+`result.reply_message_id` names a reply that holds them.
+
## Generated UI
-- **Source.** The employee calls the `show_ui` tool (`chatUi` plugin) with a json-render flat spec
- `{root, state, elements}`. The server validates it against `server/config/chat_genui_catalog.json`, the single
- source of truth for the client catalog, and streams it as `activity.snapshot` (empty spec) followed by one
- `activity.delta` per patch: `add /root`, `add /state`, then `add /elements/<id>` in depth-first order.
-- **Owner edits.** `$bindState` writes stay in the message's local state and are sent with `chat_ui_state`; the last
- write per path wins, and the client flushes after 300 ms idle, on blur, before an action and when the page hides.
- The employee sees the state on its next turn as a `[ui-state]` note.
-- **Buttons.** A press resolves `$state` params at click time. `ask` sends its text as the owner's message only when
- it equals the button's label; otherwise the text goes into the composer for review. Any other action becomes
- `send_chat_message{ui_event}`; the server checks it against the saved spec and starts a run of kind `action`
- whose turn carries `[ui-event]{…}[/ui-event]`.
+- **Source.** The employee calls the `show_ui` tool (`chatUi` plugin, `nodes/chat/chat_ui`) with a json-render flat
+ spec `{root, state, elements}`. `services/genui/spec.py` checks it against `server/config/chat_genui_catalog.json`
+ (JSON Schema per component, which prop each input binds, what each layout may hold, the limits): a spec that
+ breaks a rule fails the call with every reason, so the model writes it again; unknown types, unreachable elements,
+ stray fields and props are left out and reported back. The tool's description is generated from the same manifest,
+ byte for byte the same for the same file, and a test on each side reads the other's catalogue. The checked spec is
+ saved as a `ui` part and streamed as `activity.snapshot` (empty spec) followed by one `activity.delta` per patch:
+ `add /root`, `add /state`, then `add /elements/<id>` in depth-first order (`services/genui/patches.py`, matching
+ the handoff's `*.patches.jsonl` line for line). Only the agent answering the owner's chat message can show UI; a
+ call anywhere else says nothing was shown.
+- **Owner edits.** `$bindState` writes go to the interface's own state store and to `chat_ui_state`; the last write
+ per path wins, and the client sends after 300 ms idle, when the page hides, when the chat closes and before a
+ button press goes (`features/chat/data/uiState.ts`). The server keeps them on the part (`state`,
+ `state_revision`), on the reply once it is saved, so a reload shows them.
+- **Buttons.** A press resolves `$state` params at click time; the client tags each press with its element and label
+ (json-render hands a handler the params only). `ask` sends its text as the owner's message only when it is what
+ the button says (case and spacing aside); otherwise the text goes into the composer for review. Any other action
+ becomes `send_chat_message{ui_event: {part_id, element_id, action, params}}`: the server checks it against the
+ saved spec (a Button whose press runs that action, params it declares), saves the owner's message as the button's
+ label (`kind: "action"`, the press in `meta.ui_event`), starts a run of kind `action`, and sends the employee the
+ line `[ui-event]{"ui_id", "element", "label", "action", "params"}[/ui-event]`. A press while the employee is still
+ answering is held back with a notice. `ui_event_rejected` says why one does not fit.
- **Sanitising.** json-render 0.21 does not guard state paths (`setByPath` descends into `__proto__`), does not
validate props against the catalog, and supports `watch` (actions fired by state changes), `repeat`, `$computed`
and an action binding's `confirm`, `onSuccess` and `onError` (the last two set state or run further actions).
@@ -339,13 +358,50 @@ editor's console pane (`ConsoleChat`, compact, scope `live`) are the two hosts.
until its saved reply lands in the thread, so the streamed answer and the reply stay one element.
- **Stop** (`data/stop.ts`): the Stop button, or Esc anywhere in the pane, sends `stop_chat_run` for the lane's run
and applies the answer to the store at once; the run's events take it from there.
+- **Generated UI** (`features/chat/genui/`, `turns/GeneratedUiBlock.tsx`): a reply's interfaces come from its saved
+ `parts.ui`, or while the run streams them from its `json_render` activities (`data/parts.ts`), the run's first turn
+ keeping them until the saved reply carries them, so one element shows throughout and keeps what the owner set. The
+ renderer (`genui/ChatUi.tsx`, with json-render, in its own chunk) sanitizes again (`genui/prepare.ts`), draws the
+ twelve components (`genui/views.tsx`, through `lib/jsonRender/guard.tsx`), reveals a live one element by element
+ (forward only, so patches arriving in bursts never restart it), and routes any button action (`genui/actions.ts`,
+ a Proxy over action names). Development builds show the element and patch counts and an Inspect view.
## Notes to the employee
-Things the employee should learn on its next turn are queued in `chat_notes` and prepended to that turn's user
-message in brackets: `[updates]` (approval outcomes), `[ui-state]`, `[feedback]`. The agent's system prompt says that
-bracketed lines come from OpenCompany, not from the owner. Notes are claimed when the next run's payload is prepared
-and marked delivered when its conversation is saved, so a failed run offers them again.
+Things the employee should learn on its next turn are kept in `chat_notes` (`services/chat/notes.py`) and put ahead
+of that turn's user message, one bracketed line each. Built: `[ui-state]{"ui_id", "state"}[/ui-state]`, written by
+`chat_ui_state` for what the owner set without pressing anything; later phases add `[updates]` (approval outcomes)
+and `[feedback]`. A note is keyed per session (`ui-state:<part id>`), so a newer one replaces an older one not yet
+told. `agent.prepare_payload` claims the session's untold notes for the agent answering a run (the one with a
+`chat_stream`); the run's end marks them told when it answered (it finished, or it stopped having written
+something), so a run that failed or stopped before writing offers them again, and a note changed after its claim stays
+untold. Clearing the chat forgets them.
+
+The answering agent's system prompt ends with a fixed guide (`services/chat/guide.py` `CHAT_REPLY_GUIDE`, byte for
+byte the same on every turn): bracketed lines come from OpenCompany, not from the owner; a search result numbered
+n is cited as `[n]`; and how to suggest follow-ups.
+
+## Follow-ups
+
+The answering agent may end its reply with `<followups>["…", "…"]</followups>` (a list of lines works too). The
+stream holds the block back; Reply in Chat takes it off the reply (`guide.split_followups`: the last block, at most
+3 suggestions, 160 characters each, repeats dropped) and saves the suggestions as `parts.followups`. Outside a chat
+run the block is dropped, and a message that is only the block posts nothing. The chat shows them as buttons under
+the latest answer only, once it is done; one sends its text as the owner's message, or waits in the box while an
+answer is still coming.
+
+## Sources
+
+A plugin that declares `chat_sources` (the web searches) returns `results` with addresses. When the answering
+agent calls it, `BaseNode.as_activity` numbers them for the conversation (`services/chat/sources.py`: the session's
+counter `chat_threads.next_source`, so a number never repeats in a conversation and an older `[n]` keeps meaning
+what it did), writes `n` on each result the model reads, and saves `{n, title, url, detail?}` (at most 10 per call)
+as a `sources` part of the run; the reply carries them as `parts.sources`. The guide tells the agent to cite what it
+relies on as `[n]`. The client numbers a reply's sources 1, 2, ... in the order its text first cites them
+(`markdown/citations.ts`): each `[n]` outside code reads as a chip with that number and a tooltip naming the
+source, and the cited sources are listed under the answer (`turns/SourceChips.tsx`); sources it did not cite are
+not shown. A reply may cite a source an earlier search found: each answer resolves `[n]` against the conversation's
+sources up to it (`thread/model.ts`, `ChatTurn.sources`).
## Fixtures
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 9860a22c..d5664520 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -66,10 +66,14 @@ client/src/
├── 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
+│ ├── data/ # Thread query (scope all/live), run subscription, send / stop / clear, parts,
+│ │ # UI state sync, 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
+│ ├── genui/ # Generated UI in replies: catalog (parity with server/config/chat_genui_catalog.json),
+│ │ # views, registry, ChatUi (lazy, with json-render), prepare, actions
+│ └── turns/ composer/ markdown/ # UserTurn / AssistantTurn / StepsDisclosure / GeneratedUiBlock / 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
diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.md
index dd377c38..7a1091a8 100644
--- a/docs-internal/node-logic-flows/README.md
+++ b/docs-internal/node-logic-flows/README.md
@@ -97,6 +97,7 @@ that a retired node remains registered.
- [Chat History (`chatHistory`)](./chat_utility/chatHistory.md)
- [Reply in Chat (`chatReply`)](./chat_utility/chatReply.md)
+- [Show UI (`chatUi`)](./chat_utility/chatUi.md)
- [Chat Send (`chatSend`)](./chat_utility/chatSend.md)
- [Console (`console`)](./chat_utility/console.md)
- [File Handler (`fileHandler`)](./chat_utility/fileHandler.md)
diff --git a/docs-internal/node-logic-flows/chat_utility/chatUi.md b/docs-internal/node-logic-flows/chat_utility/chatUi.md
new file mode 100644
index 00000000..40e702b3
--- /dev/null
+++ b/docs-internal/node-logic-flows/chat_utility/chatUi.md
@@ -0,0 +1,125 @@
+# Show UI (`chatUi`)
+
+| Field | Value |
+|------|-------|
+| **Category** | chat_utility (group `("chat", "tool")`) |
+| **Backend handler** | [`server/nodes/chat/chat_ui/__init__.py`](../../../server/nodes/chat/chat_ui/__init__.py) — `ChatUiNode`; dispatch via `BaseNode.execute()` + `@Operation("show")` |
+| **Tests** | [`server/tests/nodes/test_chat_ui.py`](../../../server/tests/nodes/test_chat_ui.py), [`server/tests/services/genui/`](../../../server/tests/services/genui/), [`server/tests/services/chat/test_parts.py`](../../../server/tests/services/chat/test_parts.py) |
+| **Skill (if any)** | - |
+| **Dual-purpose tool** | no: a tool only (`component_kind = "tool"`, tool name `show_ui`) |
+
+## Purpose
+
+Lets an employee put a small interface inside its chat reply: a choice to
+make, a short form, numbers, a chart, buttons. The agent calls `show_ui`
+with a json-render spec; the owner sees it under the reply, uses it, and its
+buttons either ask something in the owner's name or come back to the agent
+as the owner's next turn. Wire it to the `input-tools` handle of the agent
+that answers through Reply in Chat. See
+[Chat Protocol → Generated UI](../../chat_protocol.md#generated-ui).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `output-tool` | tools | yes | Connects to an agent's `input-tools`. |
+
+No main input or output: it runs only when the agent calls it.
+
+## Parameters
+
+| Name | Type | Default | Required | Description |
+|------|------|---------|----------|-------------|
+| `spec` | object | - | yes | The interface as json-render's flat spec `{root, state, elements}`. A JSON string is read as the object it encodes (some providers send object arguments as strings). |
+
+The tool description is generated from
+[`server/config/chat_genui_catalog.json`](../../../server/config/chat_genui_catalog.json)
+by `services/genui/spec.py` `describe_catalog`: the components with their
+props, which prop each input binds, what each layout may hold, the state and
+condition syntax, the actions and the limits. `tool_schema_locked` pins it
+against stale persisted ToolSchema rows.
+
+## Outputs (handles)
+
+### Output payload (TypeScript shape)
+
+```ts
+// ChatUiOutput (model_config extra="allow"): what the model reads back
+{
+ shown: boolean; // false outside a reply to the owner's chat message
+ ui_id?: string; // the part id, "ui_<16 hex>"
+ elements?: number; // elements the interface kept
+ dropped?: {id: string; reason: string}[]; // unknown types, unreachable elements
+ notes?: string[]; // stray fields and props left out, and why
+ message?: string;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[spec from the model] --> B[services.genui.spec.check_spec]
+ B -- breaks a rule --> C[Raise NodeUserError listing every problem: the model writes it again]
+ B -- ok --> D{chat_stream and tool_call_id in the context?}
+ D -- no --> E[Return shown=false: an interface shows only in a reply to the owner]
+ D -- yes --> F[services.chat.parts.show_ui]
+ F --> G[Save the ui part on the chat run]
+ G --> H[Publish activity.snapshot, then one activity.delta per patch]
+ H --> I[Return shown=true + ui_id, elements, dropped, notes]
+```
+
+## Decision Logic
+
+- **Refused** (every problem in one `NodeUserError`): not an object; a root
+ that is not an element of a known type; a child that is not an element or
+ that its parent may not hold (a Row holds Buttons, a Card holds Select,
+ Toggle, TextField and Text); a cycle or a child with two parents; more than
+ 24 elements, 6 levels, 12 children or 16384 bytes; a prop its component's
+ JSON Schema refuses; `$bindState` on a prop other than the input's bound
+ one; a state path through `__proto__`, `constructor` or `prototype`; an
+ action name that is not one (`push`, `pop`, `pushState`, `removeState` and
+ `validateForm` are kept by the chat); params starting `__`.
+- **Left out and reported**: elements of an unknown type (and children
+ naming them), elements the root does not reach, element fields other than
+ `type`, `props`, `children`, `visible` and `on`, props a component does not
+ declare, `$item` / `$index` / `$bindItem` / `$computed`.
+- **Where it shows**: only a tool call of the agent answering a chat run
+ carries `chat_stream` (`agent.prepare_payload` -> AgentWorkflow ->
+ `BaseNode.as_activity` extras). A canvas Run, a delegated agent or a
+ schedule gets `shown: false`.
+- **No step**: `chat_step_hidden = True`; the interface is what shows.
+
+## Side Effects
+
+- **Database writes**: one `chat_run_parts` row (`kind = "ui"`, key
+ `ui:<part id>`, payload `{part_id, spec, state, state_revision: 0,
+ elements}`); a retried call writes the same row. Reply in Chat copies the
+ run's parts onto its reply; the run's end seals any later ones, creating an
+ empty-text reply when the run wrote nothing.
+- **Broadcasts**: `chat_run_event` frames (`activity.snapshot`,
+ `activity.delta`, `activity_type: "json_render"`) to the session's
+ subscribed sockets only (`services/chat/hub.py`).
+- **External API calls**, **file I/O**, **subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.genui.spec`, `services.genui.patches`,
+ `services.chat.parts`, the database.
+- **Python packages**: `jsonschema` (a direct dependency).
+- **Environment variables**: none.
+
+## Edge cases & known limits
+
+- The client checks the spec again before drawing it
+ (`client/src/features/chat/genui/prepare.ts` with `lib/jsonRender`), and a
+ test on each side holds the two catalogues to each other.
+- Allowed for Hire by `node_allowlist.json` `enabled_nodes`; the employee
+ builder does not wire it into new hires yet.
+
+## Related
+
+- **Other nodes**: [`chatReply`](./chatReply.md) (the answer it sits under),
+ [`chatTrigger`](../workflow_triggers/chatTrigger.md).
+- **Architecture docs**: [Chat Protocol](../../chat_protocol.md).
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index a5e79826..97546104 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -81,6 +81,7 @@ class SpecializedAgentBase(ActionNode, abstract=True):
| `needs_canvas` | `ClassVar[bool]` — when `True`, the F4.B `AgentWorkflow` tool-dispatch forwards the parent workflow's `nodes`/`edges` into the per-tool activity payload. Today only `AgentBuilderNode` opts in: `add_tool` compares the run's canvas with the saved graph, so a tool saved earlier but missing from the running snapshot is handed back to be bound. Its calling agent comes from `invoking_agent_node_id` / `parent_node_id`, not from edges. |
| `chat_step` / `chat_step_hidden` | How a call of this tool reads as a working step in the chat while it answers the owner ("Searched the web"; default "Used <display name>"); `chat_step_hidden = True` shows none (the clock, the checklist). A tool may put a short line in its result as `_step_detail`, shown under the step and removed before the model reads the result. See [Chat Protocol](./chat_protocol.md#streaming-steps-and-stop). |
| `answers_chat_run` | `ClassVar[bool]` — the node posts a chat run's answer (Reply in Chat). The agent wired straight into such a node streams its text into the chat. |
+| `chat_sources` | `ClassVar[bool]` — the tool returns web results (`results: [{title, snippet, url}]`, the searches). When the agent answering a chat run calls it, the results are numbered for the conversation in what the model reads, so the answer can cite them as `[n]`. See [Chat Protocol](./chat_protocol.md#sources). |
| `task_queue` | Temporal worker pool. See `TaskQueue` constants. |
| `retry_policy` | `RetryPolicy` dataclass (mirrors `temporalio.common.RetryPolicy`). |
| `start_to_close_timeout` / `heartbeat_timeout` | Per-node Temporal knobs. |