From c3a973f4091308d4d6293f4f528582c087bf33e7 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Sat, 21 Nov 2026 20:59:00 +0000
Subject: [PATCH] mcp: session state, account, goal, recap and subagents in
SimpleX groups (#8294)
* mcp: plan the session board with accounts, goals and recaps
* mcp: read the account, goal, recap and title of each session
* mcp: one message per session with account, goal and recap in the Main group
* mcp: test only the Main group's edits of the board
* mcp: plan subagents and workflows in the session group
* mcp: live messages of subagents and workflows, and their line on the board
* mcp: a session waits for you while any of its cards is pending
---
packages/simplex-chat-mcp/README.md | 3 +-
packages/simplex-chat-mcp/REFERENCE.md | 54 ++-
packages/simplex-chat-mcp/TESTING.md | 4 +-
packages/simplex-chat-mcp/hooks/hooks.json | 2 +
packages/simplex-chat-mcp/spec/api.md | 56 ++-
.../simplex-chat-mcp/spec/architecture.md | 43 +-
packages/simplex-chat-mcp/spec/flows.md | 112 +++--
packages/simplex-chat-mcp/src/agents.ts | 263 +++++++++++
packages/simplex-chat-mcp/src/claude-code.ts | 175 ++++++++
packages/simplex-chat-mcp/src/control.ts | 9 +-
packages/simplex-chat-mcp/src/files.ts | 6 +
packages/simplex-chat-mcp/src/hook.ts | 93 +++-
packages/simplex-chat-mcp/src/hub.ts | 224 ++++++++--
packages/simplex-chat-mcp/src/main-group.ts | 177 ++++++--
packages/simplex-chat-mcp/src/protocol.ts | 36 ++
packages/simplex-chat-mcp/src/service.ts | 6 +-
packages/simplex-chat-mcp/src/session.ts | 2 +-
.../simplex-chat-mcp/test/e2e/service.test.ts | 31 +-
.../simplex-chat-mcp/test/unit/agents.test.ts | 53 +++
.../test/unit/claude-code.test.ts | 64 +++
.../simplex-chat-mcp/test/unit/hook.test.ts | 61 ++-
.../simplex-chat-mcp/test/unit/plugin.test.ts | 2 +-
.../test/unit/service.test.ts | 8 +
.../test/unit/session.test.ts | 8 +-
.../test/unit/sessions.test.ts | 196 ++++----
plans/2026-11-21-mcp-session-board.md | 284 ++++++++++++
plans/2026-11-21-mcp-subagents.md | 423 ++++++++++++++++++
27 files changed, 2143 insertions(+), 252 deletions(-)
create mode 100644 packages/simplex-chat-mcp/src/agents.ts
create mode 100644 packages/simplex-chat-mcp/src/claude-code.ts
create mode 100644 packages/simplex-chat-mcp/test/unit/agents.test.ts
create mode 100644 packages/simplex-chat-mcp/test/unit/claude-code.test.ts
create mode 100644 plans/2026-11-21-mcp-session-board.md
create mode 100644 plans/2026-11-21-mcp-subagents.md
diff --git a/packages/simplex-chat-mcp/README.md b/packages/simplex-chat-mcp/README.md
index 65864c32c9..88ba4bd9ea 100644
--- a/packages/simplex-chat-mcp/README.md
+++ b/packages/simplex-chat-mcp/README.md
@@ -24,7 +24,8 @@ With this package, Claude Code can join channels and groups, talk to bots, and e
- Invite people to the Main group, and they join any session's group.
- Only owners and admins can approve tool calls.
-- The Main group shows every session's state.
+- The Main group shows every session's state, Claude account, model, goal, working subagents and recap.
+- A session's group shows each subagent and workflow as it works, and when it stalls.
- 🏗️ Each session as a topic in one group.
- 🏗️ Agent teams: mention an agent to message it.
diff --git a/packages/simplex-chat-mcp/REFERENCE.md b/packages/simplex-chat-mcp/REFERENCE.md
index 82426c5c8c..a9a59d8c8c 100644
--- a/packages/simplex-chat-mcp/REFERENCE.md
+++ b/packages/simplex-chat-mcp/REFERENCE.md
@@ -572,34 +572,44 @@ Only you see this link: it never enters Claude's context or tool results. Scan t
- Owners can add people with a group link of their own or by inviting their contacts.
- Observers can't send messages in the Main group, so they can't use `/join N`.
- Owners of the Main group are invited to every session's group as owners. They get each invitation in the Main group.
-- `/sessions` replies with the text of the list of sessions, below. `/join N` sends you an invitation to the group of session N, as an admin, or as an owner if you own the Main group.
+- `/sessions` replies with one line per running session, as the first line of its message on the board below, and a last line `⚪ Not running: 5 · bio, 4 · notes, 2 · openclaw, 1 · first` that names every other session, newest first, cut to one message with the count of the rest. `/join N` sends you an invitation to the group of session N, as an admin, or as an owner if you own the Main group.
- Leaving the Main group, being removed from it, or getting another role there changes nothing in the session groups.
- When no owner remains, the service creates a new link. In a terminal, `npx -y @simplex-chat/mcp@VERSION link` prints it with a QR code. While the group has owners, the command names them instead.
-After the first owner joins, Claude posts the list of sessions in the Main group, after its greeting:
+After the first owner joins, Claude posts the board of sessions in the Main group, after its greeting: one message per running session, and a summary.
```
🟢 3 · simplex-chat: working
-🟠 6 · website: waiting for you, 2 approvals
-⛔️ 7 · docs: waiting for you in Claude Code
-🔴 8 · app: idle
-⚙️ 9 · api: working in the background
-⚪ Not running: 5 · bio, 4 · notes, 2 · openclaw, 1 · first
+*WebRTC device link architecture survey*
+alice@example.com · claude-opus-4-7 · effort high · goal set
+I mapped how to move desktop–mobile linking onto WebRTC through the Haskell core. Next I need your answers to the four decisions on the page.
+```
+```
+🟠 4 · mcp-board: waiting for you, 2 approvals
+bob@example.com · claude-sonnet-4-5 · effort medium
+```
+```
+⚪ 2 · webrtc: stopped
+carol@example.com · claude-opus-4-7 · effort xhigh · goal failed
+```
+```
+3 sessions 🟠 🟢 ⚪
```
-- A session is running while its Claude Code runs, or while cards wait for a decision in its group. Each running session has a line, by number. Green is the state to keep:
+- A session's message shows its state, Claude Code's title of the conversation when it differs from the session's name, the Claude account, the model, the effort level, whether a goal is set, met or failed, a line such as `🤖 2 agents working · 1 stalled 2:10 · ⚙️ review-changes Verify 3/8` while subagents or workflows work, and Claude Code's latest recap. The account is the email of the login in Claude Code's global config, `CLAUDE_CONFIG_DIR/.claude.json` or `~/.claude.json`; the goal, the recap and the title come from the session's transcript.
+- The summary has the state of each session on the board, by number. Claude only edits it, so messages posted later, such as a new session's message or an invitation, follow it.
+- A session is running while its Claude Code runs, or while cards wait for a decision in its group. Green is the state to keep:
- `🟢 N · NAME: working`: Claude Code works on a turn, or a subagent works for it.
- - `🟠 N · NAME: waiting for you, K approvals`: K cards wait in the session's group, for a decision in the chat. A tool-use card counts only while Claude Code shows its permission dialog, or while Claude Code's state can't be read.
+ - `🟠 N · NAME: waiting for you, K approvals`: K cards wait in the session's group, for a decision in the chat, whatever Claude Code's state. A tool-use card answered in the terminal stays until the turn ends.
- `⛔️ N · NAME: waiting for you in Claude Code`: Claude Code waits for an answer in its own window, such as a dialog, which the chat can't give.
- `⚙️ N · NAME: working in the background`: Claude Code waits for the next prompt while a background command runs. The command's end starts a turn without a prompt.
- `🔴 N · NAME: idle`: Claude Code waits for the next prompt, and nothing runs.
- `▶️ N · NAME: running`: Claude Code's state can't be read.
-- The last line names every other session of the data folder, newest first. Without any session, the list is `No sessions.`
+ - `⚪ N · NAME: stopped`: Claude Code of this session ended. Claude deletes the message 23 hours after its post.
- The states are Claude Code's own: the plugin reads them from Claude Code's record of its process, `sessions/PID.json` in `CLAUDE_CONFIG_DIR` or `~/.claude`.
-- The list is one message. When it gets too long, the last line keeps the newest names that fit and ends with the count of the others, such as `190 older sessions`. The lines of running sessions are never cut.
-- Claude edits the list within 2 seconds of a change. An edit alerts nobody. The list moves up as messages, such as invitations to new sessions' groups, are posted after it.
-- SimpleX lets Claude edit a message only within 24 hours. When the list is 23 hours old, Claude posts a new list and deletes the old one for everyone.
-- When the service stops, Claude edits the list once more, with every session in the last line.
+- Claude edits a message within 2 seconds of a change. An edit alerts nobody. SimpleX lets Claude edit a message only within 24 hours; when an edit is refused, Claude posts the message again and deletes the old one for everyone.
+- When the service stops, Claude edits every message once more, with every session stopped.
+- The group of each session shows the same details as its short description, and the latest recap as its description, which stays empty until Claude Code writes a recap.
To replace the owners, run `npx -y @simplex-chat/mcp@VERSION reset-owners` in a terminal. It replaces the Main group at once, without the owners' approval:
@@ -625,7 +635,7 @@ VERSION is the plugin's version, as in `npx -y @simplex-chat/mcp@0.3.0 link`. Th
`User`'s messages are never prompts, commands or approvals.
- When someone joins or their role changes, Claude posts their rights. For an admin the post is `Bob is an admin and can send prompts to Claude and the group's commands, and approve tool use. You can change role to observer to stop it: /'observer #G ID'`, with the group's and the member's IDs. For a moderator, member or author it is `NAME is a ROLE and can send prompts to Claude; the group's commands and approvals need the role admin or owner.`, followed by the same command. The posts for an owner and for an observer have no command: `NAME is an owner and can send prompts to Claude and the group's commands, and approve tool use.` and `NAME is an observer and can't send messages.` Claude posts nothing for `User`.
- `/observer #G ID` makes that member an observer, and Claude replies `NAME is an observer and can't send messages.` Admins and owners can use it on a member whose role isn't above their own. Standing approvals that the observer gave, of all messages to a chat or all files from it, stop counting while they aren't an admin or owner, and count again if they become one. For a member who was invited and hasn't joined yet, Claude replies `No member ID in this group.` That member joins with the role of the invitation, which can be changed after the join.
-- The group's description is `The Claude Code session N. Members send it prompts; admins and owners also send the group's commands and approve tool use.`, set when the group is created. Its short description shows the model and effort, see [Model, effort and usage](#model-effort-and-usage).
+- The group's description is Claude Code's latest recap of the session, empty until the first. Its short description shows the account, the model, the effort and the goal state, see [Model, effort and usage](#model-effort-and-usage).
- The group is created in the Flat layout, which SimpleX apps from v7.1.0 show. Each member can choose another layout for it in Group info › `Chat theme` › `Chat layout`, for their own app. The Main group is shown in each member's own layout.
- The group has the commands of the agent control chat of `serve` (see [What the owner sees](#what-the-owner-sees)), without a session prefix, such as `/approve 7`, `/receive @3 9` and `/leave #2`. It also has `/give CHAT N`, `/observer #G ID`, and `/approve N all` and `/revoke TOOL` for tools, see [Tool use](#tool-use).
- A chat belongs to the session that connected it, even when the other side accepts after `connect` returned. The tools of other sessions don't show it. Their `connect` to its address returns `The chat of LINK belongs to another session; an admin or owner of that session's group can give it to this session with /give.` For example, `/give @3 2` in the group of the session that owns chat @3 gives it to session 2.
@@ -672,17 +682,23 @@ With the channel, a message from a member of a session's group, other than `User
- Read, Edit, NotebookEdit and Write: `📖 Read PATH`, `✏️ Edit PATH` for a file or a notebook, and `✏️ Write PATH`, with PATH relative to the session's folder when it is inside it;
- Grep and Glob: `🔍 Grep PATTERN in PATH` and `🔍 Glob PATTERN in PATH`, with PATH as for Read, and without ` in PATH` when the search has no path;
- WebFetch and WebSearch: `🌐 Fetch URL` and `🔍 Search QUERY`;
- - Agent: `🤖 Agent: ` and the agent's description;
- another tool: `🔧 TOOL`, and `: ` with the first of its description, query, URL, file path, path, pattern and command that is not blank. A tool whose name has `search`, such as ToolSearch or an MCP tool `search_threads`, gets `🔍` in place of `🔧`.
- The line is a live message while the step runs. The whole line is in small print. When the step ends, Claude completes it with the step's duration, after ❌ for a failure or ⏹️ for an interruption, such as `!- 💻 Run the tests 2.0 s!`. A `!` in the text of a step is shown as `ǃ`, which looks the same, because `!` would end the small print. Claude Code reports the end of a command or an agent run in the background when it is started, so its line is completed with `(in background)`, such as `!- 💻 Run the tests (in background)!`; its completion is posted later as the line of its notification. The completed line has no edited mark. A step refused at approval has no end; its line is completed without an outcome when the turn ends, when a prompt starts the next turn, or when the session ends. A line still live 23 hours after its start is completed without an outcome, because SimpleX allows edits of a message for 24 hours; the step's later end is posted as a new line. The text of a step is cut at 200 characters. Tool uses of subagents and of this plugin get no line.
+ The line is a live message while the step runs. The whole line is in small print. When the step ends, Claude completes it with the step's duration, after ❌ for a failure or ⏹️ for an interruption, such as `!- 💻 Run the tests 2.0 s!`. A `!` in the text of a step is shown as `ǃ`, which looks the same, because `!` would end the small print. Claude Code reports the end of a command or an agent run in the background when it is started, so its line is completed with `(in background)`, such as `!- 💻 Run the tests (in background)!`; its completion is posted later as the line of its notification. The completed line has no edited mark. A step refused at approval has no end; its line is completed without an outcome when the turn ends, when a prompt starts the next turn, or when the session ends. A line still live 23 hours after its start is completed without an outcome, because SimpleX allows edits of a message for 24 hours; the step's later end is posted as a new line. The text of a step is cut at 200 characters. Tool uses of this plugin get no line, and the starts of subagents and workflows get their own messages, below.
+- Each subagent and each workflow has one live message, silent, edited as it works, at most every 5 seconds:
+
+ ```
+ 🤖 Explore · find the suspend callers
+ 14 steps · 38.2k tokens · 1:05 · now: 📖 Read SuspendChat.swift
+ ```
+ A subagent with no step for 2 minutes, or 10 minutes while a step runs, shows `⚠️ no step for 2:10 · last: 💻 cabal build` instead of `now:`. When it ends, the message is completed with its time, steps and tokens and the first line of its result, such as `🤖 Explore · find the suspend callers · ✅ 2:40 · 22 steps · 61.5k tokens`, with ❌ for a failure and ⏹️ for a stop. A workflow shows its phases, done agents of all started: `⚙️ review-changes · Review 4/4 ✅ · Verify 3/8 · 2 working · 412k tokens · 6:30`, and ends as `⚙️ review-changes · ✅ 6:30 · Review 4/4 · Verify 8/8 · 412k tokens`. The notification of a finished subagent or workflow gets no line, because its message shows the end. Tokens are those of the agent's latest request, as the terminal shows them, read from its transcript every 2 seconds. Teammates of an agent team, the agents of a workflow and Claude Code's internal agents get no message of their own. A message keeps its place in the chat when it is edited. Live messages still live when the session ends are completed with ⏹️.
- Claude marks the turn's empty live message, its texts and answers, the lines of steps, and the lines of Claude Code's own prompts, of summaries of the context and of model and effort switches as silent. The answer's last message, with its line, is important, so a turn alerts once, at its end. When the line completes a live message or the turn's empty live message, the edit marks it important; SimpleX apps alert for such an edit once they support it. A SimpleX app that supports silent messages shows them without an alert; other apps alert for them as for any message.
- A text too long for one message is posted as several messages, each as long as a message can be, measured as for `send`. The first part of an answer carries the quote. A part without a quote holds up to 14,962 Latin, 7,481 Cyrillic or 4,987 CJK characters. A prompt or an answer over 250,000 characters is cut there and ends with `…`.
- The `reply` tool sends a file to the group at once, without approval, with its text as the caption, under the file rules of `send`. It returns the file's message as `item`. A caption too long for a message with the file's preview is refused with `text: too long for a message with this TYPE; shorten it.`
### Group preferences
-Owners set the group's preferences in the app, and SimpleX enforces them. Claude never overwrites them: it changes only the group's name, short description and commands, starting from the profile in the chat database.
+Owners set the group's preferences in the app, and SimpleX enforces them. Claude never overwrites them: it changes only the group's name, short description, description and commands, starting from the profile in the chat database.
- While "Files and media" is off, `reply` returns `Files and media are off in the group of this session; its owners can turn them on in the group's preferences.` The cards of sends and downloads of images and videos are posted as text, without the preview, and the sends and downloads still work. `/forward` gets `Action N: Files and media are off in the group of this session; its owners can turn them on in the group's preferences.`
- When another preference refuses one of Claude's posts, Claude posts a text that names it instead:
@@ -723,7 +739,7 @@ Claude: I want to use `Bash`: `List files`
### Model, effort and usage
-The short description of a session's group shows `MODEL · effort LEVEL`. The model is updated at the session start when Claude Code passes it, at each model change, and at the end of each turn from the model of the answer in the session's transcript. So the model shows from the first answer, also in a resumed session. An answer's model that is the shown model without `[1m]` keeps the shown model, because the transcript names the 1M context variant without that suffix. The effort level is updated at each tool step, at the end of each turn, and with the [status line](#status-line). Without the status line, a turn that runs at its own level, as after `ultrathink` in the prompt, shows that level until a later turn reports another. Once the status line reports in a session, the effort level comes only from the status line, which reports the session's level. Changes made in the terminal, or from the Claude app by Remote Control, show the same way.
+The short description of a session's group shows `ACCOUNT · MODEL · effort LEVEL · goal STATE`, the parts known so far. ACCOUNT is the email of the Claude login in Claude Code's global config, re-read when the file changes, so a `/login` shows within seconds. STATE is `set`, `met` or `failed`, from the goal entries of the transcript, and is left out without a goal or after `/goal clear`. The description is the latest recap that Claude Code wrote in the transcript; both are updated together, so a description an owner wrote is replaced at the next change. Each update shows `updated group profile` in the group, so after an update the next one waits for a minute and then shows the values of that time. The model is updated at the session start when Claude Code passes it, at each model change, and at the end of each turn from the model of the answer in the session's transcript. So the model shows from the first answer, also in a resumed session. An answer's model that is the shown model without `[1m]` keeps the shown model, because the transcript names the 1M context variant without that suffix. The effort level is updated at each tool step, at the end of each turn, and with the [status line](#status-line). Without the status line, a turn that runs at its own level, as after `ultrathink` in the prompt, shows that level until a later turn reports another. Once the status line reports in a session, the effort level comes only from the status line, which reports the session's level. Changes made in the terminal, or from the Claude app by Remote Control, show the same way.
When the model switches, Claude posts `Model changed to MODEL` in small print. When a known effort level changes, Claude posts `Effort changed to LEVEL`. The first model and the first effort level of a session get no line. Both lines are silent.
diff --git a/packages/simplex-chat-mcp/TESTING.md b/packages/simplex-chat-mcp/TESTING.md
index 3af22f510c..9c762f23de 100644
--- a/packages/simplex-chat-mcp/TESTING.md
+++ b/packages/simplex-chat-mcp/TESTING.md
@@ -164,7 +164,7 @@ The MCP server and the SessionStart, UserPromptSubmit, Stop, PostModelSwitch, Po
- The status line setting, run by `sh`, prints the status line through `status-line.js` of the data folder, which runs the unpacked package's command, with `SIMPLEX_MCP_HOME` and with `~/.simplex-mcp`.
- `npm run test:e2e`, file `test/e2e/service.test.ts`, runs with a local smp-server and xftp-server:
- An owner joins the Main group and the groups of two sessions, and approves `connect`, `send`, `download` and `leave` there. The owner's copies of the sessions' groups have the chat layout `terminal`, and the Main group has none. Chats belong to their sessions, and the owner moves one to the other session with `/give`. `/list` works after a service restart. The short description and the welcome message that the owner set in the Main group stay after the restart.
- - The Main group shows the list of sessions after the owner joins. The attached session's line follows the record file that its `/session` names: working, waiting for you with the card of a permission request, idle, and the last line after it detaches. Each change edits the same message, and `/sessions` replies with the same text.
+ - The Main group shows a message of the attached session and the summary after the owner joins. The message follows the record file that its `/session` names: working, waiting for you with the card of a permission request, idle, and stopped after it detaches. Each change edits the same message and the summary, and `/sessions` replies with the list of sessions.
- While files and media are off in a session's group, the card of a `send` of an image is text. After the owner's approval, the image message reaches the bot with its caption and its file, and the card is edited as text.
- While SimpleX links are off in a session's group:
- A `send` card is posted with the local server's SimpleX link at the end of its code span, because the core does not detect a link whose query is followed by the closing backtick.
@@ -246,7 +246,7 @@ In a session started as in step 2 above:
- The plugin's folder had no `node_modules/.package-lock.json`.
- With the same keys in `.claude/settings.json` of the folder, and without `--settings`, the run had no tool of the plugin.
19. Start Claude Code as in step 2 with an empty data folder and a machine name: `SIMPLEX_MCP_HOME=/tmp/simplex-mcp-fresh SIMPLEX_MCP_MACHINE=laptop claude --plugin-dir /tmp/simplex-plugin --dangerously-load-development-channels plugin:simplex@inline`. Exit it before the QR code shows. Start it again the same way. The QR code shows within seconds, for the group "Claude Control - laptop". Stop that service: `kill $(cat /tmp/simplex-mcp-fresh/service.lock)`.
-20. With the session of step 2 running and a second session started as in step 2 in another folder, the Main group shows the list of sessions, one line for each. Ask Claude to run `sleep 20` with Bash: its line shows 🟢 working. Send `Run ls with Bash.` in its group: the line shows 🟠 waiting for you, 1 approval; tap `/approve N`, and it shows 🟢 working, then 🔴 idle when the turn ends. Press Esc during a turn: the line shows 🔴 idle within 2 seconds, although Claude Code runs no Stop hook. Ask Claude to run `sleep 60` with Bash in the background: after its turn ends, the line shows ⚙️ working in the background until the command ends. Ask Claude to ask you a question with AskUserQuestion: the line shows ⛔️ waiting for you in Claude Code. Exit the second Claude Code: its session moves into the last line, `⚪ Not running: `. `/sessions` replies with the same text.
+20. With the session of step 2 running and a second session started as in step 2 in another folder, the Main group shows one message for each, with the Claude account, the model and the effort, and the summary `2 sessions` with their state emojis. After `/goal` with a condition, the message and the session group's short description show `goal set`, and `goal met` once it is met. After a recap, as when the terminal loses focus at the end of a turn, the message and the group's description show it. Ask Claude to run `sleep 20` with Bash: its message shows 🟢 working. Send `Run ls with Bash.` in its group: the line shows 🟠 waiting for you, 1 approval; tap `/approve N`, and it shows 🟢 working, then 🔴 idle when the turn ends. Press Esc during a turn: the line shows 🔴 idle within 2 seconds, although Claude Code runs no Stop hook. Ask Claude to run `sleep 60` with Bash in the background: after its turn ends, the line shows ⚙️ working in the background until the command ends. Ask Claude to ask you a question with AskUserQuestion: the line shows ⛔️ waiting for you in Claude Code. Exit the second Claude Code: its message shows ⚪ stopped. `/sessions` replies with the list of sessions, the stopped one in its last line, `⚪ Not running: `. Ask Claude for a background Explore agent and a foreground agent: each gets a live message in the session group, `🤖 TYPE · DESCRIPTION` with its steps, tokens, time and current step, matching the terminal; the board message shows `🤖 2 agents working`. Pause one agent on a long `sleep` without a timeout: after 10 minutes it shows `⚠️ no step for`. Each message ends with ✅, its time, steps, tokens and result, and the agent's notification posts no line. Run a two-phase workflow: one message shows its phases with done/total, and ends with ✅.
21. Send `Read README.md, say what you are doing before each step, and then summarize it in 30 lines.` in the group. An empty message from Claude appears at once, as a reply to your message, with typing dots. Claude's first remark or step fills it, and each later remark and the answer appear from their first line, growing by whole lines, at most every 3 seconds. The steps' lines appear between them. Each message ends without an edited mark. The answer's message ends with `Done in`, the turn's time and tokens in small print, and the chat list shows the answer. In the terminal, Claude's text appears by whole lines.
22. Send `Name a fruit.` in the group, and after the answer edit that message to `Name a vegetable.` Claude answers with a vegetable, as a reply to your message. In the transcript, the second tag has the same `item` as the first and `edited="true"`. Edit it into `/list`, and nothing happens. Turn on live mode in the app, type `Name a colour.` slowly, and send it. Claude answers once, after you send it, and the transcript has one tag with `Name a colour.`
23. Stop the service: `kill $(cat /tmp/simplex-mcp-test/service.lock)`.
diff --git a/packages/simplex-chat-mcp/hooks/hooks.json b/packages/simplex-chat-mcp/hooks/hooks.json
index f8eabe2d6d..e113a38fc7 100644
--- a/packages/simplex-chat-mcp/hooks/hooks.json
+++ b/packages/simplex-chat-mcp/hooks/hooks.json
@@ -7,6 +7,8 @@
"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}],
"Stop": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}],
"PostModelSwitch": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}],
+ "SubagentStart": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}],
+ "SubagentStop": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}],
"PostCompact": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/cli.js\" hook turn", "async": true}]}],
"MessageDisplay": [{"hooks": [{"type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/display.js\"", "timeout": 2}]}]
}
diff --git a/packages/simplex-chat-mcp/spec/api.md b/packages/simplex-chat-mcp/spec/api.md
index 12fdeec79b..12e2cd85dd 100644
--- a/packages/simplex-chat-mcp/spec/api.md
+++ b/packages/simplex-chat-mcp/spec/api.md
@@ -731,13 +731,28 @@ Posts:
|---|---|---|
| the first owner joined | `I'm Claude. Each Claude Code session has its own group, and you get its invitation here. /sessions lists the sessions; /join N joins the group of session N.` | [`greeting`, `MainGroup.ownerJoined`](../src/main-group.ts) |
| each `joinedGroupMember` or `connectedToGroupMember` of a human who is found among the members read again. For the first owner, it is posted after the greeting | `NAME joined. They can join the group of any Claude Code session here, prompt Claude and approve its actions.` | [`joinRights`, `MainGroup.handleEvent`](../src/main-group.ts) |
-| the first render of the list of sessions while the group has an owner, so after the greeting; a list 23 hours old, or one whose edit the core refuses with `invalidChatItemUpdate` or `chatItemNotFound` | the list of sessions, below, with `priority: -1`. A new list replaces an old one, which is then deleted for everyone; a refused deletion is logged as `old list of sessions: ERROR` | [`MainGroup.showList`, `replaceList`, `postList`](../src/main-group.ts) |
+| a running session without a message on the board, while the group has an owner, so after the greeting; a message whose edit the core refuses with `invalidChatItemUpdate` or `chatItemNotFound` | the session's message of the board, below, with `priority: -1` | [`MainGroup.showBoard`, `renderEntry`, `postEntry`](../src/main-group.ts) |
+| the first render with a session message while the group has an owner; a summary whose edit the core refuses | the summary of the board, below, with `priority: -1` | [`MainGroup.showBoard`, `renderSummary`](../src/main-group.ts) |
-The list of sessions ([`Hub.sessionsText`, `Hub.showSessions`, `Session.stateLine`](../src/hub.ts)):
+The board of sessions ([`Hub.showSessions`, `Session.boardSession`, `stoppedState`](../src/hub.ts), [`MainGroup.showBoard`, `BoardSession`, `summaryText`, `boardAge`](../src/main-group.ts)):
+
+- Each running session has one message, and each session that stopped keeps its message until the message is 23 hours old, when it is deleted for everyone. A session is running while it has a line in the list of sessions below.
+- The message of a session has these lines, the unknown ones left out:
+ - the state: the session's line of the list of sessions below, or `⚪ N · NAME: stopped`;
+ - the title: `*TITLE*`, Claude Code's title of the conversation, when it differs from NAME; without the bold marks when it has `*`;
+ - the details: the short description of the session group ([4.3](#43-session-groups));
+ - the agents line while subagents or workflows work ([4.3](#agent-messages));
+ - the recap: the description of the session group.
+- The summary is `N sessions` and the state emoji of each session with a message, by number, separated by spaces, as `4 sessions 🟠 🟢 ⛔️ ⚪`; `1 session` for one; `No sessions.` without a message.
+- Every 2 s, and once at the service's stop before the wait for the cancelled cards, the hub renders the board by session number. A message or the summary is edited only when its text differs from its text last posted or edited; the first render after a start edits each once. A message whose edit is refused is deleted for everyone and, for a running session, posted again; a refused summary is deleted and posted again. The summary is never posted again for another reason, so posts that follow it, such as a new session's message, an invitation or a reply, leave it above them. A refused deletion is logged as `old message of the board: ERROR` or `old summary of the board: ERROR`.
+- The items and their post times are kept in the Main group's custom data as `simplexMcpBoard`. When they can't be saved, the messages posted in that render are deleted for everyone, the failure is logged as `board of sessions: ERROR`, and the next render tries again. A message of a session the hub does not have is deleted.
+- The list of the earlier version, `simplexMcpList`, is deleted for everyone at the first render, and its key is removed with the save of the board.
+
+The list of sessions, the reply to `/sessions` ([`Hub.sessionsText`, `Session.stateLine`](../src/hub.ts)):
| Part | Text | Condition |
|---|---|---|
-| a running session | `🟠 N · NAME: waiting for you, K approvals`, `1 approval` for one | K pending cards of the session, without those cancelled by a stop. A tool-use card counts while Claude Code's state is `waiting` or unknown |
+| a running session | `🟠 N · NAME: waiting for you, K approvals`, `1 approval` for one | K pending cards of the session, without those cancelled by a stop, whatever Claude Code's state: a subagent's tool-use card has no dialog in the terminal, so Claude Code's state stays `busy` while it waits |
| | `⛔️ N · NAME: waiting for you in Claude Code` | no card; attached; state `waiting` |
| | `🟢 N · NAME: working` | no card; attached; state `busy` |
| | `🔴 N · NAME: idle` | no card; attached; state `idle` |
@@ -749,9 +764,6 @@ Posts:
- A session is attached while its session server is attached and the service does not stop. Its state is the `status` of Claude Code's record of the session server's parent, `CLAUDE_CONFIG_DIR` or `~/.claude`, then `sessions/PID.json`, read every 2 s for each attached session. A record that does not parse keeps the last state read; a path that is not a regular file, such as a FIFO, gives no state. A render waits at most 1 s for a read; a read that takes longer keeps the last state, and no new read of that record starts until it ends ([`Session.readRecord`, `recordStatus`](../src/hub.ts)). A status other than `busy`, `waiting`, `idle` and `shell` is unknown.
- The lines of running sessions come by number, then the line of the other sessions. Lines are joined by line breaks.
- The text fits one message, by `fitsMessage`. The lines of running sessions are kept whole. The last line keeps the most names, newest first, for which the text, with `, K older sessions` for the K left out (`1 older session` for one), still fits. When no name fits, it is `⚪ Not running: K older sessions`.
-- Every 2 s, and once at the service's stop before the wait for the cancelled cards, the hub renders the text, and Claude edits the list when the text differs from the text last posted or edited. The first render after a start always edits.
-- A text that the core refuses as too large, `errorStore largeMsg`, as with more lines of running sessions than one message holds, is logged as `list of sessions: ERROR` once, and not sent again until the text changes; the list keeps its last text.
-- When the item of a new list can't be saved in the Main group's custom data, the new list is deleted for everyone, the old one stays, and the next render tries again.
The session groups stay as they are when the membership or a role in the Main group is changed, and when the Main group is replaced by a reset of the owners. Members invited through the old Main group keep their roles in the session groups, with the rights of those roles ([`MainGroup.handleEvent`, `replace`](../src/main-group.ts), [`Session.approves`](../src/hub.ts)).
@@ -765,7 +777,7 @@ The session groups stay as they are when the membership or a role in the Main gr
| history | on |
| direct messages | on for the role `owner` |
| command menu | `/sessions` "Claude Code sessions"
`/join` "Join the group of a session", params `` |
-| custom data | `{simplexMcpMain: true}`, and `simplexMcpList: {item, at}`, the list of sessions and the time it was posted |
+| custom data | `{simplexMcpMain: true}`, and `simplexMcpBoard: {summary?: {item, at}, sessions: [{session, item, at}]}`, the items of the board and the times they were posted |
Claude updates only the display name and the command menu, starting each time from the group's current profile in the chat database. So the short description, the description and the preferences that owners set stay ([`MainGroup.load`](../src/main-group.ts), [`updateGroupProfile`, `changeGroupProfile`](../src/control.ts)).
@@ -886,6 +898,22 @@ Posts:
| Claude | files sent by `reply`, at once | [`AgentTools.reply`, `sendFile`](../src/tools.ts), the `replyChat` of the [`Session`](../src/hub.ts) constructor |
| Claude | the rights of the member's role, below. They are posted once for each join and each role change of a member other than `User`, at its `joinedGroupMember`, `connectedToGroupMember` or `memberRole` | [`Session.announceRights`, `Hub.onEvent`](../src/hub.ts), [`approverRights`, `senderRights`, `observerRights`, `sessionApproverRoles`, `canSend`, `rightsText`](../src/control.ts) |
+Subagents and workflows ([`Session.onAgents`, `readAgents`, `showCard`, `cardEditMs`](../src/hub.ts), [`Agents`, `cardText`, `agentsLine`](../src/agents.ts), [`agentStart`, `agentStep`, `leadTask`, `taskOf`](../src/hook.ts)):
+
+| State | Text | Live |
+|---|---|---|
+| a subagent working | `🤖 TYPE · DESCRIPTION`, then `N steps · X tokens · M:SS · now: STEP`, or `· last: STEP` with no open step | on |
+| stalled: no event for over 2 min with no open step, or 10 min with one | `🤖 TYPE · DESCRIPTION`, then `N steps · X tokens · M:SS · ⚠️ no step for M:SS · last: STEP` | on |
+| ended | `🤖 TYPE · DESCRIPTION · ✅ M:SS · N steps · X tokens`, then the first line of its hand-back or its answer; `❌` for a failure, `⏹️` for a kill, a stop, the last detach, the hub's stop or 23 hours | off |
+| a workflow working | `⚙️ NAME · PHASE d/t · … · K working · X tokens · M:SS`, d the ended agents of the phase and t its started ones, ` ✅` after a phase that is done when a later one started | on |
+| a workflow ended | `⚙️ NAME · ✅ M:SS · PHASE d/t · … · X tokens` | off |
+
+- Each subagent that SubagentStart reports with its record, and each workflow that the lead starts, get one message, with priority -1, sent live. Teammates and workflow agents get none; the lead's `Agent` and `Workflow` tool uses get no step line.
+- TYPE is `agent_type`; DESCRIPTION the record's; steps the subagent's tool uses; X the input, cache and output tokens of its latest request in its transcript, read every 2 s, and at the end the figures of the lead's result or task notification; M:SS the time since its start, in 5 s steps while live.
+- A live message is edited at most every 5 s while its text changes; its end is edited at once with `liveMessage: false`, and again when the task's figures arrive. The note of a task notification of a known agent or workflow is not posted. A subagent resumed after its end gets a new message.
+- Edits leave a message where it was posted.
+- While subagents or workflows work, the session's message on the board has a line `🤖 N agents working · K stalled M:SS · ⚙️ NAME PHASE d/t`. The session group's short description shows no counts.
+
Rights posts, by the member's role in the session group:
| Role | Post |
@@ -925,8 +953,8 @@ at = performance.timeOrigin of the hook process; absent: Infinity for an answer'
| Field | Value |
|---|---|
| display name | `N · NAME`, folded to a valid display name, renamed at a new title |
-| description | `The Claude Code session N. Members send it prompts; admins and owners also send the group's commands and approve tool use.`, set only when the group is created |
-| short description | `MODEL · effort LEVEL`, the parts known so far |
+| description | the latest recap of Claude Code, none before the first; a group is created without one |
+| short description | `ACCOUNT · MODEL · effort LEVEL · goal STATE`, the parts known so far: ACCOUNT the email of Claude Code's OAuth account, STATE `set`, `met` or `failed`, none without a goal |
| history | on |
| direct messages | off |
| command menu | as in [2.5](#25-group-profile) |
@@ -934,7 +962,9 @@ at = performance.timeOrigin of the hook process; absent: Infinity for an answer'
| members | `Claude`, the members invited through the Main group, the members others added directly, `User` |
| peer types | `Claude` `agent`; `User` `human`, set at each service start ([`User.open`](../src/user.ts), [`updatedUser`](../src/core.ts)). A member who joined while `User` had `agent`, as in 0.3.0, gets `human` with `User`'s next post in the group, with the event `updated profile`: the core sends a member's profile to a group before the next message after a change of its name, full name, short description, description, image or peer type |
-Claude makes the profile updates one at a time. It starts each from the group's current profile in the chat database and changes only the display name, the short description or the command menu. So a rename and a model change that overlap both stay.
+Claude makes the profile updates one at a time. It starts each from the group's current profile in the chat database and changes only the display name, the short description, the description or the command menu. So a rename and a model change that overlap both stay. The short description and the description are set together, when the model, the effort level, the account, the goal state or the recap changes; so a description an owner wrote, or the one of an earlier version, is replaced then. After an update that changed the profile, the next one waits until a minute has passed and then sets the values of that time, because each update shows `updated group profile` to every member ([`Session.describe`, `profileEveryMs`](../src/hub.ts)).
+
+The hub reads the account, the goal state, the recap and the title of each attached session every 2 s, with its record, by `AccountReader` and `TranscriptReader` ([architecture](architecture.md#claude-code-transcriptreader)), and keeps them in the session's `session.json` ([`Session.readClaudeCode`](../src/hub.ts)).
The hub takes the model and the effort level of a `/turn` only when its `at` is not older than the `at` of the value it took last. It keeps the two times apart, one for the model and one for the effort level. The model of a `/title` comes with the `at` of its SessionStart hook, as described in [4.6](#46-socket-protocol). A request without `at` counts as the current time. So when a Stop request that waited for its transcript entry arrives after a later model switch, the model of the switch stays ([`Session.turn`, `newer`](../src/hub.ts)). The model of a request with an answer that equals the shown model without a final `[1m]` counts as the shown model, because the transcript names the 1M context variant without that suffix ([`Session.turn`](../src/hub.ts)).
@@ -1013,8 +1043,8 @@ The prompts of a session, from the members of [4.3](#43-session-groups), are del
| Route | Request | Reply | Code |
|---|---|---|---|
-| `POST /session` | `{id, pid?, project, name?, config: {mainGroup, approve, expireHours}, record?}`, `pid` the session server's parent process, `record` the absolute path of Claude Code's record of that process, which the session's line in the list of sessions reads | `{number, displayName, version, protocol, owner: {owners}}`. For a `pid` marked unattended, the reply is status 403, see below. The mark is checked before and after the wait for the title of `pid` | [`Service.onSession`, `refuseUnattended`](../src/service.ts) |
-| `POST /title` | `{id, pid?, at?, name?, project, model?, config, unattended?}`, `pid` from `CLAUDE_PID`, `at` the `performance.timeOrigin` of the SessionStart hook | `{mainGroup, owner: {owners, link?}, version, protocol}`, after the title is applied, or at once for a held title. With `unattended: true`, the reply comes at once, and no session is opened. Marks 10 s old and older are removed, `pid` is marked, and a server's wait for its title ends | [`Service.onTitle`, `markUnattended`, `applyTitle`](../src/service.ts) |
+| `POST /session` | `{id, pid?, project, name?, config: {mainGroup, approve, expireHours}, record?, globalConfig?}`, `pid` the session server's parent process, `record` the absolute path of Claude Code's record of that process, which the session's line in the list of sessions reads, `globalConfig` the absolute path of Claude Code's global config, which holds the session's account | `{number, displayName, version, protocol, owner: {owners}}`. For a `pid` marked unattended, the reply is status 403, see below. The mark is checked before and after the wait for the title of `pid` | [`Service.onSession`, `refuseUnattended`](../src/service.ts) |
+| `POST /title` | `{id, pid?, at?, name?, project, model?, transcript?, config, unattended?}`, `pid` from `CLAUDE_PID`, `at` the `performance.timeOrigin` of the SessionStart hook, `transcript` its `transcript_path`, which replaces the session's transcript | `{mainGroup, owner: {owners, link?}, version, protocol}`, after the title is applied, or at once for a held title. With `unattended: true`, the reply comes at once, and no session is opened. Marks 10 s old and older are removed, `pid` is marked, and a server's wait for its title ends | [`Service.onTitle`, `markUnattended`, `applyTitle`](../src/service.ts) |
| `POST /attach` | `{id, pid?}`, `pid` the session server's parent process | a stream held open: the first line `{version, protocol}`, then `{prompt: {text, from, item, file?, replyTo?: {item?, from?}}}`, `{permission}` and `{tools}` lines. `tools` is the full list of the session's approved tools, `[{tool, approvedBy}]`, sent when it changes and to each new attachment while it is not empty ([4.3](#43-session-groups)). An attachment whose `pid` is not the one of the session's last `/session` gets `{tools: []}` in place of each `{tools}` line | [`Service.onAttach`](../src/service.ts), [`AttachLine`, `ApprovedTool`, `AttachRequest`](../src/protocol.ts), [`Session.onLine`, `sendTools`](../src/hub.ts) |
| `POST /call` | `{id, tool, input}` | lines `{progress: TEXT}`, then one line `{result: CallToolResult or null}`. The call is aborted when the request is closed | [`Service.onCall`](../src/service.ts) |
| `POST /permission` | `{id, requestId, toolName, description, inputPreview}` | `{}` after the card's action is created | [`Service.routes`](../src/service.ts) |
@@ -1083,7 +1113,7 @@ on the next start: each one taken as a new /title
| `simplex-mcp session` | `.mcp.json` | MCP over stdio |
| `simplex-mcp service` | `spawnService`, through the launcher `node -e LAUNCHER COMMAND ARGS`, which spawns the service with fd 1, 2 and 3 of its own and exits at once, so the service is no descendant of the hook or session process. The launcher writes `error: TEXT` when the spawn fails ([`launcher`, `spawnService`](../src/client.ts)) | the ready line `ready`, `running` or `error: TEXT` on fd `SIMPLEX_MCP_READY_FD`, or on stdout when it is unset. The line is dropped when its reader is gone, and the service keeps running ([`readyChannel`, `writeReady`](../src/service.ts)). If another running process holds ROOT/service.lock, the service checks the lock and the socket up to 150 times, 100 ms apart. It starts again once the lock is released, and its ready line is `running` once the socket answers. The log is written to stdout and stderr |
| `simplex-mcp hook session-start` | SessionStart hook | one JSON line, see [4.8](#48-plugin-options-files-and-hook-output) |
-| `simplex-mcp hook turn` | UserPromptSubmit, Stop, PostModelSwitch, PreToolUse, PostToolUse, PostToolUseFailure and PostCompact hooks | `{}`. A prompt or an answer over 250,000 characters is cut there and ends with `…` ([`maxText`, `cut`](../src/hook.ts)). The Stop hook sends the model of its answer and the usage of its turn, read from the transcript, and the PostModelSwitch hook sends its model with `switched`, see [4.8](#48-plugin-options-files-and-hook-output) ([`turn`, `eventFields`, `answerRecord`, `findInTranscript`, `readTail`, `lastAnswer`, `turnUsage`, `usageOf`](../src/hook.ts)). The UserPromptSubmit hook sends `typed`, `note` and `midTurn`, read from the prompt's record in the transcript ([`turn`, `promptKind`](../src/hook.ts)). The tool hooks send `step`, see [4.8](#48-plugin-options-files-and-hook-output), and nothing for a tool use of a subagent or of this plugin, or without `tool_use_id` or `tool_name` ([`turn`, `eventFields`, `stepOf`](../src/hook.ts)). The PostCompact hook sends `note` from the compaction's boundary in the transcript, and nothing for a subagent's compaction ([`eventFields`, `compactionNote`](../src/hook.ts), [flow 35](flows.md#35-a-summary-of-the-sessions-context)) |
+| `simplex-mcp hook turn` | UserPromptSubmit, Stop, PostModelSwitch, PreToolUse, PostToolUse, PostToolUseFailure, PostCompact, SubagentStart and SubagentStop hooks | `{}`. A prompt or an answer over 250,000 characters is cut there and ends with `…` ([`maxText`, `cut`](../src/hook.ts)). The Stop hook sends the model of its answer and the usage of its turn, read from the transcript, and the PostModelSwitch hook sends its model with `switched`, see [4.8](#48-plugin-options-files-and-hook-output) ([`turn`, `eventFields`, `answerRecord`, `findInTranscript`, `readTail`, `lastAnswer`, `turnUsage`, `usageOf`](../src/hook.ts)). The UserPromptSubmit hook sends `typed`, `note` and `midTurn`, read from the prompt's record in the transcript ([`turn`, `promptKind`](../src/hook.ts)). The tool hooks send `step`, see [4.8](#48-plugin-options-files-and-hook-output), and nothing for a tool use of a subagent or of this plugin, or without `tool_use_id` or `tool_name` ([`turn`, `eventFields`, `stepOf`](../src/hook.ts)). The PostCompact hook sends `note` from the compaction's boundary in the transcript, and nothing for a subagent's compaction ([`eventFields`, `compactionNote`](../src/hook.ts), [flow 35](flows.md#35-a-summary-of-the-sessions-context)) |
| `node dist/display.js` | MessageDisplay hook | `{}`, after `POST /turn` with `text`, see [4.8](#48-plugin-options-files-and-hook-output) |
| `node ROOT/status-line.js` | Claude Code's status line, with the person's `statusLine` setting | the status line, and then `POST /turn` with `effort` and `limits`, see [4.8](#48-plugin-options-files-and-hook-output) |
| `simplex-mcp link` | people | with owners, `Owners of "MAIN": A, B. To replace them, run npx -y @simplex-chat/mcp@VERSION reset-owners in a terminal.` When the service reports neither owners nor a link, `The Main group has no link. Run npx -y @simplex-chat/mcp@VERSION reset-owners in a terminal.` Otherwise, on a terminal, `Join "MAIN" in the SimpleX app. The link works once:`, a QR code and the link, and elsewhere `Run npx -y @simplex-chat/mcp@VERSION link in a terminal to see the link to "MAIN".` |
diff --git a/packages/simplex-chat-mcp/spec/architecture.md b/packages/simplex-chat-mcp/spec/architecture.md
index 738955151f..e09438dc2f 100644
--- a/packages/simplex-chat-mcp/spec/architecture.md
+++ b/packages/simplex-chat-mcp/spec/architecture.md
@@ -784,7 +784,7 @@ Data flow of a prompt from the session group:
| Symbol | Contents |
|---|---|
| `unattendedRun`, `channelInstructions`, `permissionRequest` | the text of a run that is not interactive; instructions of the channel; schema of a permission request |
-| `startSession` | The session ID and the options are checked. Every call is answered with a text when the run is not interactive or the options are invalid. The `McpServer` gets the instructions, the capabilities `claude/channel` and `claude/channel/permission`, the tools with `reply`, `pre_tool_use`, the permission request handler and a stdio transport. `pre_tool_use`, with the description and schema of `hookTool`, answers with `hookOutput` of `ServiceLink.approvedBy`, also when the run is not interactive or the options are invalid ([API 4.1](api.md#41-tools-in-the-plugin)). Without such a text, the session process connects to the service in the background. Its `POST /session` has `record`, the absolute path of Claude Code's record of the parent process: `CLAUDE_CONFIG_DIR` or `~/.claude`, then `sessions/PID.json`. |
+| `startSession` | The session ID and the options are checked. Every call is answered with a text when the run is not interactive or the options are invalid. The `McpServer` gets the instructions, the capabilities `claude/channel` and `claude/channel/permission`, the tools with `reply`, `pre_tool_use`, the permission request handler and a stdio transport. `pre_tool_use`, with the description and schema of `hookTool`, answers with `hookOutput` of `ServiceLink.approvedBy`, also when the run is not interactive or the options are invalid ([API 4.1](api.md#41-tools-in-the-plugin)). Without such a text, the session process connects to the service in the background. Its `POST /session` has `record`, the absolute path of Claude Code's record of the parent process: `CLAUDE_CONFIG_DIR` or `~/.claude`, then `sessions/PID.json`, and `globalConfig`, the absolute path of Claude Code's global config: `CLAUDE_CONFIG_DIR` or `~`, then `.claude.json`. |
| `ServiceLink.approvedBy` | the approver of a tool in the approved tools of the current attachment, or none without an attachment |
| `ServiceLink.connect`, `start`, `close`, `reconnect` | one shared connect promise, refused at once after a 403 of `/session`. After that refusal, and after `close`, `start` neither logs nor reconnects. Otherwise `start` logs a failure on stderr, and connects again later unless the failure is a `ProtocolError`. `close` ends the attachment and the retries. `reconnect` sets one timer that starts the connection again after the delay. The delay is 1 s at first, and doubles each time the timer fires, up to 30 s. |
| `ServiceLink.permission` | `POST /permission` after the connect, and nothing after the refusal |
@@ -825,6 +825,7 @@ Data flow of a prompt from the session group:
| `SessionRequest`, `TitleRequest` | `/session`, `/title`, with `unattended` for the mark of a process |
| `PermissionRequest`, `TurnRequest` | `/permission`, `/turn` |
| `Step` | `step` of `/turn`: the tool use's ID, the line's text, and `end` at the tool use's end |
+| `AgentEvent`, `AgentStart`, `TaskEnd`, `TaskStatus`, `WorkflowRun` | `agent` of `/turn`: the subagent's ID and one of `start` `{type, description, toolUse?, transcript}`, `step` (a `Step`), `report` and `stop`, each the first line of the text. `task`: the lead's tool use of an agent or a workflow, its status `completed`, `failed`, `killed` or `stopped`, and `tokens`, `steps` and `ms` when known. `workflow`: the lead's tool use of `Workflow`, the run's ID, the workflow's name and its transcript folder |
| `TextBatch` | `text` of `/turn`: the `message_id` of Claude's text, the batch's index, `final` at the text's last batch, and the batch's text |
| `Limits`, `LimitWindow` | `limits` of `/turn`: the plan's 5-hour and weekly windows of the status line command, each the share used in percent and the reset time in Unix seconds |
| `AttachLine`, `ApprovedTool` | `{prompt}` lines, with the `replyTo` of a reply or a reaction and `edited` of an edit, `{permission}` and `{tools}` lines of `/attach`; an approved tool with its approver's name |
@@ -864,7 +865,10 @@ Data flow of a prompt from the session group:
| `SessionGroupData` | session number; pending connections of `connect` with their time; the approved mode |
| `Session` | one Claude Code session, built from its `session.json` and its group's data. `Actions` get the hub's texts and the mode of the group's data, or `requests` without one. `AgentTools` get the session's ID and folder and the group for `reply`. `Control` of the session group gets the session's approver checks. The stored model and effort are kept as well. |
| `Session.busy` | an action other than a `mode` card in memory |
-| `Session.readRecord`, `stateLine`, `attached`, `recordStatus`, `withinTime` | `readRecord` reads `status` of Claude Code's record while the session is attached and the hub does not stop; otherwise, and for a missing path or file, the status is cleared, and a file that does not parse keeps it. One read of a record runs at a time, `Session.recordRead`, and a render waits for it at most 1 s, by `withinTime`. `recordStatus` opens the record with `O_NONBLOCK`, so a FIFO does not block, and reads only a regular file. `stateLine` is the session's line in the list of sessions, or none without a card and an attachment. A tool-use card counts while the status is `waiting` or not one of `claudeStates`, and a card cancelled by a stop never. |
+| `Session.readRecord`, `readStatus`, `stateLine`, `state`, `attached`, `recordStatus`, `withinTime` | `readRecord`, while the session is attached and the hub does not stop, runs `readStatus` and `readClaudeCode`; otherwise the status is cleared. `readStatus` reads `status` of Claude Code's record; for a missing path or file the status is cleared, and a file that does not parse keeps it. One read runs at a time, `Session.recordRead`, and a render waits for it at most 1 s, by `withinTime`. `recordStatus` opens the record with `O_NONBLOCK`, so a FIFO does not block, and reads only a regular file. `state` is the emoji and the text of the session's state, or none without a card and an attachment, and `stateLine` its line in the list of sessions. Every pending card counts, whatever the status, and a card cancelled by a stop never. |
+| `Session.readClaudeCode`, `ClaudeState`, `globalConfig`, `transcript` | the account by `AccountReader` from `globalConfig`, and the goal state, the recap and the title by `TranscriptReader` from `transcript`, each kept when its path is unknown. The values start from `session.json`. When one changes, they and the transcript path are stored in `session.json`, and the group's descriptions are set by `Session.describe`; a failure of that update is logged as `description of session N: ERROR`. |
+| `Session.boardSession`, `details`, `describe`, `stoppedState` | `boardSession` is the session's number, whether it runs, its state emoji and the text of its message on the board ([api.md](api.md#session-board)). `details` is the short description: the account, the model, `effort LEVEL` and `goal STATE`, the known ones joined by ` · `. `describe` sets the short description to `details`, none when empty, and the description to the recap, or none, once for each change of either; after an update that changed the profile, the next one waits until `Hub.profileMs`, 1 minute, has passed, with the values at that time. `boardSession` adds the line of `agentsLine` while subagents or workflows work. |
+| `Session.onAgents`, `readAgents`, `readAgent`, `readWorkflow`, `postCard`, `showCard`, `stopDescribing`, `cardEditMs` | `onAgents`, before the first await of `Session.turn`: a `workflow` or an `agent.start` posts a live message with priority -1; `step`, `report` and `stop` change the subagent's state; a `stop` and a `task` of a known agent or workflow edit its message at once with `liveMessage: false`, after a read of the workflow's journal, and the note of that request is not posted. `readAgents`, in `readRecord`: the tokens of each working subagent from `lastUsage` of its transcript, the journal and the tokens of each working workflow, ⏹️ for a message 23 hours old, then `showCard` of every message. `showCard` edits a live message when its text changed and 5 s passed since its last edit, and an ended one when its text changed; the edits of one message are chained in order. `endLive` ends every live message with ⏹️. `stopDescribing` cancels a waiting description update at the hub's stop. |
| `Session.requestMode`, `askMode` | `requests` applies at once. The hub then ends pending `mode` cards and clears `hostDeclined`. `host` is remembered and asked as a `mode` action while an approver is in the group and `hostDeclined` is unset. The request is forgotten after a rejected or expired card, and `hostDeclined` is set after a rejection. |
| `Session.onLine` | the writer of the session's attachments. The approved tools are sent to a new writer, and the held prompts are woken at each change. |
| `Session.onMessage`, `pass`, `replyTo` | A new message of a member first passes that member's pending live messages by `passLive`. A message typed in live mode is kept by `keepLive` and waits for its final version. Other messages go to `pass`. `pass` answers a `/` command from a member who is not an approver with the one refusal, found by `refusesCommand` and posted on the `delivery` chain. The remaining one-line `/` texts go to `Control`, and other messages go to `prompt` on the `delivery` chain, in arrival order. The `replyTo` of a reply is computed here from its quote, with the hub's profile name as Claude's name and Claude's own text without its end line by `withoutEndLine`, and passed with the message and its file. |
@@ -889,7 +893,7 @@ Data flow of a prompt from the session group:
| `Hub.configure`, `resetOwners` | expiry of all sessions and the Main group name. The Main group is replaced at once, even while owners exist. |
| `Hub.session` | the open session, renamed when its name changed, or a new `Session` with its stored or new group. The owners are invited to a new group. |
| `Hub.sessionsText`, `join`, `inviteOwner` | `SessionGroups` of the Main group. `sessionsText` is the text of the list of sessions: the lines of the running sessions by number, then `⚪ Not running: ` with the other sessions newest first, or `No sessions.` The last line keeps the most names for which the text, with the count of the rest, fits one message with the given quote; a binary search finds them. |
-| `Hub.showSessions`, `notRunningLine` | one render at a time: the records of the sessions read, and the text passed to `MainGroup.showList`; a failure is logged as `list of sessions: ERROR`. `notRunningLine` is the last line with the first K names and the count of the rest. |
+| `Hub.showSessions`, `notRunningLine` | one render at a time: the records of the sessions read, and their `boardSession`, by number, passed to `MainGroup.showBoard`; a failure is logged as `board of sessions: ERROR`. `notRunningLine` is the last line with the first K names and the count of the rest. |
| `Hub.stop` | the timer of the list cleared, actions stopped, events awaited, the running render awaited, one more render with every session not running, cancelled cards awaited up to 10 s, steps, opening messages and texts ended by `endLive` with their updates awaited, cores closed |
| `storedGroup`, `createSessionGroup` | the group of `session.json` with a matching session number; a new group in the Flat layout with `User` added |
| `Hub.onEvent` | event dispatch. A new item of a session group goes to its `onMessage`, a reaction to its `onReaction`, and an updated item to its `onUpdate`. Pending connections are claimed at `contactConnected` and `userJoinedGroup`. A session group's membership events go to its `Control`, `sendTools`, `announceRights` and `askMode`, one at a time. |
@@ -909,7 +913,7 @@ Data flow of a prompt from the session group:
| `MainGroup.onMessage`, `command` | `/sessions`, `/join N`; `Unknown command.` for another |
| `MainGroup.onEvent`, `handleEvent`, `ownerJoined` | The members are read again. The first human who joins becomes an owner. A new link is created when no owner remains. The statement of trust is posted at each human's join. New owners are invited to the open sessions. |
| `MainGroup.replace` | The Main group is deleted for all its members, and a new one is created with a new link, without a list of sessions. The session groups are kept. |
-| `MainGroup.showList`, `renderList`, `replaceList`, `postList`, `deleteItem`, `isRefusedEdit`, `isTooLarge` | `showList`, after the group's earlier events: nothing while the group is lost or for the text last refused as too large, `MainGroup.tooLarge`; such a refusal is kept and logged. `renderList`: without a list, a list posted while the group has an owner; a list 23 hours old replaced; an edit when the text differs from the text last shown; an edit refused with `invalidChatItemUpdate` or `chatItemNotFound` replaced. `postList` posts the text with priority -1 and saves the item and its time in the group's custom data; when the save fails, the new item is deleted for everyone and the error is passed on. `replaceList` posts a new list and deletes the old one for everyone, logging a refusal as `old list of sessions: ERROR`. |
+| `MainGroup.showBoard`, `renderEntry`, `postEntry`, `deleteEntry`, `renderSummary`, `edited`, `postItem`, `saveBoard`, `deleteItem`, `isRefusedEdit` | `showBoard`, after the group's earlier events, nothing while the group is lost. It deletes the old list of `simplexMcpList` for everyone, then goes through the sessions by number. `renderEntry`: a message of a stopped session 23 hours old deleted; an edit when the text differs from `MainGroup.shown`; a message whose edit is refused with `invalidChatItemUpdate` or `chatItemNotFound` deleted, and posted again for a running session. `postEntry` posts a running session's message, with priority -1, while the group has an owner. The messages of sessions the hub does not pass are deleted. `renderSummary` edits the summary when its text differs from `MainGroup.shownSummary`, posts it when there is none while the group has an owner and a session message, and deletes and posts it again when its edit is refused. `saveBoard` saves the items in the group's custom data when they changed or the old list was deleted; when the save fails, the items posted in that render are deleted for everyone and the error is passed on. `deleteItem` deletes for everyone and logs a refusal. |
| `openLink`, `deleteLink` | group link with role `member` |
| `findMainGroup`, `createMainGroup` | the newest group with `simplexMcpMain`; a new one with the short description and welcome message of trust, history, direct messages for owners and the menu |
@@ -930,18 +934,37 @@ Data flow of a prompt from the session group:
| `openCore` | folder, `ChatApi.init` with prefix `FOLDER/simplex`, active user or a new one with the given peer type, `prepareCore`, event buffer, `startChat`, preset contact deleted for a new user, profile update with the display name and the peer type |
| `deletePresetContacts` | the contact `Ask SimpleX Team`, deleted when it has no connection |
+#### [`claude-code.ts`](../src/claude-code.ts)
+
+| Symbol | Contents |
+|---|---|
+| `AccountReader` | `read(path)` returns the account of Claude Code's global config at `path`: `oauthAccount.emailAddress` when it is a non-empty string, else none. The file is opened with `O_NONBLOCK` and parsed only when its path or modification time differs from the last parse. A missing file, or a path that is not a regular file, gives none; a file that does not parse, as during a write, keeps the last account and is parsed again at the next read. |
+| `TranscriptReader`, `GoalState`, `TranscriptState`, `goalOf`, `recapOf` | `read(path)` returns the goal state, the recap and the title of a transcript. It reads the bytes from the end of the last complete line read to the end of the file; at a new path, for a file shorter than that offset, and for more than 4 MiB appended, it reads the last 4 MiB and drops the first partial line. A new path clears the state. Only complete lines that contain `"goal_status"`, `"away_summary"` or `"ai-title"` are parsed, without entries with `isSidechain: true`. `goalOf` makes the state of a `goal_status` attachment: `met` with `sentinel` none, as after `/goal clear`; `met` `met`; `failed` `failed`; otherwise `set`. `recapOf` takes the `content` of an `away_summary` entry without a final `(disable recaps in /config)`, trimmed, none when empty, cut to 1,000 characters with `…`. The title is the trimmed `aiTitle` of an `ai-title` entry. A failed read keeps the state. |
+| `AppendedLines`, `readRange` | `read(path)` returns the complete lines appended since its last read, by the rule of `TranscriptReader`, and none for a failed read. |
+| `lastUsage`, `usageTailBytes` | the tokens of the last request in the last 256 KiB of an agent's transcript: input, cache creation, cache read and output tokens of the last `assistant` entry with `message.usage` and a model other than ``; none without one or for a failed read. |
+
+#### [`agents.ts`](../src/agents.ts)
+
+| Symbol | Contents |
+|---|---|
+| `Agents`, `Card`, `Agent`, `Workflow`, `Live`, `End`, `JournalEntry`, `stalledFor`, `stallMs`, `stallCallMs`, `maxEnded` | the session's subagents and workflows, in memory, the last 100 ended ones kept. `start` adds a subagent, also for an ID that ended (a resumed agent gets a new message). `step` counts a tool use at its start, keeps it open until its end and then as the last step. `report` keeps the hand-back's first line as the result; `stop` ends the agent `completed`, with its answer's first line when no report came. `task` ends the newest agent or workflow of its tool use, keeping the time of an earlier stop. `endAll` ends the live ones `stopped`. A subagent is stalled when its last event is over 2 minutes old with no open step, or over 10 minutes with one. |
+| `applyJournal`, `journalPath`, `workflowAgentTranscript` | the `started`, `result` and `failed` lines of a workflow's `journal.jsonl`, the last per `key`, with the phase of its first line; phases in the order of their first agent. |
+| `cardText`, `agentText`, `workflowText`, `tokensText`, `clock`, `statusEmoji` | the texts of [api.md](api.md#agent-messages). `tokensText`: `850 tokens`, `38.2k tokens` with one decimal rounded down under 100k, `412k tokens`, `1.2M tokens`. `clock`: `M:SS`, `H:MM:SS` from 1 hour; times of live messages in 5 s steps. |
+| `agentsLine` | the line of the session's board message: `🤖 N agents working`, counting subagents and working agents of workflows, `K stalled M:SS` with the longest stall, and `⚙️ NAME PHASE d/t` for each working workflow's last phase; none while nothing works. |
+
#### [`hook.ts`](../src/hook.ts), [`display.ts`](../src/display.ts), [`service-request.ts`](../src/service-request.ts), [`status-line.ts`](../src/status-line.ts), [`owner.ts`](../src/owner.ts), [`qr.ts`](../src/qr.ts)
| Symbol | Contents |
|---|---|
-| [`sessionStart`](../src/hook.ts) | `{}` for a run that is not interactive. When the run is not interactive only because of `CLAUDE_CODE_SESSION_ATTENDED`, its process is marked first. In an interactive run, the hook checks Node.js, reads the options, calls `ensureService`, sends `POST /title` with the title, the folder, the model and its own start time `performance.timeOrigin`, and returns the link message. After a compaction, with `source: compact`, it sends no model, because Claude Code passes the model of the compacted conversation, a subagent's for a subagent's compaction. |
+| [`sessionStart`](../src/hook.ts) | `{}` for a run that is not interactive. When the run is not interactive only because of `CLAUDE_CODE_SESSION_ATTENDED`, its process is marked first. In an interactive run, the hook checks Node.js, reads the options, calls `ensureService`, sends `POST /title` with the title, the folder, the model, `transcript_path` as `transcript` and its own start time `performance.timeOrigin`, and returns the link message. After a compaction, with `source: compact`, it sends no model, because Claude Code passes the model of the compacted conversation, a subagent's for a subagent's compaction. |
| [`markUnattended`](../src/hook.ts) | When `CLAUDE_PID` is set, the hook calls `ensureService` and sends `POST /title` with `unattended`. A failure is logged. |
| [`turn`, `eventFields`](../src/hook.ts) | The output is `{}`. `eventFields` makes the fields of the hook's event: the model of Stop's answer and the usage of its turn, the kind of UserPromptSubmit's prompt, the `step` of a tool hook and the `note` of PostCompact. In a run that is not interactive, for a tool use of a subagent or of this plugin, or without `tool_use_id` or `tool_name`, and for PostCompact without a note, the hook sends nothing. Otherwise it calls `ensureService`, then sends `POST /turn` with the fields of [8.6](#86-channel-and-mirroring). The request is tried up to 15 times, 1 s apart, while the service returns status 409. |
| [`answerRecord`, `promptKind`, `findInTranscript`, `readTail`, `lastAnswer`, `promptRecord`, `isPrompt`, `recordText`, `recordKind`](../src/hook.ts) | `answerRecord` finds the model of Stop's answer and the usage of its turn. The model is the `message.model` of the last entry of type `assistant` without `isSidechain` in the tail of `transcript_path`, once that entry's text is the answer. No model and no usage are sent for ``, an answer without text, an empty path, an unreadable transcript, or an entry not written within the reads. The usage is sent when the hook has `prompt_id` and the answer's entry has `message.usage` and a `timestamp`. `promptKind` finds whether a person typed the prompt of UserPromptSubmit, its note and whether it is mid-turn. Its record, found by `promptRecord`, is the newest user entry or `queued_command` attachment whose text is the prompt, without subagent entries and tool results: the entry with the hook's `prompt_id` as `promptId`, or a record after the first user entry with that ID, a tool result included. Until such an entry is in the tail, `promptRecord` waits; at the last read, and at once without `prompt_id`, it takes any record with the prompt's text. It also waits while an `enqueue` entry with the prompt's text follows the record. The prompt is typed when the record's `origin.kind` is `human`, and mid-turn when the record is not the entry with `prompt_id`. A `queued_command` attachment without origin and with the `commandMode` `task-notification` is a task notification. At the last read, a record with an `enqueue` entry after it is classified by its origin, and a typed one is mid-turn. Without a record, an `enqueue` entry with the prompt's text makes the prompt typed and mid-turn; otherwise an entry with `prompt_id` and the origin `human` makes it typed. `findInTranscript` reads the tail of the size its caller gives, plus twice the bytes of the answer or the prompt: the last 1 MiB, 100 ms apart, at most 20 times for an answer and 600 times for a prompt, and the last 4 MiB, 1 s apart, at most 120 times for a compaction. It gives its search the tail's bytes, tells it which read is the last, and treats a failed read, as of a missing file, as an empty tail. |
| [`noteOf`, `taskNote`, `teammateNote`, `idleNotification`, `peerName`, `firstLine`, `decoded`, `stringOf`, `shortened`](../src/hook.ts) | `noteOf` makes the note of a record from its origin, its `turnOrigin` and the prompt, as [api.md](api.md#48-plugin-options-files-and-hook-output) lists the lines. `taskNote` reads ``, `` and `` of the first `` block, and takes the first line of a prompt without one. `teammateNote` reads the sender, the `summary` and the message of the first `` tag of a prompt without origin whose message is not an idle notification; `idleNotification` checks whether a message's JSON `type` is `idle_notification`. `firstLine`, `peerName` and `teammateNote` replace control and format characters with spaces in each first line and in the sender's name, as `oneLine` does, so a note is one line. `shortened` cuts a note to 200 characters, counted in code points. |
| [`turnUsage`, `usageOf`, `startsTurn`, `timeOf`, `count`](../src/hook.ts) | `turnUsage` looks for the turn's first entry in the tail of the answer's read, and then in the last 4, 16 and 64 MiB, and returns the usage text of the first tail that has it. `usageOf` finds the first entry, a user entry of the main conversation with the turn's `promptId` that is not a tool result (`startsTurn`), parsing only the lines with that ID, and sums `output_tokens` over the distinct `message.id` of the assistant entries after it, without subagent and `` entries, parsing only the lines of assistant entries. It returns `DURATION · OUTPUT output tokens · CONTEXT tokens in context`, DURATION from the first entry's `timestamp` to the answer's by `duration`, and CONTEXT the input, cache write and cache read tokens of the answer's usage, both counts by `tokenCount`, as `861`, `16K`, `673K` or `1.2M`. `timeOf` parses a `timestamp`; `count` is a number or 0. |
| [`compactionNote`, `recentBoundary`](../src/hook.ts) | `compactionNote` makes the line of PostCompact, `⚙️ Context summarised automatically` or `on request`, with the token counts of the boundary that `recentBoundary` finds: the last entry of type `system` and subtype `compact_boundary` without `isSidechain`, created from 60 s before the hook's start to 5 s after it. A tail is decoded only when its bytes contain `"compact_boundary"`. It makes no line for an input with `agent_id`, or without such a boundary within the reads, as [api.md](api.md#48-plugin-options-files-and-hook-output) states. |
-| [`stepOf`, `stepText`, `displayPath`](../src/hook.ts) | `stepOf` makes the `step` of a tool hook: `{id, text}` at PreToolUse, and the text with the outcome and `duration_ms` formatted by `duration`, or with `(in background)` for a launch in the background, and `end: true` at PostToolUse and PostToolUseFailure, as [api.md](api.md#48-plugin-options-files-and-hook-output) lists them. It gives no step without `tool_use_id` or `tool_name`, with `agent_id` or for this plugin's tools, and the hook then sends nothing. `stepText` makes the text from the tool's name and input, cut by `shortened` in `stepOf`. `displayPath` gives a path relative to `cwd`, unless the relative path is absolute or starts with `..`. |
+| [`agentStart`, `agentStep`, `leadTask`, `taskOf`, `figures`, `AgentRecord`, `handbackTool`, `agentRecordReads`, `taskStatuses`](../src/hook.ts) | `agentStart`, at SubagentStart: the record `TRANSCRIPT/subagents/agent-ID.meta.json`, TRANSCRIPT the hook's `transcript_path` without `.jsonl`, read every 100 ms up to 20 times; `start` with `agent_type`, the record's first line of `description` and `toolUseId`, and the agent's transcript beside the record. A teammate's record, with `taskKind`, and no record send nothing, so workflow agents, whose records are in `subagents/workflows/RUN/`, send nothing. `agentStep`, at a tool hook with `agent_id`: the `step` with the text of `stepText`, without small print, and `end` after the tool use; `SubagentHandback` sends its message's first line as `report` at its start. SubagentStop sends `stop`, its answer's first line. A request with `agent_id` has no `answer` and no `effort`. `leadTask`, at the lead's tool hooks of `Agent` and `Workflow`, which send no step: a completed `Agent` result sends `task` with `totalTokens`, `totalToolUseCount` and `totalDurationMs`; a failed one `failed`, or `killed` when interrupted; a `Workflow` result sends `workflow` with `runId`, `workflowName` and `transcriptDir`. `taskOf`, at UserPromptSubmit: `task` of a `` with ``, a known `` and the counts of ``. |
+| [`stepOf`, `stepText`, `displayPath`](../src/hook.ts) | `stepOf` makes the `step` of a tool hook: `{id, text}` at PreToolUse, and the text with the outcome and `duration_ms` formatted by `duration`, or with `(in background)` for a launch in the background, and `end: true` at PostToolUse and PostToolUseFailure, as [api.md](api.md#48-plugin-options-files-and-hook-output) lists them. It gives no step without `tool_use_id` or `tool_name`, with `agent_id` or for this plugin's tools, and the hook then sends nothing; a tool hook with `agent_id` goes to `agentStep`, and the lead's `Agent` and `Workflow` to `leadTask`. `stepText` makes the text from the tool's name and input, cut by `shortened` in `stepOf`. `displayPath` gives a path relative to `cwd`, unless the relative path is absolute or starts with `..`. |
| [`display`](../src/display.ts) | The MessageDisplay hook. Without a string `session_id` and `message_id` and an integer `index`, it sends nothing. Otherwise it sends `POST /turn` with `id`, `pid`, its start time `at` and `text` `{message, index, final, delta}`, where `final` is true only for `true` and `delta` is empty when it is not a string. It waits for the reply at most 1 s, starts no service, makes no retry and logs nothing. The process prints `{}` after the request. |
| [`postToService`, `claudePid`](../src/service-request.ts) | `postToService` sends one request with the token of `ROOT/service.token` to the socket of ROOT, and resolves when the reply ends, at a failure, without a token file, or when the wait ends without a reply. `claudePid` is `CLAUDE_PID` when it is a positive integer. `display.ts`, `service-request.ts` and `paths.ts` import only Node modules and each other, so the display hook loads no `simplex-chat`. |
| [`statusLine`, `limitParts`, `Machine`, `machineState`, `machineParts`, `lowMemoryShare`, `lowDiskBytes`, `lowMark`, `runStatusLine`](../src/status-line.ts) | The status line command, which `ROOT/status-line.js` runs. `statusLine` writes the line of the parts known: `model.display_name`, `effort LEVEL`, `N% context`, `limitParts` of `rate_limits.five_hour` and `seven_day`, and `machineParts` of `machineState` of the data root, joined by ` · `. `machineState` reads `process.availableMemory()`, the memory total as the smaller of `process.constrainedMemory()`, when it is positive, and `os.totalmem()`, and the free disk `bavail * bsize` of `statfsSync` of the data root, or of its nearest parent that it reads, none when no folder up to the root is read; it is synchronous, so the hub reads it in `Session.turn` before its first await, through `Hub.machine` with the hub's root. `machineParts` makes `RAM SIZE free` and `disk SIZE free`, none without a state, the disk part only when known, each followed by `❗️` when the memory is below 5% of the total or the disk below 5 GB. SIZE is in TB, GB or MB, the largest unit not above the value, with one decimal below 10 and none from 10, rounded down; below 1 MB it is in MB. The command does not send the machine's state; the hub reads its own for the end line. Then, with a string `session_id` and an effort level or a window, it sends `POST /turn` with `id`, `pid`, its start time `at`, `effort`, `limits` `{fiveHour?, week?}`, each `{percent, resetsAt}`, and `statusLine: true`, by `postToService`, waiting at most 1 s. `limitParts` makes `5 h: N%` and `week: N%`, N rounded down; the hub uses it for the end line. `runStatusLine` reads stdin and prints the line. `status-line.ts` imports only Node modules, `paths.ts` and `service-request.ts`. |
@@ -959,7 +982,7 @@ Data flow of a prompt from the session group:
| [`readConfig`](../src/config.ts) | `CLAUDE_PLUGIN_OPTION_*` to `Config`, defaults for blank values, `ConfigError` texts |
| [`withMachine`](../src/config.ts) | ` - MACHINE` from `SIMPLEX_MCP_MACHINE` after the Main group name, checked by `validName`, with the `ConfigError` texts of the variable |
| [`dataRoot`](../src/paths.ts), [`hubFolder`, `sessionFolder`](../src/files.ts) | ROOT, `ROOT/_hub`, `ROOT/_sessions/`. `files.ts` exports `dataRoot` of `paths.ts`. |
-| [`SessionFile`, `readSessionFile`, `writeSessionFile`, `storedSessions`](../src/files.ts) | `session.json` with number, name, project, creation time, group, aliases, model, effort and a rejected mode `host`. An unparsable file is skipped with a log line. Each write goes to `session.json.tmp`, which is renamed into place. |
+| [`SessionFile`, `readSessionFile`, `writeSessionFile`, `storedSessions`](../src/files.ts) | `session.json` with number, name, project, creation time, group, aliases, model, effort, a rejected mode `host`, and the account, the transcript path, the goal state, the recap and the title read from Claude Code's files. An unparsable file is skipped with a log line. Each write goes to `session.json.tmp`, which is renamed into place. |
| [`socketPath`](../src/paths.ts) | `ROOT/service.sock`. A path over 103 bytes is replaced by `TMP/simplex-mcp-HASH.sock`, and Windows uses `\\.\pipe\simplex-mcp-HASH`. `files.ts` exports it. |
| [`serviceTokenFile`](../src/paths.ts) | `service.token`, the name of the token file in ROOT |
| [`logFile`, `trimLog`, `openLog`](../src/files.ts) | `ROOT/service.log`, emptied when over 10 MB, mode 0600 |
@@ -1015,7 +1038,7 @@ Memory of the service:
| Approved tools sent | [`Session.sentTools`](../src/hub.ts), the list last written to the attachments, empty for a new writer | `sendTools`, `onLine` | `sendTools` |
| The requested mode | [`Session.requested`](../src/hub.ts) | `requestMode`, a rejected or expired `mode` card | `askMode` |
| Members of the Main group, its link | [`MainGroup.members`, `linkText`](../src/main-group.ts) | `refreshMembers`, `openLink` | owner checks, the statement of trust at a join, `/status`, `/title`, `/link` |
-| The list of sessions | [`MainGroup.list`](../src/main-group.ts), its item and the time it was posted, also in the group's custom data; `MainGroup.shown`, the text last posted or edited; `MainGroup.tooLarge`, the text last refused as too large | constructor, `postList`, `replace`; `showList` | `showList`, `renderList` |
+| The board of sessions | [`MainGroup.board`](../src/main-group.ts), the items of the summary and the session messages with their post times, also in the group's custom data; `MainGroup.oldList`, the item of the old list; `MainGroup.shown` and `shownSummary`, the texts last posted or edited | constructor, `saveBoard`, `replace`; `postEntry`, `renderEntry`, `deleteEntry`, `renderSummary` | `showBoard` |
| Claude Code's record of a session | [`Session.record`](../src/hub.ts), the path from the last `POST /session`; `Session.claudeStatus`, the last `status` read; `Session.recordRead`, the read in progress | `Service.onSession`; `readRecord` | `readRecord`; `stateLine` |
| Renders of the list | [`Hub.listTimer`](../src/hub.ts), every 2 s; `Hub.listing`, the running render | `Hub.open`; `showSessions` | `Hub.stop` |
@@ -1026,7 +1049,7 @@ Chat database custom data is in the core `_hub` unless noted:
| Item | Entity | Value | Written by | Read by |
|---|---|---|---|---|
| Main group marker | Main group | `{simplexMcpMain: true}` | [`createMainGroup`](../src/main-group.ts) | [`findMainGroup`](../src/main-group.ts) |
-| List of sessions | Main group | `{simplexMcpMain: true, simplexMcpList: {item, at}}`, merged with the other keys | [`MainGroup.postList`](../src/main-group.ts) | [`MainGroup` constructor, `listOf`](../src/main-group.ts) |
+| Board of sessions | Main group | `{simplexMcpMain: true, simplexMcpBoard: {summary?: {item, at}, sessions: [{session, item, at}]}}`, merged with the other keys; `simplexMcpList` of an earlier version removed | [`MainGroup.saveBoard`](../src/main-group.ts) | [`MainGroup` constructor, `boardOf`, `listOf`](../src/main-group.ts) |
| Session group | group of session N | `{simplexMcpSession: {session: N, pending?: [{connId, at}], mode?}}`, where `mode` is the approved mode | [`createSessionGroup`](../src/hub.ts), [`setMode`](../src/hub.ts), [`savePending`](../src/hub.ts), [`claimPending`](../src/hub.ts) | [`storedGroup`](../src/hub.ts), [`Session` constructor](../src/hub.ts), [`claimPending`](../src/hub.ts) |
| Action counter | group of session N | `{simplexMcp: {control: true, nextAction}}`, merged with the other keys | [`saveCounter`, `saveData`](../src/control.ts) | [`Session` constructor](../src/hub.ts) |
| Chat owner | contact or group of a peer | `{...other keys, simplexMcpOwner: {session: ID}}` | [`claim`](../src/tools.ts), [`giveChat`](../src/tools.ts) | [`owns`](../src/tools.ts) |
@@ -1115,7 +1138,7 @@ After a stop, `Hub.onEvent` ignores events ([`Hub.onEvent`](../src/hub.ts)). Oth
On `SIGINT`, `SIGTERM`, `POST /stop` or the stop timer ([`Service.shutdown`](../src/service.ts)):
1. Timers are cleared, the held titles are saved in `ROOT/titles.json`, the listener closes, and open streams are destroyed.
-2. `Hub.stop` stops the actions of every session, and edits their cards to `Cancelled: the server stopped.` It awaits the queued group events, and Claude edits the list of sessions once more, with every session not running. When cards were cancelled, they and that edit get 10 s to be sent. Then it ends the steps, the opening messages and the texts, and awaits their updates. Then the download checks stop, and the cores `_user` and `_hub` close ([`Hub.stop`](../src/hub.ts)).
+2. `Hub.stop` stops the actions of every session, and edits their cards to `Cancelled: the server stopped.` It awaits the queued group events, and Claude renders the board once more, with every session stopped. When cards were cancelled, they and that edit get 10 s to be sent. Then it ends the steps, the opening messages and the texts, and awaits their updates. Then the download checks stop, and the cores `_user` and `_hub` close ([`Hub.stop`](../src/hub.ts)).
3. The service logs `Cancelled K action(s).`, releases the lock and logs `Stopped.` The process exits after the `/stop` reply is sent, or after its client disconnects before the reply is written.
### 8.5 Approval model
diff --git a/packages/simplex-chat-mcp/spec/flows.md b/packages/simplex-chat-mcp/spec/flows.md
index a78500aa59..050d2417d5 100644
--- a/packages/simplex-chat-mcp/spec/flows.md
+++ b/packages/simplex-chat-mcp/spec/flows.md
@@ -62,10 +62,11 @@ Claude Code plugin ([participants](#claude-code-plugin-flows)):
33. [A reaction in the session group](#33-a-reaction-in-the-session-group)
34. [A tool approved for the rest of a session](#34-a-tool-approved-for-the-rest-of-a-session)
35. [A summary of the session's context](#35-a-summary-of-the-sessions-context)
-36. [The list of sessions](#36-the-list-of-sessions)
+36. [The board of sessions](#36-the-board-of-sessions)
37. [The texts of a turn](#37-the-texts-of-a-turn)
38. [The status line command](#38-the-status-line-command)
39. [An edit and a live message in the session group](#39-an-edit-and-a-live-message-in-the-session-group)
+40. [A subagent and a workflow in the session group](#40-a-subagent-and-a-workflow-in-the-session-group)
---
@@ -823,7 +824,7 @@ sequenceDiagram
O->>C: joins #35;G from the invitation in #35;M
C->>N: joinedGroupMember
N->>O: Alice is an owner and can send prompts to Claude and the group's commands, and approve tool use.
- M->>O: within 2 s, the list of sessions, silent, as in flow 36
+ M->>O: within 2 s, the board of sessions, silent, as in flow 36
```
Notes:
@@ -1676,51 +1677,54 @@ Source: [`sessionStart`, `turn`, `eventFields`, `compactionNote`, `recentBoundar
---
-## 36. The list of sessions
+## 36. The board of sessions
```mermaid
sequenceDiagram
participant CC as Claude Code
- participant R as Claude Code's record
+ participant R as record, global config, transcript
participant S as Session process
+ participant K as SessionStart hook
participant D as Service
participant N as Session N
+ participant G as Session group
participant M as MainGroup
participant C as Core _hub
participant O as Owner
- S->>D: POST /session {id, pid, project, config, record: CONFIG/sessions/PID.json}
- D->>N: record
- CC->>R: status busy
+ S->>D: POST /session {id, pid, project, config, record, globalConfig}
+ K->>D: POST /title {..., transcript}
+ D->>N: record, globalConfig, transcript
+ CC->>R: status busy; oauthAccount; goal_status, away_summary, ai-title
D->>N: every 2 s: readRecord, the session attached
- N->>R: read status
- D->>M: showList: 🟢 N · NAME: working, then the not running line
- M->>C: no list yet, an owner in the group: apiSendMessages #35;M, priority -1
- M->>C: apiSetGroupCustomData #35;M {simplexMcpMain: true, simplexMcpList: {item, at}}
- C->>O: the list
+ N->>R: read status; the config when it changed; the transcript's new lines
+ N->>G: account, goal or recap changed: short description and description
+ D->>M: showBoard: each session's message, by number
+ M->>C: no message of N, an owner in the group: apiSendMessages #35;M, priority -1
+ M->>C: no summary: apiSendMessages #35;M "1 session 🟢", priority -1
+ M->>C: apiSetGroupCustomData #35;M {simplexMcpMain: true, simplexMcpBoard}
CC->>R: status waiting, a permission dialog
CC->>S: permission_request
S->>D: POST /permission
- D->>M: showList: 🟠 N · NAME: waiting for you, 1 approval
- M->>C: apiUpdateChatItem #35;M item
- C->>O: the list edited, no alert
- CC->>R: status idle
- D->>M: showList: 🔴 N · NAME: idle
- M->>C: apiUpdateChatItem #35;M item
- Note over D,M: the list 23 hours old, or its edit refused
- M->>C: apiSendMessages #35;M the new list, priority -1, and its item saved
+ D->>M: showBoard: 🟠 N · NAME: waiting for you, 1 approval
+ M->>C: apiUpdateChatItem #35;M the message of N, and the summary
+ C->>O: edited, no alert
+ Note over D,M: an edit refused, as 24 hours after the post
M->>C: apiDeleteChatItems #35;M the old item, broadcast
+ M->>C: apiSendMessages #35;M the message again, priority -1, and the items saved
+ Note over D,M: Claude Code ends; 23 hours after the message's post
+ M->>C: apiDeleteChatItems #35;M the message of the stopped session, broadcast
```
Notes:
-- The session process sends the absolute path of Claude Code's record of its parent process, `CLAUDE_CONFIG_DIR` or `~/.claude`, then `sessions/PID.json`, and the service keeps it in the session ([`startSession`](../src/session.ts), [`Service.onSession`](../src/service.ts)).
+- The session process sends the absolute paths of Claude Code's record of its parent process, `CLAUDE_CONFIG_DIR` or `~/.claude`, then `sessions/PID.json`, and of Claude Code's global config, `CLAUDE_CONFIG_DIR` or `~`, then `.claude.json`. The SessionStart hook sends the transcript's path. The service keeps them in the session ([`startSession`](../src/session.ts), [`sessionStart`](../src/hook.ts), [`Service.onSession`, `applyTitle`](../src/service.ts)).
+- The summary is only edited, so later posts, such as a new session's message, an invitation or a reply, follow it ([`MainGroup.renderSummary`](../src/main-group.ts)).
- Claude Code writes `status` in its record at each change of its state: `busy` while a query runs or delegated work is active, `waiting` while a dialog or another request waits for the person, `idle` otherwise, and `shell` in place of `idle` while a background Bash task runs. It writes the file in place, so a read can find it half written; the hub then keeps the last status. The hub opens the record without blocking and reads only a regular file, and a render waits at most 1 s for a read; a slower read keeps the last status ([`Session.readRecord`, `recordStatus`](../src/hub.ts)).
-- A tool-use card counts while the status is `waiting` or unknown. When someone answers the dialog in the terminal, the status leaves `waiting`, and the card, which stays until the turn ends, no longer counts ([`Session.stateLine`](../src/hub.ts)).
-- When the session process detaches, the session's permissions end and the session moves into the last line. At the service's stop, the hub renders the list once more, with every session there, before it waits for the cancelled cards ([`Hub.stop`](../src/hub.ts)).
-- The text fits one message: the last line keeps the newest names that fit and counts the others ([`Hub.sessionsText`](../src/hub.ts)).
-- The first list waits for an owner, so it follows the greeting. The item and its time are kept in the Main group's custom data, so a new service edits the same list. A reset of the owners creates a new Main group, which gets its own list once an owner joins ([`MainGroup.showList`, `postList`, `replace`](../src/main-group.ts)).
-- SimpleX allows edits of a message for 24 hours and deletions for everyone for 30 hours. The hub replaces a list 23 hours old, by the wall clock, at its next render, and deletes the old one; a refused deletion is logged ([`MainGroup.replaceList`](../src/main-group.ts)).
-- An edit sends no SMP notification, and the apps alert for an edit only when it creates the item. The list's posts carry `priority: -1`; an app without silent messages alerts for them.
+- Every pending card counts, whatever the status: a subagent's tool-use card has no dialog in the terminal, so the status stays `busy` while it waits. A card answered in the terminal stays, and counts, until the turn ends ([`Session.state`](../src/hub.ts)).
+- When the session process detaches, the session's permissions end and its message shows `⚪ N · NAME: stopped`. At the service's stop, the hub renders the board once more, with every session stopped, before it waits for the cancelled cards ([`Hub.stop`](../src/hub.ts)).
+- The first messages wait for an owner, so they follow the greeting. The items and their times are kept in the Main group's custom data, so a new service edits the same messages. A reset of the owners creates a new Main group, which gets its own board once an owner joins ([`MainGroup.showBoard`, `saveBoard`, `replace`](../src/main-group.ts)).
+- SimpleX allows edits of a message for 24 hours and deletions for everyone for 30 hours. A message whose edit is refused is posted again, and a stopped session's message is deleted 23 hours after its post, by the wall clock; a refused deletion is logged ([`MainGroup.renderEntry`](../src/main-group.ts)).
+- An edit sends no SMP notification, and the apps alert for an edit only when it creates the item. The board's posts carry `priority: -1`; an app without silent messages alerts for them.
Source: [`Hub.showSessions`, `Hub.sessionsText`, `Session.readRecord`, `Session.stateLine`](../src/hub.ts), [`MainGroup.showList`](../src/main-group.ts).
@@ -1876,3 +1880,57 @@ Notes:
- A live message deleted before it is sent passes nothing, unless the member sends another message first.
Source: [`Session.onMessage`, `onUpdate`, `pass`, `keepLive`, `passLive`, `replyTo`, `prompt`, `deliver`, `bounded`, `Hub.onEvent`](../src/hub.ts), [`channelNotification`](../src/session.ts).
+
+---
+
+## 40. A subagent and a workflow in the session group
+
+```mermaid
+sequenceDiagram
+ participant L as lead
+ participant A as subagent
+ participant K as hook turn
+ participant F as session folder
+ participant D as Service
+ participant N as Session N
+ participant G as session group
+ participant M as Main group
+ L->>K: PreToolUse Agent: no step line
+ A->>K: SubagentStart agent_id, agent_type
+ K->>F: read subagents/agent-ID.meta.json
+ K->>D: POST /turn agent.start {type, description, toolUse, transcript}
+ D->>N: turn
+ N->>G: live 🤖 TYPE · DESCRIPTION, priority -1
+ loop each tool use of A
+ A->>K: PreToolUse, PostToolUse with agent_id
+ K->>D: POST /turn agent.step
+ end
+ loop every 2 s, attached
+ N->>F: last 256 KiB of agent-ID.jsonl: tokens
+ N->>G: edit when the text changed, at most every 5 s
+ N->>M: the session's board message: 🤖 N agents working
+ end
+ A->>K: SubagentStop last_assistant_message
+ K->>D: POST /turn agent.stop
+ N->>G: edit, liveMessage false: ✅ M:SS · N steps · X tokens, result
+ L->>K: UserPromptSubmit task notification, or PostToolUse Agent
+ K->>D: POST /turn task {toolUse, status, tokens, steps, ms}, with its note
+ N->>G: edit with the figures; the note not posted
+ L->>K: PostToolUse Workflow {runId, workflowName, transcriptDir}
+ K->>D: POST /turn workflow
+ N->>G: live ⚙️ NAME
+ loop every 2 s
+ N->>F: journal.jsonl appended lines; tokens of its working agents
+ N->>G: edit phases, working agents, tokens, time
+ end
+ L->>K: the workflow's task notification
+ N->>G: edit final, liveMessage false
+```
+
+Notes:
+
+- Workflow agents, teammates and Claude Code's internal agents get no message: their SubagentStart finds no record beside the transcript, a record with `taskKind`, or none, so the service drops their steps ([`agentStart`](../src/hook.ts), [`Agents.step`](../src/agents.ts)).
+- The state is in memory: after a service restart, the messages keep their last edit. The last detach and the hub's stop end the live ones with ⏹️ ([`Session.endLive`](../src/hub.ts)).
+- Edits leave the messages where they were posted.
+
+Source: [`agentStart`, `agentStep`, `leadTask`, `taskOf`](../src/hook.ts), [`Agents`, `cardText`, `agentsLine`, `applyJournal`](../src/agents.ts), [`lastUsage`, `AppendedLines`](../src/claude-code.ts), [`Session.onAgents`, `readAgents`, `showCard`](../src/hub.ts).
diff --git a/packages/simplex-chat-mcp/src/agents.ts b/packages/simplex-chat-mcp/src/agents.ts
new file mode 100644
index 0000000000..1da2017705
--- /dev/null
+++ b/packages/simplex-chat-mcp/src/agents.ts
@@ -0,0 +1,263 @@
+import {join} from "path"
+import {AppendedLines} from "./claude-code"
+import type {AgentStart, Step, TaskEnd, TaskStatus, WorkflowRun} from "./protocol"
+
+// spec: spec/architecture.md#agents-agents
+const stallMs = 120_000
+// spec: spec/architecture.md#agents-agents
+const stallCallMs = 600_000
+// spec: spec/architecture.md#agents-agents
+const maxEnded = 100
+// spec: spec/architecture.md#agents-agenttext
+const statusEmoji: {[status in TaskStatus]: string} = {completed: "✅", failed: "❌", killed: "⏹️", stopped: "⏹️"}
+
+// spec: spec/architecture.md#agents-agents
+export interface Live {
+ item?: Promise
+ sent: string
+ sentAt: number
+ postedAt: number
+ end?: End
+}
+
+// spec: spec/architecture.md#agents-agents
+export interface End {
+ status: TaskStatus
+ at: number
+ tokens?: number
+ steps?: number
+ ms?: number
+}
+
+// spec: spec/architecture.md#agents-agents
+export interface Agent extends Live {
+ kind: "agent"
+ id: string
+ type: string
+ description: string
+ toolUse?: string
+ transcript: string
+ startedAt: number
+ lastEventAt: number
+ steps: number
+ open: Map
+ last?: string
+ tokens?: number
+ result?: string
+}
+
+// spec: spec/architecture.md#agents-agents
+export interface JournalEntry {
+ state: "started" | "result" | "failed"
+ agentId: string
+ phase: string
+}
+
+// spec: spec/architecture.md#agents-agents
+export interface Workflow extends Live {
+ kind: "workflow"
+ toolUse: string
+ name: string
+ folder: string
+ startedAt: number
+ journal: Map
+ phases: string[]
+ tokens: Map
+ counted: Set
+ lines: AppendedLines
+}
+
+// spec: spec/architecture.md#agents-agents
+export type Card = Agent | Workflow
+
+// spec: spec/architecture.md#agents-agents
+export class Agents {
+ private cards: Card[] = []
+
+ all(): Card[] {
+ return this.cards
+ }
+
+ live(): Card[] {
+ return this.cards.filter(({end}) => end === undefined)
+ }
+
+ start(id: string, {type, description, toolUse, transcript}: AgentStart, now: number): Agent {
+ const agent: Agent = {kind: "agent", id, type, description, toolUse, transcript, startedAt: now, lastEventAt: now, steps: 0, open: new Map(), sent: "", sentAt: -Infinity, postedAt: now}
+ this.add(agent)
+ return agent
+ }
+
+ workflow({toolUse, name, folder}: WorkflowRun, now: number): Workflow {
+ const workflow: Workflow = {kind: "workflow", toolUse, name, folder, startedAt: now, journal: new Map(), phases: [], tokens: new Map(), counted: new Set(), lines: new AppendedLines(), sent: "", sentAt: -Infinity, postedAt: now}
+ this.add(workflow)
+ return workflow
+ }
+
+ step(id: string, {id: toolUse, text, end}: Step, now: number): void {
+ const agent = this.agent(id)
+ if (agent === undefined) return
+ agent.lastEventAt = now
+ if (end !== true) {
+ agent.steps++
+ agent.open.set(toolUse, text)
+ } else if (agent.open.delete(toolUse)) agent.last = text
+ }
+
+ report(id: string, text: string): void {
+ const agent = this.agent(id)
+ if (agent !== undefined && text !== "") agent.result = text
+ }
+
+ stop(id: string, text: string, now: number): Agent | undefined {
+ const agent = this.agent(id)
+ if (agent === undefined) return undefined
+ if (text !== "") agent.result ??= text
+ agent.end = {status: "completed", at: now}
+ return agent
+ }
+
+ task({toolUse, status, tokens, steps, ms}: TaskEnd, now: number): Card | undefined {
+ const card = [...this.cards].reverse().find(known => known.toolUse === toolUse)
+ if (card !== undefined) card.end = {status, at: card.end?.at ?? now, tokens, steps, ms}
+ return card
+ }
+
+ endAll(now: number): Card[] {
+ const ended = this.live()
+ for (const card of ended) card.end = {status: "stopped", at: now}
+ return ended
+ }
+
+ private agent(id: string): Agent | undefined {
+ return [...this.cards].reverse().find((card): card is Agent => card.kind === "agent" && card.id === id && card.end === undefined)
+ }
+
+ private add(card: Card): void {
+ this.cards.push(card)
+ const ended = this.cards.filter(({end}) => end !== undefined)
+ if (ended.length > maxEnded) this.cards = this.cards.filter(known => known !== ended[0])
+ }
+}
+
+// spec: spec/architecture.md#agents-applyjournal
+export function applyJournal(workflow: Workflow, lines: string[]): void {
+ for (const line of lines) {
+ if (!line.startsWith('{"type":"started"') && !line.startsWith('{"type":"result"') && !line.startsWith('{"type":"failed"')) continue
+ const {type, key, agentId, phase} = (parsed(line) ?? {}) as {type?: unknown; key?: unknown; agentId?: unknown; phase?: unknown}
+ if (typeof key !== "string" || typeof agentId !== "string" || (type !== "started" && type !== "result" && type !== "failed")) continue
+ const known = workflow.journal.get(key)
+ const named = known?.phase ?? (typeof phase === "string" ? phase : "")
+ if (!workflow.phases.includes(named)) workflow.phases.push(named)
+ workflow.journal.set(key, {state: type, agentId, phase: named})
+ }
+}
+
+// spec: spec/architecture.md#agents-applyjournal
+export function journalPath(workflow: Workflow): string {
+ return join(workflow.folder, "journal.jsonl")
+}
+
+// spec: spec/architecture.md#agents-applyjournal
+export function workflowAgentTranscript(workflow: Workflow, agentId: string): string {
+ return join(workflow.folder, `agent-${agentId}.jsonl`)
+}
+
+// spec: spec/architecture.md#agents-agenttext
+export function cardText(card: Card, now: number): string {
+ return card.kind === "agent" ? agentText(card, now) : workflowText(card, now)
+}
+
+// spec: spec/architecture.md#agents-agenttext
+function agentText(agent: Agent, now: number): string {
+ const title = `🤖 ${[agent.type, agent.description].filter(part => part !== "").join(" · ")}`
+ const {end} = agent
+ if (end !== undefined) {
+ const figures = [`${statusEmoji[end.status]} ${clock(end.ms ?? end.at - agent.startedAt)}`, stepsText(end.steps ?? agent.steps), tokensText(end.tokens ?? agent.tokens)]
+ return [[title, ...figures].filter(part => part !== undefined).join(" · "), agent.result].filter(line => line !== undefined).join("\n")
+ }
+ const stalled = stalledFor(agent, now)
+ const open = [...agent.open.values()].at(-1)
+ const activity = stalled !== undefined ? [`⚠️ no step for ${clock(fiveSeconds(stalled))}`, last(agent)] : open !== undefined ? [`now: ${open}`] : [last(agent)]
+ const line = [stepsText(agent.steps), tokensText(agent.tokens), clock(fiveSeconds(now - agent.startedAt)), ...activity].filter(part => part !== undefined).join(" · ")
+ return `${title}\n${line}`
+}
+
+// spec: spec/architecture.md#agents-agenttext
+function workflowText(workflow: Workflow, now: number): string {
+ const entries = [...workflow.journal.values()]
+ const ended = workflow.end !== undefined
+ const phases = workflow.phases.map((phase, i) => {
+ const started = entries.filter(entry => entry.phase === phase)
+ const done = started.filter(({state}) => state !== "started").length
+ const complete = !ended && done === started.length && i < workflow.phases.length - 1
+ return `${phase === "" ? "" : `${phase} `}${done}/${started.length}${complete ? " ✅" : ""}`
+ })
+ const tokens = tokensText(workflow.tokens.size === 0 ? undefined : [...workflow.tokens.values()].reduce((sum, count) => sum + count, 0))
+ const {end} = workflow
+ if (end !== undefined) return [`⚙️ ${workflow.name}`, `${statusEmoji[end.status]} ${clock(end.at - workflow.startedAt)}`, ...phases, tokens].filter(part => part !== undefined).join(" · ")
+ const working = entries.filter(({state}) => state === "started").length
+ return [`⚙️ ${workflow.name}`, ...phases, working === 0 ? undefined : `${working} working`, tokens, clock(fiveSeconds(now - workflow.startedAt))].filter(part => part !== undefined).join(" · ")
+}
+
+// spec: spec/architecture.md#agents-agentsline
+export function agentsLine(cards: Card[], now: number): string | undefined {
+ const live = cards.filter(({end}) => end === undefined)
+ if (live.length === 0) return undefined
+ const agents = live.filter((card): card is Agent => card.kind === "agent")
+ const workflows = live.filter((card): card is Workflow => card.kind === "workflow")
+ const working = agents.length + workflows.reduce((sum, {journal}) => sum + [...journal.values()].filter(({state}) => state === "started").length, 0)
+ const stalls = agents.flatMap(agent => stalledFor(agent, now) ?? [])
+ const workingText = working === 0 ? undefined : `${working} agent${working === 1 ? "" : "s"} working`
+ const stalledText = stalls.length === 0 ? undefined : `${stalls.length} stalled`
+ const phases = workflows.map(workflow => {
+ const phase = workflow.phases.at(-1)
+ const started = [...workflow.journal.values()].filter(entry => entry.phase === phase)
+ const done = started.filter(({state}) => state !== "started").length
+ return `⚙️ ${workflow.name}${phase === undefined ? "" : ` ${phase === "" ? "" : `${phase} `}${done}/${started.length}`}`
+ })
+ const line = [workingText === undefined ? undefined : `🤖 ${workingText}`, stalledText === undefined ? undefined : `${stalledText} ${clock(fiveSeconds(Math.max(...stalls)))}`, ...phases].filter(part => part !== undefined).join(" · ")
+ return line === "" ? undefined : line
+}
+
+// spec: spec/architecture.md#agents-agents
+function stalledFor(agent: Agent, now: number): number | undefined {
+ const quiet = now - agent.lastEventAt
+ return quiet > (agent.open.size === 0 ? stallMs : stallCallMs) ? quiet : undefined
+}
+
+function last(agent: Agent): string | undefined {
+ return agent.last === undefined ? undefined : `last: ${agent.last}`
+}
+
+function stepsText(steps: number): string {
+ return `${steps} step${steps === 1 ? "" : "s"}`
+}
+
+// spec: spec/architecture.md#agents-agenttext
+export function tokensText(tokens: number | undefined): string | undefined {
+ if (tokens === undefined) return undefined
+ const [scale, unit] = tokens >= 1e6 ? [1e6, "M"] : tokens >= 1e3 ? [1e3, "k"] : [1, ""]
+ const value = tokens / scale
+ return `${scale === 1 ? tokens : value >= 100 ? Math.floor(value) : (Math.floor(value * 10) / 10).toFixed(1)}${unit} tokens`
+}
+
+// spec: spec/architecture.md#agents-agenttext
+export function clock(ms: number): string {
+ const seconds = Math.max(0, Math.floor(ms / 1_000))
+ const [hours, minutes, rest] = [Math.floor(seconds / 3_600), Math.floor((seconds % 3_600) / 60), seconds % 60]
+ const pad = (value: number): string => String(value).padStart(2, "0")
+ return hours > 0 ? `${hours}:${pad(minutes)}:${pad(rest)}` : `${minutes}:${pad(rest)}`
+}
+
+function fiveSeconds(ms: number): number {
+ return Math.floor(ms / 5_000) * 5_000
+}
+
+function parsed(line: string): unknown {
+ try {
+ return JSON.parse(line)
+ } catch {
+ return undefined
+ }
+}
diff --git a/packages/simplex-chat-mcp/src/claude-code.ts b/packages/simplex-chat-mcp/src/claude-code.ts
new file mode 100644
index 0000000000..4c289e9fc2
--- /dev/null
+++ b/packages/simplex-chat-mcp/src/claude-code.ts
@@ -0,0 +1,175 @@
+import {constants} from "fs"
+import {FileHandle, open} from "fs/promises"
+
+// spec: spec/architecture.md#claude-code-transcriptreader
+const tailBytes = 4 * 1_048_576
+// spec: spec/architecture.md#claude-code-transcriptreader
+const markers = ['"goal_status"', '"away_summary"', '"ai-title"']
+// spec: spec/architecture.md#claude-code-transcriptreader
+const recapSuffix = /\s*\(disable recaps in \/config\)\s*$/
+// spec: spec/architecture.md#claude-code-transcriptreader
+const maxRecap = 1_000
+// spec: spec/architecture.md#claude-code-lastusage
+const usageTailBytes = 256 * 1_024
+const syntheticModel = ""
+
+// spec: spec/architecture.md#claude-code-transcriptreader
+export type GoalState = "set" | "met" | "failed"
+
+// spec: spec/architecture.md#claude-code-transcriptreader
+export interface TranscriptState {
+ goal?: GoalState
+ recap?: string
+ title?: string
+}
+
+interface Entry {
+ type?: unknown
+ subtype?: unknown
+ isSidechain?: unknown
+ content?: unknown
+ aiTitle?: unknown
+ attachment?: {type?: unknown; met?: unknown; failed?: unknown; sentinel?: unknown}
+}
+
+// spec: spec/architecture.md#claude-code-accountreader
+export class AccountReader {
+ private readAt?: {path: string; mtime: number}
+
+ constructor(public account?: string) {}
+
+ async read(path: string): Promise {
+ try {
+ const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)
+ try {
+ const stat = await file.stat()
+ if (!stat.isFile()) return (this.account = undefined)
+ if (this.readAt?.path === path && this.readAt.mtime === stat.mtimeMs) return this.account
+ const {oauthAccount} = JSON.parse(await file.readFile("utf8")) as {oauthAccount?: {emailAddress?: unknown}}
+ this.account = typeof oauthAccount?.emailAddress === "string" && oauthAccount.emailAddress !== "" ? oauthAccount.emailAddress : undefined
+ this.readAt = {path, mtime: stat.mtimeMs}
+ } finally {
+ await file.close()
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") this.account = undefined
+ }
+ return this.account
+ }
+}
+
+// spec: spec/architecture.md#claude-code-transcriptreader
+export class TranscriptReader {
+ private readonly lines: AppendedLines
+
+ constructor(
+ path?: string,
+ public state: TranscriptState = {},
+ ) {
+ this.lines = new AppendedLines(path)
+ }
+
+ async read(path: string): Promise {
+ if (path !== this.lines.path) this.state = {}
+ for (const line of await this.lines.read(path)) this.apply(line)
+ return this.state
+ }
+
+ private apply(line: string): void {
+ if (!markers.some(marker => line.includes(marker))) return
+ const entry = entryOf(line)
+ if (entry === undefined || entry.isSidechain === true) return
+ if (entry.type === "attachment" && entry.attachment?.type === "goal_status") this.state = {...this.state, goal: goalOf(entry.attachment)}
+ else if (entry.type === "system" && entry.subtype === "away_summary" && typeof entry.content === "string") this.state = {...this.state, recap: recapOf(entry.content)}
+ else if (entry.type === "ai-title" && typeof entry.aiTitle === "string") this.state = {...this.state, title: entry.aiTitle.trim() || undefined}
+ }
+}
+
+// spec: spec/architecture.md#claude-code-appendedlines
+export class AppendedLines {
+ private offset?: number
+
+ constructor(public path?: string) {}
+
+ async read(path: string): Promise {
+ if (path !== this.path) {
+ this.path = path
+ this.offset = undefined
+ }
+ return this.readAppended(path).catch(() => [])
+ }
+
+ private async readAppended(path: string): Promise {
+ const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)
+ try {
+ const stat = await file.stat()
+ return stat.isFile() ? await this.readFrom(file, stat.size) : []
+ } finally {
+ await file.close()
+ }
+ }
+
+ private async readFrom(file: FileHandle, size: number): Promise {
+ const {offset} = this
+ const start = offset === undefined || size < offset || size - offset > tailBytes ? Math.max(0, size - tailBytes) : offset
+ const aligned = start === 0 || start === offset
+ const bytes = await readRange(file, start, size)
+ const first = aligned ? 0 : bytes.indexOf(0x0a) + 1
+ if (first === 0 && !aligned) return []
+ const end = bytes.lastIndexOf(0x0a) + 1
+ this.offset = start + end
+ return end === 0 ? [] : bytes.subarray(first, end - 1).toString("utf8").split("\n")
+ }
+}
+
+// spec: spec/architecture.md#claude-code-lastusage
+export async function lastUsage(path: string): Promise {
+ try {
+ const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)
+ try {
+ const stat = await file.stat()
+ if (!stat.isFile()) return undefined
+ const lines = (await readRange(file, Math.max(0, stat.size - usageTailBytes), stat.size)).toString("utf8").split("\n")
+ for (let i = lines.length - 1; i >= 0; i--) {
+ if (!lines[i].includes('"assistant"') || !lines[i].includes('"usage"')) continue
+ const {type, message} = (entryOf(lines[i]) ?? {}) as {type?: unknown; message?: {model?: unknown; usage?: {[field: string]: unknown}}}
+ const usage = message?.usage
+ if (type !== "assistant" || usage === undefined || message?.model === syntheticModel) continue
+ return ["input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens"].reduce((sum, field) => sum + (typeof usage[field] === "number" ? (usage[field] as number) : 0), 0)
+ }
+ return undefined
+ } finally {
+ await file.close()
+ }
+ } catch {
+ return undefined
+ }
+}
+
+async function readRange(file: FileHandle, start: number, end: number): Promise {
+ const buffer = Buffer.alloc(end - start)
+ const {bytesRead} = await file.read(buffer, 0, buffer.length, start)
+ return buffer.subarray(0, bytesRead)
+}
+
+// spec: spec/architecture.md#claude-code-transcriptreader
+function goalOf({met, failed, sentinel}: NonNullable): GoalState | undefined {
+ if (met === true) return sentinel === true ? undefined : "met"
+ return failed === true ? "failed" : "set"
+}
+
+// spec: spec/architecture.md#claude-code-transcriptreader
+function recapOf(content: string): string | undefined {
+ const chars = [...content.replace(recapSuffix, "").trim()]
+ if (chars.length === 0) return undefined
+ return chars.length <= maxRecap ? chars.join("") : `${chars.slice(0, maxRecap - 1).join("")}…`
+}
+
+function entryOf(line: string): Entry | undefined {
+ try {
+ const entry = JSON.parse(line) as Entry | null
+ return typeof entry === "object" && entry !== null ? entry : undefined
+ } catch {
+ return undefined
+ }
+}
diff --git a/packages/simplex-chat-mcp/src/control.ts b/packages/simplex-chat-mcp/src/control.ts
index 2c1fbdf184..692f19ba88 100644
--- a/packages/simplex-chat-mcp/src/control.ts
+++ b/packages/simplex-chat-mcp/src/control.ts
@@ -153,8 +153,13 @@ export class Control implements Pick {
- await this.updateProfile(profile => (profile.shortDescr === shortDescr ? undefined : {...profile, shortDescr}))
+ async describe(shortDescr: string | undefined, description?: string): Promise {
+ let changed = false
+ await this.updateProfile(profile => {
+ changed = profile.shortDescr !== shortDescr || profile.description !== description
+ return changed ? {...profile, shortDescr, description} : undefined
+ })
+ return changed
}
// spec: spec/api.md#group-profile
diff --git a/packages/simplex-chat-mcp/src/files.ts b/packages/simplex-chat-mcp/src/files.ts
index 4beabb105b..e7f1e4710a 100644
--- a/packages/simplex-chat-mcp/src/files.ts
+++ b/packages/simplex-chat-mcp/src/files.ts
@@ -2,6 +2,7 @@ import {randomBytes} from "crypto"
import {chmodSync, existsSync, fchmodSync, mkdirSync, linkSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, truncateSync, unlinkSync, writeFileSync} from "fs"
import {join} from "path"
import {pathToFileURL} from "url"
+import type {GoalState} from "./claude-code"
import {ExitError, logError} from "./log"
import {serviceTokenFile} from "./paths"
@@ -21,6 +22,11 @@ export interface SessionFile {
model?: string
effort?: string
hostDeclined?: boolean
+ account?: string
+ transcript?: string
+ goal?: GoalState
+ recap?: string
+ title?: string
}
export interface ServerFile {
diff --git a/packages/simplex-chat-mcp/src/hook.ts b/packages/simplex-chat-mcp/src/hook.ts
index 9b44ce812f..c4c03c38eb 100644
--- a/packages/simplex-chat-mcp/src/hook.ts
+++ b/packages/simplex-chat-mcp/src/hook.ts
@@ -1,11 +1,11 @@
-import {open} from "fs/promises"
-import {isAbsolute, relative} from "path"
+import {open, readFile} from "fs/promises"
+import {isAbsolute, join, relative} from "path"
import {ServiceClient} from "./client"
import {interactive, interactiveEntrypoint, readConfig} from "./config"
import {dataRoot} from "./files"
import {errorText, logError, oneLine} from "./log"
import {duration} from "./messages"
-import {Step, TitleReply, TurnRequest} from "./protocol"
+import {Step, TaskEnd, TaskStatus, TitleReply, TurnRequest} from "./protocol"
import {qrCodeText} from "./qr"
import {claudePid} from "./service-request"
import {SocketError, isNotRunning} from "./socket"
@@ -47,11 +47,26 @@ const teammatePrompt = /^Another Claude session sent a message[^:\n]*:\n]*)>\n([\s\S]*?)\n<\/teammate-message>/g
const pluginTools = "mcp__plugin_simplex_simplex__"
const stepFields = ["description", "query", "url", "file_path", "path", "pattern", "command"]
+// spec: spec/architecture.md#hook-agentstart
+const handbackTool = "SubagentHandback"
+// spec: spec/architecture.md#hook-agentstart
+const agentRecordReads = 20
+// spec: spec/architecture.md#hook-agentstart
+const taskStatuses: TaskStatus[] = ["completed", "failed", "killed", "stopped"]
+
+// spec: spec/architecture.md#hook-agentstart
+interface AgentRecord {
+ agentType?: unknown
+ description?: unknown
+ toolUseId?: unknown
+ taskKind?: unknown
+}
// spec: spec/api.md#plugin-options
interface SessionStartInput {
session_id: string
session_title?: string
+ transcript_path?: string
cwd: string
model?: string
source?: string
@@ -69,6 +84,8 @@ interface TurnInput {
effort?: {level?: string}
cwd?: string
agent_id?: string
+ agent_type?: string
+ tool_response?: {[field: string]: unknown}
tool_name?: string
tool_input?: {[field: string]: unknown}
tool_use_id?: string
@@ -149,7 +166,7 @@ export async function sessionStart(stdin: string, env: NodeJS.ProcessEnv = proce
const config = readConfig(env)
const client = deps?.client ?? ServiceClient.forRoot(dataRoot(env))
await client.ensureService(version)
- const {mainGroup, owner} = await client.request("POST", "/title", {id: input.session_id, pid: claudePid(env), at, name: input.session_title, project: input.cwd, model: input.source === "compact" ? undefined : input.model, config})
+ const {mainGroup, owner} = await client.request("POST", "/title", {id: input.session_id, pid: claudePid(env), at, name: input.session_title, project: input.cwd, model: input.source === "compact" ? undefined : input.model, transcript: input.transcript_path, config})
const {link, owners} = owner
if (owners.length > 0 || link === undefined) return {}
return {systemMessage: `SimpleX MCP: scan this QR code with the SimpleX app and tap Join to supervise your agents in "${mainGroup}":\n${qrCodeText(link, "plain")}\n${link}`}
@@ -178,7 +195,8 @@ export async function turn(stdin: string, env: NodeJS.ProcessEnv = process.env,
const input = JSON.parse(stdin) as TurnInput
const event = await eventFields(input, at, readMs)
if (event === undefined) return {}
- const request = {id: input.session_id, pid: claudePid(env), at, prompt: cut(input.prompt), answer: cut(input.last_assistant_message), model: input.to_model, switched: input.to_model === undefined ? undefined : true, effort: input.effort?.level, ...event}
+ const lead = input.agent_id === undefined
+ const request = {id: input.session_id, pid: claudePid(env), at, prompt: cut(input.prompt), answer: lead ? cut(input.last_assistant_message) : undefined, model: input.to_model, switched: input.to_model === undefined ? undefined : true, effort: lead ? input.effort?.level : undefined, ...event}
await client.ensureService(version)
for (let attempt = 1; ; attempt++) {
try {
@@ -202,14 +220,23 @@ async function eventFields(input: TurnInput, at: number, readMs: number): Promis
const {model, usage} = await answerRecord(input, readMs)
return {model: input.to_model ?? model, usage}
}
- case "UserPromptSubmit":
- return promptKind(input, readMs)
+ case "UserPromptSubmit": {
+ const kind = await promptKind(input, readMs)
+ const task = taskOf(input.prompt)
+ return task === undefined ? kind : {...kind, task}
+ }
case "PreToolUse":
case "PostToolUse":
case "PostToolUseFailure": {
+ if (input.agent_id !== undefined) return agentStep(input)
+ if (input.tool_name === "Agent" || input.tool_name === "Workflow") return leadTask(input)
const step = stepOf(input)
return step === undefined ? undefined : {step}
}
+ case "SubagentStart":
+ return agentStart(input, readMs)
+ case "SubagentStop":
+ return input.agent_id === undefined ? undefined : {agent: {id: input.agent_id, stop: shortened(firstLine(input.last_assistant_message ?? ""))}}
case "PostCompact": {
const note = await compactionNote(input, at, readMs)
return note === undefined ? undefined : {note}
@@ -444,6 +471,58 @@ function stepOf({tool_use_id: id, tool_name: tool, agent_id: agent, hook_event_n
return {id, text: small(`${text}${outcome}${ms === undefined ? "" : ` ${duration(ms)}`}`), end: true}
}
+// spec: spec/architecture.md#hook-agentstart
+async function agentStart({agent_id: id, agent_type: type, transcript_path: path}: TurnInput, readMs: number): Promise | undefined> {
+ if (id === undefined || !path) return undefined
+ const folder = join(path.replace(/\.jsonl$/, ""), "subagents")
+ for (let read = 1; read <= agentRecordReads; read++) {
+ const record = await readFile(join(folder, `agent-${id}.meta.json`), "utf8").then(text => (JSON.parse(text) as AgentRecord | null) ?? undefined).catch(() => undefined)
+ if (record !== undefined) {
+ if (record.taskKind !== undefined) return undefined
+ const description = typeof record.description === "string" ? shortened(firstLine(record.description)) : ""
+ return {agent: {id, start: {type: type ?? (typeof record.agentType === "string" ? record.agentType : "agent"), description, ...(typeof record.toolUseId === "string" ? {toolUse: record.toolUseId} : {}), transcript: join(folder, `agent-${id}.jsonl`)}}}
+ }
+ if (read < agentRecordReads) await new Promise(resolve => setTimeout(resolve, readMs))
+ }
+ return undefined
+}
+
+// spec: spec/architecture.md#hook-agentstart
+function agentStep({agent_id: id, tool_use_id: toolUse, tool_name: tool, hook_event_name: event, tool_input: fields = {}, cwd}: TurnInput): Partial | undefined {
+ if (id === undefined || toolUse === undefined || tool === undefined) return undefined
+ if (tool === handbackTool) return event === "PreToolUse" ? {agent: {id, report: shortened(firstLine(stringOf(fields.message) ?? ""))}} : undefined
+ return {agent: {id, step: {id: toolUse, text: shortened(stepText(tool, fields, cwd)), ...(event === "PreToolUse" ? {} : {end: true})}}}
+}
+
+// spec: spec/architecture.md#hook-agentstart
+function leadTask({hook_event_name: event, tool_name: tool, tool_use_id: toolUse, tool_response: response = {}, is_interrupt: interrupted}: TurnInput): Partial | undefined {
+ if (toolUse === undefined || event === "PreToolUse") return undefined
+ if (tool === "Workflow") {
+ const {runId: run, workflowName: name, transcriptDir: folder} = response
+ return event === "PostToolUse" && typeof run === "string" && typeof name === "string" && typeof folder === "string" ? {workflow: {toolUse, run, name, folder}} : undefined
+ }
+ if (event === "PostToolUseFailure") return {task: {toolUse, status: interrupted === true ? "killed" : "failed"}}
+ const {status, totalTokens: tokens, totalToolUseCount: steps, totalDurationMs: ms} = response
+ return status === "completed" ? {task: {toolUse, status, ...figures(tokens, steps, ms)}} : undefined
+}
+
+// spec: spec/architecture.md#hook-agentstart
+function taskOf(prompt: string | undefined): TaskEnd | undefined {
+ const block = prompt === undefined ? undefined : /([\s\S]*?)<\/task-notification>/.exec(prompt)?.[1]
+ if (block === undefined) return undefined
+ const field = (name: string): string | undefined => new RegExp(`<${name}>([^<]*)${name}>`).exec(block)?.[1]?.trim()
+ const toolUse = field("tool-use-id")
+ const status = taskStatuses.find(known => known === field("status"))
+ if (toolUse === undefined || status === undefined) return undefined
+ return {toolUse, status, ...figures(Number(field("subagent_tokens")), Number(field("tool_uses")), Number(field("duration_ms")))}
+}
+
+// spec: spec/architecture.md#hook-agentstart
+function figures(tokens: unknown, steps: unknown, ms: unknown): Pick {
+ const of = (value: unknown): number | undefined => (typeof value === "number" && Number.isFinite(value) ? value : undefined)
+ return {tokens: of(tokens), steps: of(steps), ms: of(ms)}
+}
+
// spec: spec/architecture.md#hook-stepof
function small(text: string): string {
return `!- ${text.replaceAll("!", "ǃ")}!`
diff --git a/packages/simplex-chat-mcp/src/hub.ts b/packages/simplex-chat-mcp/src/hub.ts
index bb2f806f5a..779bca4399 100644
--- a/packages/simplex-chat-mcp/src/hub.ts
+++ b/packages/simplex-chat-mcp/src/hub.ts
@@ -4,14 +4,16 @@ import {dirname, join} from "path"
import {CC, CEvt, ChatEvent, T} from "@simplex-chat/types"
import {api} from "simplex-chat"
import {Action, Actions, HostTexts, Mode, isDecided, maxPending} from "./actions"
+import {Agent, Agents, Card, Workflow, agentsLine, applyJournal, cardText, journalPath, workflowAgentTranscript} from "./agents"
+import {AccountReader, TranscriptReader, TranscriptState, lastUsage} from "./claude-code"
import {Config} from "./config"
import {Control, canSend, controlCommands, controlDataOf, createGroup, isControlEvent, isGroupMessage, parseCommand, rightsText, safeName, sessionApproverRoles} from "./control"
import {openCore} from "./core"
import {SessionFile, hubFolder, readSessionFile, sessionFolder, writeSessionFile} from "./files"
import {chatErrorOf, errorText, log, logError, oneLine} from "./log"
-import {MainGroup, SessionGroups, createMainGroup, findMainGroup} from "./main-group"
+import {BoardSession, MainGroup, SessionGroups, createMainGroup, findMainGroup} from "./main-group"
import {Changes, ChatItemsWatch, ReplyTo, ToolCall, duration, getChat, isLive, nextChange, quoteLine, storedName, toReplyTo, validName} from "./messages"
-import {AttachLine, LimitWindow, Limits, OwnerState, PermissionRequest, ResetReply, Step, TextBatch, TurnRequest} from "./protocol"
+import {AgentEvent, AttachLine, LimitWindow, Limits, OwnerState, PermissionRequest, ResetReply, Step, TaskEnd, TextBatch, TurnRequest, WorkflowRun} from "./protocol"
import {waitForCancelledCards} from "./serve"
import {Machine, limitParts, machineParts, machineState} from "./status-line"
import {AgentTools, ToolName, featureOff, fitsMessage, maxMessageLength, ownerOf, refusedFeature} from "./tools"
@@ -72,6 +74,12 @@ const claudeStates = new Map([
])
// spec: spec/api.md#list-of-sessions
const unknownState: [string, string] = ["▶️", "running"]
+// spec: spec/api.md#session-board
+const stoppedState: [string, string] = ["⚪", "stopped"]
+// spec: spec/api.md#session-group-profile
+const profileEveryMs = 60_000
+// spec: spec/api.md#agent-messages
+const cardEditMs = 5_000
// spec: spec/architecture.md#hub-hubtexts
export const hubTexts: HostTexts = {lost: "The group of this session is lost. Start a new Claude Code session.", stopping: "The SimpleX service is stopping.", pending: `${maxPending} actions are pending; wait for the approvers' decisions.`}
@@ -88,6 +96,11 @@ interface SessionGroupData {
mode?: Mode
}
+// spec: spec/architecture.md#hub-session-readclaudecode
+interface ClaudeState extends TranscriptState {
+ account?: string
+}
+
interface Part {
text: string
priority?: number
@@ -139,6 +152,8 @@ const answerLines: LineKind = {refused: "Claude's answer was not posted", log: "
export class Session {
open = false
record?: string
+ globalConfig?: string
+ transcript?: string
readonly actions: Actions
readonly tools: AgentTools
readonly control: Control
@@ -172,6 +187,13 @@ export class Session {
private liveOrder: Promise = Promise.resolve()
private claudeStatus?: string
private recordRead?: Promise
+ private claude: ClaudeState
+ private readonly accountReader: AccountReader
+ private readonly transcriptReader: TranscriptReader
+ private readonly agents = new Agents()
+ private profileShown?: string
+ private profileAt = -Infinity
+ private profileTimer?: NodeJS.Timeout
constructor(
private readonly hub: Hub,
@@ -181,10 +203,14 @@ export class Session {
private data: SessionGroupData,
) {
const {chat, profile: user, root} = hub
- const {number, name, model, effort, hostDeclined = false} = stored
+ const {number, name, model, effort, hostDeclined = false, account, transcript, goal, recap, title} = stored
this.number = number
this.name = name
this.description = {model, effort}
+ this.transcript = transcript
+ this.claude = {account, goal, recap, title}
+ this.accountReader = new AccountReader(account)
+ this.transcriptReader = new TranscriptReader(transcript, {goal, recap, title})
this.hostDeclined = hostDeclined
this.actions = new Actions(data.mode ?? "requests", hub.expireHours, controlDataOf(group.customData)?.nextAction ?? firstAction, {
refusal: action => this.control.refusal(action),
@@ -241,32 +267,175 @@ export class Session {
// spec: spec/architecture.md#hub-session-readrecord
async readRecord(): Promise {
- if (!this.attached || this.record === undefined) {
+ if (!this.attached) {
this.claudeStatus = undefined
return
}
- this.recordRead ??= recordStatus(this.record)
- .then(
- status => {
- this.claudeStatus = status
- },
- error => {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") this.claudeStatus = undefined
- },
- )
+ this.recordRead ??= Promise.all([this.readStatus(), this.readClaudeCode(), this.readAgents()])
+ .then(() => undefined)
.finally(() => (this.recordRead = undefined))
await withinTime(this.recordRead, recordReadMs)
}
+ // spec: spec/architecture.md#hub-session-readrecord
+ private async readStatus(): Promise {
+ if (this.record === undefined) {
+ this.claudeStatus = undefined
+ return
+ }
+ await recordStatus(this.record).then(
+ status => {
+ this.claudeStatus = status
+ },
+ error => {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") this.claudeStatus = undefined
+ },
+ )
+ }
+
+ // spec: spec/architecture.md#hub-session-readclaudecode
+ private async readClaudeCode(): Promise {
+ const account = this.globalConfig === undefined ? this.claude.account : await this.accountReader.read(this.globalConfig)
+ const {goal, recap, title} = this.transcript === undefined ? this.claude : await this.transcriptReader.read(this.transcript)
+ const {claude} = this
+ if (account === claude.account && goal === claude.goal && recap === claude.recap && title === claude.title) return
+ const read = {account, goal, recap, title}
+ this.claude = read
+ this.store({...read, transcript: this.transcript})
+ await this.describe().catch(error => logError(`description of session ${this.number}`, error))
+ }
+
// spec: spec/architecture.md#hub-session-readrecord
stateLine(): string | undefined {
+ const state = this.state()
+ return state === undefined ? undefined : `${state[0]} ${this.displayName}: ${state[1]}`
+ }
+
+ // spec: spec/api.md#session-board
+ boardSession(): BoardSession {
+ const state = this.state()
+ const [emoji, text] = state ?? stoppedState
+ const {title, recap} = this.claude
+ const titled = title === undefined || title === this.name ? undefined : title.includes("*") ? title : `*${title}*`
+ const lines = [`${emoji} ${this.displayName}: ${text}`, titled, this.details() || undefined, agentsLine(this.agents.all(), Date.now()), recap]
+ return {session: this.number, running: state !== undefined, emoji, text: lines.filter(line => line !== undefined).join("\n")}
+ }
+
+ // spec: spec/architecture.md#hub-session-readrecord
+ private state(): [string, string] | undefined {
const state = claudeStates.get(this.claudeStatus ?? "")
- const dialog = state === undefined || this.claudeStatus === "waiting"
- const cards = this.actions.pending().filter(({tool, interrupted}) => !interrupted && (dialog || tool !== "permission")).length
- if (cards > 0) return `🟠 ${this.displayName}: waiting for you, ${cards} approval${cards === 1 ? "" : "s"}`
+ const cards = this.actions.pending().filter(({interrupted}) => !interrupted).length
+ if (cards > 0) return ["🟠", `waiting for you, ${cards} approval${cards === 1 ? "" : "s"}`]
if (!this.attached) return undefined
- const [emoji, text] = state ?? unknownState
- return `${emoji} ${this.displayName}: ${text}`
+ return state ?? unknownState
+ }
+
+ // spec: spec/api.md#session-group-profile
+ private details(): string {
+ const {model, effort} = this.description
+ const {account, goal} = this.claude
+ return [account, model, effort === undefined ? undefined : `effort ${effort}`, goal === undefined ? undefined : `goal ${goal}`].filter(part => part !== undefined).join(" · ")
+ }
+
+ // spec: spec/api.md#session-group-profile
+ private describe(): Promise {
+ const shortDescr = this.details()
+ const {recap} = this.claude
+ const shown = JSON.stringify([shortDescr, recap])
+ if (shown === this.profileShown) return Promise.resolve()
+ const wait = this.profileAt + this.hub.profileMs - Date.now()
+ if (wait > 0) {
+ this.profileTimer ??= setTimeout(() => {
+ this.profileTimer = undefined
+ this.describe().catch(error => logError(`description of session ${this.number}`, error))
+ }, wait).unref()
+ return Promise.resolve()
+ }
+ this.profileShown = shown
+ const at = Date.now()
+ return this.control.describe(shortDescr || undefined, recap).then(
+ changed => {
+ if (changed) this.profileAt = at
+ },
+ error => {
+ this.profileShown = undefined
+ throw error
+ },
+ )
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ stopDescribing(): void {
+ clearTimeout(this.profileTimer)
+ this.profileTimer = undefined
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ private onAgents(agent: AgentEvent | undefined, task: TaskEnd | undefined, workflow: WorkflowRun | undefined): boolean {
+ const now = Date.now()
+ if (workflow !== undefined) this.postCard(this.agents.workflow(workflow, now))
+ if (agent !== undefined && "start" in agent) this.postCard(this.agents.start(agent.id, agent.start, now))
+ if (agent !== undefined && "step" in agent) this.agents.step(agent.id, agent.step, now)
+ if (agent !== undefined && "report" in agent) this.agents.report(agent.id, agent.report)
+ const stopped = agent !== undefined && "stop" in agent ? this.agents.stop(agent.id, agent.stop, now) : undefined
+ if (stopped !== undefined) void this.showCard(stopped, now)
+ const ended = task === undefined ? undefined : this.agents.task(task, now)
+ if (ended?.kind === "workflow") void this.readWorkflow(ended).then(() => this.showCard(ended, Date.now()))
+ else if (ended !== undefined) void this.showCard(ended, now)
+ return ended !== undefined
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ private async readAgents(): Promise {
+ await Promise.all(this.agents.live().map(card => (card.kind === "agent" ? this.readAgent(card) : this.readWorkflow(card))))
+ const now = Date.now()
+ for (const card of this.agents.live()) if (now - card.postedAt >= liveLineMs) card.end = {status: "stopped", at: now}
+ for (const card of this.agents.all()) void this.showCard(card, now)
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ private async readAgent(agent: Agent): Promise {
+ const tokens = await lastUsage(agent.transcript)
+ if (tokens !== undefined) agent.tokens = tokens
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ private async readWorkflow(workflow: Workflow): Promise {
+ applyJournal(workflow, await workflow.lines.read(journalPath(workflow)))
+ const reads = [...workflow.journal.values()].filter(({state, agentId}) => state === "started" || !workflow.counted.has(agentId))
+ await Promise.all(reads.map(async ({state, agentId}) => {
+ const tokens = await lastUsage(workflowAgentTranscript(workflow, agentId))
+ if (tokens !== undefined) workflow.tokens.set(agentId, tokens)
+ if (state !== "started") workflow.counted.add(agentId)
+ }))
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ private postCard(card: Card): void {
+ const text = cardText(card, card.postedAt)
+ card.sent = text
+ card.sentAt = card.postedAt
+ card.item = this.post([{text, priority: -1}], undefined, true).then(
+ ([sent]) => sent?.chatItem.meta.itemId,
+ error => {
+ logError(`agents of session ${this.number}`, error)
+ return undefined
+ },
+ )
+ }
+
+ // spec: spec/architecture.md#hub-session-readagents
+ private showCard(card: Card, now: number): Promise | undefined {
+ const text = cardText(card, now)
+ const live = card.end === undefined
+ if (card.item === undefined || text === card.sent || (live && now - card.sentAt < cardEditMs)) return undefined
+ card.sent = text
+ card.sentAt = now
+ card.item = card.item.then(async itemId => {
+ if (itemId !== undefined) await this.updateItem(itemId, text, live).catch(error => logError(`agents of session ${this.number}`, error))
+ return itemId
+ })
+ return card.item
}
// spec: spec/architecture.md#hub-session-readrecord
@@ -389,7 +558,8 @@ export class Session {
}
// spec: spec/architecture.md#hub-session-turn
- async turn({at, prompt, typed, note, midTurn, answer, model, switched, effort, step, text, usage, limits, statusLine}: TurnRequest): Promise {
+ async turn({at, prompt, typed, note, midTurn, answer, model, switched, effort, step, text, usage, limits, statusLine, agent, task, workflow}: TurnRequest): Promise {
+ const owned = this.onAgents(agent, task, workflow)
const startsTurn = prompt !== undefined && midTurn !== true
if (startsTurn || answer !== undefined) {
this.endPermissions(at)
@@ -422,15 +592,14 @@ export class Session {
if (switches.length > 0) await this.post(switches).catch(error => this.postRefusal(error, noteRefused, featureOff))
if (text !== undefined) this.text(text, at ?? Date.now())
if (step !== undefined) await this.step(step, at ?? Date.now())
- if (note !== undefined) await this.post([{text: note, priority: -1}]).catch(error => this.postRefusal(error, noteRefused, featureOff))
+ if (note !== undefined && !owned) await this.post([{text: note, priority: -1}]).catch(error => this.postRefusal(error, noteRefused, featureOff))
const typedPrompt = prompt !== undefined && typed !== false && prompt.replace(channelPrompt, "").trim() !== "" && matched.length === 0 && parseCommand(prompt) === undefined
const userPost = typedPrompt ? this.hub.user?.post(this.number, textParts(prompt)).catch(error => this.postRefusal(error, "User's prompt was not posted", notAllowedForUser)) : undefined
if (startsTurn && (typedPrompt || matched.length > 0) && (at ?? Date.now()) >= this.answeredAt) this.openTurn(at ?? Date.now(), matched[0]?.item, userPost)
await userPost
if (answer !== undefined && end !== undefined) await this.answer(answer, quoted, at ?? Date.now(), (await streamed) === true, end)
} finally {
- const {model: shown, effort: level} = this.description
- if (described) await this.control.describe([shown, level === undefined ? undefined : `effort ${level}`].filter(part => part !== undefined).join(" · "))
+ if (described) await this.describe()
}
}
@@ -471,7 +640,9 @@ export class Session {
endLive(): Promise {
this.endSteps()
this.closeOpenings(() => true)
- return this.endTexts(Infinity).then(() => this.finalizing)
+ const now = Date.now()
+ const cards = this.agents.endAll(now).map(card => this.showCard(card, now))
+ return Promise.all([this.endTexts(Infinity), ...cards]).then(() => this.finalizing)
}
// spec: spec/architecture.md#hub-session-endpermissions
@@ -993,6 +1164,7 @@ export class Hub implements SessionGroups {
userContactId?: number
promptsHeldUntil = 0
machine = (): Machine | undefined => machineState(this.root)
+ profileMs = profileEveryMs
private readonly sessions = new Map()
stopped = false
private controlEvents: Promise = Promise.resolve()
@@ -1102,8 +1274,8 @@ export class Hub implements SessionGroups {
// spec: spec/architecture.md#hub-hub-showsessions
showSessions(): Promise {
this.listing ??= Promise.all([...this.sessions.values()].map(session => session.readRecord()))
- .then(() => this.main.showList(this.sessionsText()))
- .catch(error => logError("list of sessions", error))
+ .then(() => this.main.showBoard([...this.sessions.values()].sort((a, b) => a.number - b.number).map(session => session.boardSession())))
+ .catch(error => logError("board of sessions", error))
.finally(() => (this.listing = undefined))
return this.listing
}
@@ -1144,6 +1316,7 @@ export class Hub implements SessionGroups {
await this.showSessions()
await waitForCancelledCards(stopped.flatMap(({lost, cancelled}) => (lost ? [] : cancelled)), cardsWait, new AbortController().signal)
await Promise.all(sessions.map(session => session.endLive()))
+ for (const session of sessions) session.stopDescribing()
for (const {tools} of sessions) tools.close()
await this.user?.close()
await this.chat.close()
@@ -1164,7 +1337,6 @@ export class Hub implements SessionGroups {
const group = await createGroup(this.chat, this.profile.userId, {
displayName,
fullName: "",
- description: `The Claude Code session ${number}. Members send it prompts; admins and owners also send the group's commands and approve tool use.`,
groupPreferences: {history: {enable: T.GroupFeatureEnabled.On}, directMessages: {enable: T.GroupFeatureEnabled.Off}, commands: controlCommands},
chatLayout: T.ChatLayout.Terminal,
}, {[sessionKey]: {session: number}})
diff --git a/packages/simplex-chat-mcp/src/main-group.ts b/packages/simplex-chat-mcp/src/main-group.ts
index c5dffb447e..d6a7774049 100644
--- a/packages/simplex-chat-mcp/src/main-group.ts
+++ b/packages/simplex-chat-mcp/src/main-group.ts
@@ -14,8 +14,10 @@ const mainCommands: T.ChatBotCommand[] = [
const mainKey = "simplexMcpMain"
// spec: spec/api.md#main-group-profile
const listKey = "simplexMcpList"
-// spec: spec/api.md#list-of-sessions
-const listAge = 23 * 3_600_000
+// spec: spec/api.md#main-group-profile
+const boardKey = "simplexMcpBoard"
+// spec: spec/api.md#session-board
+const boardAge = 23 * 3_600_000
// spec: spec/architecture.md#main-group-maincommands
const greeting = "I'm Claude. Each Claude Code session has its own group, and you get its invitation here. /sessions lists the sessions; /join N joins the group of session N."
// spec: spec/api.md#main-group
@@ -36,21 +38,41 @@ export interface SessionGroups {
inviteOwner(member: T.GroupMember): Promise
}
+// spec: spec/api.md#session-board
+export interface BoardSession {
+ session: number
+ running: boolean
+ emoji: string
+ text: string
+}
+
// spec: spec/api.md#main-group-profile
-interface SessionList {
+interface BoardItem {
item: number
at: number
}
+// spec: spec/api.md#main-group-profile
+interface BoardEntry extends BoardItem {
+ session: number
+}
+
+// spec: spec/api.md#main-group-profile
+interface Board {
+ summary?: BoardItem
+ sessions: BoardEntry[]
+}
+
export class MainGroup {
lost = false
private members: T.GroupMember[] = []
private events: Promise = Promise.resolve()
private commands: Promise = Promise.resolve()
private linkText?: string
- private list?: SessionList
- private shown?: string
- private tooLarge?: string
+ private board: Board
+ private oldList?: number
+ private readonly shown = new Map()
+ private shownSummary?: string
constructor(
private readonly chat: api.ChatApi,
@@ -59,7 +81,8 @@ export class MainGroup {
private name: string,
private readonly sessions: SessionGroups,
) {
- this.list = listOf(group.customData)
+ this.board = boardOf(group.customData)
+ this.oldList = listOf(group.customData)
}
get groupId(): number {
@@ -132,7 +155,10 @@ export class MainGroup {
this.lost = true
await deleteGroup(this.chat, this.group)
this.group = await createMainGroup(this.chat, this.userId, this.name)
- this.list = undefined
+ this.board = {sessions: []}
+ this.oldList = undefined
+ this.shown.clear()
+ this.shownSummary = undefined
this.lost = false
await this.load()
await this.openLink()
@@ -140,54 +166,96 @@ export class MainGroup {
})
}
- // spec: spec/architecture.md#main-group-maingroup-showlist
- showList(text: string): Promise {
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ showBoard(sessions: BoardSession[]): Promise {
return this.serialize(async () => {
- if (this.lost || text === this.tooLarge) return
- await this.renderList(text).catch(error => {
- if (!isTooLarge(error)) throw error
- this.tooLarge = text
- logError("list of sessions", error)
- })
+ if (this.lost) return
+ if (this.oldList !== undefined) await this.deleteItem(this.oldList, "old list of sessions")
+ const owned = this.owners().length > 0
+ const posted: number[] = []
+ const entries: BoardEntry[] = []
+ for (const session of sessions) {
+ const entry = this.board.sessions.find(known => known.session === session.session)
+ const kept = entry === undefined ? (session.running && owned ? await this.postEntry(session, posted) : undefined) : await this.renderEntry(entry, session, posted)
+ if (kept !== undefined) entries.push(kept)
+ }
+ for (const entry of this.board.sessions) if (!sessions.some(({session}) => session === entry.session)) await this.deleteEntry(entry)
+ const shown = sessions.filter(({session}) => entries.some(entry => entry.session === session))
+ const summary = await this.renderSummary(summaryText(shown), owned && entries.length > 0, posted)
+ await this.saveBoard({...(summary === undefined ? {} : {summary}), sessions: entries}, posted)
})
}
- // spec: spec/architecture.md#main-group-maingroup-showlist
- private async renderList(text: string): Promise {
- const {list} = this
- if (list === undefined) {
- if (this.owners().length > 0) await this.postList(text)
- return
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async renderEntry(entry: BoardEntry, session: BoardSession, posted: number[]): Promise {
+ if (!session.running && entry.at <= Date.now() - boardAge) return this.deleteEntry(entry)
+ if (session.text === this.shown.get(entry.session)) return entry
+ if (await this.edited(entry.item, session.text)) {
+ this.shown.set(entry.session, session.text)
+ return entry
}
- if (list.at <= Date.now() - listAge) return this.replaceList(list, text)
- if (text === this.shown) return
+ await this.deleteEntry(entry)
+ return session.running ? this.postEntry(session, posted) : undefined
+ }
+
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async postEntry(session: BoardSession, posted: number[]): Promise {
+ const item = await this.postItem(session.text, posted)
+ this.shown.set(session.session, session.text)
+ return {session: session.session, ...item}
+ }
+
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async deleteEntry(entry: BoardEntry): Promise {
+ this.shown.delete(entry.session)
+ await this.deleteItem(entry.item, "old message of the board")
+ return undefined
+ }
+
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async renderSummary(text: string, postable: boolean, posted: number[]): Promise {
+ const {summary} = this.board
+ if (summary !== undefined && (text === this.shownSummary || (await this.edited(summary.item, text)))) {
+ this.shownSummary = text
+ return summary
+ }
+ if (summary !== undefined) await this.deleteItem(summary.item, "old summary of the board")
+ else if (!postable) return undefined
+ this.shownSummary = text
+ return this.postItem(text, posted)
+ }
+
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async edited(item: number, text: string): Promise {
try {
- await this.chat.apiUpdateChatItem(T.ChatType.Group, this.groupId, list.item, {type: "text", text})
- this.shown = text
+ await this.chat.apiUpdateChatItem(T.ChatType.Group, this.groupId, item, {type: "text", text})
+ return true
} catch (error) {
if (!isRefusedEdit(error)) throw error
- await this.replaceList(list, text)
+ return false
}
}
- // spec: spec/architecture.md#main-group-maingroup-showlist
- private async replaceList(old: SessionList, text: string): Promise {
- await this.postList(text)
- await this.deleteItem(old.item, "old list of sessions")
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async postItem(text: string, posted: number[]): Promise {
+ const item = await this.post(text, -1)
+ posted.push(item)
+ return {item, at: Date.now()}
}
- // spec: spec/architecture.md#main-group-maingroup-showlist
- private async postList(text: string): Promise {
- const list = {item: await this.post(text, -1), at: Date.now()}
- const customData = {...this.group.customData, [mainKey]: true, [listKey]: list}
+ // spec: spec/architecture.md#main-group-maingroup-showboard
+ private async saveBoard(board: Board, posted: number[]): Promise {
+ if (this.oldList === undefined && JSON.stringify(board) === JSON.stringify(this.board)) return
+ const {[listKey]: _, ...data} = (this.group.customData ?? {}) as {[key: string]: unknown}
+ const customData = {...data, [mainKey]: true, [boardKey]: board}
try {
await this.chat.apiSetGroupCustomData(this.groupId, customData)
} catch (error) {
- await this.deleteItem(list.item, "new list of sessions")
+ for (const item of posted) await this.deleteItem(item, "new message of the board")
throw error
}
- this.list = list
- this.shown = text
+ this.board = board
+ this.oldList = undefined
this.group = {...this.group, customData}
}
@@ -288,22 +356,39 @@ function isMissingLink(error: unknown): boolean {
return chatError?.type === "errorStore" && chatError.storeError.type === "groupLinkNotFound"
}
-// spec: spec/architecture.md#main-group-maingroup-showlist
+// spec: spec/architecture.md#main-group-maingroup-showboard
function isRefusedEdit(error: unknown): boolean {
const chatError = chatErrorOf(error)
return (chatError?.type === "error" && chatError.errorType.type === "invalidChatItemUpdate") || (chatError?.type === "errorStore" && chatError.storeError.type === "chatItemNotFound")
}
-// spec: spec/architecture.md#main-group-maingroup-showlist
-function isTooLarge(error: unknown): boolean {
- const chatError = chatErrorOf(error)
- return chatError?.type === "errorStore" && chatError.storeError.type === "largeMsg"
+// spec: spec/api.md#session-board
+function summaryText(sessions: BoardSession[]): string {
+ if (sessions.length === 0) return "No sessions."
+ return `${sessions.length} session${sessions.length === 1 ? "" : "s"} ${sessions.map(({emoji}) => emoji).join(" ")}`
}
// spec: spec/api.md#main-group-profile
-function listOf(customData: object | undefined): SessionList | undefined {
- const list = (customData as {[listKey]?: Partial} | undefined)?.[listKey]
- return typeof list?.item === "number" && typeof list.at === "number" ? {item: list.item, at: list.at} : undefined
+function listOf(customData: object | undefined): number | undefined {
+ const item = (customData as {[listKey]?: {item?: unknown}} | undefined)?.[listKey]?.item
+ return typeof item === "number" ? item : undefined
+}
+
+// spec: spec/api.md#main-group-profile
+function boardOf(customData: object | undefined): Board {
+ const board = (customData as {[boardKey]?: {summary?: unknown; sessions?: unknown}} | undefined)?.[boardKey]
+ const summary = itemOf(board?.summary)
+ const entries = board?.sessions
+ const sessions = (Array.isArray(entries) ? entries : []).flatMap((entry: {session?: unknown} | null) => {
+ const item = itemOf(entry)
+ return item !== undefined && typeof entry?.session === "number" ? [{session: entry.session, ...item}] : []
+ })
+ return {...(summary === undefined ? {} : {summary}), sessions}
+}
+
+function itemOf(value: unknown): BoardItem | undefined {
+ const {item, at} = (value ?? {}) as {item?: unknown; at?: unknown}
+ return typeof item === "number" && typeof at === "number" ? {item, at} : undefined
}
// spec: spec/api.md#main-group-profile
diff --git a/packages/simplex-chat-mcp/src/protocol.ts b/packages/simplex-chat-mcp/src/protocol.ts
index 440c9a266a..2687720a30 100644
--- a/packages/simplex-chat-mcp/src/protocol.ts
+++ b/packages/simplex-chat-mcp/src/protocol.ts
@@ -30,6 +30,7 @@ export interface SessionRequest {
name?: string
config: Config
record?: string
+ globalConfig?: string
}
// spec: spec/architecture.md#protocol-sessionrequest
@@ -40,6 +41,7 @@ export interface TitleRequest {
name?: string
project: string
model?: string
+ transcript?: string
config: Config
unattended?: boolean
}
@@ -71,6 +73,40 @@ export interface TurnRequest {
switched?: boolean
limits?: Limits
statusLine?: boolean
+ agent?: AgentEvent
+ task?: TaskEnd
+ workflow?: WorkflowRun
+}
+
+// spec: spec/architecture.md#protocol-agentevent
+export type AgentEvent = {id: string} & ({start: AgentStart} | {step: Step} | {report: string} | {stop: string})
+
+// spec: spec/architecture.md#protocol-agentevent
+export interface AgentStart {
+ type: string
+ description: string
+ toolUse?: string
+ transcript: string
+}
+
+// spec: spec/architecture.md#protocol-agentevent
+export type TaskStatus = "completed" | "failed" | "killed" | "stopped"
+
+// spec: spec/architecture.md#protocol-agentevent
+export interface TaskEnd {
+ toolUse: string
+ status: TaskStatus
+ tokens?: number
+ steps?: number
+ ms?: number
+}
+
+// spec: spec/architecture.md#protocol-agentevent
+export interface WorkflowRun {
+ toolUse: string
+ run: string
+ name: string
+ folder: string
}
// spec: spec/architecture.md#protocol-limits
diff --git a/packages/simplex-chat-mcp/src/service.ts b/packages/simplex-chat-mcp/src/service.ts
index 91b06e643c..106e482dd0 100644
--- a/packages/simplex-chat-mcp/src/service.ts
+++ b/packages/simplex-chat-mcp/src/service.ts
@@ -45,6 +45,8 @@ export interface SessionLike {
readonly displayName: string
open: boolean
record?: string
+ globalConfig?: string
+ transcript?: string
onLine?: (line: AttachLine) => void
busy(): boolean
rename(name: string): Promise
@@ -241,6 +243,7 @@ export class Service {
if (request.pid !== undefined) this.registered.emit(String(request.pid))
const agent = await entry.opening
agent.record = request.record
+ agent.globalConfig = request.globalConfig
if (previous.pid !== undefined && (previous.pid !== request.pid || started === undefined || previous.started !== started)) agent.endToolApprovals()
if (entry.attached === 0) this.scheduleIdle(id, entry)
await this.hub.configure(request.config)
@@ -284,7 +287,7 @@ export class Service {
}
// spec: spec/api.md#socket-protocol
- private async applyTitle({id: given, pid, at, name, project, model, config}: TitleRequest): Promise {
+ private async applyTitle({id: given, pid, at, name, project, model, transcript, config}: TitleRequest): Promise {
const id = await this.resolve(given, pid)
const title = name?.trim() || undefined
const entry = this.entry(id, {id, project, name: title, config})
@@ -293,6 +296,7 @@ export class Service {
this.titled.emit(String(pid))
}
const agent = await entry.opening
+ if (transcript !== undefined) agent.transcript = transcript
await this.hub.configure(config)
if (title !== undefined) await this.rename(this.folder(id), agent, title)
if (model !== undefined) await agent.turn({id, at, model})
diff --git a/packages/simplex-chat-mcp/src/session.ts b/packages/simplex-chat-mcp/src/session.ts
index 1e6d2d66e2..8d400a2fa6 100644
--- a/packages/simplex-chat-mcp/src/session.ts
+++ b/packages/simplex-chat-mcp/src/session.ts
@@ -62,7 +62,7 @@ export async function startSession(env: NodeJS.ProcessEnv = process.env, io: Ses
configError ??= error.message
}
const server = new McpServer({name: "simplex-mcp", version: io.version}, {instructions: `${instructions("Claude", "SimpleX service")}\n${channelInstructions}`, capabilities: {experimental: {"claude/channel": {}, "claude/channel/permission": {}}}})
- const link = new ServiceLink(ServiceClient.forRoot(dataRoot(env)), {id, pid: process.ppid, project: env.CLAUDE_PROJECT_DIR || process.cwd(), config, record: resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "sessions", `${process.ppid}.json`)}, io, line => {
+ const link = new ServiceLink(ServiceClient.forRoot(dataRoot(env)), {id, pid: process.ppid, project: env.CLAUDE_PROJECT_DIR || process.cwd(), config, record: resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "sessions", `${process.ppid}.json`), globalConfig: resolve(env.CLAUDE_CONFIG_DIR || homedir(), ".claude.json")}, io, line => {
const notification = channelNotification(line as AttachLine)
if (notification !== undefined) server.server.notification(notification).catch(error => logError("SimpleX channel", error))
})
diff --git a/packages/simplex-chat-mcp/test/e2e/service.test.ts b/packages/simplex-chat-mcp/test/e2e/service.test.ts
index f31e885c2e..91750d8a0d 100644
--- a/packages/simplex-chat-mcp/test/e2e/service.test.ts
+++ b/packages/simplex-chat-mcp/test/e2e/service.test.ts
@@ -238,7 +238,7 @@ test("an owner joins the Main group and each session's group, whose profile sets
expect(await mainProfile()).toMatchObject(edited)
}, 600_000)
-test("the Main group shows every session in one list, the running ones with their states from Claude Code's record and the cards, edited in place, and /sessions replies with its text", async () => {
+test("the Main group shows a message of each running session with its state from Claude Code's record and the cards, and a summary, edited in place, and /sessions replies with the list of sessions", async () => {
const root = join(dir, "list", "root")
await prepareRoot(smpServer.address, root)
const alice = await personIn("list", "Alice")
@@ -255,20 +255,31 @@ test("the Main group shows every session in one list, the running ones with thei
await until(() => attached.length === 1)
const owner = await client.request("GET", "/link")
const invitations = joinSessionGroups(alice, ["1 · one", "2 · two"])
- const working = received(alice.chat, ({chatItem}) => chatItem.meta.itemText === "🟢 1 · one: working\n⚪ Not running: 2 · two")
+ const working = received(alice.chat, ({chatItem}) => chatItem.meta.itemText === "🟢 1 · one: working")
+ const summarized = received(alice.chat, ({chatItem}) => chatItem.meta.itemText === "1 session 🟢")
const mainGroupId = await joinByLink(alice, owner.link!)
- const list = await working
- expect(list.chatInfo).toMatchObject({type: "group", groupInfo: {groupId: mainGroupId}})
+ const message = await working
+ const summary = await summarized
+ expect(message.chatInfo).toMatchObject({type: "group", groupInfo: {groupId: mainGroupId}})
await invitations
- const edited = (text: string): Promise => updated(alice.chat, inGroup(mainGroupId, ({chatItem}) => chatItem.meta.itemId === list.chatItem.meta.itemId && chatItem.meta.itemText === text))
- const waiting = edited("🟠 1 · one: waiting for you, 1 approval\n⚪ Not running: 2 · two")
+ const edited = (item: T.AChatItem, text: string): Promise => updated(alice.chat, inGroup(mainGroupId, ({chatItem}) => chatItem.meta.itemId === item.chatItem.meta.itemId && chatItem.meta.itemText === text))
+ const waiting = Promise.all([edited(message, "🟠 1 · one: waiting for you, 1 approval"), edited(summary, "1 session 🟠")])
writeFileSync(record, JSON.stringify({status: "waiting", waitingFor: "permission prompt"}))
await client.request("POST", "/permission", {id: one, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"})
await waiting
- const idle = edited("🔴 1 · one: idle\n⚪ Not running: 2 · two")
+ const idle = edited(message, "🔴 1 · one: idle")
writeFileSync(record, JSON.stringify({status: "idle"}))
+ await client.request("POST", "/turn", {id: one, answer: ""})
await idle
- const ended = edited("⚪ Not running: 2 · two, 1 · one")
+ const agentPosted = received(alice.chat, ({chatItem}) => chatItem.meta.itemText === "🤖 Explore · find callers\n0 steps · 0:00")
+ const agentLine = edited(message, "🔴 1 · one: idle\n🤖 1 agent working")
+ await client.request("POST", "/turn", {id: one, agent: {id: "a1", start: {type: "Explore", description: "find callers", transcript: join(dir, "list", "agent-a1.jsonl")}}})
+ const agentItem = await agentPosted
+ await agentLine
+ const agentEnded = updated(alice.chat, ({chatItem}) => chatItem.meta.itemId === agentItem.chatItem.meta.itemId && chatItem.meta.itemText.startsWith("🤖 Explore · find callers · ✅ ") && chatItem.meta.itemText.endsWith("\nFound 6 callers."))
+ await client.request("POST", "/turn", {id: one, agent: {id: "a1", stop: "Found 6 callers."}})
+ await agentEnded
+ const ended = Promise.all([edited(message, "⚪ 1 · one: stopped"), edited(summary, "1 session ⚪")])
controller.abort()
await ended
const replied = received(alice.chat, sessionsReply(mainGroupId, "⚪ Not running: 2 · two, 1 · one"))
@@ -428,7 +439,7 @@ test("the hooks post a prompt typed in the terminal as User, also the session's
const fixed = updated(alice.chat, matches(`^Fixed\\.\\n!- Done in 2\\.0 s · 861 output tokens · 36K tokens in context${machine}`))
const usage = {input_tokens: 3, cache_creation_input_tokens: 600, cache_read_input_tokens: 35_000, output_tokens: 861}
appendFileSync(transcript, `${JSON.stringify({type: "assistant", timestamp: "2026-11-13T10:00:02.000Z", message: {id: "msg_1", model: "claude-opus-5", content: [{type: "text", text: "Fixed."}], usage}})}\n`)
- const described = alice.chat.wait("groupUpdated", ({toGroup}) => toGroup.groupId === groupId && toGroup.groupProfile.shortDescr === "claude-opus-5", 60_000)
+ const described = alice.chat.wait("groupUpdated", ({toGroup}) => toGroup.groupId === groupId && toGroup.groupProfile.shortDescr === "claude-opus-5", 120_000)
await hook({hook_event_name: "Stop", transcript_path: transcript, prompt_id: "p1", last_assistant_message: "Fixed."})
await fixed
expect((await described)?.toGroup.groupProfile.shortDescr).toBe("claude-opus-5")
@@ -716,7 +727,7 @@ test("a member of the Main group joins a session's group by /join as admin, prom
await bob.chat.apiChatItemReaction(T.ChatType.Group, bobGroupOne, (await toolUse).chatItem.meta.itemId, true, {type: "emoji", emoji: "👍"})
await until(() => attached.some(({prompt}) => prompt?.from === "Bob" && prompt.text.endsWith("\n👍")))
expect((await alice.chat.apiListMembers(groupOne)).find(({memberProfile}) => memberProfile.displayName === "Bob")).toMatchObject({memberStatus: expect.stringMatching(/^(connected|complete)$/)})
- const described = alice.chat.wait("groupUpdated", ({toGroup}) => toGroup.groupId === groupOne && toGroup.groupProfile.shortDescr === "claude-opus-5", 60_000)
+ const described = alice.chat.wait("groupUpdated", ({toGroup}) => toGroup.groupId === groupOne && toGroup.groupProfile.shortDescr === "claude-opus-5", 120_000)
await turn(JSON.stringify({session_id: one, hook_event_name: "PostModelSwitch", to_model: "claude-opus-5"}), {}, client)
expect((await described)?.toGroup.groupProfile.groupPreferences?.files?.enable).toBe(T.GroupFeatureEnabled.Off)
diff --git a/packages/simplex-chat-mcp/test/unit/agents.test.ts b/packages/simplex-chat-mcp/test/unit/agents.test.ts
new file mode 100644
index 0000000000..91e07fea20
--- /dev/null
+++ b/packages/simplex-chat-mcp/test/unit/agents.test.ts
@@ -0,0 +1,53 @@
+import {Agents, agentsLine, applyJournal, cardText, clock, tokensText} from "../../src/agents"
+
+const start = {type: "Explore", description: "find the suspend callers", toolUse: "toolu_1", transcript: "/t/agent-a1.jsonl"}
+const journal = (lines: object[]): string[] => lines.map(line => JSON.stringify(line))
+
+describe("agents", () => {
+ it("shows a working agent's steps, tokens, time in 5 s steps and its open step", () => {
+ const agents = new Agents()
+ const agent = agents.start("a1", start, 0)
+ agents.step("a1", {id: "s1", text: "📖 Read SuspendChat.swift"}, 1_000)
+ agent.tokens = 38_200
+ expect(cardText(agent, 67_000)).toBe("🤖 Explore · find the suspend callers\n1 step · 38.2k tokens · 1:05 · now: 📖 Read SuspendChat.swift")
+ })
+
+ it("shows an agent stalled 2 minutes after its last step ended, and 10 minutes while a step runs", () => {
+ const agents = new Agents()
+ const agent = agents.start("a1", start, 0)
+ agents.step("a1", {id: "s1", text: "💻 cabal build"}, 0)
+ const running = cardText(agent, 590_000)
+ agents.step("a1", {id: "s1", text: "💻 cabal build", end: true}, 600_000)
+ expect([running, cardText(agent, 730_000)]).toEqual(["🤖 Explore · find the suspend callers\n1 step · 9:50 · now: 💻 cabal build", "🤖 Explore · find the suspend callers\n1 step · 12:10 · ⚠️ no step for 2:10 · last: 💻 cabal build"])
+ })
+
+ it("shows an ended agent with its status, time, steps and tokens of its task, and its report", () => {
+ const agents = new Agents()
+ const agent = agents.start("a1", start, 0)
+ agents.report("a1", "Found 6 callers.")
+ agents.stop("a1", "Done.", 160_000)
+ agents.task({toolUse: "toolu_1", status: "completed", tokens: 61_500, steps: 22, ms: 160_000}, 161_000)
+ expect(cardText(agent, 200_000)).toBe("🤖 Explore · find the suspend callers · ✅ 2:40 · 22 steps · 61.5k tokens\nFound 6 callers.")
+ })
+
+ it("shows a workflow's phases in order of their first agent, done ones marked, its working agents, tokens and time", () => {
+ const agents = new Agents()
+ const workflow = agents.workflow({toolUse: "toolu_2", run: "wf_1", name: "review-changes", folder: "/t/wf_1"}, 0)
+ applyJournal(workflow, journal([{type: "launched"}, {type: "started", key: "k1", agentId: "b1", phase: "Review"}, {type: "result", key: "k1", agentId: "b1"}, {type: "started", key: "k2", agentId: "b2", phase: "Verify"}, {type: "started", key: "k3", agentId: "b3", phase: "Verify"}]))
+ workflow.tokens.set("b1", 400_000).set("b2", 12_000)
+ expect(cardText(workflow, 390_000)).toBe("⚙️ review-changes · Review 1/1 ✅ · Verify 0/2 · 2 working · 412k tokens · 6:30")
+ })
+
+ it("counts working agents, the agents of workflows and stalled agents, with the longest stall and each workflow's phase", () => {
+ const agents = new Agents()
+ agents.start("a1", start, 0)
+ agents.start("a2", start, 125_000)
+ const workflow = agents.workflow({toolUse: "toolu_2", run: "wf_1", name: "review", folder: "/t/wf_1"}, 0)
+ applyJournal(workflow, journal([{type: "started", key: "k1", agentId: "b1", phase: "Verify"}]))
+ expect(agentsLine(agents.all(), 130_000)).toBe("🤖 3 agents working · 1 stalled 2:10 · ⚙️ review Verify 0/1")
+ })
+
+ it("writes tokens with one decimal under 100k and times as M:SS or H:MM:SS", () => {
+ expect([tokensText(850), tokensText(38_249), tokensText(412_000), tokensText(1_250_000), clock(65_000), clock(3_605_000)]).toEqual(["850 tokens", "38.2k tokens", "412k tokens", "1.2M tokens", "1:05", "1:00:05"])
+ })
+})
diff --git a/packages/simplex-chat-mcp/test/unit/claude-code.test.ts b/packages/simplex-chat-mcp/test/unit/claude-code.test.ts
new file mode 100644
index 0000000000..f9f8de5b89
--- /dev/null
+++ b/packages/simplex-chat-mcp/test/unit/claude-code.test.ts
@@ -0,0 +1,64 @@
+import {appendFileSync, mkdtempSync, rmSync, utimesSync, writeFileSync} from "fs"
+import {tmpdir} from "os"
+import {join} from "path"
+import {AccountReader, TranscriptReader, lastUsage} from "../../src/claude-code"
+
+let folder: string
+
+beforeEach(() => {
+ folder = mkdtempSync(join(tmpdir(), "simplex-mcp-claude-code-"))
+})
+
+afterEach(() => rmSync(folder, {recursive: true, force: true}))
+
+const goal = (attachment: object): string => `${JSON.stringify({type: "attachment", attachment: {type: "goal_status", condition: "ship it", ...attachment}})}\n`
+const recap = (content: string): string => `${JSON.stringify({type: "system", subtype: "away_summary", content})}\n`
+
+describe("Claude Code account", () => {
+ it("is the email of the global config's OAuth account, read again after a write, and kept while the file is partly written", async () => {
+ const config = join(folder, ".claude.json")
+ const reader = new AccountReader()
+ writeFileSync(config, JSON.stringify({oauthAccount: {emailAddress: "alice@example.com"}}))
+ const first = await reader.read(config)
+ writeFileSync(config, '{"oauthAccount": {"emailAd')
+ utimesSync(config, new Date(), new Date(Date.now() + 1_000))
+ const partial = await reader.read(config)
+ writeFileSync(config, JSON.stringify({oauthAccount: {emailAddress: "bob@example.com"}}))
+ utimesSync(config, new Date(), new Date(Date.now() + 2_000))
+ expect([first, partial, await reader.read(config)]).toEqual(["alice@example.com", "alice@example.com", "bob@example.com"])
+ })
+})
+
+describe("Claude Code agent transcript", () => {
+ it("gives the tokens of the last request, its input, cache and output tokens, without a synthetic entry or a partly written line", async () => {
+ const transcript = join(folder, "agent-a1.jsonl")
+ const assistant = (model: string, usage: object): string => `${JSON.stringify({type: "assistant", message: {model, usage}})}\n`
+ writeFileSync(transcript, `${assistant("claude-opus-5", {input_tokens: 2, cache_creation_input_tokens: 700, cache_read_input_tokens: 110_000, output_tokens: 1_783})}${assistant("", {input_tokens: 0, output_tokens: 0})}{"type":"assistant","message":{"usage":`)
+ expect(await lastUsage(transcript)).toBe(112_485)
+ })
+})
+
+describe("Claude Code transcript", () => {
+ it("gives the goal state of the last goal entry: set, met, failed, and none after a clear", async () => {
+ const transcript = join(folder, "t.jsonl")
+ const reader = new TranscriptReader()
+ const states: unknown[] = []
+ for (const entry of [{met: false, sentinel: true}, {met: true, reason: "done"}, {met: false, failed: true}, {met: true, sentinel: true}]) {
+ appendFileSync(transcript, goal(entry))
+ states.push((await reader.read(transcript)).goal)
+ }
+ expect(states).toEqual(["set", "met", "failed", undefined])
+ })
+
+ it("reads the appended lines only, takes the recap without the hint and the title, and clears them at a new path", async () => {
+ const transcript = join(folder, "t.jsonl")
+ const reader = new TranscriptReader()
+ writeFileSync(transcript, recap("Built the board. Next, you review it. (disable recaps in /config)"))
+ const first = await reader.read(transcript)
+ writeFileSync(transcript, goal({met: false}), {flag: "r+"})
+ appendFileSync(transcript, `${JSON.stringify({type: "ai-title", aiTitle: "Board"})}\n${recap("Tests pass.")}`)
+ const appended = await reader.read(transcript)
+ writeFileSync(join(folder, "u.jsonl"), "")
+ expect([first, appended, await reader.read(join(folder, "u.jsonl"))]).toEqual([{recap: "Built the board. Next, you review it."}, {recap: "Tests pass.", title: "Board"}, {}])
+ })
+})
diff --git a/packages/simplex-chat-mcp/test/unit/hook.test.ts b/packages/simplex-chat-mcp/test/unit/hook.test.ts
index 4732532ba4..ca129ec5d2 100644
--- a/packages/simplex-chat-mcp/test/unit/hook.test.ts
+++ b/packages/simplex-chat-mcp/test/unit/hook.test.ts
@@ -1,4 +1,4 @@
-import {appendFileSync, mkdtempSync, rmSync, truncateSync, writeFileSync} from "fs"
+import {appendFileSync, mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync} from "fs"
import {tmpdir} from "os"
import {join} from "path"
import {ServiceClient} from "../../src/client"
@@ -50,6 +50,12 @@ describe("SessionStart hook", () => {
])
})
+ it("starts the session with the path of its transcript", async () => {
+ const {client, requests} = fakeClient({owners: ["Alice"]})
+ await sessionStart(JSON.stringify({...JSON.parse(input), transcript_path: "/c/projects/p/1.jsonl"}), {}, {client, nodeVersion: "22.1.0"})
+ expect(requests).toMatchObject([{route: "/title", body: {transcript: "/c/projects/p/1.jsonl"}}])
+ })
+
it("shows the link of the service's Main group with a QR code to the person only, while it has no owner", async () => {
const link = "https://simplex.chat/g#link"
const {client} = fakeClient({owners: [], link}, undefined, "Agents")
@@ -614,7 +620,6 @@ describe("turn hooks", () => {
{id: "toolu_Read", text: "!- 📖 Read /p/app-old/src/hook.ts!"},
{id: "toolu_WebFetch", text: "!- 🌐 Fetch https://spec.torproject.org/hspow-spec/common-protocol.html!"},
{id: "toolu_WebSearch", text: '!- 🔍 Search "hs_pow.c" tor source!'},
- {id: "toolu_Agent", text: "!- 🤖 Agent: Review pass 6 usage stats!"},
{id: "toolu_ToolSearch", text: "!- 🔍 ToolSearch: select:Monitor!"},
{id: "toolu_Glob", text: "!- 🔍 Glob **/*.ts in src!"},
{id: "toolu_Grep", text: "!- 🔍 Grep endSteps in src/hub.ts!"},
@@ -629,7 +634,7 @@ describe("turn hooks", () => {
])
})
- it("send a step at the end of each tool use with its outcome and duration, or in background for a launch, and nothing for a tool use of a subagent or of this plugin, or without its ID or tool", async () => {
+ it("send a step at the end of each tool use with its outcome and duration, or in background for a launch, and nothing for a tool use of this plugin, a launch of an agent, or without its ID or tool", async () => {
const {client, requests, ensured} = turnClient()
const bash = {command: "npm test", description: "Run the tests"}
const ended = (event: string, extra: object, tool = "Bash", input: object = bash) => turn(toolUse(event, tool, input, extra), {}, client, 0, 1)
@@ -644,8 +649,6 @@ describe("turn hooks", () => {
await ended("PostToolUse", {duration_ms: 25}, "Bash", {...bash, run_in_background: true})
await ended("PostToolUse", {duration_ms: 31}, "Agent", {description: "Review", prompt: "Review it.", run_in_background: true})
await ended("PostToolUseFailure", {error: "Exit code 127", is_interrupt: false, duration_ms: 12}, "Bash", {...bash, run_in_background: true})
- await turn(toolUse("PreToolUse", "Bash", bash, {agent_id: "af945fc18f2e2d0d9", agent_type: "general-purpose"}), {}, client, 0, 1)
- await ended("PostToolUse", {agent_id: "af945fc18f2e2d0d9", duration_ms: 13})
await turn(toolUse("PreToolUse", "mcp__plugin_simplex_simplex__send", {chat: "@1", text: "hi"}), {}, client, 0, 1)
await ended("PostToolUse", {duration_ms: 120}, "mcp__plugin_simplex_simplex__send")
await turn(JSON.stringify({session_id: id, hook_event_name: "PreToolUse", tool_input: bash, tool_use_id: "toolu_1"}), {}, client, 0, 1)
@@ -660,10 +663,54 @@ describe("turn hooks", () => {
{id: "toolu_Bash", text: "!- 💻 Run the tests 42 ms!", end: true},
{id: "toolu_Bash", text: "!- 💻 Run the tests 2.0 s!", end: true},
{id: "toolu_Bash", text: "!- 💻 Run the tests (in background)!", end: true},
- {id: "toolu_Agent", text: "!- 🤖 Agent: Review (in background)!", end: true},
{id: "toolu_Bash", text: "!- 💻 Run the tests ❌ 12 ms!", end: true},
])
- expect(ensured()).toBe(11)
+ expect(ensured()).toBe(10)
+ })
+
+ it("send the start of a subagent with its type, the description and tool use of its record and its transcript, and nothing for a teammate or without a record", async () => {
+ const folder = mkdtempSync(join(tmpdir(), "simplex-mcp-agents-"))
+ try {
+ const subagents = join(folder, "s1", "subagents")
+ mkdirSync(subagents, {recursive: true})
+ writeFileSync(join(subagents, "agent-a1.meta.json"), JSON.stringify({agentType: "general-purpose", description: "Audit the call stack", toolUseId: "toolu_9"}))
+ writeFileSync(join(subagents, "agent-a2.meta.json"), JSON.stringify({agentType: "reviewer", description: "Review", taskKind: "in_process_teammate"}))
+ const {client, requests} = turnClient()
+ const started = (agent: string) => turn(JSON.stringify({session_id: id, hook_event_name: "SubagentStart", transcript_path: join(folder, "s1.jsonl"), agent_id: agent, agent_type: "Explore"}), {}, client, 0, 1, 1)
+ for (const agent of ["a1", "a2", "a3"]) await started(agent)
+ expect(requests).toEqual([{method: "POST", route: "/turn", body: {id, at: 1, agent: {id: "a1", start: {type: "Explore", description: "Audit the call stack", toolUse: "toolu_9", transcript: join(subagents, "agent-a1.jsonl")}}}}])
+ } finally {
+ rmSync(folder, {recursive: true, force: true})
+ }
+ })
+
+ it("send a subagent's tool uses as its steps, its hand-back as its report and its stop with the first line of its answer, without effort and answer", async () => {
+ const {client, requests} = turnClient()
+ const bash = {command: "npm test", description: "Run the tests"}
+ await turn(toolUse("PreToolUse", "Bash", bash, {agent_id: "a1"}), {}, client, 0, 1)
+ await turn(toolUse("PostToolUse", "Bash", bash, {agent_id: "a1"}), {}, client, 0, 1)
+ await turn(toolUse("PreToolUse", "SubagentHandback", {message: "Found 6 callers.\nDetails."}, {agent_id: "a1"}), {}, client, 0, 1)
+ await turn(JSON.stringify({session_id: id, hook_event_name: "SubagentStop", agent_id: "a1", last_assistant_message: "Done.\nMore.", effort: {level: "high"}}), {}, client, 0, 1)
+ expect(requests.map(request => (request as {body: unknown}).body)).toEqual([
+ {id, at: 1, agent: {id: "a1", step: {id: "toolu_Bash", text: "💻 Run the tests"}}},
+ {id, at: 1, agent: {id: "a1", step: {id: "toolu_Bash", text: "💻 Run the tests", end: true}}},
+ {id, at: 1, agent: {id: "a1", report: "Found 6 callers."}},
+ {id, at: 1, agent: {id: "a1", stop: "Done."}},
+ ])
+ })
+
+ it("send the end of an agent from its result or its task notification with the figures, a workflow's run from its result, and no step for either", async () => {
+ const {client, requests} = turnClient()
+ await turn(toolUse("PreToolUse", "Agent", {description: "Review"}), {}, client, 0, 1)
+ await turn(toolUse("PostToolUse", "Agent", {description: "Review"}, {tool_response: {status: "completed", agentId: "a1", totalTokens: 61_500, totalToolUseCount: 22, totalDurationMs: 160_000}}), {}, client, 0, 1)
+ await turn(toolUse("PostToolUse", "Workflow", {}, {tool_response: {status: "async_launched", runId: "wf_1", workflowName: "review", transcriptDir: "/t/wf_1"}}), {}, client, 0, 1)
+ const notification = "\na2\ntoolu_7\ncompleted\nAgent \"Map\" finished\n11248527165352\n"
+ await turn(JSON.stringify({session_id: id, hook_event_name: "UserPromptSubmit", prompt: notification}), {}, client, 0, 1)
+ expect(requests.map(request => (request as {body: {task?: unknown; workflow?: unknown}}).body).map(({task, workflow}) => task ?? workflow)).toEqual([
+ {toolUse: "toolu_Agent", status: "completed", tokens: 61_500, steps: 22, ms: 160_000},
+ {toolUse: "toolu_Workflow", run: "wf_1", name: "review", folder: "/t/wf_1"},
+ {toolUse: "toolu_7", status: "completed", tokens: 112_485, steps: 27, ms: 165_352},
+ ])
})
it("cut a prompt or an answer over 250,000 characters, so that the request fits the socket's 1 MiB", async () => {
diff --git a/packages/simplex-chat-mcp/test/unit/plugin.test.ts b/packages/simplex-chat-mcp/test/unit/plugin.test.ts
index fc2610dd0c..b35f21b002 100644
--- a/packages/simplex-chat-mcp/test/unit/plugin.test.ts
+++ b/packages/simplex-chat-mcp/test/unit/plugin.test.ts
@@ -43,7 +43,7 @@ describe("plugin", () => {
expect(hooks.SessionStart[0].hooks[0]).toEqual({type: "command", command: cli("hook session-start"), timeout: 600})
expect(hooks.PreToolUse[0].matcher).toBe("mcp__plugin_simplex_simplex__.*")
expect(hooks.PreToolUse[0].hooks[0]).toEqual({type: "command", command: 'node "${CLAUDE_PLUGIN_ROOT}/plugin/allow.js"'})
- for (const event of ["UserPromptSubmit", "Stop", "PostModelSwitch", "PostCompact"]) expect(hooks[event]).toEqual([{hooks: [{type: "command", command: cli("hook turn"), async: true}]}])
+ for (const event of ["UserPromptSubmit", "Stop", "PostModelSwitch", "PostCompact", "SubagentStart", "SubagentStop"]) expect(hooks[event]).toEqual([{hooks: [{type: "command", command: cli("hook turn"), async: true}]}])
const steps = {matcher: "*", hooks: [{type: "command", command: cli("hook turn"), async: true}]}
expect(hooks.PreToolUse[1]).toEqual({...steps, hooks: [...steps.hooks, {type: "mcp_tool", server: "plugin:simplex:simplex", tool: "pre_tool_use", input: {tool: "${tool_name}"}, timeout: 5}]})
for (const event of ["PostToolUse", "PostToolUseFailure"]) expect(hooks[event]).toEqual([steps])
diff --git a/packages/simplex-chat-mcp/test/unit/service.test.ts b/packages/simplex-chat-mcp/test/unit/service.test.ts
index c211053a3b..e6be355b28 100644
--- a/packages/simplex-chat-mcp/test/unit/service.test.ts
+++ b/packages/simplex-chat-mcp/test/unit/service.test.ts
@@ -230,6 +230,14 @@ describe("service", () => {
expect(agents.map(({record}) => record)).toEqual([undefined, undefined])
})
+ it("passes the global config of a registration and the transcript of a title to the session", async () => {
+ const {d, agents} = deps(root)
+ service = await Service.start(d, readDefaultConfig)
+ await post("/session", {id: id1, project: "/p/app", config: defaultConfig, globalConfig: "/h/.claude.json"})
+ await post("/title", {id: id1, project: "/p/app", transcript: "/c/projects/p/1.jsonl", config: defaultConfig})
+ expect(agents[0]).toMatchObject({globalConfig: "/h/.claude.json", transcript: "/c/projects/p/1.jsonl"})
+ })
+
it("expires due actions at each request that touches sessions", async () => {
const {d, expiryChecks} = deps(root)
service = await Service.start(d, readDefaultConfig)
diff --git a/packages/simplex-chat-mcp/test/unit/session.test.ts b/packages/simplex-chat-mcp/test/unit/session.test.ts
index 1b1d78cb4e..f2c23c7a44 100644
--- a/packages/simplex-chat-mcp/test/unit/session.test.ts
+++ b/packages/simplex-chat-mcp/test/unit/session.test.ts
@@ -95,8 +95,8 @@ function listCall(client: LineClient): Promise {
const listed = {chats: [], actions: []}
const listResult = {content: [{type: "text", text: JSON.stringify(listed)}], structuredContent: listed}
-const registration = (record: string): string => `session ${JSON.stringify({id, pid: process.ppid, project: "/p/app", config: {mainGroup: "Claude Control", approve: "requests", expireHours: 23}, record})}`
-const registered = registration(join(homedir(), ".claude", "sessions", `${process.ppid}.json`))
+const registration = (record: string, globalConfig: string): string => `session ${JSON.stringify({id, pid: process.ppid, project: "/p/app", config: {mainGroup: "Claude Control", approve: "requests", expireHours: 23}, record, globalConfig})}`
+const registered = registration(join(homedir(), ".claude", "sessions", `${process.ppid}.json`), join(homedir(), ".claude.json"))
const stdins: PassThrough[] = []
beforeEach(() => {
@@ -308,11 +308,11 @@ describe("session server", () => {
expect(seen).toEqual([registered, "attach", "call list"])
})
- it.each([["/c/claude", join("/c/claude", "sessions", `${process.ppid}.json`)], ["c/claude", resolve("c/claude", "sessions", `${process.ppid}.json`)]])("registers with the absolute path of Claude Code's record of its parent process, in CLAUDE_CONFIG_DIR %s, or in ~/.claude without it", async (folder, record) => {
+ it.each([["/c/claude", join("/c/claude", "sessions", `${process.ppid}.json`), join("/c/claude", ".claude.json")], ["c/claude", resolve("c/claude", "sessions", `${process.ppid}.json`), resolve("c/claude", ".claude.json")]])("registers with the absolute paths of Claude Code's record of its parent process and of its global config, in CLAUDE_CONFIG_DIR %s, or in ~/.claude and ~ without it", async (folder, record, globalConfig) => {
await fakeService(async res => endWithResult(res, listResult))
await session({CLAUDE_CONFIG_DIR: folder})
await until(() => seen.length === 2)
- expect(seen).toEqual([registration(record), "attach"])
+ expect(seen).toEqual([registration(record, globalConfig), "attach"])
})
it("uses the working folder as the project without CLAUDE_PROJECT_DIR", async () => {
diff --git a/packages/simplex-chat-mcp/test/unit/sessions.test.ts b/packages/simplex-chat-mcp/test/unit/sessions.test.ts
index 61be401878..4be6912c3a 100644
--- a/packages/simplex-chat-mcp/test/unit/sessions.test.ts
+++ b/packages/simplex-chat-mcp/test/unit/sessions.test.ts
@@ -54,6 +54,7 @@ async function hubWith(chat: FakeChat, mainMembers: T.GroupMember[] = [self, ali
chat.members.set(10, mainMembers)
const hub = new (Hub as unknown as HubConstructor)(chat.api(), user, root, 23, main, "SimpleX MCP")
hub.machine = () => undefined
+ hub.profileMs = 0
await hub.main.load()
await hub.main.start()
return hub
@@ -108,7 +109,6 @@ describe("session groups", () => {
groupProfile: {
displayName: "1 · auth",
fullName: "",
- description: "The Claude Code session 1. Members send it prompts; admins and owners also send the group's commands and approve tool use.",
groupPreferences: {history: {enable: "on"}, directMessages: {enable: "off"}, commands: controlCommands},
chatLayout: "terminal",
},
@@ -296,19 +296,19 @@ describe("session groups", () => {
expect(groupInfo.groupProfile).toMatchObject({displayName: "1 · deploy", shortDescr: "claude-opus-5"})
})
- it("keep the profile an owner changed, its preference for files and media and its layout included, at the next update of the model and at a rename, from the group's current profile", async () => {
+ it("keep the profile an owner changed, its preference for files and media and its layout included, but the description, which is the recap, at the next update of the model and at a rename, from the group's current profile", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
const session = await openSession(hub, id1, stored(1, "auth"))
const {groupInfo} = chat.chats.get("#20")!.chatInfo as T.ChatInfo.Group
const files = {enable: T.GroupFeatureEnabled.Off}
const chatLayout = T.ChatLayout.Classic
- groupInfo.groupProfile = {...groupInfo.groupProfile, description: "Release work", groupPreferences: {...groupInfo.groupProfile.groupPreferences, files}, chatLayout}
+ groupInfo.groupProfile = {...groupInfo.groupProfile, fullName: "Release work", description: "Old description", groupPreferences: {...groupInfo.groupProfile.groupPreferences, files}, chatLayout}
await session.turn({id: id1, model: "claude-opus-5"})
await session.rename("deploy")
expect(chat.profiles.filter(({groupId}) => groupId === 20).map(({groupProfile}) => groupProfile)).toEqual([
- expect.objectContaining({shortDescr: "claude-opus-5", description: "Release work", groupPreferences: expect.objectContaining({files}), chatLayout}),
- expect.objectContaining({displayName: "1 · deploy", shortDescr: "claude-opus-5", description: "Release work", groupPreferences: expect.objectContaining({files}), chatLayout}),
+ expect.objectContaining({shortDescr: "claude-opus-5", fullName: "Release work", description: undefined, groupPreferences: expect.objectContaining({files}), chatLayout}),
+ expect.objectContaining({displayName: "1 · deploy", shortDescr: "claude-opus-5", fullName: "Release work", description: undefined, groupPreferences: expect.objectContaining({files}), chatLayout}),
])
})
@@ -2606,47 +2606,72 @@ describe("Main group", () => {
expect(chat.invitations.at(-1)).toEqual({groupId: 21, viaGroupId: 10, groupMemberId: 3, memberRole: T.GroupMemberRole.Owner})
})
- it("posts the list of every session after the greeting, silent, and edits it as Claude Code's records and the cards change: working, waiting for you, waiting for you in Claude Code, idle, working in the background, and the ⚪ line after an exit", async () => {
+ it("posts a silent message of each running session and then the summary, once an owner joined, and edits them as Claude Code's records and the cards change: working, waiting for you, waiting for you in Claude Code, idle, working in the background, and stopped after an exit", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat, [self])
const one = await openSession(hub, id1, stored(1, "one"))
await openSession(hub, id2, stored(2, "two"))
+ one.record = join(root, "claude-1.json")
+ writeFileSync(one.record, JSON.stringify({pid: 100, status: "busy"}))
+ one.onLine = () => undefined
await hub.showSessions()
expect(sentTo(chat, 10)).toEqual([])
const carol = member(5, "Carol", T.GroupMemberRole.Member)
chat.members.set(10, [self, carol])
await hub.main.onEvent({type: "joinedGroupMember", groupInfo: group(10, "SimpleX MCP", self), member: carol} as unknown as ChatEvent)
await hub.showSessions()
- expect(sentTo(chat, 10).slice(-1)).toEqual(["⚪ Not running: 2 · two, 1 · one"])
- expect(sentTo(chat, 10)[0]).toMatch(/^I'm Claude\./)
+ expect(sentTo(chat, 10).slice(-2)).toEqual(["🟢 1 · one: working", "1 session 🟢"])
expect(chat.sent.at(-1)!.messages[0]).toMatchObject({priority: -1})
- const list = chat.nextItemId - 1
- expect(chat.customData.at(-1)).toEqual({chat: "#10", customData: {simplexMcpMain: true, simplexMcpList: {item: list, at: expect.any(Number)}}})
+ const [message, summary] = [chat.nextItemId - 2, chat.nextItemId - 1]
+ expect(chat.customData.at(-1)).toEqual({chat: "#10", customData: {simplexMcpMain: true, simplexMcpBoard: {summary: {item: summary, at: expect.any(Number)}, sessions: [{session: 1, item: message, at: expect.any(Number)}]}}})
await withOwner(chat, one)
- one.record = join(root, "claude-1.json")
- one.onLine = () => undefined
- const shows = async (status: string): Promise => {
+ const shows = async (status: string): Promise => {
writeFileSync(one.record!, JSON.stringify({pid: 100, status}))
const edits = chat.updates.length
await hub.showSessions()
- return chat.updates.length === edits ? undefined : chat.updates.at(-1)!.text
+ return chat.updates.slice(edits).filter(({chatId}) => chatId === 10).map(({itemId, text}) => `${itemId === message ? "message" : itemId === summary ? "summary" : itemId}: ${text}`)
}
- expect(await shows("busy")).toBe("🟢 1 · one: working\n⚪ Not running: 2 · two")
- expect(chat.updates.at(-1)).toMatchObject({chatId: 10, itemId: list})
- expect(await shows("busy")).toBeUndefined()
- expect(await shows("waiting")).toBe("⛔️ 1 · one: waiting for you in Claude Code\n⚪ Not running: 2 · two")
+ expect(await shows("busy")).toEqual([])
+ expect(await shows("waiting")).toEqual(["message: ⛔️ 1 · one: waiting for you in Claude Code", "summary: 1 session ⛔️"])
one.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"})
- expect(await shows("waiting")).toBe("🟠 1 · one: waiting for you, 1 approval\n⚪ Not running: 2 · two")
- expect(await shows("busy")).toBe("🟢 1 · one: working\n⚪ Not running: 2 · two")
- expect(await shows("idle")).toBe("🔴 1 · one: idle\n⚪ Not running: 2 · two")
- expect(await shows("shell")).toBe("⚙️ 1 · one: working in the background\n⚪ Not running: 2 · two")
+ expect(await shows("waiting")).toEqual(["message: 🟠 1 · one: waiting for you, 1 approval", "summary: 1 session 🟠"])
+ expect(await shows("busy")).toEqual([])
one.endPermissions()
+ expect(await shows("busy")).toEqual(["message: 🟢 1 · one: working", "summary: 1 session 🟢"])
+ expect(await shows("idle")).toEqual(["message: 🔴 1 · one: idle", "summary: 1 session 🔴"])
+ expect(await shows("shell")).toEqual(["message: ⚙️ 1 · one: working in the background", "summary: 1 session ⚙️"])
one.onLine = undefined
- expect(await shows("idle")).toBe("⚪ Not running: 2 · two, 1 · one")
- expect(sentTo(chat, 10).filter(text => text.startsWith("⚪"))).toHaveLength(1)
+ expect(await shows("idle")).toEqual(["message: ⚪ 1 · one: stopped", "summary: 1 session ⚪"])
+ expect(sentTo(chat, 10).filter(text => text.includes("1 · one"))).toHaveLength(1)
})
- it("counts a tool-use card only while Claude Code shows its dialog or its state is unknown, every other card, and no card cancelled by a stop, whose list is edited before the wait for the cancelled cards", async () => {
+ it("shows the title, the account, the model, the effort, the goal state and the recap of a session in its message, and the details and the recap in its group's descriptions", async () => {
+ const chat = new FakeChat()
+ const hub = await hubWith(chat)
+ const one = await openSession(hub, id1, {...stored(1, "one"), model: "claude-opus-5", effort: "high"})
+ one.globalConfig = join(root, ".claude.json")
+ writeFileSync(one.globalConfig, JSON.stringify({oauthAccount: {emailAddress: "alice@example.com"}}))
+ one.transcript = join(root, "t.jsonl")
+ const entries = [{type: "ai-title", aiTitle: "Session board"}, {type: "attachment", attachment: {type: "goal_status", met: false, sentinel: true}}, {type: "system", subtype: "away_summary", content: "Built the board. (disable recaps in /config)"}]
+ writeFileSync(one.transcript, entries.map(entry => `${JSON.stringify(entry)}\n`).join(""))
+ one.onLine = () => undefined
+ await hub.showSessions()
+ expect(sentTo(chat, 10).slice(-2)).toEqual(["▶️ 1 · one: running\n*Session board*\nalice@example.com · claude-opus-5 · effort high · goal set\nBuilt the board.", "1 session ▶️"])
+ expect(chat.profiles.filter(({groupId}) => groupId === 20).at(-1)!.groupProfile).toMatchObject({shortDescr: "alice@example.com · claude-opus-5 · effort high · goal set", description: "Built the board."})
+ expect(readSessionFile(sessionFolder(root, id1))).toMatchObject({account: "alice@example.com", goal: "set", recap: "Built the board.", title: "Session board", transcript: one.transcript})
+ })
+
+ it("deletes the message of a stopped session 23 hours after its post, and the message of a session the hub does not have", async () => {
+ const chat = new FakeChat()
+ const old = Date.now() - 23 * 3_600_000
+ const hub = await hubWith(chat, [self, alice], {simplexMcpMain: true, simplexMcpBoard: {summary: {item: 300, at: old}, sessions: [{session: 1, item: 301, at: old}, {session: 9, item: 302, at: Date.now()}]}})
+ await openSession(hub, id1, stored(1, "one"))
+ await hub.showSessions()
+ expect(chat.deletedItems.map(({itemIds}) => itemIds)).toEqual([[301], [302]])
+ expect(chat.updates).toEqual([{chatId: 10, itemId: 300, text: "No sessions."}])
+ })
+
+ it("counts every pending card, a tool-use card also while Claude Code's record says busy, as for a subagent's card without a dialog, and no card cancelled by a stop, whose board is edited before the wait for the cancelled cards", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
const one = await openSession(hub, id1, stored(1, "one"))
@@ -2660,7 +2685,7 @@ describe("Main group", () => {
one.record = join(root, "claude-1.json")
writeFileSync(one.record, JSON.stringify({status: "busy"}))
await hub.showSessions()
- expect(hub.sessionsText()).toBe("🟢 1 · one: working\n🟠 2 · two: waiting for you, 1 approval")
+ expect(hub.sessionsText()).toBe("🟠 1 · one: waiting for you, 1 approval\n🟠 2 · two: waiting for you, 1 approval")
writeFileSync(one.record, JSON.stringify({status: "compacting"}))
await hub.showSessions()
expect(hub.sessionsText()).toBe("🟠 1 · one: waiting for you, 1 approval\n🟠 2 · two: waiting for you, 1 approval")
@@ -2670,7 +2695,7 @@ describe("Main group", () => {
expect(hub.sessionsText()).toBe("🟠 1 · one: waiting for you, 2 approvals\n🟠 2 · two: waiting for you, 1 approval")
let stopped = false
const stopping = hub.stop().then(() => (stopped = true))
- await until(() => chat.updates.filter(({chatId}) => chatId === 10).at(-1)?.text === "⚪ Not running: 2 · two, 1 · one")
+ await until(() => chat.updates.filter(({chatId}) => chatId === 10).at(-1)?.text === "2 sessions ⚪ ⚪")
expect(stopped).toBe(false)
await stopping
expect(hub.sessionsText()).toBe("⚪ Not running: 2 · two, 1 · one")
@@ -2723,37 +2748,21 @@ describe("Main group", () => {
expect(hub.sessionsText()).toBe("🟢 1 · one: working")
})
- it("deletes a new list whose item it could not save and posts it again at the next render, and does not send a text the core refused as too large again until the text changes", async () => {
+ it("deletes the messages of the board it could not save and posts them again at the next render", async () => {
const chat = new FakeChat()
- const errors: string[] = []
- jest.spyOn(process.stderr, "write").mockImplementation(text => (errors.push(String(text)), true))
+ jest.spyOn(process.stderr, "write").mockImplementation(() => true)
const hub = await hubWith(chat)
const one = await openSession(hub, id1, stored(1, "one"))
+ one.onLine = () => undefined
const save = chat.apiSetGroupCustomData
chat.apiSetGroupCustomData = async () => {
throw new Error("database busy")
}
+ const first = chat.nextItemId
await hub.showSessions()
- expect(chat.deletedItems).toEqual([{chatType: T.ChatType.Group, chatId: 10, itemIds: [chat.nextItemId - 1], deleteMode: T.CIDeleteMode.Broadcast}])
- expect(errors.filter(line => line.startsWith("list of sessions: "))).toHaveLength(1)
chat.apiSetGroupCustomData = save
await hub.showSessions()
- expect(sentTo(chat, 10)).toEqual(["⚪ Not running: 1 · one", "⚪ Not running: 1 · one"])
- expect(chat.customData.at(-1)).toEqual({chat: "#10", customData: {simplexMcpMain: true, simplexMcpList: {item: chat.nextItemId - 1, at: expect.any(Number)}}})
- const tooLarge = jest.fn(async () => {
- throw new core.ChatAPIError("Chat command error", {type: "errorStore", storeError: {type: "largeMsg"}} as unknown as T.ChatError)
- })
- chat.apiUpdateChatItem = tooLarge
- one.onLine = () => undefined
- await hub.showSessions()
- await hub.showSessions()
- expect(tooLarge).toHaveBeenCalledTimes(1)
- expect(errors.filter(line => line.startsWith("list of sessions: "))).toHaveLength(2)
- one.onLine = undefined
- await hub.showSessions()
- one.onLine = () => undefined
- await hub.showSessions()
- expect(tooLarge).toHaveBeenCalledTimes(1)
+ expect([chat.deletedItems.flatMap(({itemIds}) => itemIds), sentTo(chat, 10)]).toEqual([[first, first + 1], ["▶️ 1 · one: running", "1 session ▶️", "▶️ 1 · one: running", "1 session ▶️"]])
})
it("fits the list in one message: the ⚪ line keeps the newest names that fit and counts the older ones, only the count when no name fits, and every line of a running session", async () => {
@@ -2781,42 +2790,42 @@ describe("Main group", () => {
expect(tools.fitsMessage({type: "text", text: crowded}, undefined, undefined)).toBe(true)
})
- it("posts a new list and deletes the old one for everyone when the list is 23 hours old or its edit is refused, logs a refused deletion, and edits the list of the Main group's data after a restart", async () => {
+ it("deletes the list of the earlier version for everyone and removes its key with the save of the board", async () => {
const chat = new FakeChat()
- const errors: string[] = []
- jest.spyOn(process.stderr, "write").mockImplementation(text => (errors.push(String(text)), true))
- const old = {item: 300, at: Date.now() - 23 * 3_600_000}
- const hub = await hubWith(chat, [self, alice], {simplexMcpMain: true, simplexMcpList: old})
- await openSession(hub, id1, stored(1, "one"))
+ const hub = await hubWith(chat, [self, alice], {simplexMcpMain: true, simplexMcpList: {item: 300, at: Date.now()}})
await hub.showSessions()
- expect(sentTo(chat, 10)).toEqual(["⚪ Not running: 1 · one"])
- expect(chat.deletedItems).toEqual([{chatType: T.ChatType.Group, chatId: 10, itemIds: [300], deleteMode: T.CIDeleteMode.Broadcast}])
- const posted = chat.nextItemId - 1
- const saved = chat.customData.at(-1)!.customData!
- expect(saved).toEqual({simplexMcpMain: true, simplexMcpList: {item: posted, at: expect.any(Number)}})
- const restarted = await hubWith(chat, [self, alice], saved)
- const one = await openSession(restarted, id1, stored(1, "one"))
+ expect([chat.deletedItems.map(({itemIds}) => itemIds), chat.customData.at(-1)]).toEqual([[[300]], {chat: "#10", customData: {simplexMcpMain: true, simplexMcpBoard: {sessions: []}}}])
+ })
+
+ it("edits once after a restart the messages of the board in the Main group's data", async () => {
+ const chat = new FakeChat()
+ const hub = await hubWith(chat, [self, alice], {simplexMcpMain: true, simplexMcpBoard: {summary: {item: 300, at: Date.now()}, sessions: [{session: 1, item: 301, at: Date.now()}]}})
+ const one = await openSession(hub, id1, stored(1, "one"))
+ one.onLine = () => undefined
+ await hub.showSessions()
+ await hub.showSessions()
+ expect(chat.updates).toEqual([{chatId: 10, itemId: 301, text: "▶️ 1 · one: running"}, {chatId: 10, itemId: 300, text: "1 session ▶️"}])
+ })
+
+ it("posts a message and the summary again and deletes the old ones for everyone when the core refuses their edits", async () => {
+ const chat = new FakeChat()
+ const hub = await hubWith(chat, [self, alice], {simplexMcpMain: true, simplexMcpBoard: {summary: {item: 300, at: Date.now()}, sessions: [{session: 1, item: 301, at: Date.now()}]}})
+ const one = await openSession(hub, id1, stored(1, "one"))
one.onLine = () => undefined
- await restarted.showSessions()
- expect(chat.updates.at(-1)).toEqual({chatId: 10, itemId: posted, text: "▶️ 1 · one: running"})
chat.apiUpdateChatItem = async () => {
throw new core.ChatAPIError("Chat command error", {type: "error", errorType: {type: "invalidChatItemUpdate"}} as unknown as T.ChatError)
}
- chat.apiDeleteChatItems = async () => {
- throw new core.ChatAPIError("Chat command error", {type: "error", errorType: {type: "invalidChatItemDelete"}} as unknown as T.ChatError)
- }
- one.onLine = undefined
- await restarted.showSessions()
- expect(sentTo(chat, 10)).toEqual(["⚪ Not running: 1 · one", "⚪ Not running: 1 · one"])
- expect(errors.some(line => line.startsWith("old list of sessions: "))).toBe(true)
+ await hub.showSessions()
+ expect([chat.deletedItems.map(({itemIds}) => itemIds), sentTo(chat, 10)]).toEqual([[[301], [300]], ["▶️ 1 · one: running", "1 session ▶️"]])
})
- it("posts no list while the Main group has no owner, and a new one in the new Main group after a reset of the owners once an owner joins", async () => {
+ it("posts no board while the Main group has no owner, and a new one in the new Main group after a reset of the owners once an owner joins", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
- await openSession(hub, id1, stored(1, "one"))
+ const one = await openSession(hub, id1, stored(1, "one"))
+ one.onLine = () => undefined
await hub.showSessions()
- expect(sentTo(chat, 10)).toEqual(["⚪ Not running: 1 · one"])
+ expect(sentTo(chat, 10)).toEqual(["▶️ 1 · one: running", "1 session ▶️"])
await hub.resetOwners()
chat.members.set(21, [self])
await hub.showSessions()
@@ -2825,8 +2834,45 @@ describe("Main group", () => {
chat.members.set(21, [self, carol])
await hub.main.onEvent({type: "joinedGroupMember", groupInfo: group(21, "SimpleX MCP", self), member: carol} as unknown as ChatEvent)
await hub.showSessions()
- expect(sentTo(chat, 21).at(-1)).toBe("⚪ Not running: 1 · one")
- expect(chat.customData.at(-1)).toEqual({chat: "#21", customData: {simplexMcpMain: true, simplexMcpList: {item: chat.nextItemId - 1, at: expect.any(Number)}}})
+ expect(sentTo(chat, 21).slice(-2)).toEqual(["▶️ 1 · one: running", "1 session ▶️"])
+ })
+
+ it("posts a silent live message of a subagent at its start, ends it with its result at its stop and with the figures of its task, and drops the note of that task", async () => {
+ const chat = new FakeChat()
+ const hub = await hubWith(chat)
+ const session = await openSession(hub, id1, stored(1, "one"))
+ await session.turn({id: id1, agent: {id: "a1", start: {type: "Explore", description: "find callers", toolUse: "toolu_1", transcript: join(root, "agent-a1.jsonl")}}})
+ expect(chat.sent.at(-1)).toMatchObject({chat: [T.ChatType.Group, 20], live: true, messages: [{msgContent: {text: "🤖 Explore · find callers\n0 steps · 0:00"}, priority: -1}]})
+ await session.turn({id: id1, agent: {id: "a1", stop: "Found 6 callers."}})
+ await session.turn({id: id1, prompt: "…", typed: false, note: "!- ✅ Agent finished!", task: {toolUse: "toolu_1", status: "completed", tokens: 61_500, steps: 22, ms: 160_000}})
+ await until(() => chat.updates.length === 2)
+ expect([chat.updates, sentTo(chat, 20).filter(text => text.includes("finished"))]).toEqual([[{chatId: 20, itemId: chat.nextItemId - 1, text: "🤖 Explore · find callers · ✅ 0:00 · 0 steps\nFound 6 callers."}, {chatId: 20, itemId: chat.nextItemId - 1, text: "🤖 Explore · find callers · ✅ 2:40 · 22 steps · 61.5k tokens\nFound 6 callers."}], []])
+ })
+
+ it("shows the working subagents in the session's board message, and ends their live messages with ⏹️ at the last detach", async () => {
+ const chat = new FakeChat()
+ const hub = await hubWith(chat)
+ const session = await openSession(hub, id1, stored(1, "one"))
+ session.onLine = () => undefined
+ await session.turn({id: id1, agent: {id: "a1", start: {type: "Explore", description: "find callers", transcript: join(root, "agent-a1.jsonl")}}})
+ await hub.showSessions()
+ expect(sentTo(chat, 10).at(-2)).toBe("▶️ 1 · one: running\n🤖 1 agent working")
+ await session.endLive()
+ expect(chat.updates.at(-1)).toMatchObject({chatId: 20, text: "🤖 Explore · find callers · ⏹️ 0:00 · 0 steps"})
+ })
+
+ it("updates the descriptions of a session's group at most once a minute, with the latest values", async () => {
+ const chat = new FakeChat()
+ const hub = await hubWith(chat)
+ hub.profileMs = 200
+ const session = await openSession(hub, id1, stored(1, "one"))
+ await session.turn({id: id1, model: "claude-opus-5"})
+ await session.turn({id: id1, model: "claude-sonnet-5", switched: true})
+ await session.turn({id: id1, model: "claude-haiku-5", switched: true})
+ const described = () => chat.profiles.filter(({groupId}) => groupId === 20).map(({groupProfile}) => groupProfile.shortDescr)
+ expect(described()).toEqual(["claude-opus-5"])
+ await until(() => described().length === 2)
+ expect(described()).toEqual(["claude-opus-5", "claude-haiku-5"])
})
it("replaces the Main group at once also while owners exist, without a post there, and answers /approve reset and /reject reset as unknown commands", async () => {
diff --git a/plans/2026-11-21-mcp-session-board.md b/plans/2026-11-21-mcp-session-board.md
new file mode 100644
index 0000000000..6b535a8f05
--- /dev/null
+++ b/plans/2026-11-21-mcp-session-board.md
@@ -0,0 +1,284 @@
+# SimpleX MCP: the session board in the Main group
+
+Status: renders answered by the user on 2026-11-21 (section 3); implemented on `ep/mcp-session-board`. Code references: master `3682e5459`. Claude Code references: version 2.1.311, its binary `/usr/local/bin/claude`, and the transcripts and config of this machine, read on 2026-11-21. Replaces decisions 15, 16 and 22-24 of [2026-11-13-mcp-session-list.md](2026-11-13-mcp-session-list.md).
+
+## 1. Goal
+
+The maintainer supervises many Claude Code sessions, his own and those of employees, from the Main group. The Main group shows each session's state, but neither the Claude account of a session nor its goal and recap. The user, 2026-11-20:
+
+> each session should be one message with structured information and each change should be an edit to this message, and the last message should be a summary of all sessions (N sessions, 5 running, etc.) as this summary shows up in chat list.
+
+> We don't need to see actual goal, only whether it's set, met or not. Recap as description is better.
+
+> we don't need descriptions if there is no recap I think
+
+Outcome:
+- The Main group has one message per session and a summary of all sessions, each edited at each change.
+- Each session message and each session group's short description show the account, the model, the effort level and the goal state.
+- The session group's description is the latest recap of Claude Code, and empty without one.
+
+## 2. What users see
+
+### 2.1 Main group, "Claude Control"
+
+Four sessions: working, waiting for you, idle and stopped. Each block is one message; the last one is the summary. `*TEXT*` is bold in the apps.
+
+```
+🟢 3 · simplex-chat: working
+*WebRTC device link architecture survey*
+alice@example.com · claude-opus-4-7 · effort high · goal set
+I mapped how to move desktop–mobile linking onto WebRTC through the Haskell core and published the WebRTC world map page. Next I need your answers to the four decisions on the page, starting with scope, before I plan the prototype.
+```
+```
+🟠 4 · mcp-board: waiting for you, 2 approvals
+*Session board in the Main group*
+bob@example.com · claude-sonnet-4-5 · effort medium
+```
+```
+🔴 5 · docs: idle
+*Release notes for 6.5*
+alice@example.com · claude-opus-4-7 · effort high · goal met
+The release notes for 6.5 are written and the pull request is open. Next, you review the wording of the security section.
+```
+```
+⚪ 2 · webrtc: stopped
+*WebRTC call reconnection*
+carol@example.com · claude-opus-4-7 · effort xhigh · goal failed
+```
+```
+4 sessions ⚪ 🟢 🟠 🔴
+```
+
+While no other post follows it, the chat list shows the Main group with the summary as its last message:
+
+```
+Claude Control 16:52
+4 sessions ⚪ 🟢 🟠 🔴
+```
+
+Lines of a session message, in this order:
+```
+line text shown when
+state the line of /sessions today: 🟠 waiting for you, K always; ⚪ N · NAME: stopped for a session
+ approvals; ⛔️ waiting for you in Claude Code; that has a message and neither a card nor
+ 🟢 working; 🔴 idle; ⚙️ working in the background; an attached Claude Code
+ ▶️ running
+title *AI TITLE*, Claude Code's title of the conversation the transcript has one, and it differs from NAME
+details ACCOUNT · MODEL · effort LEVEL · goal STATE any part known; unknown parts left out
+recap the latest recap, without "(disable recaps in /config)" the transcript has one
+```
+
+Summary (Q3): `N sessions` and the state emoji of each session with a message, by session number, separated by spaces; `1 session` for one; `No sessions.` without a message.
+
+Messages and the summary change only by edits, when their text changes (Q5). A new running session's message is posted after the summary, which then is no longer last; a later protocol option that moves an edited message to the bottom will restore that. A message whose edit the core refuses, with `invalidChatItemUpdate` or `chatItemNotFound`, as after the 24-hour edit window, is deleted for everyone and posted again; so is the summary. Session 3 re-posted:
+
+```
+⚪ 2 · webrtc: stopped
+...
+(message deleted) ← the old message of session 3, where the group's full deletion is off
+🟠 4 · mcp-board: waiting for you, 2 approvals
+...
+🔴 5 · docs: idle
+...
+4 sessions ⚪ 🟢 🟠 🔴
+🟢 3 · simplex-chat: working
+*WebRTC device link architecture survey*
+alice@example.com · claude-opus-4-7 · effort high · goal set
+I mapped how to move …
+```
+
+A stopped session's message is deleted for everyone 23 hours after its post, within the 30-hour window of deletion. A stopped session that starts again gets its message edited, or a new one when its message was deleted.
+
+While subagents or workflows work, the message has a line `🤖 2 agents working · 1 stalled 2:10 · ⚙️ review-changes Verify 3/8` after the details, from the work of [2026-11-21-mcp-subagents.md](2026-11-21-mcp-subagents.md), which this pull request includes. The session group's descriptions are updated at most once a minute.
+
+`/sessions` replies as today: one line per running session and the ⚪ line of the others.
+
+### 2.2 Session group "3 · simplex-chat"
+
+Group info in the apps:
+```
+3 · simplex-chat
+alice@example.com · claude-opus-4-7 · effort high · goal set ← short description
+─────────
+I mapped how to move desktop–mobile linking onto WebRTC through the ← description, "read more"
+Haskell core and published the WebRTC world map page. Next I need
+your answers to the four decisions on the page, starting with scope,
+before I plan the prototype.
+```
+
+Before the first recap the description is empty. A new group is created without a description; an existing group's description `The Claude Code session N. …` is removed at its first profile update after the change.
+
+Each change of the short description or the description shows `updated group profile` in the session group, as each model change does today ([Subscriber.hs `xGrpInfo`](../src/Simplex/Chat/Library/Subscriber.hs), `sameGroupProfileInfo` in [Internal.hs](../src/Simplex/Chat/Library/Internal.hs)).
+
+## 3. Questions for the user
+
+Answered by the user on 2026-11-21:
+```
+Q1 the stopped state ⚪ N · NAME: stopped
+Q2 the title line *AI TITLE* when it differs from NAME
+Q3 the summary one state emoji per session, separated by spaces, in session order: "4 sessions 🟠 🟢 ⛔️ ⚙️"
+Q4 the old description removed at the next profile update
+Q5 the summary only edited, at a change; never posted again, except after a refused edit;
+ board messages likewise change only by edits
+Q6 spec pointer comments kept, as the codebase does
+```
+
+## 4. Decisions
+
+Facts:
+1. Claude Code's global config is `${CLAUDE_CONFIG_DIR || homedir}/.claude.json`: `configPath:P(process.env.CLAUDE_CONFIG_DIR||ce(),\`.claude${X2()}.json\`)`, where `X2()` is the OAuth file suffix, empty in production; a non-empty legacy `CONFIG/.config.json` is read first (binary, `F()` and `Rpr()`). Its `oauthAccount.emailAddress` is the account's email; a session with an API key has no `oauthAccount`. On this machine the file has 92 KB and mode 0600, and Claude Code rewrites it during a session.
+2. A goal is recorded as transcript entries `{type: "attachment", attachment: {type: "goal_status", …}}` (binary, `tnr`, `dEt`, `Y3e`, `P_n`, `h4o`):
+ - set, or still active after a check: `met: false`, with `sentinel: true` when set or restated;
+ - met: `met: true` without `sentinel`;
+ - failed: `met: false, failed: true`;
+ - cleared by `/goal clear` (`dEt`), or no longer active at a restatement (`Y3e`): `met: true, sentinel: true`.
+ Claude Code's own active goal is the last such entry when neither `met` nor `failed` (`P_n`).
+3. A recap is a transcript entry `{type: "system", subtype: "away_summary", content}` (binary, `yzs`). Claude Code generates it from the terminal's focus and the transcript, skipped while background work is pending, and appends ` (disable recaps in /config)` to the first recaps of a process (`this.#a>S: POST /session record, globalConfig
+ K->>S: POST /title with transcript
+ CC->>F: status, oauthAccount, goal_status, away_summary, ai-title
+ S->>F: read status; config when changed; transcript appended bytes
+ S->>G: details or recap changed: short description, description
+ alt no message of a running session
+ S->>M: post the session message
+ S->>M: no summary yet: post the summary
+ else text changed
+ S->>M: edit the session message
+ S->>M: edit the summary when its emojis changed
+ else edit refused
+ S->>M: delete the old one; post again unless stopped
+ else stopped, 23 h after the post
+ S->>M: delete the message
+ end
+ S->>M: save simplexMcpBoard
+```
+
+Render:
+```
+showBoard(sessions by number):
+ the group lost: nothing
+ the old list: delete it
+ for each session:
+ entry = board.sessions[session]
+ no entry: running and an owner: post
+ stopped, 23 h old: delete
+ text = shown: keep
+ edit; refused: delete; running: post
+ for each entry of a session the hub does not have: delete
+ summary = "N sessions" + the emojis of the sessions with a message
+ none: a message and an owner: post
+ text ≠ shown: edit; refused: delete, post
+ save board when it changed; failed: delete this render's posts, log
+```
+
+Session state, `Session.readRecord`:
+```
+not attached or hub stopped: status cleared; the rest kept
+record → status as today
+config → account mtime changed: parse; error keeps the last value
+transcript → goal, recap, title appended bytes from offset (decision 11)
+changed → store in session.json; control.describe(details, recap)
+```
+
+Changes:
+```
+file change
+src/protocol.ts SessionRequest + globalConfig?; TitleRequest + transcript?
+src/session.ts startSession: globalConfig
+src/hook.ts sessionStart: transcript
+src/service.ts SessionLike + globalConfig?, transcript?; onSession, applyTitle set them
+src/claude-code.ts new: AccountReader, TranscriptReader (goal, recap, title)
+src/files.ts SessionFile + account, goal, recap, title, transcript
+src/hub.ts Session.readRecord with readStatus and readClaudeCode, state, details, describe,
+ boardSession; Hub.showSessions: main.showBoard; the session group without description
+src/main-group.ts showBoard replaces showList; summaryText; simplexMcpBoard; the old list deleted
+src/control.ts describe(shortDescr, description)
+```
+
+## 6. Compatibility
+
+- Older session servers send no `globalConfig`: the account is unknown until Claude Code restarts.
+- Sessions started before the update send no `transcript`: goal, recap and title stay unknown until their next SessionStart.
+- Older Claude Code without goals or recaps: those parts are left out.
+- Older data folders: the old list is deleted; the board is posted at the first render with an owner.
+
+## 7. Acceptance and tests
+
+```
+# criterion checked by
+1 the account follows the global config, also after a write; a partial unit: claude-code
+ write keeps the last value
+2 goal state from the last goal entry: set, met, failed, none after clear unit: claude-code
+3 recap without the suffix; only appended bytes are read; a new path clears unit: claude-code
+4 session server sends globalConfig with and without CLAUDE_CONFIG_DIR; unit: session, hook, service
+ SessionStart sends transcript; the service passes both to the session
+5 short description and description follow details and recap unit: sessions
+6 one message per running session and the summary; edits on change unit: sessions; e2e
+7 re-post after a refused edit; a stopped session's message deleted at 23 h unit: sessions
+8 the old list deleted; the board saved in the Main group's data unit: sessions
+```
+
+## 8. Docs to change
+
+- README.md: step 3, the board.
+- REFERENCE.md, "The Main group": the board, its lines and summary; the session group's descriptions.
+- spec/api.md 4.2, 4.3, 4.6; spec/architecture.md: `readState`, `showBoard`, `claude-code.ts`; spec/flows.md: the board flow.
diff --git a/plans/2026-11-21-mcp-subagents.md b/plans/2026-11-21-mcp-subagents.md
new file mode 100644
index 0000000000..a3760fc334
--- /dev/null
+++ b/plans/2026-11-21-mcp-subagents.md
@@ -0,0 +1,423 @@
+# SimpleX MCP: subagents and workflows live in the session group
+
+Status: renders approved by the user on 2026-11-21; implemented in #8294 on `ep/mcp-session-board`, with the user's answers:
+```
+Q1 A: no step lines of the lead's Agent and Workflow
+Q2 A: 2 min between tool calls, 10 min while one runs
+Q3 none: the short description shows no agent counts; agents show in their live messages and in the
+ agents line of the session's message in the Main group
+Q4 the bottom area is tracked: live agent and workflow messages keep their order and are moved down
+ only when another message follows them, with to_bottom once the core has it; until then edits
+ keep messages in place, and the tracking lands with the core option
+Q5 A
+Q6 A: the note of a task with a live message is not posted
+Q7 A: a resumed agent gets a new message
+```
+Differences from the decisions below: `start` sends the agent's `transcript` path, not its folder; a message 23 hours old ends with ⏹️; session-group profile updates wait at least one minute after the last one that changed the profile. Code references: master `20ee7cb14`, `packages/simplex-chat-mcp`. Claude Code references: version 2.1.311, its binary `/usr/local/bin/claude` at the byte offsets given, the hooks reference `https://code.claude.com/docs/en/hooks.md` (read 2026-11-21, cited by line of that file), and the transcripts of this machine.
+
+## 1. Goal
+
+The user, 2026-11-21:
+
+> I don't see subagents in the chat and what they are doing. I can only see it in terminal
+
+> I am more interested in subagents progress on tasks that I can see in terminal, and I can also see them stalling, but I don't see it in the chat.
+
+Outcome:
+- Each subagent of a session has one message in the session's group, edited as it works, and final when it ends.
+- Each workflow has one message with its phases, edited as its agents work.
+- The session group's short description and the session's message in the Main group show the counts while agents work.
+
+## 2. What users see
+
+Approved renders (2026-11-21).
+
+Subagent, working:
+```
+🤖 Explore · find the suspend callers
+14 steps · 38.2k tokens · 1:05 · now: 📖 Read SuspendChat.swift
+```
+Stalled:
+```
+🤖 Explore · find the suspend callers
+14 steps · 38.2k tokens · 3:15 · ⚠️ no step for 2:10 · last: 💻 cabal build
+```
+Ended:
+```
+🤖 Explore · find the suspend callers · ✅ 2:40 · 22 steps · 61.5k tokens
+Found 6 callers of suspendChat; the two in AppDelegate run on the main thread.
+```
+`❌` for a failure, `⏹️` for a stop.
+
+Workflow:
+```
+⚙️ review-changes · Review 4/4 ✅ · Verify 3/8 · 2 working · 412k tokens · 6:30
+```
+Ended (Q5 A):
+```
+⚙️ review-changes · ✅ 6:30 · Review 4/4 · Verify 8/8 · 412k tokens
+```
+Its agents get no messages of their own.
+
+Session group, short description while agents work:
+```
+alice@example.com · claude-opus-4-7 · effort high · 2 agents working · 1 stalled
+```
+Main group, the session's message (`ep/mcp-session-board`), a line after the details:
+```
+🤖 2 agents working · 1 stalled 2:10 · ⚙️ review-changes Verify 3/8
+```
+
+Lines:
+```
+part text source
+TYPE agent_type of SubagentStart hook input
+DESCRIPTION description of the agent's record subagents/agent-ID.meta.json
+N steps tool calls of the agent, SubagentHandback left out PreToolUse with agent_id
+X tokens input + cache creation + cache read + output tokens of the the agent's transcript; at the end the
+ agent's latest request, as the terminal task notification or the Agent result
+M:SS time since SubagentStart, in 5 s steps; H:MM:SS from 1 hour the service's clock
+now: STEP the agent's open tool call, as step lines name it PreToolUse without its PostToolUse
+last: STEP the last tool call, when none is open PostToolUse, PostToolUseFailure
+⚠️ no step for M:SS time since the agent's last hook event, past the threshold decision 19
+result line first line of the report or the final answer SubagentHandback, SubagentStop
+PHASE d/t agents of the phase ended / started, ✅ when d = t and a later the workflow's journal.jsonl
+ phase started or the workflow ended
+K working agents started and not ended the workflow's journal.jsonl
+```
+
+## 3. Questions for the user
+
+```
+Q1 the lead's own step lines "🤖 Agent: …" and "🔧 Workflow"
+ A not posted: the agent's or the workflow's message replaces them (recommended: one message per agent)
+ B posted as today, beside the messages
+Q2 the stall threshold
+ A 2 min between tool calls, 10 min while a tool call runs (recommended, decision 19)
+ B 2 min in both cases
+Q3 the short description
+ A while any agent or workflow works, also after the turn, changed at most every 30 s (recommended: background agents outlive the turn; each change adds an "updated group profile" item, fact 13)
+ B only while a turn runs
+Q4 move to the bottom, once the core has it (2026-11-21-update-to-bottom.md)
+ A an edit moves the message when an item other than an agent's or workflow's live message follows it (recommended: live messages stay together at the bottom without swapping)
+ B every edit moves the message
+Q5 a workflow's ended message
+ A ⚙️ review-changes · ✅ 6:30 · Review 4/4 · Verify 8/8 · 412k tokens (recommended: the ended subagent form)
+ B the working form with ✅ appended
+Q6 the note of a task notification for an agent or a workflow that has a message
+ A not posted: the message shows the end (recommended)
+ B posted as today
+Q7 an agent resumed with SendMessage after its end
+ A a new message; the old one stays final (recommended: the old message records the first run)
+ B the old message edited again
+```
+
+## 4. Decisions
+
+Facts:
+1. Plugin hooks run inside subagents: "When a subagent calls a tool, tool events such as `PreToolUse` and `PostToolUse` fire the same configured hooks as in the main conversation, and the input carries the `agent_id` and `agent_type`" (hooks.md:255). `agent_id` is "Present only when the hook fires from within a subagent ... Absent for the main thread" (binary 241050879, the SDK schema of hook inputs).
+2. The plugin drops them: `stepOf` returns undefined when `agent_id` is set (hook.ts:439), and `eventFields` sends nothing without a step (hook.ts:210-211). hooks.json registers neither SubagentStart nor SubagentStop (hooks/hooks.json:2-12).
+3. SubagentStart has `agent_id` and `agent_type` (hooks.md:2669); Claude Code builds it as `{...common, hook_event_name: "SubagentStart", agent_id, agent_type}` (binary 251822050) in the agent runner (binary 256639407), for Agent subagents and for workflow agents, which run in the same runner with `transcriptSubdir: "workflows/RUN"` (binary 262633027). It fires again when a subagent is resumed (hooks.md:2659). For the `web-fetch` subagent only hooks of managed settings run (hooks.md:2665).
+4. SubagentStop has `agent_id`, `agent_type`, `agent_transcript_path` and `last_assistant_message`; "`transcript_path` is the main session's transcript, while `agent_transcript_path` is the subagent's own transcript stored in a nested `subagents/` folder" (hooks.md:2709). It also fires for internal agents such as prompt suggestions (hooks.md:2711). The path is `agent-ID.jsonl` in the agent's subfolder (binary 244546157, `am`).
+5. Each agent has a record `agent-ID.meta.json` beside its transcript, with `agentType`, `description`, `toolUseId` (the lead's Agent call), `spawnDepth`, `requestShape`, and for teammates `name`, `taskKind`, `teamName` (binary 248815448; this machine: `subagents/agent-a056a6621326e5bb4.meta.json`). It is written after SubagentStart starts (binary 256652127, after 256639407). A workflow agent's record is `subagents/workflows/RUN/agent-ID.meta.json` with `agentType: "workflow-subagent"`, `description` (the label) and `workflowPhase`; 474 of 474 records of this machine.
+6. The terminal shows a running agent's tokens as input + cache creation + cache read + output of the latest request (`_S` and `vF`, binary 273458000-273460500; `bM` and `F2t`, binary 244394184), and its end as `Done (N tool uses · X tokens · DURATION)` (binary 273463295).
+7. An agent's transcript gives the same figures: for agent `abb7c6a9b3a0ae44c` of `-code-web/c4d3c64b…`, the last assistant `usage` sums to 112,485 and its tool calls without SubagentHandback count 27; its task notification has `11248527165352`.
+8. "The transcript file is written asynchronously and may lag the in-memory conversation" (hooks.md:757).
+9. The Agent tool's PostToolUse `tool_response`: foreground `status: "completed"` with `agentId`, `totalTokens`, `totalToolUseCount`, `totalDurationMs`; background `status: "async_launched"` with `agentId` (hooks.md:1968-1984). On this machine all 201 Agent results of the `-code-web` transcripts are `async_launched`.
+10. A background agent's end reaches the lead as a task notification `AGENT_ID…completed……`, once per stop (`-code-web/c4d3c64b…`). The plugin turns it into a note today (`taskNote`, hook.ts:403-411).
+11. The Workflow tool returns at once: `toolUseResult` `{status: "async_launched", taskId, taskType: "local_workflow", workflowName, runId, summary, transcriptDir, scriptPath}` (this machine, `toolu_01DBsaNfemr86Aobbsy1aqrT`). Its end is a task notification with `` of the Workflow call, `` and `Dynamic workflow "…" completed` (binary 258848776, `DTr`; this machine, task `w3tnei5uf`).
+12. A workflow's `TRANSCRIPT_DIR/journal.jsonl` has the lines `{"type":"launched"}`, `{"type":"started", key, agentId, label, phase}`, `{"type":"result", key, agentId, result}` and `{"type":"failed", key, agentId}`; 966 lines of 63 runs on this machine. `started` is appended when the agent's ID is known, without waiting (binary 262616562); an agent replayed from the cache of a resumed run gets no `started` line (the same place, `cached: !0`).
+13. The terminal groups a workflow's agents by phase from the agents present, so a phase without a started agent is not shown (binary 274204400, `ae`).
+14. A change of a group's short description creates an `updated group profile` item for every member (`sameGroupProfileInfo`, Internal.hs:3391-3392; Commands.hs:4268, Subscriber.hs:3873).
+15. Gaps between consecutive tool events in 873 subagent transcripts of this machine: from a tool result to the next tool call (the model's turn) p50 3.3 s, p99 91.4 s, 1,346 of 185,195 over 120 s; from a tool call to its result p99 106 s, p99.9 600.4 s, 166 of 136,227 over 600 s. Bash's maximum timeout is 600,000 ms (the Bash tool's description).
+16. A core of an earlier release refuses an unknown command parameter as `commandError` (`execChatCommand`, Commands.hs:436-437; `chatCmdError`, Controller.hs:1790-1791). The update option is `/_update item … to_bottom=on` (2026-11-21-update-to-bottom.md, section 4).
+17. hook.ts sends `effort` and `answer` from every event it forwards (hook.ts:181); a subagent's PreToolUse has `effort` with the subagent's level (hooks.md:761) and its SubagentStop has `last_assistant_message`.
+
+Choices:
+18. Hooks: SubagentStart and SubagentStop run `hook turn`, async. For an event with `agent_id`, `turn` sends neither `answer` nor `effort` (fact 17).
+19. Stall: an agent is stalled when its last hook event is older than 2 min while no tool call of it is open, or 10 min while one is open (Q2 A). 2 min is above the 99th percentile of the model's turns (91 s); 10 min is Bash's maximum timeout, and 0.12 % of tool runs exceed it (fact 15).
+20. The hook makes one `agent` event per subagent hook:
+ - SubagentStart: reads the record of fact 5 at `FOLDER/subagents/agent-ID.meta.json`, `FOLDER` the hook's `transcript_path` without `.jsonl`, every 100 ms for up to 2 s; sends `start` with `type`, `description`, `toolUse` and `folder`. A record found under `FOLDER/subagents/workflows/*/`, a record with `taskKind`, and no record within 2 s send nothing.
+ - PreToolUse, PostToolUse, PostToolUseFailure with `agent_id`: `step` with the tool use's ID, its text as `stepText` makes it, without the small-print markup, and `end`. SubagentHandback sends `report`, the first line of `tool_input.message`, and no step.
+ - SubagentStop: `stop` with the first line of `last_assistant_message`.
+21. The hook makes one `task` event of the lead's results:
+ - PostToolUse of Agent with `status: "completed"`: `{toolUse, status: "completed", tokens, steps, ms}` from `totalTokens`, `totalToolUseCount`, `totalDurationMs` (fact 9).
+ - PostToolUseFailure of Agent: `{toolUse, status}`, `killed` with `is_interrupt`, else `failed`.
+ - A task notification: `{toolUse, status, tokens, steps, ms}` from ``, `` and ``; the note is sent as today.
+22. The hook sends `workflow` `{toolUse, run, name, folder}` at the lead's PostToolUse of Workflow from `tool_use_id`, `runId`, `workflowName` and `transcriptDir` (fact 11).
+23. The lead's step lines of Agent and Workflow are not sent (Q1 A).
+24. Service, subagent: `start` posts the live message and records the agent by ID; `step`, `report` and `stop` of an unknown ID are dropped, which leaves out workflow agents, teammates and internal agents. A `task` whose `toolUse` is a recorded agent's or workflow's ends it and its note is dropped (Q6 A).
+25. Ends: `stop` ends the agent with ✅ and its result line, the report first; a later `task` of the same agent sets the status and the exact figures and edits the message once more. A `start` of an ended ID posts a new message (Q7 A). The hub's stop and the session's last detach end live agents with ⏹️.
+26. Tokens: every 2 s, at the hub's board tick (`Hub.showSessions`, hub.ts:1103), the service reads the last 256 KiB of each working agent's transcript, `FOLDER/subagents/agent-ID.jsonl`, and takes the last `assistant` entry with `message.usage` and a model other than ``; a read without one keeps the last value (fact 8).
+27. Workflow: `workflow` posts its live message. Every 2 s the service reads the journal's appended bytes, from the end of the last complete line read, and keeps per `key` the last of `started`, `result`, `failed`, with its `agentId` and `phase`. Phases are ordered by their first `started`; an agent without a phase is counted under its name-less phase, shown as `d/t`. Tokens are the sum of the last usage of its agents' transcripts, `TRANSCRIPT_DIR/agent-ID.jsonl`, read for agents that are working, and once when they end. The workflow ends at the `task` of its Workflow call.
+28. Text and edits: each live message is posted with priority -1 and `live`, as step lines are (`Session.step`, hub.ts:592-611). It is edited when its text changes, at most every 5 s; elapsed times are shown in 5 s steps, so an idle agent's message changes at most every 5 s. The end edit is sent at once with `live` off.
+29. Move: when the core accepts `to_bottom=on`, an edit moves the message when an item other than a live agent or workflow message follows it in the group (Q4 A). The first `commandError` to such an edit marks the core without the option for the hub's lifetime, and the edit is sent again without it (fact 16).
+30. Counts: `N agents working` counts working subagents and the working agents of workflows; `K stalled` counts stalled subagents. The short description appends ` · N agents working · K stalled`, zero parts left out, while any agent or workflow works, changed at most every 30 s (Q3 A). The Main group line, in `boardSession` of `ep/mcp-session-board`: `🤖 N agents working · K stalled M:SS · ⚙️ NAME PHASE d/t`, M:SS of the longest stall, one `⚙️` part per working workflow with its current phase.
+31. Expiry: a live message older than 23 hours is finalized as it stands, as step lines are (`liveLineMs`, `expireLive`, hub.ts:51, :882).
+32. The protocol version stays 1: `agent`, `task` and `workflow` are optional fields of `POST /turn`.
+
+## 5. Design
+
+Where the subagent's state is kept:
+```
+option cost
+S. the service, from hook events (chosen) one optional field per hook request; tokens from a 256 KiB tail every 2 s per working agent
+T. the service, from transcripts only a read of every agent transcript every 2 s; no steps of an agent that has not written yet;
+ the open tool call and the stall time need the hooks anyway
+H. the hook computes the message text each hook process reads the transcript and the record; concurrent hooks race on one message
+```
+
+Where a workflow's progress is read:
+```
+option cost
+J. journal.jsonl, appended bytes (chosen) one read of new bytes every 2 s per working workflow
+A. workflow agents' hook events phase and label only in the record; ends of cached agents missing; one record read per agent
+```
+
+Event flow:
+```mermaid
+sequenceDiagram
+ participant L as lead
+ participant A as subagent
+ participant K as hook turn
+ participant F as session folder
+ participant S as service
+ participant G as session group
+ participant M as Main group
+ L->>K: PreToolUse Agent (no step line, Q1 A)
+ A->>K: SubagentStart agent_id, agent_type
+ K->>F: read subagents/agent-ID.meta.json
+ K->>S: POST /turn agent.start {type, description, toolUse, folder}
+ S->>G: post live 🤖 TYPE · DESCRIPTION
+ loop each tool call of A
+ A->>K: PreToolUse / PostToolUse with agent_id
+ K->>S: POST /turn agent.step
+ S->>S: steps, now, last event time
+ end
+ loop every 2 s
+ S->>F: tail of agent-ID.jsonl: tokens
+ S->>G: edit when the text changed, at most every 5 s
+ S->>M: session message line; short description at most every 30 s
+ end
+ A->>K: SubagentStop last_assistant_message
+ K->>S: POST /turn agent.stop
+ S->>G: edit final, live off: ✅ M:SS · N steps · X tokens + result line
+ L->>K: task notification or Agent PostToolUse
+ K->>S: POST /turn task {toolUse, status, tokens, steps, ms}
+ S->>G: edit final with the exact figures, status ❌ or ⏹️ when so
+```
+
+Workflow flow:
+```mermaid
+sequenceDiagram
+ participant L as lead
+ participant K as hook turn
+ participant J as journal.jsonl
+ participant S as service
+ participant G as session group
+ L->>K: PostToolUse Workflow {runId, workflowName, transcriptDir}
+ K->>S: POST /turn workflow
+ S->>G: post live ⚙️ NAME
+ loop every 2 s
+ S->>J: appended lines: started, result, failed
+ S->>G: edit phases, working, tokens, time
+ end
+ L->>K: task notification of the Workflow call
+ K->>S: POST /turn task
+ S->>G: edit final, live off
+```
+
+Subagent message states:
+```mermaid
+stateDiagram-v2
+ [*] --> working: agent.start
+ working --> working: agent.step, tokens, 5 s tick
+ working --> stalled: no event 2 min, no open call; 10 min with an open call
+ stalled --> working: agent.step
+ working --> ended: agent.stop ✅, task ✅ ❌ ⏹️
+ stalled --> ended: agent.stop, task
+ working --> ended: hub stop, last detach ⏹️; 23 h
+ stalled --> ended: hub stop, last detach ⏹️; 23 h
+ ended --> ended: task: status and exact figures
+ ended --> [*]
+```
+
+```
+state text live
+working 🤖 TYPE · DESCRIPTION / N steps · X tokens · M:SS · now: STEP on
+stalled 🤖 TYPE · DESCRIPTION / N steps · X tokens · M:SS · ⚠️ no step for M:SS · last: STEP on
+ended 🤖 TYPE · DESCRIPTION · ✅ M:SS · N steps · X tokens / RESULT off
+```
+
+Workflow message states:
+```mermaid
+stateDiagram-v2
+ [*] --> working: workflow
+ working --> working: journal lines, tokens, 5 s tick
+ working --> ended: task of the Workflow call ✅ ❌ ⏹️
+ working --> ended: hub stop, last detach ⏹️; 23 h
+ ended --> [*]
+```
+
+Service tick, `Session.readAgents`, called from `Session.readRecord`:
+```
+for each working agent: tokens = lastUsage(tail of agent transcript) ?? tokens
+for each working workflow: journal += appended lines; tokens of its working agents
+for each live message: text = render(state, now); changed and 5 s since the last edit: edit
+counts changed, 30 s since: control.describe(details + counts)
+```
+
+Composition:
+```mermaid
+flowchart LR
+ HJ[hooks/hooks.json
+ SubagentStart, SubagentStop] --> HK[hook.ts turn
agentEvent, taskEvent, workflowEvent]
+ HK -->|POST /turn agent, task, workflow| SV[service.ts]
+ SV --> SE[hub.ts Session.turn → Session.agent]
+ SE --> AG[agents.ts Agents
state, render, stall]
+ SE --> CC[claude-code.ts
AgentUsage, WorkflowJournal]
+ SE --> UI[hub.ts post, updateItem
+ toBottom]
+ SE --> MG[boardSession line
ep/mcp-session-board]
+ SE --> CT[control.describe]
+```
+
+Changes:
+```
+file function or type change
+hooks/hooks.json SubagentStart, SubagentStop + command hook "hook turn", async
+src/hook.ts TurnInput + agent_type, agent_transcript_path, tool_response
+ eventFields agent_id: agentEvent; Agent and Workflow of the lead: taskEvent, workflowEvent;
+ SubagentStart, SubagentStop
+ turn no answer and effort with agent_id
+ agentEvent new: decision 20, the record read of fact 5
+ taskEvent new: decision 21; taskNote unchanged
+ stepOf Agent and Workflow of the lead: no step (Q1 A)
+src/protocol.ts TurnRequest + agent?: AgentEvent, task?: TaskEnd, workflow?: WorkflowRun
+ AgentEvent new: {id} and one of start {type, description, toolUse?, folder},
+ step {id, text, end?}, report, stop
+ TaskEnd, WorkflowRun new
+src/agents.ts Agents new: the session's agents and workflows, their states, texts, counts, stall
+src/claude-code.ts AgentUsage, WorkflowJournal new: last usage of a transcript tail; appended journal lines
+src/hub.ts Session.turn agent, task, workflow to Session.agent
+ Session.readRecord + readAgents
+ Session.updateItem + toBottom, with the fallback of decision 29
+ Session.endLive + end of live agents
+ boardSession, details + the counts of decision 30
+src/messages.ts clock new: M:SS and H:MM:SS
+```
+
+Types:
+```
+AgentEvent
+ id string agent_id
+ start? {type, description, toolUse?, folder}
+ step? {id, text, end?}
+ report? string
+ stop? string
+TaskEnd
+ toolUse string
+ status "completed" | "failed" | "killed" | "stopped"
+ tokens? number
+ steps? number
+ ms? number
+WorkflowRun
+ toolUse string
+ run string
+ name string
+ folder string
+```
+`AgentEvent` carries exactly one of `start`, `step`, `report`, `stop`; the hook builds one per input.
+
+```
+Agent (agents.ts)
+ id, type, description, toolUse?, folder
+ startedAt, lastEventAt
+ steps number
+ open Map
+ last? string
+ tokens? number
+ result? string
+ end? {status, at, tokens?, steps?, ms?}
+ item Promise
+ sent string
+ sentAt number
+Workflow (agents.ts)
+ toolUse, run, name, folder, startedAt
+ journal Map
+ phases string[] order of first started
+ tokens Map
+ end? {status, at}
+ item, sent, sentAt
+```
+
+## 6. Overlaps
+
+```
+branch shared code how conflicts are avoided
+ep/mcp-session-board Session.readRecord, boardSession, details, this work stacks on it: the agents line is one more entry of
+(in progress) describe; Session.transcript; claude-code.ts boardSession's lines; the counts append to details() for the
+ short description only; readAgents runs inside readRecord;
+ AgentUsage and WorkflowJournal join claude-code.ts. The branch
+ states the agents line is left to this work.
+ep/mcp-unblock (plan) hooks/hooks.json; TurnInput; TurnRequest; new hook lines and fields only, each on its own line; agent
+ Session.turn; cards with agent_id cards (its decision 34) stay cards; a subagent waiting on a
+ card shows as stalled with "last: STEP" until the decision
+ep/mcp-teammate-profiles hooks/hooks.json SubagentStop; stepOf with teammates (record with taskKind, or name once #8209 lands) are
+#8209, ep/mcp-teammate-steps agent_id; TurnInput agent_type, theirs: decision 20 sends no start for them, so their steps stay
+(open) agent_transcript_path, tool_response; with teammates.step; one SubagentStop line in hooks.json; one
+ no answer and effort for agent_id agent_id guard in turn; whichever lands second merges these lines
+ep/update-to-bottom (plan) Session.updateItem used behind decision 29 once the simplex-chat package has it
+```
+
+Merge order recommended: `ep/mcp-session-board`, then this work rebased onto master with `git rebase --onto`.
+
+## 7. What the renders cannot show
+
+```
+case why
+the web-fetch subagent its SubagentStart and SubagentStop run only from managed settings (fact 3)
+named teammates shown by their own profiles (#8209)
+internal agents: prompt suggestions, /btw no record; SubagentStop only (fact 4)
+"now:" while the model writes no hook event between tool calls; the line shows "last: STEP"
+tokens a few seconds late the transcript lags the conversation (fact 8); the end shows the exact figures
+workflow agents replayed from the cache no started line in a resumed run (fact 12); their phase counts start at the live agents
+workflow tokens the sum of each agent's latest request; the terminal's workflow figure is summed from its
+ own progress events and can differ
+a message's place without to_bottom an edit keeps the message where it was posted; later messages push it up
+the short description at each change each change adds an "updated group profile" item (fact 14); hence 30 s
+agents across a service restart the state is in memory; their messages stay at their last edit
+```
+
+## 8. Acceptance and tests
+
+```
+# criterion checked by
+1 SubagentStart with a record sends start; a workflow agent, a teammate and unit: hook
+ no record send nothing
+2 a subagent's tool hooks send agent steps without effort and answer; unit: hook
+ SubagentHandback sends report; SubagentStop sends stop
+3 Agent results and task notifications send task with the figures; the unit: hook
+ note stays; Workflow's result sends workflow; no step lines of Agent, Workflow
+4 last usage of a transcript tail; synthetic entries and a partial last line unit: claude-code
+ skipped
+5 journal: phases in order, retries by key, appended bytes only unit: claude-code
+6 texts of working, stalled at 2 and 10 min, ended; workflow text; 38.2k, 412k; unit: agents
+ 1:05 and 1:00:05
+7 one live message per agent: posted at start, edited at most every 5 s, unit: sessions
+ final at stop, figures at task, ⏹️ at endLive; note of its task dropped
+8 to_bottom sent when another item follows; commandError falls back to edits unit: sessions
+9 short description and the board line follow the counts, at most every 30 s unit: sessions
+10 a real session: a background Explore agent, a foreground agent, a two-phase TESTING
+ workflow; their messages against the terminal; the inputs of facts 3, 4, 9
+ and 11 recorded as fixtures
+```
+
+Unit tests use recorded inputs: the hook inputs recorded in check 10, the journal and transcript lines of facts 7 and 12, and core responses of the existing `test/unit/fixtures.ts`.
+
+## 9. Docs to change
+
+- README.md: the session group shows subagents and workflows.
+- REFERENCE.md, "The session group": the messages, their states, the stall thresholds; the short description; the Main group line.
+- spec/api.md: `POST /turn` `agent`, `task`, `workflow`; the hooks; the texts.
+- spec/architecture.md: `agentEvent`, `taskEvent`, `Agents`, `AgentUsage`, `WorkflowJournal`, `Session.readAgents`, `updateItem` with `toBottom`.
+- spec/flows.md: the subagent flow and the workflow flow of section 5.
+- TESTING.md: check 10.