Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs(chat): branches, ratings, and memory that follows the path
trohitg198a02c86c51
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3c62ec18..d8b5ba6d 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 live Ask first rule (`workflow_rules`, the chat's Ask first chip via `set_ask_first`; app replies wait in `approvalGate`, sending tool calls are held as drafts by `services/approvals/tool_calls.py` and sent after a 5 s Undo window by `ApprovedToolCallWorkflow`; cards in the chat; builder v3 gates every app reply, attaches every app tool and gives the talk agent `chatUi` and the registry's `talk_send` tools, with instructions identical whatever the rule; older employees are upgraded on Apply / Turn on Talk / Start by `services/employees/upgrade.py`), 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`. 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`). Approvals (`services/approvals/`, its own section): a plugin's `approval` spec marks a tool call that sends; while the workflow asks first it is held as a `tool_call` draft, shown as a card on the reply that made it, sent once after the Undo window by `ApprovedToolCallWorkflow`, with the outcome told to the employee as an `[update]` note. 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`). Approvals (`services/approvals/`, its own section): a plugin's `approval` spec marks a tool call that sends; while the workflow asks first it is held as a `tool_call` draft, shown as a card on the reply that made it, sent once after the Undo window by `ApprovedToolCallWorkflow`, with the outcome told to the employee as an `[update]` note. Branches (`services/chat/branches.py`): `get_chat_messages` returns the path to the thread's active leaf, each message with its versions (`siblings`), `editable` and the owner's rating; `edit_chat_message` / `regenerate_chat_reply` / `switch_chat_branch` move the path in one reserved transaction under the conversation store's lock, taking each agent's stored conversation back to the cursor its run recorded at `prepare_payload` (`chat_runs.context_cursors`) or restoring the branch's kept copy (`chat_branch_snapshots`), refused on `revision_conflict`, `run_in_progress`, `cannot_rewind`, `branch_unavailable` or `older_generation`; `set_chat_feedback` keeps a rating and tells the next turn (`[feedback]` note). 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). |@@ -999,11 +999,13 @@ class ChatMessage(SQLModel, table=True):| Handler | Description ||---------|-------------|| `send_chat_message` | Save the message and dispatch it to the workflow's chatTriggers. A workflow session answers `delivery: "now"` (running / starting / resuming) or `"queued"` (paused / pausing, runs on Resume); in any other state `not_running`, saving nothing |-| `get_chat_messages` | A session's messages, oldest first: `{id, role, message, timestamp, run_key}` (UTC-offset timestamps; `run_key` = the generation). The latest generation only (none after a Reset), unless `all_generations` (Home's thread; a Reset clears the thread, so only a row from before a Start shows beside the live ones) |+| `get_chat_messages` | The path shown in a session, oldest first: `{id, role, message, timestamp, run_key, siblings, editable, feedback, ...}` (UTC-offset timestamps; `run_key` = the generation; `siblings` = the message's versions). The latest generation only (none after a Reset), unless `all_generations` (Home's thread; a Reset clears the thread, so only a row from before a Start shows beside the live ones) || `clear_chat_messages` | Clear a session's chat, every generation; for a workflow's session its agents forget the conversation too (`chat_thread.clear_chat_session` tells the listeners registered with `register_chat_cleared_listener`: the Context plugin clears the workflow's conversations) || `save_chat_message` | Save one message with the given role || `chat_subscribe` / `chat_unsubscribe` | Start / stop receiving a session's `chat_run_event` frames; subscribe answers the live runs' snapshots || `get_chat_run` | One run's snapshot |+| `edit_chat_message` / `regenerate_chat_reply` / `switch_chat_branch` | Edit one of the owner's messages, try the latest answer again, or show another version; the agent's memory follows the path (see [Chat Protocol → Branches](./docs-internal/chat_protocol.md#branches)) |+| `set_chat_feedback` | Rate an answer `up` / `down` (or take it back); the employee reads it on its next turn |Every chat command refuses the internal worker socket, and a workflow's session answers only the workflow's owner (`services/chat/access.py`).@@ -2500,7 +2502,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins| **WhatsApp** | `whatsapp_status`, `whatsapp_connected_phone`, `whatsapp_qr`, `whatsapp_send`, `whatsapp_start`, `whatsapp_restart`, `whatsapp_groups`, `whatsapp_group_info`, `whatsapp_chat_history`, `whatsapp_newsletters`, `whatsapp_rate_limit_get`, `whatsapp_rate_limit_set`, `whatsapp_rate_limit_stats`, `whatsapp_rate_limit_unpause`, `whatsapp_mark_read`, `whatsapp_typing`, `whatsapp_presence`, `whatsapp_stop`, `whatsapp_diagnostics` || **Telegram** | `telegram_connect`, `telegram_disconnect`, `telegram_status`, `telegram_send`, `telegram_reconnect`, `telegram_get_me`, `telegram_get_chat` || **Workflow Storage** | `save_workflow`, `get_workflow`, `get_all_workflows`, `delete_workflow` |-| **Chat Messages** | `send_chat_message`, `get_chat_messages`, `clear_chat_messages`, `save_chat_message`, `chat_subscribe`, `chat_unsubscribe`, `get_chat_run` (see [chat_protocol.md](./docs-internal/chat_protocol.md)) |+| **Chat Messages** | `send_chat_message`, `get_chat_messages`, `clear_chat_messages`, `save_chat_message`, `chat_subscribe`, `chat_unsubscribe`, `get_chat_run`, `edit_chat_message`, `regenerate_chat_reply`, `switch_chat_branch`, `set_chat_feedback` (see [chat_protocol.md](./docs-internal/chat_protocol.md)) || **Console/Terminal** | `get_console_logs`, `clear_console_logs`, `get_terminal_logs`, `clear_terminal_logs` || **User Skills** | `get_user_skills`, `get_user_skill`, `create_user_skill`, `update_user_skill`, `delete_user_skill` || **Built-in Skills** | `get_skill_content`, `save_skill_content`, `scan_skill_folder`, `list_skill_folders` |diff --git a/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md b/RFC-0002-AGENT-CONTEXT-AND-MEMORY.mdindex 6ebb77d2..62cccba0 100644--- a/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md+++ b/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md@@ -19,6 +19,19 @@ Compatibility boundary: new workflow generations only> is the normative Context reference.** Sections below describing the> journal are historical rationale, not the running system.+> ## Amendment (October 2026): the chat+>+> The plain store gained three behaviors for the owner's chat, specified in+> [agent_context_flow.md](./docs-internal/agent_context_flow.md) and+> [chat_protocol.md](./docs-internal/chat_protocol.md): a stopped turn is+> saved as far as it went, and a load answers any tool call left open; what+> the owner did in the chat between turns reaches the agent as bracketed+> notes ahead of their message (`chat_notes`), never in the stored system+> prompt; and editing a message, trying an answer again or switching between+> versions takes the stored conversation back to the cursor the run recorded+> (`chat_runs.context_cursors`), or restores the copy kept for that branch+> (`chat_branch_snapshots`), under the store's lock.+## 1. SummaryOpenCompany separates two concepts that were previously conflated:diff --git a/docs-internal/agent_context_flow.md b/docs-internal/agent_context_flow.mdindex b5752473..05880e46 100644--- a/docs-internal/agent_context_flow.md+++ b/docs-internal/agent_context_flow.md@@ -133,6 +133,23 @@ passes the stored row through `close_unanswered_tool_calls`latest assistant turn with `UNANSWERED_TOOL_RESULT`, after the results the turnalready has. A closed conversation is returned unchanged.+### Chat branches rewind and restore++Editing the owner's message, trying an answer again or switching to another+version of the chat changes what the agent should remember+([Chat Protocol → Branches](./chat_protocol.md#branches)). When a chat run's+agent is prepared, `agent.prepare_payload` records on the run where the stored+conversation stood (`chat_runs.context_cursors`: its length and a digest that+leaves out the `ts` stamps), the stored row as loaded, before+`close_unanswered_tool_calls`. A branch move then writes the conversation+directly, under `conversation_lock` (the lock `save_conversation` holds) and+inside the move's reserved transaction: back to the cursor of the first run on+the part of the chat being left (refused when the stored row no longer starts+with what the cursor recorded, as after a compaction), or, for a switch, to the+conversation kept for the branch moved to (`chat_branch_snapshots`). Turns other+firings added after that point go with the branch. The Context listeners hear+of each conversation changed, as after a save.+## Transcript size: capped results, cleared old resultsThe transcript is the `agent.execute_llm_step` input on every turn and the@@ -317,6 +334,7 @@ workflow, not only the removed Context's agent.| 9 | The store never imports `nodes/`; the plugin registers its broadcaster via `register_conversation_listener`, and a listener failure can never fail a save. | Same layering rule as every plugin registry; a UI notification must not break execution. || 10 | External tool results are capped before they enter the transcript; the latest turn is never cleared or summarized; the pressure rules are chosen by the recorded `context_pressure_version`. | Uncapped results bricked every later firing (`errors.md` #28); an unread turn summarized away loses what the model asked for; a replay must schedule the commands it recorded. || 11 | A stopped turn is saved as far as it went, and a load answers any tool call the stored row left open. | A provider refuses a conversation with an unanswered call, so one cancelled run would otherwise break every later firing. |+| 12 | Only `save_conversation` and a chat branch move (under `conversation_lock`, checked against the run's cursor) rewrite a stored conversation. | A move that ignored the lock or the cursor would cut a turn being saved, or cut a summarized conversation at the wrong place. |## How this broke (August 2026 regression), and why the journal went awaydiff --git a/docs-internal/chat_protocol.md b/docs-internal/chat_protocol.mdindex e04818b8..e812c297 100644--- a/docs-internal/chat_protocol.md+++ b/docs-internal/chat_protocol.md@@ -126,10 +126,10 @@ All are WebSocket request/response handlers with snake_case payloads. Failures a| `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}` |-| `set_chat_feedback` | `{message_id, rating: "good" \| "bad" \| null, comment?}` | `{success, reaches: ["next_reply", "memory"?]}` |+| `edit_chat_message` | `{session_id, message_id, message, expected_revision?, client_message_id?}` | `{success, message_id, run_id, delivery}` (the edit's id; a resent `client_message_id` answers the first edit) |+| `regenerate_chat_reply` | `{session_id, message_id, expected_revision?}` (the latest answer, or the owner's last message when its run gave none) | `{success, message_id, run_id, delivery}` (`message_id`: the owner's message answered again) |+| `switch_chat_branch` | `{session_id, message_id, expected_revision?}` (a message beside one on the path) | `{success, leaf_id}` |+| `set_chat_feedback` | `{session_id, message_id, value: "up" \| "down" \| null}` | `{success, message_id, value, reaches: ["next_turn", "memory"?]}` (`[]` when taken back) || `get_chat_context` | `{session_id}` | `{success, commands, suggestions, capabilities, genui_catalog, limits, ask_first: {value, editable, replies_gated}}` || `clear_chat_messages` | `{session_id}` | `{success}`; also clears runs, parts, snapshots, notes and feedback, and makes the employee forget the conversation |@@ -196,10 +196,15 @@ tool_call_id?, ui_part_id?, agent_node_id?, deployment_state?}`. `status` is `pea failed run the error with the hint the run recorded, the steps it saved, and once it has ended how long itworked (`duration_ms`). It is how a reload still shows that a message went unanswered and what the employee did;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`.+- `siblings` are the messages beside it (the same parent and role), oldest first, itself included: the owner's+ edits of a message, or the answers tried for one. `index` is its own place.+- `editable` says the owner may change it now (the server decides): their text message a run answered, in the live+ generation (Edit), and the answer the path ends at once its run has ended (Try again).+- `run_id` on the owner's message names the run answering it on this path: the run of the answer after it, else its+ newest run (an answer being tried again), else the run it started.+- `feedback` is the owner's rating of an answer: `up`, `down` or null.+- `kind`: `text`, `report` (Post to Talk: not editable), `action` (a button press), `notice`.- `status`: `complete`, `stopped`, `error`.-- `siblings` are branches for owner messages and versions for replies.Parts render in this order, whatever order they were produced in: steps, text, generated UI, artifacts, approvals,sources, follow-ups.@@ -377,6 +382,15 @@ 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 runand applies the answer to the store at once; the run's events take it from there.+- **Changing the conversation** (`data/branches.ts`, `thread/turnActions.ts`): under the owner's message a hover bar+ (`turns/UserTurn.tsx`: time, ‹ 1 / 2 › between versions, Edit, Copy; Edit opens `turns/UserEditBox.tsx` in place,+ Enter sends, Esc cancels, ArrowUp in an empty box edits the last message); under a finished answer+ (`turns/ReplyActions.tsx`) Copy, Good and Bad (pressing again takes the rating back), Try again on the latest+ answer, ‹ 1 / 2 › between answers, and the time. A run that stopped or failed without an answer has Try again in+ its note. Each command sends the thread's revision as read; a refusal is told in the host's words+ (`turns/runCopy.ts` `branchRefusalText`), `not_running` through the host's own refusal. A rating shows at once and+ goes back when it does not save; its toast says where it goes (`feedbackThanks`). Suggested questions hide while+ the box holds text, and under a stopped answer.- **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 turnkeeping them until the saved reply carries them, so one element shows throughout and keeps what the owner set. The@@ -433,12 +447,55 @@ What an employee sends to someone waits for the owner's OK while its workflow as`com.opencompany.approval.<stage>`: requested, decided, undone, restored, sending, sent, failed, expired,cancelled), identity only, with the chat run when there is one.+## Branches++`services/chat/branches.py`. A session's messages form a tree: each row names the one before it (`parent_uid`) and+`chat_threads.active_leaf_uid` is where the path shown ends; `get_chat_messages` returns that path only.++- **Edit** (`edit_chat_message`) adds the new text beside the message it edits (same parent; `meta.edit_of` names+ the original) and starts a run of kind `edit` answering it (`parent_run_id`: the original's run).+- **Try again** (`regenerate_chat_reply`) moves the leaf back to the owner's message and starts a run of kind+ `regenerate` for it (`user_message_id`: that message), whose answer goes beside the old one. Only the answer the+ path ends at, or the owner's last message when its run ended without an answer.+- **Switch** (`switch_chat_branch`) moves the leaf to the newest message in the chosen version's branch.++**Memory follows the path.** `agent.prepare_payload` records, on the chat run an agent with a stored conversation+works for, that conversation as the run began (`chat_runs.context_cursors[agent] = {generation, length, digest}`,+the digest leaving out the stored `ts` stamps; the first preparation in a run wins). A move takes every agent the+runs on the part it leaves touched back to the cursor of the first such run, after checking the stored conversation+still starts that way, and keeps their conversations under the left branch's leaf (`chat_branch_snapshots`, at most+`branches.max_snapshots_per_session` per session and `branches.max_snapshot_bytes` each, `config/chat_defaults.json`).+A switch restores the snapshots of the branch it moves to. It all runs in one reserved write transaction under the+conversation store's locks (`conversation_lock`), and is refused with:++- `revision_conflict`: `expected_revision` is not the thread's revision (something was added meanwhile);+- `run_in_progress`: a run holds the lane;+- `cannot_rewind`: a stored conversation no longer starts the way it did (summarized or cleared since); going back to+ an empty conversation always works;+- `branch_unavailable`: the branch switched to has no kept conversation for an agent that worked on it;+- `older_generation`: a message or run from before the live generation;+- `not_editable` / `not_found`: not the owner's text message a run answered, not the latest answer, or not on the+ path.++After it commits, the Context listeners hear of each conversation changed, the drafts the runs on the part left made+that still wait are cancelled (`approval_lifecycle` `cancelled`), and an `[update]` note (`branch:<run id>`) tells the+employee what those runs sent anyway. `chat.updated` follows (role `user` for an edit, null for a retry or a switch).++## Feedback++`set_chat_feedback` keeps the owner's rating of an answer (`chat_feedback`, one per answer; `services/chat/+feedback.py`) and leaves a `[feedback]{"rating": "good" | "bad", "answer": "<excerpt>"}[/feedback]` note+(`feedback:<message id>`; taking the rating back drops it while untold). `reaches` lists where the rating goes:+`next_turn`, plus what a listener registered with `register_feedback_listener` adds (a plugin that keeps it too+answers `memory`; none is registered yet).+## Notes to the employeeThings 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+of that turn's user message, one bracketed line each: `[ui-state]{"ui_id", "state"}[/ui-state]`, written by+`chat_ui_state` for what the owner set without pressing anything; `[update]{...}[/update]` for what became of a draft+(`approval:<id>`) or what a branch left behind still sent (`branch:<run id>`); and `[feedback]{...}[/feedback]` for a+rating. A note is keyed per session (`ui-state:<part id>`), so a newer one replaces an older one not yettold. `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 writtensomething), so a run that failed or stopped before writing offers them again, and a note changed after its claim stays@@ -486,15 +543,19 @@ and server tests alike:| Code | Where | Meaning ||---|---|---|-| `run_in_progress` | send, edit, regenerate, switch | A run is live in this session; `run_id` names it. |-| `save_failed` | send | The message could not be saved; nothing was dispatched. |-| `not_running` | send | The employee is not running and cannot queue messages. |+| `run_in_progress` | send, edit, regenerate, switch | A run is live in this session; `run_id` names it (send only). |+| `save_failed` | send, edit, regenerate, switch | The change could not be saved; nothing was dispatched. |+| `not_running` | send, edit, regenerate, switch | The employee is not running and cannot queue messages (a switch: nothing was started since the last Reset). || `invalid_request` | send, save | A malformed field (`detail` says which): an empty message, a role other than the owner's, or a bad `client_message_id`. || `read_failed` | get_chat_messages, chat_subscribe | The thread could not be read. Never answered as an empty thread. || `not_found` | get_chat_run, stop_chat_run | No such run. || `not_stoppable` | stop_chat_run | The run ended before Stop reached it; `state` says how. |-| `conflict` | edit, regenerate, switch, set_ask_first | `expected_revision` is stale. |-| `not_editable` | edit, regenerate, decide | The message belongs to an older generation, its prefix was compacted, or an edited argument is not editable. |+| `revision_conflict` | edit, regenerate, switch | `expected_revision` is not the thread's revision. |+| `conflict` | set_ask_first | `expected_revision` is stale. |+| `not_editable` | edit, regenerate, decide | Not the owner's text message a run answered, not the latest answer, the editor's `default` chat, or an edited argument that is not editable. |+| `older_generation` | edit, regenerate, switch | A message or run from before the employee restarted. |+| `cannot_rewind` | edit, regenerate, switch | An agent's stored conversation no longer starts the way it did when the run being undone began. |+| `branch_unavailable` | switch | The branch's kept conversations are gone (too many branches, or too large to keep). || `ui_event_rejected` | send | The element or action does not match the saved spec. || `access_denied` | all | The socket's principal does not own the workflow, or it is the internal worker socket. || `too_late` | decide | The Undo or Restore window has passed. |diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex f0e7d9ab..8b721a81 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -472,6 +472,16 @@ sending and drafts belong to the chat (wire and client rules in- **Stop.** While the run works, Send is Stop, and Esc stops it too: theanswer so far stays, marked "You stopped this reply." A message stillwaiting for Resume is withdrawn the same way.+- **Changing the conversation** (between runs): the owner's message has Edit+ (in place; ArrowUp in an empty box edits the last one) and ‹ 1 / 2 ›+ between their edits of it; the latest answer has Try again, and ‹ 1 / 2 ›+ moves between the answers tried. The employee's memory follows what is+ shown: an edit or a retry takes them back to before the message, and moving+ between versions brings back what they remembered on each+ ([chat_protocol.md → Branches](./chat_protocol.md#branches)). Drafts waiting+ on the part left behind are cancelled, and the employee hears of anything+ sent there. Good and Bad rate an answer; the toast says the employee will see+ it next time, which is when the rating reaches them.- **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