mcp: a list of every session and its state in the Main group (#8182)

* 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 ✅
This commit is contained in:
Evgeny @ SimpleX Chat authored and GitHub committed 2026-11-13 23:40:02 +00:00
1 parent 743c1e7223
commit 953389322f
19 files changed
+1077 -46

No files matched your search

+1 -1
View File
@@ -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.
+24 -1
View File
@@ -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.
+5 -1
View File
@@ -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.
+4 -2
View File
@@ -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 theLine truncated
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 theLine truncated
- `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)`.
+2 -2
View File
@@ -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. |
---
+23 -4
View File
@@ -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) |
<a id="list-of-sessions"></a>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"<br>`/join` "Join the group of a session", params `<session number>` |
| 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) |
+14 -6
View File
@@ -778,7 +778,7 @@ Data flow of a prompt from the session group:
| Symbol | Contents |
|---|---|
| <a id="session-unattendedrun"></a>`unattendedRun`, `channelInstructions`, `permissionRequest` | the text of a run that is not interactive; instructions of the channel; schema of a permission request |
| <a id="session-startsession"></a>`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. |
| <a id="session-startsession"></a>`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`. |
| <a id="session-servicelink-approvedby"></a>`ServiceLink.approvedBy` | the approver of a tool in the approved tools of the current attachment, or none without an attachment |
| <a id="session-servicelink-connect"></a>`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. |
| <a id="session-servicelink-permission"></a>`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:
| <a id="hub-sessiongroupdata"></a>`SessionGroupData` | session number; pending connections of `connect` with their time; the approved mode |
| <a id="hub-session"></a>`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. |
| <a id="hub-session-busy"></a>`Session.busy` | an action other than a `mode` card in memory |
| <a id="hub-session-readrecord"></a>`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. |
| <a id="hub-session-requestmode"></a>`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. |
| <a id="hub-session-online"></a>`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. |
| <a id="hub-session-onmessage"></a>`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:
| <a id="hub-session-queue"></a>`Session.queue`, `refusesCommand` | the `delivery` chain; a one-line `/` text of a member other than `User` who is not an approver |
| <a id="hub-session-approves"></a>`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 |
| <a id="hub-hub-open"></a>`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 |
| <a id="hub-hub-open"></a>`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 |
| <a id="hub-hub-configure"></a>`Hub.configure`, `resetOwners` | expiry of all sessions and the Main group name. The Main group is replaced at once, even while owners exist. |
| <a id="hub-hub-session"></a>`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. |
| <a id="hub-hub-sessionstext"></a>`Hub.sessionsText`, `join`, `inviteOwner` | `SessionGroups` of the Main group |
| <a id="hub-hub-stop"></a>`Hub.stop` | actions stopped, events awaited, cancelled cards awaited up to 10 s, steps ended, cores closed |
| <a id="hub-hub-sessionstext"></a>`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. |
| <a id="hub-hub-showsessions"></a>`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. |
| <a id="hub-hub-stop"></a>`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 |
| <a id="hub-hub-storedgroup"></a>`storedGroup`, `createSessionGroup` | the group of `session.json` with a matching session number; a new group with `User` added |
| <a id="hub-hub-onevent"></a>`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. |
| <a id="hub-notallowedforuser"></a>`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:
| <a id="main-group-maingroup-load"></a>`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. |
| <a id="main-group-maingroup-onmessage"></a>`MainGroup.onMessage`, `command` | `/sessions`, `/join N`; `Unknown command.` for another |
| <a id="main-group-maingroup-onevent"></a>`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. |
| <a id="main-group-maingroup-replace"></a>`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. |
| <a id="main-group-maingroup-replace"></a>`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. |
| <a id="main-group-maingroup-showlist"></a>`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`. |
| <a id="main-group-maingroup-openlink"></a>`openLink`, `deleteLink` | group link with role `member` |
| <a id="main-group-findmaingroup"></a>`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
+53 -1
View File
@@ -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).
+113 -6
View File
@@ -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<string, [string, string]>([
["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<string>()
private finalizing: Promise<void> = Promise.resolve()
private expiry?: NodeJS.Timeout
private claudeStatus?: string
private recordRead?: Promise<void>
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<void> {
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<AgentTools["call"]> {
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<number, Session>()
private stopped = false
stopped = false
private controlEvents: Promise<void> = Promise.resolve()
private listTimer?: NodeJS.Timeout
private listing?: Promise<void>
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<void> {
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<Action[]> {
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<string | undefined> {
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<void>, ms: number): Promise<void> {
let timer: NodeJS.Timeout | undefined
await Promise.race([work, new Promise<void>(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<typeof fitsMessage>[2]): string[] {
const chars = [...text]
+100 -8
View File
@@ -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<string>
inviteOwner(member: T.GroupMember): Promise<void>
}
// 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<unknown> = Promise.resolve()
private commands: Promise<unknown> = 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<void> {
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<void> {
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<void> {
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<void> {
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<void> {
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<string> {
if (keyword === "sessions" && params === "") return this.sessions.sessionsText()
private async command(sender: T.GroupMember, {keyword, params}: Command, quote: T.MsgContent): Promise<string> {
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<void> {
await this.chat.apiSendMessages([T.ChatType.Group, this.groupId], [{msgContent: {type: "text", text}, mentions: {}}])
private async post(text: string, priority?: number): Promise<number> {
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<R>(work: () => Promise<R>): Promise<R> {
@@ -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<SessionList>} | 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<T.GroupInfo> {
const group = await createGroup(chat, userId, {
@@ -29,6 +29,7 @@ export interface SessionRequest {
project: string
name?: string
config: Config
record?: string
}
// spec: spec/architecture.md#protocol-sessionrequest
+2
View File
@@ -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<void>
@@ -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)
+3 -1
View File
@@ -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))
})
@@ -74,11 +74,13 @@ async function startService(root: string): Promise<Service> {
return service
}
async function openSession(client: ServiceClient, id: string, name: string): Promise<SessionReply> {
async function openSession(client: ServiceClient, id: string, name: string, record?: string): Promise<SessionReply> {
await client.request<TitleReply>("POST", "/title", {id, name, config: defaultConfig})
return client.request<SessionReply>("POST", "/session", {id, project: "/p", config: defaultConfig})
return client.request<SessionReply>("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<Map<string, number>> {
@@ -216,7 +218,7 @@ test("an owner joins the Main group and each session's group, and approves its c
const mainProfile = async () => (await alice.chat.apiListGroups(alice.user.userId)).find(({groupId}) => groupId === mainGroupId)!.groupProfile
const edited = {shortDescr: "Sessions of the team", description: "Ask Alice before you approve."}
await alice.chat.apiUpdateGroupProfile(mainGroupId, {...(await mainProfile()), ...edited})
const sessionsListed = received(alice.chat, inGroup(mainGroupId, textStarts("1 · one")))
const sessionsListed = received(alice.chat, sessionsReply(mainGroupId, "⚪ Not running: 2 · two, 1 · one"))
await ownerSends(mainGroupId, "/sessions")
await sessionsListed
await service.stop()
@@ -226,12 +228,50 @@ test("an owner joins the Main group and each session's group, and approves its c
await listedOne
expect(await openSession(client, two, "two")).toMatchObject({number: 2, displayName: "2 · two", owner: {owners: ["Alice"]}})
expect((await chatsOf(two)).sort()).toEqual([directoryChat, shopChat].sort())
const sessionsListedAgain = received(alice.chat, inGroup(mainGroupId, textStarts("1 · one")))
const sessionsListedAgain = received(alice.chat, sessionsReply(mainGroupId, "⚪ Not running: 2 · two, 1 · one"))
await ownerSends(mainGroupId, "/sessions")
await sessionsListedAgain
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 () => {
const root = join(dir, "list", "root")
await prepareRoot(smpServer.address, root)
const alice = await personIn("list", "Alice")
await startService(root)
const client = ServiceClient.forRoot(root)
const record = join(dir, "list", "claude.json")
writeFileSync(record, JSON.stringify({status: "busy"}))
await openSession(client, one, "one", record)
await openSession(client, two, "two")
const attached: AttachLine[] = []
const controller = new AbortController()
closing.push(async () => controller.abort())
client.stream("/attach", {id: one}, line => attached.push(line as AttachLine), controller.signal).catch(() => undefined)
await until(() => attached.length === 1)
const owner = await client.request<OwnerState>("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 mainGroupId = await joinByLink(alice, owner.link!)
const list = await working
expect(list.chatInfo).toMatchObject({type: "group", groupInfo: {groupId: mainGroupId}})
await invitations
const edited = (text: string): Promise<T.AChatItem> => 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")
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")
writeFileSync(record, JSON.stringify({status: "idle"}))
await idle
const ended = edited("⚪ Not running: 2 · two, 1 · one")
controller.abort()
await ended
const replied = received(alice.chat, sessionsReply(mainGroupId, "⚪ Not running: 2 · two, 1 · one"))
await alice.chat.apiSendTextMessage([T.ChatType.Group, mainGroupId], "/sessions")
await replied
}, 300_000)
test("while files and media are off in a session's group, the card of a send of an image is posted as text, the image is sent after the approval, and the card is edited as text", async () => {
const root = join(dir, "media", "root")
await prepareRoot(smpServer.address, root, xftpServer.address)
@@ -610,7 +650,7 @@ test("a member of the Main group joins a session's group by /join as admin, prom
const bobRemoved = bob.chat.wait("deletedMemberUser", ({groupInfo}) => groupInfo.groupId === bobMain, 60_000)
await alice.chat.apiRemoveMembers(mainGroupId, [bobInAlice.groupMemberId])
expect(await bobRemoved).toBeDefined()
const sessionsListed = received(alice.chat, inGroup(mainGroupId, textStarts("1 · one")))
const sessionsListed = received(alice.chat, sessionsReply(mainGroupId, "▶️ 1 · one: running"))
await alice.chat.apiSendTextMessage([T.ChatType.Group, mainGroupId], "/sessions")
await sessionsListed
await bobSends("Run the tests")
@@ -174,6 +174,7 @@ export class FakeChat {
updates: {chatId: number; itemId: number; text: string; live?: true}[] = []
replies: string[] = []
deleted: {chatType: T.ChatType; chatId: number; mode?: T.ChatDeleteMode}[] = []
deletedItems: {chatType: T.ChatType; chatId: number; itemIds: number[]; deleteMode: T.CIDeleteMode}[] = []
left: number[] = []
customData: {chat: string; customData?: object}[] = []
profiles: {groupId: number; groupProfile: T.GroupProfile}[] = []
@@ -226,6 +227,11 @@ export class FakeChat {
return item(itemId, msgContent.text, {type: "groupSnd"})
}
async apiDeleteChatItems(chatType: T.ChatType, chatId: number, itemIds: number[], deleteMode: T.CIDeleteMode): Promise<T.ChatItemDeletion[]> {
this.deletedItems.push({chatType, chatId, itemIds, deleteMode})
return []
}
async apiSendTextReply(_ci: T.AChatItem, text: string): Promise<T.AChatItem[]> {
this.replies.push(text)
return []
@@ -210,7 +210,7 @@ describe("service", () => {
expect(agents).toHaveLength(2)
})
it("passes the stored sessions to the hub, and the approval mode of each registration to its session", async () => {
it("passes the stored sessions to the hub, and the approval mode and Claude Code's record of each registration to its session", async () => {
storeSession(id1, 1, "app")
const {d, agents, stored} = deps(root)
service = await Service.start(d, readDefaultConfig)
@@ -218,11 +218,14 @@ describe("service", () => {
const host = {...defaultConfig, approve: "host" as const}
await streamLines(socketPath(root), token, "/call", {id: id1, tool: "list", input: {}}, () => undefined)
expect(agents[0].modes).toEqual([])
await post("/session", {id: id1, project: "/p/app", config: host})
expect(agents[0].record).toBeUndefined()
await post("/session", {id: id1, project: "/p/app", config: host, record: "/c/sessions/100.json"})
expect(agents[0].record).toBe("/c/sessions/100.json")
await register(id2)
await title(id2, "docs", host)
await register(id1)
expect(agents.map(({modes}) => modes)).toEqual([["host", "requests"], ["requests"]])
expect(agents.map(({record}) => record)).toEqual([undefined, undefined])
})
it("expires due actions at each request that touches sessions", async () => {
@@ -1,8 +1,8 @@
import {EventEmitter, once} from "events"
import {mkdtempSync, rmSync} from "fs"
import {Server, ServerResponse} from "http"
import {tmpdir} from "os"
import {join} from "path"
import {homedir, tmpdir} from "os"
import {join, resolve} from "path"
import {PassThrough} from "stream"
import {ServiceClient, SpawnService} from "../../src/client"
import {serviceToken, socketPath} from "../../src/files"
@@ -95,7 +95,8 @@ function listCall(client: LineClient): Promise<any> {
const listed = {chats: [], actions: []}
const listResult = {content: [{type: "text", text: JSON.stringify(listed)}], structuredContent: listed}
const registered = `session ${JSON.stringify({id, pid: process.ppid, project: "/p/app", config: {mainGroup: "Claude Control", approve: "requests", expireHours: 23}})}`
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 stdins: PassThrough[] = []
beforeEach(() => {
@@ -304,6 +305,13 @@ 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) => {
await fakeService(async res => endWithResult(res, listResult))
await session({CLAUDE_CONFIG_DIR: folder})
await until(() => seen.length === 2)
expect(seen).toEqual([registration(record), "attach"])
})
it("uses the working folder as the project without CLAUDE_PROJECT_DIR", async () => {
await fakeService(async res => endWithResult(res, listResult))
const {client} = await session({CLAUDE_PROJECT_DIR: ""})
@@ -1,3 +1,4 @@
import {execFileSync} from "child_process"
import {existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync} from "fs"
import {tmpdir} from "os"
import {join} from "path"
@@ -47,8 +48,8 @@ afterEach(() => {
rmSync(root, {recursive: true, force: true})
})
async function hubWith(chat: FakeChat, mainMembers: T.GroupMember[] = [self, alice, bob]): Promise<Hub> {
const main = group(10, "SimpleX MCP", self, {customData: {simplexMcpMain: true}})
async function hubWith(chat: FakeChat, mainMembers: T.GroupMember[] = [self, alice, bob], mainData: object = {simplexMcpMain: true}): Promise<Hub> {
const main = group(10, "SimpleX MCP", self, {customData: mainData})
chat.chats.set("#10", {chatInfo: groupChat(main), items: []})
chat.members.set(10, mainMembers)
const hub = new (Hub as unknown as HubConstructor)(chat.api(), user, root, 23, main, "SimpleX MCP")
@@ -1936,13 +1937,14 @@ describe("Main group", () => {
const one = await openSession(hub, id1, stored(1, "one"))
await openSession(hub, id2, stored(2, "two"))
one.open = true
one.onLine = () => undefined
hub.main.onMessage(mainMessage("/sessions", bob))
hub.main.onMessage(mainMessage("/join 2", bob))
hub.main.onMessage(mainMessage("/join 5", bob))
hub.main.onMessage(mainMessage("/help", bob))
await until(() => chat.replies.length === 4)
expect(chat.replies).toEqual([
"1 · one\n2 · two, closed",
"▶️ 1 · one: running\n⚪ Not running: 2 · two",
`Sent you an invitation to "2 · two".`,
"No session 5. /sessions lists the sessions.",
"Unknown command.",
@@ -1953,6 +1955,229 @@ 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, and the ⚪ line 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"))
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(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)}}})
await withOwner(chat, one)
one.record = join(root, "claude-1.json")
one.onLine = () => undefined
const shows = async (status: string): Promise<string | undefined> => {
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
}
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")
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")).toBeUndefined()
one.endPermissions()
one.onLine = undefined
expect(await shows("idle")).toBe("⚪ Not running: 2 · two, 1 · one")
expect(sentTo(chat, 10).filter(text => text.startsWith("⚪"))).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 () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
const one = await openSession(hub, id1, stored(1, "one"))
const two = await openSession(hub, id2, stored(2, "two"))
await withOwner(chat, one)
await withOwner(chat, two)
one.onLine = () => undefined
one.permission({id: id1, requestId: "abcde", toolName: "Bash", description: "Run shell command", inputPreview: "ls"})
two.requestMode("host")
expect(hub.sessionsText()).toBe("🔵 1 · one: waiting for you, 1 approval\n🔵 2 · two: waiting for you, 1 approval")
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")
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")
one.permission({id: id1, requestId: "fghij", toolName: "Write", description: "Write a file", inputPreview: "a.txt"})
writeFileSync(one.record, JSON.stringify({status: "waiting"}))
await hub.showSessions()
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")
expect(stopped).toBe(false)
await stopping
expect(hub.sessionsText()).toBe("⚪ Not running: 2 · two, 1 · one")
})
it("keeps a session's last state while its record is written, and shows running without a record, without its file or with another status", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
const one = await openSession(hub, id1, stored(1, "one"))
one.onLine = () => undefined
await hub.showSessions()
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
one.record = join(root, "claude-1.json")
await hub.showSessions()
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
writeFileSync(one.record, JSON.stringify({status: "busy"}))
await hub.showSessions()
expect(hub.sessionsText()).toBe("🟠 1 · one: working")
writeFileSync(one.record, '{"pid": 100, "sta')
await hub.showSessions()
expect(hub.sessionsText()).toBe("🟠 1 · one: working")
writeFileSync(one.record, JSON.stringify({status: "compacting"}))
await hub.showSessions()
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
writeFileSync(one.record, JSON.stringify({status: "idle"}))
await hub.showSessions()
rmSync(one.record)
await hub.showSessions()
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
})
it("reads a record without blocking: a FIFO shows running, and a read that stalls keeps the last state, ends the render within a second, and is not repeated while it stalls", async () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
const one = await openSession(hub, id1, stored(1, "one"))
one.onLine = () => undefined
one.record = join(root, "claude-fifo")
execFileSync("mkfifo", [one.record])
await hub.showSessions()
expect(hub.sessionsText()).toBe("▶️ 1 · one: running")
one.record = join(root, "claude-1.json")
writeFileSync(one.record, JSON.stringify({status: "busy"}))
await hub.showSessions()
const opened = jest.spyOn(require("fs/promises"), "open").mockImplementation(() => new Promise(() => undefined))
const started = Date.now()
await hub.showSessions()
await hub.showSessions()
expect(Date.now() - started).toBeLessThan(3_000)
expect(opened).toHaveBeenCalledTimes(1)
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 () => {
const chat = new FakeChat()
const errors: string[] = []
jest.spyOn(process.stderr, "write").mockImplementation(text => (errors.push(String(text)), true))
const hub = await hubWith(chat)
const one = await openSession(hub, id1, stored(1, "one"))
const save = chat.apiSetGroupCustomData
chat.apiSetGroupCustomData = async () => {
throw new Error("database busy")
}
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)
})
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 () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
const name = "𝐀".repeat(46)
const sessions: Session[] = []
for (let n = 1; n <= 400; n++) sessions.push(await openSession(hub, `${String(n).padStart(8, "0")}-0000-4000-8000-000000000000`, stored(n, name)))
const encoded = (text: string): number => Buffer.byteLength(JSON.stringify(text))
const text = hub.sessionsText()
expect(text).toMatch(/^⚪ Not running: 400 · 𝐀+, 399 · 𝐀+, [^\n]*, \d+ older sessions$/u)
const shown = text.split(", ").length - 1
expect(Number(/(\d+) older sessions$/.exec(text)![1])).toBe(400 - shown)
expect(tools.fitsMessage({type: "text", text}, undefined, undefined)).toBe(true)
expect(tools.fitsMessage({type: "text", text: `${text}, 1 · ${name}`}, undefined, undefined)).toBe(false)
const quote: T.MsgContent = {type: "text", text: "/sessions"}
const replied = hub.sessionsText(quote)
expect(tools.fitsMessage({type: "text", text: replied}, undefined, {content: quote})).toBe(true)
expect(encoded(replied)).toBeLessThanOrEqual(encoded(text))
let running = 0
while (!/^⚪ Not running: \d+ older sessions$/u.test(hub.sessionsText().split("\n").at(-1)!)) sessions[running++].onLine = () => undefined
const crowded = hub.sessionsText()
expect(running).toBeGreaterThanOrEqual(62)
expect(crowded.split("\n")).toEqual([...sessions.slice(0, running).map(({displayName}) => `▶️ ${displayName}: running`), `⚪ Not running: ${400 - running} older sessions`])
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 () => {
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"))
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"))
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)
})
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 () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
await openSession(hub, id1, stored(1, "one"))
await hub.showSessions()
expect(sentTo(chat, 10)).toEqual(["⚪ Not running: 1 · one"])
await hub.resetOwners()
chat.members.set(21, [self])
await hub.showSessions()
expect(sentTo(chat, 21)).toEqual([])
const carol = member(5, "Carol", T.GroupMemberRole.Member)
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)}}})
})
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 () => {
const chat = new FakeChat()
const hub = await hubWith(chat)
+437
View File
@@ -0,0 +1,437 @@
# SimpleX MCP: the list of sessions in the Main group
Status: approved by the user on 2026-11-13 and implemented on `ep/mcp-session-list`, merged with master `975cc700a`, which includes `ep/mcp-activity` (#8168). The user answered Q1 A and Q2 B on 2026-11-13; decisions 16 and 17 apply Q2 B. Code references: master `97bbbd9ac`. Claude Code references: version 2.1.322 and its binary at the byte offsets given, and the 27 session records of Claude Code 2.1.260 to 2.1.322 on this machine, read on 2026-11-13. Decisions of the 0.3.0 plan are cited as "0.3.0 decision N".
## 1. Goal
Roadmap line, [ROADMAP.md:17](../packages/simplex-chat-mcp/ROADMAP.md): "One list in the Main group shows every session and its state: working, waiting for you or idle."
The user's words, 2026-11-11, on the lead's proposal "`/sessions` showing each session as running, waiting for approval or idle":
> 5 - yes, via message editing, so main group is a list of sessions with their status (including "waiting") - we already use it for support group, and it doesn't require reposting. Or we could add protocol support for moving messages down, it would help support bot too (though a bit of re-engineering with not so much value)
On a separate post for waiting sessions, in the same message:
> I think we have an idea of "important messages" to indicate waiting, and limit alerts to them only. A separate "waiting" seems wrong.
Outcome:
- Claude keeps one message in the Main group with every session of the data folder, and edits it when a state changes. Each running session has a line with its state, and one last line names the sessions that are not running.
- The states are those of Claude Code itself: working, waiting and idle. A session also waits for you while a card in its group waits for a decision.
- `/sessions` replies with the same text.
## 2. What users see
After the first owner joins the Main group, Claude posts its greeting, as in 0.3.0, and then the list. The list shows every session of the data folder (Q2 B):
```
🟠 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 a Claude Code is attached to it, or while cards wait in its group. Each running session has its own line, by session number. The last line, `⚪ Not running: `, names every other session, newest first, as `N · NAME` separated by `, `. Without any session, the list is `No sessions.`
Lines of running sessions:
```
line when, the first that applies
🔵 N · NAME: waiting for you, K approvals K cards wait for a decision in the session's group; "1 approval" for one
🔵 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: a turn, or a subagent or another delegated task
🟢 N · NAME: idle Claude Code waits for the next prompt, also while a background command runs
▶️ N · NAME: running Claude Code is attached, and its state can't be read
```
The list is one message, so it is cut to the size of one message:
- The lines of running sessions are kept whole.
- The `⚪` line names the sessions that are not running, newest first, while the text still fits. The rest is counted at its end: `⚪ Not running: 212 · api, 211 · docs, 190 older sessions` (`1 older session` for one). When no name fits, the line is `⚪ Not running: 210 older sessions`.
- The text of a message takes at most 14,962 bytes as JSON encodes it, a line break taking 2. That holds at least 62 lines of running sessions with names of 50 four-byte characters, and the `⚪` line after them. With more running sessions than fit, the core refuses the post or the edit, and the list keeps its last text.
How the list changes:
- The emojis have the colors of Claude Code's own state indicator: green for Idle, orange for Working…, blue for Waiting.
- A tool-use card counts only while Claude Code shows its permission dialog, or while its state can't be read. When someone answers the dialog in the terminal, the card stays in the group until the turn ends (0.3.0 decision 29), and the line shows the session working again.
- When Claude Code ends, its session moves into the `⚪` line at once.
- Claude edits the list within 2 seconds of a change. An edit alerts nobody, and the apps mark the message "edited".
- Messages posted after the list, such as each owner's invitation to a new session's group, move it up (Q1 A).
- When the list is 23 hours old, Claude posts a new list at the bottom and deletes the old one for everyone. The core lets Claude edit a message only within 24 hours.
- The list's own posts are silent once receivers support silent messages (`ep/mcp-silent-messages`). Until then a new list alerts as a normal message.
- When the service stops, Claude edits the list once more: every session is in the `⚪` line.
Limits of the list's message:
```
limit value what Claude does
size of one message 15,602 bytes with a 600-byte envelope; the ⚪ line keeps the newest names that fit and
14,962 bytes of text as JSON encodes it counts the rest; running lines are kept whole
editing window of the core 24 hours from the post a new list at 23 hours; the old one deleted
deletion for everyone 30 hours from the post a refused deletion is logged; the old list keeps
its last text
edit rate the text is rendered every 2 seconds an edit only when the text changed
```
`/sessions` replies with the text of the list, cut to the size of one message with its quote of the command.
Before and after:
```
moment 0.3.0 this pull request
the first owner joins the Main group the greeting the greeting, then the list
a session starts the owners' invitations the invitations; the session's line in the list
Claude works on a turn nothing in the Main group 🟠 working
a card waits in the session's group the card the card; 🔵 waiting for you, 1 approval
a dialog waits in Claude Code nothing 🔵 waiting for you in Claude Code
a turn ends, or is interrupted the answer in the session's group 🟢 idle
Claude Code ends nothing the session moves into the ⚪ line
/sessions N · NAME, and ", closed" the text of the list
the list is 23 hours old - a new list at the bottom; the old one deleted
```
A turn with a tool-use card:
```mermaid
sequenceDiagram
participant CC as Claude Code
participant R as record of Claude Code
participant H as hub, every 2 s
participant M as Main group
participant O as owner's app
CC->>R: status busy
H->>R: read
H->>M: edit the list: 🟠 1 · app: working
M->>O: the list updated, no alert
CC->>R: status waiting, a permission dialog
CC->>H: permission request: a card in the session's group
H->>M: edit: 🔵 1 · app: waiting for you, 1 approval
O->>H: /approve 3 in the session's group
CC->>R: status busy
H->>M: edit: 🟠 1 · app: working
CC->>R: status idle, the turn ends
H->>M: edit: 🟢 1 · app: idle
```
The first owner joins, and the list is replaced after 23 hours:
```mermaid
sequenceDiagram
participant H as hub
participant M as Main group
participant O as owner's app
O->>M: joins by the link
H->>M: the greeting
H->>M: the list, silent
H->>H: Main group data: the list's item and its time
Note over H,O: each change: the list edited
Note over H,O: 23 hours after the list was posted
H->>M: a new list, silent
H->>H: Main group data: the new item and its time
H->>M: the old list deleted for everyone
M->>O: the new list at the bottom, the old one shown as deleted
```
## 3. Questions for the user
Q1. Where does the list stay as it changes? Answered A by the user on 2026-11-13.
- A, recommended: Claude edits one message in place. Edits alert nobody. Messages posted after it move it up: each session start sends every owner an invitation in the Main group, and each command gets a reply there. Claude posts a new list at the bottom once a day, because the core edits a message only within 24 hours. Cost: one new message a day while the service runs.
- B: Claude keeps the list as the last message. When another message follows it, Claude posts the list again at the bottom at the next change and deletes the old one, as the support bot does with its cards ([cards.ts:257-287](../apps/simplex-support-bot/src/cards.ts#L257-L287)). The Main group's chat-list preview then shows the list. Cost: a new message at about every session start, because of the invitations, and a deleted message left in place each time.
- C: a core and app change that moves an edited message down, as the user proposed for the support bot too. It is a later pull request; A applies until then.
Q2. Which sessions does the list show? Answered B by the user on 2026-11-13. Decisions 16 and 17 keep the list readable as it grows: the sessions that are not running share one line, newest first, and the oldest are counted when the message is full.
- A, recommended in the first draft: the sessions whose Claude Code runs, the ended ones until the service closes them 10 minutes later, and any session with cards waiting. `/sessions` lists every session with its state. The list holds as many lines as sessions run at once.
- B: every session of the data folder, ended ones as not running. A data folder keeps every session, and session numbers only grow, so the list grows with every session ever started, up to the size of one message.
## 4. Decisions
Facts:
1. Today `/sessions` replies with one line per session of the hub, `N · NAME`, with `, closed` for a session the service has no entry for ([hub.ts:431-434](../packages/simplex-chat-mcp/src/hub.ts#L431-L434), [main-group.ts:112](../packages/simplex-chat-mcp/src/main-group.ts#L112)). The hub opens every stored session at its start ([hub.ts:378](../packages/simplex-chat-mcp/src/hub.ts#L378), [files.ts:65-72](../packages/simplex-chat-mcp/src/files.ts#L65-L72)), and a new session gets the next number ([service.ts:89](../packages/simplex-chat-mcp/src/service.ts#L89), [:398](../packages/simplex-chat-mcp/src/service.ts#L398)).
2. Claude Code keeps a record of each running process in `CONFIG/sessions/PID.json`. CONFIG is "the Claude Code config directory ($CLAUDE_CONFIG_DIR or ~/.claude)" (binary text at 151817147); the folder is `Owe` (286261242), and `Bn` writes `${process.pid}.json` there (287247536).
3. Claude Code writes `status` and `waitingFor` to its record at each change of either (`Ftt({status:bn,waitingFor:fo})` at 324103663, `Ftt` at 287249749). `status` is `waiting` while a dialog, an elicitation, a worker request or a sandbox request waits for the person; otherwise it is `busy` while a query runs or delegated work is active, and `idle` else (`mEe` and `$$o`, 324091852 and 324092046). `idle` is written as `shell` while a background Bash task runs (324103201, `Rmo` at 291522871). The terminal shows the three states as Idle in green, Working… in orange and Waiting in blue (`q$o` at 324091373).
4. Claude Code writes the record in place with `writeFile` of `fs/promises` (import at 287237817), so a read during a write can return a partial file.
5. All 27 records on this machine, of Claude Code 2.1.260 to 2.1.322, have `status`: 18 `idle`, 4 `busy`, 4 `waiting` (`permission prompt` twice, `dialog open`, `input needed`) and 1 `shell`. The record of the lead's session, `4044369.json` of 2.1.322, said `busy` at 08:44 UTC on 2026-11-13 while its background agents worked.
6. The session server sends its parent process as `pid` in `POST /session` ([session.ts:53](../packages/simplex-chat-mcp/src/session.ts#L53)). On this machine the plugin's session server 4044485 has the parent 4044369, `claude --resume ...`, whose record is `~/.claude/sessions/4044369.json`. Its environment has `CLAUDE_CONFIG_DIR`, as Claude Code's has; Claude Code passes its environment to MCP servers (`ep/mcp-fixes` decision 9).
7. Claude Code runs no Stop hook after a user interrupt: "Does not run if the stoppage occurred due to a user interrupt. API errors fire StopFailure instead." (https://code.claude.com/docs/en/hooks, Stop). A typed prompt runs its UserPromptSubmit hook when it is submitted, also during a turn, and can wait for its own turn (`plans/2026-11-12-mcp-harness-notes.md`, facts 5 and 6).
8. The core edits a sent message only within one day of its time: `editable = deletable && isNothing itemForwarded`, with `deletable` true while `currentTs - itemTs < nominalDay` ([Messages.hs:538-550](../src/Simplex/Chat/Messages.hs#L538-L550)). An edit of another item is refused with `invalidChatItemUpdate` ([Commands.hs:861](../src/Simplex/Chat/Library/Commands.hs#L861), [:883](../src/Simplex/Chat/Library/Commands.hs#L883)). Deletion for everyone is allowed for a day and 6 hours ([Commands.hs:956](../src/Simplex/Chat/Library/Commands.hs#L956)).
9. An update is sent without the notification flag ([Protocol.hs:1339-1348](../src/Simplex/Chat/Protocol.hs#L1339-L1348)). The apps alert for an update only when it creates the item ([SimpleXAPI.kt:3825-3843](../apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/SimpleXAPI.kt#L3825-L3843), [SimpleXAPI.swift:3209-3219](../apps/ios/Shared/Model/SimpleXAPI.swift#L3209-L3219)), and the chat list shows the update of a chat's last item ([ChatModel.kt:679-681](../apps/multiplatform/common/src/commonMain/kotlin/chat/simplex/common/model/ChatModel.kt#L679-L681)). An edit of an item that is not live marks it edited ([Commands.hs:877](../src/Simplex/Chat/Library/Commands.hs#L877)).
10. Each new session group gets an invitation for each owner of the Main group ([hub.ts:421-423](../packages/simplex-chat-mcp/src/hub.ts#L421-L423)), sent over the Main group and saved there as an item ([Commands.hs:4416-4418](../src/Simplex/Chat/Library/Commands.hs#L4416-L4418)); "The invited member sees it in group A" ([2026-10-10-invite-member-via-group.md](../docs/rfcs/2026-10-10-invite-member-via-group.md)).
11. Tool-use cards end at the next prompt or answer and at the last detach ([hub.ts:181](../packages/simplex-chat-mcp/src/hub.ts#L181), [:204-208](../packages/simplex-chat-mcp/src/hub.ts#L204-L208), [service.ts:321](../packages/simplex-chat-mcp/src/service.ts#L321)).
12. Actions cancelled by a stop stay `pending` with `interrupted` set, and their cards say `Cancelled: the server stopped.` ([actions.ts:284-295](../packages/simplex-chat-mcp/src/actions.ts#L284-L295), [control.ts:683-686](../packages/simplex-chat-mcp/src/control.ts#L683-L686)).
13. The Main group's custom data is `{simplexMcpMain: true}` ([main-group.ts:12](../packages/simplex-chat-mcp/src/main-group.ts#L12), [:202](../packages/simplex-chat-mcp/src/main-group.ts#L202)), and `findMainGroup` finds the group by that key ([main-group.ts:185-188](../packages/simplex-chat-mcp/src/main-group.ts#L185-L188)).
14. One message holds at most 15,602 bytes as the plugin measures it: 600 for the envelope, and the JSON of the content, the file name, the quote and the mentions ([tools.ts:163-164](../packages/simplex-chat-mcp/src/tools.ts#L163-L164), [:1575-1578](../packages/simplex-chat-mcp/src/tools.ts#L1575-L1578)). A text without a quote then takes at most 14,962 bytes as JSON encodes it. A session's display name has at most 50 code points ([messages.ts:12](../packages/simplex-chat-mcp/src/messages.ts#L12), [:361](../packages/simplex-chat-mcp/src/messages.ts#L361), [hub.ts:528-530](../packages/simplex-chat-mcp/src/hub.ts#L528-L530)).
Choices:
15. The list is one message of Claude in the Main group, edited in place, with a new message when it is 23 hours old (Q1 A).
16. The list shows every session of the data folder (Q2 B). A running session, with a Claude Code attached or with cards waiting, has its own line, by number. The last line, `⚪ Not running: `, names every other session as `N · NAME`, newest first, separated by `, `. Without any session, the text is `No sessions.` `/sessions` replies with the same text.
17. The text fits one message by `fitsMessage` (fact 14), without a quote for the list, and with the quote of the command for the reply to `/sessions`. The lines of running sessions are kept whole. The `⚪` line takes the most names, newest first, for which the text with the count of the rest, `, K older sessions` (`1 older session`), still fits; when no name fits, it is `⚪ Not running: K older sessions`. A line of a running session takes at most 239 bytes: 5 for the emoji and the space, 200 for the name, 32 for `: waiting for you in Claude Code` and 2 for the line break. So at least 62 such lines fit with the `⚪` line. With more, the core refuses the post or the edit as too large, the refusal is logged, and the list keeps its last text. A refused text is not sent again until the text changes (review n5).
18. The state of a session comes from Claude Code's record (facts 2-5), not from the hooks. A turn's end is not visible to the hooks after an interrupt, and a typed prompt that waits for its own turn runs its hook before the previous turn ends (fact 7).
19. The session server sends the absolute path of its record in `POST /session` as `record`: `CLAUDE_CONFIG_DIR` or `~/.claude`, then `sessions`, then its parent's PID with `.json`, resolved against its working folder (review n1). The service passes it to the session. A later `/session` of the session replaces it.
20. Every 2 seconds the hub reads the record of each session with an attachment, and renders the list. A record that does not parse keeps the last status read (fact 4). A missing path, a missing file, a path that is not a regular file, or another status gives `running`. The record is opened without blocking, so a FIFO does not stall; a render waits at most 1 s for a read, and a slower read keeps the last status, with no new read of that record until it ends (review n2).
21. The lines of running sessions are those of section 2. The cards are the session's pending actions without those cancelled by a stop (fact 12). A tool-use card counts while the record says `waiting`, or while its status is not one of the four known ones (review m1).
22. Claude posts the first list only while the Main group has an owner, so it follows the greeting. The item and its time are kept in the Main group's custom data as `simplexMcpList: {item, at}`, next to `simplexMcpMain`, so a restarted service edits the same list.
23. Claude edits the list only when its text changed since the last post or edit; the first render after a start always edits.
24. Claude replaces a list that is 23 hours old, or whose edit the core refuses with `invalidChatItemUpdate` or `chatItemNotFound`: it posts the new list, saves its item and time, and deletes the old one for everyone. A refused deletion is logged; the old list then keeps its last text, as after a service stopped for over 30 hours. When the save of a new list's item fails, the new list is deleted for everyone and the old one stays (review n3).
25. Claude posts the list with `priority: -1`, the silent priority of `ep/mcp-silent-messages`, as `ep/mcp-activity` posts its step lines. The core and the apps ignore it until they support it.
26. At its stop, the hub renders the list once more, after the actions stop and before the wait for the cancelled cards, with every session in the `⚪` line: the stop cancels every card (fact 12). The wait then covers the edit too (review m2).
27. A reset of the owners creates a new Main group without the list; the list is posted there once an owner joins.
28. The protocol version stays 1. `record` is optional: an older service ignores it, and a session of an older session server shows `running`.
29. The greeting and the command menu stay: `/sessions` still lists the sessions.
## 5. Design
Options for the source of a session's state:
```
option producer consumer: hub wire accuracy
R. Claude Code's record (chosen) Claude Code writes it at each reads small files every 2 s + record in Claude Code's own state: interrupts,
change; the session server of attached sessions POST /session queued prompts, dialogs, subagents
sends its path
H. turn hooks + StopFailure and a turn start and end times, Stop and StopFailure after an interrupt: idle only by an
Notification hook for ordering rules of async hooks send answer "" idle notice 60 s later; a typed prompt
idle_prompt with its own turn: idle while it runs;
dialogs: unseen
S. step hooks of ep/mcp-activity depends on that pull request a step means working step a turn without tools: unseen
```
H costs more at the producer and the consumer, and is still wrong after interrupts and for queued typed prompts (fact 7). S misses turns without tool use and depends on another pull request. R reads an internal file of Claude Code, as 0.3.0 decision 121 reads its transcript; a change of its format shows `running`.
Options for the list:
```
option messages edits cost
L1. one message, edited in place (chosen) one, and one a day one per change the list moves up behind invitations (Q1 A)
L2. one message, kept last one per session start, deleted ones one per change Q1 B
L3. one message per session one per session start, N a day one per change N messages to scan; the old cards stay
L4. /sessions with states only one reply per request none no overview without asking
L5. state in each session group's name none in the Main group a profile update a profile update to every member
per change of a group for each change
```
L2 and L3 cost more messages and alerts; L4 does not show the state unasked; L5 is not in the Main group and costs a profile update per change.
Options for every session in one message (Q2 B):
```
option size of the message cost
F1. a line per running session, one ⚪ line the running lines and one the oldest names are counted
of the others, newest first (chosen) wrapped line once the message is full
F2. a line per session, the oldest cut a line per session ever started hundreds of lines to scroll past
F3. several messages, as pages up to one message each more posts and edits; not one list
F4. ranges of numbers for the others the running lines and the ranges the names of ended sessions are lost
```
F2 makes the running sessions hard to find among the ended ones, F3 costs a message per page and breaks the one list, and F4 drops the names that `/join N` needs.
Options for when the list is rendered:
```
option cost
P. every 2 s, edit when the text changed one timer; up to 2 s late
(chosen)
E. on events a file watch per record, and a notification from Actions at each
create and decision, from attach, detach, open, close and rename
```
E needs a watch of the records anyway, since Claude Code writes them without telling the plugin, and adds a call at seven places. P reads the same files and the hub's memory and catches every change.
Changes:
```
file function or type change
src/protocol.ts SessionRequest + record?: string
src/session.ts startSession the request gets record (decision 19)
src/service.ts SessionLike + record?: string
onSession agent.record = request.record
src/hub.ts constants listCheckMs = 2 s; claudeStates, unknownState
Session + record, + claudeStatus: the last status read; readRecord();
stateLine(), the line of a running session, section 2, or none;
attached, a private getter
Hub + stopped made public, read by Session.attached; + listTimer, listing
Hub.open starts the list timer, unref'd
Hub.showSessions, new reads the records of the attached sessions; main.showList(sessionsText)
Hub.sessionsText(quote?) the text of decisions 16 and 17, fitted with the quote when given;
"No sessions." without any session
Hub.stop clears the timer; waits for a running render; the last render before
the cores close
notRunningLine, new function the ⚪ line with the first K names and the count of the rest
src/main-group.ts constants listKey simplexMcpList, listAge 23 h
SessionGroups.sessionsText + the quote of the command, for /sessions
MainGroup + list {item, at} from the custom data; + shown text
MainGroup.onMessage, command the command's content passed as the quote of /sessions
MainGroup.showList, new decisions 22-25, serialized with the group's events; replaceList,
postList; isRefusedEdit, listOf
MainGroup.post returns the item's ID; an optional priority
MainGroup.replace the list cleared with the old group
```
Session state:
```
readRecord():
not attached or no record path: claude = undefined
read and parse record: claude = its status
no file: claude = undefined
unparsable: claude unchanged
cards = actions.pending() without interrupted ones,
and without permission cards when claude is known and not "waiting"
attached = onLine set and the hub not stopping
running = attached, or cards > 0
line, of a running session:
cards > 0 🔵 N · NAME: waiting for you, K approval(s)
claude = "waiting" 🔵 N · NAME: waiting for you in Claude Code
claude = "busy" 🟠 N · NAME: working
claude = idle, shell 🟢 N · NAME: idle
otherwise ▶️ N · NAME: running
```
Text of the list, and of the reply to `/sessions` with its quote:
```
sessionsText(quote):
no session: "No sessions."
lines = the lines of the running sessions, by number
names = "N · NAME" of the other sessions, by number from the newest
rest(k) = "K older sessions", "1 older session" for one, with K = the count of names - k
⚪(k) = "⚪ Not running: " + the first k names, and rest(k) when K > 0, joined by ", "
text(k) = lines, then ⚪(k), joined by line breaks; lines alone when names is empty
k = the largest k for which text(k) fits one message with quote (fact 14), or 0
text = text(k)
```
Hub and Main group:
```
every 2 s, and once at the stop:
for each attached session: readRecord()
main.showList(sessionsText(no quote))
showList(text), after the group's earlier events:
the group lost: nothing
no list: an owner in the group: post text, silent; list = {item, now}; save list; shown = text
list older than 23 h: replace
text = shown: nothing
edit the list to text; shown = text
refused with invalidChatItemUpdate or chatItemNotFound: replace
replace:
post text, silent; old = list; list = {item, now}; save list; shown = text
delete old for everyone; a refusal logged
save list: Main group custom data = {simplexMcpMain: true, simplexMcpList: list}
```
```mermaid
stateDiagram-v2
state "🟢 idle" as idle
state "🟠 working" as working
state "🔵 waiting for you" as waiting
state "⚪ in the line Not running" as stopped
[*] --> stopped: the session is created
stopped --> idle: Claude Code attaches
idle --> working: record busy
working --> waiting: a card, or record waiting
idle --> waiting: a card
waiting --> working: the card decided, record busy
waiting --> idle: the card decided, record idle
working --> idle: record idle or shell
idle --> stopped: Claude Code ends
working --> stopped: Claude Code ends
stopped --> waiting: a card of an ended session
```
A session stays in the list for as long as the data folder keeps it. A session attached while its record can't be read is `▶️ running` in place of idle, working and waiting in Claude Code.
```mermaid
flowchart LR
CC[Claude Code process PID] -->|status at each change| R["CONFIG/sessions/PID.json"]
SS[session server, child of PID] -->|POST /session with record| SV[service]
SV -->|Session.record| H[hub, every 2 s]
R -->|read| H
C[cards of each session] --> H
H -->|text changed| MG[MainGroup.showList]
MG -->|edit, or a new list after 23 h| M[Main group]
MG -->|simplexMcpList: item and time| D[Main group custom data]
```
## 6. Compatibility
- Older SimpleX apps: every app version applies edits and deletions for everyone. Apps without silent messages alert for the list's posts: the first one and one a day.
- Older Claude Code: every record on this machine since 2.1.260 has `status` (fact 5). Without a readable record, attached sessions show `▶️ running`.
- Older session servers, of Claude Code sessions started before the update: their `/session` has no `record`, so their sessions show `▶️ running` until Claude Code restarts.
- Older services: a newer hook stops an older service ([client.ts:37-40](../packages/simplex-chat-mcp/src/client.ts#L37-L40)); an older service ignores `record`.
- Older data folders: the Main group has no `simplexMcpList`, so Claude posts a list at the first render while the group has an owner. In a group whose owner joined long ago, it follows the existing messages. Every session stored before the update is in it, in the `⚪` line until its Claude Code attaches.
- `serve`: unchanged; it has no Main group.
## 7. Acceptance and tests
Done when:
```
# criterion checked by
1 after the greeting, Claude posts the list of every session, silent: the running ones unit: sessions; e2e
by number, then the ⚪ line, newest first
2 each line follows Claude Code's record: busy, waiting, idle, shell; an attached unit: sessions
session without a record is running; a partial record keeps the last state
3 cards count: tool-use cards only while the record says waiting or is unknown; unit: sessions
cancelled cards never
4 the list is edited only when its text changes; a restarted service edits the same unit: sessions
list, found in the Main group's data
5 a list 23 hours old, or whose edit is refused, is replaced and the old one deleted unit: sessions
for everyone; a refused deletion is logged
6 no list without an owner; after a reset of the owners, a new list once an owner joins unit: sessions
7 at the stop, every session is in the ⚪ line unit: sessions
8 /sessions replies with the text of the list, fitted with its quote unit: sessions; e2e
9 the text fits one message: the ⚪ line keeps the newest names that fit and counts the unit: sessions
older ones; with no name room, only the count; running lines are never cut
10 the session server sends record from CLAUDE_CONFIG_DIR or ~/.claude and its parent's unit: session; unit: service
PID, and the service passes it to the session
11 a real session: working, waiting for you with a card, waiting for you in Claude Code, TESTING check
idle after an interrupt, in the ⚪ line after an exit
```
Tests:
- `test/unit/sessions.test.ts`, in "Main group", new:
- "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, and the ⚪ line after an exit". It calls `Hub.showSessions`, so it compiles only with this change; the e2e test below fails on master.
- "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", with 400 stored sessions, with names of 50 four-byte characters, and with the quote of `/sessions`.
- "counts a tool-use card only while Claude Code shows its dialog or its record is unknown, every other card, and no card cancelled by a stop".
- "keeps a session's last state while its record is written, and shows running without a record, without its file or with another status".
- "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".
- "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".
- "puts every session in the ⚪ line at the hub's stop".
- `test/unit/sessions.test.ts`, changed: "lists the sessions and invites a member to the group of a session as admin by /join" expects the text of the list.
- `test/unit/session.test.ts`, changed: the registered request has `record`, with and without `CLAUDE_CONFIG_DIR`.
- `test/unit/service.test.ts`, changed: "/session passes its record to the session".
- `test/e2e/service.test.ts`, new: "the Main group shows every session, the running ones with their states from Claude Code's record and the cards, edited in place". A session with a record file attaches; the test writes `busy`, starts a `connect` whose card waits, approves it, and writes `idle`; Alice's app gets the list and its updates. It fails on master: no list arrives. The `/sessions` expectations of the first test are changed to the text of the list.
- `TESTING.md`, a real-session check: two sessions show in the list. `sleep 20` with Bash shows 🟠. `Run ls with Bash.` from the group shows 🔵 with 1 approval; after `/approve N` it shows 🟠, and 🟢 when the turn ends. Esc during a turn shows 🟢 within 2 s. A question of Claude in the terminal, such as AskUserQuestion, shows 🔵 in Claude Code. Exiting Claude Code moves the session into the ⚪ line. `/sessions` replies with the same text.
- Run: `npm test --prefix packages/simplex-chat-mcp`, and the end-to-end tests as TESTING.md states; the reduced build runs them in CI. No app changes, so no app test workflows.
## 8. Docs to change
- `README.md:34`: step 3 says that the Main group lists the sessions with their states.
- `REFERENCE.md`, "The Main group" (547-575): the list, its lines, the `⚪` line and its cut, edits, the daily replacement, the stop; the `/sessions` bullet with the text of the list.
- `ROADMAP.md`: the line is marked ✅. The items delivered since 0.3.0 are restored above it, marked ✅.
- `spec/api.md` 4.2: the `/sessions` rows, a "Posts" row for the list, the custom data `simplexMcpList`; 4.6: `record` of `POST /session`.
- `spec/architecture.md` 8.2: `Hub.showSessions`, `sessionsText`, `stop`, `stateLine`, `Session.record`, `readRecord`, `MainGroup.showList`; 8.3: the memory rows of `Session.record`, `Session.claude` and `MainGroup.list`, the custom data row, and Claude Code's record among the files read.
- `spec/flows.md`: flow 17 ends with the list; a new flow, the list of sessions, with the replacement.
- `TESTING.md`: the automated tests and the real-session check.
## 9. Conflict areas with the other items
```
file where items
src/hub.ts Session fields, Hub.open, Hub.stop mcp-activity (steps, endSteps in Hub.stop),
mcp-replies, mcp-live-answers
src/service.ts SessionLike, onSession mcp-activity (endSteps in SessionLike, onAttach),
mcp-fixes (runService, readyChannel)
src/session.ts startSession request (53) mcp-replies (channelInstructions, channelNotification)
src/protocol.ts SessionRequest (21-27) mcp-replies (AttachLine), mcp-activity (TurnRequest)
src/main-group.ts MainGroup, showList mcp-threads, when sessions become threads
test/unit/sessions.test.ts "Main group" (1380-1531) mcp-fixes (group name in texts)
test/e2e/service.test.ts /sessions in the first test (217-229) mcp-fixes (group name, link tests)
README.md:32-34 steps 2-3 mcp-fixes (Claude Control)
REFERENCE.md "The Main group" 547-575 mcp-fixes (Claude Control)
ROADMAP.md line 17 and neighbours mcp-fixes adds a line; mcp-flat-sessions and
mcp-agent-profile remove lines
spec/api.md 4.2, 4.6; tables several items extend mcp-activity, mcp-replies, mcp-fixes
architecture.md 8.2, 8.3
priority of the list's posts the silent priority mcp-silent-messages, mcp-activity
the line of a session model, effort or usage in the line mcp-session-usage, if it puts them there
Claude Code's record the start of work mcp-live-answers, which can read the same status
```
## 10. Estimate
```
part source lines test lines
hub.ts, main-group.ts 115 210 unit
session.ts, service.ts, protocol.ts 5 20 unit
e2e 50
docs 60 lines of text
```
About one working day, with two review rounds.