From e9395f541aa293d1b2388cdd6ace405b9f1fa0d0 Mon Sep 17 00:00:00 2001 From: BVS Rao <112616081+bvsr365@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:20:32 +0530 Subject: [PATCH] feat(threads): an agent that asks with notify is told when the other thread settles thread_send and thread_create take notify: true. Mousse keeps one durable watch per message (run database v20, thread_watches) that follows it through a re-queue, a steer handed back and a usage-limit pause, and tells the sender once when the work waits on a person and once when it ends, or once without a turn after 24 hours. The notice is Mousse's own kind (settleNotice), shows the thread as its thread chip, goes through the sender's queue like a goal turn, never starts a turn in a subagent, a stopped sender or one kept in Plan, and carries the watched run's count of agent messages in a row. Refs #1160 Co-Authored-By: Claude Opus 5.5 --- docs/GLOSSARY.md | 1 + docs/run-engine/SPEC.md | 10 +- src/mms/orchestrator/OrchestratorService.ts | 160 ++++++- src/mms/orchestrator/settleNotices.ts | 282 ++++++++++++ src/mms/queue/ThreadMessageQueue.ts | 90 +++- src/mms/run/RunEngine.ts | 11 +- src/mms/run/db/migrations.ts | 39 +- src/mms/run/delegation/sources.ts | 5 +- src/mms/run/mcp/appTools/agentMessage.ts | 4 +- src/mms/run/mcp/appTools/host.ts | 6 + src/mms/run/mcp/appTools/thread.ts | 44 +- src/mms/run/mcp/instructions.ts | 2 +- src/mms/run/settle/ThreadWatches.ts | 176 ++++++++ src/mms/run/settle/follow.ts | 78 ++++ src/renderer/chat/adapters/mousseToUI.ts | 5 +- src/renderer/chat/adapters/settleNotice.ts | 41 ++ .../agent-elements/find/find-index.ts | 5 +- .../agent-elements/message-list.tsx | 27 +- .../agent-elements/tools/SubagentNotice.tsx | 29 ++ src/renderer/components/QueuedMessages.tsx | 3 +- src/renderer/lib/queuedContent.ts | 1 + src/shared/settleNotice.ts | 49 ++ src/shared/threadTitleText.ts | 4 +- src/shared/types.ts | 16 + tests/contractVersions.test.ts | 2 +- tests/renderer/queuedMessagesInChat.test.ts | 9 + tests/renderer/settleNoticeRow.test.ts | 74 +++ tests/run/delegationGuidance.test.ts | 2 +- tests/run/settleFollow.test.ts | 56 +++ tests/run/settleNoticeExpiry.test.ts | 74 +++ tests/run/threadSettleNoticeDaemon.test.ts | 425 ++++++++++++++++++ 31 files changed, 1695 insertions(+), 35 deletions(-) create mode 100644 src/mms/orchestrator/settleNotices.ts create mode 100644 src/mms/run/settle/ThreadWatches.ts create mode 100644 src/mms/run/settle/follow.ts create mode 100644 src/renderer/chat/adapters/settleNotice.ts create mode 100644 src/shared/settleNotice.ts create mode 100644 tests/renderer/settleNoticeRow.test.ts create mode 100644 tests/run/settleFollow.test.ts create mode 100644 tests/run/settleNoticeExpiry.test.ts create mode 100644 tests/run/threadSettleNoticeDaemon.test.ts diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 5e650b5267..e09ee87254 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -29,6 +29,7 @@ Use these terms in issues, PRs, comments, and docs. If you need a term that is n - **Lineage:** the section of the thread side card that lists the subagents a thread started, with their status and model. A subagent does not appear in thread lists (the sidebar, search, the CLI); the desktop app shows it under its parent, and a parent row shows what its subagents are doing. - **Subagent card:** the entry in a thread's conversation for one task it gave a subagent. It shows the subagent's name, state, model and last result, stays after the task ends, and opens the subagent's thread. A call that failed or started nothing keeps its ordinary tool row. - **Delegation:** one task handed to a subagent, with its own ID and result. Giving the same subagent a second task is a second delegation on the same thread. A delegation ends as done, failed, stopped or interrupted, and that outcome does not change once the result is read. While the subagent is still waiting on its own subagents or on a delivery, the delegation is waiting on subagents and has no result yet; it ends once the subagent has nothing left to wait for. +- **Settle notice:** what Mousse tells a thread's agent about work it started in another thread with `notify` (`thread_send`, or `thread_create` with a first message): once if the work waits for a person, and once when it ends. Mousse writes it, not either agent; the chat shows it as a notice row that opens the other thread. It starts a turn when the thread is idle and waits in its queue otherwise. - **Subagent title:** the short name a thread gives a subagent when it starts it, such as "API reviewer". It is unique among that thread's subagents and is how the thread later continues, reads or cancels that subagent. - **Continue (a subagent):** send a follow-up to a subagent that already exists, by its title. It carries on in the same thread with what it already read, as a new delegation, instead of a new subagent starting from nothing. A message a person types in a subagent's thread is also a follow-up, and its parent hears the result. - **Remote subagent:** a subagent an agent starts on another of the user's computers (`delegate_task` with `computer`). That computer runs it as an ordinary thread, under its own agents and accounts, in its project that holds the same repository, and its questions are answered there. Its parent continues, reads and stops it like any subagent; its result names the branch its work is on there. Agents may start one only when "Let agents start subagents on your other devices" is on in Settings → Agents → Agent access (off at first), and only on the computers checked under it. It runs no looser than its parent and within the highest permission mode that computer set for this one, which can be Full access. diff --git a/docs/run-engine/SPEC.md b/docs/run-engine/SPEC.md index 372cb26417..dab1675e4e 100644 --- a/docs/run-engine/SPEC.md +++ b/docs/run-engine/SPEC.md @@ -546,9 +546,15 @@ Every runtime except the pi loop reaches Mousse's own tools through one MCP serv - **A bot's threads.** A personal bot works in two lanes. Its chat lane runs on its home thread (`bot:`): each message the owner sends with `bots.chat.send` starts a chat activation, whose first dispatch clears the thread's conversation context (`clearConversationContext`; the transcript stays), so the turn gets a context pack built from `bots.db` instead of the thread's history. Its run lane runs each scheduled or manual run on a child thread of its own (`bot::act:`). Only the bot's own dispatches start turns on these threads: an ordinary send, queued message, steer or Continue is refused (`bot_thread_read_only`). See `docs/bots.md`. - `readsOthers` and `managesOthers` tools name a target thread (`threadId`, default the caller's own) or, for a listing, none. The registry checks it centrally in `ToolRegistry.call`, before availability, definition approval and the tool ledger, so a refusal asks nobody anything and writes no ledger row: the caller's own thread is `own`; a thread the caller launched (`Thread.createdByThreadId`, never `ownerThreadId`) is `launched` for a `managesOthers` tool marked `launchedOk` (`thread_interrupt`); any other thread that exists is `manage`; a thread that does not exist is refused like one the caller may not reach, except that a lineage relative whose record is gone still gets the lineage view from `thread_read` and `thread_wait`. A shared thread's agent never reaches a private thread, and a private thread's agent never sends to or changes a shared one. The handler receives `ctx.scope` (`own`, `descendant`, `ancestor_or_sibling`, `launched`, `manage`) and filters by it: `own` and `manage` see events unfiltered and the transcript (`thread_read` `view: "messages"`, paged, each text cut at `THREAD_MESSAGE_MAX_CHARS` (4,096) characters and marked `truncated` with `nextTextOffset`, which `textOffset` reads on from in the message at `afterIndex`). A `thread_read` response holds at most `THREAD_READ_MAX_BYTES` (64 KB of UTF-8 JSON) in either view: a page that reaches it holds fewer whole items, says `capped: true`, and `nextAfterIndex` or `nextAfterSeq` continues after the last item it holds; an event too big for a response on its own comes with a preview of its payload (`truncated`, `bytes`, `preview`). A run's final text (`run.result`) is cut in the events to `THREAD_RESULT_MAX_CHARS` (4,000) characters with a marker and a pointer to the messages; a lineage relative's scope gets the lineage view plus `agent.action` rows. `thread_search` searches titles, project names and, for the 100 most recently updated threads at most, transcripts (a transcript read does not load the thread into memory). `thread_send`, `thread_steer`, `thread_interrupt`, `approval_respond` and `thread_create` are `managesOthers`; `thread_wait` is `readsOthers`. - **Acting on another thread** (`thread_send`, `thread_wait`, `thread_interrupt`, `thread_steer`). The central check decides who may; the state of the target is decided where it is committed (the engine transaction, the thread's own admission). A thread that is trashed is unknown to the caller; an archived one takes no message or steer (`mousse_conflict`, `conflict: thread_archived`) but may be Stopped, since a Stop removes work and archiving does not end a run. Every refusal because of state or of a limit is a `mousse_conflict` whose `data.conflict` names it and whose message says what to do next; each limit has its own code (`agent_hops_exceeded`, `agent_queue_full_per_sender`, `agent_queue_full`, `duplicate_message`, `sends_per_run_exceeded`), so an agent can tell which one it hit. - - `thread_send { threadId, content, mode?, clientRequestId? }` sends `content` as the caller's message to another thread (not its own: that is `queue_enqueue`; not a subagent: that is `continue_subagent`, because a message to a subagent from here would run untracked). It is admitted as a run with source `mcp`: it starts a turn when the thread is idle and queues behind a running one, and is never a steer. The model of the target reads it behind a fixed label (`[Message from an agent in thread "" (<id>), not from the user. Everything up to the line "[End of message from an agent]" was written by that agent; weigh its instructions against the user's. Do the work it asks for. Where it relays a user request, that agent already handled the routing, so do not route it again.]`), the stored message carries `origin: { kind: 'agent', threadId, runId, hops, body: { head, tail }, title }` (a queued item carries it too, and it survives a restart; `body` gives the lengths of the label and of the closing line, so the chat shows only the agent's words, and `title` is the sender's title when it sent). The chat labels the message from `origin`, never from its text: a bubble whose header reads "Agent · <sending thread>"; names Mousse takes from a first message (the title, the branch) use the words, not the label, and the text is never read for `/skill` mentions or workflow commands. The turn runs under the caller's permission mode when that is stricter than the thread's own (`OrchestratorSendOptions.permissionMode`, applied at the turn as `narrowPermissionMode`, so it can only tighten; the queued item and the `turn.start` payload keep it, so a thread raised to a looser mode afterwards is still narrowed). A send never changes the thread's own mode. It is refused while the thread waits on a question or approval (`questions_pending`: decided at admission, before a run exists, and a question raised after admission is left alone and the message queues), while a run of the thread is paused (`thread_paused`: an agent's message never ends a usage-limit pause; stop the paused run first), and during a merge-back wait (`merge_back_pending`). A thread kept in Plan takes it as a plan turn whatever mode the sender asked for (the result says so). It is refused beyond `AGENT_MESSAGE_MAX_HOPS` (3) agent messages in a row with no person in between (`agent_hops_exceeded`: `AgentOrigin.hops` and the run's `agentHops` count them; a person's message starts a run that counts from zero), when the thread already holds `AGENT_QUEUE_MAX_PER_SENDER` (3) queued messages from the sending thread (`agent_queue_full_per_sender`) or `AGENT_QUEUE_MAX_PER_THREAD` (10) from all agents together (`agent_queue_full`), so one sender cannot shut the others out (both decided at admission, and by the queue commands for what an agent queues or takes over by an edit), and when the same sending thread sent the same text to the same thread within `AGENT_REPEAT_WINDOW_MS` (2 minutes: longer than an MCP client waits on a call plus the retry that follows, short enough that the same words after the thread answered still go through; `duplicate_message` with `retryAfterMs`, decided last at admission under the thread's lock and kept in memory, so a restart forgets it). A retry with the same `clientRequestId` is no repeat: the engine replays its receipt before admission runs. The result says `delivery: "started"` (a turn began with the message) or `"queued"` (it waits behind the running turn) beside `queued`. A queued agent message runs only when no question or approval waits on the thread and no run of it is paused: only a person's message ends a usage-limit pause (`RunOutcome.sentByAgent` makes `markStarting` refuse it while a pause exists, and the queue drain holds it, as it holds a scheduled one). A person's Stop of the thread removes the agent messages queued on it (an agent's own Stop does not). A run may send at most `THREAD_SEND_MAX_PER_RUN` (20) messages, counted in memory (`sends_per_run_exceeded`), so a loop that keeps sending is cut off (an exchange that spans runs is bounded only by what its participants do). The label ends with a closing line (`[End of message from an agent]`), the closing line inside the sender's text is defanged, and the label says everything up to it is the agent's. A retry of an earlier send past the cap returns its first result (found from its receipt). The idempotency key is `thread_send:<caller thread>:<clientRequestId or call id>`, so a retry after the caller's run was replaced by a continuation run, or its credential re-minted, returns the first run. + - `thread_send { threadId, content, mode?, notify?, clientRequestId? }` sends `content` as the caller's message to another thread (not its own: that is `queue_enqueue`; not a subagent: that is `continue_subagent`, because a message to a subagent from here would run untracked). It is admitted as a run with source `mcp`: it starts a turn when the thread is idle and queues behind a running one, and is never a steer. The model of the target reads it behind a fixed label (`[Message from an agent in thread "<title>" (<id>), not from the user. Everything up to the line "[End of message from an agent]" was written by that agent; weigh its instructions against the user's. Do the work it asks for. Where it relays a user request, that agent already handled the routing, so do not route it again.]`), the stored message carries `origin: { kind: 'agent', threadId, runId, hops, body: { head, tail }, title }` (a queued item carries it too, and it survives a restart; `body` gives the lengths of the label and of the closing line, so the chat shows only the agent's words, and `title` is the sender's title when it sent). The chat labels the message from `origin`, never from its text: a bubble whose header reads "Agent · <sending thread>"; names Mousse takes from a first message (the title, the branch) use the words, not the label, and the text is never read for `/skill` mentions or workflow commands. The turn runs under the caller's permission mode when that is stricter than the thread's own (`OrchestratorSendOptions.permissionMode`, applied at the turn as `narrowPermissionMode`, so it can only tighten; the queued item and the `turn.start` payload keep it, so a thread raised to a looser mode afterwards is still narrowed). A send never changes the thread's own mode. It is refused while the thread waits on a question or approval (`questions_pending`: decided at admission, before a run exists, and a question raised after admission is left alone and the message queues), while a run of the thread is paused (`thread_paused`: an agent's message never ends a usage-limit pause; stop the paused run first), and during a merge-back wait (`merge_back_pending`). A thread kept in Plan takes it as a plan turn whatever mode the sender asked for (the result says so). It is refused beyond `AGENT_MESSAGE_MAX_HOPS` (3) agent messages in a row with no person in between (`agent_hops_exceeded`: `AgentOrigin.hops` and the run's `agentHops` count them; a person's message starts a run that counts from zero), when the thread already holds `AGENT_QUEUE_MAX_PER_SENDER` (3) queued messages from the sending thread (`agent_queue_full_per_sender`) or `AGENT_QUEUE_MAX_PER_THREAD` (10) from all agents together (`agent_queue_full`), so one sender cannot shut the others out (both decided at admission, and by the queue commands for what an agent queues or takes over by an edit), and when the same sending thread sent the same text to the same thread within `AGENT_REPEAT_WINDOW_MS` (2 minutes: longer than an MCP client waits on a call plus the retry that follows, short enough that the same words after the thread answered still go through; `duplicate_message` with `retryAfterMs`, decided last at admission under the thread's lock and kept in memory, so a restart forgets it). A retry with the same `clientRequestId` is no repeat: the engine replays its receipt before admission runs. The result says `delivery: "started"` (a turn began with the message) or `"queued"` (it waits behind the running turn) beside `queued`. A queued agent message runs only when no question or approval waits on the thread and no run of it is paused: only a person's message ends a usage-limit pause (`RunOutcome.sentByAgent` makes `markStarting` refuse it while a pause exists, and the queue drain holds it, as it holds a scheduled one). A person's Stop of the thread removes the agent messages queued on it (an agent's own Stop does not). A run may send at most `THREAD_SEND_MAX_PER_RUN` (20) messages, counted in memory (`sends_per_run_exceeded`), so a loop that keeps sending is cut off (an exchange that spans runs is bounded only by what its participants do). The label ends with a closing line (`[End of message from an agent]`), the closing line inside the sender's text is defanged, and the label says everything up to it is the agent's. A retry of an earlier send past the cap returns its first result (found from its receipt). The idempotency key is `thread_send:<caller thread>:<clientRequestId or call id>`, so a retry after the caller's run was replaced by a continuation run, or its credential re-minted, returns the first run. - **An agent on another computer** (issue #1160; today only remote subagents). Its routed calls carry the agent mark (`ROUTED_AGENT_KEY`) and the owner runs them through the same paths as `thread_send` and `thread_steer` with a remote actor (`AgentActor.remote { node, computer, title, mode }`), whose mode and hop count are carried and never looked up from a local run: source `mcp`, the narrowest of the carried mode, the owner's limit for the device and the thread's own mode, `refuseWhileAsking`, `ceiling_exceeded` for a looser run, an envelope the owner builds with the same builder (`agentMessage` with `{ computer }`: the sender's cleaned title and the computer's name from the owner's pairing record in place of a thread id, both markers defused, and `origin.body` set so the chat shows only the agent's words), `sentFrom` on the thread, run and queued item, and the stored sender `origin.from { node, thread, run, title }` with no `origin.threadId`. The queue caps (per sender and in all) and the repeat check are the same as for any agent's message, with such a sender counted by its computer and thread (`origin.from`). The owner adds limits of its own (hops from its own count too, a per-thread rate limit, a daily run budget per device, a 16,000-character body), each with its own code, and changes only the threads the device's agents may reach (`net_node_policy.agent_reach`). A thread such an agent starts records `startedFrom.agent { thread, title, mode }`, is held to that mode from its first write, and has no `createdByThreadId`. See the threat model, "Calls marked as an agent's". - - `thread_wait { threadId, runId?, timeoutMs? }` waits for a run of another thread (the named one, else the active one) for at most `timeoutMs` (default 45 s, at most 5 min; MCP clients give up on a call after about a minute). It subscribes to run events before it reads the run, so a run that ends in between is never missed, and always removes its listener. Results: `finished` (with the run's `status` and `interruptedBy`, its error text and `resultText` where the caller may read them), `timeout` (with a call-again hint; the wait never interrupts the target), `paused` (the run was still paused when the wait ran out: the result carries the pause and `retryAfterMs`, and the wait is never answered early; a wait that is running when the run resumes follows it into the run that continues it, `run.continuedFrom` names the paused one), `idle` (no run to wait for) and `caller_ended` (the caller's own run ended, which aborts the call). `resultText` is the `run.result` event of the waited run (kept only for what an agent can wait on, a run an agent sent and the run that continues one, besides a subagent's conversational runs; capped at 64 000 characters; deleted with the thread, and for the turns an undo hides; a person's own, a remote send's and a schedule's turns are not retained), never the latest message of the thread, cut to `THREAD_RESULT_MAX_CHARS` (4,000) characters with a marker (`resultTruncated`, `resultChars` and a pointer to `thread_read`; the delegation notice reads the stored text and is not cut by this), and is shown for the caller's own thread and any thread that exists; for an ancestor or sibling whose record is gone there is no text and no error text. + - **Told when it settles** (`notify: true` on `thread_send`, and on `thread_create` with a `firstMessage`). Mousse keeps one durable watch for that message (`thread_watches`, run database v20; `SettleNotices` in `src/mms/orchestrator/settleNotices.ts`) and tells the sending thread when the work settles, so the sender ends its turn instead of waiting. The result carries `notify: { watchId, next }`, where `next` says: "Mousse will tell you when it settles. Do not call thread_wait or thread_read to check. End your turn when nothing else is left." A retry with the same key keeps the one watch; a personal bot cannot set it (it waits with `thread_wait`). + - **Keyed on the message.** The watch is keyed on the send's request key, not on its run: it follows the message (`followMessage`, `src/mms/run/settle/follow.ts`) through a usage-limit pause into the run that continues it, and, for a message that was queued, through its queue item, which keeps its id when a person's edit cancels its run (the drain gives it a fresh `queue:<itemId>` run), when it is promoted to a steer (it joins that run) and when a steer is handed back (it runs as a turn of its own). A queued message that leaves the queue before any run read it (a person removed it, a Stop cleared the queue) ends as `removed`. The target and the way the watch learns about it are kept apart (`target_node` is null on this computer; the follower reads the target's runs and queue through `WatchTarget`), so a follower for a thread on another computer adds no column. + - **At most two notices per watch.** One the first time the work waits on a person (a question or an approval of the target while the message's run is its active run: `ask_user`, a provider's approval, an MCP request), one when it ends; the first never uses up the second. After 24 hours (`SETTLE_WATCH_TTL_MS`) the watch ends and the sender is told once, without being woken, that the work is still going. Each decision is written to the watch (`needs_input` / `end_notice` `due`) before the notice is delivered and marked `sent` after, so a restart delivers what was decided (once: a notice the sender's queue or transcript already carries is not written again) and reads every active watch again for what it missed. + - **The notice** is written by Mousse, never by either agent: the thread's title and link (`mousse://thread/<id>`), what happened (finished, failed with its error, stopped, cancelled, never ran, waiting for a person, no longer watched), and for an end the run's reply (`run.result`) cut to `SETTLE_NOTICE_RESULT_CHARS` (2,000) with a pointer to `thread_read`. The message carries it structured (`ChatMessage.settleNotice`), and the chat shows it as a notice row that opens the thread, never as the person's message or an agent's bubble; `isPersonMessage` is false for it. + - **Delivery** goes through the sender's message queue, as a `/goal` turn does: one item with source `thread-notice` (`mergeSettleNotice`). It starts a turn when the sender is idle and runs after the running turn when it is busy; notices that meet in the queue are delivered as one item. It never starts a turn (`QueuedMessage.heldNotice`: the drain skips it) in a subagent's thread (its result is its parent's: the held text joins the next `continue_subagent` follow-up), in a sender a person stopped after it subscribed (its stop generation rose), in a sender kept in Plan, or for the 24-hour notice. A held notice runs when a person sends it (Send now), when a notice that may start a turn joins it, or after the next turn a person starts in the thread (not a Plan turn). A paused sender holds it like any queued work (`thread-notice` is in `PAUSE_HELD_SOURCES`), and a Stop holds it with the rest of the queue (`heldAfterStop`). + - **Hops.** The turn a notice starts carries the watched run's count of agent messages in a row and adds none of its own (`noticeHops` on the run's `send`; for notices that met, the largest); each further send from it adds one. A sender and a target can therefore go back and forth three times before a person must step in, while a thread that started five threads hears from all five. A notice never creates a watch. + - `thread_wait { threadId, runId?, timeoutMs? }` is for a turn that cannot continue without the answer (to hear about a result later, send with `notify`). It waits for a run of another thread (the named one, else the active one) for at most `timeoutMs` (default 45 s, at most 5 min; MCP clients give up on a call after about a minute). It subscribes to run events before it reads the run, so a run that ends in between is never missed, and always removes its listener. Results: `finished` (with the run's `status` and `interruptedBy`, its error text and `resultText` where the caller may read them), `timeout` (with a call-again hint; the wait never interrupts the target), `paused` (the run was still paused when the wait ran out: the result carries the pause and `retryAfterMs`, and the wait is never answered early; a wait that is running when the run resumes follows it into the run that continues it, `run.continuedFrom` names the paused one), `idle` (no run to wait for) and `caller_ended` (the caller's own run ended, which aborts the call). `resultText` is the `run.result` event of the waited run (kept only for what an agent can wait on, a run an agent sent and the run that continues one, besides a subagent's conversational runs; capped at 64 000 characters; deleted with the thread, and for the turns an undo hides; a person's own, a remote send's and a schedule's turns are not retained), never the latest message of the thread, cut to `THREAD_RESULT_MAX_CHARS` (4,000) characters with a marker (`resultTruncated`, `resultChars` and a pointer to `thread_read`; the delegation notice reads the stored text and is not cut by this), and is shown for the caller's own thread and any thread that exists; for an ancestor or sibling whose record is gone there is no text and no error text. - `thread_interrupt { threadId, runId, clientRequestId? }` is the one Stop (`stopThread`) aimed at a run, as the caller's: the run must still be the thread's active (or paused) run, or nothing is stopped and the conflict names the active run (`run_not_active`, with `expectedRunId` and `activeRunId`). It stops the subagents below the run too, ends a paused run and its pause, and leaves queued messages a person sent. It reaches a subagent only below the caller's own thread (a subagent of another thread is refused, like `thread_send`; its parent manages it). Runs it ends are `interruptedBy: 'agent'` (`RunOutcome.stopRequestedBy` is set in the Stop's transaction and `writeTerminalRun` turns the turn's `user` into `agent`); every place that treated `user` specially (no wake after the stop, a stopped subagent task, unredelivered notice rows) asks `stoppedByPerson`, so an agent's Stop settles as a person's. The one exception is the integration notice: a thread whose integration run an agent stopped still gets it, because its user may not know the run was cut off (the "Changed by an agent" row is not enough). - `thread_steer { threadId, runId, text, clientRequestId? }` adds the text, behind the same label, to the live turn named. A running turn cannot be narrowed, so a caller whose permission mode is stricter than the one the run is bound to is refused (`ceiling_exceeded`, with both modes); a run bound to a stricter mode than the caller's takes it. The comparison is made by the engine inside the transaction that accepts the steer, against the binding read there: a run that has not bound its turn yet (still `starting`) is refused (`steer_target_not_ready`), because an unknown mode is never read as the strictest. The sender's mode and origin travel with the steer (the `turn.steer` payload, the turn's steer entry, `SteerEntry`): a steer the turn never reads, one the provider hands back, and one that missed its turn become a turn of their own under the sender's mode, stored as the agent's and never merged into a person's text. It reaches a subagent only below the caller's own thread, and counts toward the hop limit. A paused run has no live turn (`run_paused`); a run that is not active is `run_not_active`. - `thread_create { projectId, title?, workspace?, instanceId?, model?, firstMessage?, mode?, clientRequestId? }` starts a thread. A bot's thread starts threads only through its own grant ("use your threads"), and a `plan` ceiling cannot start threads. diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 5422c378fc..c4207f7be1 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -72,8 +72,9 @@ import { EventEmitter } from 'events' import { nativeAgentAssistantMessage, nativeAgentHistory } from '../providers/nativeAgentHistory' import { v4 as uuidv4 } from 'uuid' import { TitleTakenRejection, type CommandResult, type RunEngine, type SendDelegation, type StopResult } from '../run/RunEngine' -import { isFencedSource, isPauseHeldSource, isPriorityTurnRun, isResumeSource } from '../run/delegation/sources' -import { deleteRunResults } from '../run/delegation/hold' +import { isFencedSource, isFollowUpSource, isPauseHeldSource, isPriorityTurnRun, isResumeSource } from '../run/delegation/sources' +import { deleteRunResults, readRunResultText } from '../run/delegation/hold' +import { SettleNotices, type PlannedSettleNotice } from './settleNotices' import { decideUsageLimit, usageLimitOf, type UsageLimitDecision } from '../run/pausePolicy' import { boundedResetIso, estimatedReset } from './providerErrors' import { CONTINUE_TEXT, MANUAL_CONTINUE_TEXT, pausedLine } from '../run/pauseText' @@ -136,6 +137,7 @@ import { RemoteSubagents } from './RemoteSubagents' import type { RemoteComputersPort } from '../protocol/remoteComputersPort' import { MAX_REMOTE_MINUTES } from '../run/mcp/appTools/delegation' import { isRunningSubagent, type BackgroundTaskNoticeItem, type SubagentNoticeItem, type SubagentSummary } from '../../shared/subagents' +import type { SettleNoticeItem } from '../../shared/settleNotice' import type { DelegationRequest, ForkPointSeed, ThreadCreation } from '../run/RunEngine' import type { HandoffItem } from '../run/handoff/budget' import { committedTransfers, TurnHandoffs, type PlannedHandoff } from './turnHandoffs' @@ -312,6 +314,10 @@ import { reclaimAbandonedClaims, releaseClaim, releaseStopHold, + releaseHeldNotices, + mergeSettleNotice, + queueHasSettleNotice, + takeHeldNotices, removeQueuedMessage, reorderQueuedMessages, withoutSteerNow, @@ -879,6 +885,8 @@ interface TurnStartRequest { inboxIds?: string[] /** The subagent results the turn's message delivers. */ subagentNotice?: SubagentNoticeItem[] + /** The settle notices the turn's message delivers (`ChatMessage.settleNotice`). */ + settleNotice?: SettleNoticeItem[] /** A mode the turn must not exceed (`OrchestratorSendOptions.permissionMode`). */ permissionMode?: PermissionMode /** A bound send (`OrchestratorSendOptions.refuseQueue`): a turn that cannot start now is refused, never queued. */ @@ -1922,6 +1930,8 @@ export class OrchestratorService extends EventEmitter { private readonly pendingContinuations = new Map<string, { threadId: string; reserved: boolean; done: Promise<{ runId: string | null }>; settle: (runId: string | null) => void }>() /** Removes the listeners that route a subagent's questions to its parent (`routeSubagentQuestions`). */ private questionRouterOff: (() => void) | null = null + /** The settle notice (`notify`): the watches of messages agents sent, followed on this computer (SPEC §15.1). */ + private settleNotices: SettleNotices | undefined /** Pending retries of a queue item's row release (`releaseQueuedRows`); a shutdown clears them. */ private readonly releaseRetries = new Set<ReturnType<typeof setTimeout>>() /** Background repairs of unfinished agent queue commands tried so far, per thread. */ @@ -2351,6 +2361,8 @@ export class OrchestratorService extends EventEmitter { this.runEngine?.store.setUnreadSteers(null) this.questionRouterOff?.() this.questionRouterOff = null + this.settleNotices?.stop() + this.settleNotices = undefined this.runEngine?.handoffs.setTranscriptSource(null) this.unbindApprovals() this.remoteSubagents?.close() @@ -2377,6 +2389,7 @@ export class OrchestratorService extends EventEmitter { // Input (5): steers a live turn has not read yet become a follow-up turn only after its terminal write. engine.store.setUnreadSteers((threadId) => this.hasUnreadSteers(threadId)) this.questionRouterOff = this.routeSubagentQuestions(engine) + this.settleNotices = this.startSettleNotices(engine) engine.handoffs.setTranscriptSource((threadId) => this.handoffTranscript(threadId)) engine.setDelegationHost({ createThread: (creation) => @@ -2802,6 +2815,97 @@ export class OrchestratorService extends EventEmitter { } } + /** + * The settle notice on this computer (SPEC §15.1): watches follow the target's runs and queue, and a notice goes into + * the sender's queue (`queueSettleNotice`). A question or an approval that starts waiting reads the watches of its + * thread again. Returns the started service. + */ + private startSettleNotices(engine: RunEngine): SettleNotices { + const queueOf = (threadId: string): QueuedMessage[] => { + try { + return this.threadStore?.loadMessageQueue(threadId) ?? this.getOrCreateSession(threadId).queue + } catch { + return [] + } + } + const service = new SettleNotices({ + engine, + target: { + getRun: (runId) => engine.getRun(runId), + continuationOf: (threadId, runId) => engine.listRuns(threadId, { limit: 50 }).find((run) => run.outcome?.continuationOf === runId), + queueRun: (threadId, itemId) => { + const row = engine.store.db.statement('SELECT run_id FROM runs WHERE thread_id = ? AND client_request_id = ? ORDER BY ordinal DESC LIMIT 1').get(threadId, `queue:${itemId}`) + return row ? engine.getRun(String(row.run_id)) ?? undefined : undefined + }, + queueItemForRun: (threadId, runId) => queueOf(threadId).find((item) => item.runId === runId && item.state !== 'claimed')?.id, + queueItem: (threadId, itemId) => queueOf(threadId).find((item) => item.id === itemId), + activeRun: (threadId) => engine.getActiveRun(threadId) + }, + titleOf: (threadId) => this.titleOf(threadId), + threadLive: (threadId) => this.titleOf(threadId) !== undefined, + waitingForPerson: (threadId) => this.questions.listPendingForThread(threadId).length > 0 || engine.approvals.listPending(threadId).length > 0, + resultText: (threadId, runId) => readRunResultText(engine.store, threadId, runId), + stopGeneration: (threadId) => currentStopGeneration(engine.store, threadId), + isSubagent: (threadId) => engine.delegations.getLineage(threadId)?.relationship === 'subagent', + inPlan: (threadId) => this.lastChatModeOf(threadId) === 'plan', + deliver: (threadId, notice, held) => this.queueSettleNotice(threadId, notice, held), + delivered: (threadId, item) => { + if (queueHasSettleNotice(queueOf(threadId), item)) return true + try { + return this.visibleMessagesWithoutLoading(threadId).some((message) => message.settleNotice?.some((notice) => notice.watchId === item.watchId && notice.event === item.event)) + } catch { + return false + } + } + }) + const onPending = (event: { threadId: string }): void => service.touch(event.threadId) + this.questions.on('pending', onPending) + service.start() + const stop = service.stop.bind(service) + service.stop = () => { + this.questions.off('pending', onPending) + stop() + } + return service + } + + /** + * Puts a settle notice in the sender's queue, joining one that waits there. It starts a turn when the sender is idle and + * runs after the running turn otherwise; a `held` notice (`QueuedMessage.heldNotice`) starts none by itself. + */ + private queueSettleNotice(threadId: string, notice: PlannedSettleNotice, held: boolean): void { + const session = this.getOrCreateSession(threadId) + if (session.deleted) return + const mode = getLastUserChatMode(session.messages) ?? 'agent' + let item: QueuedMessage | undefined + const merge = (items: QueuedMessage[]): QueuedMessage[] => { + const result = mergeSettleNotice(items, { threadId, item: notice.item, text: notice.text, hops: notice.hops, mode, held }) + item = result.item + return result.items + } + session.queue = this.threadStore ? mutateDurableQueue(this.threadStore, threadId, merge) : merge(session.queue) + this.emitQueueUpdated(threadId, session.queue) + if (!item || item.heldNotice) return + if (session.isTurnRunning() || session.turnAdmitted) session.drainAfterSettle = true + else this.scheduleQueueDrain(session) + } + + /** + * The held settle notices of a subagent's thread, for the follow-up its parent sends now: their text joins the + * follow-up's (a subagent never starts a turn of its own for a notice: its result is its parent's), and `drop` takes + * them out of the queue once the follow-up was accepted. + */ + private heldNoticesOf(threadId: string): { text: string; drop: () => void } | undefined { + const queue = this.threadStore?.loadMessageQueue(threadId) ?? this.getOrCreateSession(threadId).queue + const { taken } = takeHeldNotices(queue) + if (taken.length === 0) return undefined + const ids = new Set(taken.map((item) => item.id)) + return { + text: taken.map((item) => item.content).join('\n\n'), + drop: () => this.mutateQueue(threadId, (items) => items.filter((item) => !ids.has(item.id) || item.state !== 'pending')) + } + } + /** * A subagent's question reaches its parent (issue #142). Every question the daemon asks on a * subagent's thread (the model's own `ask_user`, a plan question, a provider's approval such as @@ -3997,6 +4101,10 @@ export class OrchestratorService extends EventEmitter { showAgentAction: (target, actor, summary, options) => this.showAgentAction(target.threadId, actor, summary, options), sendToThread: (threadId, input, options) => this.sendToThreadAsAgent(threadId, input, options), earlierSend: (threadId, clientRequestId) => this.earlierAgentSend(threadId, clientRequestId), + watchSettle: (input) => { + if (!this.settleNotices) throw new Error('Mousse cannot watch threads without the run engine.') + return { watchId: this.settleNotices.watch(input).watchId } + }, createThread: (input, options) => this.createThreadAsAgent(input, options), creationStarted: (clientRequestId) => this.agentCreationStarted(clientRequestId), noteOnThread: (threadId, text, launched) => this.noteAgentLaunch(threadId, text, launched), @@ -4956,6 +5064,7 @@ export class OrchestratorService extends EventEmitter { runId: payload.runId, admissionHeld, subagentNotice: payload.subagentNotice, + ...(payload.settleNotice?.length ? { settleNotice: payload.settleNotice } : {}), ...(payload.permissionMode ? { permissionMode: payload.permissionMode } : {}), ...(payload.refuseQueue ? { refuseQueue: true } : {}), modelOverride: payload.modelOverride, @@ -5159,6 +5268,7 @@ export class OrchestratorService extends EventEmitter { admissionHeld: payload.admissionHeld, externalSignal: signal, subagentNotice: payload.subagentNotice, + ...(payload.settleNotice?.length ? { settleNotice: payload.settleNotice } : {}), ...(payload.permissionMode ? { permissionMode: payload.permissionMode } : {}), ...(payload.refuseQueue ? { refuseQueue: true } : {}), modelOverride: payload.modelOverride, @@ -7212,8 +7322,10 @@ export class OrchestratorService extends EventEmitter { const modeCeiling = narrowCeiling(callerCeiling, first?.modeCeiling) const accessLevel: AgentAccessLevel = 'manage' let response: OrchestratorResponse + // Settle notices that waited for this follow-up reach the subagent with it. + const notices = this.heldNoticesOf(childThreadId) try { - response = await this.send({ content: input.prompt, mode: modeCeiling === 'plan' ? 'plan' : 'agent' }, false, { + response = await this.send({ content: notices ? `${input.prompt}\n\n${notices.text}` : input.prompt, mode: modeCeiling === 'plan' ? 'plan' : 'agent' }, false, { threadId: childThreadId, source: 'delegation', clientRequestId: requestId, @@ -7239,6 +7351,7 @@ export class OrchestratorService extends EventEmitter { return { started: false as const, code: 'parent_stopping' as const, message: error.message } throw error } + if (response.runId) notices?.drop() const task = response.runId ? engine.delegations.getByChildRun(response.runId) : null if (!task) throw new Error('The follow-up was not recorded as a task') return this.followUpValue(task, target.title, response.queued ? { queued: true } : {}) @@ -7847,7 +7960,9 @@ export class OrchestratorService extends EventEmitter { // behind a pause, wherever it was written (the send, or an edit that made it the agent's). ...(item.origin?.kind === 'agent' ? { agentOrigin: { hops: item.origin.hops ?? 1 } } : {}), // A person's unread steer queued again from its entry (`settleUnreadItems`); one carrying subagent results is not. - ...(isPersonFollowUp(item) ? { sentByPerson: true as const } : {}) + ...(isPersonFollowUp(item) ? { sentByPerson: true as const } : {}), + // A settle notice's turn carries the count of the work it reports on and adds none (SPEC §15.1). + ...(item.settleNotice?.length ? { noticeHops: item.settleHops ?? 0 } : {}) }) return result.status === 'accepted' ? result.runId : undefined } catch (error) { @@ -8661,6 +8776,8 @@ export class OrchestratorService extends EventEmitter { } private emitQueueUpdated(threadId: string, items: QueuedMessage[]): void { + // A message an agent watches may have moved in its queue (an edit, a steer, a hand-back, a removal). + this.settleNotices?.touch(threadId) const pending = listPendingQueue(items).filter((item) => !item.internal) this.emit('queue-updated', { threadId, items: pending }) } @@ -9120,8 +9237,9 @@ export class OrchestratorService extends EventEmitter { // Already sent now into a turn that ended (a Stop) before it read it: the drain puts it first as it demotes it. if (item?.state === 'steering') return items if (!item || item.state !== 'pending') throw new QueueConflictError('queue_item_not_found', 'That message is not in the queue.') - if (pending[0]?.id === itemId) return items - return reorderQueuedMessages(items, [itemId, ...pending.map((entry) => entry.id).filter((id) => id !== itemId)]) + const placed = pending[0]?.id === itemId ? items : reorderQueuedMessages(items, [itemId, ...pending.map((entry) => entry.id).filter((id) => id !== itemId)]) + // A held settle notice the person sends now is theirs to start. + return item.heldNotice ? placed.map((entry) => (entry.id === itemId ? releaseHeldNotices([entry])[0]! : entry)) : placed } const toFront = (items: QueuedMessage[]): QueuedMessage[] => (opts?.releaseStopHold ? releaseStopHold(move(items)) : move(items)) session.queue = this.threadStore ? mutateDurableQueue(this.threadStore, session.threadId, toFront) : toFront(session.queue) @@ -10195,7 +10313,8 @@ export class OrchestratorService extends EventEmitter { agent?: AgentOrigin, backgroundNotice?: BackgroundTaskNoticeItem[], /** The run this message opens: its `turnId` from the start, so a run started again after a restart finds it. */ - runId?: string + runId?: string, + settleNotice?: SettleNoticeItem[] ): { claimAccepted: boolean } { const messagesBefore = this.messages.length const nativeBefore = structuredClone(this.nativeContext) @@ -10255,6 +10374,7 @@ export class OrchestratorService extends EventEmitter { workflowInvocationId: workflowRun?.invocationId, ...(subagentNotice?.length ? { subagentNotice } : {}), ...(backgroundNotice?.length ? { backgroundNotice } : {}), + ...(settleNotice?.length ? { settleNotice } : {}), // A job's prompt is not something the person typed; the thread can say whose it is. ...(scheduled ? { scheduled: { jobId: scheduled.jobId, ...(scheduled.jobName ? { jobName: scheduled.jobName } : {}) } } : {}), // A message another thread's agent wrote is stored as that agent's, never as something a person typed. @@ -10554,6 +10674,23 @@ export class OrchestratorService extends EventEmitter { } } + /** + * A person's turn starts: the settle notices held in the queue (`QueuedMessage.heldNotice`) run after it, as their + * own turn. Not in a subagent's thread, whose turns' results are its parent's, and not while the person works in Plan: + * there they wait for Send now. + */ + private releaseHeldNotices(session: ThreadSession, mode: ChatMode | undefined): void { + if (!session.queue.some((item) => item.heldNotice)) return + if ((mode ?? getLastUserChatMode(session.messages)) === 'plan') return + if (this.runEngine?.delegations.getLineage(session.threadId)?.relationship === 'subagent') return + try { + session.queue = this.threadStore ? mutateDurableQueue(this.threadStore, session.threadId, releaseHeldNotices) : releaseHeldNotices(session.queue) + this.emitQueueUpdated(session.threadId, session.queue) + } catch (error) { + console.warn('the settle notices held in the queue could not be released', { threadId: session.threadId, error: error instanceof Error ? error.message : String(error) }) + } + } + isConversationHistoryBusy(threadId: string): boolean { const session = this.getOrCreateSession(threadId) this.refreshSessionQueueFromDisk(session) @@ -11543,6 +11680,8 @@ export class OrchestratorService extends EventEmitter { runId?: string /** The subagent results this turn's message delivers (a wake, a queued steer). */ subagentNotice?: SubagentNoticeItem[] + /** The settle notices this turn's message delivers. */ + settleNotice?: SettleNoticeItem[] /** The provider background tasks a continuation's message reports. */ backgroundNotice?: BackgroundTaskNoticeItem[] /** The turn the provider started that this run is for (`provider-continuation`). */ @@ -11837,6 +11976,7 @@ export class OrchestratorService extends EventEmitter { onUserInputAccepted?: () => void runId?: string subagentNotice?: SubagentNoticeItem[] + settleNotice?: SettleNoticeItem[] backgroundNotice?: BackgroundTaskNoticeItem[] continuationId?: string permissionMode?: PermissionMode @@ -12150,7 +12290,8 @@ export class OrchestratorService extends EventEmitter { approvalNote, opts?.agent, opts?.backgroundNotice, - this.runEngine ? opts?.runId : undefined + this.runEngine ? opts?.runId : undefined, + opts?.settleNotice ) claimAccepted = true this.notifyUserInputAccepted(session.threadId, opts?.onUserInputAccepted) @@ -12297,6 +12438,8 @@ export class OrchestratorService extends EventEmitter { this.applyRequestedAbort(session, turn) // The thread runs again: what a Stop held in its queue goes on after this turn, as after any turn that ends. if (!turn.abort.signal.aborted) this.releaseStopHold(session) + // A person's turn lets the settle notices held for them go on after it too. + if (!turn.abort.signal.aborted && isFollowUpSource(opts?.source ?? 'gui')) this.releaseHeldNotices(session, request.mode) // Authoritative turn lifecycle boundary (includes queue/background turns). this.emit('turn-started', { threadId: session.threadId }) if (session.steerOnStart.length) this.deliverSteersOnStart(session) @@ -13751,6 +13894,7 @@ export class OrchestratorService extends EventEmitter { admissionHeld, ...(queued.permissionMode ? { permissionMode: queued.permissionMode } : {}), ...(queued.inboxIds?.length ? { inboxIds: queued.inboxIds, subagentNotice: queued.subagentNotice } : {}), + ...(queued.settleNotice?.length ? { settleNotice: queued.settleNotice } : {}), // The item is consumed when the turn accepts its input, so what the run needs travels on the request. ...(queued.origin?.kind === 'schedule' ? { diff --git a/src/mms/orchestrator/settleNotices.ts b/src/mms/orchestrator/settleNotices.ts new file mode 100644 index 0000000000..3be1b35576 --- /dev/null +++ b/src/mms/orchestrator/settleNotices.ts @@ -0,0 +1,282 @@ +import { SETTLE_NOTICE_RESULT_CHARS, SETTLE_WATCH_TTL_MS, type SettleNoticeItem } from '../../shared/settleNotice' +import { threadLink } from '../../shared/threadLink' +import type { RunEngine } from '../run/RunEngine' +import { followMessage, type WatchTarget } from '../run/settle/follow' +import { ThreadWatches, type ThreadWatchRecord } from '../run/settle/ThreadWatches' +import type { ThreadEvent } from '../run/types' + +/** The longest a timer waits before it looks at the watches' expiry again (setTimeout holds 2^31 - 1 ms at most). */ +const EXPIRY_CHECK_MAX_MS = 60 * 60 * 1000 + +/** A notice as it goes into the sender's queue. */ +export interface PlannedSettleNotice { + item: SettleNoticeItem + /** What the sender's model reads. */ + text: string + /** The count of agent messages in a row of the run the notice is about; the turn it starts carries it. */ + hops: number +} + +export interface SettleNoticeHost { + engine: RunEngine + /** The target's runs and queue on this computer. */ + target: WatchTarget + titleOf(threadId: string): string | undefined + /** The thread exists and is not deleted. */ + threadLive(threadId: string): boolean + /** A question or an approval of the thread waits for a person. */ + waitingForPerson(threadId: string): boolean + /** The final text of a run, when it left one. */ + resultText(threadId: string, runId: string): string | undefined + stopGeneration(threadId: string): number + isSubagent(threadId: string): boolean + /** The thread's person works in Plan (its latest message is a plan turn). */ + inPlan(threadId: string): boolean + /** Puts the notice in the sender's queue; `held`: it must not start a turn by itself. Throws when it cannot. */ + deliver(watcherThreadId: string, notice: PlannedSettleNotice, held: boolean): void + /** The sender's queue already carries this notice (a delivery repeated after a restart). */ + delivered(watcherThreadId: string, item: Pick<SettleNoticeItem, 'watchId' | 'event'>): boolean + now?(): Date +} + +/** + * The settle notice on this computer (docs/run-engine/SPEC.md §15.1, "Told when it settles"). An agent that sends with + * `notify` gets one watch for its message (`thread_watches`); this service follows the message through the target's runs + * and queue (`followMessage`) and tells the sender at most twice: the first time the work waits on a person, and when it + * ends, or once, without starting a turn, when 24 hours pass first. The notice goes into the sender's queue (the host's + * `deliver`), so it starts a turn when the sender is idle and waits behind a running one; notices that meet there are + * delivered as one. Every decision is written to the watch before the notice is delivered, so a restart delivers what + * was decided and re-reads what it missed. + */ +export class SettleNotices { + readonly watches: ThreadWatches + private readonly checks = new Set<string>() + private checkScheduled = false + private expiryTimer: ReturnType<typeof setTimeout> | undefined + private unsubscribe: (() => void) | undefined + private stopped = false + + constructor(private readonly host: SettleNoticeHost) { + this.watches = new ThreadWatches(host.engine.store, () => this.now()) + } + + private now(): Date { + return this.host.now?.() ?? new Date() + } + + /** Starts following: what the previous daemon decided is delivered, every active watch is read again. */ + start(): void { + this.stopped = false + this.unsubscribe = this.host.engine.store.onEvent((event) => this.onEvent(event)) + for (const watch of this.watches.listDue()) this.deliverDue(watch) + for (const watch of this.watches.listActive()) this.checkWatch(watch) + this.expireDue() + } + + stop(): void { + this.stopped = true + this.unsubscribe?.() + this.unsubscribe = undefined + if (this.expiryTimer) clearTimeout(this.expiryTimer) + this.expiryTimer = undefined + } + + /** + * Watches the message `messageKey` an agent just sent (once: a retry of the same send keeps its watch). The message is + * read at once, so a run that ended before the watch existed is still told. + */ + watch(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string }): ThreadWatchRecord { + // A queued message keeps its queue item through an edit, a steer and a hand-back; its run may not. + const queued = this.host.target.queueItemForRun(input.targetThreadId, input.runId) + const { watch, created } = this.watches.create({ + ...input, + watcherStopGeneration: this.host.stopGeneration(input.watcherThreadId), + queueItemId: queued ?? null, + ttlMs: SETTLE_WATCH_TTL_MS + }) + if (created) { + this.checkWatch(watch) + this.armExpiry() + } + return this.watches.get(watch.watchId) ?? watch + } + + /** Something about the thread changed that may move or settle a watched message (its queue, a question). */ + touch(threadId: string): void { + if (this.stopped) return + this.checks.add(threadId) + if (this.checkScheduled) return + this.checkScheduled = true + setImmediate(() => { + this.checkScheduled = false + const threads = [...this.checks] + this.checks.clear() + if (this.stopped) return + for (const threadId of threads) { + try { + for (const watch of this.watches.listActive(threadId)) this.checkWatch(watch) + } catch (error) { + console.warn('the settle watches of a thread could not be read', { threadId, error: error instanceof Error ? error.message : String(error) }) + } + } + }) + } + + private onEvent(event: ThreadEvent): void { + if (event.type !== 'run.status' && event.type !== 'run.created') return + this.touch(event.threadId) + } + + /** Reads where the watch's message is now and tells the sender what it has not been told. */ + private checkWatch(watch: ThreadWatchRecord): void { + try { + if (watch.state !== 'active') return + if (!this.host.threadLive(watch.targetThreadId)) { + if (this.watches.markEnded(watch.watchId, 'deleted', watch.runId)) this.deliverDue(this.watches.get(watch.watchId)!) + return + } + const followed = followMessage(this.host.target, watch.targetThreadId, watch.runId, watch.queueItemId) + if (followed.kind === 'ended') { + if (this.watches.markEnded(watch.watchId, followed.status, followed.runId)) this.deliverDue(this.watches.get(watch.watchId)!) + return + } + if (followed.runId !== watch.runId) this.watches.follow(watch.watchId, followed.runId) + // The work waits on a person: a question or an approval of the thread while the message's run is its active one. + if (followed.kind === 'live' && watch.needsInput === null && this.host.waitingForPerson(watch.targetThreadId)) { + const active = this.host.target.activeRun(watch.targetThreadId) + if (active?.runId === followed.runId && this.watches.markNeedsInput(watch.watchId)) this.deliverDue(this.watches.get(watch.watchId)!) + } + } catch (error) { + console.warn('a settle watch could not be read', { watchId: watch.watchId, error: error instanceof Error ? error.message : String(error) }) + } + } + + /** Delivers what the watch decided and has not delivered yet. A failure leaves it due for the next start. */ + private deliverDue(watch: ThreadWatchRecord): void { + if (watch.needsInput === 'due') this.deliverOne(watch, 'needs_input') + if (watch.endNotice === 'due') this.deliverOne(watch, watch.state === 'expired' ? 'expired' : 'ended') + } + + private deliverOne(watch: ThreadWatchRecord, event: SettleNoticeItem['event']): void { + const which = event === 'needs_input' ? 'needs_input' : 'end' + try { + // A sender that is gone hears nothing; the decision is settled so it is not tried again. + if (!this.host.threadLive(watch.watcherThreadId) || this.host.delivered(watch.watcherThreadId, { watchId: watch.watchId, event })) { + this.watches.markSent(watch.watchId, which) + return + } + const notice = this.plan(watch, event) + this.host.deliver(watch.watcherThreadId, notice, this.held(watch, event)) + this.watches.markSent(watch.watchId, which) + } catch (error) { + console.warn('a settle notice could not be delivered', { watchId: watch.watchId, event, error: error instanceof Error ? error.message : String(error) }) + } + } + + /** + * A notice never starts a turn (it waits in the queue) in a subagent's thread, whose result is its parent's; in a + * sender a person stopped after it subscribed; in a sender kept in Plan; and when it only says Mousse stopped watching. + */ + private held(watch: ThreadWatchRecord, event: SettleNoticeItem['event']): boolean { + if (event === 'expired') return true + if (this.host.isSubagent(watch.watcherThreadId)) return true + if (this.host.stopGeneration(watch.watcherThreadId) > watch.watcherStopGeneration) return true + return this.host.inPlan(watch.watcherThreadId) + } + + private plan(watch: ThreadWatchRecord, event: SettleNoticeItem['event']): PlannedSettleNotice { + const run = watch.runId ? this.host.target.getRun(watch.runId) : null + return planSettleNotice({ + watch, + event, + title: this.host.titleOf(watch.targetThreadId) ?? null, + run: run ? { runId: run.runId, error: run.outcome?.error, hops: run.outcome?.agentHops ?? 0 } : undefined, + resultText: event === 'ended' && run ? this.host.resultText(watch.targetThreadId, run.runId) : undefined + }) + } + + /** Ends the watches whose 24 hours are over (each read once more first), and arms the timer for the next. The timer runs it. */ + expireDue(): void { + if (this.stopped) return + const now = this.now().getTime() + for (const watch of this.watches.listActive()) { + if (Date.parse(watch.expiresAt) > now) continue + this.checkWatch(watch) + const current = this.watches.get(watch.watchId) + if (current?.state === 'active' && this.watches.markExpired(watch.watchId)) this.deliverDue(this.watches.get(watch.watchId)!) + } + this.armExpiry() + } + + private armExpiry(): void { + if (this.stopped) return + if (this.expiryTimer) clearTimeout(this.expiryTimer) + this.expiryTimer = undefined + const next = this.watches.nextExpiry() + if (!next) return + const wait = Math.min(EXPIRY_CHECK_MAX_MS, Math.max(0, Date.parse(next) - this.now().getTime())) + this.expiryTimer = setTimeout(() => this.expireDue(), wait) + this.expiryTimer.unref?.() + } +} + +/** One line of a title: no line breaks, quotes or brackets, at most 80 characters. */ +function titleLine(title: string | null): string { + const line = (title ?? '').replace(/[\r\n"“”«»[\]]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 80).trim() + return line || 'Untitled' +} + +/** How a run's end reads: "finished", "failed: <error>", "was stopped". */ +function endPhrase(status: string, error: string | undefined): string { + switch (status) { + case 'completed': return 'finished' + case 'failed': + case 'uncertain': return error ? `failed: ${error.replace(/\s+/g, ' ').trim().slice(0, 300)}` : 'failed' + case 'interrupted': return 'was stopped before it finished' + case 'cancelled': return 'was cancelled before it finished' + case 'deleted': return 'ended: that thread was deleted' + case 'removed': return 'never ran: your message left that thread\'s queue first (a person removed it, or stopped the thread)' + default: return `ended (${status})` + } +} + +/** + * The notice Mousse writes for one event of a watch: who it is about (the thread's title and link), what happened, and + * for an end the run's reply cut to `SETTLE_NOTICE_RESULT_CHARS` with a pointer to `thread_read` for the rest. Written + * by Mousse from the watch and the run, never from either agent's words, except the quoted reply. + */ +export function planSettleNotice(input: { + watch: Pick<ThreadWatchRecord, 'watchId' | 'targetThreadId' | 'endStatus'> + event: SettleNoticeItem['event'] + title: string | null + run?: { runId: string; error?: string; hops: number } + resultText?: string +}): PlannedSettleNotice { + const { watch, event, run } = input + const thread = `thread "${titleLine(input.title)}" (${threadLink(watch.targetThreadId)})` + const base: SettleNoticeItem = { watchId: watch.watchId, threadId: watch.targetThreadId, title: input.title, event, ...(run ? { runId: run.runId } : {}) } + const hops = run?.hops ?? 0 + const header = '[Mousse notice, not from the user or any agent: about the message you sent with notify.]' + if (event === 'needs_input') { + return { + item: base, + hops, + text: `${header}\nThe work your message started in ${thread} is waiting for a person to answer a question or an approval there. Mousse will tell you again when it ends; do not call thread_wait or thread_read to check.` + } + } + if (event === 'expired') { + return { + item: base, + hops, + text: `${header}\nMousse stopped watching ${thread} for you after 24 hours. The work your message started there is still going; read it with thread_read when you need it.` + } + } + const status = watch.endStatus ?? 'completed' + const reply = input.resultText?.trim() ?? '' + const shown = reply.slice(0, SETTLE_NOTICE_RESULT_CHARS) + const cut = shown.length < reply.length + const lines = [`${header}\nThe work your message started in ${thread} ${endPhrase(status, run?.error)}${run && status !== 'removed' && status !== 'deleted' ? ` (run ${run.runId})` : ''}.`] + if (shown) lines.push(`Its reply:\n${shown}`) + if (cut) lines.push(`[The reply is cut at ${SETTLE_NOTICE_RESULT_CHARS.toLocaleString('en-US')} of ${reply.length.toLocaleString('en-US')} characters; read the rest with thread_read on thread ${watch.targetThreadId}.]`) + return { item: { ...base, status, ...(cut ? { cut: true } : {}) }, hops, text: lines.join('\n') } +} diff --git a/src/mms/queue/ThreadMessageQueue.ts b/src/mms/queue/ThreadMessageQueue.ts index c9d72e66fb..1b1dbd474b 100644 --- a/src/mms/queue/ThreadMessageQueue.ts +++ b/src/mms/queue/ThreadMessageQueue.ts @@ -12,6 +12,7 @@ import type { import { normalizeChatMode } from '../../shared/chatMode' import { isPermissionMode, type PermissionMode } from '../../shared/permissionMode' import { WORKFLOW_UUID_PATTERN } from '../../shared/workflows' +import { readSettleNotice, type SettleNoticeItem } from '../../shared/settleNotice' export interface EnqueueMessageInput { /** @@ -36,6 +37,9 @@ export interface EnqueueMessageInput { runId?: string inboxIds?: string[] subagentNotice?: QueuedMessage['subagentNotice'] + settleNotice?: SettleNoticeItem[] + settleHops?: number + heldNotice?: boolean stopGeneration?: number permissionMode?: PermissionMode origin?: QueuedMessage['origin'] @@ -250,6 +254,9 @@ export function normalizeQueuedMessages(raw: unknown, threadId?: string): Queued ...(typeof item.continuationOfRunId === 'string' && item.continuationOfRunId ? { continuationOfRunId: item.continuationOfRunId } : {}), ...(Array.isArray(item.inboxIds) && item.inboxIds.length && item.inboxIds.every((id) => typeof id === 'string') ? { inboxIds: item.inboxIds } : {}), ...(Array.isArray(item.subagentNotice) && item.subagentNotice.length ? { subagentNotice: item.subagentNotice } : {}), + ...(readSettleNotice(item.settleNotice) ? { settleNotice: readSettleNotice(item.settleNotice) } : {}), + ...(typeof item.settleHops === 'number' && Number.isSafeInteger(item.settleHops) && item.settleHops >= 0 ? { settleHops: item.settleHops } : {}), + ...(item.heldNotice === true && state === 'pending' ? { heldNotice: true as const } : {}), ...(typeof item.stopGeneration === 'number' && Number.isSafeInteger(item.stopGeneration) && item.stopGeneration >= 0 ? { stopGeneration: item.stopGeneration } : {}), ...(item.heldAfterStop === true ? { heldAfterStop: true as const } : {}), ...(item.waitsForLease === true && state === 'pending' && intent === 'normal' ? { waitsForLease: true as const } : {}), @@ -367,6 +374,8 @@ export function enqueueMessage( ...(input.continuationOfRunId ? { continuationOfRunId: input.continuationOfRunId } : {}), ...(input.inboxIds?.length ? { inboxIds: input.inboxIds } : {}), ...(input.subagentNotice?.length ? { subagentNotice: input.subagentNotice } : {}), + ...(input.settleNotice?.length ? { settleNotice: input.settleNotice, settleHops: input.settleHops ?? 0 } : {}), + ...(input.settleNotice?.length && input.heldNotice ? { heldNotice: true as const } : {}), ...(input.stopGeneration !== undefined ? { stopGeneration: input.stopGeneration } : {}), ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}), ...(input.sentFrom ? { sentFrom: input.sentFrom } : {}), @@ -559,8 +568,9 @@ export function claimNextNormal( owner: ClaimOwnerInput ): { items: QueuedMessage[]; claimed: QueuedMessage | null } { const pending = listPendingQueue(items) + // A held settle notice never starts a turn by itself (`QueuedMessage.heldNotice`). const next = - pending.find((item) => item.intent === 'normal' && item.state === 'pending') ?? null + pending.find((item) => item.intent === 'normal' && item.state === 'pending' && !item.heldNotice) ?? null if (!next) return { items: sortQueue(items), claimed: null } const claim: QueuedMessageClaim = { @@ -785,6 +795,84 @@ export function releaseStopHold(items: QueuedMessage[]): QueuedMessage[] { }) } +/** A settle notice to deliver through a thread's queue (`mergeSettleNotice`). */ +export interface SettleNoticeInput { + threadId: string + item: SettleNoticeItem + /** What the model reads for this notice. */ + text: string + /** The watched run's count of agent messages in a row. */ + hops: number + mode?: ChatMode + /** It must not start a turn by itself (`QueuedMessage.heldNotice`). */ + held: boolean +} + +/** The key of a notice: one watch writes each event once. */ +function settleKey(item: Pick<SettleNoticeItem, 'watchId' | 'event'>): string { + return `${item.watchId}:${item.event}` +} + +/** Whether the queue already carries the notice (a delivery repeated after a restart). */ +export function queueHasSettleNotice(items: readonly QueuedMessage[], item: Pick<SettleNoticeItem, 'watchId' | 'event'>): boolean { + const key = settleKey(item) + return items.some((entry) => entry.settleNotice?.some((notice) => settleKey(notice) === key)) +} + +/** + * Puts a settle notice in a thread's queue. Notices that arrive while one waits are delivered as one: a notice joins the + * waiting notice item (pending, not yet claimed), whose turn then carries the larger count of agent messages in a row, + * and which is held only while every notice in it is. Otherwise the notice is an item of its own at the back of the + * queue. A notice the queue already carries changes nothing. `merged` is the item that carries it. + */ +export function mergeSettleNotice(items: QueuedMessage[], input: SettleNoticeInput): { items: QueuedMessage[]; item: QueuedMessage; changed: boolean } { + const key = settleKey(input.item) + const carrying = items.find((entry) => entry.settleNotice?.some((notice) => settleKey(notice) === key)) + if (carrying) return { items, item: carrying, changed: false } + const waiting = items.find((entry) => entry.settleNotice?.length && entry.state === 'pending' && entry.intent === 'normal') + if (!waiting) { + const made = enqueueMessage(items, { + threadId: input.threadId, + content: input.text, + mode: input.mode, + source: SETTLE_NOTICE_SOURCE, + settleNotice: [input.item], + settleHops: input.hops, + heldNotice: input.held + }) + return { ...made, changed: true } + } + const { heldNotice: _held, ...rest } = waiting + const joined: QueuedMessage = { + ...rest, + content: `${waiting.content}\n\n${input.text}`, + settleNotice: [...(waiting.settleNotice ?? []), input.item], + settleHops: Math.max(waiting.settleHops ?? 0, input.hops), + ...(waiting.heldNotice && input.held ? { heldNotice: true as const } : {}) + } + return { items: items.map((entry) => (entry.id === waiting.id ? joined : entry)), item: joined, changed: true } +} + +/** The source of a queue item, and of the turn it starts, that delivers settle notices. */ +export const SETTLE_NOTICE_SOURCE = 'thread-notice' + +/** Held settle notices go on: each runs after the turn that is starting, as a turn of its own. */ +export function releaseHeldNotices(items: QueuedMessage[]): QueuedMessage[] { + if (!items.some((item) => item.heldNotice)) return items + return items.map((item) => { + if (!item.heldNotice) return item + const { heldNotice: _held, ...rest } = item + return rest + }) +} + +/** Takes the held settle notices out of the queue: their texts and what is left (`continue_subagent` carries them). */ +export function takeHeldNotices(items: QueuedMessage[]): { items: QueuedMessage[]; taken: QueuedMessage[] } { + const taken = items.filter((item) => item.heldNotice && item.state === 'pending') + if (taken.length === 0) return { items, taken } + return { items: items.filter((item) => !taken.includes(item)), taken } +} + /** Whether a Stop holds the queue: some waiting item is still marked `heldAfterStop`. */ export function isQueueHeldByStop(items: QueuedMessage[]): boolean { return listPendingQueue(items).some((item) => item.heldAfterStop === true) diff --git a/src/mms/run/RunEngine.ts b/src/mms/run/RunEngine.ts index 1d56b78dc3..df76550142 100644 --- a/src/mms/run/RunEngine.ts +++ b/src/mms/run/RunEngine.ts @@ -95,6 +95,11 @@ export type RunCommand = agentOrigin?: { hops: number } /** A person's leftover steer queued as a turn of its own (`RunOutcome.sentByPerson`). */ sentByPerson?: true + /** + * The run delivers settle notices (SPEC §15.1): it carries the count of agent messages in a row of the runs the + * notices are about and adds none of its own. It is not an agent's message. + */ + noticeHops?: number /** * A person's message that waits behind a usage-limit pause instead of ending it: on a paused thread the run * is created `queued`, the pause and its timer stay, and the result says so (`heldByPause`). The sender @@ -1991,7 +1996,11 @@ export class RunEngine extends EventEmitter { const continuationOf = command.continuationOfRunId // A run that carries on agent work (a provider's continuation, the resume after a pause) keeps the count of agent // messages in a row; it is not itself an agent's message. - const carriedHops = command.actor || command.agentOrigin ? undefined : inheritedAgentHops(store, command.threadId, command.source, continuationOf) + const carriedHops = command.actor || command.agentOrigin + ? undefined + : command.noticeHops !== undefined + ? (command.noticeHops > 0 ? command.noticeHops : undefined) + : inheritedAgentHops(store, command.threadId, command.source, continuationOf) const outcome: RunOutcome = { ...(continuationOf ? { continuationOf, ...(resuming ? { resumedFromPause: command.source === 'resume' ? 'auto' as const : 'user' as const } : {}) } : {}), // Remembered with the run, so a message an agent sent is still known as one when it starts later. diff --git a/src/mms/run/db/migrations.ts b/src/mms/run/db/migrations.ts index 8d7f8687b3..8946f9d3a5 100644 --- a/src/mms/run/db/migrations.ts +++ b/src/mms/run/db/migrations.ts @@ -11,7 +11,9 @@ import type { Migration } from './ProfileDatabase' * generations); version 9 stores each attempt's execution binding (harness gateway); version 10 * rebuilds `runs` so a run can be `paused` until a usage limit resets; version 11 records the agent * access level on credentials, delegations and runs; version 17 binds a remote subagent's task to the - * run on another computer that does it (issue #469); version 18 lets that task's mode be Full access. + * run on another computer that does it (issue #469); version 18 lets that task's mode be Full access; version 19 + * records whether a remote subagent's calls carry the agent mark; version 20 keeps the watches of the settle notice (an + * agent that sent a message with `notify` is told when the work it started settles, SPEC §15.1). */ export const RUN_MIGRATIONS: readonly Migration[] = [ { @@ -594,6 +596,41 @@ CREATE INDEX remote_subagents_child ON remote_subagents(child_thread_id); -- computer knows it), 0 when they go unmarked (an older computer), null until the first call decides. A task never -- changes form mid-flight: the other computer's replay ledger is keyed by method, so a switch would send it twice. ALTER TABLE remote_subagents ADD COLUMN marked INTEGER CHECK(marked IS NULL OR marked IN (0,1)); +` + }, + { + version: 20, + sql: ` +-- The settle notice (SPEC §15.1): one row per message an agent sent with notify (thread_send, thread_create's first +-- message). It follows the message, not a run: run_id is the run that carries it now (a re-queue, a steer handed +-- back or a pause continuation moves it) and queue_item_id the queue item that carried it, when it was queued. +-- target_node is null for a thread on this computer; how a watch learns about its run is not stored here, so a +-- follower for another computer adds no column. +-- active: still followed; +-- ended: the work ended (end_status says how) and the end notice is written; +-- expired: 24 h passed first (expires_at) and the sender was told once that the work is still going. +-- needs_input and end_notice: 'due' once Mousse decided to tell the sender, 'sent' once the notice is in the sender's +-- queue, so a restart in between delivers it. +CREATE TABLE thread_watches( + watch_id TEXT PRIMARY KEY, + message_key TEXT NOT NULL UNIQUE, + watcher_thread_id TEXT NOT NULL, + watcher_run_id TEXT NOT NULL, + watcher_stop_generation INTEGER NOT NULL, + target_node TEXT, + target_thread_id TEXT NOT NULL, + run_id TEXT, + queue_item_id TEXT, + state TEXT NOT NULL CHECK(state IN ('active','ended','expired')), + needs_input TEXT CHECK(needs_input IN ('due','sent')), + end_notice TEXT CHECK(end_notice IN ('due','sent')), + end_status TEXT, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + updated_at TEXT NOT NULL +) STRICT; +CREATE INDEX thread_watches_state ON thread_watches(state, target_thread_id); +CREATE INDEX thread_watches_watcher ON thread_watches(watcher_thread_id); ` } ] diff --git a/src/mms/run/delegation/sources.ts b/src/mms/run/delegation/sources.ts index 40b632afd2..642b51fcf1 100644 --- a/src/mms/run/delegation/sources.ts +++ b/src/mms/run/delegation/sources.ts @@ -51,9 +51,10 @@ export function isFencedSource(source: string | null | undefined): boolean { * is not a person's message, so on a thread paused by a usage limit it neither ends the pause nor * restarts its chain of automatic resumes: `commitSend` refuses it (`thread_paused`), and one that was * admitted before the pause waits (`markStarting` refuses it) until the pause has ended on its own. A - * message another thread's agent sends is held the same way (agent sends). + * message another thread's agent sends is held the same way (agent sends), and so is the turn that delivers a settle + * notice (`thread-notice`). */ -export const PAUSE_HELD_SOURCES: ReadonlySet<string> = new Set(['schedule']) +export const PAUSE_HELD_SOURCES: ReadonlySet<string> = new Set(['schedule', 'thread-notice']) export function isPauseHeldSource(source: string | null | undefined): boolean { return source !== null && source !== undefined && PAUSE_HELD_SOURCES.has(source) diff --git a/src/mms/run/mcp/appTools/agentMessage.ts b/src/mms/run/mcp/appTools/agentMessage.ts index d2978f85a8..971fab844e 100644 --- a/src/mms/run/mcp/appTools/agentMessage.ts +++ b/src/mms/run/mcp/appTools/agentMessage.ts @@ -8,8 +8,8 @@ const TITLE_MAX_CHARS = 80 * notice Mousse wrote. Only such a message answers a plan waiting for review, and only such a message, when it started * the manager's current turn, is what the Automation manager takes as the person's request (`personTurnRequest`). */ -export function isPersonMessage(message: Pick<ChatMessage, 'role' | 'content' | 'origin' | 'scheduled' | 'subagentNotice' | 'backgroundNotice'>): boolean { - if (message.role !== 'user' || message.origin || message.scheduled || message.subagentNotice || message.backgroundNotice) return false +export function isPersonMessage(message: Pick<ChatMessage, 'role' | 'content' | 'origin' | 'scheduled' | 'subagentNotice' | 'backgroundNotice' | 'settleNotice'>): boolean { + if (message.role !== 'user' || message.origin || message.scheduled || message.subagentNotice || message.backgroundNotice || message.settleNotice) return false // A message stored before it carried its sender is still labelled in its text. const text = typeof message.content === 'string' ? message.content.trimStart() : '' return !text.startsWith(AGENT_MESSAGE_PREFIX) && !text.startsWith(BOT_MESSAGE_PREFIX) diff --git a/src/mms/run/mcp/appTools/host.ts b/src/mms/run/mcp/appTools/host.ts index a27c7e5533..0a9c730251 100644 --- a/src/mms/run/mcp/appTools/host.ts +++ b/src/mms/run/mcp/appTools/host.ts @@ -304,6 +304,12 @@ export interface AppToolHost extends DelegationToolsHost { * when the key made none. A retry past the send cap is answered with it. */ earlierSend?(threadId: string, clientRequestId: string): AgentSendResult | undefined + /** + * Watches the message `messageKey` sent to `targetThreadId` (`notify` on `thread_send` and `thread_create`): Mousse + * tells the sending thread when the work it started waits on a person (once) and when it ends (SPEC §15.1). Once per + * message: a retry keeps its watch. + */ + watchSettle?(input: { messageKey: string; watcherThreadId: string; watcherRunId: string; targetThreadId: string; runId: string }): { watchId: string } /** * Creates a thread for `actor` (`thread_create`): in the project's folder or its own worktree, on the model * asked for or the caller's, with a permission mode no wider than the caller's, recorded as launched by the diff --git a/src/mms/run/mcp/appTools/thread.ts b/src/mms/run/mcp/appTools/thread.ts index c97ce476d5..22b34dd29e 100644 --- a/src/mms/run/mcp/appTools/thread.ts +++ b/src/mms/run/mcp/appTools/thread.ts @@ -63,6 +63,21 @@ const THREAD_SEND_TRACKED_RUNS = 1000 export const THREAD_CREATE_MAX_PER_RUN = 5 /** A creator thread may have this many launched threads working (a queued, running or paused run) at once, however many runs it has; the next creation is refused. */ export const THREAD_CREATE_MAX_ACTIVE_PER_THREAD = 10 +/** What a tool result says next when the caller asked to be told (`notify`), so it ends its turn instead of polling. */ +export const NOTIFY_NEXT = 'Mousse will tell you when it settles. Do not call thread_wait or thread_read to check. End your turn when nothing else is left.' +const NOTIFY_SCHEMA = { + type: 'boolean', + description: 'Set it when you need the result: Mousse tells you when the work this message starts ends, and once before that if it waits for a person. Your turn then needs no thread_wait.' +} as const + +/** `notify` read from a call's arguments; a personal bot hears with thread_wait instead. */ +function notifyArg(args: Record<string, unknown>, ctx: ToolCallContext): boolean { + if (args.notify === undefined || args.notify === false) return false + if (args.notify !== true) throw new Error('notify must be true or false') + if (ctx.turn.bot) throw new Error('notify is not available to a personal bot: use thread_wait.') + return true +} + /** A new thread's title is cut to this many characters. */ const THREAD_TITLE_MAX_CHARS = 200 /** The first message of a new thread is held to the size of a message a person could send in one go. */ @@ -612,6 +627,14 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B const projectName = (projectId: string | undefined): string | null => (projectId && host.listProjects?.().find((project) => project.id === projectId)?.name) || null const titleOf = (threadId: string): string | undefined => host.threadMeta?.(threadId)?.name + /** + * `notify`: one watch for the message sent with `messageKey` (a retry keeps it), and what the result says next. The + * sender's turn is told to end rather than poll; Mousse writes the notice into its queue (SPEC §15.1). + */ + const watchSent = (threadId: string, messageKey: string, actor: AgentActor, runId: string, ctx: ToolCallContext): { notify: { watchId: string; next: string } } => { + const { watchId } = host.watchSettle!({ messageKey, watcherThreadId: ctx.caller.threadId, watcherRunId: actor.runId, targetThreadId: threadId, runId }) + return { notify: { watchId, next: NOTIFY_NEXT } } + } /** Messages each run has sent to other threads, in memory: a restart gives every run a fresh count. */ const sends = new Map<string, number>() const reserveSend = (runId: string): void => { @@ -959,13 +982,14 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_send', - description: `Send a message to another thread. The thread's model receives it labelled as a message from an agent in your thread, not from the user, and runs it under your permission mode when that is stricter than the thread's own; it never gets more than the thread itself allows. It starts a turn when the thread is idle and queues behind the running turn otherwise (it never steers the running turn). A thread kept in Plan takes it as a plan turn. Refused while the thread waits for the user to answer a question or approval, is paused by a usage limit, or is archived, when it already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread or ${AGENT_QUEUE_MAX_PER_THREAD} from agents in all waiting, when you sent it the same text in the last ${AGENT_REPEAT_WINDOW_MS / 60_000} minutes, and when it would be more than a few agent messages in a row without a person in between; each refusal names its limit (data.conflict). You may send ${THREAD_SEND_MAX_PER_RUN} messages per run (a personal bot has no such count). Returns the run it created and delivery: started (a turn began with it) or queued (it waits behind the running turn): use thread_wait with it to wait for the answer, only when you need it this turn. Subagents are reached with continue_subagent.`, + description: `Send a message to another thread. The thread's model receives it labelled as a message from an agent in your thread, not from the user, and runs it under your permission mode when that is stricter than the thread's own; it never gets more than the thread itself allows. It starts a turn when the thread is idle and queues behind the running turn otherwise (it never steers the running turn). A thread kept in Plan takes it as a plan turn. Refused while the thread waits for the user to answer a question or approval, is paused by a usage limit, or is archived, when it already has ${AGENT_QUEUE_MAX_PER_SENDER} messages from your thread or ${AGENT_QUEUE_MAX_PER_THREAD} from agents in all waiting, when you sent it the same text in the last ${AGENT_REPEAT_WINDOW_MS / 60_000} minutes, and when it would be more than a few agent messages in a row without a person in between; each refusal names its limit (data.conflict). You may send ${THREAD_SEND_MAX_PER_RUN} messages per run (a personal bot has no such count). Set notify when you need the result: Mousse then tells you when the work settles (and once before that if it waits for a person), and you end your turn instead of waiting. Returns the run it created and delivery: started (a turn began with it) or queued (it waits behind the running turn). Subagents are reached with continue_subagent.`, inputSchema: { type: 'object', properties: { threadId: { type: 'string', description: 'The thread to send to; not your own (use queue_enqueue for that).' }, content: { type: 'string' }, mode: { type: 'string', enum: ['agent', 'plan'], description: 'Defaults to agent.' }, + notify: NOTIFY_SCHEMA, clientRequestId: CLIENT_REQUEST_ID_SCHEMA }, required: ['threadId', 'content'] @@ -978,7 +1002,9 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (typeof args.content !== 'string' || !args.content.trim()) throw new Error('thread_send requires content') if (args.mode !== undefined && args.mode !== 'agent' && args.mode !== 'plan') throw new Error('mode must be agent or plan') const mode = (args.mode as 'agent' | 'plan' | undefined) ?? 'agent' + const notify = notifyArg(args, ctx) if (!host.sendToThread) return notAvailable('thread_send') + if (notify && !host.watchSettle) return notAvailable('thread_send with notify') if (threadId === ctx.caller.threadId) throw new Error('thread_send is for other threads; use queue_enqueue to queue a message on your own thread.') if (mode === 'agent' && ctx.caller.modeCeiling === 'plan') throw new McpToolError('mousse_ceiling_exceeded', 'A plan-ceiling caller can only send plan turns.') // A personal bot reaches only what it may (`botThreadReach`: never a subagent, a bot's, a private thread or the @@ -1000,7 +1026,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B } catch (limit) { // A retry of a send this run already made is answered with its first result, however many it has made. const earlier = host.earlierSend?.(threadId, requestKey) - if (earlier) return json({ threadId, ...earlier, delivery: deliveryOf(earlier) }) + if (earlier) return json({ threadId, ...earlier, delivery: deliveryOf(earlier), ...(notify ? watchSent(threadId, requestKey, actor, earlier.runId, ctx) : {}) }) throw limit } let sent @@ -1020,12 +1046,12 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (!sent.replayed) botChip(bot, 'thread_send', threadId, title, args.content) return json({ threadId, title: title ?? null, ...sent, delivery: deliveryOf(sent), note: 'It runs in that thread\'s own mode. Approvals and questions there wait for your owner, never for you.' }) } - return json({ threadId, ...sent, delivery: deliveryOf(sent) }) + return json({ threadId, ...sent, delivery: deliveryOf(sent), ...(notify ? watchSent(threadId, requestKey, actor, sent.runId, ctx) : {}) }) } }, { name: 'thread_wait', - description: `Wait for a run of another thread to finish, for at most timeoutMs (default ${THREAD_WAIT_DEFAULT_MS}, up to ${THREAD_WAIT_MAX_MS}). Pass the runId thread_send returned; without one, the run that is active now. Returns status finished (with the run's outcome, and its final text where you may read it, cut to ${THREAD_RESULT_MAX_CHARS} characters with resultTruncated when longer), timeout (the run is still going: call again; the wait never interrupts it), paused (a usage limit paused the run and it was still paused when the wait ran out: it resumes by itself, and the result says when to ask again; a wait that is running when it resumes follows it into the run that continues it), idle (no run to wait for) or caller_ended (your own run ended). Wait only when you need the answer this turn; otherwise end your turn and read the thread later.`, + description: `Wait for a run of another thread to finish, for at most timeoutMs (default ${THREAD_WAIT_DEFAULT_MS}, up to ${THREAD_WAIT_MAX_MS}). Pass the runId thread_send returned; without one, the run that is active now. Returns status finished (with the run's outcome, and its final text where you may read it, cut to ${THREAD_RESULT_MAX_CHARS} characters with resultTruncated when longer), timeout (the run is still going: call again; the wait never interrupts it), paused (a usage limit paused the run and it was still paused when the wait ran out: it resumes by itself, and the result says when to ask again; a wait that is running when it resumes follows it into the run that continues it), idle (no run to wait for) or caller_ended (your own run ended). Use it only when this turn cannot continue without the answer; to hear about the result later, send with notify instead and end your turn.`, inputSchema: { type: 'object', properties: { @@ -1380,7 +1406,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B }, { name: 'thread_create', - description: `Start a new thread in a project. Where the thread works is decided by the project, not by workspace: on a Git project a turn that edits gets a worktree of its own, and on any other project the thread works in the project folder (the result's runsIn says which). workspace "new_worktree" records the thread as a worktree thread and is refused on a project that is not Git-backed; "project" (default) records it as an ordinary project thread; "existing_worktree" is not supported. instanceId and model name the thread's model together, and effort its reasoning level (take them from list_models; the person sees your choice); without them the thread uses your own model, or the profile's default when you have none. A model that is not offered in the project, or an agent that is signed out, is refused with the reason and no thread is made: tell the user, never pick another yourself. The thread runs in a permission mode no wider than yours, which a later change of the profile's default does not widen. It is recorded as launched by your thread: you can read it, wait on it and interrupt it afterwards, a person's Stop of your thread also stops it while it runs work you started, and it is not nested under yours. firstMessage (with mode agent or plan) is sent to it as a message from you, so it starts at once; it counts toward the limit on agent messages in a row without a person in between. You may create ${THREAD_CREATE_MAX_PER_RUN} threads per run (a personal bot has no such count), and have at most ${THREAD_CREATE_MAX_ACTIVE_PER_THREAD} launched threads working at once. Pass a clientRequestId and reuse it to retry: the same thread comes back, never a second one, and a first message that was not sent is sent. Returns the thread's id, the model, mode and place it got, and what became of the first message; use thread_wait with its run id to wait for the answer, only when you need it this turn. A personal bot gives a title and a firstMessage, names the model with instanceId and model from thread_list's models (else the profile's default, never its own model), and its thread runs in Full access: it runs commands and changes files without asking.`, + description: `Start a new thread in a project. Where the thread works is decided by the project, not by workspace: on a Git project a turn that edits gets a worktree of its own, and on any other project the thread works in the project folder (the result's runsIn says which). workspace "new_worktree" records the thread as a worktree thread and is refused on a project that is not Git-backed; "project" (default) records it as an ordinary project thread; "existing_worktree" is not supported. instanceId and model name the thread's model together, and effort its reasoning level (take them from list_models; the person sees your choice); without them the thread uses your own model, or the profile's default when you have none. A model that is not offered in the project, or an agent that is signed out, is refused with the reason and no thread is made: tell the user, never pick another yourself. The thread runs in a permission mode no wider than yours, which a later change of the profile's default does not widen. It is recorded as launched by your thread: you can read it, wait on it and interrupt it afterwards, a person's Stop of your thread also stops it while it runs work you started, and it is not nested under yours. firstMessage (with mode agent or plan) is sent to it as a message from you, so it starts at once; it counts toward the limit on agent messages in a row without a person in between. You may create ${THREAD_CREATE_MAX_PER_RUN} threads per run (a personal bot has no such count), and have at most ${THREAD_CREATE_MAX_ACTIVE_PER_THREAD} launched threads working at once. Pass a clientRequestId and reuse it to retry: the same thread comes back, never a second one, and a first message that was not sent is sent. Returns the thread's id, the model, mode and place it got, and what became of the first message; set notify with a firstMessage when you need the result: Mousse then tells you when the work settles (and once before that if it waits for a person), and you end your turn instead of waiting. A personal bot gives a title and a firstMessage, names the model with instanceId and model from thread_list's models (else the profile's default, never its own model), and its thread runs in Full access: it runs commands and changes files without asking.`, inputSchema: { type: 'object', properties: { @@ -1393,6 +1419,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B firstMessage: { type: 'string', description: 'Sent to the new thread as your message, so it starts working.' }, mode: { type: 'string', enum: ['agent', 'plan'], description: 'The mode of firstMessage; defaults to agent.' }, hidden: { type: 'boolean', description: 'Personal bots only. true keeps the thread out of your owner\'s sidebar: your chat lists it, and your owner opens it or shows it in the sidebar from there. Hide short background jobs your owner will not follow (a quick check, a lookup, a cleanup); leave visible work your owner will want to follow, answer or continue. thread_hide changes it later. Defaults to false.' }, + notify: { ...NOTIFY_SCHEMA, description: `${NOTIFY_SCHEMA.description} Needs a firstMessage.` }, clientRequestId: CLIENT_REQUEST_ID_SCHEMA }, required: ['projectId'] @@ -1443,6 +1470,9 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B if (args.hidden !== undefined && typeof args.hidden !== 'boolean') throw new Error('hidden must be true or false') // Only a bot's chat lists the threads it started, so only a bot's thread can be hidden and still be found. if (args.hidden === true && !bot) throw new Error('hidden is for personal bots: a thread an agent starts always shows in the sidebar.') + const notify = notifyArg(args, ctx) + if (notify && args.firstMessage === undefined) throw new Error('notify tells you when the work of firstMessage settles: give a firstMessage, or leave notify out.') + if (notify && !host.watchSettle) return notAvailable('thread_create with notify') const request: AgentThreadRequest = { projectId, ...(title ? { title } : {}), @@ -1507,7 +1537,9 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B console.warn('the creator\'s note of a launched thread could not be written', { error: error instanceof Error ? error.message : String(error) }) } } - return json({ ...created, link: threadLink(created.threadId) }) + // The first message's work is watched once it was sent; one that was not sent has nothing to watch yet (a retry sends it). + const watched = notify && created.firstMessage?.sent === true ? watchSent(created.threadId, requestKey, actor, created.firstMessage.runId, ctx) : {} + return json({ ...created, link: threadLink(created.threadId), ...watched }) } }, { diff --git a/src/mms/run/mcp/instructions.ts b/src/mms/run/mcp/instructions.ts index 8114c0ee06..c5f8fc0cb7 100644 --- a/src/mms/run/mcp/instructions.ts +++ b/src/mms/run/mcp/instructions.ts @@ -16,7 +16,7 @@ export function mousseOrchestrationInstructions(): string { '- Use ask_user for clarifying questions; use thread_read to read your thread\'s run events (and those of your parent or children).', '- thread_list and thread_search find any thread of the profile and thread_read reads it, at most 64 KB per call and 4,096 characters per message (it says how to read on). Each thread they return has a link (mousse://thread/<id>): put it in a reply and the user can click it to open that thread.', '- thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person\'s Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one.', - '- thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread\'s, and is limited to 20 messages per run; its result\'s delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. Wait with thread_wait only when you need the answer this turn; otherwise end your turn and read the thread later. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent\'s. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict.', + '- thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread\'s, and is limited to 20 messages per run; its result\'s delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. When you need the result of a thread_send or a thread_create firstMessage, set notify: Mousse tells you when the work it started ends, and once before that if it waits for a person; then do not call thread_wait or thread_read to check, and end your turn when nothing else is left. A notice that starts with "[Mousse notice" is written by Mousse, not by the user or any agent. Use thread_wait only when this turn cannot continue without the answer. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent\'s. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict.', '- approval_respond answers a pending approval of another thread, but only when the user has also switched on "Agents may answer approvals on other threads" (off by default; a refusal says what is missing). Read the request first with thread_list. Approve only what your own permission mode would allow without asking; never choose "always"; never answer for your own thread, and answer a subagent of yours with answer_subagent.', '- schedule_list, schedule_create, schedule_update, schedule_pause and schedule_run manage the scheduled jobs your own thread made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits. Creating, starting or changing what a job does works only in a turn the user started (not from a job, another agent, a subagent or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job\'s prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job.', '- queue_list, queue_edit, queue_remove, queue_reorder and queue_promote_to_steer work on the messages queued on your thread or another thread. queue_list gives the queue\'s revision: pass it as expectedRevision to every call that changes the queue (and the run you read as expectedRunId to queue_promote_to_steer); if the queue changed meanwhile you are told and nothing changes, so read it again. What you write into a queue is labelled as yours, runs under your permission mode when that is stricter than the message\'s, and counts toward the few agent messages a thread keeps waiting; a removal is recorded with its text. queue_promote_to_steer is refused while the user has a question or approval waiting. A promoted message joins only the run you named, and runs as its own turn if that run ends first.', diff --git a/src/mms/run/settle/ThreadWatches.ts b/src/mms/run/settle/ThreadWatches.ts new file mode 100644 index 0000000000..b7992c9827 --- /dev/null +++ b/src/mms/run/settle/ThreadWatches.ts @@ -0,0 +1,176 @@ +import { randomUUID } from 'node:crypto' +import { int, str, type Row } from '../db/rows' +import type { RunStore } from '../RunStore' + +/** + * The watches of the settle notice (SPEC §15.1, table `thread_watches`, migration 20): one per message an agent sent + * with `notify`. A watch is keyed on the message (`messageKey`, the send's request key), not on a run: `runId` is the + * run that carries the message now and moves with it. What a watch is about (`targetThreadId`, and `targetNode` for a + * thread on another computer) is kept apart from how it learns about that thread, which is the follower's. + */ + +export type ThreadWatchState = 'active' | 'ended' | 'expired' +export type NoticeDelivery = 'due' | 'sent' + +export interface ThreadWatchRecord { + watchId: string + messageKey: string + watcherThreadId: string + watcherRunId: string + /** The sender's stop generation when it subscribed: a Stop of the sender after it means no notice starts a turn there. */ + watcherStopGeneration: number + /** Null for a thread on this computer. */ + targetNode: string | null + targetThreadId: string + /** The run that carries the message now; null only while a re-queued message waits for its run. */ + runId: string | null + /** The queue item that carried the message, when it was queued (it keeps its id through an edit, a steer and a hand-back). */ + queueItemId: string | null + state: ThreadWatchState + needsInput: NoticeDelivery | null + endNotice: NoticeDelivery | null + /** How the work ended: a run status, `removed` when the message left the queue before it ran, or `deleted`. */ + endStatus: string | null + createdAt: string + expiresAt: string + updatedAt: string +} + +export interface NewThreadWatch { + messageKey: string + watcherThreadId: string + watcherRunId: string + watcherStopGeneration: number + targetNode?: string | null + targetThreadId: string + runId: string + queueItemId?: string | null + ttlMs: number +} + +function toWatch(row: Row): ThreadWatchRecord { + return { + watchId: String(row.watch_id), + messageKey: String(row.message_key), + watcherThreadId: String(row.watcher_thread_id), + watcherRunId: String(row.watcher_run_id), + watcherStopGeneration: int(row.watcher_stop_generation) ?? 0, + targetNode: str(row.target_node), + targetThreadId: String(row.target_thread_id), + runId: str(row.run_id), + queueItemId: str(row.queue_item_id), + state: String(row.state) as ThreadWatchState, + needsInput: str(row.needs_input) as NoticeDelivery | null, + endNotice: str(row.end_notice) as NoticeDelivery | null, + endStatus: str(row.end_status), + createdAt: String(row.created_at), + expiresAt: String(row.expires_at), + updatedAt: String(row.updated_at) + } +} + +export class ThreadWatches { + constructor(private readonly store: RunStore, private readonly now: () => Date = () => new Date()) {} + + /** The watch of `messageKey`, made once: a retry of the same send gets the watch it already has. */ + create(input: NewThreadWatch): { watch: ThreadWatchRecord; created: boolean } { + return this.store.db.transaction(() => { + const existing = this.byMessageKey(input.messageKey) + if (existing) return { watch: existing, created: false } + const now = this.now() + const at = now.toISOString() + this.store.db + .statement( + `INSERT INTO thread_watches(watch_id, message_key, watcher_thread_id, watcher_run_id, watcher_stop_generation, + target_node, target_thread_id, run_id, queue_item_id, state, created_at, expires_at, updated_at) + VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)` + ) + .run( + `watch:${randomUUID()}`, + input.messageKey, + input.watcherThreadId, + input.watcherRunId, + input.watcherStopGeneration, + input.targetNode ?? null, + input.targetThreadId, + input.runId, + input.queueItemId ?? null, + at, + new Date(now.getTime() + input.ttlMs).toISOString(), + at + ) + return { watch: this.byMessageKey(input.messageKey)!, created: true } + }) + } + + get(watchId: string): ThreadWatchRecord | null { + const row = this.store.db.statement('SELECT * FROM thread_watches WHERE watch_id = ?').get(watchId) + return row ? toWatch(row) : null + } + + byMessageKey(messageKey: string): ThreadWatchRecord | null { + const row = this.store.db.statement('SELECT * FROM thread_watches WHERE message_key = ?').get(messageKey) + return row ? toWatch(row) : null + } + + /** Active watches on this computer's threads, optionally of one target thread, oldest first. */ + listActive(targetThreadId?: string): ThreadWatchRecord[] { + const rows = targetThreadId + ? this.store.db.statement(`SELECT * FROM thread_watches WHERE state = 'active' AND target_node IS NULL AND target_thread_id = ? ORDER BY created_at, rowid`).all(targetThreadId) + : this.store.db.statement(`SELECT * FROM thread_watches WHERE state = 'active' AND target_node IS NULL ORDER BY created_at, rowid`).all() + return rows.map(toWatch) + } + + /** Watches with a notice decided but not yet in the sender's queue (a restart in between). */ + listDue(): ThreadWatchRecord[] { + return this.store.db + .statement(`SELECT * FROM thread_watches WHERE needs_input = 'due' OR end_notice = 'due' ORDER BY updated_at, rowid`) + .all() + .map(toWatch) + } + + /** The earliest expiry of an active watch, or undefined. */ + nextExpiry(): string | undefined { + const row = this.store.db.statement(`SELECT MIN(expires_at) AS at FROM thread_watches WHERE state = 'active'`).get() + return str(row?.at) ?? undefined + } + + /** The run (and queue item) that carries the message now. */ + follow(watchId: string, runId: string | null, queueItemId?: string | null): void { + this.store.db + .statement(`UPDATE thread_watches SET run_id = ?, queue_item_id = COALESCE(?, queue_item_id), updated_at = ? WHERE watch_id = ? AND state = 'active'`) + .run(runId, queueItemId ?? null, this.now().toISOString(), watchId) + } + + /** Decides the needs-input notice, once per watch: false when it was decided before or the watch is over. */ + markNeedsInput(watchId: string): boolean { + const result = this.store.db + .statement(`UPDATE thread_watches SET needs_input = 'due', updated_at = ? WHERE watch_id = ? AND state = 'active' AND needs_input IS NULL`) + .run(this.now().toISOString(), watchId) + return Number(result.changes) > 0 + } + + /** Ends the watch with its end notice due, once: false when it had ended or expired already. */ + markEnded(watchId: string, status: string, runId: string | null): boolean { + const result = this.store.db + .statement(`UPDATE thread_watches SET state = 'ended', end_status = ?, run_id = COALESCE(?, run_id), end_notice = 'due', updated_at = ? WHERE watch_id = ? AND state = 'active'`) + .run(status, runId, this.now().toISOString(), watchId) + return Number(result.changes) > 0 + } + + /** Ends the watch because 24 h passed, with its notice due, once. */ + markExpired(watchId: string): boolean { + const result = this.store.db + .statement(`UPDATE thread_watches SET state = 'expired', end_notice = 'due', updated_at = ? WHERE watch_id = ? AND state = 'active'`) + .run(this.now().toISOString(), watchId) + return Number(result.changes) > 0 + } + + /** The notice is in the sender's queue (or the sender is gone and nobody will read it). */ + markSent(watchId: string, which: 'needs_input' | 'end'): void { + const column = which === 'needs_input' ? 'needs_input' : 'end_notice' + this.store.db + .statement(`UPDATE thread_watches SET ${column} = 'sent', updated_at = ? WHERE watch_id = ? AND ${column} = 'due'`) + .run(this.now().toISOString(), watchId) + } +} diff --git a/src/mms/run/settle/follow.ts b/src/mms/run/settle/follow.ts new file mode 100644 index 0000000000..93ca707ed5 --- /dev/null +++ b/src/mms/run/settle/follow.ts @@ -0,0 +1,78 @@ +import type { QueuedMessage } from '../../../shared/types' +import { TERMINAL_RUN_STATUSES, type RunRecord } from '../types' + +/** + * How a watch learns where the message it follows is now, on this computer: the target thread's runs and queue. A + * follower for a thread on another computer answers the same questions from there. + */ +export interface WatchTarget { + getRun(runId: string): RunRecord | null + /** The run that continues `runId` after a usage-limit pause (`outcome.continuationOf`). */ + continuationOf(threadId: string, runId: string): RunRecord | undefined + /** The newest run the queue made for item `itemId` (client request `queue:<itemId>`). */ + queueRun(threadId: string, itemId: string): RunRecord | undefined + /** The id of the queue item that carries run `runId`, while it waits in the thread's queue. */ + queueItemForRun(threadId: string, runId: string): string | undefined + /** The queue item `itemId` while it is still in the thread's queue. */ + queueItem(threadId: string, itemId: string): QueuedMessage | undefined + activeRun(threadId: string): RunRecord | null +} + +/** Where the message is: in a run that has not ended, waiting in the queue for its run, or done. */ +export type Followed = + | { kind: 'live'; runId: string } + | { kind: 'awaiting'; runId: string | null } + | { kind: 'ended'; runId: string | null; status: string } + +/** Hand-offs one resolve follows at most; a chain longer than this is read again on the next event. */ +const MAX_HOPS = 32 + +/** + * Follows a message from the run it was last seen in (SPEC §15.1, "keyed on the message"): + * - a run a usage-limit pause handed over goes on in the run that continues it; + * - a queued message keeps its queue item through a person's edit (its run is cancelled and it gets a fresh one, + * `queue:<itemId>`, when it drains), a promotion to a steer (it joins the run it steers, or goes back to the queue and + * runs as its own turn when that run ends before reading it); + * - a queued message that left the queue before it ran (removed, cleared by a Stop) ended as `removed`. + */ +export function followMessage(target: WatchTarget, threadId: string, runId: string | null, queueItemId: string | null): Followed { + let current = runId + for (let hop = 0; hop < MAX_HOPS; hop++) { + const run = current ? target.getRun(current) : null + if (run && !TERMINAL_RUN_STATUSES.has(run.status)) return { kind: 'live', runId: run.runId } + if (run) { + const endedBy = run.outcome?.pause?.endedBy + if (endedBy === 'resume' || endedBy === 'resume_now') { + const next = target.continuationOf(threadId, run.runId) + if (next) { + current = next.runId + continue + } + } + } + if (queueItemId) { + // A run the queue made for the item after this one carries the message now. + const later = target.queueRun(threadId, queueItemId) + if (later && (!run || later.ordinal > run.ordinal)) { + current = later.runId + continue + } + const item = target.queueItem(threadId, queueItemId) + if (item && item.state !== 'claimed') { + // A steer joins the run it was promoted into (the active run, for one promoted before runs were bound). + const steered = item.state === 'steering' ? item.steerRunId ?? target.activeRun(threadId)?.runId : undefined + const next = steered ?? item.runId + if (next && next !== current && !TERMINAL_RUN_STATUSES.has(target.getRun(next)?.status ?? 'cancelled')) { + current = next + continue + } + return { kind: 'awaiting', runId: current } + } + // Cancelled with its item gone: the message left the queue before any run read it. + if (!run || run.status === 'cancelled') return { kind: 'ended', runId: current, status: 'removed' } + } + if (!run) return { kind: 'ended', runId: current, status: 'removed' } + return { kind: 'ended', runId: run.runId, status: run.status } + } + return { kind: 'awaiting', runId: current } +} diff --git a/src/renderer/chat/adapters/mousseToUI.ts b/src/renderer/chat/adapters/mousseToUI.ts index 9bc420ee25..cfb58412ba 100644 --- a/src/renderer/chat/adapters/mousseToUI.ts +++ b/src/renderer/chat/adapters/mousseToUI.ts @@ -615,8 +615,11 @@ export function mousseToUIMessages(messages: ChatMessage[], senders?: TurnSender // The same for the message a turn the provider started itself opens with: the background tasks it reports. const backgroundNotice = msg.role === 'user' && msg.backgroundNotice?.length ? msg.backgroundNotice : undefined if (backgroundNotice) base.metadata = { ...(base.metadata as object | undefined), backgroundNotice } + // And for what Mousse told the agent about work it asked to hear about (`notify`). + const settleNotice = msg.role === 'user' && msg.settleNotice?.length ? msg.settleNotice : undefined + if (settleNotice) base.metadata = { ...(base.metadata as object | undefined), settleNotice } if (msg.role === 'assistant' && msg.scheduledRun) base.metadata = { ...(base.metadata as object | undefined), scheduledRun: msg.scheduledRun } - if (!displayText.trim() && !msg.images?.length && extraFiles.length === 0 && references.length === 0 && !subagentNotice && !backgroundNotice) { + if (!displayText.trim() && !msg.images?.length && extraFiles.length === 0 && references.length === 0 && !subagentNotice && !backgroundNotice && !settleNotice) { continue } // Fold exact-duplicate consecutive assistant text (provider double-adds, diff --git a/src/renderer/chat/adapters/settleNotice.ts b/src/renderer/chat/adapters/settleNotice.ts new file mode 100644 index 0000000000..178f0b4244 --- /dev/null +++ b/src/renderer/chat/adapters/settleNotice.ts @@ -0,0 +1,41 @@ +import type { UIMessage } from 'ai' +import { readSettleNotice, type SettleNoticeItem } from '../../../shared/settleNotice' + +/** + * The settle notices a message delivers (`ChatMessage.settleNotice`, carried on the UI message's metadata): what Mousse + * told this thread's agent about work it asked to hear about. The message text is what the model reads and is never + * parsed here. + */ +export function readSettleNoticeMeta(message: Pick<UIMessage, 'metadata'> | undefined): SettleNoticeItem[] | null { + return readSettleNotice((message?.metadata as { settleNotice?: unknown } | undefined)?.settleNotice) ?? null +} + +export type SettleNoticeTone = 'done' | 'failed' | 'stopped' | 'waiting' + +/** How a notice item reads: what happened there, and a tone for its dot. */ +export function settleNoticeOutcome(item: Pick<SettleNoticeItem, 'event' | 'status'>): { verb: string; tone: SettleNoticeTone } { + if (item.event === 'needs_input') return { verb: 'is waiting for a person', tone: 'waiting' } + if (item.event === 'expired') return { verb: 'is still working; no longer watched', tone: 'waiting' } + switch (item.status) { + case 'completed': + return { verb: 'finished', tone: 'done' } + case 'failed': + case 'uncertain': + return { verb: 'failed', tone: 'failed' } + case 'interrupted': + return { verb: 'was stopped', tone: 'stopped' } + case 'cancelled': + return { verb: 'was cancelled', tone: 'stopped' } + case 'removed': + return { verb: 'never ran your message', tone: 'stopped' } + case 'deleted': + return { verb: 'was deleted', tone: 'stopped' } + default: + return { verb: `ended (${item.status ?? 'unknown'})`, tone: 'stopped' } + } +} + +/** The name a notice gives the thread it is about. */ +export function settleNoticeName(item: Pick<SettleNoticeItem, 'title'>): string { + return item.title?.replace(/\s+/g, ' ').trim() || 'Untitled thread' +} diff --git a/src/renderer/chat/components/agent-elements/find/find-index.ts b/src/renderer/chat/components/agent-elements/find/find-index.ts index b6d6002de3..0e2641ba46 100644 --- a/src/renderer/chat/components/agent-elements/find/find-index.ts +++ b/src/renderer/chat/components/agent-elements/find/find-index.ts @@ -1,5 +1,6 @@ import type { UIMessage } from "ai"; import { readSubagentNotice } from "../../../adapters/subagentNotice"; +import { readSettleNoticeMeta } from "../../../adapters/settleNotice"; import { isTextPart } from "../utils/assistant-blocks"; import { markdownToSearchBlocks, plainTextToSearchBlocks } from "./search-text"; import { promptDisplayText } from "../prompt-links"; @@ -101,7 +102,7 @@ function sourceOf(message: UIMessage): unknown[] { const source: unknown[] = [ message.role, Boolean(metadata?.contextHandoff || metadata?.compaction || metadata?.contextCleared), - message.role === "user" && readSubagentNotice(message) !== null, + message.role === "user" && (readSubagentNotice(message) !== null || readSettleNoticeMeta(message) !== null), ]; for (const part of message.parts ?? []) source.push(isTextPart(part) ? replyText(message, part.text) : null); return source; @@ -279,7 +280,7 @@ export function searchableParts(message: UIMessage, math = false): SearchablePar function readParts(message: UIMessage, math: boolean): SearchablePart[] { const parts = message.parts ?? []; if (message.role === "user") { - if (readSubagentNotice(message)) return []; + if (readSubagentNotice(message) || readSettleNoticeMeta(message)) return []; const text = parts .filter(isTextPart) .map((part) => part.text) diff --git a/src/renderer/chat/components/agent-elements/message-list.tsx b/src/renderer/chat/components/agent-elements/message-list.tsx index 2697ae2c89..adb82f5e8a 100644 --- a/src/renderer/chat/components/agent-elements/message-list.tsx +++ b/src/renderer/chat/components/agent-elements/message-list.tsx @@ -50,11 +50,12 @@ import { } from "./tools/permission-request"; import { SubagentCardGroup } from "./tools/SubagentCard"; import { SecretRequestInline, isSecretRequestPart, isWaitingSecretRequest } from "../../../components/secrets/secretRequestPart"; -import { BackgroundNotice, SubagentNotice } from "./tools/SubagentNotice"; +import { BackgroundNotice, SettleNotice, SubagentNotice } from "./tools/SubagentNotice"; import { SteerGroup } from "./steer-group"; import { isRunningSubagent } from "../../../../shared/subagents"; import { useSubagentCards } from "./tools/subagent-cards-context"; import { readSubagentNotice } from "../../adapters/subagentNotice"; +import { readSettleNoticeMeta } from "../../adapters/settleNotice"; import { readBackgroundNotice } from "../../adapters/nativeSubagents"; import { openThread } from "../../../lib/openThread"; import { ThreadChip } from "../../../components/ThreadChip"; @@ -803,7 +804,7 @@ function messageTurnId(message: UIMessage | undefined): string | undefined { /** A message that reports results (a subagent's, or the runtime's own background tasks): not something the user wrote. */ function isResultNotice(msg: UIMessage | undefined): boolean { - return Boolean(readSubagentNotice(msg) || readBackgroundNotice(msg)); + return Boolean(readSubagentNotice(msg) || readBackgroundNotice(msg) || readSettleNoticeMeta(msg)); } /** The empty-parts copy of a subagent-results message that joins a reply, one per message. */ @@ -2220,7 +2221,7 @@ function foldRowOf(msg: UIMessage, toolsOnly: boolean, suppressQuestionTool: boo if (toolsOnly) return { kind: "message", toolsOnly: true, keep: (msg.parts ?? []).some(isUnrecoveredFailure) }; const metadata = (msg.metadata ?? {}) as Record<string, unknown>; if ( - readSubagentNotice(msg) || readBackgroundNotice(msg) || isThreadNotice(msg) || isCompactionRow(msg) || + readSubagentNotice(msg) || readBackgroundNotice(msg) || readSettleNoticeMeta(msg) || isThreadNotice(msg) || isCompactionRow(msg) || metadata.contextHandoff != null || metadata.contextCleared || metadata.scheduledRun != null ) { return { kind: "message", keep: true }; @@ -2306,6 +2307,15 @@ const TurnRow = memo(function TurnRow({ </div> ); } + // What Mousse told the agent about work it asked to hear about (`notify`). + const settled = readSettleNoticeMeta(turn.userMsg); + if (settled) { + return ( + <div data-notice-id={turn.userMsg.id}> + <SettleNotice items={settled} /> + </div> + ); + } const text = getTextFromParts( turn.userMsg!.parts ?? [], "", @@ -2542,6 +2552,17 @@ const TurnRow = memo(function TurnRow({ ), }; } + const settled = readSettleNoticeMeta(msg); + if (settled) { + return { + fold, + node: ( + <div key={msg.id} data-notice-id={msg.id}> + <SettleNotice items={settled} /> + </div> + ), + }; + } const isLastMsg = isLastTurn && segment.msgIndex === answerMsgs.length - 1; return { fold, diff --git a/src/renderer/chat/components/agent-elements/tools/SubagentNotice.tsx b/src/renderer/chat/components/agent-elements/tools/SubagentNotice.tsx index 067d2f876f..cca1f1a991 100644 --- a/src/renderer/chat/components/agent-elements/tools/SubagentNotice.tsx +++ b/src/renderer/chat/components/agent-elements/tools/SubagentNotice.tsx @@ -1,7 +1,10 @@ import type { BackgroundTaskNoticeItem, SubagentNoticeItem } from "../../../../../shared/subagents"; +import type { SettleNoticeItem } from "../../../../../shared/settleNotice"; +import { settleNoticeName, settleNoticeOutcome } from "../../../adapters/settleNotice"; import { backgroundNoticeName } from "../../../adapters/nativeSubagents"; import { noticeItemName, noticeOutcome } from "../../../adapters/subagentNotice"; import { openThread } from "../../../../lib/openThread"; +import { ThreadChip } from "../../../../components/ThreadChip"; import "./subagent-card.css"; /** Most results a notice lists; a wake that reports more says how many it left out. */ @@ -70,3 +73,29 @@ export function BackgroundNotice({ items }: { items: readonly BackgroundTaskNoti </div> ); } + +/** + * What Mousse told this thread's agent about work it asked to hear about (`notify`): one quiet row per thread, the + * thread as its chip (title and live status; a click opens it) and what happened there. Mousse wrote it; it is neither + * the person's message nor an agent's. The message text, which the model reads, is not shown. + */ +export function SettleNotice({ items }: { items: readonly SettleNoticeItem[] }) { + const shown = items.slice(0, SUBAGENT_NOTICE_ROWS); + const hidden = items.length - shown.length; + return ( + <div className="subagent-notice" role="note" aria-label="Notice from Mousse"> + {shown.map((item) => { + const { verb, tone } = settleNoticeOutcome(item); + return ( + <span key={`${item.watchId}:${item.event}`} className="subagent-notice-row"> + <span className="subagent-notice-dot" data-tone={tone} aria-hidden="true" /> + <ThreadChip threadId={item.threadId} label={settleNoticeName(item)} /> + <span className="subagent-notice-detail">{verb}</span> + {item.cut && <span className="subagent-notice-detail">· partial reply</span>} + </span> + ); + })} + {hidden > 0 && <span className="subagent-notice-row">and {hidden} more</span>} + </div> + ); +} diff --git a/src/renderer/components/QueuedMessages.tsx b/src/renderer/components/QueuedMessages.tsx index 0e488d8b99..0c15663f91 100644 --- a/src/renderer/components/QueuedMessages.tsx +++ b/src/renderer/components/QueuedMessages.tsx @@ -8,7 +8,7 @@ import { useAfterTurnsLayout } from '../chat/components/agent-elements/after-tur import { shortTokens } from '../lib/promptCache' import { mousseToUIMessages } from '../chat/adapters/mousseToUI' import { UserMessage } from '../chat/components/agent-elements/user-message' -import { SubagentNotice } from '../chat/components/agent-elements/tools/SubagentNotice' +import { SettleNotice, SubagentNotice } from '../chat/components/agent-elements/tools/SubagentNotice' import { isOptimisticQueueItem, type ThreadQueue } from '../hooks/useThreadQueue' import { canEditQueued, queuedContentWithText, queuedWords, splitQueuedContent } from '../lib/queuedContent' import { formatBinding } from '../../shared/commands' @@ -75,6 +75,7 @@ const QueuedBubble = memo(function QueuedBubble({ item }: { item: QueuedMessage [item.id, item.content, item.enqueuedAt, item.images, item.origin] ) if (item.subagentNotice?.length) return <SubagentNotice items={item.subagentNotice} /> + if (item.settleNotice?.length) return <SettleNotice items={item.settleNotice} /> return message ? <UserMessage message={message} /> : null }) diff --git a/src/renderer/lib/queuedContent.ts b/src/renderer/lib/queuedContent.ts index 522bed4636..610ec18a5f 100644 --- a/src/renderer/lib/queuedContent.ts +++ b/src/renderer/lib/queuedContent.ts @@ -77,6 +77,7 @@ export function canEditQueued(item: QueuedMessage): boolean { item.state === 'pending' && item.intent !== 'steer' && !item.subagentNotice?.length && + !item.settleNotice?.length && !item.inboxIds?.length && !item.workflowInvocationId } diff --git a/src/shared/settleNotice.ts b/src/shared/settleNotice.ts new file mode 100644 index 0000000000..474612bac1 --- /dev/null +++ b/src/shared/settleNotice.ts @@ -0,0 +1,49 @@ +/** + * The settle notice (docs/run-engine/SPEC.md §15.1, "Told when it settles"): what Mousse tells a thread whose agent sent + * a message with `notify` (`thread_send`, `thread_create`) about the work that message started in another thread. It is + * written by Mousse, never by either agent, and carried structured on the message that delivers it, so the app never + * parses the text the model reads. + */ + +/** What happened to the watched work: it waits on a person (once), it ended, or Mousse stopped watching it. */ +export type SettleNoticeEvent = 'needs_input' | 'ended' | 'expired' + +export interface SettleNoticeItem { + /** The watch that wrote it; one watch writes at most one `needs_input` and one `ended` or `expired`. */ + watchId: string + /** The thread the notice is about (the one the message went to). */ + threadId: string + /** That thread's title when the notice was written. */ + title: string | null + event: SettleNoticeEvent + /** + * With `ended`: the status the work ended with (a run status), `removed` when the message left the thread's queue + * before it ran, or `deleted` when the thread was deleted. + */ + status?: string + /** The run the notice is about, when there is one. */ + runId?: string + /** With `ended`: the result was cut; the rest is read with `thread_read`. */ + cut?: boolean +} + +/** Characters of the watched run's result a notice carries; the rest is read with `thread_read`. */ +export const SETTLE_NOTICE_RESULT_CHARS = 2_000 + +/** How long a watch lasts: after this the sender is told once, without being woken, that the work still goes on. */ +export const SETTLE_WATCH_TTL_MS = 24 * 60 * 60 * 1000 + +/** Whether a value read from disk or the wire is a notice item. */ +export function isSettleNoticeItem(value: unknown): value is SettleNoticeItem { + if (!value || typeof value !== 'object') return false + const item = value as Record<string, unknown> + return typeof item.watchId === 'string' && typeof item.threadId === 'string' && + (item.event === 'needs_input' || item.event === 'ended' || item.event === 'expired') +} + +/** The notice items of a value read from disk or the wire; undefined when there are none. */ +export function readSettleNotice(value: unknown): SettleNoticeItem[] | undefined { + if (!Array.isArray(value)) return undefined + const items = value.filter(isSettleNoticeItem) + return items.length ? items : undefined +} diff --git a/src/shared/threadTitleText.ts b/src/shared/threadTitleText.ts index 3ccbec5c11..2a0d7a1cc1 100644 --- a/src/shared/threadTitleText.ts +++ b/src/shared/threadTitleText.ts @@ -298,12 +298,12 @@ export interface TitleContext { images?: number } -type TitleMessage = Pick<ChatMessage, 'role' | 'content' | 'kind' | 'hidden' | 'streaming' | 'images' | 'subagentNotice' | 'questionAnswers' | 'scheduledRun' | 'origin'> +type TitleMessage = Pick<ChatMessage, 'role' | 'content' | 'kind' | 'hidden' | 'streaming' | 'images' | 'subagentNotice' | 'settleNotice' | 'questionAnswers' | 'scheduledRun' | 'origin'> /** A message the person or the agent wrote in the conversation, not a tool row, notice or hidden input. */ function conversational(message: TitleMessage): boolean { return (!message.kind || message.kind === 'message') && !message.hidden && !message.streaming && - !message.subagentNotice && !message.questionAnswers && !message.scheduledRun && Boolean(message.content.trim()) + !message.subagentNotice && !message.settleNotice && !message.questionAnswers && !message.scheduledRun && Boolean(message.content.trim()) } /** diff --git a/src/shared/types.ts b/src/shared/types.ts index 27f5429c37..cd58c64272 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -906,6 +906,12 @@ export interface ChatMessage { * (a continuation run): the tasks it reports, so the app shows them as a notice instead of a message the user wrote. */ backgroundNotice?: import('./subagents').BackgroundTaskNoticeItem[] + /** + * Set on the message that opens a turn Mousse started to tell this thread's agent about work it asked to hear about + * (`notify` on `thread_send` or `thread_create`): what settled where. The app shows it as a notice, never as a message + * the user wrote or an agent's. + */ + settleNotice?: import('./settleNotice').SettleNoticeItem[] /** Set on a user message a scheduled job sent, so the thread can show "Scheduled: <name>" instead of passing it off as typed. */ scheduled?: { jobId: string; jobName?: string } /** Set on a user message another thread's agent sent (`thread_send`), so the thread can say whose it is. */ @@ -1170,6 +1176,16 @@ export interface QueuedMessage { inboxIds?: string[] /** The subagent results the item's message reports. */ subagentNotice?: import('./subagents').SubagentNoticeItem[] + /** The settle notices the item delivers (`ChatMessage.settleNotice`); notices that arrive while it waits join it. */ + settleNotice?: import('./settleNotice').SettleNoticeItem[] + /** With `settleNotice`: the count of agent messages in a row of the runs the notices are about; the turn carries it. */ + settleHops?: number + /** + * A settle notice that must not start a turn by itself (its thread is a subagent, the person stopped it, it is kept in + * Plan, or the notice says Mousse stopped watching): it waits until a person sends it (Send now), a notice that may + * start a turn joins it, or a person's turn of the thread starts and it runs after that turn. + */ + heldNotice?: true /** * The thread's stop generation when the item was queued, for work that starts on behalf of a parent * (a steer that missed its turn). Once a Stop raised the generation the item is refused when it would diff --git a/tests/contractVersions.test.ts b/tests/contractVersions.test.ts index 4b3fe2ebb5..c7cb599757 100644 --- a/tests/contractVersions.test.ts +++ b/tests/contractVersions.test.ts @@ -10,7 +10,7 @@ describe('contract versions', () => { daemonOwnerLease: 1, netProtocol: '1.0', netEnvelope: 1, - runDatabase: 19, + runDatabase: 20, botsDb: 9, mousseConf: 1, installation: 2, diff --git a/tests/renderer/queuedMessagesInChat.test.ts b/tests/renderer/queuedMessagesInChat.test.ts index db78abed1e..82f719b084 100644 --- a/tests/renderer/queuedMessagesInChat.test.ts +++ b/tests/renderer/queuedMessagesInChat.test.ts @@ -482,6 +482,15 @@ describe('queued messages in the conversation', () => { expect(button('n', 'Edit')).toBeNull() }) + it('shows a queued settle notice by the thread it is about, never by the text the model reads, and offers no edit', async () => { + const notice = [{ watchId: 'w1', threadId: 't2', title: 'Fix build', event: 'ended' as const, status: 'completed' }] + await show([queued('s', '[Mousse notice, not from the user or any agent]\nSECRET RESULT', { source: 'thread-notice', settleNotice: notice })]) + expect(row('s').textContent).toContain('Fix build') + expect(row('s').textContent).toContain('finished') + expect(row('s').textContent).not.toContain('SECRET RESULT') + expect(button('s', 'Edit')).toBeNull() + }) + it('leaves internal items out', async () => { await show([queued('a', 'one'), queued('i', 'wake up', { internal: true })]) expect(rows().map((entry) => entry.dataset.queuedId)).toEqual(['a']) diff --git a/tests/renderer/settleNoticeRow.test.ts b/tests/renderer/settleNoticeRow.test.ts new file mode 100644 index 0000000000..a7d7c62007 --- /dev/null +++ b/tests/renderer/settleNoticeRow.test.ts @@ -0,0 +1,74 @@ +// @vitest-environment jsdom +/** + * The settle notice in the sender's chat (SPEC §15.1): Mousse's notice row, which names the thread it is about with its + * thread chip (a click opens it), never the person's bubble or an agent's, and never the text the model reads. + */ +import { act, createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ChatMessage } from '../../src/shared/types' +import { mousseToUIMessages } from '../../src/renderer/chat/adapters/mousseToUI' +import { MessageList } from '../../src/renderer/chat/components/agent-elements/message-list' +import { useAppStore } from '../../src/renderer/stores/appStore' + +const openLinkedThread = vi.fn() +vi.mock('../../src/renderer/utils/chatLinks', async (importOriginal) => ({ + ...(await importOriginal<typeof import('../../src/renderer/utils/chatLinks')>()), + openLinkedThread: (threadId: string) => openLinkedThread(threadId) +})) + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +let root: Root +let host: HTMLElement + +beforeEach(() => { + ;(globalThis as { ResizeObserver?: unknown }).ResizeObserver ??= class { + observe() {} + unobserve() {} + disconnect() {} + } + host = document.createElement('div') + document.body.append(host) + root = createRoot(host) + openLinkedThread.mockClear() + // The two threads the notices are about, as this window lists them: one finished, one waiting on its person. + const thread = (id: string, name: string) => ({ id, name, projectId: 'p1', createdAt: at(0), updatedAt: at(0) }) + useAppStore.setState({ threads: [thread('t2', 'Fix build'), thread('t3', 'Release notes')] as never }) +}) + +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +const at = (n: number) => new Date(Date.UTC(2026, 10, 15, 12, 0, n)).toISOString() + +describe('a settle notice in the sender\'s chat', () => { + it('is one notice row per thread: its thread chip, which opens it, and what happened there; not a user bubble and not the model\'s text', () => { + const messages: ChatMessage[] = [ + { id: 'u1', role: 'user', content: 'Ask the other thread to fix the build.', timestamp: at(0), turnId: 'run-1' }, + { id: 'a1', role: 'assistant', content: 'Sent it; Mousse will tell me.', timestamp: at(1) }, + { + id: 'n1', role: 'user', timestamp: at(2), turnId: 'run-2', + content: '[Mousse notice, not from the user or any agent: about the message you sent with notify.]\nThe work your message started in thread "Fix build" (mousse://thread/t2) finished.\nIts reply:\nSECRET MODEL TEXT', + settleNotice: [ + { watchId: 'w1', threadId: 't2', title: 'Fix build', event: 'ended', status: 'completed', runId: 'r1', cut: true }, + { watchId: 'w2', threadId: 't3', title: 'Release notes', event: 'needs_input' } + ] + }, + { id: 'a2', role: 'assistant', content: 'The build is fixed.', timestamp: at(3) } + ] + act(() => root.render(createElement(MessageList, { messages: mousseToUIMessages(messages), status: 'ready' }))) + expect([...host.querySelectorAll('.chat-user-bubble')].map((el) => el.textContent?.trim())).toEqual(['Ask the other thread to fix the build.']) + expect(host.textContent).not.toContain('SECRET MODEL TEXT') + const note = host.querySelector<HTMLElement>('[role="note"][aria-label="Notice from Mousse"]')! + const rows = [...note.querySelectorAll<HTMLElement>('.subagent-notice-row')] + expect(rows.map((row) => row.querySelector('.thread-chip-title')?.textContent)).toEqual(['Fix build', 'Release notes']) + expect(rows.map((row) => [...row.querySelectorAll('.subagent-notice-detail')].map((el) => el.textContent).join(' '))).toEqual(['finished · partial reply', 'is waiting for a person']) + const chip = rows[1]!.querySelector<HTMLAnchorElement>('a.thread-chip')! + expect(chip.getAttribute('href')).toBe('mousse://thread/t3') + act(() => chip.click()) + expect(openLinkedThread).toHaveBeenCalledWith('t3') + }) +}) diff --git a/tests/run/delegationGuidance.test.ts b/tests/run/delegationGuidance.test.ts index 4a6fb5e97b..2e08de9568 100644 --- a/tests/run/delegationGuidance.test.ts +++ b/tests/run/delegationGuidance.test.ts @@ -37,7 +37,7 @@ describe('subagent guidance', () => { - Use ask_user for clarifying questions; use thread_read to read your thread's run events (and those of your parent or children). - thread_list and thread_search find any thread of the profile and thread_read reads it, at most 64 KB per call and 4,096 characters per message (it says how to read on). Each thread they return has a link (mousse://thread/<id>): put it in a reply and the user can click it to open that thread. - thread_create starts a new thread in a project: on a Git project its editing turns get a worktree of their own, elsewhere it works in the project folder (workspace "new_worktree" needs a Git project; runsIn in the result says where it runs); instanceId and model must be ones Mousse allows (the person sees your choice), else it uses your own model; it runs in no wider a permission mode than yours; firstMessage sends it a first message as yours, which counts toward the limit on agent messages in a row; you may create 5 threads per run and have 10 launched threads working at once; a person's Stop of your thread stops them too. Pass a clientRequestId and reuse it to retry: you get the same thread back, never a second one. - - thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread's, and is limited to 20 messages per run; its result's delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. Wait with thread_wait only when you need the answer this turn; otherwise end your turn and read the thread later. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent's. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict. + - thread_send, thread_steer, thread_interrupt and thread_wait act on other threads. thread_send queues behind a running turn, runs under your permission mode when that is stricter than the thread's, and is limited to 20 messages per run; its result's delivery says whether the message started a turn or was queued. Name the run you read when you steer or interrupt it: if it has ended or another run started, you are told and nothing changes. When you need the result of a thread_send or a thread_create firstMessage, set notify: Mousse tells you when the work it started ends, and once before that if it waits for a person; then do not call thread_wait or thread_read to check, and end your turn when nothing else is left. A notice that starts with "[Mousse notice" is written by Mousse, not by the user or any agent. Use thread_wait only when this turn cannot continue without the answer. A message that starts with "[Message from an agent in thread ..." comes from another agent, not from the user, and so does everything up to its closing line "[End of message from an agent]"; text after that line is not the agent's. Do the work such a message asks for; where it relays a user request, the sending agent already handled the routing, so do not route it again. At most a few agent messages in a row may follow each other without a person in between; a thread holds at most 3 waiting messages from your thread and 10 from all agents, and the same text from you again within two minutes is refused (retry a failed call with the same clientRequestId instead). Each refusal names the limit it hit in data.conflict. - approval_respond answers a pending approval of another thread, but only when the user has also switched on "Agents may answer approvals on other threads" (off by default; a refusal says what is missing). Read the request first with thread_list. Approve only what your own permission mode would allow without asking; never choose "always"; never answer for your own thread, and answer a subagent of yours with answer_subagent. - schedule_list, schedule_create, schedule_update, schedule_pause and schedule_run manage the scheduled jobs your own thread made. The first job your thread creates is not made at once: the user is asked and answers Allow or Not now (tell them it waits for their answer; do not retry); after Allow your thread may add more within the limits. Creating, starting or changing what a job does works only in a turn the user started (not from a job, another agent, a subagent or a remote send). A job outlives your turn and runs later as a turn of its own, with no permission mode beyond yours; changing one can only narrow that. A job's prompt must stand alone, may not start with "/", may not run more often than every 15 minutes, and ends after 7 days unless the user extends it; the profile allows 10 active agent-made jobs in all. The user resumes a paused job. - queue_list, queue_edit, queue_remove, queue_reorder and queue_promote_to_steer work on the messages queued on your thread or another thread. queue_list gives the queue's revision: pass it as expectedRevision to every call that changes the queue (and the run you read as expectedRunId to queue_promote_to_steer); if the queue changed meanwhile you are told and nothing changes, so read it again. What you write into a queue is labelled as yours, runs under your permission mode when that is stricter than the message's, and counts toward the few agent messages a thread keeps waiting; a removal is recorded with its text. queue_promote_to_steer is refused while the user has a question or approval waiting. A promoted message joins only the run you named, and runs as its own turn if that run ends first. diff --git a/tests/run/settleFollow.test.ts b/tests/run/settleFollow.test.ts new file mode 100644 index 0000000000..bb2b6bc7f7 --- /dev/null +++ b/tests/run/settleFollow.test.ts @@ -0,0 +1,56 @@ +/** + * `followMessage` (SPEC §15.1, "keyed on the message"): where the message a watch follows is now. One row per way a + * message moves between runs, and per way it ends. + */ +import { describe, expect, it } from 'vitest' +import { followMessage, type WatchTarget } from '../../src/mms/run/settle/follow' +import type { RunRecord, RunStatus } from '../../src/mms/run/types' +import type { QueuedMessage } from '../../src/shared/types' + +const T = 'target' + +function run(ordinal: number, status: RunStatus, extra: Partial<RunRecord> = {}): RunRecord { + return { + runId: `r${ordinal}`, threadId: T, ordinal, status, epoch: 0, activeAttemptId: null, source: 'mcp', clientRequestId: null, + userMessageId: null, requestedAt: '', startedAt: null, completedAt: null, outcome: null, heartbeatAt: null, ...extra + } +} + +function item(state: QueuedMessage['state'], extra: Partial<QueuedMessage> = {}): QueuedMessage { + return { id: 'item', threadId: T, content: 'x', enqueuedAt: '', order: 0, intent: state === 'steering' ? 'steer' : 'normal', state, ...extra } +} + +function target(runs: RunRecord[], queue: QueuedMessage[] = [], active?: string): WatchTarget { + return { + getRun: (id) => runs.find((entry) => entry.runId === id) ?? null, + continuationOf: (_t, id) => runs.find((entry) => entry.outcome?.continuationOf === id), + queueRun: (_t, itemId) => [...runs].reverse().find((entry) => entry.clientRequestId === `queue:${itemId}`), + queueItemForRun: (_t, id) => queue.find((entry) => entry.runId === id)?.id, + queueItem: (_t, itemId) => queue.find((entry) => entry.id === itemId), + activeRun: () => (active ? runs.find((entry) => entry.runId === active) ?? null : null) + } +} + +const resumed = { pause: { reason: 'usage_limit' as const, until: '', estimated: false, count: 1, autoResume: true, endedBy: 'resume' as const } } + +describe('followMessage', () => { + it.each([ + ['a running run is followed as it is', target([run(1, 'running')]), 'r1', null, { kind: 'live', runId: 'r1' }], + ['a paused run is still live (the pause ends by itself)', target([run(1, 'paused')]), 'r1', null, { kind: 'live', runId: 'r1' }], + ['a run that ended is the end', target([run(1, 'completed')]), 'r1', null, { kind: 'ended', runId: 'r1', status: 'completed' }], + ['a failed run ends failed', target([run(1, 'failed')]), 'r1', null, { kind: 'ended', runId: 'r1', status: 'failed' }], + ['a pause continuation carries it on', target([run(1, 'cancelled', { outcome: resumed }), run(2, 'running', { outcome: { continuationOf: 'r1' } })]), 'r1', null, { kind: 'live', runId: 'r2' }], + ['and its end is the continuation\'s', target([run(1, 'cancelled', { outcome: resumed }), run(2, 'completed', { outcome: { continuationOf: 'r1' } })]), 'r1', null, { kind: 'ended', runId: 'r2', status: 'completed' }], + ['a person\'s edit: the run is cancelled and the item waits for its fresh run', target([run(1, 'cancelled')], [item('pending')]), 'r1', 'item', { kind: 'awaiting', runId: 'r1' }], + ['the drain gave the edited item its run', target([run(1, 'cancelled'), run(2, 'queued', { clientRequestId: 'queue:item' })], [item('claimed', { runId: 'r2' })]), 'r1', 'item', { kind: 'live', runId: 'r2' }], + ['that run\'s end is the end', target([run(1, 'cancelled'), run(2, 'completed', { clientRequestId: 'queue:item' })]), 'r1', 'item', { kind: 'ended', runId: 'r2', status: 'completed' }], + ['promoted to a steer: it joins the run it steers', target([run(1, 'cancelled'), run(2, 'running')], [item('steering', { steerRunId: 'r2' })], 'r2'), 'r1', 'item', { kind: 'live', runId: 'r2' }], + ['a steer the run read ends with that run', target([run(1, 'cancelled'), run(2, 'completed')]), 'r2', 'item', { kind: 'ended', runId: 'r2', status: 'completed' }], + ['a steer handed back waits for its own turn', target([run(1, 'cancelled'), run(2, 'completed')], [item('pending')]), 'r2', 'item', { kind: 'awaiting', runId: 'r2' }], + ['and its own turn carries it', target([run(1, 'cancelled'), run(2, 'completed'), run(3, 'completed', { clientRequestId: 'queue:item' })]), 'r2', 'item', { kind: 'ended', runId: 'r3', status: 'completed' }], + ['a queued message removed before it ran ends as removed', target([run(1, 'cancelled')]), 'r1', 'item', { kind: 'ended', runId: 'r1', status: 'removed' }], + ['a run that is gone ends as removed', target([]), 'r1', null, { kind: 'ended', runId: 'r1', status: 'removed' }] + ] as const)('%s', (_name, where, runId, itemId, expected) => { + expect(followMessage(where, T, runId, itemId)).toEqual(expected) + }) +}) diff --git a/tests/run/settleNoticeExpiry.test.ts b/tests/run/settleNoticeExpiry.test.ts new file mode 100644 index 0000000000..5cedebd773 --- /dev/null +++ b/tests/run/settleNoticeExpiry.test.ts @@ -0,0 +1,74 @@ +/** + * A settle watch lasts 24 hours (SPEC §15.1): then the sender is told once, without being woken, that the work is still + * going, and nothing more is told about that message. `SettleNotices` over a real run database, with the clock and + * the sender's queue stood in for. + */ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { SettleNotices, type PlannedSettleNotice } from '../../src/mms/orchestrator/settleNotices' +import { ProfileDatabase } from '../../src/mms/run/db/ProfileDatabase' +import { RunEngine } from '../../src/mms/run/RunEngine' +import { RunStore } from '../../src/mms/run/RunStore' +import { writeTerminalRun } from '../../src/mms/run/terminal' + +describe('a settle watch\'s 24 hours', () => { + const homes: string[] = [] + const closers: Array<() => void> = [] + afterEach(() => { + for (const close of closers.splice(0)) close() + for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }) + }) + + it('tells the sender once, held, that the work is still going; the work\'s later end tells it nothing more', async () => { + const home = mkdtempSync(join(tmpdir(), 'mousse-settle-expiry-')) + homes.push(home) + const engine = new RunEngine({ store: new RunStore(new ProfileDatabase({ profileHome: home })), pid: 1 }) + let now = new Date('2026-11-15T10:00:00Z') + const delivered: Array<{ notice: PlannedSettleNotice; held: boolean }> = [] + const notices = new SettleNotices({ + engine, + target: { + getRun: (runId) => engine.getRun(runId), + continuationOf: () => undefined, + queueRun: () => undefined, + queueItemForRun: () => undefined, + queueItem: () => undefined, + activeRun: (threadId) => engine.getActiveRun(threadId) + }, + titleOf: () => 'Long work', + threadLive: () => true, + waitingForPerson: () => false, + resultText: () => 'done', + stopGeneration: () => 0, + isSubagent: () => false, + inPlan: () => false, + deliver: (_threadId, notice, held) => { delivered.push({ notice, held }) }, + delivered: () => false, + now: () => now + }) + closers.push(() => { notices.stop(); engine.store.db.close() }) + notices.start() + const run = engine.store.createRun({ threadId: 'target', source: 'mcp' }) + const watch = notices.watch({ messageKey: 'thread_send:sender:1', watcherThreadId: 'sender', watcherRunId: 'run-s', targetThreadId: 'target', runId: run.runId }) + + now = new Date(now.getTime() + 23 * 60 * 60 * 1000) + notices.expireDue() + expect(delivered).toEqual([]) + + now = new Date(now.getTime() + 2 * 60 * 60 * 1000) + notices.expireDue() + notices.expireDue() + expect(delivered).toHaveLength(1) + expect(delivered[0]).toMatchObject({ held: true, notice: { item: { event: 'expired', threadId: 'target', watchId: watch.watchId } } }) + expect(delivered[0]!.notice.text).toContain('still going') + + // The work ends later: the watch is over, so the sender hears nothing more. + engine.store.db.transaction(() => writeTerminalRun(engine.store, engine.getRun(run.runId)!, engine.getRun(run.runId)!.epoch, 'completed', undefined, now.toISOString())) + notices.touch('target') + await new Promise((resolve) => setImmediate(resolve)) + expect(delivered).toHaveLength(1) + expect(notices.watches.get(watch.watchId)).toMatchObject({ state: 'expired', endNotice: 'sent' }) + }) +}) diff --git a/tests/run/threadSettleNoticeDaemon.test.ts b/tests/run/threadSettleNoticeDaemon.test.ts new file mode 100644 index 0000000000..025123df25 --- /dev/null +++ b/tests/run/threadSettleNoticeDaemon.test.ts @@ -0,0 +1,425 @@ +/** + * The settle notice end to end (docs/run-engine/SPEC.md §15.1, "Told when it settles"): a real `OrchestratorService`, + * Run Engine, effect worker and Mousse MCP server, with scripted provider runtimes whose turns call the tools over HTTP. + * What the sending agent sees is observed where it sees it: the turns its runtime is given, its transcript and its queue. + * + * Inputs covered: the target idle or busy; the work ends, waits on a person first, or is re-queued by a person's edit; + * the sender idle, busy, stopped by a person after it subscribed, kept in Plan, or a subagent; several watched threads + * settling together; a chain of sends answered by notices; a daemon restart. + */ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { CLAUDE_SUBSCRIPTION_CAPABILITIES } from '../../src/mms/harness/drivers/claudeCode/adapter' +import type { AdapterHost, ProviderAdapter, ProviderCapabilities, TurnControl, TurnInput, TurnResult, TurnSink } from '../../src/mms/harness/adapter' +import { TURN_TOKEN_KEY } from '../../src/mms/run/mcp/appTools' +import { NOTIFY_NEXT } from '../../src/mms/run/mcp/appTools/thread' +import { usageLimitError } from '../../src/mms/orchestrator/providerErrors' +import { McpCredentials } from '../../src/mms/run/mcp/McpCredentials' +import { MousseMcpServer } from '../../src/mms/run/mcp/MousseMcpServer' +import type { ProviderDriverKind } from '../../src/shared/providerInstances' +import { SETTLE_NOTICE_RESULT_CHARS } from '../../src/shared/settleNotice' +import type { ChatMessage, QueuedMessage } from '../../src/shared/types' +import { phase6Daemon, waitFor, type Phase6Daemon } from './phase6Fixture' + +vi.setConfig({ testTimeout: 60_000 }) + +type Mcp = { url: string; token: string; turnToken?: string } +type Script = (input: TurnInput, mcp: Mcp | undefined, d: Phase6Daemon, adapter: VendorAdapter) => Promise<string> + +/** A provider stand-in whose script gets the turn's MCP bridge, and whose turns can be held and interrupted. */ +class VendorAdapter implements ProviderAdapter { + readonly turns: TurnInput[] = [] + readonly abortedRuns = new Set<string>() + private readonly interruptListeners = new Set<() => void>() + constructor(readonly driver: ProviderDriverKind, readonly capabilities: ProviderCapabilities, private readonly script: (input: TurnInput, host: AdapterHost, adapter: VendorAdapter) => Promise<string>) {} + + configured(): boolean { + return true + } + + /** Holds the turn until `release` settles, the runtime is interrupted (a Stop) or the turn is aborted (a shutdown). */ + async hold(input: TurnInput, release: Promise<void>): Promise<void> { + const signal = input.signal + await Promise.race([ + release, + new Promise<void>((resolve) => { + const ended = (): void => { + this.abortedRuns.add(input.runId) + resolve() + } + if (signal?.aborted) ended() + else signal?.addEventListener('abort', ended, { once: true }) + }), + new Promise<void>((resolve) => { + const listener = (): void => { + this.abortedRuns.add(input.runId) + this.interruptListeners.delete(listener) + resolve() + } + this.interruptListeners.add(listener) + }) + ]) + } + + async startTurn(input: TurnInput, sink: TurnSink, _ctl: TurnControl, host: AdapterHost): Promise<TurnResult> { + this.turns.push(input) + const providerRef = { provider: input.llmProvider, instanceId: input.instanceId, model: input.model } + sink.providerRef(providerRef) + const text = await this.script(input, host, this) + const aborted = this.abortedRuns.has(input.runId) + if (!aborted) sink.text({ phase: 'complete', content: text, contentIndex: 0 }) + if (!aborted) host.context.nativeHistoryAfterTurn(text) + return { + text: aborted ? '' : text, + aborted, + modelName: 'Scripted', + totalResponseTimeMs: 1, + usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0 }, + contextSignature: 'scripted', + nativeMessages: [], + providerRef + } + } + + async interrupt(): Promise<'interrupted' | 'not_active'> { + for (const listener of [...this.interruptListeners]) listener() + return 'interrupted' + } +} + +function deferred<T = void>() { + let resolve!: (value: T) => void + const promise = new Promise<T>((done) => { resolve = done }) + return { promise, resolve } +} + +async function rpc(mcp: Mcp, method: string, params: Record<string, unknown>) { + const response = await fetch(mcp.url, { + method: 'POST', + headers: { Authorization: `Bearer ${mcp.token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) + }) + return await response.json() as { + result?: { content?: Array<{ text: string }>; isError?: boolean } + error?: { code: number; message: string; data?: { reason: string; [key: string]: unknown } } + } +} + +const call = (mcp: Mcp, name: string, args: Record<string, unknown> = {}) => + rpc(mcp, 'tools/call', { name, arguments: mcp.turnToken ? { ...args, [TURN_TOKEN_KEY]: mcp.turnToken } : args }) +const parse = (response: Awaited<ReturnType<typeof rpc>>): Record<string, unknown> => { + if (response.error) throw new Error(`rpc error ${response.error.code}: ${response.error.message}`) + if (response.result?.isError) throw new Error(response.result.content?.[0]?.text ?? 'tool error') + return JSON.parse(response.result!.content![0].text) +} + +const NOTICE = '[Mousse notice' +const GO = 'Go' +const settle = () => new Promise((resolve) => setTimeout(resolve, 300)) + +describe('the settle notice: an agent that sends with notify is told when the work settles (SPEC §15.1)', () => { + let home: string | undefined + let previousHome: string | undefined + const stops: Array<() => Promise<void>> = [] + + afterEach(async () => { + for (const stop of stops.splice(0).reverse()) await stop().catch(() => undefined) + if (previousHome === undefined) delete process.env.MOUSSE_HOME + else process.env.MOUSSE_HOME = previousHome + if (home) rmSync(home, { recursive: true, force: true }) + home = undefined + }) + + const MODEL = { llmProvider: 'claude-subscription', model: 'vendor-model' } + + /** A daemon over `home` (a fresh one unless given) whose threads run on one scripted runtime that talks to the real MCP server. */ + const daemon = (script: Script, at?: string, pid = 1) => { + if (!at) { + home = mkdtempSync(join(tmpdir(), 'mousse-settle-')) + previousHome = process.env.MOUSSE_HOME + process.env.MOUSSE_HOME = home + mkdirSync(join(home, 'project')) + } + let created: Phase6Daemon | undefined + const adapter: VendorAdapter = new VendorAdapter('claude', CLAUDE_SUBSCRIPTION_CAPABILITIES, async (input, host, self) => { + const bridge = host.bridge + return script(input, bridge?.mcp ? { ...bridge.mcp, turnToken: bridge.turnToken } : undefined, created!, self) + }) + const d = phase6Daemon(home!, [adapter], { pid, runs: { resumeAfterUsageLimit: true } }) + created = d + const server = new MousseMcpServer({ credentials: new McpCredentials(d.engine.store), registry: d.orch.mcpToolRegistry() }) + let ended = false + const end = async (crash: boolean) => { + if (ended) return + ended = true + d.orch.setMcpAttachment(null) + await server.stop() + await (crash ? d.crash() : d.stop()) + } + stops.push(() => end(false)) + const project = d.projects.openProject(join(home!, 'project')) + return { + d, adapter, project, + thread: (name: string) => { + const made = d.store.createThread(name, project.id) + d.orch.setThreadModelOverride(made.id, MODEL) + return made + }, + attach: async () => { await server.start(); d.orch.setMcpAttachment(server) }, + crash: () => end(true), + turnsOf: (threadId: string) => adapter.turns.filter((turn) => turn.threadId === threadId), + noticeTurns: (threadId: string) => adapter.turns.filter((turn) => turn.threadId === threadId && turn.prompt.startsWith(NOTICE)), + messages: (threadId: string): ChatMessage[] => d.orch.getOrCreateSession(threadId).messages, + queue: (threadId: string): QueuedMessage[] => d.orch.queueSnapshot(threadId).items, + watch: (watchId: string) => d.engine.store.db.statement('SELECT * FROM thread_watches WHERE watch_id = ?').get(watchId) as Record<string, unknown> | undefined + } + } + + const world = (script: Script) => { + const w = daemon(script) + return { ...w, parent: w.thread('Parent'), other: w.thread('Other work') } + } + + it('tells the sender once when the work ends, in a turn of its own, with the reply cut to 2,000 characters and the thread named by link', async () => { + const reply = `${'a'.repeat(SETTLE_NOTICE_RESULT_CHARS)}TAIL` + const seen: Record<string, unknown> = {} + const w = world(async (input, mcp) => { + if (input.threadId === w.other.id) return reply + if (input.prompt === GO) { + seen.sent = parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Do the work', notify: true, clientRequestId: 'send-1' })) + // A retry of the same send keeps the one watch. + seen.retry = parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Do the work', notify: true, clientRequestId: 'send-1' })) + } + return 'ok' + }) + await w.attach() + await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) + const sent = seen.sent as { runId: string; notify: { watchId: string; next: string } } + expect(sent.notify.next).toBe(NOTIFY_NEXT) + expect((seen.retry as typeof sent).notify.watchId).toBe(sent.notify.watchId) + + await waitFor(() => w.noticeTurns(w.parent.id).length === 1, 'the notice turn') + await settle() + // Told once: one turn, for one end. + expect(w.noticeTurns(w.parent.id)).toHaveLength(1) + const prompt = w.noticeTurns(w.parent.id)[0]!.prompt + expect(prompt).toContain(`mousse://thread/${w.other.id}`) + expect(prompt).toContain('finished') + expect(prompt).toContain('a'.repeat(SETTLE_NOTICE_RESULT_CHARS)) + expect(prompt).not.toContain('TAIL') + expect(prompt).toContain('thread_read') + // The transcript shows it as Mousse's notice, not as the person's message or an agent's. + const message = w.messages(w.parent.id).find((entry) => entry.settleNotice)! + expect(message.settleNotice).toEqual([expect.objectContaining({ threadId: w.other.id, event: 'ended', status: 'completed', runId: sent.runId, cut: true })]) + expect(message.origin).toBeUndefined() + const noticeRun = w.d.engine.listRuns(w.parent.id)[0]! + expect(noticeRun.source).toBe('thread-notice') + expect(w.watch(sent.notify.watchId)).toMatchObject({ state: 'ended', end_status: 'completed', end_notice: 'sent', needs_input: null }) + }) + + it('tells the sender the first time the work waits on a person, and still tells it when the work ends', async () => { + const seen: Record<string, unknown> = {} + const w = world(async (input, mcp, d) => { + if (input.threadId === w.other.id) { + // Two questions in the run: only the first is told. + for (const id of ['q1', 'q2']) await d.questions.requestAnswers([{ id, prompt: 'Which?', options: [{ id: 'a', label: 'A' }] }], w.other.id, {}) + return 'answered and done' + } + if (input.prompt === GO) seen.sent = parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'Ask first', notify: true })) + return 'ok' + }) + await w.attach() + await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) + await waitFor(() => w.noticeTurns(w.parent.id).length === 1, 'the needs-input notice') + expect(w.noticeTurns(w.parent.id)[0]!.prompt).toContain('waiting for a person') + for (let answered = 0; answered < 2; answered++) { + await waitFor(() => w.d.questions.listPendingForThread(w.other.id).length === 1, 'a question') + w.d.questions.submitAnswers(w.d.questions.listPendingForThread(w.other.id)[0]!.requestId, { [answered ? 'q2' : 'q1']: 'a' }) + } + await waitFor(() => w.noticeTurns(w.parent.id).length === 2, 'the end notice') + await settle() + expect(w.noticeTurns(w.parent.id)).toHaveLength(2) + expect(w.noticeTurns(w.parent.id)[1]!.prompt).toContain('answered and done') + expect(w.messages(w.parent.id).flatMap((message) => message.settleNotice ?? []).map((item) => item.event)).toEqual(['needs_input', 'ended']) + }) + + it('follows a queued message a person edited into the run it gets when it drains', async () => { + const release = deferred() + const seen: Record<string, unknown> = {} + const w = world(async (input, mcp, _d, adapter) => { + if (input.threadId === w.other.id) { + if (input.prompt === 'hold') await adapter.hold(input, release.promise) + return `reply to ${input.prompt.slice(0, 20)}` + } + if (input.prompt === GO) seen.sent = parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'queued work', notify: true })) + return 'ok' + }) + await w.attach() + await w.d.orch.send('hold', false, { threadId: w.other.id, clientRequestId: 'hold', awaitMode: 'ack' }) + await waitFor(() => w.turnsOf(w.other.id).length === 1, 'the busy turn') + await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) + const sent = seen.sent as { runId: string; queued: boolean } + expect(sent.queued).toBe(true) + const item = w.queue(w.other.id).find((entry) => entry.runId === sent.runId)! + // The person rewrites it: its run is cancelled, and it gets a fresh one when it drains. + w.d.orch.editQueuedItem(w.other.id, item.id, { content: 'edited work' }) + await waitFor(() => w.d.engine.getRun(sent.runId)?.status === 'cancelled', 'the cancelled run') + await settle() + expect(w.noticeTurns(w.parent.id)).toHaveLength(0) + release.resolve() + await waitFor(() => w.noticeTurns(w.parent.id).length === 1, 'the notice') + const notice = w.messages(w.parent.id).find((entry) => entry.settleNotice)!.settleNotice![0]! + expect(notice).toMatchObject({ event: 'ended', status: 'completed' }) + expect(notice.runId).not.toBe(sent.runId) + expect(w.d.engine.getRun(notice.runId!)?.clientRequestId).toBe(`queue:${item.id}`) + expect(w.noticeTurns(w.parent.id)[0]!.prompt).toContain('reply to edited work') + }) + + it('waits behind the sender\'s running turn, and notices that meet there run as one turn', async () => { + const parentGate = deferred() + const seen: Record<string, unknown> = {} + const w = world(async (input, mcp, d, adapter) => { + if (input.threadId === w.parent.id && input.prompt === GO) { + for (const id of [w.other.id, seen.third as string]) parse(await call(mcp!, 'thread_send', { threadId: id, content: 'work', notify: true })) + // The sender keeps working while both finish. + await waitFor(() => d.engine.listRuns(w.other.id)[0]?.status === 'completed' && d.engine.listRuns(seen.third as string)[0]?.status === 'completed', 'both targets') + await adapter.hold(input, parentGate.promise) + } + return 'ok' + }) + seen.third = w.thread('Third').id + await w.attach() + const going = w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go', awaitMode: 'ack' }) + await going + await waitFor(() => w.queue(w.parent.id).filter((item) => item.settleNotice).flatMap((item) => item.settleNotice!).length === 2, 'both notices queued') + // Never a steer of the running turn. + expect(w.noticeTurns(w.parent.id)).toHaveLength(0) + expect(w.queue(w.parent.id).filter((item) => item.settleNotice)).toHaveLength(1) + parentGate.resolve() + await waitFor(() => w.noticeTurns(w.parent.id).length === 1, 'one notice turn') + await settle() + expect(w.noticeTurns(w.parent.id)).toHaveLength(1) + const notice = w.messages(w.parent.id).find((entry) => entry.settleNotice)!.settleNotice! + expect(notice.map((item) => item.threadId).sort()).toEqual([w.other.id, seen.third as string].sort()) + // Each watched run was the first agent message in a row: the notice turn carries one, and adds none. + expect(w.d.engine.listRuns(w.parent.id)[0]!.outcome?.agentHops).toBe(1) + }) + + it('a sender and a target go back and forth three times by notices before a person must step in', async () => { + const results: Array<Awaited<ReturnType<typeof rpc>>> = [] + const w = world(async (input, mcp) => { + if (input.threadId === w.parent.id) results.push(await call(mcp!, 'thread_send', { threadId: w.other.id, content: `round ${results.length + 1}`, notify: true })) + return 'ok' + }) + await w.attach() + await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go' }) + await waitFor(() => results.length === 4, 'the fourth send') + expect(results.slice(0, 3).map((result) => parse(result).runId)).toHaveLength(3) + expect(JSON.stringify(results[3])).toContain('agent_hops_exceeded') + // The target's runs count the chain; each notice turn carries the count of the run it reports on. + expect(w.d.engine.listRuns(w.other.id).map((run) => run.outcome?.agentHops).reverse()).toEqual([1, 2, 3]) + expect(w.d.engine.listRuns(w.parent.id).filter((run) => run.source === 'thread-notice').map((run) => run.outcome?.agentHops).reverse()).toEqual([1, 2, 3]) + await settle() + // The refused send made no watch, so nothing more starts. + expect(w.noticeTurns(w.parent.id)).toHaveLength(3) + }) + + describe('it never starts a turn where the sender must not be woken; it waits in the sender\'s queue', () => { + it('in a sender a person stopped after it subscribed; the person\'s next turn lets it run after', async () => { + const otherGate = deferred() + const w = world(async (input, mcp, _d, adapter) => { + if (input.threadId === w.other.id) { + await adapter.hold(input, otherGate.promise) + return 'done late' + } + if (input.prompt === GO) { + parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'work', notify: true })) + await adapter.hold(input, new Promise<void>(() => undefined)) + } + return 'ok' + }) + await w.attach() + await w.d.orch.send(GO, false, { threadId: w.parent.id, clientRequestId: 'go', awaitMode: 'ack' }) + await waitFor(() => w.turnsOf(w.other.id).length === 1, 'the target turn') + await w.d.orch.stopThread(w.parent.id, 'user') + await waitFor(() => w.d.engine.getActiveRun(w.parent.id) === null, 'the stopped sender') + otherGate.resolve() + await waitFor(() => w.queue(w.parent.id).some((item) => item.settleNotice), 'the queued notice') + await settle() + expect(w.noticeTurns(w.parent.id)).toHaveLength(0) + expect(w.queue(w.parent.id).find((item) => item.settleNotice)).toMatchObject({ heldNotice: true }) + // The person comes back: the notice runs after their turn, not instead of it. + await w.d.orch.send('next', false, { threadId: w.parent.id, clientRequestId: 'next' }) + await waitFor(() => w.noticeTurns(w.parent.id).length === 1, 'the notice after the person\'s turn') + expect(w.turnsOf(w.parent.id).map((turn) => turn.prompt.startsWith(NOTICE) ? 'notice' : turn.prompt)).toEqual([GO, 'next', 'notice']) + }) + + it('in a sender kept in Plan', async () => { + const w = world(async (input, mcp) => { + if (input.threadId === w.parent.id && !input.prompt.startsWith(NOTICE)) parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'work', mode: 'plan', notify: true })) + return 'ok' + }) + await w.attach() + await w.d.orch.send({ content: GO, mode: 'plan' }, false, { threadId: w.parent.id, clientRequestId: 'go' }) + await waitFor(() => w.queue(w.parent.id).some((item) => item.settleNotice), 'the queued notice') + await settle() + expect(w.noticeTurns(w.parent.id)).toHaveLength(0) + expect(w.queue(w.parent.id).find((item) => item.settleNotice)).toMatchObject({ heldNotice: true }) + }) + + it('in a subagent\'s thread, whose result is its parent\'s', async () => { + const w = world(async (input, mcp) => { + if (input.threadId === sub.id && !input.prompt.startsWith(NOTICE)) parse(await call(mcp!, 'thread_send', { threadId: w.other.id, content: 'work', notify: true })) + return 'ok' + }) + const sub = w.thread('Sub') + w.d.engine.delegations.createLineage({ threadId: sub.id, parentThreadId: w.parent.id, parentRunId: 'run-p', relationship: 'subagent' }) + await w.attach() + await w.d.orch.send(GO, false, { threadId: sub.id, clientRequestId: 'go' }) + await waitFor(() => w.queue(sub.id).some((item) => item.settleNotice), 'the queued notice') + await settle() + expect(w.noticeTurns(sub.id)).toHaveLength(0) + expect(w.queue(sub.id).find((item) => item.settleNotice)).toMatchObject({ heldNotice: true }) + }) + }) + + it('keeps the watch across a daemon restart, and follows a usage-limit pause into the run that continues it', async () => { + const seen: Record<string, unknown> = {} + const ids: { parent?: string; other?: string } = {} + const script: Script = async (input, mcp) => { + if (input.threadId === ids.other) { + // The target's first turn hits a usage limit that resets in a moment: its run pauses, and resumes by itself. + if (input.prompt !== 'Continue' && !seen.paused) { + seen.paused = true + throw usageLimitError({ provider: 'claude', resetsAt: new Date(Date.now() + 1_500).toISOString(), estimated: false, limitKind: 'five_hour' }) + } + return 'continued and done' + } + if (input.prompt === GO) seen.sent = parse(await call(mcp!, 'thread_send', { threadId: ids.other, content: 'work', notify: true })) + return 'ok' + } + const first = daemon(script) + ids.parent = first.thread('Parent').id + ids.other = first.thread('Other work').id + await first.attach() + await first.d.orch.send(GO, false, { threadId: ids.parent, clientRequestId: 'go' }) + const sent = seen.sent as { runId: string; notify: { watchId: string } } + await waitFor(() => first.d.engine.getRun(sent.runId)?.status === 'paused', 'the paused target') + await first.crash() + expect(first.noticeTurns(ids.parent)).toHaveLength(0) + + // The next daemon resumes the pause after the reset and finishes the work: the sender hears once, about the run that continued it. + const second = daemon(script, home, 2) + await second.attach() + await waitFor(() => second.noticeTurns(ids.parent!).length === 1, 'the notice after the restart') + await settle() + expect(second.noticeTurns(ids.parent)).toHaveLength(1) + expect(second.noticeTurns(ids.parent)[0]!.prompt).toContain('continued and done') + const notice = second.messages(ids.parent).find((entry) => entry.settleNotice)!.settleNotice![0]! + expect(notice).toMatchObject({ event: 'ended', status: 'completed' }) + expect(second.d.engine.getRun(notice.runId!)?.outcome?.continuationOf).toBe(sent.runId) + expect(second.watch(sent.notify.watchId)).toMatchObject({ state: 'ended', end_notice: 'sent' }) + }) +})