From 953389322f4819c8dacb648691fd7d27eec31f45 Mon Sep 17 00:00:00 2001
From: "Evgeny @ SimpleX Chat"
<259188159+evgeny-simplex@users.noreply.github.com>
Date: Fri, 13 Nov 2026 23:40:02 +0000
Subject: [PATCH] mcp: a list of every session and its state in the Main group
(#8182)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* plan: mcp-activity
* plan: mcp-activity list format
* plan: mcp-activity answers and live step lines
* mcp: a silent line per step of Claude's work, completed at its end
* plan: mcp-activity as implemented
* mcp: finalize step lines within a day and load only the hook's modules
* plan: mcp-activity review decisions as implemented
* plan: mcp-session-list
* plan: mcp-session-list, every session in one message (Q2 B)
* mcp: end live step lines by the wall clock
* mcp: exact spec ranges and measured hook load time
* mcp: a list of every session and its state in the Main group
* plan: mcp-session-list as implemented
* mcp: list of sessions: unknown states count cards, bounded record reads, stop edit before the card wait
* plan: mcp-session-list merged with master
* mcp: ROADMAP marks the items delivered since 0.3.0 with ✅
---
packages/simplex-chat-mcp/README.md | 2 +-
packages/simplex-chat-mcp/REFERENCE.md | 25 +-
packages/simplex-chat-mcp/ROADMAP.md | 6 +-
packages/simplex-chat-mcp/TESTING.md | 6 +-
packages/simplex-chat-mcp/spec/README.md | 4 +-
packages/simplex-chat-mcp/spec/api.md | 27 +-
.../simplex-chat-mcp/spec/architecture.md | 20 +-
packages/simplex-chat-mcp/spec/flows.md | 54 ++-
packages/simplex-chat-mcp/src/hub.ts | 119 ++++-
packages/simplex-chat-mcp/src/main-group.ts | 108 ++++-
packages/simplex-chat-mcp/src/protocol.ts | 1 +
packages/simplex-chat-mcp/src/service.ts | 2 +
packages/simplex-chat-mcp/src/session.ts | 4 +-
.../simplex-chat-mcp/test/e2e/service.test.ts | 50 +-
.../simplex-chat-mcp/test/unit/fixtures.ts | 6 +
.../test/unit/service.test.ts | 7 +-
.../test/unit/session.test.ts | 14 +-
.../test/unit/sessions.test.ts | 231 ++++++++-
plans/2026-11-13-mcp-session-list.md | 437 ++++++++++++++++++
19 files changed, 1077 insertions(+), 46 deletions(-)
create mode 100644 plans/2026-11-13-mcp-session-list.md
diff --git a/packages/simplex-chat-mcp/README.md b/packages/simplex-chat-mcp/README.md
index 1e6accb543..753033a827 100644
--- a/packages/simplex-chat-mcp/README.md
+++ b/packages/simplex-chat-mcp/README.md
@@ -33,7 +33,7 @@ You need Node.js 22 or later, Claude Code, and the [SimpleX Chat app](https://si
On several machines or containers, set `SIMPLEX_MCP_MACHINE` on each, for example `SIMPLEX_MCP_MACHINE=laptop`, to name its group "Claude Control - laptop".
-3. Each Claude Code session gets its own group, such as "1 · my-project". Join it from the invitation in "Claude Control".
+3. Each Claude Code session gets its own group, such as "1 · my-project". Join it from the invitation in "Claude Control". A list there shows every session and its state: working, waiting for you or idle.
4. Send prompts in the session's group, and Claude answers there. Reply to a message to show Claude which one you mean. Claude also gets your reactions, as emoji replies. Prompts you type in the terminal appear there too, and Claude Code's own prompts, such as a finished background task, appear as one line each. Each step of Claude's work, such as running the tests, appears as one line, completed with its outcome when the step ends. A line also shows when Claude Code summarises the session's context. Before Claude acts in other chats or uses a tool such as Bash, it asks in the group, and one tap approves. Another tap approves the tool for the rest of the session.
diff --git a/packages/simplex-chat-mcp/REFERENCE.md b/packages/simplex-chat-mcp/REFERENCE.md
index 9bf5530900..460d7b8940 100644
--- a/packages/simplex-chat-mcp/REFERENCE.md
+++ b/packages/simplex-chat-mcp/REFERENCE.md
@@ -569,10 +569,33 @@ 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` lists the sessions and marks the closed ones with `, closed`. `/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 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.
- 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:
+
+```
+🟠 3 · simplex-chat: working
+🔵 6 · website: waiting for you, 2 approvals
+🔵 7 · docs: waiting for you in Claude Code
+🟢 8 · app: idle
+⚪ Not running: 5 · bio, 4 · notes, 2 · openclaw, 1 · first
+```
+
+- 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:
+ - `🔵 N · NAME: waiting for you, K approvals`: K cards wait in the session's group. 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 in Claude Code`: Claude Code waits for an answer in its own window, such as a dialog.
+ - `🟠 N · NAME: working`: Claude Code works on a turn, or a subagent works for it.
+ - `🟢 N · NAME: idle`: Claude Code waits for the next prompt, also while a background command 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.`
+- 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.
+
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:
- The old Main group is deleted for all its members, and a new one is created. The session groups don't change: members who joined them from the old Main group keep their roles.
diff --git a/packages/simplex-chat-mcp/ROADMAP.md b/packages/simplex-chat-mcp/ROADMAP.md
index 5241092251..5a5c92a586 100644
--- a/packages/simplex-chat-mcp/ROADMAP.md
+++ b/packages/simplex-chat-mcp/ROADMAP.md
@@ -15,7 +15,11 @@ What comes next for Claude Code in SimpleX Chat.
## In your sessions
-- One list in the Main group shows every session and its state: working, waiting for you or idle.
+- ✅ Reply to a message, and Claude knows which one you mean.
+- ✅ React to a message, and Claude sees your reaction.
+- ✅ Allow a tool for the rest of a session with one tap.
+- ✅ See when a session's context is summarised.
+- ✅ One list in the Main group shows every session and its state: working, waiting for you or idle.
- See what Claude is doing while it works, with its code changes as diffs.
- The model, effort and usage of each session show in its description, updated as they change.
- Each session is a topic inside one group, not a group of its own.
diff --git a/packages/simplex-chat-mcp/TESTING.md b/packages/simplex-chat-mcp/TESTING.md
index c224aea878..f387d32c8a 100644
--- a/packages/simplex-chat-mcp/TESTING.md
+++ b/packages/simplex-chat-mcp/TESTING.md
@@ -153,7 +153,7 @@ The MCP server and the SessionStart, UserPromptSubmit, Stop, PostModelSwitch, Po
- the hooks;
- the plugin files.
- In these tests, the Stop hook reads the model of its answer from the end of a sparse 3 GiB transcript. It finds the model even when the answer's entry is written after the hook started. The UserPromptSubmit hook marks a prompt as typed only when its record has the origin `human`. Task notifications, messages of other sessions and channel prompts are not marked. A typed prompt is marked also when the transcript is created with its entry 30 reads after the hook started, as after a user's own prompt hook of 3 s. The hook sends the one-line note of each kind of Claude Code's own prompt, a teammate's message included, also when idle notifications precede it in its prompt, and none for a typed or a channel prompt or idle notifications only. A note stays on one line when the sender's name has a line break or a control character. A prompt that reaches a running turn is found by its queued command or its own later entry, and it is marked mid-turn, also when the turn's first entry is out of the tail and only its tool results are in it. Its record is taken by its text, past a meta entry with the same prompt ID; a prompt with the text of the turn's own prompt waits while it is queued. A typed prompt still queued after the reads is typed and mid-turn. The hook sends the note of Claude Code's own prompt also when a later prompt with its text is still queued after the reads, as a repeated monitor event. The hub posts the note as Claude, without a quote. A mid-turn prompt ends no tool-use card and keeps the turn's quote; an owner's prompt added to the turn adds a turn record, and the answer quotes it. A member's emoji reaction reaches the session as the emoji after the quote line of the reacted message, with that message's ID as `item` and `replyTo.item`. A reacted image or video without a caption is quoted with its type and file name, and its file is not received. One of the apps' eight emoji reaches the session. Another reaction, such as U+FE0F alone, `❤️` with U+FE0F, a newer emoji, a text of two lines or another type, reaches no session and gets the reply `This reaction is not supported.` The reply is posted once for each member and reacted message, also when the member removes the reaction and adds it again, and never for a reaction to the reply. The reactions of an observer and of `User`, removed reactions and reactions in the Main group, with one of the eight emoji or another value, reach no session and get no reply. A reaction to a pending tool-use card leaves the card pending. The answer of a reaction's turn quotes the reacted message, Claude's own answer included, and two equal reactions to one message are quoted in their own turns. The tool hooks send a step at the start of each tool use of the main conversation, with its text from the tool's input and paths relative to the session's folder, and at its end with ✅, ❌ or ⏹️ and the duration, or with `(in background)` for a launch in the background; Grep and Glob show the pattern, then the path; a tool use of a subagent or of this plugin, or without its ID or tool, sends nothing. The hub posts the start of a step as a silent live line, updates it at the step's end with live off, also while the start's send is in flight, and posts an end that arrives before its start as a silent line, and nothing for that start. Steps without an end are completed with their own text at an answer, at a prompt that starts a turn, at the last detach and at the hub's stop, not at a prompt added to the running turn, and the hub posts nothing for their later ends. A line still live 23 hours after its start is completed with its text, and the later end is posted as a new silent line. When the wall clock moves 23 hours on while the timers stand still, as in a sleep, the line is completed at the next check of the minute or at its step's end. The hub's stop waits for the updates that the last detach started. A refused step gets one refusal post, `Claude's note was not posted: ...`, as a refused note does; a failed send or update is logged, and nothing more is posted. A note and the parts of an answer but the last are silent, and the last part of an answer is important. `/approve N all` on a tool-use card approves the use and its tool for the rest of the session, replies with `/revoke TOOL`, and sends the approved tools to the session; a later card of that tool says that Claude Code still asks for it and offers no `all`. An approved tool counts only while its approver is an admin or owner, after a role change and after `/observer`, and no more after the approver leaves or is removed. `/revoke TOOL` ends the approval, `/list` shows the approved tools after the chats, and `/approve N all` of another kind of action is refused. The approvals are kept across a detach, and each new attachment gets them. The service keeps them when the session's process registers and attaches again, and ends them when another process registers the session and when the session closes. A process with the PID of an ended process of the session and another start time counts as another process, and so does each registration of a process whose start time is unknown. The start time of a running process reads the same twice and differs from that of a later child; a process that does not run and an ID that is not a positive integer have none. While two processes have the session attached, only the attachments of the process that registered it last get the approved tools, and the others get an empty list. The tool approvals end, and the session gets an empty list, when the session's group is lost: deleted, Claude removed, or Claude no longer its owner, at an event and at a load. The session server answers the PreToolUse hook with `allow` for a tool approved on its current attachment, and with an empty text for other tools, after its attachment ends, and in a run that is not interactive. The PostCompact hook sends the line of a compaction with its trigger and token counts, also when the boundary is written 30 reads after the hook started. It sends nothing for an input with `agent_id`, for a subagent's boundary, for a boundary older than 60 s and for one stamped more than 5 s after the hook started. The SessionStart hook of a compaction sends no model. The records follow sessions recorded with Claude Code 2.1.322 on 2026-11-12. The hooks, the session server and the service are tested with the environments of two `claude -p` runs, recorded with Claude Code 2.1.319 in `test/unit/claude-p-runs.jsonl`. One run has the entrypoint `claude-vscode` of a VS Code session, and the other is a plain `claude -p` run. The session server must answer `server/discover` with `Method not found` and negotiate the revision 2025-11-25. Claude Code 2.1.319 registers no channel for a server in the modern MCP era, 2026-07-28, so this test fails after an SDK upgrade that turns that era on.
+ In these tests, the Stop hook reads the model of its answer from the end of a sparse 3 GiB transcript. It finds the model even when the answer's entry is written after the hook started. The UserPromptSubmit hook marks a prompt as typed only when its record has the origin `human`. Task notifications, messages of other sessions and channel prompts are not marked. A typed prompt is marked also when the transcript is created with its entry 30 reads after the hook started, as after a user's own prompt hook of 3 s. The hook sends the one-line note of each kind of Claude Code's own prompt, a teammate's message included, also when idle notifications precede it in its prompt, and none for a typed or a channel prompt or idle notifications only. A note stays on one line when the sender's name has a line break or a control character. A prompt that reaches a running turn is found by its queued command or its own later entry, and it is marked mid-turn, also when the turn's first entry is out of the tail and only its tool results are in it. Its record is taken by its text, past a meta entry with the same prompt ID; a prompt with the text of the turn's own prompt waits while it is queued. A typed prompt still queued after the reads is typed and mid-turn. The hook sends the note of Claude Code's own prompt also when a later prompt with its text is still queued after the reads, as a repeated monitor event. The hub posts the note as Claude, without a quote. A mid-turn prompt ends no tool-use card and keeps the turn's quote; an owner's prompt added to the turn adds a turn record, and the answer quotes it. A member's emoji reaction reaches the session as the emoji after the quote line of the reacted message, with that message's ID as `item` and `replyTo.item`. A reacted image or video without a caption is quoted with its type and file name, and its file is not received. One of the apps' eight emoji reaches the session. Another reaction, such as U+FE0F alone, `❤️` with U+FE0F, a newer emoji, a text of two lines or another type, reaches no session and gets the reply `This reaction is not supported.` The reply is posted once for each member and reacted message, also when the member removes the reaction and adds it again, and never for a reaction to the reply. The reactions of an observer and of `User`, removed reactions and reactions in the Main group, with one of the eight emoji or another value, reach no session and get no reply. A reaction to a pending tool-use card leaves the card pending. The answer of a reaction's turn quotes the reacted message, Claude's own answer included, and two equal reactions to one message are quoted in their own turns. The tool hooks send a step at the start of each tool use of the main conversation, with its text from the tool's input and paths relative to the session's folder, and at its end with ✅, ❌ or ⏹️ and the duration, or with `(in background)` for a launch in the background; Grep and Glob show the pattern, then the path; a tool use of a subagent or of this plugin, or without its ID or tool, sends nothing. The hub posts the start of a step as a silent live line, updates it at the step's end with live off, also while the start's send is in flight, and posts an end that arrives before its start as a silent line, and nothing for that start. Steps without an end are completed with their own text at an answer, at a prompt that starts a turn, at the last detach and at the hub's stop, not at a prompt added to the running turn, and the hub posts nothing for their later ends. A line still live 23 hours after its start is completed with its text, and the later end is posted as a new silent line. When the wall clock moves 23 hours on while the timers stand still, as in a sleep, the line is completed at the next check of the minute or at its step's end. The hub's stop waits for the updates that the last detach started. A refused step gets one refusal post, `Claude's note was not posted: ...`, as a refused note does; a failed send or update is logged, and nothing more is posted. A note and the parts of an answer but the last are silent, and the last part of an answer is important. `/approve N all` on a tool-use card approves the use and its tool for the rest of the session, replies with `/revoke TOOL`, and sends the approved tools to the session; a later card of that tool says that Claude Code still asks for it and offers no `all`. An approved tool counts only while its approver is an admin or owner, after a role change and after `/observer`, and no more after the approver leaves or is removed. `/revoke TOOL` ends the approval, `/list` shows the approved tools after the chats, and `/approve N all` of another kind of action is refused. The approvals are kept across a detach, and each new attachment gets them. The service keeps them when the session's process registers and attaches again, and ends them when another process registers the session and when the session closes. A process with the PID of an ended process of the session and another start time counts as another process, and so does each registration of a process whose start time is unknown. The start time of a running process reads the same twice and differs from that of a later child; a process that does not run and an ID that is not a positive integer have none. While two processes have the session attached, only the attachments of the process that registered it last get the approved tools, and the others get an empty list. The tool approvals end, and the session gets an empty list, when the session's group is lost: deleted, Claude removed, or Claude no longer its owner, at an event and at a load. The session server answers the PreToolUse hook with `allow` for a tool approved on its current attachment, and with an empty text for other tools, after its attachment ends, and in a run that is not interactive. The PostCompact hook sends the line of a compaction with its trigger and token counts, also when the boundary is written 30 reads after the hook started. It sends nothing for an input with `agent_id`, for a subagent's boundary, for a boundary older than 60 s and for one stamped more than 5 s after the hook started. The SessionStart hook of a compaction sends no model. The list of sessions is posted silent in the Main group after the greeting, only while the group has an owner, and edited only when its text changes: a running session's line follows Claude Code's record, `busy`, `waiting`, `idle` or `shell`, and its cards; a record being written keeps the last state; a missing record or another status shows `running`; a tool-use card counts only while the record says `waiting` or is unknown, also with an unknown status, and a card cancelled by a stop never; the stop's edit comes before the wait for the cancelled cards. A FIFO as the record shows `running`, and a read that stalls keeps the last state, ends the render within a second and is not repeated while it stalls. A new list whose item can't be saved is deleted and posted again at the next render, and a text refused as too large is not sent again until it changes. The other sessions share the last line, newest first; with 400 sessions of 50 four-byte characters, it keeps the names that fit one message and counts the rest, also with the quote of `/sessions`, and at least 62 lines of running sessions fit. A list 23 hours old, or whose edit is refused, is replaced and the old one deleted for everyone; a refused deletion is logged. A new service edits the list kept in the Main group's data, and the new Main group of a reset gets a new list once an owner joins. The session server sends the absolute path of Claude Code's record, from `CLAUDE_CONFIG_DIR`, also a relative one, or `~/.claude`, and the service passes it to the session. The records follow sessions recorded with Claude Code 2.1.322 on 2026-11-12. The hooks, the session server and the service are tested with the environments of two `claude -p` runs, recorded with Claude Code 2.1.319 in `test/unit/claude-p-runs.jsonl`. One run has the entrypoint `claude-vscode` of a VS Code session, and the other is a plain `claude -p` run. The session server must answer `server/discover` with `Method not found` and negotiate the revision 2025-11-25. Claude Code 2.1.319 registers no channel for a server in the modern MCP era, 2026-07-28, so this test fails after an SDK upgrade that turns that era on.
- `npm run test:e2e`, file `test/e2e/launch.test.ts`, installs a copy of the package with `npm ci` and packs it, as `build.yml` publishes it. The test checks these facts:
- The tarball has no lockfile.
- Its top-level entries are the build, `node_modules` and the plugin files.
@@ -162,6 +162,7 @@ The MCP server and the SessionStart, UserPromptSubmit, Stop, PostModelSwitch, Po
- Installed into a project offline, from the tarball alone, the package keeps its modules in its own folder, and `simplex-mcp` runs.
- `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. 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.
- 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.
@@ -238,4 +239,5 @@ 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. Stop the service: `kill $(cat /tmp/simplex-mcp-test/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 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.
+21. Stop the service: `kill $(cat /tmp/simplex-mcp-test/service.lock)`.
diff --git a/packages/simplex-chat-mcp/spec/README.md b/packages/simplex-chat-mcp/spec/README.md
index f480dee195..1ddc4d5a5b 100644
--- a/packages/simplex-chat-mcp/spec/README.md
+++ b/packages/simplex-chat-mcp/spec/README.md
@@ -187,7 +187,7 @@ graph TD
| [`protocol.ts`](../src/protocol.ts) | plugin: request and reply types of the socket routes, protocol version |
| [`service.ts`](../src/service.ts) | plugin: routes, session registry, session IDs of one Claude Code process, attachments, idle close and stop, ready line |
| [`hub.ts`](../src/hub.ts) | plugin: the profile `Claude`, the sessions, their groups, prompts, answers and tool-use cards |
-| [`main-group.ts`](../src/main-group.ts) | plugin: the Main group, its owners, `/sessions`, `/join`, owner reset |
+| [`main-group.ts`](../src/main-group.ts) | plugin: the Main group, its owners, the list of sessions, `/sessions`, `/join`, owner reset |
| [`user.ts`](../src/user.ts) | plugin: the profile `User` |
| [`hook.ts`](../src/hook.ts) | plugin: `hook session-start` and `hook turn` |
| [`owner.ts`](../src/owner.ts) | plugin: `link` and `reset-owners` |
@@ -208,7 +208,7 @@ Claude Code uses these files of the plugin, described in [API 4.8](api.md#48-plu
| Document | Contents |
|---|---|
| [Architecture](architecture.md) | system diagram, modules and types, state, process lifecycle, approval model, security boundaries, limits. Section 8 covers the plugin. |
-| [Flows](flows.md) | sequence diagrams of the main flows with source locations. Flows 17-34 cover the plugin. |
+| [Flows](flows.md) | sequence diagrams of the main flows with source locations. Flows 17-36 cover the plugin. |
| [API](api.md) | the six tools, the control chat commands, replies and cards, the CLI. Section 4 covers the plugin's tools, groups, channel, socket protocol, commands and files. |
---
diff --git a/packages/simplex-chat-mcp/spec/api.md b/packages/simplex-chat-mcp/spec/api.md
index b2750f626a..32ec76a23c 100644
--- a/packages/simplex-chat-mcp/spec/api.md
+++ b/packages/simplex-chat-mcp/spec/api.md
@@ -717,8 +717,7 @@ Sources: [`AgentTools.reply`, `sendFile`, `refusedFeature`, `featureOff`, `Agent
| Request | Condition | Reply | Code |
|---|---|---|---|
-| `/sessions` | no session | `No sessions.` | [`Hub.sessionsText`](../src/hub.ts) |
-| `/sessions` | otherwise | one line per session of the hub: `N · NAME`, with `, closed` when the service has no entry for it | [`Hub.sessionsText`](../src/hub.ts) |
+| `/sessions` | | the text of the list of sessions, below, fitted to one message with the quote of the command | [`Hub.sessionsText`](../src/hub.ts) |
| `/join N` | no session N | `No session N. /sessions lists the sessions.` | [`Hub.join`](../src/hub.ts) |
| `/join N` | the sender is a member of its group | `You are a member of "N · NAME".` | [`Hub.join`](../src/hub.ts) |
| `/join N` | otherwise: the sender is invited through the Main group, as `owner` when the sender is an owner of the Main group, else as `admin` | `Sent you an invitation to "N · NAME".` | [`Hub.join`, `Session.invite`](../src/hub.ts) |
@@ -730,6 +729,26 @@ 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) |
+
+The list of sessions ([`Hub.sessionsText`, `Hub.showSessions`, `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 |
+| | `🔵 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` or `shell` |
+| | `▶️ N · NAME: running` | no card; attached; no record path, no record file, or another state |
+| the other sessions | `⚪ Not running: N · NAME, N · NAME, K older sessions`, newest first | sessions without a card and without an attachment, or all of them while the service stops |
+| no session | `No sessions.` | |
+
+- 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)).
@@ -743,7 +762,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}` |
+| custom data | `{simplexMcpMain: true}`, and `simplexMcpList: {item, at}`, the list of sessions and the time it was 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)).
@@ -958,7 +977,7 @@ 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}}`, `pid` the session server's parent process | `{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 /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 /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) |
diff --git a/packages/simplex-chat-mcp/spec/architecture.md b/packages/simplex-chat-mcp/spec/architecture.md
index 0bcb86e57e..442da5b7cf 100644
--- a/packages/simplex-chat-mcp/spec/architecture.md
+++ b/packages/simplex-chat-mcp/spec/architecture.md
@@ -778,7 +778,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. |
+| `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`. |
| `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 |
@@ -856,6 +856,7 @@ 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.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` | The hub 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 passed with the message and its file. |
@@ -873,11 +874,12 @@ Data flow of a prompt from the session group:
| `Session.queue`, `refusesCommand` | the `delivery` chain; a one-line `/` text of a member other than `User` who is not an approver |
| `Session.approves`, `isUser`, `setMode`, `declineHost`, `store`, `savePending` | approver check: not `User`, the role `admin` or `owner` in the session group; the member of the contact `Hub.userContactId`; the mode and its record in the group's custom data; `hostDeclined` and its record; fields written into `session.json`; a pending connection recorded, those older than a day dropped |
| `Hub.userContactId` | the hub's contact marked `simplexMcpUser`, read at the start |
-| `Hub.open` | core `_hub`, Main group found or created, `MainGroup` load and start, `User` unless it fails, the contact of `User`, the stored sessions, events |
+| `Hub.open` | core `_hub`, Main group found or created, `MainGroup` load and start, `User` unless it fails, the contact of `User`, the stored sessions, events, the timer of the list of sessions, every 2 s |
| `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 |
-| `Hub.stop` | actions stopped, events awaited, cancelled cards awaited up to 10 s, steps ended, cores closed |
+| `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.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 ended, cores closed |
| `storedGroup`, `createSessionGroup` | the group of `session.json` with a matching session number; a new group with `User` added |
| `Hub.onEvent` | event dispatch. 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. |
| `notAllowedForUser` | `NAME are not allowed for User in the group of this session; its owners can allow them in the group's preferences.` It is posted for a prompt of `User` refused by a group preference, including one that is on only for roles above that of `User`. |
@@ -894,7 +896,8 @@ Data flow of a prompt from the session group:
| `MainGroup.load`, `start` | lost check, name and menu from the group's current profile, and members. The short description and welcome message are kept. Without owners, `start` takes the existing link, or creates a new one. |
| `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. The session groups are kept. |
+| `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`. |
| `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 |
@@ -989,6 +992,9 @@ 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` |
+| 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` |
A session process keeps one connection promise, one attachment, the refusal of the service, and the retry delay with its timer in memory (the fields of [`ServiceLink`](../src/session.ts)). It also keeps the approved tools of each attachment, and answers the PreToolUse hook from those of the current one (`ServiceLink.approvedTools`).
@@ -997,6 +1003,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) |
| 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) |
@@ -1018,6 +1025,7 @@ Files:
| `ROOT/_hub/`, `ROOT/_user/` | databases and `tmp/` of the profiles `Claude` and `User` | [`openCore`](../src/core.ts) | the cores |
| `ROOT/_sessions/ID/session.json` | `{number, name, project, created, group?, aliases?, model?, effort?, hostDeclined?}`, 0600, replaced whole through `session.json.tmp` | [`Service.openAgent`, `rename`, `alias`](../src/service.ts), [`Hub.session`, `Session.declineHost`, `store`](../src/hub.ts) | `Service` constructor, `resolve`, `Hub.session`, `alias`, `store` |
| `ROOT/_sessions/ID/files/` | downloads of the session's chats as in [3.3](#33-files). The files of the prompts from the group are in `group/`. `sent/` is deleted when the session opens. | the core ([`Session.receive`, `Hub.session`](../src/hub.ts)) | tools, Claude |
+| `CLAUDE_CONFIG_DIR/sessions/PID.json`, or `~/.claude/sessions/PID.json` | Claude Code's record of its process PID, with `status` `busy`, `waiting`, `idle` or `shell`, written in place at each change of its state | Claude Code | [`Session.readRecord`](../src/hub.ts), every 2 s while its session is attached |
### 8.4 Process lifecycle
@@ -1083,7 +1091,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 gives the cancelled cards 10 s to be sent. 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 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 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 5dc3fb03b6..035b21d630 100644
--- a/packages/simplex-chat-mcp/spec/flows.md
+++ b/packages/simplex-chat-mcp/spec/flows.md
@@ -1,6 +1,6 @@
# SimpleX MCP server: flows
-> Sequence diagrams of the main flows of `@simplex-chat/mcp` 0.3.0, each with notes and source locations. `serve` is shown in flows 1-16, and the Claude Code plugin in flows 17-33.
+> Sequence diagrams of the main flows of `@simplex-chat/mcp` 0.3.0, each with notes and source locations. `serve` is shown in flows 1-16, and the Claude Code plugin in flows 17-36.
>
> Related specs: [README](README.md) | [Architecture](architecture.md) | [API](api.md)
@@ -62,6 +62,7 @@ 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)
---
@@ -816,6 +817,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
```
Notes:
@@ -1639,3 +1641,53 @@ Notes:
- After a compaction Claude Code runs the SessionStart hooks with `source: compact` and the model of the compacted conversation, which is a subagent's model for a subagent's compaction. The SessionStart hook sends `/title` without the model then, so the group's description keeps the session's model ([`sessionStart`](../src/hook.ts)).
Source: [`sessionStart`, `turn`, `eventFields`, `compactionNote`, `recentBoundary`, `findInTranscript`, `readTail`](../src/hook.ts), the `PostCompact` entry of [`hooks`](../hooks/hooks.json).
+
+---
+
+## 36. The list of sessions
+
+```mermaid
+sequenceDiagram
+ participant CC as Claude Code
+ participant R as Claude Code's record
+ participant S as Session process
+ participant D as Service
+ participant N as Session N
+ 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
+ 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
+ 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
+ M->>C: apiDeleteChatItems #35;M the old item, 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)).
+- 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.
+
+Source: [`Hub.showSessions`, `Hub.sessionsText`, `Session.readRecord`, `Session.stateLine`](../src/hub.ts), [`MainGroup.showList`](../src/main-group.ts).
diff --git a/packages/simplex-chat-mcp/src/hub.ts b/packages/simplex-chat-mcp/src/hub.ts
index 45401cb722..28cb787f53 100644
--- a/packages/simplex-chat-mcp/src/hub.ts
+++ b/packages/simplex-chat-mcp/src/hub.ts
@@ -1,4 +1,5 @@
-import {mkdirSync, rmSync} from "fs"
+import {constants, mkdirSync, rmSync} from "fs"
+import {open} from "fs/promises"
import {dirname, join} from "path"
import {CEvt, ChatEvent, T} from "@simplex-chat/types"
import {api} from "simplex-chat"
@@ -47,6 +48,19 @@ const maxFinished = 100
const liveLineMs = 23 * 3_600_000
// spec: spec/api.md#session-groups
const stepCheckMs = 60_000
+// spec: spec/api.md#list-of-sessions
+const listCheckMs = 2_000
+// spec: spec/api.md#list-of-sessions
+const recordReadMs = 1_000
+// spec: spec/api.md#list-of-sessions
+const claudeStates = new Map([
+ ["waiting", ["🔵", "waiting for you in Claude Code"]],
+ ["busy", ["🟠", "working"]],
+ ["idle", ["🟢", "idle"]],
+ ["shell", ["🟢", "idle"]],
+])
+// spec: spec/api.md#list-of-sessions
+const unknownState: [string, string] = ["▶️", "running"]
// 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.`}
@@ -78,6 +92,7 @@ interface LiveStep {
// spec: spec/architecture.md#hub-session
export class Session {
open = false
+ record?: string
readonly actions: Actions
readonly tools: AgentTools
readonly control: Control
@@ -100,6 +115,8 @@ export class Session {
private readonly finished = new Set()
private finalizing: Promise = Promise.resolve()
private expiry?: NodeJS.Timeout
+ private claudeStatus?: string
+ private recordRead?: Promise
constructor(
private readonly hub: Hub,
@@ -167,6 +184,41 @@ export class Session {
return this.actions.all().some(({tool}) => tool !== "mode")
}
+ // spec: spec/architecture.md#hub-session-readrecord
+ async readRecord(): Promise {
+ if (!this.attached || this.record === undefined) {
+ 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
+ },
+ )
+ .finally(() => (this.recordRead = undefined))
+ await withinTime(this.recordRead, recordReadMs)
+ }
+
+ // spec: spec/architecture.md#hub-session-readrecord
+ stateLine(): 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"}`
+ if (!this.attached) return undefined
+ const [emoji, text] = state ?? unknownState
+ return `${emoji} ${this.displayName}: ${text}`
+ }
+
+ // spec: spec/architecture.md#hub-session-readrecord
+ private get attached(): boolean {
+ return this.onLine !== undefined && !this.hub.stopped
+ }
+
call(tool: ToolName, input: unknown, call: ToolCall): ReturnType {
return this.tools.call(tool, input, call)
}
@@ -540,8 +592,10 @@ export class Hub implements SessionGroups {
userContactId?: number
promptsHeldUntil = 0
private readonly sessions = new Map()
- private stopped = false
+ stopped = false
private controlEvents: Promise = Promise.resolve()
+ private listTimer?: NodeJS.Timeout
+ private listing?: Promise
private constructor(
readonly chat: api.ChatApi,
@@ -568,6 +622,7 @@ export class Hub implements SessionGroups {
for (const {id, session} of stored) await hub.session(id, session)
hub.promptsHeldUntil = Date.now() + attachWait
await core.events(event => hub.onEvent(event))
+ hub.listTimer = setInterval(() => hub.showSessions(), listCheckMs).unref()
return hub
} catch (error) {
await core.chat.close().catch(() => undefined)
@@ -622,10 +677,33 @@ export class Hub implements SessionGroups {
return this.sessions.get(number)?.id
}
- // spec: spec/api.md#main-group
- sessionsText(): string {
- const lines = [...this.sessions.values()].map(session => `${session.displayName}${session.open ? "" : ", closed"}`)
- return lines.length > 0 ? lines.join("\n") : "No sessions."
+ // spec: spec/api.md#list-of-sessions
+ sessionsText(quote?: T.MsgContent): string {
+ const sessions = [...this.sessions.values()].sort((a, b) => a.number - b.number)
+ if (sessions.length === 0) return "No sessions."
+ const lines = sessions.map(session => session.stateLine())
+ const running = lines.filter(line => line !== undefined)
+ const names = sessions.filter((_, i) => lines[i] === undefined).map(({displayName}) => displayName).reverse()
+ const text = (shown: number): string => [...running, ...(names.length === 0 ? [] : [notRunningLine(names, shown)])].join("\n")
+ const fits = (shown: number): boolean => fitsMessage({type: "text", text: text(shown)}, undefined, quote === undefined ? undefined : {content: quote})
+ if (fits(names.length)) return text(names.length)
+ let low = 0
+ let high = names.length - 1
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2)
+ if (fits(middle)) low = middle
+ else high = middle - 1
+ }
+ return text(low)
+ }
+
+ // 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))
+ .finally(() => (this.listing = undefined))
+ return this.listing
}
// spec: spec/api.md#main-group
@@ -656,9 +734,12 @@ export class Hub implements SessionGroups {
// spec: spec/architecture.md#hub-hub-stop
async stop(): Promise {
this.stopped = true
+ clearInterval(this.listTimer)
const sessions = [...this.sessions.values()]
const stopped = await Promise.all(sessions.map(async ({actions}) => ({lost: actions.lost, cancelled: await actions.stop()})))
await this.controlEvents
+ await this.listing
+ await this.showSessions()
await waitForCancelledCards(stopped.flatMap(({lost, cancelled}) => (lost ? [] : cancelled)), cardsWait, new AbortController().signal)
await Promise.all(sessions.map(session => session.endSteps()))
for (const {tools} of sessions) tools.close()
@@ -733,6 +814,32 @@ function groupName(number: number, name: string): string {
return validName(`${number} · ${name}`)
}
+// spec: spec/architecture.md#hub-session-readrecord
+async function recordStatus(path: string): Promise {
+ const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)
+ try {
+ if (!(await file.stat()).isFile()) return undefined
+ const {status} = JSON.parse(await file.readFile("utf8")) as {status?: unknown}
+ return typeof status === "string" ? status : undefined
+ } finally {
+ await file.close()
+ }
+}
+
+// spec: spec/architecture.md#hub-session-readrecord
+async function withinTime(work: Promise, ms: number): Promise {
+ let timer: NodeJS.Timeout | undefined
+ await Promise.race([work, new Promise(resolve => (timer = setTimeout(resolve, ms)))])
+ clearTimeout(timer)
+}
+
+// spec: spec/api.md#list-of-sessions
+function notRunningLine(names: string[], shown: number): string {
+ const rest = names.length - shown
+ const older = rest === 0 ? [] : [`${rest} older session${rest === 1 ? "" : "s"}`]
+ return `⚪ Not running: ${[...names.slice(0, shown), ...older].join(", ")}`
+}
+
// spec: spec/architecture.md#hub-textparts
function textParts(text: string, quote?: Parameters[2]): string[] {
const chars = [...text]
diff --git a/packages/simplex-chat-mcp/src/main-group.ts b/packages/simplex-chat-mcp/src/main-group.ts
index b96630fbe0..c5dffb447e 100644
--- a/packages/simplex-chat-mcp/src/main-group.ts
+++ b/packages/simplex-chat-mcp/src/main-group.ts
@@ -12,6 +12,10 @@ const mainCommands: T.ChatBotCommand[] = [
]
// spec: spec/architecture.md#main-group-maincommands
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/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
@@ -27,17 +31,26 @@ const shortDescr = "Everyone in this group can join the groups of your Claude Co
// spec: spec/architecture.md#main-group-sessiongroups
export interface SessionGroups {
- sessionsText(): string
+ sessionsText(quote?: T.MsgContent): string
join(member: T.GroupMember, session: number): Promise
inviteOwner(member: T.GroupMember): Promise
}
+// spec: spec/api.md#main-group-profile
+interface SessionList {
+ item: number
+ at: number
+}
+
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
constructor(
private readonly chat: api.ChatApi,
@@ -45,7 +58,9 @@ export class MainGroup {
private readonly userId: number,
private name: string,
private readonly sessions: SessionGroups,
- ) {}
+ ) {
+ this.list = listOf(group.customData)
+ }
get groupId(): number {
return this.group.groupId
@@ -96,11 +111,12 @@ export class MainGroup {
onMessage(ci: T.AChatItem): void {
const {chatItem} = ci
if (this.lost || chatItem.chatDir.type !== "groupRcv" || chatItem.content.type !== "rcvMsgContent") return
- const command = parseCommand(chatItem.content.msgContent.text)
+ const {msgContent} = chatItem.content
+ const command = parseCommand(msgContent.text)
if (command === undefined) return
const sender = chatItem.chatDir.groupMember
this.commands = this.commands
- .then(() => this.command(sender, command))
+ .then(() => this.command(sender, command, msgContent))
.then(reply => this.chat.apiSendTextReply(ci, reply))
.catch(error => logError("Main group command", error))
}
@@ -116,6 +132,7 @@ 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.lost = false
await this.load()
await this.openLink()
@@ -123,9 +140,64 @@ export class MainGroup {
})
}
+ // spec: spec/architecture.md#main-group-maingroup-showlist
+ showList(text: string): 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)
+ })
+ })
+ }
+
+ // 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
+ }
+ if (list.at <= Date.now() - listAge) return this.replaceList(list, text)
+ if (text === this.shown) return
+ try {
+ await this.chat.apiUpdateChatItem(T.ChatType.Group, this.groupId, list.item, {type: "text", text})
+ this.shown = text
+ } catch (error) {
+ if (!isRefusedEdit(error)) throw error
+ await this.replaceList(list, text)
+ }
+ }
+
+ // 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-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}
+ try {
+ await this.chat.apiSetGroupCustomData(this.groupId, customData)
+ } catch (error) {
+ await this.deleteItem(list.item, "new list of sessions")
+ throw error
+ }
+ this.list = list
+ this.shown = text
+ this.group = {...this.group, customData}
+ }
+
+ private async deleteItem(item: number, subject: string): Promise {
+ await this.chat.apiDeleteChatItems(T.ChatType.Group, this.groupId, [item], T.CIDeleteMode.Broadcast).catch(error => logError(subject, error))
+ }
+
// spec: spec/api.md#main-group
- private async command(sender: T.GroupMember, {keyword, params}: Command): Promise {
- if (keyword === "sessions" && params === "") return this.sessions.sessionsText()
+ private async command(sender: T.GroupMember, {keyword, params}: Command, quote: T.MsgContent): Promise {
+ if (keyword === "sessions" && params === "") return this.sessions.sessionsText(quote)
if (keyword === "join" && /^\d+$/.test(params)) return this.sessions.join(sender, Number(params))
return unknownCommand
}
@@ -180,8 +252,10 @@ export class MainGroup {
}
}
- private async post(text: string): Promise {
- await this.chat.apiSendMessages([T.ChatType.Group, this.groupId], [{msgContent: {type: "text", text}, mentions: {}}])
+ private async post(text: string, priority?: number): Promise {
+ const message: T.ComposedMessage & {priority?: number} = {msgContent: {type: "text", text}, mentions: {}, priority}
+ const [sent] = await this.chat.apiSendMessages([T.ChatType.Group, this.groupId], [message])
+ return sent.chatItem.meta.itemId
}
private serialize(work: () => Promise): Promise {
@@ -214,6 +288,24 @@ function isMissingLink(error: unknown): boolean {
return chatError?.type === "errorStore" && chatError.storeError.type === "groupLinkNotFound"
}
+// spec: spec/architecture.md#main-group-maingroup-showlist
+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#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
+}
+
// spec: spec/api.md#main-group-profile
export async function createMainGroup(chat: api.ChatApi, userId: number, displayName: string): Promise {
const group = await createGroup(chat, userId, {
diff --git a/packages/simplex-chat-mcp/src/protocol.ts b/packages/simplex-chat-mcp/src/protocol.ts
index 6c31bdb856..a257fb903e 100644
--- a/packages/simplex-chat-mcp/src/protocol.ts
+++ b/packages/simplex-chat-mcp/src/protocol.ts
@@ -29,6 +29,7 @@ export interface SessionRequest {
project: string
name?: string
config: Config
+ record?: string
}
// spec: spec/architecture.md#protocol-sessionrequest
diff --git a/packages/simplex-chat-mcp/src/service.ts b/packages/simplex-chat-mcp/src/service.ts
index 21421e4027..d9cb92b1ab 100644
--- a/packages/simplex-chat-mcp/src/service.ts
+++ b/packages/simplex-chat-mcp/src/service.ts
@@ -44,6 +44,7 @@ export interface SessionLike {
readonly number: number
readonly displayName: string
open: boolean
+ record?: string
onLine?: (line: AttachLine) => void
busy(): boolean
rename(name: string): Promise
@@ -231,6 +232,7 @@ export class Service {
entry.seen = Date.now()
if (request.pid !== undefined) this.registered.emit(String(request.pid))
const agent = await entry.opening
+ agent.record = request.record
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)
diff --git a/packages/simplex-chat-mcp/src/session.ts b/packages/simplex-chat-mcp/src/session.ts
index e6074220a6..517cfd4164 100644
--- a/packages/simplex-chat-mcp/src/session.ts
+++ b/packages/simplex-chat-mcp/src/session.ts
@@ -1,3 +1,5 @@
+import {homedir} from "os"
+import {join, resolve} from "path"
import {Readable, Writable} from "stream"
import {CallToolResult, JsonSchemaType, McpServer, fromJsonSchema} from "@modelcontextprotocol/server"
import {StdioServerTransport} from "@modelcontextprotocol/server/stdio"
@@ -60,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}, 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`)}, 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 653b5845f4..df94b16936 100644
--- a/packages/simplex-chat-mcp/test/e2e/service.test.ts
+++ b/packages/simplex-chat-mcp/test/e2e/service.test.ts
@@ -74,11 +74,13 @@ async function startService(root: string): Promise {
return service
}
-async function openSession(client: ServiceClient, id: string, name: string): Promise {
+async function openSession(client: ServiceClient, id: string, name: string, record?: string): Promise {
await client.request("POST", "/title", {id, name, config: defaultConfig})
- return client.request("POST", "/session", {id, project: "/p", config: defaultConfig})
+ return client.request("POST", "/session", {id, project: "/p", config: defaultConfig, record})
}
+const sessionsReply = (groupId: number, text: string): ItemCheck => inGroup(groupId, ({chatItem}) => chatItem.quotedItem !== undefined && chatItem.meta.itemText === text)
+
const inGroup = (groupId: number, check: ItemCheck): ItemCheck => ci => ci.chatInfo.type === "group" && ci.chatInfo.groupInfo.groupId === groupId && check(ci)
async function joinSessionGroups(owner: Person, names: string[]): Promise