From 37bfabefe67ba5fbe81ae68e364cc36d129731a3 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:31:31 -0500 Subject: [PATCH 01/16] feat(contracts): fields and shared rules for child reports, access and Stop Stage 1, step 1 of docs/design/agent-autonomy-no-limits.md (rev 6, which this commit adds). Nothing behaves differently yet. - A message, a queued message and what starts a turn from one can carry the sender's access (`requestCeiling`) and a lead pass's block (`passBlocked`). - A report can be a follow-up no request asked for (`fromThread.followUp`). - A child keeps the reports it owes its parent (`childRequests.owedReports`). - A thread started without report back can stay under its starter's Stop (`stopsWithParent`). - `thread.session.stop` takes a server-only `cause` (family, cleanup). - `thread.delete` can name the threads the dialog listed (`alsoDelete`). - A check-back can be marked dormant; a dormant one no longer counts as live. - A thread started over a link keeps the access it was started with, and a linked send carries the sender's access, with a flag for computers that enforce it. - Shared: `attachedDescendantsOf` and `stopReachOf` walk a family in tree order with levels and a visited set; `isStillGoing` is the one test for what a stop targets, what its count shows and what holds a revert. --- docs/design/agent-autonomy-no-limits.md | 488 ++++++++++++++++++++--- packages/contracts/src/orchestration.ts | 110 +++++ packages/contracts/src/peerRpc.ts | 14 + packages/shared/src/checkBacks.ts | 7 +- packages/shared/src/childThreads.test.ts | 91 +++++ packages/shared/src/childThreads.ts | 152 +++++++ 6 files changed, 807 insertions(+), 55 deletions(-) diff --git a/docs/design/agent-autonomy-no-limits.md b/docs/design/agent-autonomy-no-limits.md index 92f35260f..c2aac4864 100644 --- a/docs/design/agent-autonomy-no-limits.md +++ b/docs/design/agent-autonomy-no-limits.md @@ -1,6 +1,6 @@ # Agents work without per-message limits, and threads nest -Status (Nov 23 2026): Part 1 is built. Part 2 is **not built**: GPT-6.2 Astra's review of rev 1 found that its delivery rule loses or misroutes answers (see "Review of Part 2, rev 1" at the end), so it needs a redesign before anyone builds it. Asked for by Will: "do it all the T3 code way, we will accept the same risks that they are taking". The goal is a lead agent that directs other agents, in a room or in threads it starts, for hours or days without the user writing. +Status (Nov 23 2026): Part 1 is built and merged (#1055). Part 2 is **not built**. This is its sixth and last plan, after five reviews by GPT-6.2 Astra. Rev 1 held a parent's request open until the threads below had settled, which loses or misroutes answers. Rev 2 reports every turn upward instead, and that decision has held since. Rev 3 tried to route each report to the exact work and room agent it belonged to, which did not converge. Rev 4 replaced that with fixed rules and two build stages. Rev 5 rewrote it against today's main. Rev 6 below folds in Will's four decisions and gives the seven sequences from the fifth review an expected outcome and a test each. Next, Opus 5.5 builds stage 1 and Astra reviews each step's diff. All five reviews are kept at the end with the current answer under each finding. Asked for by Will: "do it all the T3 code way, we will accept the same risks that they are taking". The goal is a lead agent that directs other agents, in a room or in threads it starts, for hours or days without the user writing. ## What T3 Code does (pingdotgg/t3code at f1c13177d8) @@ -33,92 +33,476 @@ Kept, because none of them caps how much agents do over time: Schema: the four counter fields stay in the schema, because an older client (a phone or another computer on an earlier version) still requires them when it decodes a thread from a newer server. Nothing counts or reads them any more; stored values are left as they were. The `limit` outcome is gone from the room and thread tool results; the web still reads it in old transcripts (`apps/web/src/childThreads.ts`). `thread.child-requests-reset` now only lifts a lead pass's block, and an old event with `keepsPassBlock` changes nothing. -## Part 2: threads nest to any depth +Surfaces and tests for Part 1 (built): -### Rules that go +- Contracts: the constants and counters above. No new wire fields. +- App guide: the rooms topic and the threads topic lost the limits. +- Tests: `roomAgentRequests` and `agentRequestDecisions` accept a fourth and a fortieth request; the shared `childThreads` tests accept starts and sends past the old limits. -Every "a thread started by another thread can't..." refusal: +## Part 2: threads nest to any depth (rev 6) -- `callerRefusal`'s `DEPTH_REFUSAL` (`packages/shared/src/childThreads.ts:74`): `thread_start`, `thread_send`, `thread_stop`, `thread_wrap` from an attached child. -- `decideChildrenStop`'s two refusals (`childThreadDecisions.ts:1814,1833`). -- `thread.create` refusing a parent that is itself an attached child (`decider.ts:1559`). -- Put back's "parent is itself an attached child" and "this thread has started threads of its own" (`childThreads.ts:286-291`). A cycle can't form: `parentThreadId` is set once at creation, and put back only re-attaches to that thread. -- The tool texts and `Depth 1` section of `child-threads.md`. +Rev 6 is written against main at 66ab80915, after four changes merged: the per-message limits are gone (#1055), a deleted parent's threads are cleaned up only when the server really deleted them (#1051), archiving a parent no longer kills a child's check-back (#1056), and the user's Stop ends every agent's check-backs (#1057). Every line number here is from that commit. Five reviews are at the end of this file, with the current answer under each finding. -Kept: the access ceiling (a child never gets more than its parent, checked at create and on every send, so it holds down any chain), linked computers (a thread another computer's agent started here stays fenced from thread tools, `isLinkFenced`), and the lead chat's `ownChildRefusal` for passes. +The examples use three threads. R is the root, the thread the user talks to. M is a thread R started. G is a thread M started. -### A middle thread answers only when its own children have +### Is this converging -Today a request from R to its child M settles when M's answering turn completes with no awaited background tasks. If M started threads of its own in that turn, R gets "I started G1 and G2" and goes on; G1's report later wakes only M, and M's final answer reaches R only as a late-reply note at R's next turn (`lateReplyOf`), never waking it. That breaks a lead directing a team for hours. +Rev 3 was not. It tried to say exactly which piece of the parent's work every turn in a child belonged to, and which agent of a room that work was for, and to carry that through every way a turn can start. Rev 4 removed that whole class with fixed rules: a thread's later reports go to the agent that started it, a middle thread reads each report in a turn of its own, there are no late replies, and what lifts a Stop is left as it is today. -New rule: **a thread's open child requests are owed work, like awaited background tasks.** One predicate `owedWorkCount(thread) = awaitedBackgroundTaskCount + open child requests that report back` replaces the background count wherever delivery reads it: +The fourth review found ten more problems and no new class. Three were fixed on main while it was being written (#1051, #1056, #1057). Of the other seven, most are in how today's code already behaves with one parent and one child, whatever this plan does: a child whose runtime dies is reported as stopped by the user, a check-back in the wrong moment strands a waiting answer, a thread started without report back is outside every Stop, and wrapping a thread does not stop reports to it. The reviews have turned into an audit of the child-thread code that is already shipped. That is useful, and it is also why a plan review will keep finding things: each one reads further into code the plan did not write. -1. `childDeliveryForTurnEnd`: M's answering turn completes with owed work → `awaiting_background` with that turn as the candidate (unchanged path, wider input). -2. A turn in M started by **a report from one of M's own children** (`fromThread.kind === "report"`, the report's `threadId` attached to M) continues R's `awaiting_background` request, exactly as a follow-up turn started by background work does today (`pendingMessageId === null`). Completed with owed work left → it becomes the new candidate. Completed with none → R's request settles `answered` with that turn's last reply. Failed or stopped → settles as today. - - A turn started by the user or by R's own `thread_send` still answers only its own message (unchanged). -3. `isQuietCandidate` also requires no open child requests, and the reactor re-checks quiet candidates when **M's child requests settle** (`thread.child-request-settled` on M), not only on M's `session-set`. That covers M's last child settling with no report (`thread_stop` by M, declined approval, separated by the user): M takes no turn, so R's request settles with the candidate. -4. Restart: an `awaiting_background` request whose candidate thread still has open child requests is **not** settled with the candidate at startup. Those child requests recover by their own rules and wake M, which continues R's request. Only background work dies with the process; child requests don't. -5. Usage-limit continue: a report turn in M that continues R's request is heldable like an answering turn (`answersHeldableRequest`), so "continue at reset" keeps R's request open instead of failing it. -6. Linked computers: the link ledger path (`LinkRequests`) uses the same `childDeliveryForTurnEnd`; a remote child is fenced from starting threads, so it never has owed child requests. No change there beyond the shared input. +The rules that came out of the fourth and fifth reviews each remove a case instead of handling it: -R's shell keeps showing "Waiting · N threads" from `awaitedChildThreadCount`; it counts R's own open requests, which now stay open while grandchildren work. That's the truthful state. +| The case | The rule that removes it | +| ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| A runtime that dies mid-turn is read as the user's Stop | A turn was stopped on purpose only if it is the turn a Stop named. Main already records that (#1057) | +| A runtime exits and a new session hides the evidence | The handler that ingests the exit settles the running turn there and then, and the next turn start sweeps anything left | +| A check-back, a goal's turn or anything else is taken for background work coming back | Nothing continues a waiting answer. It ends when the child's next turn starts, whatever starts it | +| A continue after a usage limit runs with wider access | A continue keeps the ceiling of the turn it continues | +| An agent starts a thread no Stop reaches | A thread started without report back stays under its starter's Stop until the user writes in it | +| A saved check-back fires in a thread Stop skipped | A listed check-back counts until the runtime that could fire it has ended, and then it is marked dormant | +| A wrapped thread is woken by a later check-back | A report is dropped while its parent is wrapped, by the parent's state, not by an epoch | +| Revert names a Stop control that isn't shown | One "still going" test for the refusal, the stop and the count | +| A retry runs ahead of reports that waited longer | In an idle thread, agents' messages run in the order they arrived | +| An old client breaks on a new event | The one new event type is never sent on the thread stream | -### Stop, wrap, archive and delete reach the whole subtree +What rev 4 gave up stays given up: in a room, a thread's later reports wake the agent that started it, and the lead can hear about work the user asked a middle thread for directly. -Each stays one decision in the decider, so nothing slips through between steps (the failure T3 Code's bug list is full of): +The fifth review asked one narrow question, whether rev 5 opens a new class of problem, and found none. It found seven sequences that needed an explicit outcome and a test. They are listed under "The seven sequences from the fifth review", and Astra has agreed that after this round the reviews move to each build step's diff. -- **"Stop N working threads"** (`thread.children.stop` without ids) stops every working descendant, not just direct children: each thread's own Stop rules apply (its open requests settle `stopped`, queued reports unqueued, notes added). The menu count is the subtree's. `thread_stop` from an agent on its own child stops that child's subtree too, so a lead can end a whole branch in one call. -- **Stop on a thread itself** keeps today's rule: its requests settle, its children keep running. Changing that is a separate decision Will made (child-threads.md decision 4 covers wrap; Stop follows it). -- **Archive cascade** recurses: a settled attached descendant is archived and stamped `archivedWithParentAt`; a live one is separated, with its own subtree staying attached to it. Unarchive restores everything stamped by that archive. -- **Delete with its threads** deletes the whole attached subtree; without it, direct children are separated and keep their own subtrees. -- **Auto-wrap** already reads the parent's done state recursively (`fileInboxThreads.resolveDone`); only the "one level deep" comment changes. +### The decision: every turn a child finishes on its own goes up as a report -### Sidebar +Today a child talks to its parent in two ways. An **answer** settles a request the parent made, and wakes the parent. A **late reply** is work the child did afterwards with no request open. It wakes nobody, and the parent's agent reads it at its next turn (`lateReplyOf`, `childThreadDelivery.ts:381`). -The root's family shows every attached descendant, in tree order (each child followed by its own descendants, creation order within a level), one line each, indented one step per level below the first. The summary line ("●●● 7 threads · 1 needs you") counts the whole subtree. A collapsed family still shows any descendant that needs the user, and the open one. A middle thread's row gets the same menu items a parent row has ("Stop N working threads" for its subtree). Indentation steps stop growing after level 3 so titles keep room on a phone. +With nesting, almost everything a middle thread does after its first answer is a late reply. M answers R "I started G1 and G2", and that settles R's request. G1's report then wakes M, M does the real work, and R never hears of it unless something else wakes R. -`familyParentKeyOf` stays the direct parent; a new `familyRootKeyOf` walks up attached parents (with a visited set) to pick the family a row renders under. +Three ways to fix that: -### Chat +1. **Hold R's request open until M's own threads have settled** (rev 1). The first review showed five ways this loses or misroutes an answer. One request has to stay bound to a chain of M's turns that nobody planned, across restarts, usage limits and other messages arriving in M. +2. **Hold nothing, and report every turn** (T3 Code's `completionWake: "always"`, `OrchestratorMcpService.ts:2975`). R's request settles when M's answering turn ends, as today. Each later turn M finishes on its own goes to R as a new report and wakes R. +3. **Report only when M's whole subtree is quiet.** A stuck or days-long G would silence everything M learns in the meantime, and the server would need a re-check for every way a subtree goes quiet. + +Every revision since rev 2 takes option 2. What it costs: R is woken once for every turn a child finishes on its own, and each piece of news climbs one turn per level. A middle thread that checks back every five minutes wakes its parent every five minutes. That is the risk T3 Code takes and Will accepted. The preamble tells a child that each of these replies wakes the thread above it. + +### Delivery rules + +1. **Requests are unchanged.** A request answers to the turn its own message started (`childDeliveryForTurnEnd`). It waits past that turn only for the child's own background tasks (`awaiting_background`), never for the child's threads. +2. **Which turns report.** A turn in an attached child on this computer owes its parent a report unless one of these is true. Each is read from the message that started the turn, when the turn starts, never from what is open when it ends: + - The message is a request from its parent. That turn answers the request (rule 1) and is never anything else, even if the request is cancelled before the turn ends (the agent that asked left, `decider.ts:3376`). + - A person wrote the message (`composer` or `sentFrom`, `personWrote`, `childThreadDecisions.ts:2153`), or an outside agent did (`fromOutside`). + - The message is a hand-off from another agent in the same thread. That reply goes to the agent that asked (`routeHandOffReply`), and the turn that agent then takes reports. + - The message is a continue (`trigger`: a usage limit reset, a restart, an account switch) of a turn a person or an outside agent started. A continue is judged by the turn it continues. If that turn answered a request and the request is moved onto the continue in the same decision, as continue at reset does today (`decider.ts:5496`), the continue answers it. In every other case the continue reports. -Nothing new: a middle thread already shows "Started by " and its own "Started N threads" cards. The attached-child preamble adds one sentence when the thread may start threads: "Threads you start report back to you; your final answer goes back once they have." + Everything else reports: a report from one of its own threads, the reply to a hand-off or a review, a scheduled run, an automatic fix, and every turn the provider starts with no message (a check-back, background work that finished). -## Every surface +3. **The owed list.** The decision that starts a reporting turn adds an entry to a short list on the child: the turn, the parent's delivery epoch and the child's attachment epoch as they are then. The entry is the durable promise. It is removed when the report is settled, and the whole list is emptied when the child's attachment epoch moves. + - For a turn a message starts, the decision that emits `thread.turn-start-requested` adds it, keyed by the message, before the provider has taken the turn. + - For a turn the provider starts, ingestion says so on the session update that marks the turn started, and that decision adds it. + - The same decision sweeps the list. A new turn starting means every earlier turn in the thread is over, so any older entry still there is settled first, as a turn that ended without being stopped (rule 5). Nothing can leave an entry behind for good. + - The list lives in the thread's state, which the decider reads. No decision has to look up an old turn row. +4. **Nothing continues a waiting answer.** A request in `awaiting_background` holds the child's last reply as its answer so far. Today a later turn with no starting message is taken to be the background work coming back, and its reply replaces the answer (`childDeliveryForTurnEnd`, `childThreadDelivery.ts:134`). But a turn with no message can be a check-back, or the turn a goal starts when it is handed straight to the provider (`setThreadGoal`, `ProviderCommandReactor.ts:4374`), and no provider says "this turn is the background work coming back". So the guess goes, on this computer: + - The waiting request settles with its answer so far when the child's next turn starts, whatever starts it: the user's message, a room agent's, a report, a later request, a check-back, a goal, or the background work itself. The decision that starts that turn settles it first. This replaces `settleCandidateBeforeUserTurn` (`decider.ts:562`), which does the same today for the user's turns only. + - It also settles when the child goes quiet with nothing left running, as today (`isQuietCandidate`, `childThreadDelivery.ts:271`). That check needs the answer so far to be the child's newest turn, which is now always true while a request waits. + - The turn that started then reports or answers by rule 2, like any other. -- **Providers.** Thread tools already reach Codex, Claude, OpenCode and HTTP ACP agents through the room endpoint; children get them like any thread. No per-driver change. -- **Clients.** Web and desktop share the sidebar; phone gets it through the same components. -- **Contracts.** Constant and counter removals; no new wire fields (descendant walks are computed). -- **App guide.** Rooms topic and threads topic lose the limits and gain "threads can start threads". -- **Reverse states.** Stop subtree ↔ next message resumes each; archive subtree ↔ unarchive restores the stamped ones; separate ↔ put back (now allowed at any depth). + What it costs: when background work does come back, the parent hears twice, once with the answer so far and once with the follow-up, where today it hears once. In a parent with no parent of its own the second usually lands in the turn the first started, because reports are steered there. If a driver later marks a turn as started by finished background work, that turn can answer the request directly again. -## Tests (extend existing files) +5. **Settling a report.** When the turn ends, `thread.child-report.settle` decides it once and removes the entry. + - Completed with a reply: delivered. + - Failed: delivered as "'' failed: <error>." followed by "It continues by itself when the limit resets." when the thread waits to continue at a reset, and by "Send it a message with thread_send to continue." otherwise. Nothing is held for the continue. The continue is a turn of its own and reports when it ends. + - Stopped on purpose, or completed with no reply: dropped. + - Ended without being stopped: delivered as "'<title>' stopped before it finished: <reason>. Send it a message with thread_send to continue." +6. **Stopped on purpose is a recorded fact, not a guess.** Since #1057 a Stop names the turn it is for, and the session keeps it until another turn starts (`stopRequestedTurnId`, `packages/contracts/src/orchestration.ts:2212`; both the user's Stop and a session stop set it, `ProjectionPipeline.ts:2224`). A turn that ends interrupted was stopped on purpose only if it is that turn. Today every interrupted turn is treated as the user's Stop: when Claude's stream ends mid-turn the adapter closes the turn as interrupted (`ClaudeAdapter.ts:8479`), and the parent is told "The user stopped" the child (`childThreadDelivery.ts:183`). New: + - A request's answering turn that ends interrupted says "The user stopped '<title>' before it finished." only when it is the turn Stop named. Otherwise the request settles `failed` with the text in rule 5. + - **An exit settles the turn it took with it, where the exit is ingested.** Codex can emit `session.exited` with no turn end (`CodexAdapter.ts:1937`). Ingestion clears the running turn there (`ProviderRuntimeIngestion.ts:3496`), so it knows which turn that was, and it routes that turn's end through the same function as any other turn end, in the same handler, before the next event. Today this is left to a reactor that waits five seconds and then rereads the session (`ChildThreadReactor.ts:305`, `:355`). If a message starts a new session in that time, the reactor sees a running session and does nothing, and the old turn is never settled. The reactor stays as a backstop for a request, and the sweep in rule 3 is the backstop for a report. + - A waiting request (`awaiting_background`) whose child's session ends without a Stop settles `answered` with its answer so far, as it does after a restart. + - This replaces rev 4's plan to mark the idle reaper's stop. The reaper never issues a Stop, so nothing it closes is named, and nothing it closes is called the user's doing. No new field on the session is needed. +7. **When a report is dropped instead.** The decision delivers only if all of these hold. Otherwise it drops the report, and a dropped report stays dropped. + - The entry's two epochs still equal the parent's delivery epoch and the child's attachment epoch. This catches a completion that crosses a `thread_stop`, a separate and put back, or the parent's Stop (`childThreadDecisions.ts:1417`, `:1865`, `:1963`). + - The child is still attached to that parent, and neither is deleted. + - The parent is not archived, and is not wrapped up by hand right now (its done override, set by the user or by its own parent's agent). The epoch can't carry this one. A wrap moves it at most once (`decider.ts:2308`), and not at all when the thread has nothing open (`childThreadDecisions.ts:1941`), and a turn that starts after the wrap records the new value. "Wrapped right now" means its done override says done and is newer than its newest turn, the test the sidebar already files by. Reopening the parent lets reports through again. + - Neither thread is under the user's Stop hold. +8. **What a delivered report is.** A user-role message in the parent with `fromThread { threadId, requestId, kind: "report", followUp: true }` and a queued follow-up, as an answer is delivered today. The schema requires `requestId`, so it carries one derived from the child's turn. It goes to the agent that started the child, or to the thread's own agent if that one has left the room. If that agent leaves while a follow-up report for it is still queued, the leave decision hands the queued report to the thread's own agent. Today it takes every queued report for a leaving agent off the queue (`decider.ts:3394`), which is right for an answer to a request that agent made and wrong for a report nobody asked for. The message carries the current epochs, so the existing checks before send still apply (`isCancelledReport`, `childThreadDecisions.ts:2231`). The text is clipped as answers are. The child is stamped handed back as of that turn, so it wraps itself as it does after an answer. The builder checks `pushAlertRules.ts`, which cancels a child's "done" alert on `child-request-settled`. A follow-up has no such event, and it must not alert the user each time a child reports. +9. **A middle thread reads each report in a turn of its own.** Today a report is steered into a running turn where the provider can steer (`steerQueuedAgentMessage`, `ProviderCommandReactor.ts:5501`). In an attached child, a report from one of its own threads is never steered. It waits and starts its own turn, which reports. So a report can't be swallowed by a turn the user started, and two tasks can't end up in one answer. A thread with no parent steers as it does today. Its turns report to nobody, so nothing can be lost there. +10. **After a failed turn, the reports that waited are read first.** After a turn fails, the thread's queue is sent on only when something new is queued or a later turn ends (`maybeSendNextQueuedFollowUp`, `ProviderCommandReactor.ts:6203`). So a report that waited behind the failed turn (rule 9) sits unread, while the thread that sent it is already stamped handed back. Two changes: + - The failure report counts them: "'<title>' failed: <error>. 2 reports from its threads are waiting in it unread. Send it a message with thread_send and it reads them first." + - That last sentence is not true today. When a message is queued in an idle thread, the handler sends that message, picked by its id, ahead of anything an agent queued earlier (`processFollowUpQueued`, `ProviderCommandReactor.ts:6076`). New: in an idle thread, the handler sends the oldest message an agent queued, not the newest. The user's own queued messages still go before any agent's, as today. So the parent's retry runs after both reports. If the first report's turn fails too, the parent is told again with the new count, and nothing has been skipped. -- `roomAgentRequests`/`agentRequestDecisions`: a fourth and a fortieth request are accepted. -- `childThreads` shared tests: starts and sends past the old limits accepted; an attached child can start, send, stop and wrap; put back allowed for a thread with its own children. -- `decider.childThreads.test.ts`: create under an attached child; subtree stop in one command; archive and unarchive of a three-level family; delete with children three levels. -- `childThreadDelivery` tests: M's answering turn with an open child request → `awaiting_background`; G's report turn in M with nothing left owed → R's request answered with that reply; with more owed → new candidate; M's last child settled without a report → quiet candidate settles; restart keeps an awaiting request whose thread still has open child requests. -- `Sidebar.logic` tests: tree order, indentation level, subtree counts, root key walk. -- Browser: the family rows render three levels; polish shot with real fonts, light and dark unchanged colours. -- Live: a throwaway stack (never `~/.threadlines/userdata`), a Claude root starts a child that starts a grandchild; the grandchild's answer reaches the root and wakes it; "Stop N working threads" on the root stops all three levels. + The queue is not sent on by itself after a failure. That would burn one failed turn per queued report in a thread that keeps failing. + +11. **A start that fails.** When preparing the provider fails or times out, no turn ever ends (`reportFailedStart`, `ProviderCommandReactor.ts:3427`), and today a parent's request for that child stays `running` for good. New: a failed start settles what its message owed. A request settles `failed` ("'<title>' could not start its turn: <error>"). An owed entry delivers the failure report. A start that is taken back on purpose before the provider took it (a report that went stale, a Stop while the turn was being prepared) removes its entry and sends nothing. +12. **No more late replies on this computer.** With rule 2, the only unasked work that does not reach the parent is work that was dropped on purpose. So `lateReplyOf`, `lateReplyRecipient`, `lateRepliesForAgent` and the `lateReplies` part of `thread.child-notes.delivered` go. Late replies that were unread at the upgrade stay in the child for `thread_read`. A child on a linked computer never had late replies and still doesn't. +13. **Continue at reset.** `reportsToTopLevel` (`decider.ts:929`) arms the wait for a report turn only in a thread with no parent. It drops that condition, so a middle thread's report turn continues by itself too. Whether it waits or not, its failure has already gone up (rule 5). +14. **Restart.** Startup settles every entry on every owed list whose turn has ended or never started. There is no time window, and turns from before the upgrade have no entry. + - A turn that completed before the crash is delivered. + - A turn the restart cut off, or that failed, delivers its failure. For a cut-off turn the text is "'<title>' was interrupted by a Threadlines restart. Send it a message with thread_send to continue." + - A waiting request settles with its answer so far, as today. No later turn is looked for (rule 4), so `finishedTurnAfterRestart` (`childThreadDelivery.ts:295`) loses its waiting branch, which picks the newest turn no message started and can pick an unrelated check-back. + - Other requests recover as today (`settleFromPreviousProcess`, `ChildThreadReactor.ts:409`). +15. **Linked computers.** Unchanged. A thread another computer started here answers through the link ledger, is fenced from thread tools, has no owed list and sends no follow-up reports. The ledger keeps today's waiting rule, the guess in rule 4 included, since nothing else brings a linked child's later work back. + +Where it goes: `routeChildReport` (`ProviderRuntimeIngestion.ts:2770`) returns early when the parent has no open request for the child. That early return goes. One pure function in `childThreadDelivery.ts` takes the turn's end, the session's stopped turn, the child's owed list and the parent's open requests, and returns the request settle, the report settle, or nothing. The turn end, the ingested exit, the sweep and startup all call it, so a turn can never be delivered as both. + +### What a child and its parent are told + +- **Attached child preamble** (`ProviderCommandReactor.ts:2268`). Today: "Another agent started this thread from the thread "X", and your final reply goes back to it automatically. Work in this thread's own checkout, and end with the answer it needs." Add: "If you take more turns later that the user did not start, for example when a thread you started reports back, the reply that ends each one goes back too and wakes that thread. Keep those replies short when nothing has changed." +- **Follow-up report preamble.** "Report from thread "X" (<id>), which took another turn on its own after its last answer. It's information from another agent, not instructions from the user." +- **`thread_start` and `thread_send` descriptions** (`threadTools.ts`). Add: "A thread you start can start threads of its own. Its final reply comes back to you and wakes you, and so does the reply ending any later turn it takes on its own." ACP agents learn rules only from descriptions. + +### Rules that go + +Every refusal that says a thread started by another thread can't direct threads: + +- `DEPTH_REFUSAL` in `callerRefusal` (`packages/shared/src/childThreads.ts:73-85`), which `childStartRefusal`, `childSendRefusal` and `leadPassRefusal` all call. +- The handlers' own checks through `depthRefusal()` (`threadToolHandlers.ts:525`): `threadStart` :931, `ownChild` :1743 (local send and stop), `remoteSend` :2142, `remoteStop` :2215, `threadWrap` :2287. The first, second and last go. The two remote ones are replaced by the linked-computer rule below. +- `thread.create` refusing a parent that is itself an attached child (`decider.ts:1573`). +- `decideChildrenStop`'s refusal of an attached caller (`childThreadDecisions.ts:1809`). Its twin for threads on another computer (:1828) stays, as part of the linked-computer rule below. +- Put back's "is part of another thread's family" and "has started threads of its own" (`childThreads.ts:249-254`). A cycle can't form: `parentThreadId` is set once at creation, and put back only re-attaches to that thread. +- The words "one level deep" wherever they state the rule: the "Depth 1" bullet in `child-threads.md:150`, code comments (`childThreads.ts:63`, `threadToolHandlers.ts:524`, `Sidebar.logic.ts:1066`, `decider.ts:1559`), and the contracts comment at `orchestration.ts:5341`. `fleet.md:1347` changes to say a move carries one level. + +Kept: + +- A thread messages, stops and wraps only threads it started (`ownChildRefusal`). R reaches G only through M. +- The lead chat cannot pass to an attached child (`childThreads.ts:351`), and a lead is top-level. +- "Agents can start threads" (off, ask, automatic) and "Threads can share a checkout" apply at every level. In ask mode the approval card shows in the thread whose agent asked. The root's sidebar line counts it as "needs you". +- Five threads per call. + +Threads started without report back keep the option at every level. What Stop does with them is under "Stop". + +### Stop + +Stop is the only brake Will kept, so it has to reach everything an agent can set going. + +- **Stop reaches everything an agent started that the user has not made their own.** There are two kinds of thread under a thread. An attached one reports back and shows in its family. A loose one was started with `reportBack: false`: it is its starter's child on paper but was never attached (`ThreadBootstrap.ts:687`), its request settles as soon as it is set up (`ChildThreadReactor.ts:266`), and it shows as a row of its own. Today no stop reaches a loose thread, so an agent can start any number of them outside its own Stop, and each can do the same. Decided by Will: the option stays, at every level, and a loose thread is under its starter's Stop until the user makes it their own. + - **The user makes it their own by writing in it.** The server keeps one optional flag on a thread started without report back, set when it is made and cleared for good by the first message a person writes there (`composer` or `sentFrom`), or when the user puts it back under its parent. A thread from before this change has no flag and is the user's. + - **Stop's reach** is every attached thread under the stopped thread, plus every flagged loose thread under it, and so on down through both kinds. Every subtree stop uses that walk: the user's Stop, "Stop N working threads", the button on the tab row, and an agent's `thread_stop` on a child. + - **Only Stop uses that walk.** Reports, the sidebar's family, the tabs, wrap, archive, delete and revert follow attached threads only. A loose thread reports to nobody, so it can't wake anything above it. + +- **The Stop button stops the thread and everything in its reach.** Decided by Will. `thread.turn.interrupt` is what the composer's Stop and an outside agent's stop send (`ChatView.tsx:6537`, `connectToolHandlers.ts:2348`). Its decision (`decider.ts:4716`) keeps what it does today to the thread itself, and in the same decision stops every thread in its reach that is still going. This is T3 Code's rule (`ThreadManagementService.ts:1743`), and it replaces "children keep running" from `child-threads.md`. With reports climbing on their own and no limits, a subtree left running can keep itself going with nobody watching, and it spends the user's usage. A stopped turn can be resumed with a message. Spent usage can't be taken back. +- **Still going** is one test, used for what a stop targets, for the count in "Stop N working threads" and on the tab row's button, and for the revert refusal, so a refusal never names a remedy that isn't on screen. A thread is still going when it has any of: a turn running or starting, a queued message or a pending start, an approval, question or plan waiting on the user, background work of any kind, an open request of its own, a wait to continue at a reset, or a check-back that can still fire. An idle session with none of these is not going. The test goes in `packages/shared`, written over fields the thread's shell and its detail both have. Today the server's target test is `childHasLiveWork` plus open requests (`childThreadDecisions.ts:1813`), and the client counts only the Working, Starting, Answering and Waiting pills (`Sidebar.logic.ts:1783`), so they disagree on a thread that only checks back. +- **A check-back that can still fire** is any check-back on the thread's list that is not marked dormant, a saved one included. This is main's own Stop test (`hasLiveCheckBack`, `packages/shared/src/checkBacks.ts:101`), and rev 5 was wrong to narrow it to check-backs that die with the runtime: a saved job fires in a runtime that is still alive, with nobody writing. What main's test can't say is when a saved job has stopped being able to fire, so a thread with one would count as going for ever, and the revert refusal would never clear. New: when an agent's runtime ends, for any reason, the check-backs still listed for that agent are marked dormant in the same list write. A dormant one does not count. When that agent runs again its runtime reports its list afresh, which replaces the agent's entries (`replaceAgentCheckBacks`, `checkBacks.ts:8`) and so clears the mark. The sidebar's "Checking back" pill ignores dormant entries too. +- **Check-backs end with Stop.** Since #1057 the user's Stop cancels every agent's check-backs in the thread and stops the runtimes that hold them, background work included (`endCheckBacksOnStop`, `decider.ts:1204`), and a check-back reported just after Stop is cancelled too (`ProviderRuntimeIngestion.ts:2976`). Rev 4 had to plan around check-backs that outlived Stop. That is gone. One limit stays, noted on main: a quiet child on a linked computer that holds only a check-back is not reached by `thread_stop`. +- **A stop has a cause, and the cause decides the hold.** Today every stop runs `decideAgentChainStop`, which leaves the durable hold (`agentRequests.hold`) on a thread in a room or with an agent's message in its queue (`agentRequestDecisions.ts:1019`). A held thread's agent can't start or message threads (`callerRefusal`), and a parent's request does not lift the hold (`decider.ts:3991`). With one rule for every stop, a subtree stop would leave M and G held, and after the user wrote to R the team would stay stuck. So `thread.session.stop` takes a server-only cause, and the chain stop reads it: + - **The user's Stop** (`thread.turn.interrupt` on the named thread). The hold always goes on when the thread is an attached child, has attached children or has open child requests, and its delivery epoch always moves. + - **Stopped with its family** (a thread under that Stop, a child stopped by `thread_stop`, "Stop N working threads"). No new hold. Its attachment epoch moves, its queue is cleared of agents' messages, and it takes its parent's next message without the user writing in it. A hold it already had from the user's own Stop in it stays. + - **Cleanup** (archive, delete, the sweeper, a move, a link: `ws.ts:1374`, `:1465`, `ThreadAutoArchiveSweeper.ts:170`, `LinkRequests.ts:1271`). No new hold, and no cascade. An archived thread that comes back must take work again. +- **What the hold does.** The held thread's agent can't start or message threads. Reports to it and from it are dropped (delivery rule 7). `childSendRefusal` refuses a parent's send to a held child with the words the lead's pass already uses: "The user stopped that thread. It takes work again once they write there." Today such a message sits unseen in the child's queue. +- **What lifts the hold stays as it is today.** A message that no agent wrote lifts it: the user's, and also a scheduled run's or an automatic fix's (`decider.ts:1049`, `:1092`, `:3991`, `ProviderCommandReactor.ts:6039`). Those are automation the user set up, a schedule that targets a stopped lead keeps working as it does now, and rooms don't change. +- **One automatic path is closed.** When a provider session falls back, the server resends the turn's message by itself (`processNativeSessionFellBack`, `ProviderCommandReactor.ts:6397`), and a resend lifts the hold (`decider.ts:4197`). `thread.turn.resend` already refuses a resend whose chain epoch has moved (`decider.ts:4046`), but the fallback sends no epoch. It now sends the epoch of the turn it resends, so one that arrives after a Stop is refused. +- **What Stop does not take back.** A report the thread had already finished and queued in its parent before the Stop still reaches the parent. The user stopped this thread, not the one above it, and a child the user stops even tells its parent so. To stop the parent, stop the parent, which clears its queue of agents' messages. +- **What stopping a thread under it does.** What `thread.children.stop` does to a child today (`childThreadDecisions.ts:1785`): its parent's requests for it settle `stopped` with no report, its parent's messages still queued in it are taken back, the reports it queued upward are unqueued, the turn it was cut off in is stamped handed back, its attachment epoch moves (which empties its owed list), and its session is stopped with the family cause. Targets are found by walking `parentThreadId` from the thread records before anything is settled, so stopping M first can't hide G. +- **Stop inside a middle thread** stops M and everything under M. R hears as today if a request for M was open ("The user stopped 'M' before it finished."). +- **"Stop N working threads"** (`thread.children.stop` without ids) stops every thread in the row's reach that is still going, and N counts exactly those, loose ones included. The thread itself keeps running and gets no hold. +- **`thread_stop` from an agent** stops that child and everything in the child's reach. It returns `stopped` when anything there was still going, and `not_running` only when nothing was. `childHasWork` (`threadToolHandlers.ts:335`) moves to the same test over that reach. An agent still can't name a loose thread: it only stops threads that are attached to it. +- **An outside agent's stop** reaches only the threads that agent may stop itself. `outsideStopRefusal` (`outsideTurns.ts:158`) is asked for each one. A thread the user gave more access than that agent's limit keeps running, and the tool's answer names it. +- **A Stop button on the tab row.** Decided by Will. A root that waits on its team has no running turn, so its composer shows no Stop button, and today the only brake is in the row's menu. The chat's family tab row gets a plain "Stop N threads" button at its end while anything in the open thread's reach is still going. N is the menu item's count, and it sends the same command. + +### Wrap, archive, delete, revert, separate, put back + +Each is one decision, as today. The subtree is found with one shared walk (see "Data model"). + +- **Outstanding work** is the test for wrapping. It asks a different question from "still going": not "can this start a turn by itself" but "is something unfinished here". A thread has outstanding work when `childHasLiveWork` says so (`childThreadDecisions.ts:1724`): a running turn, an approval, a question, a plan, awaited background work, a queued message, or an open request of its own, which includes a start still waiting for the user's yes. An idle session that is merely still open does not count, and neither does a check-back, as today. +- **Auto-wrap** (`isThreadDone`, `Sidebar.logic.ts:873`). A thread that waits on requests of its own is already held open: `canMarkThreadDone` (`:739`) reads the Waiting pill, which covers a start not yet made into a thread. That holds M while its request to G is open. It does not hold M after G's first answer, when G works on and M has nothing open. New condition on the handed-back rule: an attached child does not count as done while any thread under it is working, waiting, or needs the user. The "its parent is done" rule stays and already recurses (`resolveDone`, `:1096`). +- **`thread_wrap`** returns `working` for a child when it or anything under it has outstanding work (`agentWrapRefusal`, `childThreadDecisions.ts:2106`). Wrapping a finished M wraps M only; its finished threads follow by the "parent is done" rule. +- **Wrapping a thread by hand** keeps decision 4: nothing under it stops. Its open requests are cancelled, and while it stays wrapped, reports to it are dropped (delivery rule 7). Its live children stand on their own in the sidebar with "↳ <title>", as a wrapped parent's children do today. +- **Revert is refused while anything under the thread is still going.** Today revert is refused only while the thread has open requests or queued reports (`childRevertRefusal`, `childThreadDecisions.ts:2189`). With reports after the first answer, R can hold neither and still have G working for M. Reverting then would let M wake R about a task the revert removed. New: revert is refused in a thread while any attached thread under it is still going, by the Stop test, with today's words ("Finish or stop its threads first..."). Loose threads are not counted here, because they report to nobody. Because it is the same test "Stop N working threads" counts by, the menu item is always there when the refusal shows. After it runs, every runtime under the thread has ended, so every check-back there is dormant, the test is false, and revert goes through. +- **Archive.** Main already has the rule for one level (#1056, `childArchivePlan`, `childThreadDecisions.ts:2072`): a child is live, and is separated instead of archived, when it has work of any kind, a request open from its parent, or a check-back that would die with its runtime. The cascade applies that same test going down. A settled attached thread is archived and stamped `archivedWithParentAt` with the root's archive time. A live one is separated from its parent and keeps everything under it. The walk does not go below a thread it separated. Unarchive restores every thread stamped by that archive (`childrenArchivedWith`, `childThreadDecisions.ts:2171`). The sweeper and "Archive inactive threads now" already skip a thread whose check-back is still owed; they also skip one with a live thread anywhere under it. One limit stays, noted on main: a child on a linked computer that is mid-request is still stopped when its parent is archived. +- **Delete names what it deletes.** Since #1051 the client winds down only the thread the user named, and the server cleans up each thread it really deletes (`ThreadDeletionReactor.ts:67`), so a thread the server keeps no longer loses its terminals. What is left is the count: the dialog counts from the client's store, and the server builds its own list when it decides (`decider.ts:1940`), which can hold a thread started in between. New optional `alsoDelete` on `thread.delete`: the ids the dialog listed. The server deletes exactly those that are still attached, unarchived threads under the named one. Any other attached thread under a deleted one is separated and kept, with what is under it. Archived threads are never in the list and are never deleted this way, on either end. `withChildren` alone keeps today's meaning for a client that has not updated, including today's small race: a direct child that appears between its count and the server's decision is deleted too. The old command has no way to say which threads it meant. +- **Separate** ("Make it its own thread"). The thread leaves with everything under it still attached to it. +- **Put back** works at any depth and for a thread with threads of its own. One new refusal: a thread that has threads on another computer (`remoteChildren`, or an open request to one) can't be put back under a parent. Today's check does not look at them (`childThreads.ts:252`). + +### Access, the lead's pass, linked computers, moves + +- **Every message that carries a parent's work carries the parent's access, and it is checked wherever a pass's ceiling is checked today.** A child's access is checked at start today (`decideChildStart`, `clampLaunchToCeiling`, `thread.create`). A send checks nothing (`childThreadDecisions.ts:703`). New: a parent's request carries a `requestCeiling`, the sender's access when it sent, or its pass ceiling if that is narrower. One helper compares it with the receiving thread's access: + - at the send; + - at every decision that starts a turn from a stored message (the ones that call `passCeilingRefusal` today, `decider.ts:3605`, `:4088`, `:4458`); + - in the reactor, when it prepares the session and when it starts the turn (`ProviderCommandReactor.ts:1452`, `:2629`). The reactor rereads the thread there, so a thread the user widened after the decision would otherwise run the request with more access than its sender. + + Words: "'<title>' has more access than this thread has now. Do the work here, or tell the user, who can send it there." It refuses and does not lower the child, because agent traffic never changes a thread's settings (`decider.ts:4540`). Narrowing a parent does not reach down the tree by itself. + +- **A continue keeps the ceiling of the turn it continues.** The reactor reads the ceiling from the turn's own starting message (`ProviderCommandReactor.ts:2584`). A continue after a usage limit is a fresh message with the thread's current access and no origin (`decider.ts:5463`), and the parent's request is moved onto it afterwards (`decider.ts:5496`). So today, and under rev 4, a child the user widened while it waited runs the parent's request with the wider access, and no check has anything to read. New: the ceiling is a field of the message, not of its origin, and every continue (a usage limit reset, a restart, an account switch) copies it from the message that started the turn it continues. The same helper then refuses the continue's turn in the decision and in the reactor. A refused continue ends the wait without continuing, and the request it held settles `failed` through the helper that ends held requests today (`decideHeldRequestsEnd`, `decider.ts:1274`), with the words above. +- **Over the link, the ceiling is sent, and both ends have a rule for the case where it can't be.** Decided by Will. Today a send to a child on a linked computer carries only a request id, a thread id and the text (`PeerSendInput`, `peerRpc.ts:360`), and that computer runs it at the thread's own access (`decideRemoteRequestQueue`, `childThreadDecisions.ts:1276`). New optional `ceiling` on that send, and a new flag on what a linked computer says about itself (`PeerDescriptor`, `peerRpc.ts:213`, where optional flags such as `moves` already mean "absent: an older server"). Four cases: + - **Both updated.** The receiver stores the ceiling on the message, and the same helper refuses the turn there if the thread's access is above it. + - **The sender is updated, the receiver is older.** The receiver can't check anything. The send is allowed only when the sender has the widest access there is, where no ceiling can be broken. Any narrower sender is refused: "<computer> runs an older Threadlines that can't hold this thread's access limit. Update it, or send the work yourself." + - **The sender is older, the receiver is updated.** The request arrives with no ceiling, and the receiver can't know the parent's access. It gives the request a ceiling of its own: the thread's access when the request arrived, or the access the link started the thread with if that is narrower. A thread a link starts from now on records that access on its `remoteOrigin`. So a child the user widened on the receiving computer does not run that work wider. One thing stays out of reach: a parent the user narrowed on the older computer, below what its child was started with. Only that computer knows, and it is closed when it updates. + - **Work queued before the upgrade.** A queued request with no ceiling is given one when its turn is about to start, by the same two rules: from the parent's access now when the parent is on this computer, and as an older sender's request when it came over a link. +- **A lead's pass keeps its block down a chain.** Today a thread working on a pass can't start threads but can message its own (`childThreads.ts:121-127`, `:165-188`). With nesting, that child could start threads, and one lead message would fan out after all. New: a request sent by a thread whose `passCeiling` is set also carries `passBlocked`. The decision that starts that message's turn sets the receiver's `passCeiling` to the request's ceiling (the narrowest, as passes do). The receiver's own sends carry it further. It is not `fromThread.ceiling`, which means "this is a lead's pass" in the preamble (`ProviderCommandReactor.ts:2262`) and in `answersHeldableRequest`. The block lifts when a person writes in that thread (today's reset), or when its parent's next request arrives without the flag, which can only happen after a person wrote in the parent. +- **Linked computers stay fenced.** A thread another computer started here still gets no thread tools (`isLinkFenced`). New fence: an attached child cannot start a thread on another computer ("A thread another thread started can only start threads on its own computer."), and `remoteSend` and `remoteStop` refuse the same way. So a nested tree lives on one computer, a subtree stop never crosses a link below the first level, and a report from another computer only ever arrives in a top-level thread. +- **A nested family does not move to another computer, and neither does a thread inside its nested part.** Today an attached child may move alone and stay its parent's child across the link (`threadMoveDecisions.ts:291-307`). With R, M and G, moving G alone would leave M owning a thread on another computer, which the fence above says cannot exist. So `threadMoveRefusals` refuses a thread when any of these holds: its parent is itself an attached child, or it is an attached child with attached children, or one of its children has attached children. A leaf directly under a top-level thread may still move alone, even when a sibling has threads of its own. That leaves the top-level thread with one child on another computer, which is allowed today and breaks nothing above. The check runs at admission and again when the move starts, because `decideMoveStart` re-runs the same function (`threadMoveDecisions.ts:900`). Words only, since the refusal codes are a closed set older peers decode: "This thread is part of a family more than one level deep, which can't move yet. Make it its own thread first." The web's move dialog and quit dialog show the reason (`threadMove.ts:898-1005`). Moving a nested family is a follow-up. +- **A move waits for reports in both directions.** "Move when done" waits today for the thread's own requests and its queue (`workWaits`, `threadMoveDecisions.ts:465`). Ingestion writes the session as ready before it routes the turn's report (`ProviderRuntimeIngestion.ts:3636`, then `:4144`), so a thread could freeze with a report still in flight. And when a parent and its child are queued to move together (`planFamilies`, `MoveQueue.ts:271`), the parent can freeze first, after which a settle against it is refused (`threadMoveDecisions.ts:866`) and the child, still owing, never follows. New: a thread counts as working for a move while it has an entry on its own owed list, while its parent has a request open for it, and while any thread attached to it has an entry on its owed list. So the child's turn ends, the report settles into a parent that has not frozen, and then both are free. +- **Outside agents and assistants** keep their own tool set. A thread one of them started stays fenced. A message one of them sends into a child is the user's own conversation, and its turn is not reported upward. + +### Sidebar + +Today a grandchild has no row at all, because `familyParentKeyOf` looks one step up and only a row with no parent draws children (`Sidebar.logic.ts:1563`, `buildInboxSections` :1911). + +- **One family per root.** A family is a live thread with no live attached parent, plus every thread reachable from it down attached links, as long as each link's parent is still in the live family. `familyParentKeyOf` stays the direct parent. A new `familyRootKeyOf` walks up, with a visited set. +- **Open family.** Every member gets one line, in tree order. Each thread is followed by its own threads, in creation order within a level. The first level sits where child rows sit today. Each level below is indented one step (12px), and the indent stops growing after two steps so titles keep room on a phone. +- **Summary line** on the root: dots and counts cover the whole family ("7 threads · 1 needs you"). There is one chevron per family. Middle threads get no summary line of their own. +- **Collapsed family.** It still shows any member that needs the user and the one open in the chat. They show without indent, because the rows that would explain the indent are hidden. +- **Wrapped members.** A wrapped member leaves the live family (`hasLeftLiveFamily`, :1618) only when no thread under it is still in the family. In Wrapped it holds its own wrapped threads inside it, at any depth, and its count is the subtree's. +- **A live thread under a wrapped parent** stands alone with "↳ <parent>" as today, and it now heads a family of its own. It draws its threads and gets a summary line. Today those threads vanish. +- **Fold, keys and attention.** A family still takes one seat. It has attention when any member has a status pill (`inboxLiveRowHasAttention`, :2097). `orderedThreadKeys` equals the rendered rows. +- **Menus and hover cards.** Every member's row gets "Stop N working threads" for the threads under it, "Make it its own thread", and the rest of a child row's menu. The hover card names the direct parent ("Started by <parent>") and, for a thread with threads, counts those under it. +- **Filters.** Project and computer scope apply to the root, and the family travels with it. + +### Chat + +- **Family tabs** (`familyTabs.logic.ts:84`, `lead-chat.md` "Family tabs"). The row shows the whole family the sidebar shows, root first, then every member in the sidebar's order. One function decides membership for both, as the lead chat design requires. It shows on every member while the root is live. A tab below the first level carries the small corner arrow the sidebar uses for "started by", and its tooltip names its parent. The "+N" menu indents its rows by level. The root's tab and the open thread's tab stay on the row. The row ends with the "Stop N threads" button described under "Stop". +- **Header chip, cards, pill.** "Started by <parent>" names the direct parent, which is right at any depth. "Started N threads" cards list the threads that turn started. "Waiting · N threads" counts the thread's own open requests. A root whose team is working with no request open shows no wait pill; its sidebar line and tabs show who is working. + +### Data model + +Everything here is an optional field on something that exists, except one command and one event. + +- **The owed list.** An optional list in the thread's child-request state (`childRequests`), which already travels in the thread's stored JSON. Each entry: the turn or the message that will start it, and the two epochs. Optional fields add an entry on `thread.turn-start-requested` and on the session update that marks a provider-started turn. `thread.handed-back` removes one when its report is delivered. +- **The report.** New server-only command `thread.child-report.settle`: child, turn, outcome, text, optional error. Its ids are derived from the child and turn. Delivered, it emits events that exist today (`thread.message-sent`, `thread.follow-up-queued`, `thread.handed-back`). Dropped, it emits one new event on the child that removes the entry. +- **That one new event type stays out of the thread stream.** Astra checked the assumption rev 4 left to the builder, and it was wrong: a client replays stored events when it resubscribes to a thread (`ws.ts:1744`), decodes them against a closed union, and fails the whole batch on a type it does not know, then retries from the same place. The server filters what it sends through `isThreadDetailEvent` (`ws.ts:248`). So the new event is not added to that filter, as `thread.lead-pass-recorded` is not. No client needs it: the owed list is the server's bookkeeping. And nothing rides on `thread.handed-back` with a flag, because an old client would read that as delivered. +- **The ceiling.** Optional `requestCeiling` and `passBlocked` on a message and on the commands and events that start a turn from it. Optional `followUp` on `fromThread`. `PeerSendInput` gains optional `ceiling`, and `PeerDescriptor` a flag that says the computer enforces it. `remoteOrigin` gains the access a link started the thread with. +- **Stop.** A server-only `cause` on `thread.session.stop` (`family`, `cleanup`), which the Normalizer refuses from clients. The chain stop can move the chain epoch without leaving the hold. The fallback's resend carries a chain epoch. Nothing new is stored on the session: the turn a Stop was for is already there (`stopRequestedTurnId`, migration 118). +- **Loose threads.** One optional flag on a thread and its shell: started without report back and not yet the user's. The projector clears it on the first person-written message and on a put back, so no new event is needed. +- **Check-backs.** Optional `dormant` on `OrchestrationCheckBack`, set by the server when the agent's runtime ends. +- **`thread.delete`**: optional `alsoDelete: ThreadId[]`. +- **Removed.** The late-reply functions and the `lateReplies` field's use. Old events that carry it still decode. The local rule that a turn with no message continues a waiting answer, and `finishedTurnAfterRestart`'s waiting branch with it. +- **Shared code.** `attachedDescendantsOf(threads, rootId)` in `packages/shared/src/childThreads.ts` returns the subtree in tree order with each thread's level, with a visited set. The "still going" test sits beside it. The server's stop, wrap, revert, archive, delete and move rules and the web's sidebar, tabs, menus and delete dialog use them. `attachedChildrenOf` (`childThreadDecisions.ts:193`) stays for the places that mean direct children. A second walk, Stop's reach, adds flagged loose threads at each step. +- **No migration.** +- **Older clients.** Every new field is optional, and excess fields are ignored when decoding. The builder confirms an older client decodes a thread and a message that carry them, as Part 1 did for the counters. + +### Every surface + +- **Entry points.** The composer's Stop, the sidebar row menu, the family tab row (tabs and its Stop button), the delete, archive and revert dialogs, the move dialog and the quit dialog. The command palette has no family actions and gets none. There is no keybinding for any of this. +- **Clients.** Web and desktop share the components. The phone uses them over the relay, so the indent and the tab row need a check at phone width. A phone or another computer on an older version shows a nested family the way it shows one today (grandchildren missing from the sidebar) until it updates. Its Stop and "Stop N working threads" still stop the whole subtree, because the server decides. Its delete sends `withChildren` and deletes one level. +- **Providers.** Every provider that gets thread tools today gets them in a child the same way (Codex, Claude, OpenCode, and ACP agents that take HTTP MCP). No driver changes. The plan reads two things a driver already reports: whether a provider-started turn is a check-back, and the list of check-backs, which only Claude has. Community agents get the behavior only through the generic core. +- **Contracts.** Everything under "Data model". +- **Reverse states.** Stop on a thread and the next message that no agent wrote. A subtree stop and the next message from above. Wrap and reopen, with reports dropped only in between. Archive and unarchive of what that archive stamped. Separate and put back at any depth. Delete has no way back, so it deletes only what the dialog listed. +- **The app guide.** The child-threads topic (`apps/server/src/guide/topics.ts:110-124`) changes in six places: threads can start threads; a thread that takes another turn on its own after its answer now wakes its parent with that reply, where it used to wait for the parent's next turn; Stop on a thread stops the threads under it, where the topic says today that they keep working, and "Stop N working threads" covers every level and counts a thread that only checks back; a thread another thread started only starts threads on its own computer; a thread started without report back is stopped with the thread that started it until you write in it; a thread can't be reverted while threads under it are still going. The lead chat topic's line on a pass target gains "and neither can the threads it messages". No setting row moves, so `appPlaces.ts` is unchanged. +- **Docs.** `child-threads.md` (Depth 1, Delivery, Late replies, Stop, revert, put back, archive, delete), `lead-chat.md` (family tabs, no fan-out, the usage-limit rule for report turns), `fleet.md` (a move carries one level; what a move waits for). + +### The seven sequences from the fifth review + +Each has one expected outcome and one regression test. The test names the file it extends. + +| # | The sequence | Expected outcome | Test | +| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | M has answered R and sits idle with a saved, recurring check-back and a live runtime. The user stops R. | M is stopped with R: its runtime ends and its saved job is marked dormant. Before the Stop, "Stop N working threads" counts M and a revert in R is refused. After it, M is not counted and the revert goes through. | `decider.childThreads.test.ts`: the interrupt on R targets M; the list write that follows marks the job dormant; `childRevertRefusal` flips. `threadMenu.logic.test.ts`: the count before and after. | +| 2 | R is on a computer with an older Threadlines and has narrow access. Its child on an updated computer was started narrow and the user has since widened it. R sends it work. The same with work queued before the upgrade. | The request arrives with no ceiling. The receiver gives it one, the access the link started the thread with, and refuses the turn because the thread is now wider. With the child unchanged, the turn runs as today. | Decider test for `thread.remote-request.queue` and the turn start that follows: no ceiling in, a refused turn for a widened thread, an accepted one for an unchanged thread, and a queued entry from before the upgrade handled the same way. | +| 3 | R starts five threads with `reportBack: false`. Setup finishes and every request settles. The user stops R. Then the same after the user has written in one of them. | All five are stopped. In the second run the one the user wrote in keeps running and the other four are stopped. "Stop N working threads" on R counts five, then four. | `decider.childThreads.test.ts`: the interrupt on R with five flagged loose threads, and with one unflagged. `threadMenu.logic.test.ts`: the count. | +| 4 | R has M's first answer. M is in a follow-up turn that owes R a report. The user queues R and M to move together. | Neither freezes while M's report is owed. M's turn ends, the report settles into R, then both freeze and move. | `threadMoveDecisions` test: `workWaits` holds R while its attached child has an owed entry, and holds M while its own list has one; both clear after the settle. | +| 5 | M's answer to R waits on background work. The user sets a goal in M, and Claude starts the goal's turn with no message. | R's request settles with M's answer so far when the goal's turn starts. The goal's turn does not answer the request. It reports by rule 2 when it ends. | Decider test: a provider-started turn that is not a check-back starts while a request waits; the request settles `answered` with the earlier turn's reply; the new turn has an owed entry and no request. | +| 6 | Codex exits during M's reporting turn and emits only `session.exited`. Two seconds later a message from R starts a new session in M. | R is told "'M' stopped before it finished" for the turn that was cut off, once. The new turn then answers R's message. No owed entry is left. | Ingestion test with the replayed Codex exit: the exit's handler settles the entry before the next event. Decider test for the sweep: a turn start with an older entry on the list settles it first. | +| 7 | Two reports wait behind M's failed turn. R sends M a retry. Then the same where the first report's turn also fails. | M reads the older report first, then the second, then R's retry. In the second run R is told M failed again with "1 report waiting", and nothing was skipped. | `ProviderCommandReactor` test: a message queued in an idle thread with two older agent entries sends the oldest; with a user's queued message present, that goes first as today. | + +### Tests (extend existing files) + +- **Shared rules** (`childThreads` tests). An attached child may start, send, stop and wrap, with and without report back. Put back is allowed for a thread with threads of its own and refused for one with threads on another computer. A send is refused when the child has more access than the request's ceiling, and when the child is under the user's hold. `attachedDescendantsOf` returns tree order and levels and survives a cycle in bad data. Stop's reach adds a flagged loose thread and what is under it, and leaves out one the user has written in. "Still going" is true for a thread whose only work is a check-back, saved or not, false once that check-back is dormant, and false for an idle open session. +- **Which turns report** (decider tests, commands in and events out). One case per kind of start: a parent's request, a person's message, an outside agent's, a hand-off, a hand-off's reply, a review's reply that arrives after the asking turn ended, a report from its own thread, a scheduled run, an automatic fix, a check-back, a goal's turn, background work. A continue after a limit, a restart and an account switch each follow the turn they continue, for a person's turn and for a reporting one. A turn whose request was cancelled when its agent left sends nothing. +- **Reports** (`childThreadDelivery` tests, pure, and decider tests for the settle). + - Completed is delivered; failed delivers the failure text, with the "continues by itself" line when the wait is armed; a second settle of the same turn is refused. + - A turn interrupted by the Stop that named it is dropped. A turn interrupted with no Stop (Claude's "runtime stream ended") delivers "stopped before it finished", for an owed entry and for a request, and never says the user stopped it. + - Sequence 6: an exit with a turn still running settles in the exit's handler, and the sweep settles anything older when the next turn starts. + - Each drop on its own: `thread_stop`, separate and put back, the parent held, the child held, the parent wrapped by hand. After the parent is reopened, the child's next turn is delivered. + - A report queued in R before the user stops M still reaches R. + - A failed start settles a request `failed`, and delivers a failure for an owed entry. A start taken back sends nothing. + - Sequence 7: the failure report counts the reports waiting, and the oldest agent message goes first. + - In an attached child, a report from its own thread is not steered into a running turn, the user's or a request's. In a thread with no parent it is steered as today. + - A follow-up goes to the agent that started the child, and to the thread's own agent once that one has left. One already queued when that agent leaves is handed to the thread's own agent. An answer queued for a leaving agent is taken off, as today. +- **Waiting answers.** Sequence 5, and the same for each other kind of start: a check-back, a report, a later request, the user's message and background work coming back each settle the waiting request with its answer so far before the turn runs. After a check-back did, background work that finishes with no further turn leaves nothing open. After a restart a waiting request settles with its answer so far, and no later turn is sent as its answer. +- **Stop** (decider tests). + - `thread.turn.interrupt` on a root with three levels: every thread in its reach that is still going is stopped in one decision, the root has the hold, and no thread under it gains one, even one that is a room or had an agent's message queued. + - Sequences 1 and 3. + - M was stopped by the user earlier and still has its hold. The user then stops R. M keeps its hold. + - After a stop the user writes to the root, the root sends M, M runs and sends G, G runs. Nobody wrote in M or G. + - Archive and unarchive of M leave no new hold on it. + - A fallback resend issued before a Stop and decided after it is refused, and the hold stays. + - A scheduled run into a stopped lead runs as it does today. + - An agent's runtime that ends by the idle reaper marks its listed check-backs dormant, and its next run clears the mark. + - An outside agent's stop leaves running a thread above its limit and names it. +- **Wrap, revert, archive, delete.** `thread_wrap` wraps M when G finished and its session is still open, and returns `working` while M has a start waiting for approval. Revert in R is refused while G works for M with nothing open in R, and while G only checks back; in both cases the menu offers "Stop N working threads", and revert is allowed after it. A loose thread that is still going does not block a revert. Archive and unarchive of three levels with one live thread in the middle and one that only holds a check-back. Delete with `alsoDelete` deletes the listed threads and separates one started after the list was made; `withChildren` alone deletes one level. +- **Access and the pass.** R sends M a request, the user widens M, and the turn is refused at the decision and again in the reactor. M stops on a usage limit while answering R, the user widens M, and the continue at the reset is refused and R's request settles `failed`. A request from a pass-blocked thread sets the receiver's block; the receiver can't start threads; the block lifts on a person's message and on an unflagged request from its parent. Over the link: both updated, the ceiling is carried and enforced; an updated sender to an older receiver is allowed with the widest access and refused otherwise; sequence 2 for an older sender. +- **Reactor and ingestion.** G's report starts M's turn and M's reply reaches R and starts R's turn. Startup delivers an owed turn that completed before the crash, delivers one interruption report for a cut-off owed turn, and ignores turns with no entry. A reaped child's waiting request settles `answered`, with no "user stopped". +- **Handlers** (`threadToolHandlers` tests). Each tool from an attached child; `thread_stop` returns `stopped` for an idle child with a thread under it that is still going; a start on another computer from an attached child is refused. +- **Moves.** With R, M, G and a leaf S under R: R, M and G are each refused, at admission and at the start of the move, and S may move alone. Sequence 4. +- **Old clients.** A thread replay that spans a dropped report decodes on a client built before this change (a fixture of the older union). +- **Web logic.** `Sidebar.logic.test.ts` ("child thread families"): tree order, levels, subtree counts and dots, the collapsed set, the root key walk, a wrapped middle thread with a live thread under it, a live thread under a wrapped parent heading its own family, a middle thread that does not auto-wrap while a thread under it works, and no "Checking back" pill for a dormant check-back. `familyTabs.logic.test.ts`: the tabs equal the sidebar's members for a root, a middle thread and a leaf, and the Stop button's count. `threadMenu.logic.test.ts`: the count by "still going" over Stop's reach. Delete: a test for the ids it sends. +- **Browser.** `InboxRows.browser.tsx` and `ChatView.sidebar.browser.tsx`: three levels render under one root, open and collapsed. `ChatView.agents.browser.tsx`: the tab row for three levels, and its Stop button with a polish shot in light and dark. +- **Live**, on a throwaway stack (never `~/.threadlines/userdata`). Stage 1: a Claude parent and a child; the child's check-back wakes the parent; Stop on the parent stops the child, its check-back and a thread it started without report back; killing the child's Claude process mid-turn tells the parent it stopped unexpectedly; a restart with the child mid-turn tells the parent once. Stage 2: a root starts a child that starts a grandchild; the grandchild's answer reaches the root and wakes it; Stop on the root stops all three; a Codex child in the chain covers a provider that queues reports. + +### Build steps + +Two stages, each its own pull request. Stage 1 changes how today's one-level families behave and can run for real before any thread nests. Stage 2 turns nesting on. Every step is one diff that Astra reviews before the next starts. Within a stage the server steps touch the same files and are built in order by one builder; the web step runs beside them in its own worktree. + +**Stage 1: reports, access and Stop for today's families.** + +1. **Contracts and shared rules.** The owed list, the report command and its event (outside the thread stream), the ceiling fields, the stop cause, `alsoDelete`, the loose-thread flag, the dormant mark, the "still going" test and Stop's reach. Shared tests, and the old-client replay fixture. Nothing behaves differently yet. +2. **Reports.** Which turns report, the owed list and its sweep, the settle and its drops, stopped on purpose against ended by itself, the exit that settles its turn, waiting answers, failed starts, no steering into an attached child, oldest first in an idle queue, a leaving agent's queued follow-ups, startup recovery, the removal of late replies. Sequences 5, 6 and 7. This is the risky step. It changes when a parent is woken. +3. **Access.** The request ceiling at every check, the continue that keeps it, the linked send in both directions, work queued before the upgrade. Sequence 2. +4. **Stop.** Stop causes and the hold, Stop reaching a thread's children and its loose threads, the dormant mark when a runtime ends, the shared test in the stop decision and the tool, the fallback resend's epoch, the revert rule, delete by ids, the wrap test, what a move waits for. Sequences 1, 3 and 4. Guide topic and docs for these. +5. **Web for stage 1.** The count in "Stop N working threads", the Stop button on the tab row, the "Checking back" pill and dormant check-backs, the delete dialog's ids. Before and after shots. + +**Stage 2: nesting.** Nothing in steps 6 and 7 can be reached by a user, because no thread can nest until step 8. + +6. **The walk and the cascades.** `attachedDescendantsOf`; Stop, `thread.children.stop`, `thread_stop`, archive, unarchive, delete, revert and wrap over a subtree; put back at any depth; the move refusal; the pass block's inheritance; the linked-computer fence. Tested on trees built straight into the read model. +7. **Web for nested families.** The family tree in `Sidebar.logic.ts` and its rows, the summary line, the auto-wrap condition, family tabs, menus and counts, the move and quit dialogs. Tested and shot on fixtures. Before and after shots. +8. **The switch, as the last commit.** The removed depth refusals in `childThreads.ts`, `thread.create` and the handlers, then the preambles and tool descriptions, the guide topics and the docs. Nesting becomes reachable only here, followed by the stage 2 live run. + +Each stage ends with the gates (`vp fmt`, `vp lint`, `vp run typecheck`, the targeted tests, `@threadlines/web#test:browser`) and its live list. + +### Decided by Will + +1. **Stop on a thread stops every thread under it, the whole tree.** Yes. +2. **Stop also reaches threads an agent started with `reportBack: false`**, unless the user has made one their own. The option stays. +3. **The access limit is sent to linked computers.** Yes. +4. **The "Stop N threads" button goes at the end of the chat's family tab row.** Yes. +5. **Two stages.** Stage 1 ships by itself first. + +Things decided in the plan that Will should know about: + +- In a room, a thread's later reports go to the agent that started it. +- The lead can be woken by work the user asked a middle thread for directly. +- Late replies go away. Work that used to wait for the parent's next turn now wakes it, or is dropped on purpose. +- The user makes a thread started without report back their own by writing in it. Until then it stops with its starter. +- A parent hears twice when a child's background work comes back: once with the answer so far, once with the follow-up. Today it hears once. No provider says which turn is the background work coming back, and guessing sent the wrong turn's reply as the answer. +- A child whose runtime dies mid-turn now tells its parent it stopped unexpectedly. Today the parent is told the user stopped it. +- With a linked computer on an older Threadlines, one access case can't be closed until it updates: a parent narrowed there, below what its child was started with. +- No limits of any kind; nested trees stay on one computer; no nested family moves to another computer yet. ## Review of Part 2, rev 1 (GPT-6.2 Astra, Nov 23 2026) -Checked against the code; each holds. A redesign has to answer all of them. +Checked against the code; each holds. Under each finding is the answer as it stands in rev 5. 1. **Pending reports are owed work too.** A child's request leaves `open` when its report is queued, not when the middle thread has read it. M with G1 and G2: G2 settles while M handles G1's report on a provider that can't steer, so M's turn ends with zero open requests and R gets the G1-only answer. + - Nothing above M waits on M's threads. M's G1 turn and its G2 turn each go up as a report (delivery rule 2). 2. **Downstream work needs the upstream request's identity.** R sends M a second task while the first waits on G: M's second turn sees G open and becomes a candidate too; G's report steered into it answers the wrong request. In a room the two requests can come from different agents. + - A request answers only to the turn its own message started, and in a middle thread a report is never steered into another turn (rule 9), so no request gets another's content. Which room agent hears a later report is a fixed rule: the one that started the thread (rule 8). 3. **The session reaper (`ProviderSessionReaper.ts`, 30 minutes idle) stops an idle middle thread** whose children are still working, and `ChildThreadReactor.settleStoppedAnswers` then tells R "the user stopped" M. Runtime eviction must not read as a stop. + - A turn or a session counts as stopped by the user only when a Stop named it (rule 6). The reaper issues no Stop, so nothing it closes reads as one, and no mark is needed. 4. **Restart** settles R before M's queued report replays (M has zero open requests once G settled), misses a report turn that completed before the crash (recovery only matches `pendingMessageId === null` continuations), and delivers M's first turn when its `awaiting_background` update didn't commit. + - The first and third need a request held across M's turns, which does not exist. The second is rule 14: every reporting turn is on the child's owed list from its start, and startup settles what is still on it. 5. **A room hand-off in M** goes through `thread.turn.start` without `fromThread`, so `settleCandidateBeforeUserTurn` sends R the candidate while G works. + - Nothing continues a waiting answer: it ends at the child's next turn of any kind (rule 4), and that is safe because what M finishes later goes up as reports. A turn that answers a hand-off is recognised by its starting message and is not reported; the asking agent's next turn is (rule 2). 6. **Usage-limit continue** (`isHeldByContinueAtReset`) requires `running` and the failed turn's own message; an `awaiting_background` request continued by a report turn fails at once. + - No request rides on a report turn. Its failure goes up at once, and the continue is a turn of its own that reports when it ends (rules 5 and 13). 7. **Reports with no local attached child** (a remote G with `environmentId`, a `neverMade` G) still start turns in M; and a queued report taken back (separate, wrap, room departure) triggers no re-check. + - Rule 2 reads how M's turn started, not who the report came from. A report from another computer can't arrive in a middle thread: an attached child can't start threads there, and no thread in the nested part of a family moves there. Nothing is held, so a report taken back needs no re-check. 8. **The MCP handlers have their own depth checks** (`threadToolHandlers.ts` start, local ownership, remote send, remote stop, wrap), separate from the shared and decider rules listed above. + - All five are listed under "Rules that go". Start, local ownership and wrap go. The two remote ones become the linked-computer fence. 9. **Nesting lets a lead pass escape its ceiling** (T passes to its existing child M, which carries no pass block and starts G), and ordinary sends don't re-check the parent's current access when the user narrowed it after the child was made. + - A blocked thread's requests carry the block down. Every request carries the sender's access, checked at the send, at turn start and in the reactor, and a continue keeps it ("Access"). 10. **Delete with its threads** would delete more than the dialog counted (`useThreadActions.ts` counts direct children only and winds down only those). + - The command names the threads the dialog listed (`alsoDelete`), and the server deletes only those. Cleanup now follows what the server really deleted (#1051). 11. **Agent-issued subtree stop** returns `not_running` for an idle M whose child works (`childHasWork` ignores M's own requests), and stopping M first settles the requests used to find the rest. + - `childHasWork` uses the "still going" test over the subtree, targets come from walking `parentThreadId` before anything settles, and a thread stopped with its family gets no hold ("Stop"). 12. **Late replies and moves** assume one level (`lateRepliesForAgent` returns early for an attached thread; move admission and whole-family moves refuse or flatten a middle parent). + - Late replies are gone (rule 12). A nested family does not move, and neither does a thread inside its nested part. 13. **The chat's family tabs** (`familyTabs.logic.ts`) list a parent's direct children only and would disagree with a nested sidebar. - -Atomicity is fine: the engine commits one decision's events in one transaction, and `decideCommandSequence` projects each step before the next. The counter fields can go from storage, but older clients need them on the wire (kept, see Part 1). - -A simpler direction worth weighing in the redesign: T3 Code's own. Every completion of a child that isn't the user's own conversation with it wakes its parent with a report, instead of holding the parent's request open until the subtree settles. R's request settles as today; M's later answers arrive as new reports. That removes findings 1, 2, 4, 5 and 6 (no request stays open across M's turns) at the cost of R being woken more often, which is the risk Will accepted. Findings 3 and 7 to 13 remain either way. + - The tabs show the same members in the same order as the sidebar, from one function ("Chat"). + +Atomicity is fine: the engine commits one decision's events in one transaction, and `decideCommandSequence` projects each step before the next. + +## Review of Part 2, rev 2 (GPT-6.2 Astra, Nov 23 2026) + +Astra reviewed rev 2 and accepted the decision to settle each request with its own answering turn. It found 13 problems in the rest. All 13 held against the code; 10 and 13 were narrower than stated. Under each is the answer as it stands in rev 5. + +1. **Stop can strand the team, and can come off without the user writing.** A subtree stop issues `thread.session.stop` per descendant, which runs the chain stop and would hold M and G. Archive cleanup has the same effect. A scheduled run's queued message lifts the hold. + - A stop has a cause, and only the user's Stop on the named thread leaves the hold. What lifts a hold is left as it is today. A schedule is automation the user set up, and it already lifts a Stop in a room. +2. **Stopping M does not stop M's own check-back from waking R.** + - Fixed on main. Since #1057 the user's Stop ends every agent's check-backs in the thread. A report from a held thread is dropped as well (rule 7). +3. **A delayed completion can cross a Stop, a separate and put back, or a wrap and reopen.** + - The owed entry holds the two epochs from when the turn started, and the settle delivers only if they still match. A wrapped parent is checked by its state (rule 7). +4. **Linked-computer sends cannot enforce the access ceiling, and an outside agent's stop would reach a descendant above its limit.** + - The ceiling goes over the link as an optional field, with a rule at each end for a computer that has not updated ("Access"). An outside agent's stop reaches only the threads that agent may stop itself. +5. **A lone move can create the cross-computer grandchild the plan says cannot exist.** + - A thread whose parent is itself an attached child does not move, checked at admission and when the move starts. Put back is refused for a thread with threads on another computer. +6. **Looking at what is open when a turn ends confuses an answer with a follow-up.** + - Whether a turn reports is read from the message that started it, when it starts (rule 2). +7. **The wrong room agent is woken, and a check-back or a continue is credited to the wrong work.** + - Rev 3 tried to route each report to the agent whose work it was, and that cannot be done for every kind of turn. A later report goes to the agent that started the thread. A continue of a person's turn stays the person's (rule 2). +8. **The late-reply net can pass on an outside assistant's answer, repeat a report, or lose one when a report is steered into a person's turn.** + - There are no late replies on this computer any more (rule 12), and a middle thread never has a report steered into a turn (rule 9). +9. **The two-minute startup window can't tell an upgrade from a crash, misses failed and older turns, and a restart can report an interruption twice.** + - The window is gone. Startup settles the owed lists, which only turns started after this change are on, and one function decides each turn once (rule 14). +10. **A report turn that never starts leaves R waiting, and a named room agent's turn skips the usage-limit wait.** + - A failed start settles what its message owed (rule 11). A failed turn reports at once whether or not it waits to continue (rule 5). +11. **A crash while a report is being steered delivers it twice.** + - In a middle thread reports are never steered, so it can't happen there. In a thread with no parent it can, as it can today for answers. The third review accepted that as a stated limit. +12. **`thread_wrap` refuses a finished subtree while sessions are merely idle, and misses a grandchild start that waits for approval.** + - Wrapping uses "outstanding work", which leaves out an idle open session and includes the thread's own open requests. +13. **Delete can remove a thread the user never confirmed.** + - The command names the threads the dialog listed. + +## Review of Part 2, rev 3 (GPT-6.2 Astra, Nov 23 2026) + +Astra reviewed rev 3 and found 12 more problems, in paths that bypass the turn start, mix the work of two turns, or read a different record after a Stop or a restart. Findings 3, 6, 7 and 9 were about the routing rev 4 removed and were taken as true without tracing. Under each is the answer as it stands in rev 5. + +1. **A report queued in a busy R still wakes R after the user stops M, and a report dropped for that Stop can come back as a late reply.** + - First half rejected. A report M finished and queued before the Stop is not cancelled by it. The user stopped M, not R, and a child the user stops even tells its parent so. Cancelling would also take back answers a parent has not read yet, which no Stop does today. Second half fixed: there are no late replies, so a dropped report stays dropped. +2. **The access check ends before the provider receives the work.** + - Fixed. The message carries its ceiling, and the same helper checks it in the reactor where a pass's ceiling is checked today, after the thread is reread. +3. **A provider-started background turn can report to the wrong room agent.** + - Gone. No turn is assigned to an agent by position. A later report goes to the agent that started the thread. +4. **Steering mixes two requests from the same agent, and a person can steer into a turn that reports upward.** + - First half fixed: in a middle thread a report is never steered. Second half rejected: a user's steer becomes part of the turn it lands in. That is the standing rule for answers (`child-threads.md`, rev 3 fix 5), and a follow-up turn is treated the same. +5. **Restart recovery can deliver one check-back as both a request's answer and a report, and the decider can't see an older turn's state.** + - Fixed. The owed list is in the thread's state. Nothing continues a waiting answer, so no later turn can be sent as one, live or after a restart (rules 4 and 14). +6. **A review that returns after the asking turn ended loses its route.** + - Gone. There is no route to lose. The reply starts a turn in M that no person wrote, so it reports (rule 2). +7. **A scheduled run into a stopped lead stays queued and blocks later runs.** + - Gone. What lifts a hold is as it is today, so the run starts as it does now. +8. **An account switch and an overtaken reset continue can lose the answer.** + - Fixed for reports: nothing is held for a continue. The failure has already gone up, and a continue reports as its own turn unless a request was moved onto it (rule 2). For requests, the failure a parent is told when an account is switched is today's behavior and is not changed here. +9. **Claude does not always give a check-back's id, and updates from idle room agents can bind one to the wrong turn.** + - Gone. Nothing uses a check-back's id. The plan only reads the mark that a turn is a check-back. +10. **A family stop must not remove a hold the user put on a descendant, and an automatic resend can lift a hold.** + - Both fixed. A hold a thread already had stays. The fallback's resend carries the chain epoch of the turn it resends and is refused after a Stop. +11. **Revert lets a subtree wake a lead about work the user removed.** + - Fixed. Revert is refused while any thread under the thread is still going. +12. **An older phone's delete can still take a child that appeared after its count, and a new event type breaks an old client that replays events.** + - First half rejected as not fixable here: the old command has no field to say which threads it meant, and the race exists today at one level. Second half fixed in rev 5: the new event type is kept out of the thread stream. Rev 4 left this to the builder to confirm, and the fourth review showed the assumption was wrong. + +## Review of Part 2, rev 4 (GPT-6.2 Astra, Nov 23 2026) + +Astra reviewed rev 4 (commit 9144768f9, before the rebase) and judged stage 1 unsafe as written: the access bypass, lost follow-ups and several Stop failures already happen with one parent and one child. It found 10 problems and checked the two things rev 4 left to the builder. Each was read against main at 66ab80915. Each line says whether it is fixed on main, still open or changed, and how rev 5 answers it. + +1. **A usage-limit continue can run a parent's request with wider access, and an older linked computer can ignore the ceiling.** + - Holds, both parts, and still open on main. The continue is a fresh message with the thread's current access and no origin (`decider.ts:5463`), and the reactor reads a ceiling only from the turn's own message (`ProviderCommandReactor.ts:2584`). A continue keeps the ceiling of the turn it continues, and a refused continue fails the request it held. Over the link, a computer that does not say it enforces the ceiling takes work only from a sender with the widest access, and an updated computer gives a ceiling to work that arrives without one ("Access"). +2. **An agent can start work outside the Stop walk with `reportBack: false`, and a recurring check-back survives the composer's Stop.** + - First part holds and is open on main: the thread is its starter's child on paper, never attached (`ThreadBootstrap.ts:687`), and it can start more. Rev 5 answered with two refusals. Will then decided the other way, and rev 6 follows him: the option stays at every level, and a thread started without report back is in its starter's Stop reach until the user writes in it. Second part is fixed on main by #1057. +3. **A child can disappear mid-report without waking its parent or reporting failure.** + - Holds and is open on main, where it also misreports a request: Claude's stream ending mid-turn closes the turn as interrupted (`ClaudeAdapter.ts:8479`), and the parent is told the user stopped it. Codex can exit with no turn end at all. Rev 5: stopped on purpose is read from the turn a Stop named, which main records since #1057. Anything else that ends a turn or a session reports "stopped before it finished", from the turn end and from the stopped-session reactor (rule 6). +4. **A check-back can strand a background answer, then be delivered twice across a restart.** + - Holds and is open on main for the first half. A waiting answer lasts only until the child's next turn starts, so a check-back settles it with its answer so far before it runs. Rev 6 goes one step further and lets nothing continue a waiting answer (rules 4 and 14). +5. **A middle thread can leave a delivered report unread after its turn fails, and a follow-up queued for an agent that then leaves the room is lost.** + - Both hold. First: the queue does not move on a failed turn (`ProviderCommandReactor.ts:6203`). The failure report says how many reports are waiting. Rev 5 claimed the parent's next send would read them first, which today's queue does not do. Rev 6 makes it true: in an idle thread the oldest agent message goes first (rule 10). Second: fixed. The leave decision hands a queued follow-up to the thread's own agent (rule 8). +6. **Wrapping R doesn't stop its child's next check-back from waking it.** + - Holds, and it is worse than stated: a wrap moves the epoch only when the thread has something open (`childThreadDecisions.ts:1941`). Rev 5: a report is dropped while its parent is wrapped, read from the parent's state (rule 7). Reopening lets reports through again. +7. **Archive can cancel the very check-back the parent waits for.** + - Fixed on main by #1056. The cascade in this plan uses main's test going down ("Archive"). +8. **`alsoDelete` protects the thread row too late to protect a surviving child's data.** + - Fixed on main by #1051: the client winds down only the named thread, and the server cleans up each thread it really deleted. `alsoDelete` stays for the other half, the count the user confirmed. +9. **A one-level move can outrun report settlement, and the nested move rule misses a leaf beside a nested sibling.** + - First half holds in part. A frozen child does not block the settle, because the freeze reads the parent the command names (`threadMoveDecisions.ts:866`). But a child can freeze with a report still owed, since a move waits only for the thread's own requests and queue. Rev 5: a thread that owes a report, or has a request from its parent open, counts as working for a move. Second half rejected: a leaf directly under a top-level thread may move alone even when a sibling has threads. That leaves a top-level thread with one child on another computer, which is allowed today. Rev 4's sentence said the rule covered every member of the family, and that sentence was wrong, not the rule. +10. **Revert can tell the user to press a Stop control that doesn't exist.** + - Holds. One "still going" test for the revert refusal, the stop's targets and the menu's count. An idle open session is not going. A thread that only checks back is, with a saved job or not, until the runtime that could fire it has ended ("Stop"). + +What rev 4 left to the builder: + +- **Old clients do replay events.** Astra is right, and main confirms it: a resubscribe replays stored events through `isThreadDetailEvent` (`ws.ts:248`, `:1744`), the client decodes a closed union, and one unknown type fails the batch. Rev 5 keeps the one new event type out of that filter and puts no flag on `thread.handed-back`. +- **The stored session has no room for the reaper's cause, and the reaper's write can land late.** Right on both counts. Rev 5 needs no cause: see finding 3. + +## Review of Part 2, rev 5 (GPT-6.2 Astra, Nov 23 2026) + +Astra reviewed rev 5 (commit 19cdc8438) with one question: does it open a new class of problem. It found none. It agreed the wrap fix holds and that the archive and delete conclusions match main. It found seven sequences that needed an explicit outcome and a test, and agreed to move to reviews of each build step once the plan has them. Will decided the four open questions in the same round. Each sequence was read against main at 66ab80915. Their outcomes and tests are in "The seven sequences from the fifth review". + +1. **Stop misses an attached child whose only work is a saved check-back.** Rev 5's test left out saved jobs because they survive a runtime restart, but a live runtime fires one with nobody writing. + - Holds. Main counts saved jobs for Stop for exactly this reason (`hasLiveCheckBack`, `packages/shared/src/checkBacks.ts:101`). Rev 6 uses main's test, and adds what it lacked: a listed check-back is marked dormant when its agent's runtime ends, so the test turns false after a stop and the revert refusal clears. +2. **The linked access check covers one upgrade direction only.** An older sender never checks the flag, and the updated receiver gets no ceiling. + - Holds. Rev 6 adds the receiver's rule: a request with no ceiling gets one from the access the link started the thread with, or the thread's access when it arrived. Work queued before the upgrade is handled the same way. One case can't be closed from the receiving end and is stated: a parent narrowed on the older computer. +3. **A top-level agent can start any number of workers outside its Stop with `reportBack: false`.** + - Holds. Will decided: Stop reaches them, unless the user has made one their own. Rev 5's two refusals are gone. +4. **A family move can freeze the report's recipient first.** + - Holds. A move now waits for reports coming in from attached threads as well as going out. +5. **A provider-started turn without a check-back mark can answer the wrong request.** A goal's turn is one. + - Holds. No provider gives positive evidence that a turn is the background work coming back, so rev 6 drops the guess: nothing continues a waiting answer (rule 4). +6. **A runtime exit can still leave the parent waiting when a new session starts inside the reactor's five seconds.** + - Holds. The handler that ingests the exit settles the turn it took, and the next turn start sweeps any older entry (rules 3 and 6). +7. **The advertised recovery send does not read waiting reports first.** The idle-queue handler sends the newly arrived message by its id. + - Holds. In an idle thread the oldest agent message now goes first (rule 10). diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index d40a48470..fcf3a097c 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -624,6 +624,25 @@ export const LeadPassCeiling = Schema.Struct({ }); export type LeadPassCeiling = typeof LeadPassCeiling.Type; +/** + * The most a parent thread's work may run with in the thread it sent it to + * (docs/design/agent-autonomy-no-limits.md, "Access"), kept on the message + * that carries it and on what starts a turn from it. `requestCeiling`: the + * sender's access when it sent, or its pass ceiling if that was narrower; + * every decision that starts a turn from the message, and the reactor when it + * prepares and starts that turn, refuse when the thread has more access by + * then. A continue (a usage limit reset, a restart, an account switch) copies + * it from the message that started the turn it continues. `passBlocked`: the + * sender was working on a lead chat's pass, so the turn this starts blocks + * the receiver from starting threads too (docs/design/lead-chat.md, "No + * fan-out"). Absent: no ceiling (the user's own messages, and work queued + * before the ceiling existed, which gets one when its turn starts). + */ +export const MessageAccessFields = { + requestCeiling: Schema.optional(LeadPassCeiling), + passBlocked: Schema.optional(Schema.Literal(true)), +}; + /** * A message that crossed between a thread and one it started: a `request` its * parent's agent wrote into the child, or a `report`, the child's answer @@ -660,6 +679,13 @@ export const ThreadMessageOrigin = Schema.Struct({ ceiling: Schema.optional(LeadPassCeiling), /** A pass: the lead's agent that passed it (a room's agent), for its notes. Absent: its own. */ passedBy: Schema.optional(ThreadParticipantId), + /** + * A report no request asked for: a turn the child took on its own after + * its answer went back (a report from one of its own threads, a check-back, + * a scheduled run, background work that finished). `requestId` is then + * derived from the child's turn. Absent: an answer to a request. + */ + followUp: Schema.optional(Schema.Literal(true)), }); export type ThreadMessageOrigin = typeof ThreadMessageOrigin.Type; @@ -685,6 +711,13 @@ export const ThreadRemoteOrigin = Schema.Struct({ environmentLabel: TrimmedNonEmptyString, threadId: ThreadId, threadTitle: TrimmedNonEmptyString, + /** + * The access the link started the thread with. A request that arrives over + * the link with no ceiling (an older sender) runs with no more than this + * (docs/design/agent-autonomy-no-limits.md, "Access"). Absent: a thread + * started before it was kept. + */ + launchedAccess: Schema.optional(LeadPassCeiling), }); export type ThreadRemoteOrigin = typeof ThreadRemoteOrigin.Type; @@ -875,6 +908,13 @@ export const OrchestrationCheckBack = Schema.Struct({ cron: Schema.optional(TrimmedNonEmptyString), /** Saved by the provider to outlive the runtime that set it. */ durable: Schema.Boolean, + /** + * The runtime that could fire it has ended (any reason), so it can't fire + * until that agent runs again, whose runtime then reports its list afresh + * and clears this. A dormant check-back doesn't make a thread still going + * (docs/design/agent-autonomy-no-limits.md, "Stop"). Set by the server. + */ + dormant: Schema.optional(Schema.Literal(true)), }); export type OrchestrationCheckBack = typeof OrchestrationCheckBack.Type; @@ -1403,6 +1443,8 @@ export const OrchestrationMessage = Schema.Struct({ invite: Schema.optional(RoomAgentInvite), /** Child threads: a message another thread's agent wrote. See ThreadMessageOrigin. */ fromThread: Schema.optional(ThreadMessageOrigin), + /** See MessageAccessFields. */ + ...MessageAccessFields, /** A user-role message an outside agent wrote. See OutsideAgentRef. */ fromOutside: Schema.optional(OutsideAgentRef), /** See MessageComposer. Absent on every message an agent or automation wrote. */ @@ -2483,6 +2525,8 @@ export const OrchestrationQueuedFollowUp = Schema.Struct({ * exists and it is never the user's. */ fromThread: Schema.optional(ThreadMessageOrigin), + /** See MessageAccessFields. */ + ...MessageAccessFields, /** See MessageComposer: kept so the message is written with it when sent. */ composer: Schema.optional(MessageComposer), /** See MessageSentFrom: kept so the message is written with it when sent. */ @@ -3003,12 +3047,41 @@ export type ChildRequestNote = typeof ChildRequestNote.Type; * `sendsSinceUser` are no longer counted or read, and stay only so older * clients still decode a thread. */ +/** + * The epochs a child's report is delivered under (docs/design/ + * agent-autonomy-no-limits.md, "Delivery rules", rule 7): its parent's + * delivery epoch and its own attachment epoch when the turn that owes it + * started. A report whose stamps no longer match is dropped. + */ +export const OwedReportStamps = Schema.Struct({ + deliveryEpoch: NonNegativeInt, + attachmentEpoch: NonNegativeInt, +}); +export type OwedReportStamps = typeof OwedReportStamps.Type; + +/** + * A report this thread owes its parent: a turn it takes on its own after its + * answer went back (rule 2). Added by the decision that starts the turn, + * keyed by the message that starts it or, for a turn the provider starts with + * no message, by the turn. Removed when the report is settled, and the whole + * list empties when the thread's attachment epoch moves. + */ +export const OwedChildReport = Schema.Struct({ + messageId: Schema.optional(MessageId), + turnId: Schema.optional(TurnId), + ...OwedReportStamps.fields, + createdAt: IsoDateTime, +}); +export type OwedChildReport = typeof OwedChildReport.Type; + export const OrchestrationChildRequestState = Schema.Struct({ open: Schema.Array(OrchestrationChildRequest), deliveryEpoch: NonNegativeInt, startsSinceUser: NonNegativeInt, sendsSinceUser: NonNegativeInt, pendingNotes: Schema.Array(ChildRequestNote), + /** Reports this thread owes its parent, oldest first. Absent: none. */ + owedReports: Schema.optional(Schema.Array(OwedChildReport)), /** Children on linked computers, kept after their requests settle. Absent: none. */ remoteChildren: Schema.optional(Schema.Array(RemoteChildThread)), /** Cancels still owed to linked computers, oldest first. Absent: none. */ @@ -3143,6 +3216,8 @@ export const OrchestrationThread = Schema.Struct({ parentTurnId: Schema.NullOr(TurnId).pipe(Schema.withDecodingDefault(Effect.succeed(null))), /** See OrchestrationThreadShell.attachedToParent. */ attachedToParent: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** See OrchestrationThreadShell.stopsWithParent. */ + stopsWithParent: Schema.optional(Schema.Literal(true)), /** * Raised each time this child's answers to its parent are cut off (it was * separated, put back, or stopped), so an answer delivered under an earlier @@ -3408,6 +3483,15 @@ export const OrchestrationThreadShell = Schema.Struct({ * the answers to the parent's requests go back to it. False once separated. */ attachedToParent: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** + * Started without report back (`thread_start` with `reportBack: false`), + * and not yet the user's: it is under its parent's Stop though it was never + * attached (docs/design/agent-autonomy-no-limits.md, "Stop"). Cleared for + * good by the first message a person writes in it, or by putting it back + * under its parent. Absent: the user's own (and every such thread started + * before it was kept). + */ + stopsWithParent: Schema.optional(Schema.Literal(true)), /** * The turn whose answer last went back to the parent, and when: as a report, * as a late reply its agent was told of at its next turn, or a turn the @@ -3675,6 +3759,8 @@ const ThreadCreateLineageFields = { /** The parent's turn whose agent started it. */ parentTurnId: Schema.optional(TurnId), attachedToParent: Schema.optional(Schema.Boolean), + /** Started without report back: see OrchestrationThreadShell.stopsWithParent. */ + stopsWithParent: Schema.optional(Schema.Literal(true)), /** Started over a computer link: see ThreadRemoteOrigin. Only the link handler sets it. */ remoteOrigin: Schema.optional(ThreadRemoteOrigin), /** Started by a scheduled run: see ThreadScheduledRun. Only the scheduler sets it. */ @@ -3780,6 +3866,13 @@ const ThreadDeleteCommand = Schema.Struct({ * they are separated and live on as threads of their own. */ withChildren: Schema.optional(Schema.Boolean), + /** + * With `withChildren`: the threads the confirm dialog listed. The server + * deletes exactly those that are still attached, unarchived threads under + * this one, and separates any other. Absent (an older client): every + * attached child, one level. + */ + alsoDelete: Schema.optional(Schema.Array(ThreadId)), }); const ThreadArchiveCommand = Schema.Struct({ @@ -4069,6 +4162,8 @@ export const ThreadTurnStartCommand = Schema.Struct({ * client turn-start schema has no such field). See ThreadMessageOrigin. */ fromThread: Schema.optional(ThreadMessageOrigin), + /** Server only. See MessageAccessFields. */ + ...MessageAccessFields, /** * An outside agent's turn (server only, set by `/mcp/connect`). The decider * refuses it when the thread's access is above `maxRuntimeMode`. @@ -4447,6 +4542,15 @@ const ThreadSessionStopCommand = Schema.Struct({ * for one turn never ends the next one, which may be the user's. */ expectedTurnId: Schema.optional(Schema.NullOr(TurnId)), + /** + * Server only: why the session stops, which decides whether it leaves the + * Stop hold (docs/design/agent-autonomy-no-limits.md, "Stop"). `family`: + * stopped with a thread above it (its starter's Stop, "Stop N working + * threads", an agent's thread_stop); no new hold, and it takes its + * parent's next message. `cleanup`: archive, delete, the sweeper, a move, + * a link; no new hold and no cascade. Absent: the thread's own Stop. + */ + cause: Schema.optional(Schema.Literals(["family", "cleanup"])), createdAt: IsoDateTime, }); @@ -6278,6 +6382,8 @@ export const ThreadCreatedPayload = Schema.Struct({ parentThreadId: Schema.optional(ThreadId), parentTurnId: Schema.optional(TurnId), attachedToParent: Schema.optional(Schema.Boolean), + /** See OrchestrationThreadShell.stopsWithParent. */ + stopsWithParent: Schema.optional(Schema.Literal(true)), /** See OrchestrationThreadShell.remoteOrigin. */ remoteOrigin: Schema.optional(ThreadRemoteOrigin), /** See OrchestrationThreadShell.scheduledRun. */ @@ -6801,6 +6907,8 @@ export const ThreadMessageSentPayload = Schema.Struct({ invite: Schema.optional(RoomAgentInvite), /** See OrchestrationMessage.fromThread. */ fromThread: Schema.optional(ThreadMessageOrigin), + /** See MessageAccessFields. */ + ...MessageAccessFields, /** See OrchestrationMessage.fromOutside. */ fromOutside: Schema.optional(OutsideAgentRef), /** See OrchestrationMessage.composer. */ @@ -6866,6 +6974,8 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({ * not sent. */ fromThread: Schema.optional(ThreadMessageOrigin), + /** See MessageAccessFields. */ + ...MessageAccessFields, /** * An outside agent's turn: who, and its ceiling. The provider starts at the * mode this event carries, which the decider checked against the ceiling. diff --git a/packages/contracts/src/peerRpc.ts b/packages/contracts/src/peerRpc.ts index eaed6b21f..23269f98d 100644 --- a/packages/contracts/src/peerRpc.ts +++ b/packages/contracts/src/peerRpc.ts @@ -24,6 +24,7 @@ import { ChatAttachment, ChatSkillReferenceList, KnownAssistant, + LeadPassCeiling, MessageComposer, MessageSentFrom, ModelSelection, @@ -286,6 +287,13 @@ export const PeerDescriptor = Schema.Struct({ * ever sent to it. */ moveLinkLineage: Schema.optional(Schema.Boolean), + /** + * Holds a parent's access limit on work sent to a thread it started here + * (PeerSendInput's `ceiling`, docs/design/agent-autonomy-no-limits.md, + * "Access"). Absent: an older server, which runs the work at the thread's + * own access, so only a sender with the widest access sends it work. + */ + enforcesRequestCeiling: Schema.optional(Schema.Boolean), /** * Takes back the threads a moving thread's agent started here over this * link as that thread's children (docs/design/fleet.md, Part 3f, (g)): @@ -361,6 +369,12 @@ export const PeerSendInput = Schema.Struct({ requestId: ChildRequestId, threadId: ThreadId, text: TrimmedNonEmptyString, + /** + * The sender's access when it sent (see MessageAccessFields): the thread + * refuses the work while it has more. Absent: an older sender, so the + * thread gives the request a ceiling of its own. + */ + ceiling: Schema.optional(LeadPassCeiling), }); export type PeerSendInput = typeof PeerSendInput.Type; diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index 8b069a412..8a0aa821f 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -94,11 +94,12 @@ export function runtimeCheckBackOwed( /** * Whether one of the thread's agents can still wake itself up. A job saved * to the project counts too: in a room, the thread's session says nothing of - * the other agents' runtimes, where it may still fire. A stop counts it as + * the other agents' runtimes, where it may still fire. One marked dormant + * can't: the runtime that could fire it has ended. A stop counts the rest as * work to stop. */ export function hasLiveCheckBack(thread: { - readonly checkBacks?: ReadonlyArray<OrchestrationCheckBack> | undefined; + readonly checkBacks?: ReadonlyArray<Pick<OrchestrationCheckBack, "dormant">> | undefined; }): boolean { - return (thread.checkBacks ?? []).length > 0; + return (thread.checkBacks ?? []).some((checkBack) => checkBack.dormant !== true); } diff --git a/packages/shared/src/childThreads.test.ts b/packages/shared/src/childThreads.test.ts index 8b4197d93..050c06faf 100644 --- a/packages/shared/src/childThreads.test.ts +++ b/packages/shared/src/childThreads.test.ts @@ -11,13 +11,17 @@ import { import { describe, expect, it } from "vite-plus/test"; import { + attachedDescendantsOf, childAttachRefusal, childRequestStateOn, childSendRefusal, childStartRefusal, isHandedBackCompletion, + isStillGoing, remoteChildrenOf, remoteChildStartsOf, + stopReachOf, + type StillGoingInput, } from "./childThreads.ts"; const PARENT = ThreadId.make("parent"); @@ -246,3 +250,90 @@ describe("isHandedBackCompletion", () => { ).toBe(false); }); }); + +describe("family walks", () => { + const member = ( + id: string, + parent: string | null, + createdAt: string, + extra: { attached?: boolean; stopsWithParent?: true; deletedAt?: string } = {}, + ) => ({ + id: ThreadId.make(id), + parentThreadId: parent === null ? null : ThreadId.make(parent), + attachedToParent: extra.attached ?? parent !== null, + ...(extra.stopsWithParent ? { stopsWithParent: extra.stopsWithParent } : {}), + deletedAt: extra.deletedAt ?? null, + createdAt, + }); + const ids = (walk: ReadonlyArray<{ thread: { id: string }; level: number }>) => + walk.map((entry) => `${entry.thread.id}@${entry.level}`); + + it("lists a family in tree order with levels, and leaves out separated and deleted threads", () => { + const threads = [ + member("root", null, "2026-11-23T10:00:00.000Z"), + member("m2", "root", "2026-11-23T10:02:00.000Z"), + member("m1", "root", "2026-11-23T10:01:00.000Z"), + member("g1", "m1", "2026-11-23T10:03:00.000Z"), + member("separated", "root", "2026-11-23T10:04:00.000Z", { attached: false }), + member("deleted", "m2", "2026-11-23T10:05:00.000Z", { + deletedAt: "2026-11-23T11:00:00.000Z", + }), + member("loose", "m2", "2026-11-23T10:06:00.000Z", { attached: false, stopsWithParent: true }), + member("under-loose", "loose", "2026-11-23T10:07:00.000Z"), + ]; + expect(ids(attachedDescendantsOf(threads, ThreadId.make("root")))).toEqual([ + "m1@1", + "g1@2", + "m2@1", + ]); + // Stop also takes a thread started without report back, and what is under it. + expect(ids(stopReachOf(threads, ThreadId.make("root")))).toEqual([ + "m1@1", + "g1@2", + "m2@1", + "loose@2", + "under-loose@3", + ]); + }); + + it("never loops on a cycle in bad data", () => { + const threads = [ + member("a", "b", "2026-11-23T10:00:00.000Z"), + member("b", "a", "2026-11-23T10:01:00.000Z"), + ]; + expect(ids(attachedDescendantsOf(threads, ThreadId.make("a")))).toEqual(["b@1"]); + }); +}); + +describe("isStillGoing", () => { + const idle: StillGoingInput = { + session: { status: "ready" }, + latestTurn: { state: "completed" }, + queuedCount: 0, + waitsOnUser: false, + openRequestCount: 0, + }; + + it("is false for an idle open session, and true for each kind of work", () => { + expect(isStillGoing(idle)).toBe(false); + expect(isStillGoing({ ...idle, latestTurn: { state: "running" } })).toBe(true); + expect(isStillGoing({ ...idle, session: { status: "starting" } })).toBe(true); + expect(isStillGoing({ ...idle, queuedCount: 1 })).toBe(true); + expect(isStillGoing({ ...idle, waitsOnUser: true })).toBe(true); + expect(isStillGoing({ ...idle, openRequestCount: 1 })).toBe(true); + expect( + isStillGoing({ ...idle, session: { status: "ready", pendingBackgroundTaskCount: 1 } }), + ).toBe(true); + expect( + isStillGoing({ + ...idle, + session: { status: "error", continueAtReset: { at: "2026-11-23T12:00:00.000Z" } }, + }), + ).toBe(true); + }); + + it("counts a check-back, saved or not, until it is dormant", () => { + expect(isStillGoing({ ...idle, checkBacks: [{}] })).toBe(true); + expect(isStillGoing({ ...idle, checkBacks: [{ dormant: true }] })).toBe(false); + }); +}); diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 45bb6fa1e..63c24dfc3 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -30,6 +30,7 @@ import { type TurnId, } from "@threadlines/contracts"; +import { hasLiveCheckBack } from "./checkBacks.ts"; import { exceedsRuntimeMode, saferRuntimeMode } from "./runtimeMode.ts"; import { isRoomThread } from "./threadParticipants.ts"; @@ -769,3 +770,154 @@ export const isHandedBackCompletion = (thread: { thread.latestTurn !== null && thread.latestTurn.state !== "running" && thread.latestTurn.turnId === thread.handedBackTurnId; + +// ── Families of any depth ──────────────────────────────────────────── +// +// docs/design/agent-autonomy-no-limits.md. A thread's family is every thread +// reachable from it down attached links. Stop reaches further: it also takes +// a thread started without report back (`stopsWithParent`) until the user +// makes it their own. + +/** What the family walks read about a thread. */ +export interface FamilyMember { + readonly id: ThreadId; + readonly parentThreadId: ThreadId | null; + readonly attachedToParent: boolean; + readonly stopsWithParent?: true | undefined; + readonly deletedAt?: string | null | undefined; + readonly createdAt: string; +} + +/** A thread under another, and how many links down from it. */ +export interface FamilyMemberAt<T extends FamilyMember> { + readonly thread: T; + /** 1 for a direct child, 2 for its child, and so on. */ + readonly level: number; +} + +function walkDown<T extends FamilyMember>( + threads: ReadonlyArray<T>, + rootId: ThreadId, + follows: (thread: T) => boolean, +): ReadonlyArray<FamilyMemberAt<T>> { + const childrenOf = new Map<ThreadId, T[]>(); + for (const thread of threads) { + if (thread.parentThreadId === null || (thread.deletedAt ?? null) !== null) continue; + if (!follows(thread)) continue; + const siblings = childrenOf.get(thread.parentThreadId) ?? []; + siblings.push(thread); + childrenOf.set(thread.parentThreadId, siblings); + } + const out: FamilyMemberAt<T>[] = []; + // Bad data must never loop: a thread is visited once, the root never. + const visited = new Set<ThreadId>([rootId]); + const visit = (parentId: ThreadId, level: number) => { + const children = (childrenOf.get(parentId) ?? []).toSorted((left, right) => + left.createdAt.localeCompare(right.createdAt), + ); + for (const child of children) { + if (visited.has(child.id)) continue; + visited.add(child.id); + out.push({ thread: child, level }); + visit(child.id, level + 1); + } + }; + visit(rootId, 1); + return out; +} + +/** + * Every thread attached under `rootId`, at any depth, in tree order: each + * thread followed by its own threads, oldest first within a level. Reports, + * the sidebar family, the tabs, wrap, archive, delete and revert follow this. + */ +export function attachedDescendantsOf<T extends FamilyMember>( + threads: ReadonlyArray<T>, + rootId: ThreadId, +): ReadonlyArray<FamilyMemberAt<T>> { + return walkDown(threads, rootId, (thread) => thread.attachedToParent); +} + +/** + * Every thread a Stop on `rootId` reaches, in tree order: the attached ones, + * and the ones started without report back that the user has not made their + * own, and so on down through both kinds. Only Stop follows this walk. + */ +export function stopReachOf<T extends FamilyMember>( + threads: ReadonlyArray<T>, + rootId: ThreadId, +): ReadonlyArray<FamilyMemberAt<T>> { + return walkDown( + threads, + rootId, + (thread) => thread.attachedToParent || thread.stopsWithParent === true, + ); +} + +/** + * What the "still going" test reads about a thread. The thread's shell and + * its detail both carry these, so the server's stop and revert rules and the + * client's counts read the same answer. + */ +export interface StillGoingInput { + readonly session: { + readonly status: string; + readonly pendingBackgroundTaskCount?: number | undefined; + readonly awaitedBackgroundTaskCount?: number | undefined; + readonly continueAtReset?: unknown; + } | null; + readonly latestTurn: { readonly state: string } | null; + /** Messages waiting in its queue. */ + readonly queuedCount: number; + /** An approval, a question or a plan waiting on the user. */ + readonly waitsOnUser: boolean; + /** Its own open child requests, starts still waiting for the user included. */ + readonly openRequestCount: number; + readonly checkBacks?: ReadonlyArray<{ readonly dormant?: true | undefined }> | undefined; +} + +/** + * Whether a thread is still going (docs/design/agent-autonomy-no-limits.md, + * "Stop"): it can start a turn by itself, or is in one. What a stop targets, + * what "Stop N working threads" and the tab row's button count, and what + * holds a revert all read this, so a refusal never names a remedy that isn't + * on screen. An idle session with none of these is not going. + */ +export function isStillGoing(thread: StillGoingInput): boolean { + const session = thread.session; + return ( + thread.latestTurn?.state === "running" || + session?.status === "running" || + session?.status === "starting" || + thread.queuedCount > 0 || + thread.waitsOnUser || + (session?.pendingBackgroundTaskCount ?? 0) > 0 || + (session?.awaitedBackgroundTaskCount ?? 0) > 0 || + thread.openRequestCount > 0 || + (session?.continueAtReset ?? null) !== null || + hasLiveCheckBack(thread) + ); +} + +/** The "still going" input from a thread's shell, as the client holds it. */ +export function stillGoingInputOfShell(shell: { + readonly session: StillGoingInput["session"]; + readonly latestTurn: StillGoingInput["latestTurn"]; + readonly queuedFollowUps?: ReadonlyArray<unknown> | undefined; + readonly hasPendingApprovals: boolean; + readonly hasPendingUserInput: boolean; + readonly hasActionableProposedPlan: boolean; + readonly awaitedChildThreadCount?: number | undefined; + readonly pendingChildApproval?: boolean | undefined; + readonly checkBacks?: StillGoingInput["checkBacks"]; +}): StillGoingInput { + return { + session: shell.session, + latestTurn: shell.latestTurn, + queuedCount: shell.queuedFollowUps?.length ?? 0, + waitsOnUser: + shell.hasPendingApprovals || shell.hasPendingUserInput || shell.hasActionableProposedPlan, + openRequestCount: (shell.awaitedChildThreadCount ?? 0) + (shell.pendingChildApproval ? 1 : 0), + checkBacks: shell.checkBacks, + }; +} From 1741985dd6be65fd1f7315a592f791fb7053dbf7 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:38:34 -0500 Subject: [PATCH 02/16] feat(contracts): keep the access limit on linked sends and record owed reports at turn start Fixes from the step 1 review: an outgoing child request and thread.remote-request.queue carry the sender's access; thread.turn-start-requested and thread.session-set carry the report a starting turn owes, and an owed report is keyed by message or by turn; the still-going test reads plain facts and counts a running side answer and a turn about to start; a client can't give a session stop its cause or claim stopsWithParent. --- apps/server/src/orchestration/Normalizer.ts | 8 ++ .../src/orchestration/childThreadDecisions.ts | 2 + packages/contracts/src/orchestration.ts | 42 ++++++++-- packages/shared/src/childThreads.test.ts | 52 ++++++++---- packages/shared/src/childThreads.ts | 81 ++++++++++++------- 5 files changed, 132 insertions(+), 53 deletions(-) diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.ts index f7d5604ae..98ccdf9a6 100644 --- a/apps/server/src/orchestration/Normalizer.ts +++ b/apps/server/src/orchestration/Normalizer.ts @@ -182,6 +182,14 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) => }); } + // Nor say why a session stops: only the server stops one with its family + // or as cleanup, which leaves no Stop hold. + if (command.type === "thread.session.stop" && command.cause !== undefined) { + return yield* new OrchestrationDispatchCommandError({ + message: "Only the server can stop a thread with its family or as cleanup.", + }); + } + // Nor speak for a parent's agent: its thread_wrap is checked as the agent's. if (command.type === "thread.done-override.set" && command.byParentAgent !== undefined) { return yield* new OrchestrationDispatchCommandError({ diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 20b3c4074..6b87de6cf 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -114,6 +114,7 @@ export function claimsServerLineage(fields: { readonly parentThreadId?: unknown; readonly parentTurnId?: unknown; readonly attachedToParent?: unknown; + readonly stopsWithParent?: unknown; readonly remoteOrigin?: unknown; readonly scheduledRun?: unknown; readonly outsideOrigin?: unknown; @@ -123,6 +124,7 @@ export function claimsServerLineage(fields: { fields.parentThreadId !== undefined || fields.parentTurnId !== undefined || fields.attachedToParent !== undefined || + fields.stopsWithParent !== undefined || fields.remoteOrigin !== undefined || fields.scheduledRun !== undefined || fields.outsideOrigin !== undefined || diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index fcf3a097c..2c4653c98 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -3005,6 +3005,13 @@ export const OrchestrationChildRequest = Schema.Struct({ callerTurnId: TurnId, /** This thread's delivery epoch when it was asked; see OrchestrationChildRequestState. */ deliveryEpoch: NonNegativeInt, + /** + * This thread's access when it asked, and its pass's block (see + * MessageAccessFields): kept on the request so a send delivered later, or + * retried over a link, carries the limit that was in force when the agent + * sent it. Absent: a request from before it was kept. + */ + ...MessageAccessFields, status: ChildRequestStatus, /** Reserved when it is asked for, before the child exists. */ childThreadId: ThreadId, @@ -3066,12 +3073,10 @@ export type OwedReportStamps = typeof OwedReportStamps.Type; * no message, by the turn. Removed when the report is settled, and the whole * list empties when the thread's attachment epoch moves. */ -export const OwedChildReport = Schema.Struct({ - messageId: Schema.optional(MessageId), - turnId: Schema.optional(TurnId), - ...OwedReportStamps.fields, - createdAt: IsoDateTime, -}); +export const OwedChildReport = Schema.Union([ + Schema.Struct({ messageId: MessageId, ...OwedReportStamps.fields, createdAt: IsoDateTime }), + Schema.Struct({ turnId: TurnId, ...OwedReportStamps.fields, createdAt: IsoDateTime }), +]); export type OwedChildReport = typeof OwedChildReport.Type; export const OrchestrationChildRequestState = Schema.Struct({ @@ -4784,6 +4789,13 @@ const ThreadSessionSetCommand = Schema.Struct({ * usage limit with a known reset arms "Continue at reset" when it is on. */ continueAfterUsageLimits: Schema.optional(Schema.Boolean), + /** + * Ingestion's word that `session.activeTurnId` is a turn the provider + * started with no message (a check-back, background work that finished), + * so the decision can record the report it owes its parent + * (docs/design/agent-autonomy-no-limits.md, "Delivery rules", rule 3). + */ + providerStartedTurn: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, }); @@ -5580,6 +5592,12 @@ const ThreadRemoteRequestQueueCommand = Schema.Struct({ messageId: MessageId, text: TrimmedNonEmptyString, fromThread: ThreadMessageOrigin, + /** + * The asking computer's ceiling (PeerSendInput's `ceiling`), or, from an + * older sender that sends none, the one this computer gives the request. + * See MessageAccessFields. + */ + ...MessageAccessFields, createdAt: IsoDateTime, }); @@ -6994,6 +7012,12 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({ */ liftsMoveFence: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, + /** + * The turn owes the thread's parent a report: recorded on + * `childRequests.owedReports`, keyed by `messageId`, with these stamps. + * See OwedChildReport. + */ + owesReport: Schema.optional(OwedReportStamps), }); export const ThreadFollowUpSubmittedPayload = Schema.Struct({ @@ -7131,6 +7155,12 @@ export const ThreadWorkflowRunRecordedPayload = Schema.Struct({ export const ThreadSessionSetPayload = Schema.Struct({ threadId: ThreadId, session: OrchestrationSession, + /** + * The report the provider-started turn now running owes the thread's + * parent: added to `childRequests.owedReports`. See ThreadSessionSetCommand's + * `providerStartedTurn`. + */ + owedReport: Schema.optional(OwedChildReport), }); /** The user closed this error's notice; see `OrchestrationSession.lastErrorDismissedAt`. */ diff --git a/packages/shared/src/childThreads.test.ts b/packages/shared/src/childThreads.test.ts index 050c06faf..129720f5c 100644 --- a/packages/shared/src/childThreads.test.ts +++ b/packages/shared/src/childThreads.test.ts @@ -20,6 +20,7 @@ import { isStillGoing, remoteChildrenOf, remoteChildStartsOf, + stillGoingInputOfShell, stopReachOf, type StillGoingInput, } from "./childThreads.ts"; @@ -307,33 +308,52 @@ describe("family walks", () => { describe("isStillGoing", () => { const idle: StillGoingInput = { - session: { status: "ready" }, - latestTurn: { state: "completed" }, + turnInFlight: false, queuedCount: 0, waitsOnUser: false, + backgroundWork: false, openRequestCount: 0, + waitsForReset: false, + sideAnswerRunning: false, }; it("is false for an idle open session, and true for each kind of work", () => { expect(isStillGoing(idle)).toBe(false); - expect(isStillGoing({ ...idle, latestTurn: { state: "running" } })).toBe(true); - expect(isStillGoing({ ...idle, session: { status: "starting" } })).toBe(true); - expect(isStillGoing({ ...idle, queuedCount: 1 })).toBe(true); - expect(isStillGoing({ ...idle, waitsOnUser: true })).toBe(true); - expect(isStillGoing({ ...idle, openRequestCount: 1 })).toBe(true); - expect( - isStillGoing({ ...idle, session: { status: "ready", pendingBackgroundTaskCount: 1 } }), - ).toBe(true); - expect( - isStillGoing({ - ...idle, - session: { status: "error", continueAtReset: { at: "2026-11-23T12:00:00.000Z" } }, - }), - ).toBe(true); + for (const going of [ + { turnInFlight: true }, + { queuedCount: 1 }, + { waitsOnUser: true }, + { backgroundWork: true }, + { openRequestCount: 1 }, + { waitsForReset: true }, + { sideAnswerRunning: true }, + ]) { + expect(isStillGoing({ ...idle, ...going })).toBe(true); + } }); it("counts a check-back, saved or not, until it is dormant", () => { expect(isStillGoing({ ...idle, checkBacks: [{}] })).toBe(true); expect(isStillGoing({ ...idle, checkBacks: [{ dormant: true }] })).toBe(false); }); + + it("reads a shell: an open session with nothing in it is not going", () => { + const shell = { + session: { status: "ready" }, + latestTurn: { state: "completed" }, + queuedFollowUps: [], + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + awaitedChildThreadCount: 0, + pendingChildApproval: false, + }; + expect(isStillGoing(stillGoingInputOfShell(shell))).toBe(false); + expect( + isStillGoing(stillGoingInputOfShell({ ...shell, session: { status: "starting" } })), + ).toBe(true); + expect(isStillGoing(stillGoingInputOfShell({ ...shell, pendingChildApproval: true }))).toBe( + true, + ); + }); }); diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 63c24dfc3..42803b7d4 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -31,6 +31,7 @@ import { } from "@threadlines/contracts"; import { hasLiveCheckBack } from "./checkBacks.ts"; +import { hasLiveSideTurn, type SideTurnFields } from "./sideTurns.ts"; import { exceedsRuntimeMode, saferRuntimeMode } from "./runtimeMode.ts"; import { isRoomThread } from "./threadParticipants.ts"; @@ -855,24 +856,27 @@ export function stopReachOf<T extends FamilyMember>( } /** - * What the "still going" test reads about a thread. The thread's shell and - * its detail both carry these, so the server's stop and revert rules and the - * client's counts read the same answer. + * What the "still going" test reads about a thread, as plain facts. The + * server builds it from a thread's detail, the client from its shell or its + * sidebar summary (each knows its own fields: a summary renames the session's + * `starting`, and only the client sees a message no turn has picked up yet), + * so both read the same answer from the same facts. */ export interface StillGoingInput { - readonly session: { - readonly status: string; - readonly pendingBackgroundTaskCount?: number | undefined; - readonly awaitedBackgroundTaskCount?: number | undefined; - readonly continueAtReset?: unknown; - } | null; - readonly latestTurn: { readonly state: string } | null; + /** A turn running or starting, or a message about to start one. */ + readonly turnInFlight: boolean; /** Messages waiting in its queue. */ readonly queuedCount: number; /** An approval, a question or a plan waiting on the user. */ readonly waitsOnUser: boolean; + /** Background work of any kind, awaited or not (a dev server it left running). */ + readonly backgroundWork: boolean; /** Its own open child requests, starts still waiting for the user included. */ readonly openRequestCount: number; + /** A wait to continue at a usage limit's reset. */ + readonly waitsForReset: boolean; + /** A room agent answering on the side. */ + readonly sideAnswerRunning: boolean; readonly checkBacks?: ReadonlyArray<{ readonly dormant?: true | undefined }> | undefined; } @@ -884,40 +888,55 @@ export interface StillGoingInput { * on screen. An idle session with none of these is not going. */ export function isStillGoing(thread: StillGoingInput): boolean { - const session = thread.session; return ( - thread.latestTurn?.state === "running" || - session?.status === "running" || - session?.status === "starting" || + thread.turnInFlight || thread.queuedCount > 0 || thread.waitsOnUser || - (session?.pendingBackgroundTaskCount ?? 0) > 0 || - (session?.awaitedBackgroundTaskCount ?? 0) > 0 || + thread.backgroundWork || thread.openRequestCount > 0 || - (session?.continueAtReset ?? null) !== null || + thread.waitsForReset || + thread.sideAnswerRunning || hasLiveCheckBack(thread) ); } -/** The "still going" input from a thread's shell, as the client holds it. */ -export function stillGoingInputOfShell(shell: { - readonly session: StillGoingInput["session"]; - readonly latestTurn: StillGoingInput["latestTurn"]; - readonly queuedFollowUps?: ReadonlyArray<unknown> | undefined; - readonly hasPendingApprovals: boolean; - readonly hasPendingUserInput: boolean; - readonly hasActionableProposedPlan: boolean; - readonly awaitedChildThreadCount?: number | undefined; - readonly pendingChildApproval?: boolean | undefined; - readonly checkBacks?: StillGoingInput["checkBacks"]; -}): StillGoingInput { +/** + * The "still going" facts from a thread's shell as the server sends it. The + * client adds a message no turn has picked up yet to `turnInFlight` itself. + */ +export function stillGoingInputOfShell( + shell: SideTurnFields & { + readonly session: { + readonly status: string; + readonly pendingBackgroundTaskCount?: number | undefined; + readonly awaitedBackgroundTaskCount?: number | undefined; + readonly continueAtReset?: unknown; + } | null; + readonly latestTurn: { readonly state: string } | null; + readonly queuedFollowUps?: ReadonlyArray<unknown> | undefined; + readonly hasPendingApprovals: boolean; + readonly hasPendingUserInput: boolean; + readonly hasActionableProposedPlan: boolean; + readonly awaitedChildThreadCount?: number | undefined; + readonly pendingChildApproval?: boolean | undefined; + readonly checkBacks?: StillGoingInput["checkBacks"]; + }, +): StillGoingInput { + const session = shell.session; return { - session: shell.session, - latestTurn: shell.latestTurn, + turnInFlight: + shell.latestTurn?.state === "running" || + session?.status === "running" || + session?.status === "starting", queuedCount: shell.queuedFollowUps?.length ?? 0, waitsOnUser: shell.hasPendingApprovals || shell.hasPendingUserInput || shell.hasActionableProposedPlan, + backgroundWork: + (session?.pendingBackgroundTaskCount ?? 0) > 0 || + (session?.awaitedBackgroundTaskCount ?? 0) > 0, openRequestCount: (shell.awaitedChildThreadCount ?? 0) + (shell.pendingChildApproval ? 1 : 0), + waitsForReset: (session?.continueAtReset ?? null) !== null, + sideAnswerRunning: hasLiveSideTurn(shell), checkBacks: shell.checkBacks, }; } From 077fd8a8ed6925fa55041037d2409f324ecafd99 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:58:04 -0500 Subject: [PATCH 03/16] feat(web): Stop counts every thread still going, and the family row gets a Stop button Stage 1, step 5 of docs/design/agent-autonomy-no-limits.md. - "Stop N working threads" counts by the shared still-going test over Stop's reach (countStillGoingInReach), so a child that only checks back and a thread started without report back that the user hasn't written in are counted. The summary's facts are read in its own words: `connecting` for a starting session, the queue count, and a message no turn has picked up yet. - The chat's family tab row ends with a plain "Stop N threads" button while the open thread's reach has anything still going. It sends the menu's command (thread.children.stop, no ids). The tabs sit in their own strip, so they take the room it leaves and scroll under it on a phone. - The web store carries stopsWithParent and clears it on a person-written message and on put back, as the server does. - The "Checking back" pill, the wrapped row's countdown and the chat's check-back line ignore dormant check-backs; the store notices a dormant mark changing. - Delete with its threads sends alsoDelete with the ids the dialog counted, keeping withChildren for older servers. --- .../components/ChatView.agents.browser.tsx | 73 +++++++++++ .../components/ChatView.sidebar.browser.tsx | 16 ++- apps/web/src/components/Sidebar.logic.test.ts | 19 +++ apps/web/src/components/Sidebar.logic.ts | 39 +++++- apps/web/src/components/chat/FamilyTabs.tsx | 97 ++++++++++---- .../components/chat/MessagesTimeline.logic.ts | 6 +- .../src/components/chat/MessagesTimeline.tsx | 9 +- apps/web/src/components/chat/checkBacks.ts | 20 ++- .../components/chat/familyTabs.logic.test.ts | 33 ++++- .../src/components/chat/familyTabs.logic.ts | 20 +++ .../src/components/threadMenu.logic.test.ts | 119 +++++++++++++++++- apps/web/src/components/threadMenu.logic.ts | 48 ++++++- apps/web/src/hooks/useThreadActions.ts | 77 +++++++----- apps/web/src/hooks/useThreadMenu.ts | 80 +++++------- apps/web/src/lib/threadSessionCommands.ts | 16 +++ apps/web/src/store.ts | 38 +++++- apps/web/src/types.ts | 6 + docs/design/lead-chat.md | 6 + 18 files changed, 594 insertions(+), 128 deletions(-) diff --git a/apps/web/src/components/ChatView.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx index c80763c3e..fd9faecc7 100644 --- a/apps/web/src/components/ChatView.agents.browser.tsx +++ b/apps/web/src/components/ChatView.agents.browser.tsx @@ -77,6 +77,7 @@ import { rpcHarness, createUserMessage, withLinkedThreadReadFixture, + setSidebarThreadWork, } from "./ChatView.browser-harness"; import { selectSidebarThreadSummaryByRef, useStore } from "../store"; import { resolveThreadStatusPill } from "./Sidebar.logic"; @@ -1426,6 +1427,78 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { } }); + it("ends the family row with Stop while the parent's threads are going, and sends what the menu sends", async () => { + const child = "thread-family-stop-child" as ThreadId; + const quiet = "thread-family-stop-quiet" as ThreadId; + const withThreads = addThreadToSnapshot( + addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-family-stop" as MessageId, + targetText: "family stop target", + }), + child, + ), + quiet, + ); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...withThreads, + threads: withThreads.threads.map((thread) => + thread.id === child || thread.id === quiet + ? { + ...thread, + title: thread.id === child ? "Write the changelog" : "Fix the flaky test", + parentThreadId: THREAD_ID, + attachedToParent: true, + createdAt: thread.id === child ? isoAt(10) : isoAt(20), + } + : thread, + ), + }, + }); + const row = () => document.querySelector<HTMLElement>('[data-testid="family-tabs"]'); + const stopButton = () => + row()?.querySelector<HTMLButtonElement>('[data-testid="family-tabs-stop"]') ?? null; + try { + await waitForElement(row, "The family row should show on the parent."); + // Nothing under the parent is going: no button. + await vi.waitFor(() => expect(row()!.querySelectorAll('[role="tab"]').length).toBe(3), { + timeout: 10_000, + }); + expect(stopButton()).toBeNull(); + + // A child waits on the user: the parent's Stop reaches it. + setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, child, "needs-you"); + await vi.waitFor(() => expect(stopButton()?.textContent).toBe("Stop 1 thread")); + // It sits at the row's end, after the last tab. + const lastTab = [...row()!.querySelectorAll<HTMLElement>('[role="tab"]')].at(-1)!; + expect(stopButton()!.getBoundingClientRect().left).toBeGreaterThan( + lastTab.getBoundingClientRect().right, + ); + + stopButton()!.click(); + const stops = () => + wsRequests.filter( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "thread.children.stop", + ); + await vi.waitFor(() => expect(stops()).toHaveLength(1)); + // The parent, with no ids: every thread its Stop reaches that is still going. + expect(stops()[0]).toMatchObject({ threadId: THREAD_ID }); + expect(stops()[0]).not.toHaveProperty("childThreadIds"); + + // Once nothing is going, the button leaves. + setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, child, "needs-you", { + hasPendingApprovals: false, + }); + await vi.waitFor(() => expect(stopButton()).toBeNull()); + } finally { + await mounted.cleanup(); + } + }); + it("opens a thread started on a computer this app can't see, read through the link", async () => { const windows = EnvironmentId.make("environment-windows"); const childId = "thread-child-windows" as ThreadId; diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index cfdbdc9ae..ff422af71 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -565,16 +565,22 @@ describe("ChatView (full app): sidebar", () => { await page.getByRole("button", { name: "Delete", exact: true }).click(); await page.getByTestId("thread-delete-with-children").click(); await page.getByTestId("thread-delete-confirm").click(); + // It names the threads the dialog counted, so the server deletes those + // and keeps one started since; withChildren stays for an older server. await vi.waitFor(() => { expect( - wsRequests.some( + wsRequests.filter( (request) => request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && - request.type === "thread.delete" && - request.threadId === THREAD_ID && - request.withChildren === true, + request.type === "thread.delete", ), - ).toBe(true); + ).toEqual([ + expect.objectContaining({ + threadId: THREAD_ID, + withChildren: true, + alsoDelete: [childId], + }), + ]); }); // The server decides which children go. This one is still here (it was diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index fef32cb5d..92c5cbf4b 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -628,6 +628,25 @@ describe("resolveThreadStatusPill", () => { label: "Checking back", checkBackAt: "2026-03-09T12:00:00.000Z", }); + // A dormant one can't fire until its agent runs again: the pill names the + // next one that can, and none once every one is dormant. + const [later, sooner] = settled.checkBacks; + expect( + resolveThreadStatusPill({ + thread: { ...settled, checkBacks: [later!, { ...sooner!, dormant: true as const }] }, + }), + ).toMatchObject({ label: "Checking back", checkBackAt: "2026-03-09T12:30:00.000Z" }); + expect( + resolveThreadStatusPill({ + thread: { + ...settled, + checkBacks: settled.checkBacks.map((checkBack) => ({ + ...checkBack, + dormant: true as const, + })), + }, + }), + ).toBeNull(); // A result nobody has read comes first. expect( resolveThreadStatusPill({ thread: { ...settled, lastVisitedAt: undefined } }), diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 0e5ffbb71..11cda8c2f 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -25,7 +25,7 @@ import { isLatestTurnSettled, isWaitingOnBackgroundTasks } from "../session-logi import { startOfLocalDayMs } from "../timestampFormat"; import { nextCheckBack } from "./chat/checkBacks"; import { shortFamilyTitles } from "./familyTitles.logic"; -import { isHandedBackCompletion } from "@threadlines/shared/childThreads"; +import { isHandedBackCompletion, type StillGoingInput } from "@threadlines/shared/childThreads"; import { hasUnseenCompletion as hasUnseenCompletionSince, hasUnseenSessionFailure as hasUnseenSessionFailureSince, @@ -1779,11 +1779,46 @@ const IN_FLIGHT: ReadonlySet<ThreadStatusPill["label"]> = new Set([ "Waiting", ]); -/** A child with work in flight: what "Stop N working threads" stops. */ +/** + * A child whose row shows work in flight (Working, Starting, Answering, + * Waiting): what a family's summary line counts as working. What a Stop + * reaches is wider (threadMenu.logic.ts, `countStillGoingInReach`). + */ export function isChildThreadWorking<T extends InboxFamilyStatus>(entry: T): boolean { return !entry.isDone && entry.status !== null && IN_FLIGHT.has(entry.status.label); } +/** + * The "still going" facts (`isStillGoing`) from a sidebar summary. A summary + * says `connecting` for a session the server calls `starting`, keeps only how + * many messages are queued, and is the one place that sees a message no turn + * has picked up yet ({@link hasQueuedTurnStart}), which counts as a turn about + * to start. + */ +export function stillGoingInputOfSummary( + thread: SidebarThreadSummary, + now: string, +): StillGoingInput { + const session = thread.session; + return { + turnInFlight: + thread.latestTurn?.state === "running" || + session?.status === "running" || + session?.status === "connecting" || + hasQueuedTurnStart(thread, { now }), + queuedCount: thread.queuedFollowUpCount ?? 0, + waitsOnUser: + thread.hasPendingApprovals || thread.hasPendingUserInput || thread.hasActionableProposedPlan, + backgroundWork: + (session?.pendingBackgroundTaskCount ?? 0) > 0 || + (session?.awaitedBackgroundTaskCount ?? 0) > 0, + openRequestCount: (thread.awaitedChildThreadCount ?? 0) + (thread.pendingChildApproval ? 1 : 0), + waitsForReset: (session?.continueAtReset ?? null) !== null, + sideAnswerRunning: hasLiveSideTurn(thread), + checkBacks: thread.checkBacks, + }; +} + /** What a thread asks of the user right now, as the rail and Fleet count it. */ export type ThreadAttention = "needs-you" | "working"; diff --git a/apps/web/src/components/chat/FamilyTabs.tsx b/apps/web/src/components/chat/FamilyTabs.tsx index 86c0ff8e5..59c590776 100644 --- a/apps/web/src/components/chat/FamilyTabs.tsx +++ b/apps/web/src/components/chat/FamilyTabs.tsx @@ -16,9 +16,10 @@ import { parseScopedThreadKey, scopedThreadKey } from "@threadlines/client-runtime"; import type { ScopedThreadRef } from "@threadlines/contracts"; import { useNavigate } from "@tanstack/react-router"; -import { CheckIcon, CrownIcon } from "lucide-react"; +import { CheckIcon, CrownIcon, SquareIcon } from "lucide-react"; import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { create } from "zustand"; +import { useShallow } from "zustand/react/shallow"; import { useInboxThreads } from "../../hooks/useInboxThreads"; import { useIsMobile } from "../../hooks/useMediaQuery"; @@ -29,9 +30,12 @@ import { useTouchHoldMenu } from "../../hooks/useTouchHoldMenu"; import { useConnectedComputerCapabilityCheck } from "../../environments/computerCapabilities"; import { linkedThreadRouteParams } from "../../environments/links/linkedThreads"; import { requestIdleThreadDetailPrewarm } from "../../environments/runtime/service"; +import { stopThreadsUnder } from "../../lib/threadSessionCommands"; import { cn } from "../../lib/utils"; +import { selectSidebarThreadsAcrossEnvironments, useStore } from "../../store"; import { buildThreadRouteParams } from "../../threadRoutes"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; +import { failureNotice, toastManager } from "../ui/toast"; import { LeadChatCard, LeadChatSuggestion } from "./LeadChatHints"; import { FAMILY_TAB_MIN_WIDTH_PX, @@ -61,13 +65,20 @@ export function useFamilyTabsShown(threadKey: string | null): boolean { const TAB_BOX_CLASS = "flex h-6 items-center gap-1.5 rounded-md px-2 text-xs"; /** The "+N" button's box, shared the same way. */ const OVERFLOW_BOX_CLASS = "relative flex h-6 shrink-0 items-center rounded-md px-2 text-xs"; +/** The "Stop N threads" button's box. */ +const STOP_BOX_CLASS = "flex h-6 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs"; + +/** "Stop 1 thread", "Stop 3 threads". */ +function stopLabel(count: number): string { + return `Stop ${count} ${count === 1 ? "thread" : "threads"}`; +} /** What a tab shows as its title: the lead's is "Lead". */ function tabText(tab: FamilyTab): string { return tab.kind === "parent" && tab.lead ? "Lead" : tab.shortTitle; } -/** The row as drawn: its width inside the padding, the gap between tabs, and each tab's own width. */ +/** The tab strip as drawn: its width (what the Stop button leaves), the gap between tabs, and each tab's own width. */ interface RowMeasure { readonly rowPx: number; readonly gapPx: number; @@ -89,7 +100,7 @@ function sameRowMeasure(left: RowMeasure | null, right: RowMeasure): boolean { } /** - * Reads the row and the hidden copies of its tabs (`measureRef`): what fits + * Reads the tab strip and the hidden copies of its tabs (`measureRef`): what fits * is decided before a tab is drawn, and one behind "+N" isn't drawn at all. * The copies are the tabs' own markup and classes, so a larger browser font, * a theme's font, or a font that loads late shows up as a resize the @@ -209,6 +220,7 @@ export function FamilyTabs({ openKey, parentKey }: { openKey: string; parentKey? */ export function useFamilyTabs(openKey: string, parentKey?: string): FamilyTabsModel | null { const { entries, nowIso } = useInboxThreads(); + const threads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); const remoteFamilyChildren = useRemoteFamilyChildren(nowIso); const readsLinked = useConnectedComputerCapabilityCheck("linkedThreadRead"); const family = useMemo(() => { @@ -217,6 +229,7 @@ export function useFamilyTabs(openKey: string, parentKey?: string): FamilyTabsMo openKey, parentKey, entries, + threads, remoteChildrenOf: (parent) => remoteFamilyChildren(parent.thread, (threadId) => keys.has(scopedThreadKey({ environmentId: parent.thread.environmentId, threadId })), @@ -224,7 +237,7 @@ export function useFamilyTabs(openKey: string, parentKey?: string): FamilyTabsMo canReadLinked: (parent) => readsLinked(parent.thread.environmentId), now: nowIso, }); - }, [entries, nowIso, openKey, parentKey, readsLinked, remoteFamilyChildren]); + }, [entries, nowIso, openKey, parentKey, readsLinked, remoteFamilyChildren, threads]); return useKept(family, sameFamilyTabs); } @@ -254,6 +267,7 @@ const FamilyTabRow = memo(function FamilyTabRow({ } }, [openKey, isMobile]); + const stop = family.stop; const { shown, hidden } = measure === null ? { shown: family.tabs, hidden: [] as readonly FamilyTab[] } @@ -284,15 +298,9 @@ const FamilyTabRow = memo(function FamilyTabRow({ return ( <> <div - ref={rowRef} - role="tablist" - aria-label="This thread's family" data-testid="family-tabs" data-family-key={family.familyKey} - className={cn( - "relative flex min-w-0 shrink-0 items-center gap-0.5 border-b border-border px-3 py-1 sm:px-5", - isMobile && "overflow-x-auto [scrollbar-width:none]", - )} + className="relative flex min-w-0 shrink-0 items-center gap-0.5 border-b border-border px-3 py-1 sm:px-5" > {isMobile ? null : ( // Every tab and "+N" at full width, unseen, for useRowMeasure. @@ -316,17 +324,29 @@ const FamilyTabRow = memo(function FamilyTabRow({ </span> </div> )} - {shown.map((tab) => ( - <FamilyTabButton - key={tab.key} - tab={tab} - active={tab.key === family.openKey} - fill={!isMobile} - onOpen={onOpen} - buttonRef={tab.key === family.openKey ? openTabRef : undefined} - /> - ))} - {hidden.length > 0 ? <FamilyTabOverflow hidden={hidden} onOpen={onOpen} /> : null} + {/* The tabs take the room the Stop button leaves; on a phone they scroll sideways under it. */} + <div + ref={rowRef} + role="tablist" + aria-label="This thread's family" + className={cn( + "flex min-w-0 flex-1 items-center gap-0.5", + isMobile && "overflow-x-auto [scrollbar-width:none]", + )} + > + {shown.map((tab) => ( + <FamilyTabButton + key={tab.key} + tab={tab} + active={tab.key === family.openKey} + fill={!isMobile} + onOpen={onOpen} + buttonRef={tab.key === family.openKey ? openTabRef : undefined} + /> + ))} + {hidden.length > 0 ? <FamilyTabOverflow hidden={hidden} onOpen={onOpen} /> : null} + </div> + {stop !== null ? <FamilyStopButton threadRef={stop.threadRef} count={stop.count} /> : null} </div> {suggestLead !== null ? <LeadChatSuggestion parentRef={suggestLead} /> : null} </> @@ -437,6 +457,39 @@ function FamilyTabFace({ tab }: { tab: FamilyTab }) { ); } +/** + * "Stop N threads" at the row's end (docs/design/agent-autonomy-no-limits.md, + * "Stop"): a lead waiting on its team has no running turn, so its composer + * shows no Stop. It sends what the menu's "Stop N working threads" sends, and + * shows only while something in the open thread's reach is still going. + */ +const FamilyStopButton = memo(function FamilyStopButton({ + threadRef, + count, +}: { + threadRef: ScopedThreadRef; + count: number; +}) { + return ( + <button + type="button" + data-testid="family-tabs-stop" + className={cn( + STOP_BOX_CLASS, + "text-muted-foreground transition-colors hover:text-foreground focus-ring", + )} + onClick={() => { + stopThreadsUnder(threadRef).catch((error: unknown) => { + toastManager.add(failureNotice({ title: "Couldn't stop its threads", error })); + }); + }} + > + <SquareIcon aria-hidden="true" className="size-2 shrink-0 fill-current" strokeWidth={0} /> + <span className="whitespace-nowrap">{stopLabel(count)}</span> + </button> + ); +}); + /** "+N": the tabs that don't fit, with their status; amber while one needs the user. */ function FamilyTabOverflow({ hidden, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 45ac48c32..8d57372bf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,6 +1,7 @@ import * as Equal from "effect/Equal"; import { estimateWorkflowRunCardHeight } from "./workflowRunView"; import { MCP_APP_CARD_ESTIMATED_PX } from "./mcpAppClient"; +import { nextCheckBack } from "./checkBacks"; import { formatAwaitedTasks, formatSoleAwaitedWorkflow, @@ -848,8 +849,9 @@ export function deriveMessagesTimelineRows(input: { }); } - // A settled thread an agent will come back to says when, at the tail. - if (!input.isWorking && input.checkBacks && input.checkBacks.length > 0) { + // A settled thread an agent will come back to says when, at the tail. A + // dormant check-back can't fire until its agent runs again, so it says nothing. + if (!input.isWorking && input.checkBacks && nextCheckBack(input.checkBacks) !== null) { rows.push({ ...UNPLACED, kind: "check-back", diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index de0b9e953..ea8791877 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -214,7 +214,12 @@ import { TranscriptHighlightContextCard, } from "./TranscriptHighlightContextCard"; import { TooltipProvider, TooltipWrapper } from "../ui/tooltip"; -import { describeCheckBack, formatCheckBackTime, nextCheckBack } from "./checkBacks"; +import { + describeCheckBack, + formatCheckBackTime, + liveCheckBacks, + nextCheckBack, +} from "./checkBacks"; import { useRelativeTimeTick } from "../../hooks/useRelativeTimeTick"; import { deriveDisplayedUserMessageState, @@ -4591,7 +4596,7 @@ function CheckBackTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "chec const { label, when } = describeCheckBack(soonest, nowMs); // In a room, the line says which agent will come back. const agentName = roomAgents?.get(roomAgentKey(soonest.participantId))?.name ?? null; - const others = row.checkBacks.filter((checkBack) => checkBack !== soonest); + const others = liveCheckBacks(row.checkBacks).filter((checkBack) => checkBack !== soonest); return ( <div className="py-1" data-check-back-row="true"> <p className="flex min-w-0 items-center gap-1.5 pl-1 text-xs leading-4 text-muted-foreground"> diff --git a/apps/web/src/components/chat/checkBacks.ts b/apps/web/src/components/chat/checkBacks.ts index 9c7158d3e..c3a7ec963 100644 --- a/apps/web/src/components/chat/checkBacks.ts +++ b/apps/web/src/components/chat/checkBacks.ts @@ -72,12 +72,26 @@ export function describeCheckBack( }; } -/** The soonest check-back, the one the chat and the sidebar name. */ +/** + * The check-backs that can still fire. One marked dormant can't: the runtime + * that would fire it has ended, until that agent runs again. + */ +export function liveCheckBacks( + checkBacks: ReadonlyArray<OrchestrationCheckBack> | undefined, +): ReadonlyArray<OrchestrationCheckBack> { + if (!checkBacks || checkBacks.length === 0) return []; + return checkBacks.some((checkBack) => checkBack.dormant === true) + ? checkBacks.filter((checkBack) => checkBack.dormant !== true) + : checkBacks; +} + +/** The soonest check-back that can still fire, the one the chat and the sidebar name. */ export function nextCheckBack( checkBacks: ReadonlyArray<OrchestrationCheckBack> | undefined, ): OrchestrationCheckBack | null { - if (!checkBacks || checkBacks.length === 0) return null; - return checkBacks.reduce((soonest, checkBack) => + const live = liveCheckBacks(checkBacks); + if (live.length === 0) return null; + return live.reduce((soonest, checkBack) => checkBack.scheduledFor < soonest.scheduledFor ? checkBack : soonest, ); } diff --git a/apps/web/src/components/chat/familyTabs.logic.test.ts b/apps/web/src/components/chat/familyTabs.logic.test.ts index bfa423a26..dd8f833f6 100644 --- a/apps/web/src/components/chat/familyTabs.logic.test.ts +++ b/apps/web/src/components/chat/familyTabs.logic.test.ts @@ -61,10 +61,15 @@ function entry( }; } -const tabsFor = (open: string, entries: readonly FamilyTabEntry[]) => +const tabsFor = ( + open: string, + entries: readonly FamilyTabEntry[], + threads: readonly SidebarThreadSummary[] = entries.map((member) => member.thread), +) => familyTabsOf({ openKey: keyOf(open), entries, + threads, remoteChildrenOf: () => [], canReadLinked: () => true, now: NOW, @@ -136,6 +141,31 @@ describe("family tabs", () => { const openGone = tabsFor("gone", wrapped); expect(openGone?.tabs.find((tab) => tab.key === keyOf("gone"))).toMatchObject({ done: true }); }); + + it("ends with Stop on the open thread while its Stop reaches something still going", () => { + const running = { status: "running" } as SidebarThreadSummary["session"]; + const busy = (member: FamilyTabEntry, extra: Partial<SidebarThreadSummary> = {}) => ({ + ...member, + thread: { ...member.thread, session: running, ...extra }, + }); + // A child at work, and a thread started without report back the lead's + // Stop still reaches: not a tab, but counted, as the menu counts it. + const loose = busy(entry("loose", { parent: "lead", attached: false }), { + stopsWithParent: true, + }); + const members = [family[0]!, busy(family[1]!), family[2]!]; + const threads = [...members, loose].map((member) => member.thread); + const onLead = tabsFor("lead", members, threads); + expect(onLead?.tabs.map((tab) => tab.key)).not.toContain(keyOf("loose")); + expect(onLead?.stop).toEqual({ + threadRef: scopeThreadRef(environmentId, ThreadId.make("lead")), + count: 2, + }); + // On a child the row is the same, and the button is for the child's own reach: none. + expect(tabsFor("second", members, threads)?.stop).toBeNull(); + // Nothing going: no button. + expect(tabsFor("lead", family)?.stop).toBeNull(); + }); }); describe("family tabs with children on a computer this app can't see", () => { @@ -151,6 +181,7 @@ describe("family tabs with children on a computer this app can't see", () => { openKey: input.open, parentKey: input.parentKey, entries: [parent], + threads: [parent.thread], remoteChildrenOf: () => input.remote ?? children, canReadLinked: () => input.readsLinked ?? true, now: NOW, diff --git a/apps/web/src/components/chat/familyTabs.logic.ts b/apps/web/src/components/chat/familyTabs.logic.ts index 4667fbb83..410147407 100644 --- a/apps/web/src/components/chat/familyTabs.logic.ts +++ b/apps/web/src/components/chat/familyTabs.logic.ts @@ -20,6 +20,7 @@ import { liveFamilyOf, } from "../Sidebar.logic"; import { shortFamilyTitles } from "../familyTitles.logic"; +import { countStillGoingInReach } from "../threadMenu.logic"; /** One tab on the row. */ export interface FamilyTab { @@ -60,6 +61,13 @@ export interface FamilyTabs { readonly familyKey: string; readonly tabs: readonly FamilyTab[]; readonly openKey: string; + /** + * The "Stop N threads" button at the row's end: the open thread, and how + * many threads its Stop reaches that are still going (the count its menu's + * "Stop N working threads" shows). Null while none are, or when the open + * thread is one this app reads through the link. + */ + readonly stop: { readonly threadRef: ScopedThreadRef; readonly count: number } | null; } /** What the row reads about each thread, filed the way the sidebar files it. */ @@ -85,6 +93,8 @@ export function familyTabsOf<E extends FamilyTabEntry>(input: { readonly openKey: string; readonly parentKey?: string | undefined; readonly entries: readonly E[]; + /** Every thread the app holds: where a Stop on the open thread can reach. */ + readonly threads: readonly SidebarThreadSummary[]; readonly remoteChildrenOf: (parent: E) => readonly InboxRemoteChild[]; readonly canReadLinked: (parent: E) => boolean; readonly now: string; @@ -148,9 +158,18 @@ export function familyTabsOf<E extends FamilyTabEntry>(input: { }); const children = [...family.children.map(childTab), ...family.remoteChildren.map(remoteTab)]; const shortTitles = shortFamilyTitles(children.map((tab) => tab.title)); + const stopCount = + open === undefined ? 0 : countStillGoingInReach(input.threads, open.thread, input.now); return { familyKey: parent.threadKey, openKey: input.openKey, + stop: + open !== undefined && stopCount > 0 + ? { + threadRef: scopeThreadRef(open.thread.environmentId, open.thread.id), + count: stopCount, + } + : null, tabs: [ { key: parent.threadKey, @@ -190,6 +209,7 @@ export function sameFamilyTabs(left: FamilyTabs | null, right: FamilyTabs | null return ( left.familyKey === right.familyKey && left.openKey === right.openKey && + left.stop?.count === right.stop?.count && left.tabs.length === right.tabs.length && left.tabs.every((tab, index) => { const other = right.tabs[index]!; diff --git a/apps/web/src/components/threadMenu.logic.test.ts b/apps/web/src/components/threadMenu.logic.test.ts index d6aa02c16..e58e6bf4a 100644 --- a/apps/web/src/components/threadMenu.logic.test.ts +++ b/apps/web/src/components/threadMenu.logic.test.ts @@ -1,6 +1,14 @@ +import { + EnvironmentId, + type OrchestrationCheckBack, + ProviderDriverKind, + ThreadId, +} from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; +import type { SidebarThreadSummary } from "../types"; import { + countStillGoingInReach, describeThreadMenu, describeThreadSelectionMenu, type ThreadMenuFacts, @@ -11,7 +19,7 @@ const facts = (overrides: Partial<ThreadMenuFacts> = {}): ThreadMenuFacts => ({ inbox: { isDone: false, canMarkDone: true }, attachedChild: false, putBack: null, - workingChildCount: 0, + stillGoingCount: 0, moveOffered: false, running: false, ...overrides, @@ -28,7 +36,7 @@ describe("the thread menu", () => { describeThreadMenu( facts({ attachedChild: true, - workingChildCount: 2, + stillGoingCount: 2, moveOffered: true, }), ), @@ -87,3 +95,110 @@ describe("the thread menu", () => { expect(describeThreadSelectionMenu({ count: 2, allPinned: true })[1]?.label).toBe("Unpin (2)"); }); }); + +describe("what Stop N working threads counts", () => { + const environmentId = EnvironmentId.make("environment-local"); + const NOW = "2026-11-23T12:00:00.000Z"; + const idleSession: NonNullable<SidebarThreadSummary["session"]> = { + provider: ProviderDriverKind.make("claude"), + status: "ready", + orchestrationStatus: "ready", + createdAt: "2026-11-23T10:00:00.000Z", + updatedAt: "2026-11-23T10:00:00.000Z", + }; + const savedJob: OrchestrationCheckBack = { + id: "every-5m", + participantId: null, + scheduledFor: "2026-11-23T12:05:00.000Z", + exact: false, + recurring: true, + durable: true, + }; + const thread = ( + id: string, + overrides: Partial<SidebarThreadSummary> = {}, + ): SidebarThreadSummary => ({ + id: ThreadId.make(id), + environmentId, + projectId: "project" as SidebarThreadSummary["projectId"], + title: id, + interactionMode: "default", + session: idleSession, + createdAt: "2026-11-23T10:00:00.000Z", + archivedAt: null, + pinnedAt: null, + doneOverride: null, + lastSeenAt: null, + latestTurn: null, + branch: null, + worktreePath: null, + effectiveCwd: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + cumulativeDiffStat: null, + ...overrides, + }); + const childOf = (parent: string, id: string, overrides: Partial<SidebarThreadSummary> = {}) => + thread(id, { parentThreadId: ThreadId.make(parent), attachedToParent: true, ...overrides }); + const looseOf = (parent: string, id: string, overrides: Partial<SidebarThreadSummary> = {}) => + thread(id, { + parentThreadId: ThreadId.make(parent), + attachedToParent: false, + stopsWithParent: true, + session: { ...idleSession, status: "running", orchestrationStatus: "running" }, + ...overrides, + }); + const count = (threads: readonly SidebarThreadSummary[], root = "lead") => + countStillGoingInReach(threads, { environmentId, id: ThreadId.make(root) }, NOW); + + it("counts a child that only checks back, until its check-back goes dormant", () => { + // Sequence 1: M answered and sits idle with a saved, recurring check-back. + const before = [thread("lead"), childOf("lead", "m", { checkBacks: [savedJob] })]; + expect(count(before)).toBe(1); + expect(read(describeThreadMenu(facts({ stillGoingCount: count(before) })))).toContain( + "Stop 1 working thread", + ); + // After the Stop its runtime ended, so the job is dormant: nothing to stop. + const after = [ + thread("lead"), + childOf("lead", "m", { checkBacks: [{ ...savedJob, dormant: true }] }), + ]; + expect(count(after)).toBe(0); + expect(read(describeThreadMenu(facts({ stillGoingCount: count(after) })))).not.toContain( + "Stop 0 working threads", + ); + }); + + it("counts threads started without report back until the user writes in one", () => { + // Sequence 3: five loose threads still at work; then the user made one theirs. + const loose = ["a", "b", "c", "d", "e"].map((id) => looseOf("lead", id)); + expect(count([thread("lead"), ...loose])).toBe(5); + const madeOwn = loose.map((child, index) => { + if (index !== 0) return child; + const { stopsWithParent: _written, ...own } = child; + return own; + }); + expect(count([thread("lead"), ...madeOwn])).toBe(4); + // Another thread's loose threads, and the thread itself, are not its to stop. + expect( + count([ + thread("lead", { session: { ...idleSession, status: "running" } }), + looseOf("other", "f"), + ]), + ).toBe(0); + }); + + it("reads a summary's own words for a starting turn, a queue and a message no turn took yet", () => { + const children = [ + childOf("lead", "idle"), + childOf("lead", "starting", { session: { ...idleSession, status: "connecting" } }), + childOf("lead", "queued", { queuedFollowUpCount: 1 }), + // Sent a minute ago and newer than its last turn: about to start. + childOf("lead", "sent", { latestUserMessageAt: "2026-11-23T11:59:00.000Z" }), + childOf("lead", "waiting", { awaitedChildThreadCount: 1 }), + ]; + expect(count([thread("lead"), ...children])).toBe(4); + }); +}); diff --git a/apps/web/src/components/threadMenu.logic.ts b/apps/web/src/components/threadMenu.logic.ts index fa2373660..e679bd51b 100644 --- a/apps/web/src/components/threadMenu.logic.ts +++ b/apps/web/src/components/threadMenu.logic.ts @@ -1,6 +1,9 @@ -import type { ContextMenuItem } from "@threadlines/contracts"; +import type { ContextMenuItem, ThreadId } from "@threadlines/contracts"; +import { type FamilyMember, isStillGoing, stopReachOf } from "@threadlines/shared/childThreads"; import { LEAD_MENU_SUBLABEL, leadMenuLabel, type LeadMenuState } from "../leadChat"; +import type { SidebarThreadSummary } from "../types"; +import { stillGoingInputOfSummary } from "./Sidebar.logic"; /** Everything a thread's menu can do. Every surface that offers it offers the same. */ export type ThreadMenuAction = @@ -32,8 +35,11 @@ export interface ThreadMenuFacts { readonly attachedChild: boolean; /** A separated child whose parent could take it back; `refusal` says why it can't now. */ readonly putBack: { readonly parentTitle: string; readonly refusal: string | null } | null; - /** Threads it started that are still at work. */ - readonly workingChildCount: number; + /** + * Threads its Stop reaches that are still going (`countStillGoingInReach`), + * one that only checks back and one started without report back included. + */ + readonly stillGoingCount: number; readonly moveOffered: boolean; /** Its agent is mid-turn: archiving waits until it stops. */ readonly running: boolean; @@ -46,6 +52,38 @@ export interface ThreadMenuFacts { } | null; } +/** + * How many threads a Stop on `thread` reaches that are still going: what + * "Stop N working threads" and the family row's Stop button count, by the + * server's own walk (`stopReachOf`) and test (`isStillGoing`). Threads + * started without report back that the user hasn't written in count too. + * `threads` is every thread the app holds; only those on the same computer + * can be in reach. + */ +export function countStillGoingInReach( + threads: Iterable<SidebarThreadSummary>, + thread: Pick<SidebarThreadSummary, "environmentId" | "id">, + now: string, +): number { + const members: FamilyMember[] = []; + const summaries = new Map<ThreadId, SidebarThreadSummary>(); + for (const candidate of threads) { + if (candidate.environmentId !== thread.environmentId) continue; + summaries.set(candidate.id, candidate); + members.push({ + id: candidate.id, + parentThreadId: candidate.parentThreadId ?? null, + attachedToParent: candidate.attachedToParent ?? false, + stopsWithParent: candidate.stopsWithParent, + createdAt: candidate.createdAt, + }); + } + return stopReachOf(members, thread.id).filter((member) => { + const summary = summaries.get(member.thread.id); + return summary !== undefined && isStillGoing(stillGoingInputOfSummary(summary, now)); + }).length; +} + /** * Whether the thread's agent is mid-turn, from its session: the menu greys out * Archive then, and a swipe doesn't offer it. @@ -121,10 +159,10 @@ export function describeThreadMenu(facts: ThreadMenuFacts): ContextMenuItem<Thre disabled: refusal !== null, }); } - if (facts.workingChildCount > 0) { + if (facts.stillGoingCount > 0) { family.push({ id: "stop-children", - label: `Stop ${facts.workingChildCount} working ${facts.workingChildCount === 1 ? "thread" : "threads"}`, + label: `Stop ${facts.stillGoingCount} working ${facts.stillGoingCount === 1 ? "thread" : "threads"}`, }); } items.push(...asGroup(family)); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 3e81a9908..83077a9e1 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -55,26 +55,35 @@ async function confirmOrphanedWorktreeDeletion(worktreePath: string): Promise<bo } /** - * The threads a delete "with its threads" should take along: the thread's + * The threads a delete "with its threads" offers to take along: the thread's * attached children that are not archived, as this device knows them. The - * server applies the same rule to its own state, so the count the user is - * shown matches what goes. It can still differ when a child leaves the family - * in the meantime, so this list only decides the count and where to navigate. - * The server cleans up each thread it actually deletes (ThreadDeletionReactor) - * and each client forgets it when its removal arrives. + * dialog counts these and the delete names them (`alsoDelete`), so the server + * deletes exactly what the user was shown: one still attached and unarchived + * when it decides. A thread started after the dialog counted is separated and + * kept. The server cleans up each thread it actually deletes + * (ThreadDeletionReactor) and each client forgets it when its removal arrives. */ -function selectDeletableChildThreads(target: ScopedThreadRef): Thread[] { - return selectThreadsForEnvironment(useStore.getState(), target.environmentId).filter( - (thread) => - thread.parentThreadId === target.threadId && - thread.attachedToParent === true && - thread.archivedAt === null, - ); +export function deletableChildThreadIds(target: ScopedThreadRef): ThreadId[] { + return selectThreadsForEnvironment(useStore.getState(), target.environmentId) + .filter( + (thread) => + thread.parentThreadId === target.threadId && + thread.attachedToParent === true && + thread.archivedAt === null, + ) + .map((thread) => thread.id); } -/** How many threads a delete "with its threads" would take along; see selectDeletableChildThreads. */ -export function countAttachedChildThreads(target: ScopedThreadRef): number { - return selectDeletableChildThreads(target).length; +/** + * What `thread.delete` says about the family: with its threads, naming the + * ones the dialog listed. `withChildren` stays for a server that predates + * `alsoDelete`, where it means every attached child, one level. + */ +function familyDeleteFields(alsoDelete: ReadonlyArray<ThreadId> | undefined): { + readonly withChildren?: true; + readonly alsoDelete?: ThreadId[]; +} { + return alsoDelete === undefined ? {} : { withChildren: true, alsoDelete: [...alsoDelete] }; } /** @@ -241,8 +250,11 @@ export function useThreadActions() { target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string>; - /** Child threads: delete the threads in its family too, instead of separating them. */ - withChildren?: boolean; + /** + * Child threads: delete these threads in its family too, the ones the + * dialog listed (deletableChildThreadIds), instead of separating them. + */ + alsoDelete?: ReadonlyArray<ThreadId>; } = {}, ) => { const api = readEnvironmentApi(target.environmentId); @@ -273,18 +285,18 @@ export function useThreadActions() { // An archived parent can still have live threads in its family. The // server winds down and deletes the ones it takes along. - const deletedChildren = opts.withChildren ? selectDeletableChildThreads(target) : []; + const deletedChildren = opts.alsoDelete ?? []; await api.orchestration.dispatchCommand({ type: "thread.delete", commandId: newCommandId(), threadId: target.threadId, - ...(opts.withChildren ? { withChildren: true } : {}), + ...familyDeleteFields(opts.alsoDelete), }); refreshArchivedThreadsForEnvironment(target.environmentId); const currentRouteThreadRef = getCurrentRouteThreadRef(); if ( currentRouteThreadRef?.environmentId === target.environmentId && - deletedChildren.some((child) => child.id === currentRouteThreadRef.threadId) + deletedChildren.includes(currentRouteThreadRef.threadId) ) { await router.navigate({ to: "/", replace: true }); } @@ -334,20 +346,17 @@ export function useThreadActions() { threadProject !== undefined && (await confirmOrphanedWorktreeDeletion(orphanedWorktreePath)); - // Its family goes with it when asked. The server decides which children - // that is and winds each one down; this device only steers away from them. - const deletedChildren = opts.withChildren ? selectDeletableChildThreads(threadRef) : []; + // Its family goes with it when asked: the threads the dialog listed. The + // server winds each one down; this device only steers away from them. + const deletedChildren = opts.alsoDelete ?? []; await windDownThreadBeforeDelete(api, threadRef.environmentId, thread); - const deletedThreadIds = new Set<ThreadId>([ - ...(deletedIds ?? []), - ...deletedChildren.map((child) => child.id), - ]); + const deletedThreadIds = new Set<ThreadId>([...(deletedIds ?? []), ...deletedChildren]); const currentRouteThreadRef = getCurrentRouteThreadRef(); const shouldNavigateToFallback = currentRouteThreadRef?.environmentId === threadRef.environmentId && (currentRouteThreadRef.threadId === threadRef.threadId || - deletedChildren.some((child) => child.id === currentRouteThreadRef.threadId)); + deletedChildren.includes(currentRouteThreadRef.threadId)); const fallbackThreadId = getFallbackThreadIdAfterDelete({ threads, deletedThreadId: threadRef.threadId, @@ -357,7 +366,7 @@ export function useThreadActions() { type: "thread.delete", commandId: newCommandId(), threadId: threadRef.threadId, - ...(opts.withChildren ? { withChildren: true } : {}), + ...familyDeleteFields(opts.alsoDelete), }); refreshArchivedThreadsForEnvironment(threadRef.environmentId); forgetDeletedThread(threadRef.environmentId, thread); @@ -411,17 +420,17 @@ export function useThreadActions() { const localApi = readLocalApi(); const resolved = resolveThreadTarget(target); const title = opts.title ?? resolved?.thread.title; - const childCount = countAttachedChildThreads(target); + const childIds = deletableChildThreadIds(target); - if (confirmThreadDelete && childCount > 0) { + if (confirmThreadDelete && childIds.length > 0) { const answer = await confirmThreadDeleteWithChildren({ title: title ?? "this thread", - childCount, + childCount: childIds.length, }); if (answer === null) { return; } - await deleteThread(target, { withChildren: answer.withChildren }); + await deleteThread(target, answer.withChildren ? { alsoDelete: childIds } : {}); return; } diff --git a/apps/web/src/hooks/useThreadMenu.ts b/apps/web/src/hooks/useThreadMenu.ts index 969b8a0ee..033c7a432 100644 --- a/apps/web/src/hooks/useThreadMenu.ts +++ b/apps/web/src/hooks/useThreadMenu.ts @@ -3,15 +3,12 @@ import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@threadlines/c import { childAttachRefusal } from "@threadlines/shared/childThreads"; import { useCallback, useMemo } from "react"; -import { - attachedParentKeyOf, - isChildThreadWorking, - resolveThreadStatusPill, -} from "../components/Sidebar.logic"; +import { attachedParentKeyOf } from "../components/Sidebar.logic"; import { confirmThreadDeleteWithChildren } from "../components/ThreadDeleteDialog"; import { openThreadMoveDialog } from "../components/ThreadMoveDialog"; import { openThreadRenameDialog } from "../components/ThreadRenameDialog"; import { + countStillGoingInReach, describeThreadMenu, isThreadTurnRunning, describeThreadSelectionMenu, @@ -26,6 +23,7 @@ import { markThreadUnreadByKey, reopenThreadByKey, } from "../lib/threadInboxSync"; +import { stopThreadsUnder } from "../lib/threadSessionCommands"; import { newCommandId } from "../lib/utils"; import { readLocalApi } from "../localApi"; import { @@ -37,7 +35,7 @@ import { import type { SidebarThreadSummary } from "../types"; import { useSettings } from "./useSettings"; import { readLeadMenuState, setProjectLead } from "../leadChat"; -import { useThreadActions } from "./useThreadActions"; +import { deletableChildThreadIds, useThreadActions } from "./useThreadActions"; /** The thread a menu is for, and what only its surface knows. */ export interface ThreadMenuTarget { @@ -91,14 +89,11 @@ export function useThreadMenu() { const children = [...byKey.values()].filter( (candidate) => candidate.archivedAt === null && attachedParentKeyOf(candidate) === threadKey, ); - const workingChildCount = children.filter((child) => - isChildThreadWorking({ - threadKey: scopedThreadKey(scopeThreadRef(child.environmentId, child.id)), - thread: child, - status: resolveThreadStatusPill({ thread: child }), - isDone: false, - }), - ).length; + const stillGoingCount = countStillGoingInReach( + byKey.values(), + thread, + new Date().toISOString(), + ); const parent = thread.parentThreadId != null ? (byKey.get( @@ -138,7 +133,7 @@ export function useThreadMenu() { inbox: target.inbox ?? null, attachedChild, putBack, - workingChildCount, + stillGoingCount, moveOffered: readThreadMoveOffered(thread), running: isThreadTurnRunning(full?.session), customOrder: target.customOrder ?? null, @@ -186,35 +181,30 @@ export function useThreadMenu() { case "reopen": reopenThreadByKey(threadKey); return; + case "stop-children": + try { + await stopThreadsUnder(threadRef); + } catch (error) { + errorToast("Couldn't stop its threads", error); + } + return; case "separate": - case "attach": - case "stop-children": { + case "attach": { const api = readEnvironmentApi(threadRef.environmentId); if (!api) return; try { - await api.orchestration.dispatchCommand( - action === "stop-children" - ? { - type: "thread.children.stop", - commandId: newCommandId(), - threadId: threadRef.threadId, - createdAt: new Date().toISOString(), - } - : { - type: "thread.parent-attachment.set", - commandId: newCommandId(), - threadId: threadRef.threadId, - attached: action === "attach", - createdAt: new Date().toISOString(), - }, - ); + await api.orchestration.dispatchCommand({ + type: "thread.parent-attachment.set", + commandId: newCommandId(), + threadId: threadRef.threadId, + attached: action === "attach", + createdAt: new Date().toISOString(), + }); } catch (error) { errorToast( - action === "stop-children" - ? "Couldn't stop its threads" - : action === "attach" - ? "Couldn't put the thread back" - : "Couldn't make it its own thread", + action === "attach" + ? "Couldn't put the thread back" + : "Couldn't make it its own thread", error, ); } @@ -281,18 +271,16 @@ export function useThreadMenu() { } case "delete": { const api = readLocalApi(); - // A parent's threads are separated, not deleted, unless the user says so. - const childCount = [...byKey.values()].filter( - (candidate) => - candidate.archivedAt === null && attachedParentKeyOf(candidate) === threadKey, - ).length; - if (confirmDelete && childCount > 0) { + // A parent's threads are separated, not deleted, unless the user + // says so; then exactly the ones the dialog counted go. + const childIds = deletableChildThreadIds(threadRef); + if (confirmDelete && childIds.length > 0) { const answer = await confirmThreadDeleteWithChildren({ title: thread.title, - childCount, + childCount: childIds.length, }); if (answer === null) return; - await deleteThread(threadRef, { withChildren: answer.withChildren }); + await deleteThread(threadRef, answer.withChildren ? { alsoDelete: childIds } : {}); return; } if ( diff --git a/apps/web/src/lib/threadSessionCommands.ts b/apps/web/src/lib/threadSessionCommands.ts index edcacd867..482dfe710 100644 --- a/apps/web/src/lib/threadSessionCommands.ts +++ b/apps/web/src/lib/threadSessionCommands.ts @@ -20,3 +20,19 @@ export async function stopThreadSession(threadRef: ScopedThreadRef): Promise<voi createdAt: new Date().toISOString(), }); } + +/** + * Stop every thread under this one that is still going ("Stop N working + * threads" in its menu, and the Stop button on its family's tab row). The + * thread itself keeps running; the server decides which threads that is. + */ +export async function stopThreadsUnder(threadRef: ScopedThreadRef): Promise<void> { + const api = readEnvironmentApi(threadRef.environmentId); + if (!api) return; + await api.orchestration.dispatchCommand({ + type: "thread.children.stop", + commandId: newCommandId(), + threadId: threadRef.threadId, + createdAt: new Date().toISOString(), + }); +} diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 206d0da75..9e241aa00 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -435,6 +435,13 @@ function mapMessage(environmentId: EnvironmentId, message: OrchestrationMessage) }; } +/** The thread without the mark that keeps it under its starter's Stop (stopsWithParent). */ +function withoutStopsWithParent(thread: Thread): Thread { + if (thread.stopsWithParent === undefined) return thread; + const { stopsWithParent: _made, ...rest } = thread; + return rest; +} + /** * A thread's place in a family of child threads, as every web copy of it * carries it: normalized so a missing field and its empty value read alike. @@ -443,6 +450,7 @@ function threadLineage(thread: { readonly parentThreadId?: ThreadId | null | undefined; readonly parentTurnId?: TurnId | null | undefined; readonly attachedToParent?: boolean | undefined; + readonly stopsWithParent?: true | undefined; readonly handedBackAt?: string | null | undefined; readonly handedBackTurnId?: TurnId | null | undefined; readonly scheduledRun?: ThreadScheduledRun | null | undefined; @@ -453,6 +461,7 @@ function threadLineage(thread: { | "parentThreadId" | "parentTurnId" | "attachedToParent" + | "stopsWithParent" | "handedBackAt" | "handedBackTurnId" | "scheduledRun" @@ -463,6 +472,7 @@ function threadLineage(thread: { parentThreadId: thread.parentThreadId ?? null, parentTurnId: thread.parentTurnId ?? null, attachedToParent: thread.attachedToParent ?? false, + ...(thread.stopsWithParent === true ? { stopsWithParent: true as const } : {}), handedBackAt: thread.handedBackAt ?? null, handedBackTurnId: thread.handedBackTurnId ?? null, scheduledRun: thread.scheduledRun ?? null, @@ -750,6 +760,7 @@ function sidebarLineage( | "parentThreadId" | "parentTurnId" | "attachedToParent" + | "stopsWithParent" | "handedBackAt" | "handedBackTurnId" | "awaitedChildThreadCount" @@ -771,6 +782,7 @@ function sidebarLineage( | "parentThreadId" | "parentTurnId" | "attachedToParent" + | "stopsWithParent" | "handedBackAt" | "handedBackTurnId" | "awaitedChildThreadCount" @@ -793,6 +805,7 @@ function sidebarLineage( parentThreadId: thread.parentThreadId ?? null, parentTurnId: thread.parentTurnId ?? null, attachedToParent: thread.attachedToParent ?? false, + ...(thread.stopsWithParent === true ? { stopsWithParent: true as const } : {}), handedBackAt: thread.handedBackAt ?? null, handedBackTurnId: thread.handedBackTurnId ?? null, awaitedChildThreadCount: thread.awaitedChildThreadCount ?? 0, @@ -1416,6 +1429,7 @@ function sidebarThreadSummariesEqual( (left.parentThreadId ?? null) === (right.parentThreadId ?? null) && (left.parentTurnId ?? null) === (right.parentTurnId ?? null) && (left.attachedToParent ?? false) === (right.attachedToParent ?? false) && + (left.stopsWithParent ?? false) === (right.stopsWithParent ?? false) && (left.handedBackAt ?? null) === (right.handedBackAt ?? null) && (left.handedBackTurnId ?? null) === (right.handedBackTurnId ?? null) && (left.awaitedChildThreadCount ?? 0) === (right.awaitedChildThreadCount ?? 0) && @@ -1536,6 +1550,7 @@ function threadShellsEqual(left: ThreadShell | undefined, right: ThreadShell): b (left.parentThreadId ?? null) === (right.parentThreadId ?? null) && (left.parentTurnId ?? null) === (right.parentTurnId ?? null) && (left.attachedToParent ?? false) === (right.attachedToParent ?? false) && + (left.stopsWithParent ?? false) === (right.stopsWithParent ?? false) && (left.handedBackAt ?? null) === (right.handedBackAt ?? null) && (left.handedBackTurnId ?? null) === (right.handedBackTurnId ?? null) && (left.awaitedChildThreadCount ?? 0) === (right.awaitedChildThreadCount ?? 0) && @@ -1575,8 +1590,12 @@ function checkBackListsEqual( const rightList = right ?? []; return ( sameCheckBacks(leftList, rightList) && + // The agent and the dormant mark too: a check-back whose runtime ended + // leaves the "Checking back" pill. leftList.every( - (checkBack, index) => checkBack.participantId === rightList[index]?.participantId, + (checkBack, index) => + checkBack.participantId === rightList[index]?.participantId && + checkBack.dormant === rightList[index]?.dormant, ) ); } @@ -2781,6 +2800,7 @@ function applyEnvironmentOrchestrationEvent( parentThreadId: event.payload.parentThreadId ?? null, parentTurnId: event.payload.parentTurnId ?? null, attachedToParent: event.payload.attachedToParent ?? false, + ...(event.payload.stopsWithParent === true ? { stopsWithParent: true as const } : {}), parentAttachmentEpoch: 0, handedBackAt: null, handedBackTurnId: null, @@ -3232,8 +3252,13 @@ function applyEnvironmentOrchestrationEvent( assistantMessageId: event.payload.messageId, }) : thread.latestTurn; + // A person writing here makes a thread started without report back + // their own: it leaves its starter's Stop, as on the server. + const madeOwn = + event.payload.role === "user" && + (event.payload.composer !== undefined || event.payload.sentFrom !== undefined); return { - ...thread, + ...(madeOwn ? withoutStopsWithParent(thread) : thread), messages, turnDiffSummaries, latestTurn, @@ -3856,17 +3881,22 @@ function applyEnvironmentOrchestrationEvent( // Taken back by the thread that started it over a link, which moved // here: a child here now, no longer the other computer's. const adoptedBy = event.payload.adoptedBy; + // Put back under its parent, a thread started without report back is + // the family's, not under Stop on its own any more. return updateThreadState(state, event.payload.threadId, (thread) => adoptedBy !== undefined ? { - ...thread, + ...withoutStopsWithParent(thread), attachedToParent: event.payload.attached, parentThreadId: adoptedBy.parentThreadId, remoteOrigin: null, } : (thread.attachedToParent ?? false) === event.payload.attached ? thread - : { ...thread, attachedToParent: event.payload.attached }, + : { + ...(event.payload.attached ? withoutStopsWithParent(thread) : thread), + attachedToParent: event.payload.attached, + }, ); } diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index bc5bbd164..2338e2b0f 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -282,6 +282,8 @@ export interface Thread { parentTurnId?: TurnId | null; /** Still part of its parent's family. Absent means separated or no parent. */ attachedToParent?: boolean; + /** See OrchestrationThreadShell.stopsWithParent: under its parent's Stop though never attached. */ + stopsWithParent?: true; /** When its last answer went back to its parent, and from which turn. */ handedBackAt?: string | null; handedBackTurnId?: TurnId | null; @@ -403,6 +405,8 @@ export interface ThreadShell { parentTurnId?: TurnId | null; /** Still part of its parent's family. Absent means separated or no parent. */ attachedToParent?: boolean; + /** See OrchestrationThreadShell.stopsWithParent: under its parent's Stop though never attached. */ + stopsWithParent?: true; /** When its last answer went back to its parent, and from which turn. */ handedBackAt?: string | null; handedBackTurnId?: TurnId | null; @@ -548,6 +552,8 @@ export interface SidebarThreadSummary { parentTurnId?: TurnId | null; /** See ThreadShell.attachedToParent: nested under its parent in the inbox. */ attachedToParent?: boolean; + /** See ThreadShell.stopsWithParent: under its parent's Stop though never attached. */ + stopsWithParent?: true; /** See ThreadShell.scheduledRun. */ scheduledRun?: ThreadScheduledRun | null; /** Its worktree is another thread's (ThreadWorktreeOrigin): a guest there, not its owner. */ diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md index 66ec02b26..a77ae1f0f 100644 --- a/docs/design/lead-chat.md +++ b/docs/design/lead-chat.md @@ -189,6 +189,12 @@ always one click away, and so is every thread it started. The parent's tab and the open thread's tab are always on the row. "+N" carries an amber dot when a hidden thread needs the user. On a phone the row scrolls sideways instead and the open tab is scrolled into view. +- **Stop.** While anything a Stop on the open thread reaches is still going, the row + ends with a plain "Stop N threads" button. It counts and sends what the thread + menu's "Stop N working threads" does (`thread.children.stop`), so a lead waiting on + its team, which has no running turn and so no Stop in its composer, still has a + brake on screen (docs/design/agent-autonomy-no-limits.md, "Stop"). The tabs take the + room it leaves, and on a phone it stays put while they scroll. - **What it replaces.** While the row shows, the header drops the "Started by" chip and the "Lead chat" chip: the row says both. - **The sidebar is unchanged.** The open child still shows under its parent's row as From a28ddc1c408b38a6ba32e9b475ad9d5ac90fde4d Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:08:16 -0500 Subject: [PATCH 04/16] fix(web): Stop counts what the stop settles, and a person's queued or steered message frees a loose thread Fixes from the step 5 review. - A thread started without report back leaves its starter's Stop on every event that records a person's message (composer or sentFrom): sent, queued, steered in and accepted, not only sent. - The Stop count (now countThreadsToStop) adds what an id-less thread.children.stop also settles: a child on a linked computer with a request open, and a child still being set up with no thread yet. - The count's "waits on the user" reads every approval the Pending Approval pill reads; a summary rebuilt from the thread's detail keeps a settings change, a key request and a schedule approval apart. - Delete with its threads no longer leaves a listed child's open chat: the server may keep it, and the thread route goes home when a removal really arrives. Only the named thread's chat steers away. - The Scheduled page's "and N more" counts only check-backs that can fire. - Browser test: the family row's Stop stays in view on a phone while the tabs scroll. --- .../components/ChatView.agents.browser.tsx | 52 ++++++++++++ .../components/ChatView.sidebar.browser.tsx | 12 +++ apps/web/src/components/Sidebar.logic.ts | 18 ++-- .../src/components/chat/familyTabs.logic.ts | 10 +-- .../scheduled/scheduled.logic.test.ts | 10 +++ .../components/scheduled/scheduled.logic.ts | 5 +- .../src/components/threadMenu.logic.test.ts | 66 +++++++++++++-- apps/web/src/components/threadMenu.logic.ts | 40 +++++---- apps/web/src/hooks/useThreadActions.ts | 24 +++--- apps/web/src/hooks/useThreadMenu.ts | 10 +-- apps/web/src/store.test.ts | 84 +++++++++++++++++++ apps/web/src/store.ts | 28 +++++-- docs/design/lead-chat.md | 8 +- 13 files changed, 302 insertions(+), 65 deletions(-) diff --git a/apps/web/src/components/ChatView.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx index fd9faecc7..028929232 100644 --- a/apps/web/src/components/ChatView.agents.browser.tsx +++ b/apps/web/src/components/ChatView.agents.browser.tsx @@ -1499,6 +1499,58 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { } }); + it("keeps the family row's Stop in view on a phone while the tabs scroll under it", async () => { + const children = ["phone-first", "phone-second", "phone-third"].map( + (id) => `thread-family-${id}` as ThreadId, + ); + const withThreads = children.reduce( + (snapshot, id) => addThreadToSnapshot(snapshot, id), + createSnapshotForTargetUser({ + targetMessageId: "msg-user-family-phone" as MessageId, + targetText: "family phone target", + }), + ); + const mounted = await mountChatView({ + viewport: PHONE_VIEWPORT, + snapshot: { + ...withThreads, + threads: withThreads.threads.map((thread) => { + const index = children.indexOf(thread.id); + return index === -1 + ? thread + : { + ...thread, + title: `A long title for the thread that does part ${index + 1} of the work`, + parentThreadId: THREAD_ID, + attachedToParent: true, + createdAt: isoAt(10 + index), + }; + }), + }, + }); + const row = () => document.querySelector<HTMLElement>('[data-testid="family-tabs"]'); + try { + await waitForElement(row, "The family row should show on the parent."); + setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, children[2]!, "needs-you"); + const stop = await waitForElement( + () => row()?.querySelector<HTMLElement>('[data-testid="family-tabs-stop"]') ?? null, + "The Stop button should show.", + ); + const strip = row()!.querySelector<HTMLElement>('[role="tablist"]')!; + // The tabs overflow and scroll; the button stays whole inside the row and the screen. + expect(strip.scrollWidth).toBeGreaterThan(strip.clientWidth); + const rowRect = row()!.getBoundingClientRect(); + const stopRect = stop.getBoundingClientRect(); + expect(stopRect.left).toBeGreaterThanOrEqual(strip.getBoundingClientRect().right); + expect(stopRect.right).toBeLessThanOrEqual(Math.min(rowRect.right, window.innerWidth)); + strip.scrollLeft = strip.scrollWidth; + await nextFrames(2); + expect(stop.getBoundingClientRect().left).toBe(stopRect.left); + } finally { + await mounted.cleanup(); + } + }); + it("opens a thread started on a computer this app can't see, read through the link", async () => { const windows = EnvironmentId.make("environment-windows"); const childId = "thread-child-windows" as ThreadId; diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index ff422af71..7c90295cb 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -549,6 +549,16 @@ describe("ChatView (full app): sidebar", () => { const mounted = await mountFamily(null); try { useComposerDraftStore.getState().setPrompt(childRef, "half-written reply"); + // The child is open while its parent is deleted from the sidebar. + await mounted.router.navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: LOCAL_ENVIRONMENT_ID, threadId: childId }, + }); + await waitForURL( + mounted.router, + (pathname) => pathname.endsWith(`/${childId}`), + "The child should be open.", + ); const row = await waitForElement( () => document.querySelector<HTMLElement>(`[data-testid="thread-row-${THREAD_ID}"]`), "The parent's sidebar row should be on screen.", @@ -598,6 +608,8 @@ describe("ChatView (full app): sidebar", () => { expect(useComposerDraftStore.getState().getComposerDraft(childRef)?.prompt).toBe( "half-written reply", ); + // Nor is its chat left: only the thread's real removal does that. + expect(mounted.router.state.location.pathname.endsWith(`/${childId}`)).toBe(true); // The thread the user named is wound down here as before. expect( wsRequests.some( diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 11cda8c2f..3dc8b73bc 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1782,7 +1782,7 @@ const IN_FLIGHT: ReadonlySet<ThreadStatusPill["label"]> = new Set([ /** * A child whose row shows work in flight (Working, Starting, Answering, * Waiting): what a family's summary line counts as working. What a Stop - * reaches is wider (threadMenu.logic.ts, `countStillGoingInReach`). + * reaches is wider (threadMenu.logic.ts, `countThreadsToStop`). */ export function isChildThreadWorking<T extends InboxFamilyStatus>(entry: T): boolean { return !entry.isDone && entry.status !== null && IN_FLIGHT.has(entry.status.label); @@ -1791,9 +1791,9 @@ export function isChildThreadWorking<T extends InboxFamilyStatus>(entry: T): boo /** * The "still going" facts (`isStillGoing`) from a sidebar summary. A summary * says `connecting` for a session the server calls `starting`, keeps only how - * many messages are queued, and is the one place that sees a message no turn - * has picked up yet ({@link hasQueuedTurnStart}), which counts as a turn about - * to start. + * many messages are queued, keeps some approvals apart, and is the one place + * that sees a message no turn has picked up yet ({@link hasQueuedTurnStart}), + * which counts as a turn about to start. */ export function stillGoingInputOfSummary( thread: SidebarThreadSummary, @@ -1807,8 +1807,16 @@ export function stillGoingInputOfSummary( session?.status === "connecting" || hasQueuedTurnStart(thread, { now }), queuedCount: thread.queuedFollowUpCount ?? 0, + // Every wait the "Pending Approval" pill reads: a summary rebuilt from the + // thread's detail keeps a settings change, a key or a schedule apart from + // hasPendingApprovals, where the server's shell folds the first two in. waitsOnUser: - thread.hasPendingApprovals || thread.hasPendingUserInput || thread.hasActionableProposedPlan, + thread.hasPendingApprovals || + thread.pendingSettingsChange === true || + thread.pendingSecretRequest === true || + thread.pendingScheduleApproval === true || + thread.hasPendingUserInput || + thread.hasActionableProposedPlan, backgroundWork: (session?.pendingBackgroundTaskCount ?? 0) > 0 || (session?.awaitedBackgroundTaskCount ?? 0) > 0, diff --git a/apps/web/src/components/chat/familyTabs.logic.ts b/apps/web/src/components/chat/familyTabs.logic.ts index 410147407..26149d833 100644 --- a/apps/web/src/components/chat/familyTabs.logic.ts +++ b/apps/web/src/components/chat/familyTabs.logic.ts @@ -20,7 +20,7 @@ import { liveFamilyOf, } from "../Sidebar.logic"; import { shortFamilyTitles } from "../familyTitles.logic"; -import { countStillGoingInReach } from "../threadMenu.logic"; +import { countThreadsToStop } from "../threadMenu.logic"; /** One tab on the row. */ export interface FamilyTab { @@ -63,9 +63,9 @@ export interface FamilyTabs { readonly openKey: string; /** * The "Stop N threads" button at the row's end: the open thread, and how - * many threads its Stop reaches that are still going (the count its menu's - * "Stop N working threads" shows). Null while none are, or when the open - * thread is one this app reads through the link. + * many threads stopping its threads would stop (`countThreadsToStop`, the + * count its menu's "Stop N working threads" shows). Null while that is + * none, or when the open thread is one this app reads through the link. */ readonly stop: { readonly threadRef: ScopedThreadRef; readonly count: number } | null; } @@ -159,7 +159,7 @@ export function familyTabsOf<E extends FamilyTabEntry>(input: { const children = [...family.children.map(childTab), ...family.remoteChildren.map(remoteTab)]; const shortTitles = shortFamilyTitles(children.map((tab) => tab.title)); const stopCount = - open === undefined ? 0 : countStillGoingInReach(input.threads, open.thread, input.now); + open === undefined ? 0 : countThreadsToStop(input.threads, open.thread, input.now); return { familyKey: parent.threadKey, openKey: input.openKey, diff --git a/apps/web/src/components/scheduled/scheduled.logic.test.ts b/apps/web/src/components/scheduled/scheduled.logic.test.ts index 18b3c5ecb..d6977b081 100644 --- a/apps/web/src/components/scheduled/scheduled.logic.test.ts +++ b/apps/web/src/components/scheduled/scheduled.logic.test.ts @@ -423,12 +423,22 @@ describe("check-backs on the Scheduled page", () => { archivedAt: "2026-10-21T07:00:00.000Z", checkBacks: [checkBack("gone", "2026-10-21T08:30:00.000Z")], }, + { + // Its runtime ended: the dormant one is neither the next nor one more. + title: "Paused", + archivedAt: null, + checkBacks: [ + { ...checkBack("dormant", "2026-10-21T11:00:00.000Z"), dormant: true as const }, + checkBack("live", "2026-10-21T12:00:00.000Z"), + ], + }, ]); expect( listed.map((entry) => [entry.thread.title, entry.soonest.id, entry.more] as const), ).toEqual([ ["Docs", "docs", 0], ["Deploy", "soon", 1], + ["Paused", "live", 0], ]); }); }); diff --git a/apps/web/src/components/scheduled/scheduled.logic.ts b/apps/web/src/components/scheduled/scheduled.logic.ts index 6c964b6d3..4581c7782 100644 --- a/apps/web/src/components/scheduled/scheduled.logic.ts +++ b/apps/web/src/components/scheduled/scheduled.logic.ts @@ -47,7 +47,7 @@ import { import * as Result from "effect/Result"; import { viewerTimeZone } from "../../lib/timeZones"; -import { nextCheckBack } from "../chat/checkBacks"; +import { liveCheckBacks, nextCheckBack } from "../chat/checkBacks"; // --------------------------------------------------------------------------- // Where the page is (its search params are in scheduledShell.logic.ts) @@ -1238,7 +1238,8 @@ export function checkBackThreads< .flatMap((thread) => { const soonest = nextCheckBack(thread.checkBacks); if (thread.archivedAt !== null || soonest === null) return []; - return [{ thread, soonest, more: (thread.checkBacks?.length ?? 1) - 1 }]; + // A dormant one can't fire until its agent runs again, so it isn't one more. + return [{ thread, soonest, more: liveCheckBacks(thread.checkBacks).length - 1 }]; }) .toSorted( (left, right) => diff --git a/apps/web/src/components/threadMenu.logic.test.ts b/apps/web/src/components/threadMenu.logic.test.ts index e58e6bf4a..775a9fc55 100644 --- a/apps/web/src/components/threadMenu.logic.test.ts +++ b/apps/web/src/components/threadMenu.logic.test.ts @@ -8,7 +8,7 @@ import { describe, expect, it } from "vite-plus/test"; import type { SidebarThreadSummary } from "../types"; import { - countStillGoingInReach, + countThreadsToStop, describeThreadMenu, describeThreadSelectionMenu, type ThreadMenuFacts, @@ -19,7 +19,7 @@ const facts = (overrides: Partial<ThreadMenuFacts> = {}): ThreadMenuFacts => ({ inbox: { isDone: false, canMarkDone: true }, attachedChild: false, putBack: null, - stillGoingCount: 0, + stopCount: 0, moveOffered: false, running: false, ...overrides, @@ -36,7 +36,7 @@ describe("the thread menu", () => { describeThreadMenu( facts({ attachedChild: true, - stillGoingCount: 2, + stopCount: 2, moveOffered: true, }), ), @@ -151,13 +151,17 @@ describe("what Stop N working threads counts", () => { ...overrides, }); const count = (threads: readonly SidebarThreadSummary[], root = "lead") => - countStillGoingInReach(threads, { environmentId, id: ThreadId.make(root) }, NOW); + countThreadsToStop( + threads, + threads.find((entry) => entry.id === root)!, + NOW, + ); it("counts a child that only checks back, until its check-back goes dormant", () => { // Sequence 1: M answered and sits idle with a saved, recurring check-back. const before = [thread("lead"), childOf("lead", "m", { checkBacks: [savedJob] })]; expect(count(before)).toBe(1); - expect(read(describeThreadMenu(facts({ stillGoingCount: count(before) })))).toContain( + expect(read(describeThreadMenu(facts({ stopCount: count(before) })))).toContain( "Stop 1 working thread", ); // After the Stop its runtime ended, so the job is dormant: nothing to stop. @@ -166,7 +170,7 @@ describe("what Stop N working threads counts", () => { childOf("lead", "m", { checkBacks: [{ ...savedJob, dormant: true }] }), ]; expect(count(after)).toBe(0); - expect(read(describeThreadMenu(facts({ stillGoingCount: count(after) })))).not.toContain( + expect(read(describeThreadMenu(facts({ stopCount: count(after) })))).not.toContain( "Stop 0 working threads", ); }); @@ -201,4 +205,54 @@ describe("what Stop N working threads counts", () => { ]; expect(count([thread("lead"), ...children])).toBe(4); }); + + it("counts an idle child waiting on any approval its pill shows", () => { + // A summary rebuilt from the thread's detail keeps these apart from hasPendingApprovals. + for (const wait of [ + { pendingSettingsChange: true }, + { pendingSecretRequest: true }, + { pendingScheduleApproval: true }, + ]) { + expect(count([thread("lead"), childOf("lead", "asks", wait)])).toBe(1); + } + }); + + it("counts what the stop settles beyond this computer's threads", () => { + const linkedChild = (id: string, followed?: boolean) => ({ + environmentId: EnvironmentId.make("environment-windows"), + label: "Windows PC", + threadId: ThreadId.make(id), + handle: id, + title: id, + attachmentEpoch: 0, + cachedStatus: "working", + updatedAt: "2026-11-23T11:00:00.000Z", + ...(followed !== undefined ? { followed } : {}), + }); + const lead = thread("lead", { + // One it has a request open with (and one from an older server that + // doesn't say), and one whose request already settled. + remoteChildren: [ + linkedChild("asked", true), + linkedChild("older"), + linkedChild("done", false), + ], + // One being set up here with no thread yet, and one whose thread arrived. + localChildStarts: [ + { + requestId: "request-setup" as never, + childThreadId: ThreadId.make("setting-up"), + title: "setting up", + createdAt: "2026-11-23T11:00:00.000Z", + }, + { + requestId: "request-arrived" as never, + childThreadId: ThreadId.make("arrived"), + title: "arrived", + createdAt: "2026-11-23T11:00:00.000Z", + }, + ], + }); + expect(count([lead, childOf("lead", "arrived")])).toBe(3); + }); }); diff --git a/apps/web/src/components/threadMenu.logic.ts b/apps/web/src/components/threadMenu.logic.ts index e679bd51b..e59355093 100644 --- a/apps/web/src/components/threadMenu.logic.ts +++ b/apps/web/src/components/threadMenu.logic.ts @@ -36,10 +36,10 @@ export interface ThreadMenuFacts { /** A separated child whose parent could take it back; `refusal` says why it can't now. */ readonly putBack: { readonly parentTitle: string; readonly refusal: string | null } | null; /** - * Threads its Stop reaches that are still going (`countStillGoingInReach`), - * one that only checks back and one started without report back included. + * Threads its Stop would stop (`countThreadsToStop`): one that only checks + * back, one started without report back, and one on a linked computer included. */ - readonly stillGoingCount: number; + readonly stopCount: number; readonly moveOffered: boolean; /** Its agent is mid-turn: archiving waits until it stops. */ readonly running: boolean; @@ -53,16 +53,22 @@ export interface ThreadMenuFacts { } /** - * How many threads a Stop on `thread` reaches that are still going: what - * "Stop N working threads" and the family row's Stop button count, by the - * server's own walk (`stopReachOf`) and test (`isStillGoing`). Threads - * started without report back that the user hasn't written in count too. - * `threads` is every thread the app holds; only those on the same computer - * can be in reach. + * How many threads "Stop N working threads" and the family row's Stop button + * stop: what an id-less `thread.children.stop` on `thread` targets. + * - Every thread its Stop reaches on this computer that is still going, by + * the server's own walk (`stopReachOf`) and test (`isStillGoing`), threads + * started without report back that the user hasn't written in included. + * - Each child on a linked computer it has a request open with: that request + * is settled and the child stopped there. + * - Each child started here that is still being set up, with no thread yet. + * `threads` is every thread the app holds. */ -export function countStillGoingInReach( +export function countThreadsToStop( threads: Iterable<SidebarThreadSummary>, - thread: Pick<SidebarThreadSummary, "environmentId" | "id">, + thread: Pick< + SidebarThreadSummary, + "environmentId" | "id" | "remoteChildren" | "localChildStarts" + >, now: string, ): number { const members: FamilyMember[] = []; @@ -78,10 +84,16 @@ export function countStillGoingInReach( createdAt: candidate.createdAt, }); } - return stopReachOf(members, thread.id).filter((member) => { + const here = stopReachOf(members, thread.id).filter((member) => { const summary = summaries.get(member.thread.id); return summary !== undefined && isStillGoing(stillGoingInputOfSummary(summary, now)); }).length; + // Absent `followed` is an older server's: it says nothing, so the request is taken as open. + const linked = (thread.remoteChildren ?? []).filter((child) => child.followed !== false).length; + const settingUp = (thread.localChildStarts ?? []).filter( + (start) => !summaries.has(start.childThreadId), + ).length; + return here + linked + settingUp; } /** @@ -159,10 +171,10 @@ export function describeThreadMenu(facts: ThreadMenuFacts): ContextMenuItem<Thre disabled: refusal !== null, }); } - if (facts.stillGoingCount > 0) { + if (facts.stopCount > 0) { family.push({ id: "stop-children", - label: `Stop ${facts.stillGoingCount} working ${facts.stillGoingCount === 1 ? "thread" : "threads"}`, + label: `Stop ${facts.stopCount} working ${facts.stopCount === 1 ? "thread" : "threads"}`, }); } items.push(...asGroup(family)); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 83077a9e1..211764ea7 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -284,8 +284,8 @@ export function useThreadActions() { (await confirmOrphanedWorktreeDeletion(orphanedWorktreePath)); // An archived parent can still have live threads in its family. The - // server winds down and deletes the ones it takes along. - const deletedChildren = opts.alsoDelete ?? []; + // server winds down and deletes the ones it takes along; a child open + // here leaves the chat when its removal arrives (the thread route). await api.orchestration.dispatchCommand({ type: "thread.delete", commandId: newCommandId(), @@ -293,13 +293,6 @@ export function useThreadActions() { ...familyDeleteFields(opts.alsoDelete), }); refreshArchivedThreadsForEnvironment(target.environmentId); - const currentRouteThreadRef = getCurrentRouteThreadRef(); - if ( - currentRouteThreadRef?.environmentId === target.environmentId && - deletedChildren.includes(currentRouteThreadRef.threadId) - ) { - await router.navigate({ to: "/", replace: true }); - } if (shouldDeleteWorktree && orphanedWorktreePath && projectCwd) { await removeOrphanedWorktree({ @@ -347,16 +340,19 @@ export function useThreadActions() { (await confirmOrphanedWorktreeDeletion(orphanedWorktreePath)); // Its family goes with it when asked: the threads the dialog listed. The - // server winds each one down; this device only steers away from them. - const deletedChildren = opts.alsoDelete ?? []; + // server winds each one down and may keep one that left the family + // since, so a child open here is left to its removal (the thread route + // goes home when it arrives). Only the fallback avoids the listed ones. await windDownThreadBeforeDelete(api, threadRef.environmentId, thread); - const deletedThreadIds = new Set<ThreadId>([...(deletedIds ?? []), ...deletedChildren]); + const deletedThreadIds = new Set<ThreadId>([ + ...(deletedIds ?? []), + ...(opts.alsoDelete ?? []), + ]); const currentRouteThreadRef = getCurrentRouteThreadRef(); const shouldNavigateToFallback = currentRouteThreadRef?.environmentId === threadRef.environmentId && - (currentRouteThreadRef.threadId === threadRef.threadId || - deletedChildren.includes(currentRouteThreadRef.threadId)); + currentRouteThreadRef.threadId === threadRef.threadId; const fallbackThreadId = getFallbackThreadIdAfterDelete({ threads, deletedThreadId: threadRef.threadId, diff --git a/apps/web/src/hooks/useThreadMenu.ts b/apps/web/src/hooks/useThreadMenu.ts index 033c7a432..57901caae 100644 --- a/apps/web/src/hooks/useThreadMenu.ts +++ b/apps/web/src/hooks/useThreadMenu.ts @@ -8,7 +8,7 @@ import { confirmThreadDeleteWithChildren } from "../components/ThreadDeleteDialo import { openThreadMoveDialog } from "../components/ThreadMoveDialog"; import { openThreadRenameDialog } from "../components/ThreadRenameDialog"; import { - countStillGoingInReach, + countThreadsToStop, describeThreadMenu, isThreadTurnRunning, describeThreadSelectionMenu, @@ -89,11 +89,7 @@ export function useThreadMenu() { const children = [...byKey.values()].filter( (candidate) => candidate.archivedAt === null && attachedParentKeyOf(candidate) === threadKey, ); - const stillGoingCount = countStillGoingInReach( - byKey.values(), - thread, - new Date().toISOString(), - ); + const stopCount = countThreadsToStop(byKey.values(), thread, new Date().toISOString()); const parent = thread.parentThreadId != null ? (byKey.get( @@ -133,7 +129,7 @@ export function useThreadMenu() { inbox: target.inbox ?? null, attachedChild, putBack, - stillGoingCount, + stopCount, moveOffered: readThreadMoveOffered(thread), running: isThreadTurnRunning(full?.session), customOrder: target.customOrder ?? null, diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 3e6b694f7..e4462aa01 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -2016,6 +2016,90 @@ describe("incremental orchestration updates", () => { expect(sidebarThreads[0]?.remoteOrigin?.threadId).toBe("thread-on-mac"); }); + it("takes a thread started without report back out of its starter's Stop once a person writes in it", () => { + const threadId = ThreadId.make("thread-1"); + const threadRef = scopeThreadRef(localEnvironmentId, threadId); + const base = makeState(makeThread({ id: threadId })); + const environment = base.environmentStateById[localEnvironmentId]!; + const loose: AppState = { + ...base, + environmentStateById: { + ...base.environmentStateById, + [localEnvironmentId]: { + ...environment, + threadShellById: { + ...environment.threadShellById, + [threadId]: { + ...environment.threadShellById[threadId]!, + parentThreadId: ThreadId.make("thread-lead"), + attachedToParent: false, + stopsWithParent: true, + }, + }, + }, + }, + }; + const flagOf = (state: AppState) => selectThreadByRef(state, threadRef)?.stopsWithParent; + expect(flagOf(loose)).toBe(true); + const queued = (origin: { composer?: "typed"; fromAgentThread?: true }) => + applyOrchestrationEvent( + loose, + makeEvent("thread.follow-up-queued", { + threadId, + followUp: { + messageId: MessageId.make("message-queued"), + text: "and the tests too", + attachments: [], + ...(origin.composer !== undefined ? { composer: origin.composer } : {}), + ...(origin.fromAgentThread + ? { + fromThread: { + threadId: ThreadId.make("thread-lead"), + requestId: ChildRequestId.make("request-1"), + kind: "request" as const, + }, + } + : {}), + runtimeMode: DEFAULT_COMPOSER_RUNTIME_MODE, + interactionMode: DEFAULT_INTERACTION_MODE, + createdAt: "2026-02-27T00:00:01.000Z", + }, + }), + localEnvironmentId, + ); + // Queued behind a running turn, steered in, or accepted: each is the person writing. + expect(flagOf(queued({ composer: "typed" }))).toBeUndefined(); + const steer = { + threadId, + turnId: TurnId.make("turn-1"), + messageId: MessageId.make("message-steer"), + role: "user" as const, + text: "steer it", + sentFrom: { kind: "phone" as const }, + createdAt: "2026-02-27T00:00:02.000Z", + }; + expect( + flagOf( + applyOrchestrationEvent( + loose, + makeEvent("thread.follow-up-submitted", steer), + localEnvironmentId, + ), + ), + ).toBeUndefined(); + expect( + flagOf( + applyOrchestrationEvent( + loose, + makeEvent("thread.follow-up-accepted", steer), + localEnvironmentId, + ), + ), + ).toBeUndefined(); + // The agent that started it writing there leaves it under that agent's Stop. + expect(flagOf(queued({ fromAgentThread: true }))).toBe(true); + }); + it("adds accepted follow-ups as inline user messages", () => { const threadId = ThreadId.make("thread-1"); const turnId = TurnId.make("turn-1"); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 9e241aa00..2fcca3dce 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -442,6 +442,21 @@ function withoutStopsWithParent(thread: Thread): Thread { return rest; } +/** + * A person wrote this message (the server's `personWrote`: it came from a + * composer or carries the device it was sent from), so the thread is theirs + * and leaves its starter's Stop. Every event that records such a message + * applies it: a message sent, queued, steered in or accepted. + */ +function madeOwnBy( + thread: Thread, + message: { readonly composer?: unknown; readonly sentFrom?: unknown }, +): Thread { + return message.composer !== undefined || message.sentFrom !== undefined + ? withoutStopsWithParent(thread) + : thread; +} + /** * A thread's place in a family of child threads, as every web copy of it * carries it: normalized so a missing field and its empty value read alike. @@ -2932,7 +2947,7 @@ function applyEnvironmentOrchestrationEvent( case "thread.follow-up-queued": return updateThreadState(state, event.payload.threadId, (thread) => ({ - ...thread, + ...madeOwnBy(thread, event.payload.followUp), queuedFollowUps: withQueuedFollowUp(thread.queuedFollowUps ?? [], event.payload.followUp), })); @@ -3099,7 +3114,7 @@ function applyEnvironmentOrchestrationEvent( case "thread.follow-up-submitted": return updateThreadState(state, event.payload.threadId, (thread) => ({ - ...thread, + ...madeOwnBy(thread, event.payload), updatedAt: event.payload.createdAt, })); @@ -3126,7 +3141,7 @@ function applyEnvironmentOrchestrationEvent( updatedAt: event.payload.createdAt, }); return { - ...thread, + ...madeOwnBy(thread, event.payload), messages: upsertThreadMessage(thread.messages, message), updatedAt: event.payload.createdAt, }; @@ -3252,13 +3267,8 @@ function applyEnvironmentOrchestrationEvent( assistantMessageId: event.payload.messageId, }) : thread.latestTurn; - // A person writing here makes a thread started without report back - // their own: it leaves its starter's Stop, as on the server. - const madeOwn = - event.payload.role === "user" && - (event.payload.composer !== undefined || event.payload.sentFrom !== undefined); return { - ...(madeOwn ? withoutStopsWithParent(thread) : thread), + ...(event.payload.role === "user" ? madeOwnBy(thread, event.payload) : thread), messages, turnDiffSummaries, latestTurn, diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md index a77ae1f0f..328f22c92 100644 --- a/docs/design/lead-chat.md +++ b/docs/design/lead-chat.md @@ -189,9 +189,11 @@ always one click away, and so is every thread it started. The parent's tab and the open thread's tab are always on the row. "+N" carries an amber dot when a hidden thread needs the user. On a phone the row scrolls sideways instead and the open tab is scrolled into view. -- **Stop.** While anything a Stop on the open thread reaches is still going, the row - ends with a plain "Stop N threads" button. It counts and sends what the thread - menu's "Stop N working threads" does (`thread.children.stop`), so a lead waiting on +- **Stop.** While stopping the open thread's threads would stop anything (a thread + its Stop reaches that is still going, a child on a linked computer it has a request + open with, or a child still being set up), the row ends with a plain "Stop N + threads" button. It counts and sends what the thread menu's "Stop N working + threads" does (`thread.children.stop`), so a lead waiting on its team, which has no running turn and so no Stop in its composer, still has a brake on screen (docs/design/agent-autonomy-no-limits.md, "Stop"). The tabs take the room it leaves, and on a phone it stays put while they scroll. From 47f50bcf1265bc64ae021097a70e23cf26d0ede7 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:09:26 -0500 Subject: [PATCH 05/16] feat(server): a child's later turns report to its parent Stage 1, step 2 of docs/design/agent-autonomy-no-limits.md ("Delivery rules"). - A turn an attached child takes on its own (a check-back, a scheduled run, an automatic fix, a goal, a report from its own thread) owes its parent a report. The decision that starts it records an entry on the child's owed list; a person's message, an outside agent's, a hand-off and the parent's own request owe nothing, and a continue follows the turn it continues. - The new server-only thread.child-report.settle delivers the report as a follow-up (fromThread.followUp) to the agent that started the child, or drops it (stale epochs, separated, parent archived, wrapped by hand, or held). A drop writes thread.child-report-dropped, which is never sent on the thread stream, so older clients can still replay a thread. - Turn ends, the exit that takes a running turn with it, a failed or taken-back start, the next turn's start (sweep) and startup all settle an owed entry through one pure function, so a turn is reported once. - Stopped on purpose is the turn a Stop named; any other interrupted turn tells the parent it stopped before it finished. - A request waiting on background work settles with its answer so far when the child's next turn starts, whatever starts it. A linked computer's ledger keeps today's rule. - Late replies are gone. A thread with a parent no longer has reports from its own threads steered into a running turn; an idle thread sends the oldest message an agent queued first; a leaving agent's queued follow-up reports go to the thread's own agent; report turns continue at a reset in a thread with a parent too; a child's report doesn't push-alert. --- apps/server/src/links/LinkRequests.ts | 15 +- apps/server/src/mcp/threadTools.ts | 4 +- .../Layers/ChildThreadReactor.test.ts | 59 +++ .../Layers/ChildThreadReactor.ts | 64 ++- .../Layers/ProjectionPipeline.ts | 45 +- .../Layers/ProviderCommandReactor.test.ts | 136 ++++++ .../Layers/ProviderCommandReactor.ts | 151 ++++--- .../Layers/ProviderRuntimeIngestion.test.ts | 100 +++++ .../Layers/ProviderRuntimeIngestion.ts | 71 +++- apps/server/src/orchestration/Schemas.ts | 2 + apps/server/src/orchestration/childReports.ts | 394 ++++++++++++++++++ .../src/orchestration/childThreadDecisions.ts | 59 +-- .../orchestration/childThreadDelivery.test.ts | 195 ++++++--- .../src/orchestration/childThreadDelivery.ts | 321 ++++++++------ .../decider.childThreads.test.ts | 380 +++++++++++++++-- apps/server/src/orchestration/decider.ts | 202 ++++++--- .../orchestration/decider.turnRetry.test.ts | 7 +- apps/server/src/orchestration/projector.ts | 104 +++-- .../src/provider/agentContextBudget.json | 2 +- .../src/pushAlerts/pushAlertRules.test.ts | 11 + apps/server/src/pushAlerts/pushAlertRules.ts | 6 + apps/server/src/ws.test.ts | 38 ++ packages/contracts/src/orchestration.ts | 61 ++- packages/shared/src/childThreads.ts | 41 ++ 24 files changed, 2032 insertions(+), 436 deletions(-) create mode 100644 apps/server/src/orchestration/childReports.ts diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 94e01de50..887fa0b60 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -1917,6 +1917,7 @@ const make = Effect.gen(function* () { end: input.end, pendingMessageId: input.pendingMessageId, awaitedBackgroundTaskCount: input.child.session?.awaitedBackgroundTaskCount ?? 0, + continuesWaitingAnswer: true, }); if (delivery === null) return; const row = rows.find((entry) => entry.requestId === delivery.requestId); @@ -2306,11 +2307,17 @@ const make = Effect.gen(function* () { const childTurns = yield* turns .listByThreadId({ threadId: thread.id }) .pipe(Effect.mapError(() => peerError(`${ownLabel()} couldn't read the thread's turns.`))); - const finishedTurnId = finishedTurnAfterRestart(childTurns, { - ...request, - status: row.status === "awaiting_background" ? "awaiting_background" : "running", + const finishedTurnId = finishedTurnAfterRestart( + childTurns, + { + ...request, + status: row.status === "awaiting_background" ? "awaiting_background" : "running", + }, + { continuesWaitingAnswer: true }, + ); + const delivery = childDeliveryAfterRestart(thread, request, finishedTurnId, { + continuesWaitingAnswer: true, }); - const delivery = childDeliveryAfterRestart(thread, request, finishedTurnId); yield* settleOrFail( row, toOutcome(delivery.type === "thread.child-request.settle" ? delivery.outcome : "failed"), diff --git a/apps/server/src/mcp/threadTools.ts b/apps/server/src/mcp/threadTools.ts index 5f5253008..c12ae73d2 100644 --- a/apps/server/src/mcp/threadTools.ts +++ b/apps/server/src/mcp/threadTools.ts @@ -262,7 +262,7 @@ export const ThreadStartTool = loadedOnDemand( drivesThreads( Tool.make("thread_start", { description: - "Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. " + + "Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes and wakes you, and so does the reply ending any later turn it takes on its own (a check-back, say); with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. " + `At most ${CHILD_THREADS_PER_CALL} threads per call; make more calls for more.`, parameters: Schema.Struct({ threads: Schema.Array( @@ -345,7 +345,7 @@ export const ThreadSendTool = loadedOnDemand( drivesThreads( Tool.make("thread_send", { description: - "Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). The project's lead chat may also pass a message to an open thread in this project that it did not start (not a room, not one another thread owns, not one the user stopped): it works on it there, and nothing comes back. " + + "Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message and wakes you, like a start, and so does the reply ending any later turn it takes on its own. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). The project's lead chat may also pass a message to an open thread in this project that it did not start (not a room, not one another thread owns, not one the user stopped): it works on it there, and nothing comes back. " + "Don't poll; end your turn if you have nothing else to do.", parameters: Schema.Struct({ threadId: ThreadIdParameter, diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts index 7a0c722ff..1591ffb05 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts @@ -165,6 +165,8 @@ function withReactor<A, E>( projects: [], threads: [...harness.threads.values()].map((entry) => ({ id: entry.id, + parentThreadId: entry.parentThreadId, + attachedToParent: entry.attachedToParent, queuedFollowUps: entry.queuedFollowUps ?? [], session: entry.session, awaitedChildThreadCount: entry.childRequests.open.filter( @@ -213,6 +215,8 @@ function withReactor<A, E>( options.shareWorktrees === true ? { agentThreadsShareWorktrees: true } : {}, ), ); + // This process starts after everything the fixtures wrote. + yield* TestClock.setTime(Date.parse(now) + 60_000); return yield* Effect.gen(function* () { const reactor = yield* makeChildThreadReactor; yield* reactor.start(); @@ -294,6 +298,61 @@ describe("ChildThreadReactor", () => { ), ); + it.effect("after a restart, settles each report a child still owed, once", () => + withReactor( + [ + parentWith([]), + thread(CHILD, { + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + owedReports: [ + // Its turn completed before the crash: delivered. + { messageId: CHILD_MESSAGE, deliveryEpoch: 0, attachmentEpoch: 0, createdAt: now }, + // A check-back the restart cut off. + { + turnId: TurnId.make("child-turn-2"), + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: now, + }, + ], + }, + messages: [ + { + id: MessageId.make("answer"), + role: "assistant", + text: "Release notes checked again: nothing new.", + turnId: TurnId.make("child-turn-1"), + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }), + ], + { completedTurnFor: CHILD_MESSAGE }, + (harness) => + Effect.sync(() => { + const reports = harness.dispatched.filter( + (command) => command.type === "thread.child-report.settle", + ); + expect(reports).toMatchObject([ + { + threadId: CHILD, + owed: { messageId: CHILD_MESSAGE }, + turnId: TurnId.make("child-turn-1"), + text: "Release notes checked again: nothing new.", + }, + { + threadId: CHILD, + owed: { turnId: TurnId.make("child-turn-2") }, + text: "'Write the changelog' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.", + }, + ]); + }), + ), + ); + it.effect("resumes a setup the previous process left unfinished", () => withReactor([parentWith([request({ status: "starting" })])], {}, (harness) => Effect.gen(function* () { diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index e0094253b..3a0566dd4 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -33,9 +33,11 @@ import { familyWorkStopped } from "../threadMoveCarry.ts"; import { childDeliveryAfterRestart, childDeliveryForQuietCandidate, + childReportAfterRestart, finishedTurnAfterRestart, isHeldByContinueAtReset, isQuietCandidate, + stoppedBeforeFinishedText, } from "../childThreadDelivery.ts"; import { ChildThreadReactor, @@ -356,12 +358,18 @@ export const makeChildThreadReactor = Effect.gen(function* () { if (latestStatus !== "stopped" && latestStatus !== "error") { return; } + // Stopped on purpose only when a Stop named a turn: a runtime that + // died, or the idle reaper, is never the user's doing (rule 6). + const stoppedByStop = (child.session?.stopRequestedTurnId ?? null) !== null; for (const request of parent.childRequests.open) { if ( request.childThreadId !== childId || (request.status !== "running" && request.status !== "awaiting_background") || // Waiting to continue at a usage limit's reset: the continue answers it. - isHeldByContinueAtReset(child, request) + isHeldByContinueAtReset(child, request) || + // An answer waiting on background work whose runtime ended without + // a Stop stands as it is: the quiet check settles it answered. + (request.status === "awaiting_background" && status === "stopped" && !stoppedByStop) ) { continue; } @@ -369,10 +377,16 @@ export const makeChildThreadReactor = Effect.gen(function* () { parent, request, status === "stopped" - ? { - outcome: "stopped", - text: `The user stopped '${child.title}' before it finished.`, - } + ? stoppedByStop + ? { + outcome: "stopped", + text: `The user stopped '${child.title}' before it finished.`, + } + : { + outcome: "failed", + text: stoppedBeforeFinishedText(child.title, "its session ended"), + error: "Its session ended before it finished.", + } : { outcome: "failed", text: `'${child.title}' failed: ${child.session?.lastError ?? "its session ended with an error."}`, @@ -479,6 +493,44 @@ export const makeChildThreadReactor = Effect.gen(function* () { } }); + /** + * Reports the previous process owed and never settled (rule 14): every + * entry on every child's owed list made before this process started. A + * turn that completed is delivered, one that failed delivers its failure, + * and one the restart cut off, or that never started, says so. Turns from + * before the owed list existed have no entry and send nothing. + */ + const settleOwedReportsFromPreviousProcess = (startedAt: string) => + Effect.gen(function* () { + const shell = yield* snapshots.getShellSnapshot().pipe(Effect.orElseSucceed(() => undefined)); + for (const summary of shell?.threads ?? []) { + if (summary.parentThreadId === null || !summary.attachedToParent) continue; + const child = yield* readThread(summary.id); + const owed = (child?.childRequests.owedReports ?? []).filter( + (entry) => entry.createdAt < startedAt, + ); + if (child === undefined || owed.length === 0) continue; + const parent = yield* readThread(summary.parentThreadId); + // A parent whose move stopped its family's work is left as it is. + if (parent !== undefined && familyWorkStopped(parent)) continue; + const childTurns = yield* turns + .listByThreadId({ threadId: child.id }) + .pipe(Effect.orElseSucceed(() => [] as const)); + for (const entry of owed) { + const turn = childTurns.find((candidate) => + "turnId" in entry + ? candidate.turnId === entry.turnId + : candidate.pendingMessageId === entry.messageId && candidate.turnId !== null, + ); + const delivery = childReportAfterRestart(child, entry, turn); + yield* dispatch( + { ...delivery, threadId: child.id, createdAt: yield* nowIso }, + "settle a child's owed report after a restart", + ); + } + } + }); + /** * Reports the previous process queued for a parent but never sent: the * normal queue only sends when a turn ends, and there is no turn after a @@ -558,8 +610,10 @@ export const makeChildThreadReactor = Effect.gen(function* () { // Subscribed before the previous process's requests are settled, so the // events that settling writes are seen here too. const events = yield* engine.subscribeDomainEvents; + const startedAt = yield* nowIso; const queuedBeforeRestart = yield* reportsQueuedBeforeRestart; yield* settleFromPreviousProcess.pipe( + Effect.andThen(settleOwedReportsFromPreviousProcess(startedAt)), Effect.andThen(sendReportsQueuedBeforeRestart(queuedBeforeRestart)), Effect.catchCause((cause) => Effect.logWarning( diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 12a0a1735..e7e6e288c 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -908,6 +908,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti case "thread.child-notes-delivered": case "thread.child-deliveries-cancelled": case "thread.child-requests-reset": + case "thread.child-report-dropped": case "thread.lead-pass-recorded": case "thread.remote-child-updated": case "thread.remote-cancel-queued": @@ -945,7 +946,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ) : event.type === "thread.lead-pass-recorded" ? childRequestStateOn.leadPass(state, event.payload) - : childRequestStateOn.reset(state, event.payload); + : event.type === "thread.child-report-dropped" + ? childRequestStateOn.owedRemoved(state, event.payload.owed) + : childRequestStateOn.reset(state, event.payload); if (childRequests !== state) { yield* projectionThreadRepository.upsert({ ...existingRow.value, childRequests }); } @@ -1005,9 +1008,27 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...existingRow.value, handedBackAt: event.payload.handedBackAt, handedBackTurnId: event.payload.turnId, + // See the in-memory projector: the report it owed went up. + ...(event.payload.owedReport !== undefined + ? { + childRequests: childRequestStateOn.owedRemoved( + existingRow.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE, + event.payload.owedReport, + ), + } + : {}), } : { ...existingRow.value, + // See the in-memory projector: a moved epoch ends what it owed. + ...(existingRow.value.parentAttachmentEpoch !== event.payload.attachmentEpoch && + existingRow.value.childRequests != null + ? { + childRequests: childRequestStateOn.owedCleared( + existingRow.value.childRequests, + ), + } + : {}), attachedToParent: event.payload.attached ? 1 : 0, parentAttachmentEpoch: event.payload.attachmentEpoch, // See the in-memory projector: taken back over its link. @@ -1122,6 +1143,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ), } : {}), + // See the in-memory projector: a turn that owes its parent a report. + ...(event.payload.owesReport !== undefined + ? { + childRequests: childRequestStateOn.owedAdded( + existingRow.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE, + { + messageId: event.payload.messageId, + ...event.payload.owesReport, + createdAt: event.payload.createdAt, + }, + ), + } + : {}), }); return; } @@ -1454,6 +1488,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti yield* projectionThreadRepository.upsert({ ...existingRow.value, latestTurnId: nextLatestTurnId, + // See the in-memory projector: a provider-started turn's report. + ...(event.payload.owedReport !== undefined + ? { + childRequests: childRequestStateOn.owedAdded( + existingRow.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE, + event.payload.owedReport, + ), + } + : {}), updatedAt: event.occurredAt, }); yield* refreshThreadShellSummary(event.payload.threadId); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 76b88c720..b0731db91 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1344,6 +1344,62 @@ describe("ProviderCommandReactor", () => { expect(harness.sendTurn.mock.calls.length).toBe(0); }); + it("tells a child's parent when a turn that owed it a report could not start (rule 11)", async () => { + const harness = await createHarness(); + const dispatch = (command: OrchestrationCommand) => + Effect.runPromise(harness.engine.dispatch(command)); + const child = ThreadId.make("child-fails"); + await dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-child-fails-create"), + threadId: child, + projectId: asProjectId("project-1"), + title: "Watch CI", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + parentThreadId: ThreadId.make("thread-1"), + attachedToParent: true, + createdAt: "2026-01-01T00:00:00.000Z", + }); + harness.startSession.mockImplementationOnce(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: "codex", + method: "thread.turn.start", + detail: "spawn failed in test harness", + }), + ), + ); + // A turn nobody asked for (an automatic fix): it owes its parent a report. + await dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-child-fails-turn"), + threadId: child, + message: { + messageId: asMessageId("child-fails-message"), + role: "user", + text: "CI failed; fix it.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }); + const report = async () => + (await harness.readModel()).threads + .find((entry) => entry.id === ThreadId.make("thread-1")) + ?.messages.find((message) => message.fromThread?.followUp === true); + await waitFor(async () => (await report()) !== undefined); + expect((await report())?.text).toBe( + "'Watch CI' could not start its turn: spawn failed in test harness. Send it a message with thread_send to continue.", + ); + const childThread = (await harness.readModel()).threads.find((entry) => entry.id === child); + expect(childThread?.childRequests.owedReports).toBeUndefined(); + }); + it("hides a saved key in a provider's failure text before storing it", async () => { const secretScrubber = makeSecretScrubber(); secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); @@ -6559,6 +6615,86 @@ describe("ProviderCommandReactor", () => { expect(thread?.queuedFollowUps ?? []).toEqual([]); }); + it("after a failed turn, sends the oldest message an agent queued when a newer one arrives (sequence 7)", async () => { + const harness = await createHarness({ + remoteRequestGate: { messageVerdict: () => Effect.succeed("run") }, + }); + const remoteThread = ThreadId.make("remote-thread-failed"); + const origin = { + linkDeviceId: "device-windows", + environmentId: EnvironmentId.make("env-windows"), + environmentLabel: "Windows PC", + threadId: ThreadId.make("windows-parent"), + threadTitle: "Ship the release", + }; + const dispatch = (command: OrchestrationCommand) => + Effect.runPromise(harness.engine.dispatch(command)); + await dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-failed-thread-create"), + threadId: remoteThread, + projectId: asProjectId("project-1"), + title: "Write the changelog", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + remoteOrigin: origin, + createdAt: "2026-01-01T00:00:00.000Z", + }); + const setSession = (status: "running" | "error", at: string) => + dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-failed-session-${status}-${at}`), + threadId: remoteThread, + session: { + threadId: remoteThread, + status, + providerName: "codex", + providerInstanceId: ProviderInstanceId.make("codex"), + runtimeMode: "approval-required", + activeTurnId: status === "running" ? asTurnId("turn-failing") : null, + pendingBackgroundTaskCount: 0, + lastError: status === "error" ? "Overloaded" : null, + updatedAt: at, + }, + createdAt: at, + }); + const queue = (messageId: MessageId, at: string) => + dispatch({ + type: "thread.remote-request.queue", + commandId: CommandId.make(`cmd-failed-queue-${messageId}`), + threadId: remoteThread, + messageId, + text: `message ${messageId}`, + fromThread: { + threadId: origin.threadId, + requestId: ChildRequestId.make(`request-${messageId}`), + kind: "request", + environmentId: origin.environmentId, + }, + createdAt: at, + }); + await setSession("running", "2026-01-01T00:00:01.000Z"); + await queue(asMessageId("waited-first"), "2026-01-01T00:00:02.000Z"); + await harness.drain(); + await queue(asMessageId("waited-second"), "2026-01-01T00:00:03.000Z"); + await harness.drain(); + // The turn fails: the queue isn't sent on by itself. + await setSession("error", "2026-01-01T00:00:04.000Z"); + await harness.drain(); + expect(harness.sendTurn).not.toHaveBeenCalled(); + + // A retry arrives: the message that waited longest goes first. + await queue(asMessageId("retry"), "2026-01-01T00:00:05.000Z"); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ + threadId: remoteThread, + messageId: asMessageId("waited-first"), + }); + }); + it("holds a linked computer's queued message while its record can't be read, then sends it", async () => { const messageId = asMessageId("remote-held"); const verdicts: Array<"run" | "unknown"> = ["unknown"]; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 9ec25d344..59ace63ec 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -54,6 +54,7 @@ import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/proje import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings"; import { isAttachedChild, + isOwedReport, notesFor, remoteChildOf, withinModeCeiling, @@ -165,13 +166,7 @@ import { GitWorkflowService } from "../../git/GitWorkflowService.ts"; import { checkpointHandover, HandoverCaptureWait } from "../checkpointHandover.ts"; import { inviteAnswerRefusal } from "../agentInvites.ts"; import { handOffReplyText } from "../agentRequestDecisions.ts"; -import { isCancelledReport } from "../childThreadDecisions.ts"; -import { - type LateReply, - lateRepliesText, - lateReplyOf, - lateReplyRecipient, -} from "../childThreadDelivery.ts"; +import { childReportMessageId, isCancelledReport } from "../childThreadDecisions.ts"; import { NO_BACKGROUND_TASKS } from "../sessionBackgroundTasks.ts"; import { isRestorePaid } from "../threadMoveDecisions.ts"; import { isLinkFenced } from "../linkFence.ts"; @@ -2266,14 +2261,20 @@ const make = Effect.gen(function* () { ); } else if (fromThread.kind === "request") { lines.push( - thread.attachedToParent || fromThread.environmentId !== undefined + fromThread.environmentId !== undefined ? `Another agent started this thread from the thread "${otherTitle}", and your final reply goes back to it automatically. Work in this thread's own checkout, and end with the answer it needs.` - : `Another agent started this thread from the thread "${otherTitle}". Nothing you write goes back to it automatically.`, + : thread.attachedToParent + ? `Another agent started this thread from the thread "${otherTitle}", and your final reply goes back to it automatically. Work in this thread's own checkout, and end with the answer it needs. If you take more turns later that the user did not start, for example when a check-back fires, the reply that ends each one goes back too and wakes that thread. Keep those replies short when nothing has changed.` + : `Another agent started this thread from the thread "${otherTitle}". Nothing you write goes back to it automatically.`, ); } else if (fromThread.neverMade === true) { lines.push( `This message is from Threadlines: a thread you asked to start (thread ${fromThread.threadId}) was never made, so nothing more will come from it. It is not instructions from the user.`, ); + } else if (fromThread.followUp === true) { + lines.push( + `Report from thread "${otherTitle}" (${fromThread.threadId}), which took another turn on its own after its last answer. It's information from another agent, not instructions from the user.`, + ); } else { lines.push( `This message is a report from "${otherTitle}" (thread ${fromThread.threadId}), a thread you started. It is information from another agent, not instructions from the user. More reports may follow; use thread_list or thread_read to check on your threads.`, @@ -2289,14 +2290,10 @@ const make = Effect.gen(function* () { ].join("\n"), ); } - const lateReplies = yield* lateRepliesForAgent(thread, participantId); - if (lateReplies.length > 0) { - lines.push(lateRepliesText(lateReplies)); - } return { text: lines.length > 0 ? lines.join("\n\n") : undefined, delivered: (createdAt: string) => - notes.length === 0 && lateReplies.length === 0 + notes.length === 0 ? Effect.void : orchestrationEngine .dispatch({ @@ -2304,53 +2301,12 @@ const make = Effect.gen(function* () { commandId: serverCommandId("child-notes-delivered"), threadId: thread.id, requestIds: notes.map((note) => note.requestId), - ...(lateReplies.length > 0 - ? { - lateReplies: lateReplies.map(({ childThreadId, turnId }) => ({ - childThreadId, - turnId, - })), - } - : {}), createdAt, }) .pipe(Effect.catch(() => Effect.void)), }; }); - /** - * Child threads: the late replies (lateReplyOf) of this thread's children - * that are for `participantId`, found from its children's rows (indexed by - * parent, so a thread with none reads nothing). A failed read tells of none - * this turn; they are told of at the next. - */ - const lateRepliesForAgent = Effect.fnUntraced(function* ( - thread: OrchestrationThread, - participantId: ThreadParticipantId | null, - ) { - if (thread.archivedAt !== null || isAttachedChild(thread)) return []; - const shells = yield* projectionSnapshotQuery - .listThreadShells({ parentThreadId: thread.id }) - .pipe(Effect.orElseSucceed(() => [])); - const candidates = shells.filter( - (shell) => - shell.parentThreadId === thread.id && - shell.attachedToParent && - shell.handedBackTurnId !== null && - shell.latestTurn !== null && - shell.latestTurn.turnId !== shell.handedBackTurnId && - shell.latestTurn.state === "completed" && - lateReplyRecipient(thread, shell) === participantId, - ); - const replies: LateReply[] = []; - for (const shell of candidates) { - const child = yield* resolveThread(shell.id).pipe(Effect.orElseSucceed(() => undefined)); - const reply = child === undefined ? null : lateReplyOf(thread, child); - if (reply !== null) replies.push(reply); - } - return replies; - }); - /** * The lead chat's role (docs/design/lead-chat.md, "Role text"): added to * every turn that starts in a project's lead, whatever started it, and to @@ -3400,6 +3356,72 @@ const make = Effect.gen(function* () { }); }).pipe(Effect.ignoreCause({ log: true })); + /** + * Child threads: a turn that never started settles what its message owed + * its parent (docs/design/agent-autonomy-no-limits.md, rule 11). With + * `detail`, the start failed: a parent's request settles failed and an + * owed report delivers the failure. Without, the start was taken back on + * purpose (Stop, a report gone stale): the owed report goes with nothing + * sent, and a request is settled by whatever took it back. + */ + const settleChildWorkForUnstartedTurn = (detail: string | null) => + Effect.gen(function* () { + const latest = yield* resolveThread(event.payload.threadId); + if (latest === undefined || latest.parentThreadId === null) { + return; + } + const messageId = event.payload.messageId; + const failure = + detail === null + ? undefined + : `'${latest.title}' could not start its turn: ${detail.replace(/\.$/, "")}.`; + if ( + (latest.childRequests.owedReports ?? []).some((entry) => + isOwedReport(entry, { messageId }), + ) + ) { + yield* orchestrationEngine.dispatch({ + type: "thread.child-report.settle", + commandId: serverCommandId("child-report-unstarted"), + threadId: latest.id, + owed: { messageId }, + turnId: null, + ...(failure !== undefined + ? { text: `${failure} Send it a message with thread_send to continue.` } + : {}), + createdAt: yield* nowIso, + }); + } + if (failure === undefined || detail === null) { + return; + } + const parent = yield* resolveThread(latest.parentThreadId); + const request = parent?.childRequests.open.find( + (entry) => + entry.childThreadId === latest.id && + entry.remote === undefined && + entry.status === "running" && + entry.childMessageId === messageId, + ); + if (parent === undefined || request === undefined) { + return; + } + yield* orchestrationEngine.dispatch({ + type: "thread.child-request.settle", + commandId: serverCommandId("child-request-start-failed"), + threadId: parent.id, + requestId: request.requestId, + outcome: "failed", + reply: { + messageId: childReportMessageId(request.requestId), + text: failure, + turnId: null, + }, + error: detail, + createdAt: yield* nowIso, + }); + }).pipe(Effect.ignoreCause({ log: true })); + // A message no one can send again never reached the agent: a lead // chat's pass, or an outside agent's message. The decider marks it so no // history carries it (and a pass's lead hears); anything else it leaves. @@ -3435,6 +3457,7 @@ const make = Effect.gen(function* () { return mark.pipe( Effect.andThen(handleTurnStartFailure(cause)), Effect.andThen(failHandOffForFailedStart(detail)), + Effect.andThen(settleChildWorkForUnstartedTurn(detail)), ); }; @@ -3548,6 +3571,7 @@ const make = Effect.gen(function* () { }), ), ); + yield* settleChildWorkForUnstartedTurn(null); yield* Effect.logInfo("continue not sent: the user wrote first", { threadId: event.payload.threadId, messageId: event.payload.messageId, @@ -3579,6 +3603,7 @@ const make = Effect.gen(function* () { createdAt: yield* nowIso, }); } + yield* settleChildWorkForUnstartedTurn(null); }); /** @@ -5528,6 +5553,13 @@ const make = Effect.gen(function* () { if (!isReply && queued.fromThread?.kind !== "report") { return; } + // A thread that reports to a parent reads each report from its own + // threads in a turn of its own, which reports in turn: steered into a + // running turn, it could be swallowed by the user's turn or a request's + // answer (docs/design/agent-autonomy-no-limits.md, rule 9). + if (!isReply && isAttachedChild(thread) && (thread.remoteOrigin ?? null) === null) { + return; + } // Only one that came while this turn ran: one left from before it (its // steer missed the last turn's end) keeps its place in the chat and goes // as a turn of its own after this one, as before. @@ -6073,7 +6105,14 @@ const make = Effect.gen(function* () { ) { return; } - const next = event.payload.followUp; + // In an idle thread, agents' messages run in the order they arrived: one + // that waited behind a failed turn goes before the newer one that woke + // the queue (docs/design/agent-autonomy-no-limits.md, rule 10). + const next = + fromUser || waitsForMove + ? event.payload.followUp + : ((thread.queuedFollowUps ?? []).find((entry) => isAgentOrigin(entry)) ?? + event.payload.followUp); if (yield* releaseSlotForQueuedAgent(thread, next)) { releasedMessageByThread.set(thread.id, next.messageId); return; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 150266202..5e37be992 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -1383,6 +1383,106 @@ describe("ProviderRuntimeIngestion", () => { expect(await cancelsSoFar()).toBe(cancelsAtStop + 1); }); + it("reports a child's check-back to its parent, and settles one its exiting runtime took with it once (sequence 6)", async () => { + const harness = await createHarness(); + const createdAt = "2026-01-01T00:00:00.000Z"; + const child = asThreadId("child-1"); + // thread-1 is the parent; child-1 reports to it. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-child-create"), + threadId: child, + projectId: asProjectId("project-1"), + title: "Watch CI", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + parentThreadId: asThreadId("thread-1"), + attachedToParent: true, + createdAt, + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-child-session-seed"), + threadId: child, + session: { + threadId: child, + status: "ready", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }), + ); + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "ready", + runtimeMode: "approval-required", + threadId: child, + createdAt, + updatedAt: createdAt, + }); + const event = (type: string, id: string, extra: Record<string, unknown> = {}) => + ({ + type, + eventId: asEventId(id), + provider: ProviderDriverKind.make("codex"), + threadId: child, + createdAt: "2026-01-01T00:00:01.000Z", + ...extra, + }) as never; + const reportsIn = async () => + (await harness.readModel()).threads + .find((entry) => entry.id === asThreadId("thread-1")) + ?.messages.filter((message) => message.fromThread?.followUp === true) ?? []; + + // A check-back fires: the provider starts a turn with no message. + harness.emit( + event("turn.started", "evt-child-check-back", { + turnId: asTurnId("child-turn-1"), + payload: { trigger: { kind: "check-back" } }, + }), + ); + await harness.drain(); + let childThread = await waitForThread( + harness.readModel, + (entry) => (entry.childRequests.owedReports ?? []).length === 1, + 10_000, + child, + ); + expect(childThread.childRequests.owedReports).toMatchObject([{ turnId: "child-turn-1" }]); + + // Codex exits with only session.exited: the exit's handler settles it. + harness.emit( + event("session.exited", "evt-child-exited", { + payload: { reason: "Codex app-server exited", exitKind: "error" }, + }), + ); + await harness.drain(); + childThread = await waitForThread( + harness.readModel, + (entry) => entry.childRequests.owedReports === undefined, + 10_000, + child, + ); + expect((await reportsIn()).map((message) => message.text)).toEqual([ + "'Watch CI' stopped before it finished: Codex app-server exited. Send it a message with thread_send to continue.", + ]); + + // The next turn starts: nothing is left to settle, so nothing goes twice. + harness.emit(event("turn.started", "evt-child-next", { turnId: asTurnId("child-turn-2") })); + await harness.drain(); + expect(await reportsIn()).toHaveLength(1); + }); + it("maps turn started/completed events into thread session updates", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 2fa3744ce..ad7162e6e 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -81,7 +81,7 @@ import { type ProviderActivityStreamSnapshot, } from "./ProviderActivityProjection.ts"; import { handOffReplyText } from "../agentRequestDecisions.ts"; -import { childDeliveryForTurnEnd } from "../childThreadDelivery.ts"; +import { childDeliveryForEndedTurn } from "../childThreadDelivery.ts"; import { RemoteRequestTurnEnds } from "../Services/RemoteRequestTurnEnds.ts"; import { ScheduledRunTurnEnds } from "../Services/ScheduledRunTurnEnds.ts"; import { RealtimeVoiceDevices } from "../Services/RealtimeVoiceDevices.ts"; @@ -2759,13 +2759,15 @@ const make = Effect.gen(function* () { }); /** - * Child threads: a child's turn ended and its words were just flushed. If - * that turn answers a request its parent's agent made (the request's message - * started it, or it is the follow-up its own background work started), the - * answer goes back in one decider step that settles the request, writes the - * report into the parent and queues it for the agent that asked. With - * background work still owed, the answer waits for it. Never on the session - * going idle, which comes before buffered text is final. + * Child threads: a child's turn ended and its words were just flushed (or + * its runtime exited with the turn). If that turn answers a request its + * parent's agent made (the request's message started it), the answer goes + * back in one decider step that settles the request, writes the report into + * the parent and queues it for the agent that asked; with background work + * still owed, the answer waits for it. If the turn owed its parent a report + * (docs/design/agent-autonomy-no-limits.md, rule 2), that report is settled + * the same way. Never on the session going idle, which comes before + * buffered text is final. */ const routeChildReport = Effect.fn("routeChildReport")(function* (input: { readonly threadId: ThreadId; @@ -2808,7 +2810,7 @@ const make = Effect.gen(function* () { : parent.childRequests.open.filter( (request) => request.childThreadId === child.id && request.remote === undefined, ); - if (parent === undefined || parent === null || owned.length === 0) { + if (owned.length === 0 && (child.childRequests.owedReports ?? []).length === 0) { return; } const turn = yield* projectionTurnRepository @@ -2817,7 +2819,7 @@ const make = Effect.gen(function* () { Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), ); - const delivery = childDeliveryForTurnEnd({ + const delivery = childDeliveryForEndedTurn({ owned, child, end: { turnId: input.turnId, outcome: input.outcome, error: input.error }, @@ -2828,12 +2830,16 @@ const make = Effect.gen(function* () { return; } yield* orchestrationEngine - .dispatch({ ...delivery, threadId: parent.id, createdAt: input.createdAt }) + .dispatch( + delivery.type === "thread.child-report.settle" + ? { ...delivery, threadId: child.id, createdAt: input.createdAt } + : { ...delivery, threadId: child.parentThreadId, createdAt: input.createdAt }, + ) .pipe( Effect.catch((error) => Effect.logInfo("provider runtime ingestion could not deliver a child thread's answer", { threadId: input.threadId, - requestId: delivery.requestId, + turnId: input.turnId, detail: String(error), }), ), @@ -3399,6 +3405,29 @@ const make = Effect.gen(function* () { } } + // A turn that starts now: the message it was asked with, or none (the + // provider started it: a check-back, a goal, background work that + // finished), so the decision knows what it owes a parent (rules 2, 3). + const turnStartFields = (nextActiveTurnId: TurnId | null) => + Effect.gen(function* () { + if ( + event.type !== "turn.started" || + nextActiveTurnId === null || + (activeTurnId !== null && sameId(activeTurnId, nextActiveTurnId)) + ) { + return {}; + } + const pending = + thread.session?.status === "starting" + ? yield* projectionTurnRepository + .getPendingTurnStartByThreadId({ threadId: thread.id }) + .pipe(Effect.orElseSucceed(() => Option.none())) + : Option.none(); + return Option.isSome(pending) + ? { turnMessageId: pending.value.messageId } + : { providerStartedTurn: true as const }; + }); + const conflictsWithActiveTurn = activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; @@ -3638,6 +3667,7 @@ const make = Effect.gen(function* () { threadId: thread.id, session, ...usageLimitFields, + ...(yield* turnStartFields(nextActiveTurnId)), createdAt: now, }); yield* Ref.update(unstoredSessionReportAt, (reports) => { @@ -4230,6 +4260,23 @@ const make = Effect.gen(function* () { }); } yield* clearTurnStateForSession(thread.id); + // A runtime that exits mid-turn takes the turn with it, and may never + // end it: its end goes to the child's parent here, before the next + // event can start a new session (docs/design/agent-autonomy-no-limits.md, + // rule 6). A turn whose message is sent again on a new runtime goes on. + if ( + activeTurnId !== null && + shouldApplyThreadLifecycle && + event.payload.resendTurn === undefined + ) { + yield* routeChildReport({ + threadId: thread.id, + turnId: activeTurnId, + outcome: "interrupted", + error: event.payload.reason ?? "its session exited", + createdAt: now, + }); + } } if (event.type === "session.exited" && event.payload.resendTurn !== undefined) { diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index ac32fe97b..c6ed24745 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -30,6 +30,7 @@ import { ThreadChildNotesDeliveredPayload as ContractsThreadChildNotesDeliveredPayloadSchema, ThreadChildDeliveriesCancelledPayload as ContractsThreadChildDeliveriesCancelledPayloadSchema, ThreadChildRequestsResetPayload as ContractsThreadChildRequestsResetPayloadSchema, + ThreadChildReportDroppedPayload as ContractsThreadChildReportDroppedPayloadSchema, ThreadLeadPassRecordedPayload as ContractsThreadLeadPassRecordedPayloadSchema, ThreadHandedBackPayload as ContractsThreadHandedBackPayloadSchema, ThreadRemoteCancelQueuedPayload as ContractsThreadRemoteCancelQueuedPayloadSchema, @@ -131,6 +132,7 @@ export const ThreadChildNotesDeliveredPayload = ContractsThreadChildNotesDeliver export const ThreadChildDeliveriesCancelledPayload = ContractsThreadChildDeliveriesCancelledPayloadSchema; export const ThreadChildRequestsResetPayload = ContractsThreadChildRequestsResetPayloadSchema; +export const ThreadChildReportDroppedPayload = ContractsThreadChildReportDroppedPayloadSchema; export const ThreadLeadPassRecordedPayload = ContractsThreadLeadPassRecordedPayloadSchema; export const ThreadHandedBackPayload = ContractsThreadHandedBackPayloadSchema; export const ThreadRemoteChildUpdatedPayload = ContractsThreadRemoteChildUpdatedPayloadSchema; diff --git a/apps/server/src/orchestration/childReports.ts b/apps/server/src/orchestration/childReports.ts new file mode 100644 index 000000000..269eff87f --- /dev/null +++ b/apps/server/src/orchestration/childReports.ts @@ -0,0 +1,394 @@ +/** + * Child threads: the reports a child owes its parent for turns it takes on + * its own after its answer went back (docs/design/agent-autonomy-no-limits.md, + * Part 2, "Delivery rules"). The decision that starts such a turn records an + * entry on the child's owed list; the decision that settles the turn writes + * the report into the parent, or drops it, and removes the entry. Each + * function returns the events to plan, or a refusal. + */ +import { + ChildRequestId, + type OrchestrationMessage, + type OrchestrationReadModel, + type OrchestrationThread, + type OwedChildReport, + type OwedReportKey, + type OwedReportStamps, + type ThreadMessageOrigin, + type ThreadParticipantId, + type TurnId, +} from "@threadlines/contracts"; +import { isOwedReport, owedReportKeyOf } from "@threadlines/shared/childThreads"; +import { activeParticipants } from "@threadlines/shared/threadParticipants"; + +import { + type ChildEventBase, + type ChildThreadDecision, + childReportMessageId, + decideChildRequestSettle, + personWrote, +} from "./childThreadDecisions.ts"; +import { + childDeliveryForQuietCandidate, + stoppedBeforeFinishedText, +} from "./childThreadDelivery.ts"; +import { currentAgentModel, messageAgentModels } from "./messageAgentModels.ts"; + +type PlannedEvent = Extract<ChildThreadDecision, ReadonlyArray<unknown>>[number]; + +const findThread = (readModel: OrchestrationReadModel, threadId: string) => + readModel.threads.find((thread) => thread.id === threadId && thread.deletedAt === null) ?? null; + +/** The parent a child on this computer reports to, while it is attached to it here. */ +function reportingParent( + readModel: OrchestrationReadModel, + child: OrchestrationThread, +): OrchestrationThread | null { + if ( + child.deletedAt !== null || + child.parentThreadId === null || + !child.attachedToParent || + (child.remoteOrigin ?? null) !== null + ) { + return null; + } + return findThread(readModel, child.parentThreadId); +} + +/** + * The epochs a report from `child` would be delivered under now, or null when + * the child reports to nobody here (no parent, separated, started over a link). + */ +export function owedReportStamps( + readModel: OrchestrationReadModel, + child: OrchestrationThread, +): OwedReportStamps | null { + const parent = reportingParent(readModel, child); + return parent === null + ? null + : { + deliveryEpoch: parent.childRequests.deliveryEpoch, + attachmentEpoch: child.parentAttachmentEpoch, + }; +} + +/** What a turn's starting message says about who started it. */ +export interface TurnStartOrigin { + readonly fromThread?: ThreadMessageOrigin | undefined; + readonly fromOutside?: unknown; + readonly composer?: unknown; + readonly sentFrom?: unknown; + readonly trigger?: string | undefined; + readonly requestKind?: OrchestrationMessage["requestKind"]; +} + +/** Whether a message's own turn answers someone other than the thread's parent (rule 2). */ +function answersSomeoneElse(origin: TurnStartOrigin): boolean { + return ( + origin.fromThread?.kind === "request" || + personWrote(origin) || + origin.fromOutside !== undefined || + // A hand-off's reply goes back to the agent that handed off. + origin.requestKind === "hand_off" + ); +} + +/** + * Whether a turn started by a message owes `child`'s parent a report (rule 2), + * and under which epochs. Read from the message that starts it, never from + * what is open when it ends. A continue (`trigger`) is judged by the turn it + * continues (`continued`, the newest message that is not a continue itself), + * and answers the request the same decision moves onto it + * (`continueAnswersRequest`). + */ +export function turnStartOwesReport( + readModel: OrchestrationReadModel, + child: OrchestrationThread, + start: TurnStartOrigin, + continued: { + readonly origin: TurnStartOrigin | undefined; + readonly answersRequest: boolean; + }, +): OwedReportStamps | undefined { + const stamps = owedReportStamps(readModel, child); + if (stamps === null) return undefined; + if (start.trigger !== undefined) { + if (continued.answersRequest) return undefined; + const origin = continued.origin; + // A continue of a turn a request started reports: that request was + // settled when the turn stopped, unless it was moved onto this one. + if (origin !== undefined && origin.fromThread?.kind !== "request" && answersSomeoneElse(origin)) + return undefined; + return stamps; + } + return answersSomeoneElse(start) ? undefined : stamps; +} + +/** + * The message a continue continues: the newest message that started a turn + * for `participantId` before it, skipping continues, messages still queued + * and the continue's own message. + */ +export function continuedTurnMessage( + thread: OrchestrationThread, + participantId: ThreadParticipantId | null, + continueMessageId: string, +): OrchestrationMessage | undefined { + const queued = new Set((thread.queuedFollowUps ?? []).map((entry) => entry.messageId)); + return thread.messages.findLast( + (message) => + message.role === "user" && + message.id !== continueMessageId && + message.sideTurnId === undefined && + message.trigger === undefined && + !queued.has(message.id) && + (message.participantId ?? null) === participantId, + ); +} + +/** + * Whether the user wrapped a thread up by hand and it still stands: its done + * override says done and is newer than its newest turn, the test the sidebar + * files by. Reopening it, or a newer turn, lets reports through again. + */ +export function isWrappedByHand(thread: OrchestrationThread): boolean { + const override = thread.doneOverride; + if (override === null || override.state !== "done") return false; + const turn = thread.latestTurn; + const lastTurnAt = + turn === null ? null : (turn.completedAt ?? turn.startedAt ?? turn.requestedAt); + return lastTurnAt === null || Date.parse(override.at) >= Date.parse(lastTurnAt); +} + +/** + * Why a report owed under `entry` can't be delivered now (rule 7), or null. + * A dropped report stays dropped. + */ +export function reportDropReason( + readModel: OrchestrationReadModel, + child: OrchestrationThread, + entry: OwedChildReport, +): string | null { + const parent = reportingParent(readModel, child); + if (parent === null) return "The child is no longer in its parent's family."; + if ( + entry.deliveryEpoch !== parent.childRequests.deliveryEpoch || + entry.attachmentEpoch !== child.parentAttachmentEpoch + ) { + return "Its delivery was cancelled since the turn started."; + } + if (parent.archivedAt !== null) return "The parent is archived."; + if (isWrappedByHand(parent)) return "The parent is wrapped up."; + if (parent.agentRequests.hold || child.agentRequests.hold) return "The user stopped one of them."; + return null; +} + +/** + * The agent of `parent` a child's later reports go to: the one its first + * answer went to, which is the agent that started it, or the one whose turn + * started it; while that agent is still in the room. Otherwise the thread's own. + */ +export function reportRecipient( + parent: OrchestrationThread, + child: Pick<OrchestrationThread, "id" | "parentTurnId">, +): ThreadParticipantId | null { + const firstReport = parent.messages.find( + (message) => + message.fromThread?.kind === "report" && + message.fromThread.threadId === child.id && + message.fromThread.environmentId === undefined, + ); + const starter = + firstReport === undefined && child.parentTurnId !== null + ? parent.messages.find( + (message) => message.role === "assistant" && message.turnId === child.parentTurnId, + ) + : undefined; + const participantId = (firstReport ?? starter)?.participantId ?? null; + return participantId !== null && + activeParticipants(parent).some((participant) => participant.id === participantId) + ? participantId + : null; +} + +/** The request id a follow-up report carries, derived from the child and its turn. */ +export const followUpReportRequestId = ( + child: Pick<OrchestrationThread, "id">, + turnId: TurnId | null, + key: OwedReportKey, +) => + ChildRequestId.make( + `report:${child.id}:${turnId ?? ("messageId" in key ? key.messageId : key.turnId)}`, + ); + +/** + * A turn `child` owed its parent a report for is over + * (`thread.child-report.settle`): with `text`, the report is written into the + * parent and queued for the agent that started the child, and the child is + * stamped handed back as of that turn; otherwise, or when rule 7 says no, it + * is dropped. Either way its entry goes, so a turn is reported once. + */ +export function decideChildReportSettle( + readModel: OrchestrationReadModel, + child: OrchestrationThread, + input: { + readonly owed: OwedReportKey; + readonly turnId: TurnId | null; + readonly text?: string | undefined; + }, + baseFor: ChildEventBase, + createdAt: string, +): ChildThreadDecision { + const entry = (child.childRequests.owedReports ?? []).find((listed) => + isOwedReport(listed, input.owed), + ); + if (entry === undefined) { + return { refusal: "That report was already settled." }; + } + const key = owedReportKeyOf(entry); + const dropped: PlannedEvent = { + ...baseFor(child.id), + type: "thread.child-report-dropped", + payload: { threadId: child.id, owed: key, turnId: input.turnId, createdAt }, + }; + const parent = reportingParent(readModel, child); + const text = input.text?.trim(); + if ( + parent === null || + text === undefined || + text.length === 0 || + reportDropReason(readModel, child, entry) !== null + ) { + return [dropped]; + } + const requestId = followUpReportRequestId(child, input.turnId, key); + const messageId = childReportMessageId(requestId); + if (parent.messages.some((message) => message.id === messageId)) { + return [dropped]; + } + const fromThread = { + threadId: child.id, + requestId, + kind: "report" as const, + followUp: true as const, + deliveryEpoch: parent.childRequests.deliveryEpoch, + attachmentEpoch: child.parentAttachmentEpoch, + }; + const participantId = reportRecipient(parent, child); + return [ + { + ...baseFor(parent.id), + type: "thread.message-sent", + payload: { + threadId: parent.id, + messageId, + role: "user", + text, + attachments: [], + participantId, + fromThread, + agentModels: messageAgentModels(parent, [ + { participantId, modelSelection: currentAgentModel(parent, participantId) }, + ]), + turnId: null, + streaming: false, + createdAt, + updatedAt: createdAt, + }, + }, + { + ...baseFor(parent.id), + type: "thread.follow-up-queued", + payload: { + threadId: parent.id, + followUp: { + messageId, + text, + attachments: [], + ...(participantId !== null ? { participantId } : {}), + fromThread, + runtimeMode: parent.runtimeMode, + interactionMode: parent.interactionMode, + createdAt, + }, + }, + }, + { + ...baseFor(child.id), + type: "thread.handed-back", + payload: { + threadId: child.id, + turnId: input.turnId, + handedBackAt: createdAt, + owedReport: key, + }, + }, + ]; +} + +/** + * A turn is starting in `child`, so every earlier turn is over: each entry + * still owed for one (anything `keep` doesn't name) is settled first, as a + * turn that ended without being stopped (rule 3). Nothing leaves an entry + * behind for good. + */ +export function sweepOwedReports( + readModel: OrchestrationReadModel, + child: OrchestrationThread, + keep: (entry: OwedChildReport) => boolean, + baseFor: ChildEventBase, + createdAt: string, +): ReadonlyArray<PlannedEvent> { + return (child.childRequests.owedReports ?? []) + .filter((entry) => !keep(entry)) + .flatMap((entry) => { + const decision = decideChildReportSettle( + readModel, + child, + { + owed: owedReportKeyOf(entry), + turnId: "turnId" in entry ? entry.turnId : null, + text: stoppedBeforeFinishedText( + child.title, + "its turn ended without its reply reaching Threadlines", + ), + }, + baseFor, + createdAt, + ); + return "refusal" in decision ? [] : decision; + }); +} + +/** + * A turn is starting in `child`, whatever starts it: a parent's request still + * waiting on the child's background work settles now with its answer so far + * (rule 4). No later turn is taken for that work coming back. + */ +export function settleWaitingAnswer( + readModel: OrchestrationReadModel, + child: OrchestrationThread, + baseFor: ChildEventBase, + createdAt: string, +): ReadonlyArray<PlannedEvent> { + const parent = reportingParent(readModel, child); + if (parent === null) return []; + return parent.childRequests.open + .filter( + (request) => + request.childThreadId === child.id && + request.remote === undefined && + request.status === "awaiting_background", + ) + .flatMap((request) => { + const delivery = childDeliveryForQuietCandidate(child, request); + if (delivery === null || delivery.type !== "thread.child-request.settle") return []; + const decision = decideChildRequestSettle( + readModel, + parent, + { ...delivery, threadId: parent.id, createdAt }, + baseFor, + ); + return "refusal" in decision ? [] : decision; + }); +} diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 6b87de6cf..11285b250 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -1333,60 +1333,27 @@ export function decideRemoteRequestQueue( ]; } -/** - * Notes went out with an agent's turn (`thread.child-notes.delivered`), and - * with them children's late replies (lateReplyOf): each child whose newest - * turn is still the one told of is recorded as handed back as of it, so it - * wraps itself. One that moved on since (a newer turn, or it left the family) - * is left as it is and is told of again when it qualifies. - */ +/** Notes went out with an agent's turn (`thread.child-notes.delivered`). */ export function decideChildNotesDelivered( - readModel: OrchestrationReadModel, parent: OrchestrationThread, command: CommandOf<"thread.child-notes.delivered">, baseFor: ChildEventBase, ): ChildThreadDecision { - const notesDelivered = parent.childRequests.pendingNotes.some((note) => - command.requestIds.includes(note.requestId), - ); - const handedBack = (command.lateReplies ?? []).flatMap((reply): ReadonlyArray<PlannedEvent> => { - const child = findThread(readModel, reply.childThreadId); - if ( - child === null || - child.parentThreadId !== parent.id || - !child.attachedToParent || - child.latestTurn?.turnId !== reply.turnId || - child.latestTurn.state === "running" || - child.handedBackTurnId === reply.turnId - ) { - return []; - } - return [ - { - ...baseFor(child.id), - type: "thread.handed-back", - payload: { threadId: child.id, turnId: reply.turnId, handedBackAt: command.createdAt }, - }, - ]; - }); - if (!notesDelivered && handedBack.length === 0) { + if ( + !parent.childRequests.pendingNotes.some((note) => command.requestIds.includes(note.requestId)) + ) { return refuse("Those notes were already delivered."); } return [ - ...(notesDelivered - ? [ - { - ...baseFor(parent.id), - type: "thread.child-notes-delivered" as const, - payload: { - threadId: parent.id, - requestIds: command.requestIds, - createdAt: command.createdAt, - }, - }, - ] - : []), - ...handedBack, + { + ...baseFor(parent.id), + type: "thread.child-notes-delivered", + payload: { + threadId: parent.id, + requestIds: command.requestIds, + createdAt: command.createdAt, + }, + }, ]; } diff --git a/apps/server/src/orchestration/childThreadDelivery.test.ts b/apps/server/src/orchestration/childThreadDelivery.test.ts index ffa4c995b..a5c7aa698 100644 --- a/apps/server/src/orchestration/childThreadDelivery.test.ts +++ b/apps/server/src/orchestration/childThreadDelivery.test.ts @@ -14,7 +14,11 @@ import { } from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { childDeliveryForTurnEnd, lateReplyOf } from "./childThreadDelivery.ts"; +import { + childDeliveryForEndedTurn, + childDeliveryForTurnEnd, + childReportForTurnEnd, +} from "./childThreadDelivery.ts"; const now = "2026-10-04T10:00:00.000Z"; const PARENT = ThreadId.make("parent"); @@ -102,93 +106,170 @@ describe("childDeliveryForTurnEnd", () => { expect(delivery?.requestId).toBe(later.requestId); }); - it("lets only a turn no message started continue a request waiting on background work", () => { - const continuation = childDeliveryForTurnEnd({ + it("never takes a later turn for background work coming back, except in a linked computer's ledger", () => { + const input = { owned: parent.childRequests.open, child: thread(CHILD), - end: { turnId: TurnId.make("turn-continued"), outcome: "completed" }, + end: { turnId: TurnId.make("turn-continued"), outcome: "completed" as const }, pendingMessageId: null, awaitedBackgroundTaskCount: 0, - }); - expect(continuation?.requestId).toBe(waiting.requestId); + }; + // Here the turn's start already settled the waiting request (rule 4). + expect(childDeliveryForTurnEnd(input)).toBeNull(); + expect(childDeliveryForTurnEnd({ ...input, continuesWaitingAnswer: true })?.requestId).toBe( + waiting.requestId, + ); const userTurn = childDeliveryForTurnEnd({ - owned: parent.childRequests.open, - child: thread(CHILD), + ...input, end: { turnId: TurnId.make("turn-user"), outcome: "completed" }, pendingMessageId: MessageId.make("user-message"), - awaitedBackgroundTaskCount: 0, }); expect(userTurn).toBeNull(); }); + + it("says the user stopped a request's turn only when a Stop named it", () => { + const turnId = TurnId.make("turn-b"); + const end = { turnId, outcome: "interrupted" as const, error: "runtime stream ended" }; + const cutOff = childDeliveryForTurnEnd({ + owned: [later], + child: thread(CHILD, { session: session() }), + end, + pendingMessageId: later.childMessageId, + awaitedBackgroundTaskCount: 0, + }); + expect(cutOff).toMatchObject({ + outcome: "failed", + reply: { + text: "'Write the changelog' stopped before it finished: runtime stream ended. Send it a message with thread_send to continue.", + }, + }); + const stopped = childDeliveryForTurnEnd({ + owned: [later], + child: thread(CHILD, { session: session({ stopRequestedTurnId: turnId }) }), + end, + pendingMessageId: later.childMessageId, + awaitedBackgroundTaskCount: 0, + }); + expect(stopped).toMatchObject({ + outcome: "stopped", + reply: { text: "The user stopped 'Write the changelog' before it finished." }, + }); + }); }); -describe("lateReplyOf", () => { - const handedBack = TurnId.make("turn-answer"); - const later = TurnId.make("turn-check-back"); - const child = (overrides: Partial<OrchestrationThread> = {}) => +const session = ( + overrides: Partial<NonNullable<OrchestrationThread["session"]>> = {}, +): NonNullable<OrchestrationThread["session"]> => ({ + threadId: CHILD, + status: "ready", + providerName: "claudeAgent", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: null, + updatedAt: now, + ...overrides, +}); + +describe("childReportForTurnEnd", () => { + const turnId = TurnId.make("turn-check-back"); + const owing = (overrides: Partial<OrchestrationThread> = {}) => thread(CHILD, { - handedBackTurnId: handedBack, - handedBackAt: "2026-10-04T10:05:00.000Z", - latestTurn: { - turnId: later, - state: "completed", - requestedAt: "2026-10-04T10:10:00.000Z", - startedAt: "2026-10-04T10:10:00.000Z", - completedAt: "2026-10-04T10:12:00.000Z", - assistantMessageId: MessageId.make("late-answer"), + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + owedReports: [{ turnId, deliveryEpoch: 0, attachmentEpoch: 0, createdAt: now }], }, messages: [ { id: MessageId.make("late-answer"), role: "assistant", text: "The reviewer found three bugs; all fixed in cf7b10d.", - turnId: later, + turnId, streaming: false, - createdAt: "2026-10-04T10:12:00.000Z", - updatedAt: "2026-10-04T10:12:00.000Z", + createdAt: now, + updatedAt: now, }, ], ...overrides, }); - const parent = thread(PARENT); + const report = ( + child: OrchestrationThread, + end: Parameters<typeof childReportForTurnEnd>[0]["end"], + ) => childReportForTurnEnd({ child, end, pendingMessageId: null }); - it("tells the parent of a finished turn nobody asked for after the child's answer went back", () => { - expect(lateReplyOf(parent, child())).toEqual({ - childThreadId: CHILD, - turnId: later, - title: "Write the changelog", + it("reports a completed turn's reply, and nothing for a turn that owed nothing", () => { + expect(report(owing(), { turnId, outcome: "completed" })).toMatchObject({ + type: "thread.child-report.settle", + owed: { turnId }, + turnId, text: "The reviewer found three bugs; all fixed in cf7b10d.", }); - // Its answer is the newest turn: nothing more to tell. - expect(lateReplyOf(parent, child({ handedBackTurnId: later }))).toBeNull(); + expect(report(thread(CHILD), { turnId, outcome: "completed" })).toBeNull(); + // A reply-less turn settles with nothing to say, so it is dropped. + expect(report(owing({ messages: [] }), { turnId, outcome: "completed" })?.text).toBeUndefined(); }); - it("leaves work the user asked for, or a request still owes, to those", () => { - const automatic = { - id: MessageId.make("user-message"), - role: "user" as const, - text: "Also rename the button.", - turnId: later, - streaming: false, - createdAt: "2026-10-04T10:10:00.000Z", - updatedAt: "2026-10-04T10:10:00.000Z", - }; - const told = child(); - const typed = { ...automatic, composer: "typed" as const }; - expect(lateReplyOf(parent, { ...told, messages: [typed, ...told.messages] })).toBeNull(); - // A reviewer's reply, or an automatic fix the server wrote, is not the user's. - const reviewerReply = { ...automatic, fromAgent: { participantId: null } }; - expect( - lateReplyOf(parent, { ...told, messages: [reviewerReply, ...told.messages] }), - ).not.toBeNull(); + it("delivers a failure, says whether it goes on by itself, and counts the reports waiting in it", () => { + expect(report(owing(), { turnId, outcome: "failed", error: "Overloaded." })?.text).toBe( + "'Write the changelog' failed: Overloaded. Send it a message with thread_send to continue.", + ); + const waitingForReset = owing({ + session: session({ status: "error", continueAtReset: { resetsAt: now, at: now } }), + }); + expect(report(waitingForReset, { turnId, outcome: "failed", error: "Usage limit" })?.text).toBe( + "'Write the changelog' failed: Usage limit. It continues by itself when the limit resets.", + ); + const queuedReport = (id: string) => ({ + messageId: MessageId.make(id), + text: "done", + attachments: [], + fromThread: { + threadId: ThreadId.make(id), + requestId: ChildRequestId.make(id), + kind: "report" as const, + }, + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: now, + }); + const withReports = owing({ queuedFollowUps: [queuedReport("g1"), queuedReport("g2")] }); + expect(report(withReports, { turnId, outcome: "failed", error: "Overloaded" })?.text).toBe( + "'Write the changelog' failed: Overloaded. 2 reports from its threads are waiting in it unread. Send it a message with thread_send and it reads them first.", + ); + }); + + it("drops a turn a Stop named, and tells of one cut off without a Stop", () => { + const end = { turnId, outcome: "interrupted" as const, error: "runtime stream ended" }; expect( - lateReplyOf(parent, { ...told, messages: [automatic, ...told.messages] }), - ).not.toBeNull(); - const asking = thread(PARENT, { - childRequests: { ...EMPTY_CHILD_REQUEST_STATE, open: [request("a", {})] }, + report(owing({ session: session({ stopRequestedTurnId: turnId }) }), end)?.text, + ).toBeUndefined(); + expect(report(owing({ session: session() }), end)?.text).toBe( + "'Write the changelog' stopped before it finished: runtime stream ended. Send it a message with thread_send to continue.", + ); + }); + + it("settles a request's turn as the request, never also as a report", () => { + const requested = request("c", { status: "running" }); + const child = thread(CHILD, { + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + owedReports: [ + { + messageId: MessageId.make("other"), + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: now, + }, + ], + }, + }); + const delivery = childDeliveryForEndedTurn({ + owned: [requested], + child, + end: { turnId: TurnId.make("turn-c"), outcome: "completed" }, + pendingMessageId: requested.childMessageId, + awaitedBackgroundTaskCount: 0, }); - expect(lateReplyOf(asking, told)).toBeNull(); - expect(lateReplyOf(parent, child({ attachedToParent: false }))).toBeNull(); + expect(delivery?.type).toBe("thread.child-request.settle"); }); }); diff --git a/apps/server/src/orchestration/childThreadDelivery.ts b/apps/server/src/orchestration/childThreadDelivery.ts index 7e1bdc3fe..3d4b8d724 100644 --- a/apps/server/src/orchestration/childThreadDelivery.ts +++ b/apps/server/src/orchestration/childThreadDelivery.ts @@ -1,12 +1,14 @@ /** - * Child threads: when a child's work is an answer for its parent, and what - * that answer says (docs/design/child-threads.md, "Delivery"). Pure: runtime - * ingestion calls it once a child's turn has ended and its words are final, - * the reactor once a child that was finishing background work goes quiet, - * and startup for whatever a restart cut off. Each returns the command to - * dispatch, or null when the turn answers nothing. The same rules decide a - * child's answers to a parent on a linked computer (LinkRequests), whose - * requests live in a ledger rather than on a parent here. + * Child threads: when a child's work is an answer for its parent or a report + * to it, and what it says (docs/design/child-threads.md, "Delivery", and + * docs/design/agent-autonomy-no-limits.md, "Delivery rules"). Pure: runtime + * ingestion calls it once a child's turn has ended and its words are final + * (or its runtime exited with the turn), the reactor once a child that was + * finishing background work goes quiet, and startup for whatever a restart + * cut off. Each returns the command to dispatch, or null when the turn + * answers nothing. The same rules decide a child's answers to a parent on a + * linked computer (LinkRequests), whose requests live in a ledger rather than + * on a parent here, and which owes no reports. */ import { type ChildRequestOutcome, @@ -14,18 +16,13 @@ import { type MessageId, type OrchestrationChildRequest, type OrchestrationThread, - type ThreadId, - type ThreadParticipantId, + type OwedChildReport, + type OwedReportKey, type TurnId, } from "@threadlines/contracts"; -import { activeParticipants } from "@threadlines/shared/threadParticipants"; +import { isOwedReport, owedReportKeyOf } from "@threadlines/shared/childThreads"; -import { - childHasLiveWork, - childReportMessageId, - childReportText, - personWroteSince, -} from "./childThreadDecisions.ts"; +import { childReportMessageId, childReportText } from "./childThreadDecisions.ts"; import { turnStartingMessage } from "./continueTurns.ts"; /** What the delivery rules read of a request, wherever it is kept. */ @@ -109,12 +106,24 @@ const partialAnswer = ( : `\n\nIts last reply before that:\n\n${childReportText(candidate)}`; }; +/** What the parent is told of a turn that ended without being stopped (rule 5). */ +export const stoppedBeforeFinishedText = (title: string, reason: string) => + `'${title}' stopped before it finished: ${reason.replace(/\.$/, "")}. Send it a message with thread_send to continue.`; + +/** + * Whether a turn that ended interrupted was stopped on purpose: it is the + * turn a Stop named (rule 6). A runtime that died, the idle reaper, or a + * stream that ended mid-turn names none, and is never the user's doing. + */ +export const stoppedOnPurpose = (child: Pick<OrchestrationThread, "session">, turnId: TurnId) => + (child.session?.stopRequestedTurnId ?? null) === turnId; + /** - * A child's turn ended. It answers the request whose message started it, or, - * for a request whose turn already ended while the child kept waiting on its - * own background work, the follow-up turn that work started. With background - * work still owed, the answer waits for it (`awaiting_background`, keeping - * this turn as the answer so far). + * A child's turn ended. It answers the request whose message started it, and + * nothing else: a turn no message started never continues a request waiting + * on background work (rule 4; the turn's start settled that one). With + * background work still owed, the answer waits for it (`awaiting_background`, + * keeping this turn as the answer so far). */ export function childDeliveryForTurnEnd(input: { /** The child's open requests: on its parent here, or in the link ledger. */ @@ -125,17 +134,22 @@ export function childDeliveryForTurnEnd(input: { readonly pendingMessageId: MessageId | null; /** The child's background work it still waits on, as of the turn's end. */ readonly awaitedBackgroundTaskCount: number; + /** + * A linked computer's ledger: a turn no message started still continues a + * request waiting on background work, since nothing else brings a linked + * child's later work back (rule 15). + */ + readonly continuesWaitingAnswer?: boolean; }): ChildDelivery | null { const { owned, child, end } = input; - // The request whose own message started this turn comes first. Only a turn - // no message started (the follow-up a child's background work starts on - // its own) continues a request waiting on that work; a turn the parent or - // the user started answers its own message, never an older request. const request = owned.find( - (entry) => entry.status === "running" && entry.childMessageId === input.pendingMessageId, + (entry) => + input.pendingMessageId !== null && + entry.status === "running" && + entry.childMessageId === input.pendingMessageId, ) ?? - (input.pendingMessageId === null + (input.continuesWaitingAnswer === true && input.pendingMessageId === null ? owned.find( (entry) => entry.status === "awaiting_background" && @@ -180,6 +194,16 @@ export function childDeliveryForTurnEnd(input: { error, ); } + if (!stoppedOnPurpose(child, end.turnId)) { + const reason = end.error ?? "its runtime stopped"; + return settle( + request, + "failed", + `${stoppedBeforeFinishedText(child.title, reason)}${partialAnswer(child, request)}`, + end.turnId, + reason, + ); + } return settle( request, "stopped", @@ -188,6 +212,133 @@ export function childDeliveryForTurnEnd(input: { ); } +/** A report a child's ended turn owed its parent: the command that settles it. */ +export interface ChildReportDelivery { + readonly type: "thread.child-report.settle"; + readonly commandId: CommandId; + readonly owed: OwedReportKey; + readonly turnId: TurnId | null; + readonly text?: string; +} + +const reportSettleCommandId = (child: Pick<OrchestrationThread, "id">, key: OwedReportKey) => + CommandId.make( + `server:child-report:${child.id}:${"messageId" in key ? `message:${key.messageId}` : `turn:${key.turnId}`}:settle`, + ); + +/** The owed entry a turn settles: keyed by the turn, or by the message that started it. */ +export function owedEntryForTurn( + child: Pick<OrchestrationThread, "childRequests">, + turnId: TurnId, + pendingMessageId: MessageId | null, +): OwedChildReport | undefined { + return (child.childRequests.owedReports ?? []).find( + (entry) => + isOwedReport(entry, { turnId }) || + (pendingMessageId !== null && isOwedReport(entry, { messageId: pendingMessageId })), + ); +} + +/** + * What a turn that ended failed says (rule 5), with the reports from its own + * threads waiting in it unread (rule 10), and whether it goes on by itself. + */ +export function reportFailureText(child: OrchestrationThread, error: string): string { + const waiting = (child.queuedFollowUps ?? []).filter( + (queued) => queued.fromThread?.kind === "report", + ).length; + const failed = `'${child.title}' failed: ${error.replace(/\.$/, "")}.`; + if ((child.session?.continueAtReset ?? null) !== null) { + return `${failed} It continues by itself when the limit resets.`; + } + if (waiting === 0) { + return `${failed} Send it a message with thread_send to continue.`; + } + const reports = + waiting === 1 ? "1 report from its threads is" : `${waiting} reports from its threads are`; + return `${failed} ${reports} waiting in it unread. Send it a message with thread_send and it reads them first.`; +} + +/** + * The report an ended turn owed (rules 5 and 6): its reply when it completed, + * its failure, or "stopped before it finished" when it was cut off without a + * Stop naming it. Nothing to say (stopped on purpose, completed with no + * reply) settles it as dropped. Null when the turn owed nothing. + */ +export function childReportForTurnEnd(input: { + readonly child: OrchestrationThread; + readonly end: ChildTurnEnd; + readonly pendingMessageId: MessageId | null; +}): ChildReportDelivery | null { + const { child, end } = input; + const entry = owedEntryForTurn(child, end.turnId, input.pendingMessageId); + if (entry === undefined) return null; + const owed = owedReportKeyOf(entry); + const text = + end.outcome === "completed" + ? reportReplyText(child, end.turnId) + : end.outcome === "failed" + ? reportFailureText(child, end.error ?? "Its turn did not finish.") + : stoppedOnPurpose(child, end.turnId) + ? undefined + : stoppedBeforeFinishedText(child.title, end.error ?? "its runtime stopped"); + return { + type: "thread.child-report.settle", + commandId: reportSettleCommandId(child, owed), + owed, + turnId: end.turnId, + ...(text !== undefined ? { text } : {}), + }; +} + +/** A turn's reply as a report, clipped as answers are; undefined when it said nothing. */ +function reportReplyText(child: OrchestrationThread, turnId: TurnId): string | undefined { + const reply = lastAnswerOfTurn(child, turnId)?.trim(); + return reply === undefined || reply.length === 0 ? undefined : childReportText(reply); +} + +/** + * A child's turn ended: the request it answers settles, or the report it + * owed does. Never both: a turn a request started owes no report (rule 2). + * The turn end, the exit that took a turn with it, and startup all call this. + */ +export function childDeliveryForEndedTurn(input: { + readonly owned: ReadonlyArray<ChildDeliveryRequest>; + readonly child: OrchestrationThread; + readonly end: ChildTurnEnd; + readonly pendingMessageId: MessageId | null; + readonly awaitedBackgroundTaskCount: number; +}): ChildDelivery | ChildReportDelivery | null { + return childDeliveryForTurnEnd(input) ?? childReportForTurnEnd(input); +} + +/** + * An owed turn a restart cut off or left unreported (rule 14): a completed + * turn is delivered, a failed one delivers its failure, and one the restart + * cut off (or that never started) says so. + */ +export function childReportAfterRestart( + child: OrchestrationThread, + entry: OwedChildReport, + turn: { readonly turnId: TurnId | null; readonly state: string } | undefined, +): ChildReportDelivery { + const owed = owedReportKeyOf(entry); + const turnId = turn?.turnId ?? ("turnId" in entry ? entry.turnId : null); + const text = + turn?.state === "completed" && turnId !== null + ? reportReplyText(child, turnId) + : turn?.state === "error" + ? reportFailureText(child, child.session?.lastError ?? "Its turn did not finish.") + : `'${child.title}' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.`; + return { + type: "thread.child-report.settle", + commandId: reportSettleCommandId(child, owed), + owed, + turnId, + ...(text !== undefined ? { text } : {}), + }; +} + /** * Whether a parent's request is held open by the child's wait to continue * after a usage limit (docs/design/lead-chat.md, "Usage limits"): the child @@ -289,8 +440,10 @@ export function isQuietCandidate( /** * The turn that durably finished a request's answer before a restart, if one - * did: the turn its message started, or, for an answer waiting on background - * work, the latest follow-up that work started on its own. + * did: the turn its message started. No later turn is looked for (rule 4), + * except in a linked computer's ledger (`continuesWaitingAnswer`, rule 15): + * there an answer waiting on background work takes the latest follow-up that + * work started on its own. */ export function finishedTurnAfterRestart( childTurns: ReadonlyArray<{ @@ -301,6 +454,7 @@ export function finishedTurnAfterRestart( readonly completedAt: string | null; }>, request: ChildDeliveryRequest, + options: { readonly continuesWaitingAnswer?: boolean } = {}, ): TurnId | null { const candidateEnded = childTurns.find((entry) => entry.turnId === request.candidateTurnId)?.completedAt ?? ""; @@ -309,7 +463,7 @@ export function finishedTurnAfterRestart( ? childTurns.find( (turn) => turn.pendingMessageId === request.childMessageId && turn.state === "completed", ) - : request.status === "awaiting_background" + : request.status === "awaiting_background" && options.continuesWaitingAnswer === true ? childTurns .filter( (turn) => @@ -327,14 +481,21 @@ export function finishedTurnAfterRestart( /** * A request a server restart cut off: an answer that durably finished is - * delivered; anything else is reported as interrupted, with what the child had + * delivered, and one waiting on background work settles with its answer so + * far; anything else is reported as interrupted, with what the child had * said so far, so the agent that asked can send it a message to continue. */ export function childDeliveryAfterRestart( child: OrchestrationThread, request: ChildDeliveryRequest, finishedTurnId: TurnId | null, + options: { readonly continuesWaitingAnswer?: boolean } = {}, ): ChildDelivery { + const waiting = + finishedTurnId === null && options.continuesWaitingAnswer !== true + ? childDeliveryForQuietCandidate(child, request) + : null; + if (waiting !== null) return waiting; if (finishedTurnId !== null) { return settle( request, @@ -352,99 +513,3 @@ export function childDeliveryAfterRestart( error, ); } - -/** How much of each late reply rides along; the rest is in the child (thread_read). */ -const LATE_REPLY_CHAR_LIMIT = 4_000; - -/** - * Work a child did after its answer reached its parent, which nobody asked - * for: a check-back woke it, or an agent it asked (a reviewer in its own - * room) replied, and it carried on. No request is open for it, so nothing - * goes back as a report. Instead the parent's agent is told at its next turn - * (`lateRepliesFor`), without being woken: a child that keeps checking back - * can't wake its parent over and over. Once told, the child is recorded as - * handed back as of that turn, so it wraps itself like one that answered. - * - * Read from the threads as they are, not from anything recorded when the - * child's turn ended, so a restart loses nothing. Only a finished turn with - * a reply counts, while the child is still in this parent's family, settled, - * and no person has written to it since its answer went back (then the work - * is theirs, not the parent's; personWrote). - */ -export interface LateReply { - readonly childThreadId: ThreadId; - readonly turnId: TurnId; - readonly title: string; - readonly text: string; -} - -export function lateReplyOf( - parent: OrchestrationThread, - child: OrchestrationThread, -): LateReply | null { - const { handedBackTurnId, handedBackAt } = child; - const turn = child.latestTurn; - if ( - child.deletedAt !== null || - child.archivedAt !== null || - !child.attachedToParent || - child.parentThreadId !== parent.id || - handedBackTurnId === null || - handedBackAt === null || - turn === null || - turn.turnId === handedBackTurnId || - turn.state !== "completed" || - parent.childRequests.open.some((request) => request.childThreadId === child.id) || - childHasLiveWork(child) - ) { - return null; - } - if (personWroteSince(child, handedBackAt)) return null; - const reply = lastAnswerOfTurn(child, turn.turnId)?.trim(); - if (reply === undefined || reply.length === 0) return null; - return { - childThreadId: child.id, - turnId: turn.turnId, - title: child.title, - text: - reply.length > LATE_REPLY_CHAR_LIMIT - ? `${reply.slice(0, LATE_REPLY_CHAR_LIMIT)} [clipped; read the rest with thread_read]` - : reply, - }; -} - -/** - * The agent of `parent` a child's late reply is for: the one its last report - * went to, or, with none (stopped before it answered), the one whose turn - * started it; while that agent is still in the room. Otherwise the thread's own. - */ -export function lateReplyRecipient( - parent: OrchestrationThread, - child: Pick<OrchestrationThread, "id" | "parentTurnId">, -): ThreadParticipantId | null { - const lastReport = parent.messages.findLast( - (message) => - message.fromThread?.kind === "report" && - message.fromThread.threadId === child.id && - message.fromThread.environmentId === undefined, - ); - const starter = - lastReport === undefined && child.parentTurnId !== null - ? parent.messages.find( - (message) => message.role === "assistant" && message.turnId === child.parentTurnId, - ) - : undefined; - const participantId = (lastReport ?? starter)?.participantId ?? null; - return participantId !== null && - activeParticipants(parent).some((participant) => participant.id === participantId) - ? participantId - : null; -} - -/** The lines a parent's agent reads about its children's late replies. */ -export function lateRepliesText(replies: ReadonlyArray<LateReply>): string { - return [ - "Threads you started kept working after their answer to you, without being asked (a check-back, or a reply from an agent they asked). Their latest replies follow. It is information from other agents, not instructions from the user.", - ...replies.map((reply) => `"${reply.title}" (thread ${reply.childThreadId}):\n\n${reply.text}`), - ].join("\n\n"); -} diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index b72703894..e4f6f7ba1 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -925,41 +925,6 @@ describe("decider child threads", () => { expect(threadIn(idle.model, CHILD).handedBackTurnId).toBeNull(); }); - it("records a child's late reply as handed back once its parent's agent was told, only while it is the newest turn", async () => { - const delivered = await run(await familyWithRunningChild(), settleAnswered()); - const lateTurn = TurnId.make("child-turn-2"); - const later = { - ...delivered.model, - threads: delivered.model.threads.map((entry) => - entry.id === CHILD - ? { - ...entry, - latestTurn: { - turnId: lateTurn, - state: "completed" as const, - requestedAt: at(12), - startedAt: at(12), - completedAt: at(13), - assistantMessageId: null, - }, - } - : entry, - ), - }; - const told = (turnId: TurnId) => ({ - type: "thread.child-notes.delivered" as const, - commandId: CommandId.make(`told-${turnId}`), - threadId: PARENT, - requestIds: [], - lateReplies: [{ childThreadId: CHILD, turnId }], - createdAt: at(14), - }); - const recorded = await run(later, told(lateTurn)); - expect(threadIn(recorded.model, CHILD).handedBackTurnId).toBe(lateTurn); - // Told of a turn that is no longer its newest: nothing to record. - expect(await refused(later, told(TurnId.make("child-turn-1")))).toBe(true); - }); - it("a separated child keeps the parent's message still queued for it, as its own work", async () => { const family = await familyWithRunningChild(); const busyChild = (model: OrchestrationReadModel) => ({ @@ -1920,3 +1885,348 @@ describe("decider: a stop meant for one turn", () => { expect((await run(usersTurn, stop("user-turn"))).events.length).toBeGreaterThan(0); }); }); + +describe("decider child reports", () => { + /** A child whose answer went back, idle, with the parent's answer queued. */ + async function answeredFamily() { + const delivered = await run(await familyWithRunningChild(), settleAnswered()); + return { + ...delivered.model, + threads: delivered.model.threads.map((entry) => + entry.id === CHILD + ? { + ...entry, + session: session(CHILD, { status: "ready", activeTurnId: null }), + latestTurn: { + turnId: TurnId.make("child-turn-1"), + state: "completed" as const, + requestedAt: at(3), + startedAt: at(3), + completedAt: at(9), + assistantMessageId: null, + }, + } + : entry.id === PARENT + ? { ...entry, queuedFollowUps: [] } + : entry, + ), + }; + } + + const turnStart = ( + id: string, + extra: Partial<Extract<OrchestrationCommand, { type: "thread.turn.start" }>> = {}, + ): Extract<OrchestrationCommand, { type: "thread.turn.start" }> => ({ + type: "thread.turn.start", + commandId: CommandId.make(`turn-${id}`), + threadId: CHILD, + message: { messageId: MessageId.make(id), role: "user", text: "Go on.", attachments: [] }, + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(20), + ...extra, + }); + + const owesOf = (events: ReadonlyArray<Planned>) => + (events as ReadonlyArray<OrchestrationEvent>).flatMap((event) => + event.type === "thread.turn-start-requested" ? [event.payload.owesReport ?? null] : [], + ); + + const providerTurn = ( + turnId: string, + createdAt = at(30), + ): Extract<OrchestrationCommand, { type: "thread.session.set" }> => ({ + type: "thread.session.set", + commandId: CommandId.make(`session-${turnId}`), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make(turnId), updatedAt: createdAt }), + providerStartedTurn: true, + createdAt, + }); + + const settleReport = ( + owed: { readonly turnId: TurnId } | { readonly messageId: MessageId }, + turnId: string, + text: string | undefined = "Found two more bugs; fixed.", + createdAt = at(40), + ): Extract<OrchestrationCommand, { type: "thread.child-report.settle" }> => ({ + type: "thread.child-report.settle", + commandId: CommandId.make(`report-${turnId}`), + threadId: CHILD, + owed, + turnId: TurnId.make(turnId), + ...(text !== undefined ? { text } : {}), + createdAt, + }); + + it("owes a report only for turns nobody else answers for (rule 2)", async () => { + const family = await answeredFamily(); + const owes = async (command: OrchestrationCommand) => + owesOf((await run(family, command)).events)[0]; + const stamps = { deliveryEpoch: 0, attachmentEpoch: 0 }; + // The parent's request answers it, and owes nothing more. + expect(threadIn(family, CHILD).childRequests.owedReports).toBeUndefined(); + // A person's message is theirs. + expect(await owes(turnStart("typed", { composer: "typed" }))).toBeNull(); + expect(await owes(turnStart("phone", { sentFrom: { kind: "phone" } as never }))).toBeNull(); + // A scheduled run, an automatic fix, a report from its own thread: it reports. + expect(await owes(turnStart("scheduled", { scheduledTaskId: "task-1" as never }))).toEqual( + stamps, + ); + expect(await owes(turnStart("automatic"))).toEqual(stamps); + expect( + await owes( + turnStart("report", { + fromThread: { + threadId: ThreadId.make("grandchild"), + requestId: ChildRequestId.make("g"), + kind: "report", + }, + }), + ), + ).toEqual(stamps); + // A continue is judged by the turn it continues. + const afterTyped = await run(family, turnStart("typed-2", { composer: "typed" })); + const idleAgain = { + ...afterTyped.model, + threads: afterTyped.model.threads.map((entry) => + entry.id === CHILD + ? { ...entry, session: session(CHILD, { status: "ready", activeTurnId: null }) } + : entry, + ), + }; + const restart = turnStart("restart", { trigger: "serverRestart", createdAt: at(25) }); + expect(owesOf((await run(idleAgain, restart)).events)[0]).toBeNull(); + const afterAutomatic = await run(family, turnStart("automatic-2")); + const idleAfterAutomatic = { + ...afterAutomatic.model, + threads: afterAutomatic.model.threads.map((entry) => + entry.id === CHILD + ? { ...entry, session: session(CHILD, { status: "ready", activeTurnId: null }) } + : entry, + ), + }; + expect(owesOf((await run(idleAfterAutomatic, restart)).events)[0]).toEqual(stamps); + // A thread with no parent owes nobody. + const top = readModel([ + thread(PARENT, { session: session(PARENT, { status: "ready", activeTurnId: null }) }), + ]); + expect( + owesOf((await run(top, { ...turnStart("top"), threadId: PARENT })).events)[0], + ).toBeNull(); + }); + + it("delivers a report into the parent once, for the agent that started the child", async () => { + const family = await answeredFamily(); + const checkBack = await run(family, providerTurn("child-turn-2")); + const owed = threadIn(checkBack.model, CHILD).childRequests.owedReports; + expect(owed).toEqual([ + { + turnId: TurnId.make("child-turn-2"), + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: at(30), + }, + ]); + const settled = await run( + checkBack.model, + settleReport({ turnId: TurnId.make("child-turn-2") }, "child-turn-2"), + ); + const parent = threadIn(settled.model, PARENT); + const report = parent.messages.at(-1); + expect(report).toMatchObject({ + role: "user", + text: "Found two more bugs; fixed.", + fromThread: { threadId: CHILD, kind: "report", followUp: true }, + }); + expect(parent.queuedFollowUps?.map((queued) => queued.messageId)).toEqual([report?.id]); + expect(threadIn(settled.model, CHILD)).toMatchObject({ + handedBackTurnId: TurnId.make("child-turn-2"), + }); + expect(threadIn(settled.model, CHILD).childRequests.owedReports).toBeUndefined(); + // Settled once: a second settle of the same turn is refused. + expect( + await refused( + settled.model, + settleReport({ turnId: TurnId.make("child-turn-2") }, "child-turn-2"), + ), + ).toBe(true); + }); + + it("drops a report while the parent is wrapped up or held, and delivers again once it is reopened", async () => { + const family = await answeredFamily(); + const owing = (await run(family, providerTurn("child-turn-2"))).model; + const wrapped = ( + await run(owing, { + type: "thread.done-override.set", + commandId: CommandId.make("wrap"), + threadId: PARENT, + state: "done", + at: at(35), + }) + ).model; + const dropped = await run( + wrapped, + settleReport({ turnId: TurnId.make("child-turn-2") }, "child-turn-2"), + ); + expect(dropped.events.map((event) => event.type)).toEqual(["thread.child-report-dropped"]); + expect(threadIn(dropped.model, CHILD).childRequests.owedReports).toBeUndefined(); + + const reopened = ( + await run(dropped.model, { + type: "thread.done-override.set", + commandId: CommandId.make("reopen"), + threadId: PARENT, + state: "active", + at: at(45), + }) + ).model; + const next = (await run(reopened, providerTurn("child-turn-3", at(50)))).model; + const delivered = await run( + next, + settleReport({ turnId: TurnId.make("child-turn-3") }, "child-turn-3", undefined, at(55)), + ); + expect(delivered.events.map((event) => event.type)).toContain("thread.message-sent"); + + const held = { + ...next, + threads: next.threads.map((entry) => + entry.id === PARENT + ? { ...entry, agentRequests: { ...entry.agentRequests, hold: true } } + : entry, + ), + }; + const heldOut = await run( + held, + settleReport({ turnId: TurnId.make("child-turn-3") }, "child-turn-3", undefined, at(55)), + ); + expect(heldOut.events.map((event) => event.type)).toEqual(["thread.child-report-dropped"]); + }); + + it("forgets what a child owed once it is separated", async () => { + const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; + const separated = await run(owing, { + type: "thread.parent-attachment.set", + commandId: CommandId.make("separate"), + threadId: CHILD, + attached: false, + createdAt: at(35), + }); + expect(threadIn(separated.model, CHILD).childRequests.owedReports).toBeUndefined(); + }); + + it("settles a request waiting on background work when a turn the provider started begins (sequence 5)", async () => { + const family = await familyWithRunningChild(); + const waiting = { + ...family, + threads: family.threads.map((entry) => + entry.id === PARENT + ? { + ...entry, + childRequests: { + ...entry.childRequests, + open: entry.childRequests.open.map((request) => ({ + ...request, + status: "awaiting_background" as const, + candidateTurnId: TurnId.make("child-turn-1"), + })), + }, + } + : entry.id === CHILD + ? { + ...entry, + session: session(CHILD, { status: "ready", activeTurnId: null }), + messages: [ + ...entry.messages, + { + id: MessageId.make("answer-so-far"), + role: "assistant" as const, + text: "Changelog drafted; tests still running.", + turnId: TurnId.make("child-turn-1"), + streaming: false, + createdAt: at(8), + updatedAt: at(8), + }, + ], + } + : entry, + ), + }; + const goalTurn = await run(waiting, providerTurn("goal-turn")); + const parent = threadIn(goalTurn.model, PARENT); + expect(parent.childRequests.open).toEqual([]); + expect(parent.messages.at(-1)).toMatchObject({ + text: "Changelog drafted; tests still running.", + fromThread: { kind: "report", requestId: REQUEST }, + }); + expect(threadIn(goalTurn.model, CHILD).childRequests.owedReports).toEqual([ + { turnId: TurnId.make("goal-turn"), deliveryEpoch: 0, attachmentEpoch: 0, createdAt: at(30) }, + ]); + }); + + it("settles what an earlier turn still owed when the next turn starts, once (sequence 6)", async () => { + const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; + // The runtime exited and nothing settled that turn; a message from the + // parent starts the next one. + const next = await run(owing, { + type: "thread.session.set", + commandId: CommandId.make("session-next"), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make("child-turn-3"), updatedAt: at(40) }), + turnMessageId: MessageId.make("next-message"), + createdAt: at(40), + }); + const reports = threadIn(next.model, PARENT).messages.filter( + (message) => message.fromThread?.followUp === true, + ); + expect(reports.map((message) => message.text)).toEqual([ + "'Write the changelog' stopped before it finished: its turn ended without its reply reaching Threadlines. Send it a message with thread_send to continue.", + ]); + expect(threadIn(next.model, CHILD).childRequests.owedReports).toBeUndefined(); + }); + + it("hands a leaving agent's queued follow-up report to the thread's own agent, and takes its answers off", async () => { + const reviewer = "reviewer" as never; + const queued = (id: string, followUp: boolean) => ({ + messageId: MessageId.make(id), + text: "done", + attachments: [], + participantId: reviewer, + fromThread: { + threadId: CHILD, + requestId: ChildRequestId.make(id), + kind: "report" as const, + ...(followUp ? { followUp: true as const } : {}), + }, + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(5), + }); + const room = readModel([ + thread(PARENT, { + session: session(PARENT, { status: "ready", activeTurnId: null }), + participants: [ + { + id: reviewer, + handle: "Reviewer", + modelSelection: model, + joinedAt: now, + leftAt: null, + } as never, + ], + queuedFollowUps: [queued("answer", false), queued("follow-up", true)], + }), + ]); + const left = await run(room, { + type: "thread.participant.remove", + commandId: CommandId.make("leave"), + threadId: PARENT, + participantId: reviewer, + createdAt: at(10), + }); + expect(threadIn(left.model, PARENT).queuedFollowUps).toEqual([ + expect.objectContaining({ messageId: MessageId.make("follow-up") }), + ]); + expect(threadIn(left.model, PARENT).queuedFollowUps?.[0]?.participantId).toBeUndefined(); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index efa9f4d69..cdf2d98df 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -51,7 +51,11 @@ import { import { secretRequestIdOfAnswerMessage } from "@threadlines/shared/secretRequests"; import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; -import { isAttachedChild, passCeilingRefusal } from "@threadlines/shared/childThreads"; +import { + isAttachedChild, + isOwedReport, + passCeilingRefusal, +} from "@threadlines/shared/childThreads"; import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; @@ -118,7 +122,14 @@ import { withinModeCeiling, } from "./childThreadDecisions.ts"; import { - childDeliveryForQuietCandidate, + continuedTurnMessage, + decideChildReportSettle, + owedReportStamps, + settleWaitingAnswer, + sweepOwedReports, + turnStartOwesReport, +} from "./childReports.ts"; +import { failedTurnMessage, heldRequestEnded, isHeldByContinueAtReset, @@ -553,42 +564,6 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({ return plannedEvents; }); -/** - * Child threads: the user writes to a child whose answer to its parent was - * waiting on the child's background work. The answer so far goes back now, - * before the user's turn, so the user taking over never changes what the - * parent receives. - */ -function settleCandidateBeforeUserTurn( - readModel: OrchestrationReadModel, - child: OrchestrationThread, - command: Pick<OrchestrationCommand, "commandId"> & { readonly createdAt: string }, -): ReadonlyArray<PlannedOrchestrationEvent> { - if (child.parentThreadId === null) { - return []; - } - const parent = readModel.threads.find( - (entry) => entry.id === child.parentThreadId && entry.deletedAt === null, - ); - const request = parent?.childRequests.open.find( - (entry) => entry.childThreadId === child.id && entry.status === "awaiting_background", - ); - if (parent === undefined || request === undefined) { - return []; - } - const delivery = childDeliveryForQuietCandidate(child, request); - if (delivery === null || delivery.type !== "thread.child-request.settle") { - return []; - } - const decision = decideChildRequestSettle( - readModel, - parent, - { ...delivery, threadId: parent.id, createdAt: command.createdAt }, - childEventBase(command, command.createdAt), - ); - return "refusal" in decision ? [] : decision; -} - /** * Child threads on Stop (or a session stop) in `thread`: what it was owed by * its own children will not come back, and a parent's requests still queued @@ -925,7 +900,11 @@ function answersHeldableRequest( ); } -/** A report from one of its threads, heard in a thread no parent waits on. */ +/** + * A report from one of its threads: its turn continues by itself at the + * reset, in a thread with a parent too, whose own report of that turn went + * up when it failed (docs/design/agent-autonomy-no-limits.md, rule 13). + */ function reportsToTopLevel( thread: OrchestrationThread, session: OrchestrationSession, @@ -933,7 +912,6 @@ function reportsToTopLevel( ): boolean { return ( startedBy.fromThread?.kind === "report" && - !isAttachedChild(thread) && (thread.remoteOrigin ?? null) === null && sessionSlotParticipantId(session) === null ); @@ -2801,6 +2779,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" case "thread.lead.pass": case "thread.child-request.update": case "thread.child-request.settle": + case "thread.child-report.settle": case "thread.child-notes.delivered": case "thread.remote-child.update": case "thread.remote-cancels.delivered": @@ -2826,15 +2805,23 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ? decideChildRequestUpdate(thread, command, baseFor) : command.type === "thread.child-request.settle" ? decideChildRequestSettle(readModel, thread, command, baseFor) - : command.type === "thread.remote-child.update" - ? decideRemoteChildUpdate(thread, command, baseFor) - : command.type === "thread.remote-cancels.delivered" - ? decideRemoteCancelsDelivered(thread, command, baseFor) - : command.type === "thread.remote-request.queue" - ? decideRemoteRequestQueue(thread, command, baseFor) - : command.type === "thread.remote-handed-back.record" - ? decideRemoteHandedBackRecord(thread, command, baseFor) - : decideChildNotesDelivered(readModel, thread, command, baseFor), + : command.type === "thread.child-report.settle" + ? decideChildReportSettle( + readModel, + thread, + command, + baseFor, + command.createdAt, + ) + : command.type === "thread.remote-child.update" + ? decideRemoteChildUpdate(thread, command, baseFor) + : command.type === "thread.remote-cancels.delivered" + ? decideRemoteCancelsDelivered(thread, command, baseFor) + : command.type === "thread.remote-request.queue" + ? decideRemoteRequestQueue(thread, command, baseFor) + : command.type === "thread.remote-handed-back.record" + ? decideRemoteHandedBackRecord(thread, command, baseFor) + : decideChildNotesDelivered(thread, command, baseFor), ); } @@ -3391,12 +3378,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" settledAt: command.createdAt, }, })), - // A child's report, and a scheduled task's run, for the leaving agent: + // A child's answer, and a scheduled task's run, for the leaving agent: // never handed to another (the task's run says its agent left). ...(thread.queuedFollowUps ?? []) .filter( (queued) => - (queued.fromThread?.kind === "report" || queued.scheduledTaskId !== undefined) && + ((queued.fromThread?.kind === "report" && queued.fromThread.followUp !== true) || + queued.scheduledTaskId !== undefined) && queued.participantId === participant.id, ) .map((queued): PlannedOrchestrationEvent => ({ @@ -3409,6 +3397,23 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" createdAt: command.createdAt, }, })), + // A later report nobody asked for goes to the thread's own agent + // instead (docs/design/agent-autonomy-no-limits.md, rule 8). + ...(thread.queuedFollowUps ?? []) + .filter( + (queued) => + queued.fromThread?.kind === "report" && + queued.fromThread.followUp === true && + queued.participantId === participant.id, + ) + .map((queued): PlannedOrchestrationEvent => { + const { participantId: _leaving, ...forOwnAgent } = queued; + return { + ...leavingBase(thread.id), + type: "thread.follow-up-queued", + payload: { threadId: thread.id, followUp: forOwnAgent }, + }; + }), ]; return [ ...cancelAgentRequestsForLeaving(thread, participant.id, removeBase, command.createdAt), @@ -3863,6 +3868,26 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ), }, }; + // Child threads: a turn the child takes on its own owes its parent a + // report (docs/design/agent-autonomy-no-limits.md, rule 2). A queued + // agent's message was written when it was queued, with what it is. + const queuedMessage = targetThread.messages.find( + (message) => message.id === command.message.messageId, + ); + const owesReport = turnStartOwesReport( + readModel, + targetThread, + { ...command, requestKind: queuedMessage?.requestKind }, + { + origin: + command.trigger === undefined + ? undefined + : continuedTurnMessage(targetThread, participantId, command.message.messageId), + answersRequest: + command.trigger === "usageLimitReset" && + heldRequestsOf(readModel, targetThread) !== null, + }, + ); const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = { ...withEventBase({ aggregateKind: "thread", @@ -3902,6 +3927,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // proven theirs does (turnLiftsMoveFence). ...(turnLiftsMoveFence(targetThread, command) ? { liftsMoveFence: true as const } : {}), createdAt: command.createdAt, + ...(owesReport !== undefined ? { owesReport } : {}), }, }; const turnBase = () => @@ -3975,6 +4001,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }) : []; return [ + // A parent's request still waiting on this child's background work + // settles with its answer so far, whatever starts this turn (rule 4). + ...settleWaitingAnswer( + readModel, + targetThread, + childEventBase(command, command.createdAt), + command.createdAt, + ), userMessageEvent, ...(titleSeedEvent ? [titleSeedEvent] : []), ...(startingSessionEvent ? [startingSessionEvent] : []), @@ -3992,7 +4026,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...resetChildRequestsForUser(targetThread, turnBase, command.createdAt, { keepsPassBlock: command.trigger !== undefined || !personWrote(command), }), - ...settleCandidateBeforeUserTurn(readModel, targetThread, command), ] : []), // Words the user typed now, not a message they queued earlier, which @@ -4141,6 +4174,16 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ), }, }; + const resendOwes = + command.type === "thread.turn.resend" + ? turnStartOwesReport(readModel, targetThread, lastUserMessage, { + origin: + lastUserMessage.trigger === undefined + ? undefined + : continuedTurnMessage(targetThread, retryParticipantId, lastUserMessage.id), + answersRequest: false, + }) + : undefined; const retryTurnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = { ...withEventBase({ aggregateKind: "thread", @@ -4164,12 +4207,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(lastUserMessage.skills !== undefined ? { skills: lastUserMessage.skills } : {}), chainEpoch: targetThread.agentRequests.chainEpoch, createdAt: command.createdAt, + // A resend runs the same message again, so its turn owes what that + // message's turn owed. A retry is the user acting: theirs. + ...(resendOwes !== undefined ? { owesReport: resendOwes } : {}), }, }; // A request a wait to continue held stays open through a retry: the // retry sends the very message it is bound to, so its turn answers it. // Retrying is the user acting: agents may make requests again. return [ + ...settleWaitingAnswer( + readModel, + targetThread, + childEventBase(command, command.createdAt), + command.createdAt, + ), retrySessionEvent, retryTurnStartRequestedEvent, // A lead chat's pass, run again: still held to its ceiling. @@ -5133,6 +5185,46 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, projectId: thread.projectId, }); + // Child threads: a turn starts in the runtime. One the provider started + // with no message owes the parent a report (rule 2), every turn before + // it is over, so what is still owed for one is settled (rule 3), and a + // request waiting on background work settles with its answer so far + // (rule 4). + const startedTurnId = + command.session.status === "running" && + command.session.activeTurnId !== null && + command.session.activeTurnId !== (thread.session?.activeTurnId ?? null) + ? command.session.activeTurnId + : null; + const providerTurnStamps = + startedTurnId !== null && command.providerStartedTurn === true + ? owedReportStamps(readModel, thread) + : null; + const owedReport = + startedTurnId !== null && providerTurnStamps !== null + ? { turnId: startedTurnId, ...providerTurnStamps, createdAt: command.createdAt } + : undefined; + const turnStartEvents: ReadonlyArray<PlannedOrchestrationEvent> = + startedTurnId === null + ? [] + : [ + ...sweepOwedReports( + readModel, + thread, + (entry) => + isOwedReport(entry, { turnId: startedTurnId }) || + (command.turnMessageId !== undefined && + isOwedReport(entry, { messageId: command.turnMessageId })), + childEventBase(command, command.createdAt), + command.createdAt, + ), + ...settleWaitingAnswer( + readModel, + thread, + childEventBase(command, command.createdAt), + command.createdAt, + ), + ]; const sessionSetEvent = { ...withEventBase({ aggregateKind: "thread", @@ -5144,6 +5236,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" type: "thread.session-set", payload: { threadId: command.threadId, + ...(owedReport !== undefined ? { owedReport } : {}), session: withArmedContinueAtReset( readModel, thread, @@ -5195,9 +5288,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }) : []; if (!selectionSettled && !stoppedCheckoutMove) { - return waitEnded.length === 0 ? sessionSetEvent : [sessionSetEvent, ...waitEnded]; + return waitEnded.length === 0 && turnStartEvents.length === 0 + ? sessionSetEvent + : [...turnStartEvents, sessionSetEvent, ...waitEnded]; } return [ + ...turnStartEvents, sessionSetEvent, ...waitEnded, { diff --git a/apps/server/src/orchestration/decider.turnRetry.test.ts b/apps/server/src/orchestration/decider.turnRetry.test.ts index 6dba990dc..44ce85460 100644 --- a/apps/server/src/orchestration/decider.turnRetry.test.ts +++ b/apps/server/src/orchestration/decider.turnRetry.test.ts @@ -1105,11 +1105,12 @@ describe("a usage limit pauses a thread an agent started", () => { expect(openRequests(fired.readModel)).toEqual([]); }); - it("leaves a request waiting on background work on today's path", async () => { + it("arms nothing for a request waiting on background work, which no later turn answers", async () => { const armed = await run(model({ requestStatus: "awaiting_background" }), limitHit(true)); - // Nothing armed for it, and the follow-up's failure settles it as before. expect(threadIn(armed.readModel, childId).session?.continueAtReset).toBeUndefined(); expect(turnEnded(armed.readModel, null as unknown as MessageId)).toBeNull(); + // The follow-up's start settled the waiting request with its answer so + // far (rule 4), so its failure answers nothing. expect( childDeliveryForTurnEnd({ owned: openRequests(armed.readModel), @@ -1118,6 +1119,6 @@ describe("a usage limit pauses a thread an agent started", () => { pendingMessageId: null, awaitedBackgroundTaskCount: 0, }), - ).toMatchObject({ type: "thread.child-request.settle", outcome: "failed" }); + ).toBeNull(); }); }); diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index ec8dc6cb9..35fb0dbb4 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -121,6 +121,7 @@ import { ThreadChildRequestSubmittedPayload, ThreadChildRequestUpdatedPayload, ThreadChildRequestsResetPayload, + ThreadChildReportDroppedPayload, ThreadLeadPassRecordedPayload, ThreadSessionStopRequestedPayload, ThreadTurnInterruptRequestedPayload, @@ -1190,13 +1191,36 @@ export function projectEvent( // are not work on the child. case "thread.handed-back": return decodeForEvent(ThreadHandedBackPayload, event.payload, event.type, "payload").pipe( - Effect.map((payload) => ({ - ...nextBase, - threads: updateThread(nextBase.threads, payload.threadId, { - handedBackAt: payload.handedBackAt, - handedBackTurnId: payload.turnId, - }), - })), + Effect.map((payload) => { + const owedReport = payload.owedReport; + const withOwed = + owedReport === undefined + ? nextBase + : updateChildRequests(nextBase, payload.threadId, (state) => + childRequestStateOn.owedRemoved(state, owedReport), + ); + return { + ...withOwed, + threads: updateThread(withOwed.threads, payload.threadId, { + handedBackAt: payload.handedBackAt, + handedBackTurnId: payload.turnId, + }), + }; + }), + ); + + case "thread.child-report-dropped": + return decodeForEvent( + ThreadChildReportDroppedPayload, + event.payload, + event.type, + "payload", + ).pipe( + Effect.map((payload) => + updateChildRequests(nextBase, payload.threadId, (state) => + childRequestStateOn.owedRemoved(state, payload.owed), + ), + ), ); case "thread.parent-attachment-set": @@ -1206,23 +1230,31 @@ export function projectEvent( event.type, "payload", ).pipe( - Effect.map((payload) => ({ - ...nextBase, - threads: updateThread(nextBase.threads, payload.threadId, { - attachedToParent: payload.attached, - parentAttachmentEpoch: payload.attachmentEpoch, - // Taken back by the thread that started it over a link, which - // moved here (ThreadAdoptedFromLink): this computer's child now. - ...(payload.adoptedBy !== undefined - ? { - parentThreadId: payload.adoptedBy.parentThreadId, - parentTurnId: null, - remoteOrigin: null, - adoptedFromLink: payload.adoptedBy.fromLink, - } - : {}), - }), - })), + Effect.map((payload) => { + // A moved attachment epoch: nothing the thread owed is owed any more. + const thread = nextBase.threads.find((entry) => entry.id === payload.threadId); + const withOwed = + thread !== undefined && thread.parentAttachmentEpoch !== payload.attachmentEpoch + ? updateChildRequests(nextBase, payload.threadId, childRequestStateOn.owedCleared) + : nextBase; + return { + ...withOwed, + threads: updateThread(withOwed.threads, payload.threadId, { + attachedToParent: payload.attached, + parentAttachmentEpoch: payload.attachmentEpoch, + // Taken back by the thread that started it over a link, which + // moved here (ThreadAdoptedFromLink): this computer's child now. + ...(payload.adoptedBy !== undefined + ? { + parentThreadId: payload.adoptedBy.parentThreadId, + parentTurnId: null, + remoteOrigin: null, + adoptedFromLink: payload.adoptedBy.fromLink, + } + : {}), + }), + }; + }), ); case "thread.participant-removed": @@ -1273,7 +1305,7 @@ export function projectEvent( : thread.participants.map((entry) => entry.id === participantId ? { ...entry, modelSelection } : entry, ); - return { + const updated = { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { participants, @@ -1304,6 +1336,17 @@ export function projectEvent( : {}), }), }; + // A turn that owes the parent a report: see OwedChildReport. + const owes = payload.owesReport; + return owes === undefined + ? updated + : updateChildRequests(updated, payload.threadId, (state) => + childRequestStateOn.owedAdded(state, { + messageId: payload.messageId, + ...owes, + createdAt: payload.createdAt, + }), + ); }), ); @@ -1777,9 +1820,16 @@ export function projectEvent( : {}), }; + const owedReport = payload.owedReport; + const withOwed = + owedReport === undefined + ? nextBase + : updateChildRequests(nextBase, payload.threadId, (state) => + childRequestStateOn.owedAdded(state, owedReport), + ); return { - ...nextBase, - threads: updateThread(nextBase.threads, payload.threadId, { + ...withOwed, + threads: updateThread(withOwed.threads, payload.threadId, { session, latestTurn: session.status === "running" && session.activeTurnId !== null diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 575ee04bd..4620c01ea 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -17,5 +17,5 @@ "show_page" ], "upFrontToolDefinitionBytes": 18074, - "onDemandToolDefinitionBytes": 50678 + "onDemandToolDefinitionBytes": 50856 } diff --git a/apps/server/src/pushAlerts/pushAlertRules.test.ts b/apps/server/src/pushAlerts/pushAlertRules.test.ts index 968b0dd4a..4daacfff8 100644 --- a/apps/server/src/pushAlerts/pushAlertRules.test.ts +++ b/apps/server/src/pushAlerts/pushAlertRules.test.ts @@ -232,6 +232,17 @@ describe("pushAlertActionsForEvent", () => { }), ), ).toEqual([{ type: "cancel-thread", threadId: CHILD, kinds: ["finished", "failed"] }]); + // A later turn it reported on its own: no alert each time a child reports. + expect( + pushAlertActionsForEvent( + event("thread.handed-back", { + threadId: CHILD, + turnId: "child-turn-2", + handedBackAt: "2026-10-23T12:00:00.000Z", + owedReport: { turnId: "child-turn-2" }, + }), + ), + ).toEqual([{ type: "cancel-thread", threadId: CHILD, kinds: ["finished", "failed"] }]); expect( pushAlertActionsForEvent( event("thread.seen-set", { threadId: THREAD, at: "2026-10-23T12:00:00.000Z" }), diff --git a/apps/server/src/pushAlerts/pushAlertRules.ts b/apps/server/src/pushAlerts/pushAlertRules.ts index fd1f12f93..a21675915 100644 --- a/apps/server/src/pushAlerts/pushAlertRules.ts +++ b/apps/server/src/pushAlerts/pushAlertRules.ts @@ -264,6 +264,12 @@ export function pushAlertActionsForEvent( // The child's result went to the parent thread, whose agent carries on // with it: the parent's own alert is the one that counts. return [{ type: "cancel-thread", threadId: event.payload.childThreadId, kinds: DONE_KINDS }]; + case "thread.handed-back": + // A later turn a child took on its own went up to its parent as a + // report: the same, and no alert each time a child reports. + return event.payload.owedReport === undefined + ? [] + : [{ type: "cancel-thread", threadId: event.payload.threadId, kinds: DONE_KINDS }]; case "thread.seen-set": // Opened somewhere: no need to say it finished. return [{ type: "cancel-thread", threadId: event.payload.threadId, kinds: DONE_KINDS }]; diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index fc64ce766..a568aa580 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -10,6 +10,7 @@ import { TurnId, type OrchestrationEvent, } from "@threadlines/contracts"; +import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; import { isThreadDetailEvent } from "./ws.ts"; @@ -137,4 +138,41 @@ describe("isThreadDetailEvent", () => { expect(isThreadDetailEvent(event)).toBe(true); }); + + it("never streams a dropped report, so a client built before it can replay a thread", () => { + const threadId = ThreadId.make("thread-1"); + const at = "2026-01-01T00:00:00.000Z"; + const owed = { turnId: TurnId.make("turn-2") }; + const replay = [ + makeThreadEvent("thread.child-report-dropped", { + threadId, + owed, + turnId: owed.turnId, + createdAt: at, + }), + makeThreadEvent("thread.handed-back", { + threadId, + turnId: owed.turnId, + handedBackAt: at, + owedReport: owed, + }), + ]; + const streamed = replay.filter(isThreadDetailEvent); + expect(streamed.map((event) => event.type)).toEqual(["thread.handed-back"]); + // What a client built before the owed list knew of a handed-back event: + // the new field is extra, and extra fields are ignored when decoding. + const OlderHandedBack = Schema.Struct({ + type: Schema.Literal("thread.handed-back"), + payload: Schema.Struct({ + threadId: Schema.String, + turnId: Schema.NullOr(Schema.String), + handedBackAt: Schema.String, + }), + }); + expect(Schema.decodeUnknownSync(OlderHandedBack)(streamed[0]).payload).toEqual({ + threadId, + turnId: owed.turnId, + handedBackAt: at, + }); + }); }); diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 2c4653c98..01da164f1 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -3079,6 +3079,13 @@ export const OwedChildReport = Schema.Union([ ]); export type OwedChildReport = typeof OwedChildReport.Type; +/** Which owed report: the one keyed by the message that starts its turn, or by the turn. */ +export const OwedReportKey = Schema.Union([ + Schema.Struct({ messageId: MessageId }), + Schema.Struct({ turnId: TurnId }), +]); +export type OwedReportKey = typeof OwedReportKey.Type; + export const OrchestrationChildRequestState = Schema.Struct({ open: Schema.Array(OrchestrationChildRequest), deliveryEpoch: NonNegativeInt, @@ -4796,6 +4803,12 @@ const ThreadSessionSetCommand = Schema.Struct({ * (docs/design/agent-autonomy-no-limits.md, "Delivery rules", rule 3). */ providerStartedTurn: Schema.optional(Schema.Literal(true)), + /** + * Ingestion's word that `session.activeTurnId` is the turn this message + * asked for. The decision that marks a turn started settles every report + * the thread still owes for an earlier turn, and leaves this turn's alone. + */ + turnMessageId: Schema.optional(MessageId), createdAt: IsoDateTime, }); @@ -5649,18 +5662,32 @@ const ThreadChildRequestSettleCommand = Schema.Struct({ }); /** - * Child threads: notes went out with an agent's turn, and with them the late - * replies of children that kept working after their answer (each child's - * newest turn then counts as handed back). + * Child threads, server only: a turn a child owes its parent a report for is + * over (docs/design/agent-autonomy-no-limits.md, "Delivery rules", rules 5 + * to 8). With `text`, the report is written into the parent and queued for + * the agent that started the child, unless its delivery was cancelled + * meanwhile; without, or when cancelled, it is dropped. Either way the owed + * entry goes, so a turn is reported once. */ +const ThreadChildReportSettleCommand = Schema.Struct({ + type: Schema.Literal("thread.child-report.settle"), + commandId: CommandId, + /** The child that owes the report. */ + threadId: ThreadId, + owed: OwedReportKey, + /** The child's turn it reports on. Null: a turn that never started. */ + turnId: Schema.NullOr(TurnId), + /** What goes up. Absent: nothing to say (stopped on purpose, no reply, taken back). */ + text: Schema.optional(TrimmedNonEmptyString), + createdAt: IsoDateTime, +}); + +/** Child threads: notes went out with an agent's turn. */ const ThreadChildNotesDeliveredCommand = Schema.Struct({ type: Schema.Literal("thread.child-notes.delivered"), commandId: CommandId, threadId: ThreadId, requestIds: Schema.Array(ChildRequestId), - lateReplies: Schema.optional( - Schema.Array(Schema.Struct({ childThreadId: ThreadId, turnId: TurnId })), - ), createdAt: IsoDateTime, }); @@ -6177,6 +6204,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadMessageNotRunCommand, ThreadChildRequestUpdateCommand, ThreadChildRequestSettleCommand, + ThreadChildReportSettleCommand, ThreadChildNotesDeliveredCommand, ThreadRemoteChildUpdateCommand, ThreadRemoteCancelsDeliveredCommand, @@ -6276,6 +6304,7 @@ export const OrchestrationEventType = Schema.Literals([ "thread.child-notes-delivered", "thread.child-deliveries-cancelled", "thread.child-requests-reset", + "thread.child-report-dropped", "thread.lead-pass-recorded", "thread.remote-child-updated", "thread.remote-cancel-queued", @@ -6785,6 +6814,19 @@ export const ThreadChildNotesDeliveredPayload = Schema.Struct({ * Stop, or the thread was wrapped: its delivery epoch moves to * `deliveryEpoch`, so no answer asked for before comes back. */ +/** + * On a child, server only: a report it owed its parent was dropped, so the + * owed entry goes (docs/design/agent-autonomy-no-limits.md, rule 7). Never + * sent on the thread stream: a client built before it would fail to decode + * the batch. A delivered report removes its entry with `thread.handed-back`. + */ +export const ThreadChildReportDroppedPayload = Schema.Struct({ + threadId: ThreadId, + owed: OwedReportKey, + turnId: Schema.NullOr(TurnId), + createdAt: IsoDateTime, +}); + export const ThreadChildDeliveriesCancelledPayload = Schema.Struct({ threadId: ThreadId, deliveryEpoch: NonNegativeInt, @@ -6836,6 +6878,8 @@ export const ThreadHandedBackPayload = Schema.Struct({ threadId: ThreadId, turnId: Schema.NullOr(TurnId), handedBackAt: IsoDateTime, + /** A report the child owed went up: its entry on `childRequests.owedReports` goes. */ + owedReport: Schema.optional(OwedReportKey), }); /** On a child: separated from or put back into its parent's family. No `updatedAt`. */ @@ -7596,6 +7640,11 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.child-requests-reset"), payload: ThreadChildRequestsResetPayload, }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.child-report-dropped"), + payload: ThreadChildReportDroppedPayload, + }), Schema.Struct({ ...EventBaseFields, type: Schema.Literal("thread.lead-pass-recorded"), diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 42803b7d4..0deb77e7d 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -13,6 +13,8 @@ import { type ChildRequestStatus, type OrchestrationChildRequest, type OrchestrationChildRequestState, + type OwedChildReport, + type OwedReportKey, type RemoteChildCancel, type RemoteChildRequest, type FamilyRemoteChild, @@ -755,8 +757,47 @@ export const childRequestStateOn = { } } }, + /** A turn starts that owes the parent a report (docs/design/agent-autonomy-no-limits.md, rule 3). */ + owedAdded: ( + state: OrchestrationChildRequestState, + entry: OwedChildReport, + ): OrchestrationChildRequestState => { + const owed = state.owedReports ?? []; + return owed.some((listed) => isOwedReport(listed, entry)) + ? state + : { ...state, owedReports: [...owed, entry] }; + }, + /** An owed report was settled, delivered or dropped. */ + owedRemoved: ( + state: OrchestrationChildRequestState, + key: OwedReportKey, + ): OrchestrationChildRequestState => { + const owed = state.owedReports ?? []; + if (!owed.some((listed) => isOwedReport(listed, key))) return state; + const rest = owed.filter((listed) => !isOwedReport(listed, key)); + if (rest.length > 0) return { ...state, owedReports: rest }; + const { owedReports: _gone, ...without } = state; + return without; + }, + /** The thread's attachment epoch moved: nothing it owed is owed any more. */ + owedCleared: (state: OrchestrationChildRequestState): OrchestrationChildRequestState => { + if (state.owedReports === undefined) return state; + const { owedReports: _gone, ...without } = state; + return without; + }, }; +/** Whether an owed report is the one `key` names: by its message, or by its turn. */ +export function isOwedReport(entry: OwedReportKey, key: OwedReportKey): boolean { + return "messageId" in key + ? "messageId" in entry && entry.messageId === key.messageId + : "turnId" in entry && entry.turnId === key.turnId; +} + +/** An owed report's key alone, as events name it. */ +export const owedReportKeyOf = (entry: OwedReportKey): OwedReportKey => + "messageId" in entry ? { messageId: entry.messageId } : { turnId: entry.turnId }; + /** * Whether a child's latest finished work is exactly what went back to its * parent: then the parent's agent has read it, and with the "wrap up finished From 3ba72fedf29ebf2a112771db09068995b376422b Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:47:11 -0500 Subject: [PATCH 06/16] fix(server): settle child reports only where turns are known, and keep the parent held Fixes from the step 2 review. - A writer that marks a turn running says what started it (TurnStartedBy): the reactor names the message the provider took, ingestion names the pending message or the provider, and a check-back is always the provider's. The turn record binds the pending message only when that writer names it, so a check-back during preparation never takes a message's start or answers its request. - What earlier turns still owe is swept by ingestion alone, which has taken every earlier turn end; it keeps the starting turn's entry, the pending message's and the one bound to the turn. The decider no longer sweeps. - A child's report that a restart cut off after it left the parent's queue is sent again at startup. - The user's Stop always holds a thread with a family, so a child's later report is dropped until the user writes. - A continue is judged by its turn's first message, never one steered in. - A report's settle command id comes from its owed entry, so a resend's entry settles on its own. - A turn the provider took is never settled as unstarted. - A child keeps the agent that started it (childRequests.reportsTo) for its later reports, and a requeued message keeps its place in the queue. - The stopped-session backstop reads the session as it is now and counts a Stop only when it named that request's turn. - orchestration.replayEvents leaves out server-only events. --- .../Layers/ChildThreadReactor.test.ts | 64 ++++++ .../Layers/ChildThreadReactor.ts | 46 +++-- .../Layers/ProjectionPipeline.ts | 32 ++- .../Layers/ProviderCommandReactor.ts | 12 +- .../Layers/ProviderRuntimeIngestion.test.ts | 73 +++++++ .../Layers/ProviderRuntimeIngestion.ts | 105 +++++++--- .../orchestration/agentRequestDecisions.ts | 10 + apps/server/src/orchestration/childReports.ts | 66 ++----- .../orchestration/childThreadDelivery.test.ts | 31 +++ .../src/orchestration/childThreadDelivery.ts | 44 ++++- .../decider.childThreads.test.ts | 184 ++++++++++++++++-- apps/server/src/orchestration/decider.ts | 120 +++++++++--- apps/server/src/orchestration/projector.ts | 4 + apps/server/src/ws.test.ts | 6 +- apps/server/src/ws.ts | 13 +- packages/contracts/src/orchestration.ts | 44 +++-- packages/shared/src/queuedFollowUps.ts | 15 +- 17 files changed, 705 insertions(+), 164 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts index 1591ffb05..c2c4cb25e 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts @@ -443,6 +443,70 @@ describe("ChildThreadReactor", () => { ), ); + it.effect( + "keeps an answer waiting on background work when its runtime errors and then exits without a Stop (finding 9)", + () => { + const childWith = (status: "error" | "stopped") => + thread(CHILD, { + latestTurn: { + turnId: TurnId.make("child-turn-1"), + state: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + assistantMessageId: null, + }, + session: { + threadId: CHILD, + status, + providerName: "claudeAgent", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + awaitedBackgroundTaskCount: 0, + lastError: status === "error" ? "runtime crashed" : null, + updatedAt: now, + }, + messages: [ + { + id: MessageId.make("candidate"), + role: "assistant", + text: "Done; tests still running.", + turnId: TurnId.make("child-turn-1"), + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }); + return withReactor([parentWith([]), childWith("error")], {}, (harness) => + Effect.gen(function* () { + harness.threads.set( + PARENT, + parentWith([ + request({ + status: "awaiting_background", + candidateTurnId: TurnId.make("child-turn-1"), + }), + ]), + ); + yield* PubSub.publish(harness.events, { + type: "thread.session-set", + payload: { threadId: CHILD }, + } as unknown as OrchestrationEvent); + yield* settle; + // The runtime exits before the error's grace is up. + harness.threads.set(CHILD, childWith("stopped")); + yield* TestClock.adjust(Duration.seconds(6)); + yield* settle; + expect(settles(harness).filter((entry) => entry.outcome === "failed")).toEqual([]); + yield* TestClock.adjust(Duration.seconds(10)); + yield* settle; + expect(settles(harness)).toMatchObject([{ outcome: "answered" }]); + }), + ); + }, + ); + describe("a child errored on a usage limit (docs/design/lead-chat.md, ruling 3)", () => { const erroredTurn = TurnId.make("child-turn-1"); const asked = { diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index 3a0566dd4..7e26231fd 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -318,7 +318,7 @@ export const makeChildThreadReactor = Effect.gen(function* () { ) : Effect.void, ), - Effect.andThen(settleStoppedAnswers(parent.id, childId, status)), + Effect.andThen(settleStoppedAnswers(parent.id, childId)), Effect.ensuring(Effect.sync(() => stopChecks.delete(childId))), Effect.forkDetach, ); @@ -344,35 +344,51 @@ export const makeChildThreadReactor = Effect.gen(function* () { } }); - const settleStoppedAnswers = ( - parentId: ThreadId, - childId: ThreadId, - status: "stopped" | "error", - ) => + /** + * A child's session stopped or errored with a request mid-answer and no + * turn end settled it. Read as it is now, not as it was when the check was + * set: an error followed by an exit is a stop. Stopped on purpose only when + * a Stop named that request's own turn: a runtime that died, or the idle + * reaper, is never the user's doing (rule 6), and an answer waiting on + * background work whose runtime simply ended stands as it is (the quiet + * check settles it answered). + */ + const settleStoppedAnswers = (parentId: ThreadId, childId: ThreadId) => Effect.gen(function* () { const [parent, child] = [yield* readThread(parentId), yield* readThread(childId)]; if (parent === undefined || child === undefined) { return; } - const latestStatus = child.session?.status; - if (latestStatus !== "stopped" && latestStatus !== "error") { + const status = child.session?.status; + if (status !== "stopped" && status !== "error") { return; } - // Stopped on purpose only when a Stop named a turn: a runtime that - // died, or the idle reaper, is never the user's doing (rule 6). - const stoppedByStop = (child.session?.stopRequestedTurnId ?? null) !== null; + const stopRequestedTurnId = child.session?.stopRequestedTurnId ?? null; + const childTurns = + stopRequestedTurnId === null + ? [] + : yield* turns + .listByThreadId({ threadId: child.id }) + .pipe(Effect.orElseSucceed(() => [] as const)); + const requestTurnId = (request: OrchestrationChildRequest) => + request.status === "awaiting_background" + ? (request.candidateTurnId ?? null) + : (childTurns.find((turn) => turn.pendingMessageId === request.childMessageId)?.turnId ?? + null); for (const request of parent.childRequests.open) { if ( request.childThreadId !== childId || (request.status !== "running" && request.status !== "awaiting_background") || // Waiting to continue at a usage limit's reset: the continue answers it. - isHeldByContinueAtReset(child, request) || - // An answer waiting on background work whose runtime ended without - // a Stop stands as it is: the quiet check settles it answered. - (request.status === "awaiting_background" && status === "stopped" && !stoppedByStop) + isHeldByContinueAtReset(child, request) ) { continue; } + const stoppedByStop = + stopRequestedTurnId !== null && requestTurnId(request) === stopRequestedTurnId; + if (request.status === "awaiting_background" && status === "stopped" && !stoppedByStop) { + continue; + } yield* settle( parent, request, diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index e7e6e288c..7f7843304 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -566,6 +566,14 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti parentThreadId: event.payload.parentThreadId ?? null, parentTurnId: event.payload.parentTurnId ?? null, attachedToParent: event.payload.attachedToParent === true ? 1 : 0, + ...(event.payload.reportsTo !== undefined + ? { + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + reportsTo: event.payload.reportsTo, + }, + } + : {}), remoteOrigin: event.payload.remoteOrigin ?? null, scheduledRun: event.payload.scheduledRun ?? null, worktreeOrigin: event.payload.worktreeOrigin ?? null, @@ -2361,9 +2369,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti threadId: event.payload.threadId, turnId, }); - const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ - threadId: event.payload.threadId, - }); + // The pending message is this turn's unless the writer that marked + // it running said otherwise: a turn the provider started (a + // check-back while the message is still being prepared) leaves the + // message waiting for its own turn. + const startedBy = event.payload.turnStartedBy; + const pendingTurnStart = Option.filter( + yield* projectionTurnRepository.getPendingTurnStartByThreadId({ + threadId: event.payload.threadId, + }), + (pending) => + startedBy === undefined || + ("messageId" in startedBy && startedBy.messageId === pending.messageId), + ); if (Option.isSome(existingTurn)) { const nextState = existingTurn.value.state === "completed" || existingTurn.value.state === "error" @@ -2427,9 +2445,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti }); } - yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ - threadId: event.payload.threadId, - }); + if (Option.isSome(pendingTurnStart)) { + yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ + threadId: event.payload.threadId, + }); + } return; } diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 59ace63ec..0d4010a78 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -48,6 +48,7 @@ import { ThreadNativeSessionFellBackPayload, ThreadForkSeedOutcomePayload, type TurnId, + type TurnStartedBy, } from "@threadlines/contracts"; import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed"; import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/projectLead"; @@ -1075,11 +1076,14 @@ const make = Effect.gen(function* () { readonly threadId: ThreadId; readonly session: OrchestrationSession; readonly createdAt: string; + /** For an update that marks a turn running: the message it was asked with. */ + readonly turnStartedBy?: TurnStartedBy; }) => orchestrationEngine.dispatch({ type: "thread.session.set", commandId: serverCommandId("provider-session-set"), threadId: input.threadId, + ...(input.turnStartedBy !== undefined ? { turnStartedBy: input.turnStartedBy } : {}), // The stored error reaches the thread and phone alerts: no saved key in it. session: input.session.lastError === null || input.session.lastError === undefined @@ -1206,6 +1210,8 @@ const make = Effect.gen(function* () { const markProviderTurnAccepted = Effect.fnUntraced(function* (input: { readonly threadId: ThreadId; readonly turnId: TurnId; + /** The message the provider took this turn for. */ + readonly messageId: MessageId; }) { // The turn owes its checkpoint from now on, whether or not its thread is // a room yet: an agent added mid-turn must wait for it (checkpointHandover). @@ -1243,6 +1249,7 @@ const make = Effect.gen(function* () { updatedAt, }, createdAt: updatedAt, + turnStartedBy: { messageId: input.messageId }, }); }); @@ -3457,7 +3464,9 @@ const make = Effect.gen(function* () { return mark.pipe( Effect.andThen(handleTurnStartFailure(cause)), Effect.andThen(failHandOffForFailedStart(detail)), - Effect.andThen(settleChildWorkForUnstartedTurn(detail)), + // Only a turn the provider never took: one it took ends (and settles + // what it owes) by its own turn end, whatever failed after. + Effect.andThen(beforeSend ? settleChildWorkForUnstartedTurn(detail) : Effect.void), ); }; @@ -3798,6 +3807,7 @@ const make = Effect.gen(function* () { markProviderTurnAccepted({ threadId: event.payload.threadId, turnId: turn.turnId, + messageId: event.payload.messageId, }), ), Effect.tap(() => diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 5e37be992..59b3db893 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -1483,6 +1483,79 @@ describe("ProviderRuntimeIngestion", () => { expect(await reportsIn()).toHaveLength(1); }); + it("takes a check-back that fires while a message is being prepared for its own turn, not the message's (finding 2)", async () => { + const harness = await createHarness(); + const createdAt = "2026-01-01T00:00:00.000Z"; + const child = asThreadId("child-2"); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-child-2-create"), + threadId: child, + projectId: asProjectId("project-1"), + title: "Watch CI", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + parentThreadId: asThreadId("thread-1"), + attachedToParent: true, + createdAt, + }), + ); + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "ready", + runtimeMode: "approval-required", + threadId: child, + createdAt, + updatedAt: createdAt, + }); + // An automatic fix's message is being prepared: it owes a report. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-child-2-turn"), + threadId: child, + message: { + messageId: asMessageId("fix-message"), + role: "user", + text: "CI failed; fix it.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + // A check-back fires first. + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-child-2-check-back"), + provider: ProviderDriverKind.make("codex"), + threadId: child, + createdAt: "2026-01-01T00:00:02.000Z", + turnId: asTurnId("check-back-turn"), + payload: { trigger: { kind: "check-back" } }, + } as never); + await harness.drain(); + const owed = ( + await waitForThread( + harness.readModel, + (entry) => (entry.childRequests.owedReports ?? []).length === 2, + 10_000, + child, + ) + ).childRequests.owedReports; + // Both stay owed: the message waits for its own turn, the check-back owes its own. + expect(owed).toMatchObject([{ messageId: "fix-message" }, { turnId: "check-back-turn" }]); + const parent = (await harness.readModel()).threads.find( + (entry) => entry.id === asThreadId("thread-1"), + ); + expect(parent?.messages.filter((message) => message.fromThread !== undefined)).toEqual([]); + }); + it("maps turn started/completed events into thread session updates", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index ad7162e6e..25f7afa3d 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -25,6 +25,7 @@ import { type OrchestrationSideTurnOutcome, TurnId, type TurnTrigger, + type TurnStartedBy, type OrchestrationCheckpointSummary, type OrchestrationProposedPlan, type OrchestrationThread, @@ -81,7 +82,7 @@ import { type ProviderActivityStreamSnapshot, } from "./ProviderActivityProjection.ts"; import { handOffReplyText } from "../agentRequestDecisions.ts"; -import { childDeliveryForEndedTurn } from "../childThreadDelivery.ts"; +import { childDeliveryForEndedTurn, staleOwedReports } from "../childThreadDelivery.ts"; import { RemoteRequestTurnEnds } from "../Services/RemoteRequestTurnEnds.ts"; import { ScheduledRunTurnEnds } from "../Services/ScheduledRunTurnEnds.ts"; import { RealtimeVoiceDevices } from "../Services/RealtimeVoiceDevices.ts"; @@ -2846,6 +2847,51 @@ const make = Effect.gen(function* () { ); }); + /** + * Child threads: a turn is starting in `threadId`, and this handler has + * already taken every earlier turn's end, so a report the thread still owes + * for an earlier turn will never be settled by one (a lost turn end). It is + * settled now, as a turn that ended without being stopped (docs/design/ + * agent-autonomy-no-limits.md, rule 3). The starting turn's own entry is + * kept, and so is the entry of a message still waiting to start or already + * bound to this turn. Only this handler sweeps: a writer outside it could + * run ahead of a turn end it hasn't taken yet. + */ + const sweepOwedReports = Effect.fn("sweepOwedReports")(function* (input: { + readonly threadId: ThreadId; + readonly turnId: TurnId; + readonly pendingMessageId: MessageId | null; + readonly createdAt: string; + }) { + const child = yield* resolveThreadDetail(input.threadId); + if (child === undefined || child === null) return; + if ((child.childRequests.owedReports ?? []).length === 0) return; + const boundTurn = yield* projectionTurnRepository + .getByTurnId({ threadId: input.threadId, turnId: input.turnId }) + .pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); + const stale = staleOwedReports(child, { + turnId: input.turnId, + messageIds: [input.pendingMessageId, boundTurn?.pendingMessageId ?? null].filter( + (messageId): messageId is MessageId => messageId !== null, + ), + }); + for (const delivery of stale) { + yield* orchestrationEngine + .dispatch({ ...delivery, threadId: child.id, createdAt: input.createdAt }) + .pipe( + Effect.catch((error) => + Effect.logInfo("provider runtime ingestion could not settle a child's lost report", { + threadId: input.threadId, + detail: String(error), + }), + ), + ); + } + }); + /** * A workflow run's update, recorded as the driver reported it with who runs * it: the agent and the provider session it lives in, so Stop and transcript @@ -3407,26 +3453,31 @@ const make = Effect.gen(function* () { // A turn that starts now: the message it was asked with, or none (the // provider started it: a check-back, a goal, background work that - // finished), so the decision knows what it owes a parent (rules 2, 3). - const turnStartFields = (nextActiveTurnId: TurnId | null) => - Effect.gen(function* () { - if ( - event.type !== "turn.started" || - nextActiveTurnId === null || - (activeTurnId !== null && sameId(activeTurnId, nextActiveTurnId)) - ) { - return {}; - } - const pending = - thread.session?.status === "starting" - ? yield* projectionTurnRepository - .getPendingTurnStartByThreadId({ threadId: thread.id }) - .pipe(Effect.orElseSucceed(() => Option.none())) - : Option.none(); - return Option.isSome(pending) - ? { turnMessageId: pending.value.messageId } - : { providerStartedTurn: true as const }; - }); + // finished), so the decision knows what it owes a parent (rule 2) and + // the turn record is bound to the right message. A check-back says so + // itself, and is never the pending message's turn. + const pendingTurnStart = + event.type === "turn.started" + ? yield* projectionTurnRepository + .getPendingTurnStartByThreadId({ threadId: thread.id }) + .pipe(Effect.orElseSucceed(() => Option.none())) + : Option.none(); + const turnStartFields = (nextActiveTurnId: TurnId | null) => { + if ( + event.type !== "turn.started" || + nextActiveTurnId === null || + (activeTurnId !== null && sameId(activeTurnId, nextActiveTurnId)) + ) { + return {}; + } + const turnStartedBy: TurnStartedBy = + turnTriggerOf(event)?.kind !== "check-back" && + thread.session?.status === "starting" && + Option.isSome(pendingTurnStart) + ? { messageId: pendingTurnStart.value.messageId } + : { provider: true }; + return { turnStartedBy }; + }; const conflictsWithActiveTurn = activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); @@ -3606,6 +3657,16 @@ const make = Effect.gen(function* () { }; if (shouldApplyThreadLifecycle) { + if (event.type === "turn.started" && eventTurnId !== undefined) { + yield* sweepOwedReports({ + threadId: thread.id, + turnId: eventTurnId, + pendingMessageId: Option.isSome(pendingTurnStart) + ? pendingTurnStart.value.messageId + : null, + createdAt: now, + }); + } if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { yield* markSourceProposedPlanImplemented( acceptedTurnStartedSourcePlan.sourceThreadId, @@ -3667,7 +3728,7 @@ const make = Effect.gen(function* () { threadId: thread.id, session, ...usageLimitFields, - ...(yield* turnStartFields(nextActiveTurnId)), + ...turnStartFields(nextActiveTurnId), createdAt: now, }); yield* Ref.update(unstoredSessionReportAt, (reports) => { diff --git a/apps/server/src/orchestration/agentRequestDecisions.ts b/apps/server/src/orchestration/agentRequestDecisions.ts index 3a05a7789..5f37746b7 100644 --- a/apps/server/src/orchestration/agentRequestDecisions.ts +++ b/apps/server/src/orchestration/agentRequestDecisions.ts @@ -1011,12 +1011,22 @@ export function decideAgentChainStop( thread: OrchestrationThread, base: EventBase, createdAt: string, + options: { + /** + * The user's Stop in a thread with a family of its own (threads attached + * to it, or requests open to them): the hold always goes on, so a child's + * later report can't wake it, now or after a restart, until the user + * writes (docs/design/agent-autonomy-no-limits.md, "Stop"). + */ + readonly holdsFamily?: boolean; + } = {}, ): ReadonlyArray<PlannedEvent> { const state = thread.agentRequests; // Outside rooms only invites make requests. A thread that never had one has // no chain to end; one that did still moves its epoch, so a review's reply // already on its way to a turn is caught too. if ( + options.holdsFamily !== true && !hasAgentRecords(thread) && state.open.length === 0 && !(thread.queuedFollowUps ?? []).some(isAgentOrigin) diff --git a/apps/server/src/orchestration/childReports.ts b/apps/server/src/orchestration/childReports.ts index 269eff87f..74cdac1c4 100644 --- a/apps/server/src/orchestration/childReports.ts +++ b/apps/server/src/orchestration/childReports.ts @@ -20,6 +20,7 @@ import { } from "@threadlines/contracts"; import { isOwedReport, owedReportKeyOf } from "@threadlines/shared/childThreads"; import { activeParticipants } from "@threadlines/shared/threadParticipants"; +import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { type ChildEventBase, @@ -28,10 +29,7 @@ import { decideChildRequestSettle, personWrote, } from "./childThreadDecisions.ts"; -import { - childDeliveryForQuietCandidate, - stoppedBeforeFinishedText, -} from "./childThreadDelivery.ts"; +import { childDeliveryForQuietCandidate } from "./childThreadDelivery.ts"; import { currentAgentModel, messageAgentModels } from "./messageAgentModels.ts"; type PlannedEvent = Extract<ChildThreadDecision, ReadonlyArray<unknown>>[number]; @@ -126,8 +124,8 @@ export function turnStartOwesReport( /** * The message a continue continues: the newest message that started a turn - * for `participantId` before it, skipping continues, messages still queued - * and the continue's own message. + * for `participantId` before it, skipping continues, messages still queued, + * messages beside a turn (isTurnAside) and the continue's own message. */ export function continuedTurnMessage( thread: OrchestrationThread, @@ -139,7 +137,9 @@ export function continuedTurnMessage( (message) => message.role === "user" && message.id !== continueMessageId && - message.sideTurnId === undefined && + // A message steered into a turn (the user's, a room agent's reply) is + // never the one that started it. + !isTurnAside(message) && message.trigger === undefined && !queued.has(message.id) && (message.participantId ?? null) === participantId, @@ -184,14 +184,24 @@ export function reportDropReason( } /** - * The agent of `parent` a child's later reports go to: the one its first - * answer went to, which is the agent that started it, or the one whose turn - * started it; while that agent is still in the room. Otherwise the thread's own. + * The agent of `parent` a child's later reports go to: the one whose request + * started it (`reportsTo`, kept on the child), while that agent is still in + * the room; otherwise the thread's own. A child started before that was kept + * goes by its first answer's agent, or the one whose turn started it, as far + * as the parent's history still shows them. */ export function reportRecipient( parent: OrchestrationThread, - child: Pick<OrchestrationThread, "id" | "parentTurnId">, + child: Pick<OrchestrationThread, "id" | "parentTurnId" | "childRequests">, ): ThreadParticipantId | null { + const kept = child.childRequests.reportsTo; + if (kept !== undefined) { + const keptId = kept.participantId; + return keptId !== null && + activeParticipants(parent).some((participant) => participant.id === keptId) + ? keptId + : null; + } const firstReport = parent.messages.find( (message) => message.fromThread?.kind === "report" && @@ -326,40 +336,6 @@ export function decideChildReportSettle( ]; } -/** - * A turn is starting in `child`, so every earlier turn is over: each entry - * still owed for one (anything `keep` doesn't name) is settled first, as a - * turn that ended without being stopped (rule 3). Nothing leaves an entry - * behind for good. - */ -export function sweepOwedReports( - readModel: OrchestrationReadModel, - child: OrchestrationThread, - keep: (entry: OwedChildReport) => boolean, - baseFor: ChildEventBase, - createdAt: string, -): ReadonlyArray<PlannedEvent> { - return (child.childRequests.owedReports ?? []) - .filter((entry) => !keep(entry)) - .flatMap((entry) => { - const decision = decideChildReportSettle( - readModel, - child, - { - owed: owedReportKeyOf(entry), - turnId: "turnId" in entry ? entry.turnId : null, - text: stoppedBeforeFinishedText( - child.title, - "its turn ended without its reply reaching Threadlines", - ), - }, - baseFor, - createdAt, - ); - return "refusal" in decision ? [] : decision; - }); -} - /** * A turn is starting in `child`, whatever starts it: a parent's request still * waiting on the child's background work settles now with its answer so far diff --git a/apps/server/src/orchestration/childThreadDelivery.test.ts b/apps/server/src/orchestration/childThreadDelivery.test.ts index a5c7aa698..de13ac689 100644 --- a/apps/server/src/orchestration/childThreadDelivery.test.ts +++ b/apps/server/src/orchestration/childThreadDelivery.test.ts @@ -232,6 +232,16 @@ describe("childReportForTurnEnd", () => { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, createdAt: now, }); + // A second failure with one report still unread counts it again. + expect( + report(owing({ queuedFollowUps: [queuedReport("g1")] }), { + turnId, + outcome: "failed", + error: "Overloaded", + })?.text, + ).toBe( + "'Write the changelog' failed: Overloaded. 1 report from its threads is waiting in it unread. Send it a message with thread_send and it reads them first.", + ); const withReports = owing({ queuedFollowUps: [queuedReport("g1"), queuedReport("g2")] }); expect(report(withReports, { turnId, outcome: "failed", error: "Overloaded" })?.text).toBe( "'Write the changelog' failed: Overloaded. 2 reports from its threads are waiting in it unread. Send it a message with thread_send and it reads them first.", @@ -248,6 +258,27 @@ describe("childReportForTurnEnd", () => { ); }); + it("gives a resend's new entry for the same message a settle of its own (finding 6)", () => { + const messageId = MessageId.make("scheduled"); + const entry = (createdAt: string) => ({ + messageId, + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt, + }); + const settleFor = (createdAt: string, ended: string) => + childReportForTurnEnd({ + child: thread(CHILD, { + childRequests: { ...EMPTY_CHILD_REQUEST_STATE, owedReports: [entry(createdAt)] }, + }), + end: { turnId: TurnId.make(ended), outcome: "failed", error: "Rejected" }, + pendingMessageId: messageId, + }); + const first = settleFor("2026-10-04T10:00:00.000Z", "turn-first"); + const resent = settleFor("2026-10-04T10:01:00.000Z", "turn-resent"); + expect(first?.commandId).not.toBe(resent?.commandId); + }); + it("settles a request's turn as the request, never also as a report", () => { const requested = request("c", { status: "running" }); const child = thread(CHILD, { diff --git a/apps/server/src/orchestration/childThreadDelivery.ts b/apps/server/src/orchestration/childThreadDelivery.ts index 3d4b8d724..ee63b3ee5 100644 --- a/apps/server/src/orchestration/childThreadDelivery.ts +++ b/apps/server/src/orchestration/childThreadDelivery.ts @@ -221,9 +221,14 @@ export interface ChildReportDelivery { readonly text?: string; } -const reportSettleCommandId = (child: Pick<OrchestrationThread, "id">, key: OwedReportKey) => +/** + * The settle's command id, from the owed entry itself: the same entry settles + * once however often it is routed, and a new entry for the same message (a + * resend runs it again) is a settle of its own. + */ +const reportSettleCommandId = (child: Pick<OrchestrationThread, "id">, entry: OwedChildReport) => CommandId.make( - `server:child-report:${child.id}:${"messageId" in key ? `message:${key.messageId}` : `turn:${key.turnId}`}:settle`, + `server:child-report:${child.id}:${"messageId" in entry ? `message:${entry.messageId}` : `turn:${entry.turnId}`}:${entry.createdAt}:settle`, ); /** The owed entry a turn settles: keyed by the turn, or by the message that started it. */ @@ -284,7 +289,7 @@ export function childReportForTurnEnd(input: { : stoppedBeforeFinishedText(child.title, end.error ?? "its runtime stopped"); return { type: "thread.child-report.settle", - commandId: reportSettleCommandId(child, owed), + commandId: reportSettleCommandId(child, entry), owed, turnId: end.turnId, ...(text !== undefined ? { text } : {}), @@ -312,6 +317,37 @@ export function childDeliveryForEndedTurn(input: { return childDeliveryForTurnEnd(input) ?? childReportForTurnEnd(input); } +/** + * A turn is starting: what the thread still owes for earlier turns, each + * settled as a turn that ended without being stopped (rule 3). The starting + * turn's entry, and the entries of `messageIds` (a message still waiting to + * start, or the one bound to this turn), are kept. + */ +export function staleOwedReports( + child: OrchestrationThread, + keep: { readonly turnId: TurnId; readonly messageIds: ReadonlyArray<MessageId> }, +): ReadonlyArray<ChildReportDelivery> { + return (child.childRequests.owedReports ?? []) + .filter( + (entry) => + !isOwedReport(entry, { turnId: keep.turnId }) && + !keep.messageIds.some((messageId) => isOwedReport(entry, { messageId })), + ) + .map((entry) => { + const owed = owedReportKeyOf(entry); + return { + type: "thread.child-report.settle" as const, + commandId: reportSettleCommandId(child, entry), + owed, + turnId: "turnId" in entry ? entry.turnId : null, + text: stoppedBeforeFinishedText( + child.title, + "its turn ended without its reply reaching Threadlines", + ), + }; + }); +} + /** * An owed turn a restart cut off or left unreported (rule 14): a completed * turn is delivered, a failed one delivers its failure, and one the restart @@ -332,7 +368,7 @@ export function childReportAfterRestart( : `'${child.title}' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.`; return { type: "thread.child-report.settle", - commandId: reportSettleCommandId(child, owed), + commandId: reportSettleCommandId(child, entry), owed, turnId, ...(text !== undefined ? { text } : {}), diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index e4f6f7ba1..ed507d5c0 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -27,6 +27,7 @@ import * as Exit from "effect/Exit"; import { describe, expect, it } from "vite-plus/test"; import { childReportMessageId, isCancelledReport } from "./childThreadDecisions.ts"; +import { reportRecipient } from "./childReports.ts"; import { decideOrchestrationCommand } from "./decider.ts"; import { projectEvent } from "./projector.ts"; @@ -1940,7 +1941,7 @@ describe("decider child reports", () => { commandId: CommandId.make(`session-${turnId}`), threadId: CHILD, session: session(CHILD, { activeTurnId: TurnId.make(turnId), updatedAt: createdAt }), - providerStartedTurn: true, + turnStartedBy: { provider: true }, createdAt, }); @@ -2164,25 +2165,164 @@ describe("decider child reports", () => { ]); }); - it("settles what an earlier turn still owed when the next turn starts, once (sequence 6)", async () => { - const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; - // The runtime exited and nothing settled that turn; a message from the - // parent starts the next one. - const next = await run(owing, { + it("never settles a starting turn's own report, whichever writer marks it running first (finding 1)", async () => { + // A scheduled run's message owes a report; the reactor marks its turn + // running before ingestion does. + const family = await answeredFamily(); + const asked = await run(family, turnStart("scheduled", { scheduledTaskId: "task-1" as never })); + const accepted = await run(asked.model, { type: "thread.session.set", - commandId: CommandId.make("session-next"), + commandId: CommandId.make("session-accepted"), threadId: CHILD, - session: session(CHILD, { activeTurnId: TurnId.make("child-turn-3"), updatedAt: at(40) }), - turnMessageId: MessageId.make("next-message"), - createdAt: at(40), + session: session(CHILD, { activeTurnId: TurnId.make("child-turn-2"), updatedAt: at(21) }), + turnStartedBy: { messageId: MessageId.make("scheduled") }, + createdAt: at(21), }); - const reports = threadIn(next.model, PARENT).messages.filter( - (message) => message.fromThread?.followUp === true, - ); - expect(reports.map((message) => message.text)).toEqual([ - "'Write the changelog' stopped before it finished: its turn ended without its reply reaching Threadlines. Send it a message with thread_send to continue.", + expect(accepted.events.map((event) => event.type)).toEqual(["thread.session-set"]); + expect(threadIn(accepted.model, CHILD).childRequests.owedReports).toEqual([ + expect.objectContaining({ messageId: MessageId.make("scheduled") }), ]); - expect(threadIn(next.model, CHILD).childRequests.owedReports).toBeUndefined(); + }); + + it("sends again a report the restart cut off after it left the parent's queue (finding 3)", async () => { + const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; + const delivered = await run( + owing, + settleReport({ turnId: TurnId.make("child-turn-2") }, "child-turn-2"), + ); + const report = threadIn(delivered.model, PARENT).queuedFollowUps?.[0]; + if (report === undefined) throw new Error("no report queued"); + // Taken off the queue to start its turn, then the process stopped. + const sent = await run(delivered.model, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("send-report"), + threadId: PARENT, + messageId: report.messageId, + createdAt: at(41), + }); + const cut = { + ...sent.model, + threads: sent.model.threads.map((entry) => + entry.id === PARENT + ? { ...entry, session: session(PARENT, { status: "interrupted", activeTurnId: null }) } + : entry, + ), + }; + const restarted = await run(cut, { + type: "thread.restart.continue", + commandId: CommandId.make("restart"), + threadId: PARENT, + turnId: null, + participantId: null, + waitingOnUser: false, + continueAfterRestart: false, + messageId: MessageId.make("restart-continue"), + activityId: EventId.make("restart-activity"), + createdAt: at(50), + }); + const resent = (restarted.events as ReadonlyArray<OrchestrationEvent>).find( + (event) => event.type === "thread.turn-start-requested", + ); + expect(resent?.payload).toMatchObject({ messageId: report.messageId }); + }); + + it("holds a stopped parent with a family, so a child's later report can't wake it (finding 4)", async () => { + const family = await answeredFamily(); + const stopped = await run(family, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-parent"), + threadId: PARENT, + createdAt: at(15), + }); + expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); + // A check-back after Stop records the new epoch; its report is dropped all the same. + const owing = (await run(stopped.model, providerTurn("child-turn-2"))).model; + const settled = await run( + owing, + settleReport({ turnId: TurnId.make("child-turn-2") }, "child-turn-2"), + ); + expect(settled.events.map((event) => event.type)).toEqual(["thread.child-report-dropped"]); + }); + + it("judges a continue by the message that started the turn, not one steered into it (finding 5)", async () => { + const family = await answeredFamily(); + const typed = await run(family, turnStart("typed", { composer: "typed" })); + // A room agent's reply was steered into the person's turn: it carries the turn's id. + const withSteer = { + ...typed.model, + threads: typed.model.threads.map((entry) => + entry.id === CHILD + ? { + ...entry, + session: session(CHILD, { status: "ready", activeTurnId: null }), + messages: [ + ...entry.messages, + { + id: MessageId.make("steered-reply"), + role: "user" as const, + text: "Reviewer: looks fine.", + fromAgent: { participantId: null }, + requestKind: "reply" as const, + turnId: TurnId.make("child-turn-typed"), + streaming: false, + createdAt: at(21), + updatedAt: at(21), + }, + ], + } + : entry, + ), + }; + const continued = await run( + withSteer, + turnStart("switch", { trigger: "accountSwitch", createdAt: at(30) }), + ); + expect(owesOf(continued.events)[0]).toBeNull(); + }); + + it("keeps the agent that started a child as its reports' recipient for good (finding 8)", async () => { + const reviewer = "reviewer" as never; + const family = await familyWithRunningChild(); + expect(threadIn(family, CHILD).childRequests.reportsTo).toEqual(PRIMARY); + // The parent's history no longer shows who started it; a room agent's + // report is the oldest one left. + const rolled = { + ...family, + threads: family.threads.map((entry) => + entry.id === PARENT + ? { + ...entry, + participants: [ + { + id: reviewer, + handle: "Reviewer", + modelSelection: model, + joinedAt: now, + leftAt: null, + } as never, + ], + messages: [ + { + id: MessageId.make("reviewer-report"), + role: "user" as const, + text: "done", + participantId: reviewer, + fromThread: { + threadId: CHILD, + requestId: ChildRequestId.make("r2"), + kind: "report" as const, + }, + turnId: null, + streaming: false, + createdAt: at(5), + updatedAt: at(5), + }, + ], + } + : entry, + ), + }; + expect(reportRecipient(threadIn(rolled, PARENT), threadIn(rolled, CHILD))).toBeNull(); }); it("hands a leaving agent's queued follow-up report to the thread's own agent, and takes its answers off", async () => { @@ -2214,7 +2354,11 @@ describe("decider child reports", () => { leftAt: null, } as never, ], - queuedFollowUps: [queued("answer", false), queued("follow-up", true)], + queuedFollowUps: [ + queued("answer", false), + queued("follow-up", true), + { ...queued("newer", true), participantId: undefined }, + ], }), ]); const left = await run(room, { @@ -2224,8 +2368,10 @@ describe("decider child reports", () => { participantId: reviewer, createdAt: at(10), }); - expect(threadIn(left.model, PARENT).queuedFollowUps).toEqual([ - expect.objectContaining({ messageId: MessageId.make("follow-up") }), + // It keeps its place ahead of the newer message (rule 10). + expect(threadIn(left.model, PARENT).queuedFollowUps?.map((entry) => entry.messageId)).toEqual([ + MessageId.make("follow-up"), + MessageId.make("newer"), ]); expect(threadIn(left.model, PARENT).queuedFollowUps?.[0]?.participantId).toBeUndefined(); }); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index cdf2d98df..3d7306a56 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -51,11 +51,7 @@ import { import { secretRequestIdOfAnswerMessage } from "@threadlines/shared/secretRequests"; import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; -import { - isAttachedChild, - isOwedReport, - passCeilingRefusal, -} from "@threadlines/shared/childThreads"; +import { isAttachedChild, passCeilingRefusal } from "@threadlines/shared/childThreads"; import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; @@ -126,7 +122,6 @@ import { decideChildReportSettle, owedReportStamps, settleWaitingAnswer, - sweepOwedReports, turnStartOwesReport, } from "./childReports.ts"; import { @@ -900,6 +895,45 @@ function answersHeldableRequest( ); } +/** + * The child's report `participantId` was being started on when a restart cut + * the thread off before the provider took it: the newest message that starts + * a turn for that agent (not one still queued), a report nothing answered + * since. Null when there is none, or the thread can't take it now. + */ +function reportCutBeforeItsTurn( + thread: OrchestrationThread, + participantId: ThreadParticipantId | null, +): OrchestrationMessage | null { + const session = thread.session; + if ( + session === null || + (session.status !== "interrupted" && session.status !== "stopped") || + thread.archivedAt !== null || + (thread.move ?? null) !== null + ) { + return null; + } + const queued = new Set((thread.queuedFollowUps ?? []).map((entry) => entry.messageId)); + const index = thread.messages.findLastIndex( + (message) => + message.role === "user" && + !isTurnAside(message) && + !queued.has(message.id) && + (message.participantId ?? null) === participantId, + ); + const message = index < 0 ? undefined : thread.messages[index]; + if ( + message === undefined || + message.fromThread?.kind !== "report" || + message.notSent === true || + thread.messages.slice(index + 1).some((later) => later.role === "assistant") + ) { + return null; + } + return message; +} + /** * A report from one of its threads: its turn continues by itself at the * reset, in a thread with a parent too, whose own report of that turn went @@ -1636,6 +1670,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" occurredAt: command.createdAt, commandId: command.commandId, }); + // Child threads: the agent whose request starts it, kept for good, so + // its later reports go to that agent however long the parent's history + // grows (docs/design/agent-autonomy-no-limits.md, rule 8). + const reportsTo = + parentThreadId !== undefined && command.attachedToParent === true + ? readModel.threads + .find((entry) => entry.id === parentThreadId) + ?.childRequests.open.find( + (request) => request.kind === "start" && request.childThreadId === command.threadId, + )?.from + : undefined; const createdEvent: PlannedOrchestrationEvent = { ...threadBase(), type: "thread.created", @@ -1655,6 +1700,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ? { parentTurnId: command.parentTurnId } : {}), attachedToParent: command.attachedToParent === true, + ...(reportsTo !== undefined ? { reportsTo } : {}), } : {}), ...(command.remoteOrigin !== undefined ? { remoteOrigin: command.remoteOrigin } : {}), @@ -4796,7 +4842,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // parent's requests still queued here are taken back. Every agent's // check-backs end with it. const chainStop = [ - ...decideAgentChainStop(thread, base, command.createdAt), + ...decideAgentChainStop(thread, base, command.createdAt, { + holdsFamily: + thread.childRequests.open.length > 0 || + attachedChildrenOf(readModel, thread.id).length > 0, + }), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), ...endCheckBacksOnStop(thread, base, command.createdAt), @@ -5186,10 +5236,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" projectId: thread.projectId, }); // Child threads: a turn starts in the runtime. One the provider started - // with no message owes the parent a report (rule 2), every turn before - // it is over, so what is still owed for one is settled (rule 3), and a - // request waiting on background work settles with its answer so far - // (rule 4). + // with no message owes the parent a report (rule 2), and a request + // waiting on background work settles with its answer so far (rule 4). + // What earlier turns still owe is swept by ingestion, which sees every + // turn's end before the next turn's start. const startedTurnId = command.session.status === "running" && command.session.activeTurnId !== null && @@ -5197,7 +5247,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ? command.session.activeTurnId : null; const providerTurnStamps = - startedTurnId !== null && command.providerStartedTurn === true + startedTurnId !== null && + command.turnStartedBy !== undefined && + "provider" in command.turnStartedBy ? owedReportStamps(readModel, thread) : null; const owedReport = @@ -5207,24 +5259,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" const turnStartEvents: ReadonlyArray<PlannedOrchestrationEvent> = startedTurnId === null ? [] - : [ - ...sweepOwedReports( - readModel, - thread, - (entry) => - isOwedReport(entry, { turnId: startedTurnId }) || - (command.turnMessageId !== undefined && - isOwedReport(entry, { messageId: command.turnMessageId })), - childEventBase(command, command.createdAt), - command.createdAt, - ), - ...settleWaitingAnswer( - readModel, - thread, - childEventBase(command, command.createdAt), - command.createdAt, - ), - ]; + : settleWaitingAnswer( + readModel, + thread, + childEventBase(command, command.createdAt), + command.createdAt, + ); const sessionSetEvent = { ...withEventBase({ aggregateKind: "thread", @@ -5237,6 +5277,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" payload: { threadId: command.threadId, ...(owedReport !== undefined ? { owedReport } : {}), + ...(command.turnStartedBy !== undefined ? { turnStartedBy: command.turnStartedBy } : {}), session: withArmedContinueAtReset( readModel, thread, @@ -5620,6 +5661,25 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); + // A child's report the restart cut off before its agent ever got it + // (taken off the queue, then the process stopped) is sent again: the + // parent's agent never heard it, and nothing else brings it back. + const unheardReport = + command.turnId === null ? reportCutBeforeItsTurn(thread, command.participantId) : null; + if (unheardReport !== null) { + return yield* decideCommandSequence({ + commands: [ + { + type: "thread.turn.resend", + commandId: command.commandId, + threadId: command.threadId, + messageId: unheardReport.id, + createdAt: command.createdAt, + }, + ], + readModel, + }); + } const verdict = restartContinueVerdict(thread, { turnStarted: command.turnId !== null, participantId: command.participantId, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 35fb0dbb4..0f8816fa8 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -8,6 +8,7 @@ import type { ThreadId, } from "@threadlines/contracts"; import { + EMPTY_CHILD_REQUEST_STATE, OrchestrationCheckpointSummary, OrchestrationMessage, OrchestrationSession, @@ -478,6 +479,9 @@ export function projectEvent( parentThreadId: payload.parentThreadId ?? null, parentTurnId: payload.parentTurnId ?? null, attachedToParent: payload.attachedToParent ?? false, + ...(payload.reportsTo !== undefined + ? { childRequests: { ...EMPTY_CHILD_REQUEST_STATE, reportsTo: payload.reportsTo } } + : {}), ...(payload.remoteOrigin !== undefined ? { remoteOrigin: payload.remoteOrigin } : {}), ...(payload.scheduledRun !== undefined ? { scheduledRun: payload.scheduledRun } : {}), ...(payload.worktreeOrigin !== undefined diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index a568aa580..1e118a47d 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -13,7 +13,7 @@ import { import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; -import { isThreadDetailEvent } from "./ws.ts"; +import { isServerOnlyEvent, isThreadDetailEvent } from "./ws.ts"; function makeThreadEvent<T extends OrchestrationEvent["type"]>( type: T, @@ -157,8 +157,12 @@ describe("isThreadDetailEvent", () => { owedReport: owed, }), ]; + // Neither the thread stream nor orchestration.replayEvents sends it. const streamed = replay.filter(isThreadDetailEvent); expect(streamed.map((event) => event.type)).toEqual(["thread.handed-back"]); + expect(replay.filter((event) => !isServerOnlyEvent(event)).map((event) => event.type)).toEqual([ + "thread.handed-back", + ]); // What a client built before the owed list knew of a handed-back event: // the new field is extra, and extra fields are ignored when decoding. const OlderHandedBack = Schema.Struct({ diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 6ef37e52f..c8d4cdb7c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -245,6 +245,15 @@ const isWorkspacePathOutsideRootError = Schema.is(WorkspacePathOutsideRootError) const nowIso = Effect.map(DateTime.now, DateTime.formatIso); +/** + * Events only the server reads (its own bookkeeping, like a child's dropped + * report). They are never sent to a client in any form: a client decodes + * events against a closed union, and one built before such an event would + * fail the whole batch it came in. + */ +export const isServerOnlyEvent = (event: OrchestrationEvent): boolean => + event.type === "thread.child-report-dropped"; + export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract< OrchestrationEvent, { @@ -1659,7 +1668,9 @@ const makeCoreRpcLayer = ( }), ), ).pipe( - Effect.map((events) => Array.from(events)), + Effect.map((events) => + Array.from(events).filter((event) => !isServerOnlyEvent(event)), + ), Effect.flatMap(enrichOrchestrationEvents), Effect.mapError( (cause) => diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 01da164f1..af1f17ac7 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -3079,6 +3079,21 @@ export const OwedChildReport = Schema.Union([ ]); export type OwedChildReport = typeof OwedChildReport.Type; +/** + * What started the turn a session update marks running, from the writer that + * knows: the message it was asked with, or the provider with no message (a + * check-back, a goal, background work that finished). The decision records + * the report a provider-started turn owes a parent (docs/design/ + * agent-autonomy-no-limits.md, rules 2 and 3), and the turn record is bound + * to the pending message only when this names it. Absent: the writer can't + * tell, and the pending message, if any, is taken as the turn's. + */ +export const TurnStartedBy = Schema.Union([ + Schema.Struct({ messageId: MessageId }), + Schema.Struct({ provider: Schema.Literal(true) }), +]); +export type TurnStartedBy = typeof TurnStartedBy.Type; + /** Which owed report: the one keyed by the message that starts its turn, or by the turn. */ export const OwedReportKey = Schema.Union([ Schema.Struct({ messageId: MessageId }), @@ -3094,6 +3109,13 @@ export const OrchestrationChildRequestState = Schema.Struct({ pendingNotes: Schema.Array(ChildRequestNote), /** Reports this thread owes its parent, oldest first. Absent: none. */ owedReports: Schema.optional(Schema.Array(OwedChildReport)), + /** + * The agent of its parent whose request started this thread, kept for + * good: its later reports go to that agent while it is in the room + * (docs/design/agent-autonomy-no-limits.md, rule 8). Absent: a thread + * started before it was kept, or put back under a parent. + */ + reportsTo: Schema.optional(RoomAgentRef), /** Children on linked computers, kept after their requests settle. Absent: none. */ remoteChildren: Schema.optional(Schema.Array(RemoteChildThread)), /** Cancels still owed to linked computers, oldest first. Absent: none. */ @@ -4796,19 +4818,8 @@ const ThreadSessionSetCommand = Schema.Struct({ * usage limit with a known reset arms "Continue at reset" when it is on. */ continueAfterUsageLimits: Schema.optional(Schema.Boolean), - /** - * Ingestion's word that `session.activeTurnId` is a turn the provider - * started with no message (a check-back, background work that finished), - * so the decision can record the report it owes its parent - * (docs/design/agent-autonomy-no-limits.md, "Delivery rules", rule 3). - */ - providerStartedTurn: Schema.optional(Schema.Literal(true)), - /** - * Ingestion's word that `session.activeTurnId` is the turn this message - * asked for. The decision that marks a turn started settles every report - * the thread still owes for an earlier turn, and leaves this turn's alone. - */ - turnMessageId: Schema.optional(MessageId), + /** See TurnStartedBy. */ + turnStartedBy: Schema.optional(TurnStartedBy), createdAt: IsoDateTime, }); @@ -6431,6 +6442,8 @@ export const ThreadCreatedPayload = Schema.Struct({ attachedToParent: Schema.optional(Schema.Boolean), /** See OrchestrationThreadShell.stopsWithParent. */ stopsWithParent: Schema.optional(Schema.Literal(true)), + /** See OrchestrationChildRequestState.reportsTo. */ + reportsTo: Schema.optional(RoomAgentRef), /** See OrchestrationThreadShell.remoteOrigin. */ remoteOrigin: Schema.optional(ThreadRemoteOrigin), /** See OrchestrationThreadShell.scheduledRun. */ @@ -7201,10 +7214,11 @@ export const ThreadSessionSetPayload = Schema.Struct({ session: OrchestrationSession, /** * The report the provider-started turn now running owes the thread's - * parent: added to `childRequests.owedReports`. See ThreadSessionSetCommand's - * `providerStartedTurn`. + * parent: added to `childRequests.owedReports`. */ owedReport: Schema.optional(OwedChildReport), + /** See TurnStartedBy. */ + turnStartedBy: Schema.optional(TurnStartedBy), }); /** The user closed this error's notice; see `OrchestrationSession.lastErrorDismissedAt`. */ diff --git a/packages/shared/src/queuedFollowUps.ts b/packages/shared/src/queuedFollowUps.ts index ecd5d4420..9ecc00bc7 100644 --- a/packages/shared/src/queuedFollowUps.ts +++ b/packages/shared/src/queuedFollowUps.ts @@ -1,11 +1,12 @@ import type { OrchestrationQueuedFollowUp } from "@threadlines/contracts"; /** - * A thread's queue after `followUp` was queued: one with the same message id - * is replaced, and the new one goes last, except a message Threadlines wrote - * because the thread moved or its move didn't happen (`afterMove`, - * docs/design/fleet.md, Part 3e), which goes ahead of every message the - * user queued, behind any other one like it. Every reader of + * A thread's queue after `followUp` was queued: one already there with the + * same message id is replaced where it stands (a report handed to another + * agent keeps its turn in line); a new one goes last, except a message + * Threadlines wrote because the thread moved or its move didn't happen + * (`afterMove`, docs/design/fleet.md, Part 3e), which goes ahead of every + * message the user queued, behind any other one like it. Every reader of * `thread.follow-up-queued` (server read models, clients) applies it, so they * agree on what goes next. */ @@ -13,6 +14,10 @@ export function withQueuedFollowUp( current: ReadonlyArray<OrchestrationQueuedFollowUp>, followUp: OrchestrationQueuedFollowUp, ): ReadonlyArray<OrchestrationQueuedFollowUp> { + const at = current.findIndex((queued) => queued.messageId === followUp.messageId); + if (at >= 0 && (current[at]!.afterMove === true) === (followUp.afterMove === true)) { + return current.map((queued, index) => (index === at ? followUp : queued)); + } const rest = current.filter((queued) => queued.messageId !== followUp.messageId); if (followUp.afterMove !== true) return [...rest, followUp]; const ahead = rest.filter((queued) => queued.afterMove === true); From 34a4b7b34d47af7abab648420b9d1f27c1135aab Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:13:59 -0500 Subject: [PATCH 07/16] fix(server): bind a turn's message only when its writer names it, and put cut-off reports back Second round of fixes on step 2's review. - A session update binds the pending message to its turn only when the writer that marked the turn running named that message. An update that names nothing (a task count, a repeat) changes nothing, and a turn Claude opens by itself (claude/synthetic-turn-start, a background agent finishing) or a check-back is the provider's. - Restart no longer resends a cut-off report. Startup puts a report whose turn the provider never took back on the parent's queue, found by the exact pending message (thread.follow-up.restore). The decider leaves it off when its delivery was cancelled since, and it never touches the hold. - In an idle thread, and at startup, agents' queued messages go in the order they arrived (createdAt), so a report put back keeps its turn. - A message run again has a turn per run: restart and the stopped-session backstop take the newest turn, and a report for a turn that never started gets a request id of its own. - A child from before reportsTo reports to the thread's own agent. --- .../Layers/ChildThreadReactor.test.ts | 85 +++++++++++++ .../Layers/ChildThreadReactor.ts | 39 ++++-- .../Layers/ProjectionPipeline.test.ts | 2 + .../Layers/ProjectionPipeline.ts | 14 ++- .../Layers/ProviderCommandReactor.test.ts | 47 ++++--- .../Layers/ProviderCommandReactor.ts | 42 ++++++- .../Layers/ProviderRuntimeIngestion.test.ts | 109 +++++++++++++++- .../Layers/ProviderRuntimeIngestion.ts | 8 +- apps/server/src/orchestration/childReports.ts | 46 +++---- .../decider.childThreads.test.ts | 44 ++++--- apps/server/src/orchestration/decider.ts | 118 +++++++++--------- .../src/scheduled/scheduledTestComputer.ts | 40 +++--- packages/contracts/src/orchestration.ts | 15 +++ packages/shared/src/queuedFollowUps.ts | 20 +++ 14 files changed, 476 insertions(+), 153 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts index c2c4cb25e..a2b67cc7a 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts @@ -207,6 +207,7 @@ function withReactor<A, E>( turnId: TurnId.make("child-turn-1"), pendingMessageId: options.completedTurnFor, state: "completed", + requestedAt: now, }, ], ), @@ -353,6 +354,42 @@ describe("ChildThreadReactor", () => { ), ); + it.effect( + "after a restart, never takes an earlier run of the same message for a resend's entry (finding 6)", + () => + withReactor( + [ + parentWith([]), + thread(CHILD, { + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + // Made when the message was sent again, after its first run ended. + owedReports: [ + { + messageId: CHILD_MESSAGE, + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: "2026-10-04T10:00:30.000Z", + }, + ], + }, + }), + ], + { completedTurnFor: CHILD_MESSAGE }, + (harness) => + Effect.sync(() => { + expect( + harness.dispatched.filter((command) => command.type === "thread.child-report.settle"), + ).toMatchObject([ + { + turnId: null, + text: "'Write the changelog' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.", + }, + ]); + }), + ), + ); + it.effect("resumes a setup the previous process left unfinished", () => withReactor([parentWith([request({ status: "starting" })])], {}, (harness) => Effect.gen(function* () { @@ -759,4 +796,52 @@ describe("ChildThreadReactor", () => { }), ), ); + + it.effect( + "after a restart, sends first the report that arrived first, one put back after the cut included (finding 5)", + () => { + const report = (id: string, createdAt: string) => ({ + messageId: MessageId.make(id), + text: "done", + attachments: [], + fromThread: { + threadId: CHILD, + requestId: ChildRequestId.make(id), + kind: "report" as const, + }, + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt, + }); + return withReactor( + [ + thread(PARENT, { + session: { + threadId: PARENT, + status: "interrupted", + providerName: "claudeAgent", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + // A was put back after B: it keeps the time it first arrived. + queuedFollowUps: [ + report("report-b", "2026-10-04T10:00:02.000Z"), + report("report-a", "2026-10-04T10:00:01.000Z"), + ], + }), + ], + {}, + (harness) => + Effect.sync(() => { + expect( + harness.dispatched + .filter((command) => command.type === "thread.follow-up.send-queued") + .map((command) => (command as { messageId: string }).messageId), + ).toEqual(["report-a"]); + }), + ); + }, + ); }); diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index 7e26231fd..d25e15844 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -8,6 +8,7 @@ import { type OrchestrationEvent, type OrchestrationThread, type ThreadId, + type TurnId, } from "@threadlines/contracts"; import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; import { agentThreadsMode, agentThreadsShareWorktrees } from "@threadlines/shared/serverSettings"; @@ -23,6 +24,7 @@ import * as Stream from "effect/Stream"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { firstArrived } from "@threadlines/shared/queuedFollowUps"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { childHasLiveWork, @@ -79,6 +81,26 @@ type ReactorEvent = Extract< const nowIso = Effect.map(DateTime.now, DateTime.formatIso); +/** The newest turn a message started, asked for no earlier than `since`. */ +const newestTurnFor = < + Turn extends { + readonly turnId: TurnId | null; + readonly pendingMessageId: MessageId | null; + readonly requestedAt: string; + }, +>( + turns: ReadonlyArray<Turn>, + messageId: MessageId, + since = "", +): Turn | undefined => + turns + .filter( + (turn) => + turn.turnId !== null && turn.pendingMessageId === messageId && turn.requestedAt >= since, + ) + .toSorted((left, right) => left.requestedAt.localeCompare(right.requestedAt)) + .at(-1); + export const makeChildThreadReactor = Effect.gen(function* () { const engine = yield* OrchestrationEngineService; const snapshots = yield* ProjectionSnapshotQuery; @@ -370,11 +392,12 @@ export const makeChildThreadReactor = Effect.gen(function* () { : yield* turns .listByThreadId({ threadId: child.id }) .pipe(Effect.orElseSucceed(() => [] as const)); + // A retry or a resend runs the same message again: its newest turn is + // the one the request is on. const requestTurnId = (request: OrchestrationChildRequest) => request.status === "awaiting_background" ? (request.candidateTurnId ?? null) - : (childTurns.find((turn) => turn.pendingMessageId === request.childMessageId)?.turnId ?? - null); + : (newestTurnFor(childTurns, request.childMessageId)?.turnId ?? null); for (const request of parent.childRequests.open) { if ( request.childThreadId !== childId || @@ -533,11 +556,12 @@ export const makeChildThreadReactor = Effect.gen(function* () { .listByThreadId({ threadId: child.id }) .pipe(Effect.orElseSucceed(() => [] as const)); for (const entry of owed) { - const turn = childTurns.find((candidate) => + // A message run again (a resend) has a turn per run: only one + // asked for since this entry was made is its turn. + const turn = "turnId" in entry - ? candidate.turnId === entry.turnId - : candidate.pendingMessageId === entry.messageId && candidate.turnId !== null, - ); + ? childTurns.find((candidate) => candidate.turnId === entry.turnId) + : newestTurnFor(childTurns, entry.messageId, entry.createdAt); const delivery = childReportAfterRestart(child, entry, turn); yield* dispatch( { ...delivery, threadId: child.id, createdAt: yield* nowIso }, @@ -558,7 +582,8 @@ export const makeChildThreadReactor = Effect.gen(function* () { const shell = yield* snapshots.getShellSnapshot().pipe(Effect.orElseSucceed(() => undefined)); return (shell?.threads ?? []).flatMap((summary) => { const queued = summary.queuedFollowUps ?? []; - const report = queued.find((entry) => entry.fromThread?.kind === "report"); + // The one that arrived first: one put back after a restart keeps its time. + const report = firstArrived(queued, (entry) => entry.fromThread?.kind === "report"); const status = summary.session?.status; return report === undefined || familyWorkStopped(summary) || diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index 360adfda5..b9e4691bf 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2469,6 +2469,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta lastError: null, updatedAt: sessionSetAt, }, + // The writer that marked the turn running names its message. + turnStartedBy: { messageId }, }, }); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 7f7843304..e488ce0a1 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -2369,18 +2369,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti threadId: event.payload.threadId, turnId, }); - // The pending message is this turn's unless the writer that marked - // it running said otherwise: a turn the provider started (a - // check-back while the message is still being prepared) leaves the - // message waiting for its own turn. + // The pending message becomes this turn's only when the writer that + // marked it running named it. A turn the provider started (a + // check-back, a background agent finishing) leaves the message + // waiting for its own turn, and an update that names nothing (a + // task count, a repeat) changes nothing. const startedBy = event.payload.turnStartedBy; const pendingTurnStart = Option.filter( yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId: event.payload.threadId, }), (pending) => - startedBy === undefined || - ("messageId" in startedBy && startedBy.messageId === pending.messageId), + startedBy !== undefined && + "messageId" in startedBy && + startedBy.messageId === pending.messageId, ); if (Option.isSome(existingTurn)) { const nextState = diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index b0731db91..022822065 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -3300,11 +3300,19 @@ describe("ProviderCommandReactor", () => { ) => Effect.gen(function* () { const id = (name: string) => `${threadId}-${name}`; - const sessionSet = (name: string, session: Partial<OrchestrationSession>) => + const sessionSet = ( + name: string, + session: Partial<OrchestrationSession>, + startedBy?: string, + ) => engine.dispatch({ type: "thread.session.set", commandId: CommandId.make(id(`session-${name}`)), threadId, + // A turn's start names its message, as the reactor does. + ...(startedBy !== undefined + ? { turnStartedBy: { messageId: asMessageId(startedBy) } } + : {}), session: { threadId, status: "ready", @@ -3387,10 +3395,11 @@ describe("ProviderCommandReactor", () => { runtimeMode: "full-access", createdAt: now, }); - yield* sessionSet("caller-running", { - status: "running", - activeTurnId: asTurnId("turn-caller"), - }); + yield* sessionSet( + "caller-running", + { status: "running", activeTurnId: asTurnId("turn-caller") }, + id("work"), + ); yield* engine.dispatch({ type: "thread.follow-up.submit", commandId: CommandId.make(id("user-for-astra")), @@ -3430,20 +3439,28 @@ describe("ProviderCommandReactor", () => { }); // Astra works the user's message first, then the hand-off starts. yield* sendQueued(id("user-for-astra")); - yield* sessionSet("astra-user-running", { - status: "running", - activeTurnId: asTurnId("turn-astra-user"), - participantId: astraId, - }); + yield* sessionSet( + "astra-user-running", + { + status: "running", + activeTurnId: asTurnId("turn-astra-user"), + participantId: astraId, + }, + id("user-for-astra"), + ); yield* answer("turn-astra-user", astraId, "the logs look fine"); yield* sessionSet("astra-user-ready", { participantId: astraId }); yield* sendQueued(id("hand-off")); if (ownTurnFinished) { - yield* sessionSet("astra-hand-off-running", { - status: "running", - activeTurnId: asTurnId("turn-astra-hand-off"), - participantId: astraId, - }); + yield* sessionSet( + "astra-hand-off-running", + { + status: "running", + activeTurnId: asTurnId("turn-astra-hand-off"), + participantId: astraId, + }, + id("hand-off"), + ); yield* answer("turn-astra-hand-off", astraId, "retry tests fixed"); yield* sessionSet("astra-hand-off-ready", { participantId: astraId }); } diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 0d4010a78..e356c48a0 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -51,6 +51,7 @@ import { type TurnStartedBy, } from "@threadlines/contracts"; import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed"; +import { firstArrived } from "@threadlines/shared/queuedFollowUps"; import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/projectLead"; import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings"; import { @@ -6121,8 +6122,7 @@ const make = Effect.gen(function* () { const next = fromUser || waitsForMove ? event.payload.followUp - : ((thread.queuedFollowUps ?? []).find((entry) => isAgentOrigin(entry)) ?? - event.payload.followUp); + : (firstArrived(thread.queuedFollowUps ?? [], isAgentOrigin) ?? event.payload.followUp); if (yield* releaseSlotForQueuedAgent(thread, next)) { releasedMessageByThread.set(thread.id, next.messageId); return; @@ -7319,6 +7319,41 @@ const make = Effect.gen(function* () { }); }).pipe(Effect.ignoreCause({ log: true })); + /** + * A restart cut off a turn the provider never took, and its message was a + * child's report taken off the queue to start it: the report goes back on + * the queue as it was (`thread.follow-up.restore`), found by the exact + * message the turn was started for, so the parent's agent still hears it. + * The decider leaves it off if its delivery was cancelled meanwhile. + */ + const restoreReportCutBeforeStart = (threadId: ThreadId) => + Effect.gen(function* () { + const pending = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId }); + if (Option.isNone(pending)) return; + const thread = yield* resolveThread(threadId); + const message = thread?.messages.find((entry) => entry.id === pending.value.messageId); + if (message?.fromThread?.kind !== "report") return; + yield* orchestrationEngine + .dispatch({ + type: "thread.follow-up.restore", + commandId: CommandId.make( + `server:report-restore:${threadId}:${message.id}:${pending.value.requestedAt}`, + ), + threadId, + messageId: message.id, + createdAt: yield* nowIso, + }) + .pipe( + Effect.catch((error) => + Effect.logInfo("provider command reactor did not put a cut-off report back", { + threadId, + messageId: message.id, + detail: String(error), + }), + ), + ); + }).pipe(Effect.ignoreCause({ log: true })); + const settleSessionsFromPreviousProcess = Effect.fn("settleSessionsFromPreviousProcess")( function* () { const snapshot = yield* projectionSnapshotQuery.getShellSnapshot(); @@ -7407,6 +7442,9 @@ const make = Effect.gen(function* () { createdAt, }); yield* takeBackOutsideQueued(thread.id, createdAt); + if (session.activeTurnId === null) { + yield* restoreReportCutBeforeStart(thread.id); + } // Read now: startup expires the questions the previous process left. const activities = (yield* resolveThread(thread.id))?.activities ?? []; turnsCutByRestart.push({ diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 59b3db893..6c96bbe63 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -931,11 +931,16 @@ describe("ProviderRuntimeIngestion", () => { id: string, participantId: ThreadParticipantId | null, turn: string | null, + startedBy?: string, ) => dispatch({ type: "thread.session.set", commandId: CommandId.make(id), threadId, + // As the reactor names the message the provider took the turn for. + ...(startedBy !== undefined + ? { turnStartedBy: { messageId: asMessageId(startedBy) } } + : {}), session: { threadId, status: turn === null ? "ready" : "running", @@ -989,7 +994,7 @@ describe("ProviderRuntimeIngestion", () => { messageId: asMessageId("hand-off-request"), createdAt: now, }); - await setSession("cmd-astra-working", astraId, "turn-astra"); + await setSession("cmd-astra-working", astraId, "turn-astra", "hand-off-request"); const astraEvent = (id: string, event: Record<string, unknown>) => harness.emit({ @@ -1550,10 +1555,106 @@ describe("ProviderRuntimeIngestion", () => { ).childRequests.owedReports; // Both stay owed: the message waits for its own turn, the check-back owes its own. expect(owed).toMatchObject([{ messageId: "fix-message" }, { turnId: "check-back-turn" }]); - const parent = (await harness.readModel()).threads.find( - (entry) => entry.id === asThreadId("thread-1"), + // The check-back starts a task: a second running update that names no message. + harness.emit({ + type: "task.snapshot.updated", + eventId: asEventId("evt-child-2-task"), + provider: ProviderDriverKind.make("codex"), + threadId: child, + createdAt: "2026-01-01T00:00:03.000Z", + payload: { + tasks: [ + { taskId: "task-1", taskType: "local_bash", kind: "command", description: "Run CI" }, + ], + }, + } as never); + await harness.drain(); + // The check-back's turn ends: it settles its own report, never the message's. + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-child-2-check-back-done"), + provider: ProviderDriverKind.make("codex"), + threadId: child, + createdAt: "2026-01-01T00:00:04.000Z", + turnId: asTurnId("check-back-turn"), + payload: { state: "completed" }, + } as never); + await harness.drain(); + const after = await waitForThread( + harness.readModel, + (entry) => (entry.childRequests.owedReports ?? []).length === 1, + 10_000, + child, ); - expect(parent?.messages.filter((message) => message.fromThread !== undefined)).toEqual([]); + expect(after.childRequests.owedReports).toMatchObject([{ messageId: "fix-message" }]); + }); + + it("takes a turn Claude opens by itself while a message is being prepared for its own (finding 1)", async () => { + const harness = await createHarness(); + const createdAt = "2026-01-01T00:00:00.000Z"; + const child = asThreadId("child-3"); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-child-3-create"), + threadId: child, + projectId: asProjectId("project-1"), + title: "Watch CI", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + parentThreadId: asThreadId("thread-1"), + attachedToParent: true, + createdAt, + }), + ); + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "ready", + runtimeMode: "approval-required", + threadId: child, + createdAt, + updatedAt: createdAt, + }); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-child-3-turn"), + threadId: child, + message: { + messageId: asMessageId("fix-message-3"), + role: "user", + text: "CI failed; fix it.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + // A background agent finishes: Claude opens a turn with no trigger. + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-child-3-synthetic"), + provider: ProviderDriverKind.make("codex"), + threadId: child, + createdAt: "2026-01-01T00:00:02.000Z", + turnId: asTurnId("background-turn"), + payload: {}, + raw: { source: "claude.sdk.message", method: "claude/synthetic-turn-start", payload: {} }, + } as never); + await harness.drain(); + const owed = ( + await waitForThread( + harness.readModel, + (entry) => (entry.childRequests.owedReports ?? []).length === 2, + 10_000, + child, + ) + ).childRequests.owedReports; + expect(owed).toMatchObject([{ messageId: "fix-message-3" }, { turnId: "background-turn" }]); }); it("maps turn started/completed events into thread session updates", async () => { diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 25f7afa3d..835adcc5f 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -3470,8 +3470,14 @@ const make = Effect.gen(function* () { ) { return {}; } + // A turn Claude opened by itself (a background agent finishing, a + // check-back) says so; Threadlines starts a message's turn through + // the provider, never that way. + const providerOpened = + turnTriggerOf(event)?.kind === "check-back" || + event.raw?.method === "claude/synthetic-turn-start"; const turnStartedBy: TurnStartedBy = - turnTriggerOf(event)?.kind !== "check-back" && + !providerOpened && thread.session?.status === "starting" && Option.isSome(pendingTurnStart) ? { messageId: pendingTurnStart.value.messageId } diff --git a/apps/server/src/orchestration/childReports.ts b/apps/server/src/orchestration/childReports.ts index 74cdac1c4..baa3c6ac7 100644 --- a/apps/server/src/orchestration/childReports.ts +++ b/apps/server/src/orchestration/childReports.ts @@ -187,48 +187,32 @@ export function reportDropReason( * The agent of `parent` a child's later reports go to: the one whose request * started it (`reportsTo`, kept on the child), while that agent is still in * the room; otherwise the thread's own. A child started before that was kept - * goes by its first answer's agent, or the one whose turn started it, as far - * as the parent's history still shows them. + * reports to the thread's own agent: the parent's history can't say for sure + * who started it, and the wrong room agent is worse than the thread's own. */ export function reportRecipient( parent: OrchestrationThread, - child: Pick<OrchestrationThread, "id" | "parentTurnId" | "childRequests">, + child: Pick<OrchestrationThread, "childRequests">, ): ThreadParticipantId | null { - const kept = child.childRequests.reportsTo; - if (kept !== undefined) { - const keptId = kept.participantId; - return keptId !== null && - activeParticipants(parent).some((participant) => participant.id === keptId) - ? keptId - : null; - } - const firstReport = parent.messages.find( - (message) => - message.fromThread?.kind === "report" && - message.fromThread.threadId === child.id && - message.fromThread.environmentId === undefined, - ); - const starter = - firstReport === undefined && child.parentTurnId !== null - ? parent.messages.find( - (message) => message.role === "assistant" && message.turnId === child.parentTurnId, - ) - : undefined; - const participantId = (firstReport ?? starter)?.participantId ?? null; - return participantId !== null && - activeParticipants(parent).some((participant) => participant.id === participantId) - ? participantId + const keptId = child.childRequests.reportsTo?.participantId ?? null; + return keptId !== null && + activeParticipants(parent).some((participant) => participant.id === keptId) + ? keptId : null; } -/** The request id a follow-up report carries, derived from the child and its turn. */ +/** + * The request id a follow-up report carries, derived from the child and its + * turn; for a turn that never started, from the owed entry itself, so a + * message run again is a report of its own. + */ export const followUpReportRequestId = ( child: Pick<OrchestrationThread, "id">, turnId: TurnId | null, - key: OwedReportKey, + entry: OwedChildReport, ) => ChildRequestId.make( - `report:${child.id}:${turnId ?? ("messageId" in key ? key.messageId : key.turnId)}`, + `report:${child.id}:${turnId ?? `${"messageId" in entry ? entry.messageId : entry.turnId}:${entry.createdAt}`}`, ); /** @@ -271,7 +255,7 @@ export function decideChildReportSettle( ) { return [dropped]; } - const requestId = followUpReportRequestId(child, input.turnId, key); + const requestId = followUpReportRequestId(child, input.turnId, entry); const messageId = childReportMessageId(requestId); if (parent.messages.some((message) => message.id === messageId)) { return [dropped]; diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index ed507d5c0..1933fd948 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -2184,7 +2184,7 @@ describe("decider child reports", () => { ]); }); - it("sends again a report the restart cut off after it left the parent's queue (finding 3)", async () => { + it("puts a report a restart cut off back on the queue as it was, unless Stop came since (findings 3, 4)", async () => { const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; const delivered = await run( owing, @@ -2208,22 +2208,26 @@ describe("decider child reports", () => { : entry, ), }; - const restarted = await run(cut, { - type: "thread.restart.continue", - commandId: CommandId.make("restart"), + const restore = { + type: "thread.follow-up.restore" as const, + commandId: CommandId.make("restore"), threadId: PARENT, - turnId: null, - participantId: null, - waitingOnUser: false, - continueAfterRestart: false, - messageId: MessageId.make("restart-continue"), - activityId: EventId.make("restart-activity"), + messageId: report.messageId, createdAt: at(50), + }; + const restored = await run(cut, restore); + expect(threadIn(restored.model, PARENT).queuedFollowUps).toEqual([ + expect.objectContaining({ messageId: report.messageId, createdAt: report.createdAt }), + ]); + // Stop landed after it left the queue: it stays off, and the hold stays on. + const stopped = await run(cut, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-after-dequeue"), + threadId: PARENT, + createdAt: at(45), }); - const resent = (restarted.events as ReadonlyArray<OrchestrationEvent>).find( - (event) => event.type === "thread.turn-start-requested", - ); - expect(resent?.payload).toMatchObject({ messageId: report.messageId }); + expect(await refused(stopped.model, restore)).toBe(true); + expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); }); it("holds a stopped parent with a family, so a child's later report can't wake it (finding 4)", async () => { @@ -2323,6 +2327,18 @@ describe("decider child reports", () => { ), }; expect(reportRecipient(threadIn(rolled, PARENT), threadIn(rolled, CHILD))).toBeNull(); + // A child from before it was kept goes to the thread's own agent, not to + // whichever agent's report history still shows. + const unkept = { ...threadIn(rolled, CHILD).childRequests, reportsTo: undefined }; + expect( + reportRecipient(threadIn(rolled, PARENT), { childRequests: unkept as never }), + ).toBeNull(); + // A kept room agent still in the room gets them. + expect( + reportRecipient(threadIn(rolled, PARENT), { + childRequests: { ...unkept, reportsTo: { participantId: reviewer } } as never, + }), + ).toBe(reviewer); }); it("hands a leaving agent's queued follow-up report to the thread's own agent, and takes its answers off", async () => { diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 3d7306a56..2b3b0df79 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -895,45 +895,6 @@ function answersHeldableRequest( ); } -/** - * The child's report `participantId` was being started on when a restart cut - * the thread off before the provider took it: the newest message that starts - * a turn for that agent (not one still queued), a report nothing answered - * since. Null when there is none, or the thread can't take it now. - */ -function reportCutBeforeItsTurn( - thread: OrchestrationThread, - participantId: ThreadParticipantId | null, -): OrchestrationMessage | null { - const session = thread.session; - if ( - session === null || - (session.status !== "interrupted" && session.status !== "stopped") || - thread.archivedAt !== null || - (thread.move ?? null) !== null - ) { - return null; - } - const queued = new Set((thread.queuedFollowUps ?? []).map((entry) => entry.messageId)); - const index = thread.messages.findLastIndex( - (message) => - message.role === "user" && - !isTurnAside(message) && - !queued.has(message.id) && - (message.participantId ?? null) === participantId, - ); - const message = index < 0 ? undefined : thread.messages[index]; - if ( - message === undefined || - message.fromThread?.kind !== "report" || - message.notSent === true || - thread.messages.slice(index + 1).some((later) => later.role === "assistant") - ) { - return null; - } - return message; -} - /** * A report from one of its threads: its turn continues by itself at the * reset, in a thread with a parent too, whose own report of that turn went @@ -4315,6 +4276,66 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" return yield* decideFollowUpSubmit(targetThread, command); } + // A child's report a restart cut off before the provider took its turn + // goes back on the queue as it was (docs/design/agent-autonomy-no-limits.md, + // rule 14). It is the report's own record: nothing about the thread + // changes, the Stop hold included, and one whose delivery was cancelled + // since (Stop, a wrap, the child separated) stays off. + case "thread.follow-up.restore": { + const thread = yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const message = thread.messages.find((entry) => entry.id === command.messageId); + const fromThread = message?.fromThread; + if ( + message === undefined || + fromThread === undefined || + fromThread.kind !== "report" || + message.notSent === true || + (thread.queuedFollowUps ?? []).some((queued) => queued.messageId === message.id) + ) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "That message is not a report waiting to be heard.", + }); + } + if (isStaleReport(readModel, thread, fromThread)) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "That report's delivery was cancelled.", + }); + } + const participantId = message.participantId ?? null; + const present = + participantId !== null && + activeParticipants(thread).some((entry) => entry.id === participantId); + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.follow-up-queued", + payload: { + threadId: command.threadId, + followUp: { + messageId: message.id, + text: message.text, + attachments: message.attachments ?? [], + ...(present ? { participantId } : {}), + fromThread, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + // When it first arrived: agents' messages run in that order. + createdAt: message.createdAt, + }, + }, + }; + } + case "thread.follow-up.unqueue": { const targetThread = yield* requireThread({ readModel, @@ -5661,25 +5682,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); - // A child's report the restart cut off before its agent ever got it - // (taken off the queue, then the process stopped) is sent again: the - // parent's agent never heard it, and nothing else brings it back. - const unheardReport = - command.turnId === null ? reportCutBeforeItsTurn(thread, command.participantId) : null; - if (unheardReport !== null) { - return yield* decideCommandSequence({ - commands: [ - { - type: "thread.turn.resend", - commandId: command.commandId, - threadId: command.threadId, - messageId: unheardReport.id, - createdAt: command.createdAt, - }, - ], - readModel, - }); - } const verdict = restartContinueVerdict(thread, { turnStarted: command.turnId !== null, participantId: command.participantId, diff --git a/apps/server/src/scheduled/scheduledTestComputer.ts b/apps/server/src/scheduled/scheduledTestComputer.ts index 2af244b16..575c62f63 100644 --- a/apps/server/src/scheduled/scheduledTestComputer.ts +++ b/apps/server/src/scheduled/scheduledTestComputer.ts @@ -333,23 +333,33 @@ export const makeComputer = Effect.gen(function* () { repo.listRuns({ taskId, limit: 50 }).pipe(Effect.map((rows) => rows.toReversed())); const events = engine.readEvents(0).pipe(Stream.runCollect); - /** The thread's agent starts work on `turnId`: the turn binds to the pending message. */ + /** + * The thread's agent starts work on `turnId`: the turn binds to the pending + * message, which the update names as the reactor does once the provider + * took the turn (the thread's newest user message). + */ const turnRuns = (threadId: ThreadId, turnId: TurnId) => - engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make(`session-running:${threadId}:${turnId}`), - threadId, - session: { + Effect.gen(function* () { + const messageId = (yield* thread(threadId))?.messages.findLast( + (message) => message.role === "user", + )?.id; + return yield* engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`session-running:${threadId}:${turnId}`), threadId, - status: "running", - providerName: "codex", - providerInstanceId: CODEX, - runtimeMode: "auto", - activeTurnId: turnId, - lastError: null, - updatedAt: AT, - }, - createdAt: AT, + ...(messageId !== undefined ? { turnStartedBy: { messageId } } : {}), + session: { + threadId, + status: "running", + providerName: "codex", + providerInstanceId: CODEX, + runtimeMode: "auto", + activeTurnId: turnId, + lastError: null, + updatedAt: AT, + }, + createdAt: AT, + }); }); const turnCompletes = (threadId: ThreadId, turnId: TurnId) => diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index af1f17ac7..ef7279955 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -5672,6 +5672,20 @@ const ThreadChildRequestSettleCommand = Schema.Struct({ createdAt: IsoDateTime, }); +/** + * Child threads, server only: a child's report taken off its parent's queue + * to start a turn that a restart cut off before the provider took it goes + * back on the queue, as it was, so the parent's agent still hears it. Never + * a report whose delivery was cancelled since, and never the user writing. + */ +const ThreadFollowUpRestoreCommand = Schema.Struct({ + type: Schema.Literal("thread.follow-up.restore"), + commandId: CommandId, + threadId: ThreadId, + messageId: MessageId, + createdAt: IsoDateTime, +}); + /** * Child threads, server only: a turn a child owes its parent a report for is * over (docs/design/agent-autonomy-no-limits.md, "Delivery rules", rules 5 @@ -6216,6 +6230,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadChildRequestUpdateCommand, ThreadChildRequestSettleCommand, ThreadChildReportSettleCommand, + ThreadFollowUpRestoreCommand, ThreadChildNotesDeliveredCommand, ThreadRemoteChildUpdateCommand, ThreadRemoteCancelsDeliveredCommand, diff --git a/packages/shared/src/queuedFollowUps.ts b/packages/shared/src/queuedFollowUps.ts index 9ecc00bc7..f5ee11b9d 100644 --- a/packages/shared/src/queuedFollowUps.ts +++ b/packages/shared/src/queuedFollowUps.ts @@ -24,3 +24,23 @@ export function withQueuedFollowUp( const behind = rest.filter((queued) => queued.afterMove !== true); return [...ahead, followUp, ...behind]; } + +/** + * Of the queued messages `include` picks, the one that arrived first. In an + * idle thread agents' messages run in the order they arrived + * (docs/design/agent-autonomy-no-limits.md, rule 10), which is their + * `createdAt`, not their place: a report put back after a restart keeps the + * time it first arrived. + */ +export function firstArrived<Queued extends { readonly createdAt: string }>( + queued: ReadonlyArray<Queued>, + include: (entry: Queued) => boolean, +): Queued | undefined { + let first: Queued | undefined; + for (const entry of queued) { + if (include(entry) && (first === undefined || entry.createdAt < first.createdAt)) { + first = entry; + } + } + return first; +} From 3fddb66bce25dee3c9fbda1d827bcfe31b466ff2 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:32:37 -0500 Subject: [PATCH 08/16] fix(server): put a report whose start died back at the front, and know each run by its turn Fable's rules for findings 3 to 6 of step 2's second review (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", copied here from bf82b9eb6). - Rule A: thread.turn-start.take-back replaces thread.follow-up.restore. A child's report whose start died before the provider took it (restart, or a failed start) goes back ahead of every other agent message (putBack), or is marked not run when it can no longer be delivered (stale, held, archived, moving). Never a turn start, never the chain epoch or the hold. A thread whose report was put back gets no restart note or continue, and the turns projection drops the pending start when its message goes back or is marked not run. A put-back report waits for the next thing that moves the queue, so a start that keeps failing can't loop. - Rule B: a message has one start no turn has claimed. A new start replaces its unclaimed owed entry; the session update that names the message binds the entry to the turn and records the turn on the parent's running request (answeringTurnId). Turn ends, startup and the stopped-session backstop match by turn id; a request from before goes by its message's newest turn. At startup an entry no turn claimed is dropped. - Rule C: nothing automatic restarts a report's turn. The createdAt ordering from the last round is gone: the queue's order (with putBack) decides. --- .../Layers/ChildThreadReactor.test.ts | 167 +++++++----- .../Layers/ChildThreadReactor.ts | 31 +-- .../Layers/ProjectionPipeline.ts | 39 ++- .../Layers/ProviderCommandReactor.test.ts | 242 ++++++++++++++++++ .../Layers/ProviderCommandReactor.ts | 105 +++++--- .../Layers/ProviderRuntimeIngestion.ts | 16 +- .../orchestration/childThreadDelivery.test.ts | 21 -- .../src/orchestration/childThreadDelivery.ts | 83 ++++-- .../decider.childThreads.test.ts | 146 +++++++++-- apps/server/src/orchestration/decider.ts | 206 ++++++++++----- apps/server/src/orchestration/projector.ts | 15 +- docs/design/agent-autonomy-no-limits.md | 65 +++++ packages/contracts/src/orchestration.ts | 39 ++- packages/shared/src/childThreads.ts | 46 +++- packages/shared/src/queuedFollowUps.ts | 46 ++-- 15 files changed, 949 insertions(+), 318 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts index a2b67cc7a..3f23b73f7 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts @@ -132,6 +132,13 @@ function withReactor<A, E>( options: { readonly setupFails?: boolean; readonly completedTurnFor?: MessageId; + /** The child's turn rows, in the repository's order; overrides `completedTurnFor`. */ + readonly turns?: ReadonlyArray<{ + readonly turnId: TurnId; + readonly pendingMessageId: MessageId | null; + readonly state: string; + readonly requestedAt: string; + }>; /** "Threads can share a checkout" (default off, as the setting is). */ readonly shareWorktrees?: boolean; }, @@ -199,17 +206,19 @@ function withReactor<A, E>( Layer.succeed(ProjectionTurnRepository, { listByThreadId: () => Effect.succeed( - options.completedTurnFor === undefined - ? [] - : [ - { - threadId: CHILD, - turnId: TurnId.make("child-turn-1"), - pendingMessageId: options.completedTurnFor, - state: "completed", - requestedAt: now, - }, - ], + options.turns !== undefined + ? options.turns.map((turn) => ({ threadId: CHILD, ...turn })) + : options.completedTurnFor === undefined + ? [] + : [ + { + threadId: CHILD, + turnId: TurnId.make("child-turn-1"), + pendingMessageId: options.completedTurnFor, + state: "completed", + requestedAt: now, + }, + ], ), } as unknown as ProjectionTurnRepositoryShape), ServerSettingsService.layerTest( @@ -308,7 +317,12 @@ describe("ChildThreadReactor", () => { ...EMPTY_CHILD_REQUEST_STATE, owedReports: [ // Its turn completed before the crash: delivered. - { messageId: CHILD_MESSAGE, deliveryEpoch: 0, attachmentEpoch: 0, createdAt: now }, + { + turnId: TurnId.make("child-turn-1"), + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: now, + }, // A check-back the restart cut off. { turnId: TurnId.make("child-turn-2"), @@ -340,7 +354,7 @@ describe("ChildThreadReactor", () => { expect(reports).toMatchObject([ { threadId: CHILD, - owed: { messageId: CHILD_MESSAGE }, + owed: { turnId: TurnId.make("child-turn-1") }, turnId: TurnId.make("child-turn-1"), text: "Release notes checked again: nothing new.", }, @@ -355,7 +369,7 @@ describe("ChildThreadReactor", () => { ); it.effect( - "after a restart, never takes an earlier run of the same message for a resend's entry (finding 6)", + "after a restart, settles nothing against a message's earlier run for a resend no turn claimed (finding 6)", () => withReactor( [ @@ -363,7 +377,7 @@ describe("ChildThreadReactor", () => { thread(CHILD, { childRequests: { ...EMPTY_CHILD_REQUEST_STATE, - // Made when the message was sent again, after its first run ended. + // The resend's start, cut before any turn took it. owedReports: [ { messageId: CHILD_MESSAGE, @@ -375,17 +389,16 @@ describe("ChildThreadReactor", () => { }, }), ], + // The message's first run finished and was reported long ago. { completedTurnFor: CHILD_MESSAGE }, (harness) => Effect.sync(() => { - expect( - harness.dispatched.filter((command) => command.type === "thread.child-report.settle"), - ).toMatchObject([ - { - turnId: null, - text: "'Write the changelog' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.", - }, - ]); + const settles = harness.dispatched.filter( + (command) => command.type === "thread.child-report.settle", + ); + expect(settles).toHaveLength(1); + expect(settles[0]).toMatchObject({ owed: { messageId: CHILD_MESSAGE }, turnId: null }); + expect(settles[0]).not.toHaveProperty("text"); }), ), ); @@ -544,6 +557,66 @@ describe("ChildThreadReactor", () => { }, ); + it.effect( + "says the user stopped a retry when Stop named the retry's turn, whatever order the turns are listed in (finding 6)", + () => { + const stoppedChild = thread(CHILD, { + session: { + threadId: CHILD, + status: "stopped", + providerName: "claudeAgent", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: null, + stopRequestedTurnId: TurnId.make("retry-turn"), + updatedAt: now, + }, + }); + return withReactor( + [parentWith([]), stoppedChild], + { + // The first run (stopped on a usage limit) is listed first. + turns: [ + { + turnId: TurnId.make("first-turn"), + pendingMessageId: CHILD_MESSAGE, + state: "error", + requestedAt: "2026-10-04T09:00:00.000Z", + }, + { + turnId: TurnId.make("retry-turn"), + pendingMessageId: CHILD_MESSAGE, + state: "interrupted", + requestedAt: "2026-10-04T09:30:00.000Z", + }, + ], + }, + (harness) => + Effect.gen(function* () { + harness.threads.set( + PARENT, + parentWith([ + request({ status: "running", answeringTurnId: TurnId.make("retry-turn") }), + ]), + ); + yield* PubSub.publish(harness.events, { + type: "thread.session-set", + payload: { threadId: CHILD }, + } as unknown as OrchestrationEvent); + yield* settle; + yield* TestClock.adjust(Duration.seconds(6)); + yield* settle; + expect(settles(harness)).toMatchObject([ + { + outcome: "stopped", + reply: { text: "The user stopped 'Write the changelog' before it finished." }, + }, + ]); + }), + ); + }, + ); + describe("a child errored on a usage limit (docs/design/lead-chat.md, ruling 3)", () => { const erroredTurn = TurnId.make("child-turn-1"); const asked = { @@ -796,52 +869,4 @@ describe("ChildThreadReactor", () => { }), ), ); - - it.effect( - "after a restart, sends first the report that arrived first, one put back after the cut included (finding 5)", - () => { - const report = (id: string, createdAt: string) => ({ - messageId: MessageId.make(id), - text: "done", - attachments: [], - fromThread: { - threadId: CHILD, - requestId: ChildRequestId.make(id), - kind: "report" as const, - }, - runtimeMode: "auto-accept-edits" as const, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - createdAt, - }); - return withReactor( - [ - thread(PARENT, { - session: { - threadId: PARENT, - status: "interrupted", - providerName: "claudeAgent", - runtimeMode: "auto-accept-edits", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - // A was put back after B: it keeps the time it first arrived. - queuedFollowUps: [ - report("report-b", "2026-10-04T10:00:02.000Z"), - report("report-a", "2026-10-04T10:00:01.000Z"), - ], - }), - ], - {}, - (harness) => - Effect.sync(() => { - expect( - harness.dispatched - .filter((command) => command.type === "thread.follow-up.send-queued") - .map((command) => (command as { messageId: string }).messageId), - ).toEqual(["report-a"]); - }), - ); - }, - ); }); diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index d25e15844..a38a7f1e0 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -24,7 +24,6 @@ import * as Stream from "effect/Stream"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { firstArrived } from "@threadlines/shared/queuedFollowUps"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { childHasLiveWork, @@ -81,7 +80,10 @@ type ReactorEvent = Extract< const nowIso = Effect.map(DateTime.now, DateTime.formatIso); -/** The newest turn a message started, asked for no earlier than `since`. */ +/** + * The newest turn a message started: only for a request from before it kept + * its turn (`answeringTurnId`), never the first listed. + */ const newestTurnFor = < Turn extends { readonly turnId: TurnId | null; @@ -91,13 +93,9 @@ const newestTurnFor = < >( turns: ReadonlyArray<Turn>, messageId: MessageId, - since = "", ): Turn | undefined => turns - .filter( - (turn) => - turn.turnId !== null && turn.pendingMessageId === messageId && turn.requestedAt >= since, - ) + .filter((turn) => turn.turnId !== null && turn.pendingMessageId === messageId) .toSorted((left, right) => left.requestedAt.localeCompare(right.requestedAt)) .at(-1); @@ -392,12 +390,15 @@ export const makeChildThreadReactor = Effect.gen(function* () { : yield* turns .listByThreadId({ threadId: child.id }) .pipe(Effect.orElseSucceed(() => [] as const)); - // A retry or a resend runs the same message again: its newest turn is - // the one the request is on. + // The turn the request recorded when it started (a retry or resend + // overwrites it); a request from before that goes by its message's + // newest turn. const requestTurnId = (request: OrchestrationChildRequest) => request.status === "awaiting_background" ? (request.candidateTurnId ?? null) - : (newestTurnFor(childTurns, request.childMessageId)?.turnId ?? null); + : (request.answeringTurnId ?? + newestTurnFor(childTurns, request.childMessageId)?.turnId ?? + null); for (const request of parent.childRequests.open) { if ( request.childThreadId !== childId || @@ -556,12 +557,12 @@ export const makeChildThreadReactor = Effect.gen(function* () { .listByThreadId({ threadId: child.id }) .pipe(Effect.orElseSucceed(() => [] as const)); for (const entry of owed) { - // A message run again (a resend) has a turn per run: only one - // asked for since this entry was made is its turn. + // An entry is settled against the turn that claimed it, by id; one + // no turn claimed never started and goes with nothing said. const turn = "turnId" in entry ? childTurns.find((candidate) => candidate.turnId === entry.turnId) - : newestTurnFor(childTurns, entry.messageId, entry.createdAt); + : undefined; const delivery = childReportAfterRestart(child, entry, turn); yield* dispatch( { ...delivery, threadId: child.id, createdAt: yield* nowIso }, @@ -582,8 +583,8 @@ export const makeChildThreadReactor = Effect.gen(function* () { const shell = yield* snapshots.getShellSnapshot().pipe(Effect.orElseSucceed(() => undefined)); return (shell?.threads ?? []).flatMap((summary) => { const queued = summary.queuedFollowUps ?? []; - // The one that arrived first: one put back after a restart keeps its time. - const report = firstArrived(queued, (entry) => entry.fromThread?.kind === "report"); + // The first in line: one put back after its start died is at the front. + const report = queued.find((entry) => entry.fromThread?.kind === "report"); const status = summary.session?.status; return report === undefined || familyWorkStopped(summary) || diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index e488ce0a1..0ea4dfda9 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1496,13 +1496,24 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti yield* projectionThreadRepository.upsert({ ...existingRow.value, latestTurnId: nextLatestTurnId, - // See the in-memory projector: a provider-started turn's report. - ...(event.payload.owedReport !== undefined + // See the in-memory projector: a provider-started turn's report, + // and the turn claiming its message's report. + ...(event.payload.owedReport !== undefined || + (event.payload.owedReportBinds !== undefined && + event.payload.session.activeTurnId !== null) ? { - childRequests: childRequestStateOn.owedAdded( - existingRow.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE, - event.payload.owedReport, - ), + childRequests: ((state) => { + const owedReport = event.payload.owedReport; + const binds = event.payload.owedReportBinds; + const activeTurnId = event.payload.session.activeTurnId; + const added = + owedReport === undefined + ? state + : childRequestStateOn.owedAdded(state, owedReport); + return binds === undefined || activeTurnId === null + ? added + : childRequestStateOn.owedBound(added, binds, activeTurnId); + })(existingRow.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE), } : {}), updatedAt: event.occurredAt, @@ -2318,6 +2329,22 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn( "applyThreadTurnsProjection", )(function* (event, _attachmentSideEffects) { + // A start whose message went back on the queue, or was marked not run, + // is gone: its row must never bind to a later turn. + const startTakenBack = + event.type === "thread.continue-at-reset-skipped" + ? { threadId: event.payload.threadId, messageId: event.payload.messageId } + : event.type === "thread.follow-up-queued" && event.payload.followUp.putBack === true + ? { threadId: event.payload.threadId, messageId: event.payload.followUp.messageId } + : null; + if (startTakenBack !== null) { + const { threadId } = startTakenBack; + const pending = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId }); + if (Option.isSome(pending) && pending.value.messageId === startTakenBack.messageId) { + yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ threadId }); + } + return; + } switch (event.type) { case "thread.turn-start-requested": { yield* projectionTurnRepository.replacePendingTurnStart({ diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 022822065..08d6f0531 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1400,6 +1400,99 @@ describe("ProviderCommandReactor", () => { expect(childThread?.childRequests.owedReports).toBeUndefined(); }); + it("puts a report whose start failed back at the front, and sends it before the next one (rule A)", async () => { + const harness = await createHarness(); + const dispatch = (command: OrchestrationCommand) => + Effect.runPromise(harness.engine.dispatch(command)); + const parent = ThreadId.make("parent-report-fails"); + const child = ThreadId.make("child-report-fails"); + await dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-parent-report-fails-create"), + threadId: parent, + projectId: asProjectId("project-1"), + title: "Ship the release", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + }); + await dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-child-report-fails-create"), + threadId: child, + projectId: asProjectId("project-1"), + title: "Watch CI", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + parentThreadId: parent, + attachedToParent: true, + createdAt: "2026-01-01T00:00:00.000Z", + }); + const report = async (turn: string) => { + await dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-child-${turn}`), + threadId: child, + turnStartedBy: { provider: true }, + session: { + threadId: child, + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: asTurnId(turn), + lastError: null, + updatedAt: "2026-01-01T00:00:01.000Z", + }, + createdAt: "2026-01-01T00:00:01.000Z", + }); + await dispatch({ + type: "thread.child-report.settle", + commandId: CommandId.make(`cmd-settle-${turn}`), + threadId: child, + owed: { turnId: asTurnId(turn) }, + turnId: asTurnId(turn), + text: `CI checked (${turn}).`, + createdAt: "2026-01-01T00:00:02.000Z", + }); + return MessageId.make(`child-report:report:${child}:${turn}`); + }; + harness.startSession.mockImplementationOnce(() => + Effect.fail( + new ProviderAdapterRequestError({ + provider: "codex", + method: "thread.turn.start", + detail: "spawn failed in test harness", + }), + ), + ); + const first = await report("check-a"); + const parentThread = async () => + (await harness.readModel()).threads.find((entry) => entry.id === parent); + // Its start fails: it is back at the front, not marked not run. + await waitFor(async () => + ((await parentThread())?.queuedFollowUps ?? []).some( + (entry) => entry.messageId === first && entry.putBack === true, + ), + ); + expect( + (await parentThread())?.messages.find((message) => message.id === first)?.notSent, + ).toBeUndefined(); + expect(harness.sendTurn).not.toHaveBeenCalled(); + // The next report queued in the idle thread sends the one that waited first. + await report("check-b"); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({ + threadId: parent, + messageId: first, + }); + }); + it("hides a saved key in a provider's failure text before storing it", async () => { const secretScrubber = makeSecretScrubber(); secretScrubber.watch("STRIPE_SECRET_KEY", "sk_test_51Hq9xYz"); @@ -3517,6 +3610,155 @@ describe("ProviderCommandReactor", () => { ).toBe(false); }); + it("after a restart, puts a report cut before its start back at the front and sends it first, with no restart note (findings 3, 5)", async () => { + const now = "2026-01-01T00:00:00.000Z"; + const projectId = asProjectId("project-restart-report"); + const parent = ThreadId.make("thread-restart-report-parent"); + const user = ThreadId.make("thread-restart-user-cut"); + const child = ThreadId.make("thread-restart-report-child"); + const reportOf = (turn: string) => MessageId.make(`child-report:report:${child}:${turn}`); + const harness = await createHarness({ + beforeStart: (engine) => + Effect.gen(function* () { + yield* engine.dispatch({ + type: "project.create", + commandId: CommandId.make("cmd-project-restart-report"), + projectId, + title: "Restart Report", + workspaceRoot: PROJECT_ROOT, + defaultModelSelection: null, + createdAt: now, + }); + for (const [threadId, extra] of [ + [parent, {}], + [user, {}], + [child, { parentThreadId: parent, attachedToParent: true }], + ] as const) { + yield* engine.dispatch({ + type: "thread.create", + commandId: CommandId.make(`cmd-create-${threadId}`), + threadId, + projectId, + title: threadId === child ? "Watch CI" : "Thread", + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + branch: null, + worktreePath: null, + ...extra, + createdAt: now, + }); + } + // The child reports twice (two check-backs): A, then B. + for (const turn of ["check-a", "check-b"]) { + yield* engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-child-${turn}`), + threadId: child, + turnStartedBy: { provider: true }, + session: { + threadId: child, + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: asTurnId(turn), + lastError: null, + updatedAt: now, + }, + createdAt: now, + }); + yield* engine.dispatch({ + type: "thread.child-report.settle", + commandId: CommandId.make(`cmd-settle-${turn}`), + threadId: child, + owed: { turnId: asTurnId(turn) }, + turnId: asTurnId(turn), + text: `CI checked (${turn}).`, + createdAt: now, + }); + } + // A is taken off the queue to start the parent's turn; the process stops. + yield* engine.dispatch({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make("cmd-send-report-a"), + threadId: parent, + messageId: reportOf("check-a"), + createdAt: now, + }); + // A person's message in another thread, cut before its start too. + yield* engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-user-cut"), + threadId: user, + message: { + messageId: asMessageId("user-cut-message"), + role: "user", + text: "Rename the button.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "full-access", + composer: "typed", + createdAt: now, + }); + }), + }); + const readThread = async (threadId: ThreadId) => + (await harness.readModel()).threads.find((entry) => entry.id === threadId); + // A is back at the front, ahead of B, and the thread has no restart note. + await waitFor(async () => ((await readThread(parent))?.queuedFollowUps ?? []).length === 2); + expect((await readThread(parent))?.queuedFollowUps?.map((entry) => entry.messageId)).toEqual([ + reportOf("check-a"), + reportOf("check-b"), + ]); + // The child reactor's startup sends the first queued report, the queue's own send. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make("cmd-send-after-restart"), + threadId: parent, + messageId: reportOf("check-a"), + createdAt: now, + }), + ); + await waitFor(() => + harness.sendTurn.mock.calls.some( + ([request]) => (request as { threadId?: string }).threadId === parent, + ), + ); + await harness.drain(); + const sentToParent = () => + harness.sendTurn.mock.calls + .map(([request]) => request as { threadId: string; messageId?: string }) + .filter((request) => request.threadId === parent) + .map((request) => request.messageId); + expect(sentToParent()).toEqual([reportOf("check-a")]); + // B came after A: in a thread with no parent it goes into A's running + // turn, as reports do there, never ahead of it. + await waitFor( + async () => + (await readThread(parent))?.messages.some( + (message) => message.id === reportOf("check-b") && message.turnId !== null, + ) === true, + ); + expect(sentToParent()).toEqual([reportOf("check-a")]); + expect( + (await readThread(parent))?.activities.some( + (entry) => entry.kind === "provider.session.restart-interrupted", + ), + ).toBe(false); + // Left alone: a person's start the restart cut gets today's note. + await waitFor( + async () => + (await readThread(user))?.activities.some( + (entry) => entry.kind === "provider.session.restart-interrupted", + ) === true, + ); + }); + it("does not start an agent whose session was stopped while its turn waited to take over", async () => { const { harness, threadId, astraId, dispatch, settle, now } = await startRoomWithMessageQueuedForAstra(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index e356c48a0..1d9aee1be 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -51,7 +51,6 @@ import { type TurnStartedBy, } from "@threadlines/contracts"; import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed"; -import { firstArrived } from "@threadlines/shared/queuedFollowUps"; import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/projectLead"; import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings"; import { @@ -1208,6 +1207,46 @@ const make = Effect.gen(function* () { createdAt, }); + /** + * A child's report whose turn start died before the provider took it (a + * restart, a failed start) goes back to the front of the queue, or is + * marked not run when it can no longer be delivered + * (`thread.turn-start.take-back`, docs/design/agent-autonomy-no-limits.md, + * "Restart and turn binding", rule A). True when it is back on the queue. + * Anything that isn't a report is left alone. + */ + const takeBackReportStart = ( + threadId: ThreadId, + messageId: MessageId, + why: "restart" | "failed-start", + ) => + Effect.gen(function* () { + const thread = yield* resolveThread(threadId); + const message = thread?.messages.find((entry) => entry.id === messageId); + if (message?.fromThread?.kind !== "report") return false; + const taken = yield* orchestrationEngine + .dispatch({ + type: "thread.turn-start.take-back", + commandId: serverCommandId(`turn-start-take-back-${why}`), + threadId, + messageId, + createdAt: yield* nowIso, + }) + .pipe( + Effect.as(true), + Effect.catch((error) => + Effect.logInfo("provider command reactor could not take a report's start back", { + threadId, + messageId, + detail: String(error), + }).pipe(Effect.as(false)), + ), + ); + if (!taken) return false; + const latest = yield* resolveThread(threadId); + return (latest?.queuedFollowUps ?? []).some((queued) => queued.messageId === messageId); + }).pipe(Effect.orElseSucceed(() => false)); + const markProviderTurnAccepted = Effect.fnUntraced(function* (input: { readonly threadId: ThreadId; readonly turnId: TurnId; @@ -3466,8 +3505,15 @@ const make = Effect.gen(function* () { Effect.andThen(handleTurnStartFailure(cause)), Effect.andThen(failHandOffForFailedStart(detail)), // Only a turn the provider never took: one it took ends (and settles - // what it owes) by its own turn end, whatever failed after. - Effect.andThen(beforeSend ? settleChildWorkForUnstartedTurn(detail) : Effect.void), + // what it owes) by its own turn end, whatever failed after. A child's + // report goes back to the front of the queue instead. + Effect.andThen( + !beforeSend + ? Effect.void + : message.fromThread?.kind === "report" + ? takeBackReportStart(event.payload.threadId, event.payload.messageId, "failed-start") + : settleChildWorkForUnstartedTurn(detail), + ), ); }; @@ -6077,6 +6123,12 @@ const make = Effect.gen(function* () { if (event.payload.imported === true) { return; } + // A report put back after its start died waits for the next thing that + // moves the queue (a restart's send, a new message, a turn's end): sent + // on by itself, a start that keeps failing would never stop. + if (event.payload.followUp.putBack === true) { + return; + } // A message the user sent after Stop means they are moving on. One an // agent queued (in this thread, or from another thread) never does. const fromUser = !isAgentOrigin(event.payload.followUp); @@ -6122,7 +6174,8 @@ const make = Effect.gen(function* () { const next = fromUser || waitsForMove ? event.payload.followUp - : (firstArrived(thread.queuedFollowUps ?? [], isAgentOrigin) ?? event.payload.followUp); + : ((thread.queuedFollowUps ?? []).find((entry) => isAgentOrigin(entry)) ?? + event.payload.followUp); if (yield* releaseSlotForQueuedAgent(thread, next)) { releasedMessageByThread.set(thread.id, next.messageId); return; @@ -7320,39 +7373,17 @@ const make = Effect.gen(function* () { }).pipe(Effect.ignoreCause({ log: true })); /** - * A restart cut off a turn the provider never took, and its message was a - * child's report taken off the queue to start it: the report goes back on - * the queue as it was (`thread.follow-up.restore`), found by the exact - * message the turn was started for, so the parent's agent still hears it. - * The decider leaves it off if its delivery was cancelled meanwhile. + * A restart cut off a turn the provider never took: if the start the + * thread was waiting on (its pending start, the exact message) was a + * child's report, it is taken back. True when the report went back on the + * queue, which then sends it. */ - const restoreReportCutBeforeStart = (threadId: ThreadId) => + const takeBackReportCutByRestart = (threadId: ThreadId) => Effect.gen(function* () { const pending = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId }); - if (Option.isNone(pending)) return; - const thread = yield* resolveThread(threadId); - const message = thread?.messages.find((entry) => entry.id === pending.value.messageId); - if (message?.fromThread?.kind !== "report") return; - yield* orchestrationEngine - .dispatch({ - type: "thread.follow-up.restore", - commandId: CommandId.make( - `server:report-restore:${threadId}:${message.id}:${pending.value.requestedAt}`, - ), - threadId, - messageId: message.id, - createdAt: yield* nowIso, - }) - .pipe( - Effect.catch((error) => - Effect.logInfo("provider command reactor did not put a cut-off report back", { - threadId, - messageId: message.id, - detail: String(error), - }), - ), - ); - }).pipe(Effect.ignoreCause({ log: true })); + if (Option.isNone(pending)) return false; + return yield* takeBackReportStart(threadId, pending.value.messageId, "restart"); + }).pipe(Effect.orElseSucceed(() => false)); const settleSessionsFromPreviousProcess = Effect.fn("settleSessionsFromPreviousProcess")( function* () { @@ -7442,8 +7473,10 @@ const make = Effect.gen(function* () { createdAt, }); yield* takeBackOutsideQueued(thread.id, createdAt); - if (session.activeTurnId === null) { - yield* restoreReportCutBeforeStart(thread.id); + // A child's report cut before its start goes back on the queue and is + // sent from there: no restart note and no continue for it. + if (session.activeTurnId === null && (yield* takeBackReportCutByRestart(thread.id))) { + continue; } // Read now: startup expires the questions the previous process left. const activities = (yield* resolveThread(thread.id))?.activities ?? []; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 835adcc5f..04ec3a245 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -2853,9 +2853,9 @@ const make = Effect.gen(function* () { * for an earlier turn will never be settled by one (a lost turn end). It is * settled now, as a turn that ended without being stopped (docs/design/ * agent-autonomy-no-limits.md, rule 3). The starting turn's own entry is - * kept, and so is the entry of a message still waiting to start or already - * bound to this turn. Only this handler sweeps: a writer outside it could - * run ahead of a turn end it hasn't taken yet. + * kept, and so is the entry of a message still waiting to start (its turn + * claims it when it starts). Only this handler sweeps: a writer outside it + * could run ahead of a turn end it hasn't taken yet. */ const sweepOwedReports = Effect.fn("sweepOwedReports")(function* (input: { readonly threadId: ThreadId; @@ -2866,17 +2866,9 @@ const make = Effect.gen(function* () { const child = yield* resolveThreadDetail(input.threadId); if (child === undefined || child === null) return; if ((child.childRequests.owedReports ?? []).length === 0) return; - const boundTurn = yield* projectionTurnRepository - .getByTurnId({ threadId: input.threadId, turnId: input.turnId }) - .pipe( - Effect.map(Option.getOrUndefined), - Effect.orElseSucceed(() => undefined), - ); const stale = staleOwedReports(child, { turnId: input.turnId, - messageIds: [input.pendingMessageId, boundTurn?.pendingMessageId ?? null].filter( - (messageId): messageId is MessageId => messageId !== null, - ), + messageIds: input.pendingMessageId === null ? [] : [input.pendingMessageId], }); for (const delivery of stale) { yield* orchestrationEngine diff --git a/apps/server/src/orchestration/childThreadDelivery.test.ts b/apps/server/src/orchestration/childThreadDelivery.test.ts index de13ac689..a5a8afb23 100644 --- a/apps/server/src/orchestration/childThreadDelivery.test.ts +++ b/apps/server/src/orchestration/childThreadDelivery.test.ts @@ -258,27 +258,6 @@ describe("childReportForTurnEnd", () => { ); }); - it("gives a resend's new entry for the same message a settle of its own (finding 6)", () => { - const messageId = MessageId.make("scheduled"); - const entry = (createdAt: string) => ({ - messageId, - deliveryEpoch: 0, - attachmentEpoch: 0, - createdAt, - }); - const settleFor = (createdAt: string, ended: string) => - childReportForTurnEnd({ - child: thread(CHILD, { - childRequests: { ...EMPTY_CHILD_REQUEST_STATE, owedReports: [entry(createdAt)] }, - }), - end: { turnId: TurnId.make(ended), outcome: "failed", error: "Rejected" }, - pendingMessageId: messageId, - }); - const first = settleFor("2026-10-04T10:00:00.000Z", "turn-first"); - const resent = settleFor("2026-10-04T10:01:00.000Z", "turn-resent"); - expect(first?.commandId).not.toBe(resent?.commandId); - }); - it("settles a request's turn as the request, never also as a report", () => { const requested = request("c", { status: "running" }); const child = thread(CHILD, { diff --git a/apps/server/src/orchestration/childThreadDelivery.ts b/apps/server/src/orchestration/childThreadDelivery.ts index ee63b3ee5..e314f6497 100644 --- a/apps/server/src/orchestration/childThreadDelivery.ts +++ b/apps/server/src/orchestration/childThreadDelivery.ts @@ -29,7 +29,24 @@ import { turnStartingMessage } from "./continueTurns.ts"; export type ChildDeliveryRequest = Pick< OrchestrationChildRequest, "requestId" | "status" | "childMessageId" | "candidateTurnId" ->; +> & + Partial<Pick<OrchestrationChildRequest, "answeringTurnId">>; + +/** + * Whether a running request is answered by the ended turn: the turn it + * recorded when it started ("Restart and turn binding", rule B). A request + * from before that was kept (and a linked computer's ledger, which keeps + * none) goes by the message that started the ended turn. + */ +const answersRequest = ( + request: ChildDeliveryRequest, + turnId: TurnId, + pendingMessageId: MessageId | null, +) => + request.status === "running" && + (request.answeringTurnId !== undefined + ? request.answeringTurnId === turnId + : pendingMessageId !== null && request.childMessageId === pendingMessageId); /** How a child's turn ended. */ export interface ChildTurnEnd { @@ -143,12 +160,7 @@ export function childDeliveryForTurnEnd(input: { }): ChildDelivery | null { const { owned, child, end } = input; const request = - owned.find( - (entry) => - input.pendingMessageId !== null && - entry.status === "running" && - entry.childMessageId === input.pendingMessageId, - ) ?? + owned.find((entry) => answersRequest(entry, end.turnId, input.pendingMessageId)) ?? (input.continuesWaitingAnswer === true && input.pendingMessageId === null ? owned.find( (entry) => @@ -231,17 +243,17 @@ const reportSettleCommandId = (child: Pick<OrchestrationThread, "id">, entry: Ow `server:child-report:${child.id}:${"messageId" in entry ? `message:${entry.messageId}` : `turn:${entry.turnId}`}:${entry.createdAt}:settle`, ); -/** The owed entry a turn settles: keyed by the turn, or by the message that started it. */ +/** + * The owed entry a turn settles: the one keyed by that turn. A message's + * entry is keyed by the turn that took it from the moment it started + * ("Restart and turn binding", rule B), so no turn is ever matched by its + * message. + */ export function owedEntryForTurn( child: Pick<OrchestrationThread, "childRequests">, turnId: TurnId, - pendingMessageId: MessageId | null, ): OwedChildReport | undefined { - return (child.childRequests.owedReports ?? []).find( - (entry) => - isOwedReport(entry, { turnId }) || - (pendingMessageId !== null && isOwedReport(entry, { messageId: pendingMessageId })), - ); + return (child.childRequests.owedReports ?? []).find((entry) => isOwedReport(entry, { turnId })); } /** @@ -276,7 +288,7 @@ export function childReportForTurnEnd(input: { readonly pendingMessageId: MessageId | null; }): ChildReportDelivery | null { const { child, end } = input; - const entry = owedEntryForTurn(child, end.turnId, input.pendingMessageId); + const entry = owedEntryForTurn(child, end.turnId); if (entry === undefined) return null; const owed = owedReportKeyOf(entry); const text = @@ -349,23 +361,27 @@ export function staleOwedReports( } /** - * An owed turn a restart cut off or left unreported (rule 14): a completed - * turn is delivered, a failed one delivers its failure, and one the restart - * cut off (or that never started) says so. + * An owed entry a restart left unsettled (rule 14). One bound to a turn is + * settled against that turn alone: a completed turn is delivered, a failed + * one delivers its failure, and one the restart cut off says so. One no turn + * claimed never started: it goes with nothing said (its message's start was + * put back or marked not run, "Restart and turn binding", rule A). */ export function childReportAfterRestart( child: OrchestrationThread, entry: OwedChildReport, - turn: { readonly turnId: TurnId | null; readonly state: string } | undefined, + turn: { readonly state: string } | undefined, ): ChildReportDelivery { const owed = owedReportKeyOf(entry); - const turnId = turn?.turnId ?? ("turnId" in entry ? entry.turnId : null); + const turnId = "turnId" in entry ? entry.turnId : null; const text = - turn?.state === "completed" && turnId !== null - ? reportReplyText(child, turnId) - : turn?.state === "error" - ? reportFailureText(child, child.session?.lastError ?? "Its turn did not finish.") - : `'${child.title}' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.`; + turnId === null + ? undefined + : turn?.state === "completed" + ? reportReplyText(child, turnId) + : turn?.state === "error" + ? reportFailureText(child, child.session?.lastError ?? "Its turn did not finish.") + : `'${child.title}' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.`; return { type: "thread.child-report.settle", commandId: reportSettleCommandId(child, entry), @@ -494,11 +510,22 @@ export function finishedTurnAfterRestart( ): TurnId | null { const candidateEnded = childTurns.find((entry) => entry.turnId === request.candidateTurnId)?.completedAt ?? ""; + // The turn the request recorded; a request from before that was kept goes + // by the newest turn its message started, never the first listed. + const answering = + request.answeringTurnId !== undefined + ? childTurns.find((turn) => turn.turnId === request.answeringTurnId) + : childTurns + .filter( + (turn) => turn.turnId !== null && turn.pendingMessageId === request.childMessageId, + ) + .toSorted((left, right) => left.requestedAt.localeCompare(right.requestedAt)) + .at(-1); const finishedTurn = request.status === "running" - ? childTurns.find( - (turn) => turn.pendingMessageId === request.childMessageId && turn.state === "completed", - ) + ? answering?.state === "completed" + ? answering + : undefined : request.status === "awaiting_background" && options.continuesWaitingAnswer === true ? childTurns .filter( diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 1933fd948..0e86651f2 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -2179,12 +2179,14 @@ describe("decider child reports", () => { createdAt: at(21), }); expect(accepted.events.map((event) => event.type)).toEqual(["thread.session-set"]); + // The turn claims it: from here on the entry is known by the turn. expect(threadIn(accepted.model, CHILD).childRequests.owedReports).toEqual([ - expect.objectContaining({ messageId: MessageId.make("scheduled") }), + expect.objectContaining({ turnId: TurnId.make("child-turn-2") }), ]); }); - it("puts a report a restart cut off back on the queue as it was, unless Stop came since (findings 3, 4)", async () => { + /** A follow-up report delivered into the parent, then taken off its queue to start its turn. */ + async function reportStarting() { const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; const delivered = await run( owing, @@ -2192,7 +2194,6 @@ describe("decider child reports", () => { ); const report = threadIn(delivered.model, PARENT).queuedFollowUps?.[0]; if (report === undefined) throw new Error("no report queued"); - // Taken off the queue to start its turn, then the process stopped. const sent = await run(delivered.model, { type: "thread.follow-up.send-queued", commandId: CommandId.make("send-report"), @@ -2200,34 +2201,68 @@ describe("decider child reports", () => { messageId: report.messageId, createdAt: at(41), }); - const cut = { - ...sent.model, - threads: sent.model.threads.map((entry) => + return { model: sent.model, report }; + } + + const takeBack = (messageId: MessageId) => ({ + type: "thread.turn-start.take-back" as const, + commandId: CommandId.make("take-back"), + threadId: PARENT, + messageId, + createdAt: at(50), + }); + + it("puts a report whose start died back at the front, ahead of a newer agent message (finding 3)", async () => { + const { model: starting, report } = await reportStarting(); + // Another agent's message arrived meanwhile. + const newer = { + ...starting, + threads: starting.threads.map((entry) => entry.id === PARENT - ? { ...entry, session: session(PARENT, { status: "interrupted", activeTurnId: null }) } + ? { + ...entry, + session: session(PARENT, { status: "interrupted", activeTurnId: null }), + queuedFollowUps: [ + { + messageId: MessageId.make("newer-report"), + text: "later", + attachments: [], + fromThread: { + threadId: CHILD, + requestId: ChildRequestId.make("newer"), + kind: "report" as const, + }, + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(45), + }, + ], + } : entry, ), }; - const restore = { - type: "thread.follow-up.restore" as const, - commandId: CommandId.make("restore"), - threadId: PARENT, - messageId: report.messageId, - createdAt: at(50), - }; - const restored = await run(cut, restore); - expect(threadIn(restored.model, PARENT).queuedFollowUps).toEqual([ - expect.objectContaining({ messageId: report.messageId, createdAt: report.createdAt }), + const taken = await run(newer, takeBack(report.messageId)); + expect(taken.events.map((event) => event.type)).toEqual(["thread.follow-up-queued"]); + expect(threadIn(taken.model, PARENT).queuedFollowUps?.map((entry) => entry.messageId)).toEqual([ + report.messageId, + MessageId.make("newer-report"), ]); - // Stop landed after it left the queue: it stays off, and the hold stays on. - const stopped = await run(cut, { + }); + + it("marks a report not run when Stop came after it left the queue, and starts nothing (finding 4)", async () => { + const { model: starting, report } = await reportStarting(); + const stopped = await run(starting, { type: "thread.turn.interrupt", commandId: CommandId.make("stop-after-dequeue"), threadId: PARENT, createdAt: at(45), }); - expect(await refused(stopped.model, restore)).toBe(true); - expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); + const taken = await run(stopped.model, takeBack(report.messageId)); + expect(taken.events.map((event) => event.type)).toEqual(["thread.continue-at-reset-skipped"]); + const parent = threadIn(taken.model, PARENT); + expect(parent.queuedFollowUps ?? []).toEqual([]); + expect(parent.messages.find((message) => message.id === report.messageId)?.notSent).toBe(true); + expect(parent.agentRequests.hold).toBe(true); }); it("holds a stopped parent with a family, so a child's later report can't wake it (finding 4)", async () => { @@ -2341,6 +2376,75 @@ describe("decider child reports", () => { ).toBe(reviewer); }); + it("knows each run of a message by its own turn: a resend reports once, for its own turn (finding 6)", async () => { + const family = await answeredFamily(); + const named = (turn: string, createdAt: string) => ({ + type: "thread.session.set" as const, + commandId: CommandId.make(`session-${turn}`), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make(turn), updatedAt: createdAt }), + turnStartedBy: { messageId: MessageId.make("scheduled") }, + createdAt, + }); + const idle = (model: OrchestrationReadModel) => ({ + ...model, + threads: model.threads.map((entry) => + entry.id === CHILD + ? { ...entry, session: session(CHILD, { status: "ready", activeTurnId: null }) } + : entry, + ), + }); + // First run: its turn claims the message's entry and reports. + const asked = await run(family, turnStart("scheduled", { scheduledTaskId: "task-1" as never })); + const first = await run(asked.model, named("run-1", at(21))); + const reported = await run( + idle(first.model), + settleReport({ turnId: TurnId.make("run-1") }, "run-1", "First run.", at(22)), + ); + // A resend runs the same message: a new unclaimed entry, then its own turn. + const resent = await run(reported.model, { + type: "thread.turn.resend", + commandId: CommandId.make("resend"), + threadId: CHILD, + messageId: MessageId.make("scheduled"), + createdAt: at(23), + }); + expect(threadIn(resent.model, CHILD).childRequests.owedReports).toEqual([ + expect.objectContaining({ messageId: MessageId.make("scheduled") }), + ]); + const second = await run(resent.model, named("run-2", at(24))); + expect(threadIn(second.model, CHILD).childRequests.owedReports).toEqual([ + expect.objectContaining({ turnId: TurnId.make("run-2") }), + ]); + // The first run's turn has nothing left to settle; the second reports once. + expect( + await refused(second.model, settleReport({ turnId: TurnId.make("run-1") }, "run-1")), + ).toBe(true); + const done = await run( + idle(second.model), + settleReport({ turnId: TurnId.make("run-2") }, "run-2", "Second run.", at(25)), + ); + const reports = threadIn(done.model, PARENT).messages.filter( + (message) => message.fromThread?.followUp === true, + ); + expect(reports.map((message) => message.text)).toEqual(["First run.", "Second run."]); + }); + + it("records the turn that took a parent's request, so readers know it by its id (rule B)", async () => { + const family = await familyWithRunningChild(); + const started = await run(family, { + type: "thread.session.set", + commandId: CommandId.make("session-request-turn"), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make("child-turn-1"), updatedAt: at(4) }), + turnStartedBy: { messageId: CHILD_MESSAGE }, + createdAt: at(4), + }); + expect(threadIn(started.model, PARENT).childRequests.open).toMatchObject([ + { requestId: REQUEST, status: "running", answeringTurnId: TurnId.make("child-turn-1") }, + ]); + }); + it("hands a leaving agent's queued follow-up report to the thread's own agent, and takes its answers off", async () => { const reviewer = "reviewer" as never; const queued = (id: string, followUp: boolean) => ({ diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 2b3b0df79..deae9373f 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -2730,6 +2730,92 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // Never reached the agent after the queue let it go (the provider // reactor's last check, Stop, or a start that failed): a message no one // can send again is marked, so no history carries it. + // A child's report whose turn start died before the provider took it (a + // restart, a failed start) goes back to the front of the queue, or is + // marked not run when it can no longer be delivered + // (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", + // rule A). Never a turn start: the queue's own send checks it again. The + // chain epoch and the Stop hold stay as they are. + case "thread.turn-start.take-back": { + const thread = yield* requireThread({ readModel, command, threadId: command.threadId }); + const message = thread.messages.find((entry) => entry.id === command.messageId); + const fromThread = message?.fromThread; + if ( + message === undefined || + fromThread === undefined || + fromThread.kind !== "report" || + message.notSent === true || + (message.turnId ?? null) !== null || + (thread.queuedFollowUps ?? []).some((queued) => queued.messageId === message.id) + ) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "That message is not a report whose start was cut off.", + }); + } + const base = () => + withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }); + // In a thread that reports to a parent itself, the start's unclaimed + // owed entry goes; the next start adds a new one. + const owedEntryGone: ReadonlyArray<PlannedOrchestrationEvent> = ( + thread.childRequests.owedReports ?? [] + ).some((entry) => "messageId" in entry && entry.messageId === message.id) + ? [ + { + ...base(), + type: "thread.child-report-dropped", + payload: { + threadId: thread.id, + owed: { messageId: message.id }, + turnId: null, + createdAt: command.createdAt, + }, + }, + ] + : []; + const deliverable = + !isStaleReport(readModel, thread, fromThread) && + !thread.agentRequests.hold && + thread.archivedAt === null && + (thread.move ?? null) === null; + if (!deliverable) { + return [ + ...owedEntryGone, + outsideNotSentEvent(base(), thread.id, message.id, command.createdAt), + ]; + } + const participantId = message.participantId ?? null; + const present = + participantId !== null && + activeParticipants(thread).some((entry) => entry.id === participantId); + return [ + ...owedEntryGone, + { + ...base(), + type: "thread.follow-up-queued", + payload: { + threadId: command.threadId, + followUp: { + messageId: message.id, + text: message.text, + attachments: message.attachments ?? [], + ...(present ? { participantId } : {}), + fromThread, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + putBack: true, + createdAt: command.createdAt, + }, + }, + }, + ]; + } + case "thread.message.not-run": { const target = yield* requireThread({ readModel, command, threadId: command.threadId }); const message = target.messages.find((entry) => entry.id === command.messageId); @@ -4276,66 +4362,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" return yield* decideFollowUpSubmit(targetThread, command); } - // A child's report a restart cut off before the provider took its turn - // goes back on the queue as it was (docs/design/agent-autonomy-no-limits.md, - // rule 14). It is the report's own record: nothing about the thread - // changes, the Stop hold included, and one whose delivery was cancelled - // since (Stop, a wrap, the child separated) stays off. - case "thread.follow-up.restore": { - const thread = yield* requireThread({ - readModel, - command, - threadId: command.threadId, - }); - const message = thread.messages.find((entry) => entry.id === command.messageId); - const fromThread = message?.fromThread; - if ( - message === undefined || - fromThread === undefined || - fromThread.kind !== "report" || - message.notSent === true || - (thread.queuedFollowUps ?? []).some((queued) => queued.messageId === message.id) - ) { - return yield* new OrchestrationCommandInvariantError({ - commandType: command.type, - detail: "That message is not a report waiting to be heard.", - }); - } - if (isStaleReport(readModel, thread, fromThread)) { - return yield* new OrchestrationCommandInvariantError({ - commandType: command.type, - detail: "That report's delivery was cancelled.", - }); - } - const participantId = message.participantId ?? null; - const present = - participantId !== null && - activeParticipants(thread).some((entry) => entry.id === participantId); - return { - ...withEventBase({ - aggregateKind: "thread", - aggregateId: command.threadId, - occurredAt: command.createdAt, - commandId: command.commandId, - }), - type: "thread.follow-up-queued", - payload: { - threadId: command.threadId, - followUp: { - messageId: message.id, - text: message.text, - attachments: message.attachments ?? [], - ...(present ? { participantId } : {}), - fromThread, - runtimeMode: thread.runtimeMode, - interactionMode: thread.interactionMode, - // When it first arrived: agents' messages run in that order. - createdAt: message.createdAt, - }, - }, - }; - } - case "thread.follow-up.unqueue": { const targetThread = yield* requireThread({ readModel, @@ -5277,15 +5303,62 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" startedTurnId !== null && providerTurnStamps !== null ? { turnId: startedTurnId, ...providerTurnStamps, createdAt: command.createdAt } : undefined; + // The turn claims the message that started it ("Restart and turn + // binding", rule B): its owed report is keyed by the turn from here on, + // and a parent's request it answers records the turn, so every later + // reader knows the turn by its id, never by its message. + const startedMessageId = + startedTurnId !== null && + command.turnStartedBy !== undefined && + "messageId" in command.turnStartedBy + ? command.turnStartedBy.messageId + : null; + const owedReportBinds = + startedMessageId !== null && + (thread.childRequests.owedReports ?? []).some( + (entry) => "messageId" in entry && entry.messageId === startedMessageId, + ) + ? startedMessageId + : null; + const parentForTurn = + startedMessageId !== null && thread.parentThreadId !== null + ? readModel.threads.find((entry) => entry.id === thread.parentThreadId) + : undefined; + const answeredRequests: ReadonlyArray<PlannedOrchestrationEvent> = + parentForTurn === undefined || startedTurnId === null + ? [] + : parentForTurn.childRequests.open + .filter( + (request) => + request.childThreadId === thread.id && + request.remote === undefined && + request.status === "running" && + request.childMessageId === startedMessageId && + request.answeringTurnId !== startedTurnId, + ) + .map((request) => ({ + ...childEventBase(command, command.createdAt)(parentForTurn.id), + type: "thread.child-request-updated" as const, + payload: { + threadId: parentForTurn.id, + requestId: request.requestId, + status: "running" as const, + answeringTurnId: startedTurnId, + updatedAt: command.createdAt, + }, + })); const turnStartEvents: ReadonlyArray<PlannedOrchestrationEvent> = startedTurnId === null ? [] - : settleWaitingAnswer( - readModel, - thread, - childEventBase(command, command.createdAt), - command.createdAt, - ); + : [ + ...settleWaitingAnswer( + readModel, + thread, + childEventBase(command, command.createdAt), + command.createdAt, + ), + ...answeredRequests, + ]; const sessionSetEvent = { ...withEventBase({ aggregateKind: "thread", @@ -5299,6 +5372,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" threadId: command.threadId, ...(owedReport !== undefined ? { owedReport } : {}), ...(command.turnStartedBy !== undefined ? { turnStartedBy: command.turnStartedBy } : {}), + ...(owedReportBinds !== null ? { owedReportBinds } : {}), session: withArmedContinueAtReset( readModel, thread, diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 0f8816fa8..dd1045db0 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -1825,12 +1825,15 @@ export function projectEvent( }; const owedReport = payload.owedReport; - const withOwed = - owedReport === undefined - ? nextBase - : updateChildRequests(nextBase, payload.threadId, (state) => - childRequestStateOn.owedAdded(state, owedReport), - ); + const binds = payload.owedReportBinds; + const activeTurnId = payload.session.activeTurnId; + const withOwed = updateChildRequests(nextBase, payload.threadId, (state) => { + const added = + owedReport === undefined ? state : childRequestStateOn.owedAdded(state, owedReport); + return binds === undefined || activeTurnId === null + ? added + : childRequestStateOn.owedBound(added, binds, activeTurnId); + }); return { ...withOwed, threads: updateThread(withOwed.threads, payload.threadId, { diff --git a/docs/design/agent-autonomy-no-limits.md b/docs/design/agent-autonomy-no-limits.md index c2aac4864..9091baeaf 100644 --- a/docs/design/agent-autonomy-no-limits.md +++ b/docs/design/agent-autonomy-no-limits.md @@ -142,6 +142,71 @@ Every revision since rev 2 takes option 2. What it costs: R is woken once for ev Where it goes: `routeChildReport` (`ProviderRuntimeIngestion.ts:2770`) returns early when the parent has no open request for the child. That early return goes. One pure function in `childThreadDelivery.ts` takes the turn's end, the session's stopped turn, the child's owed list and the parent's open requests, and returns the request settle, the report settle, or nothing. The turn end, the ingested exit, the sweep and startup all call it, so a turn can never be delivered as both. +### Restart and turn binding (stage 1, step 2) + +Written after Astra's second review of step 2 as built (`feat/child-reports-stage-1-server`, 47f50bcf1 and 3ba72fedf). Its findings 3 to 6 are one family: a report that left its parent's queue but never reached the provider, and a message that starts more than one turn. Step 2 as built recovers the first by working out after a restart which report was cut off (`reportCutBeforeItsTurn`, `decider.ts:904`) and sending it again with `thread.turn.resend`. That guess is finding 3, the resend is finding 4, its place in the startup order is finding 5, and looking a turn up by its message is finding 6. These three rules replace it. Line numbers in this subsection are from 3ba72fedf. + +**Rule A. A report whose start dies before the provider takes it goes back to the front of the queue. Nothing sends it again by any other road.** + +- One new server-only command, `thread.turn-start.take-back { threadId, messageId }`, decided in `decider.ts` beside `thread.message.not-run`. It acts only on a message that is a child's report (`fromThread.kind === "report"`), is not in the queue, and has no turn. + - If the report could still be delivered, by the test the queue already applies to a queued report (`isStaleReport` on the stamps the message carries, the thread not held, not archived, not moving), it emits `thread.follow-up-queued` with the entry rebuilt from the stored message and a new optional `putBack` flag on the entry. + - If not, it marks the message not run, as a report that goes stale while its turn is prepared is marked today, and queues nothing. + - It never emits a turn start, never touches the chain epoch, and never calls `resetAgentRequestsForUser`. + - If the thread is itself a child, the unbound owed entry for that message is removed. The next start adds a new one. +- `withQueuedFollowUp` (`packages/shared/src/queuedFollowUps.ts`) puts a `putBack` entry ahead of every other message an agent queued, behind an earlier `putBack` one. This is the pattern `afterMove` already uses. The user's own queued messages keep their place, and the sender still takes them first. +- Two callers, the only two places a start can die: + - **Restart.** `settleSessionsFromPreviousProcess` (`ProviderCommandReactor.ts:7322`), at the point where it already handles an outside agent's message cut before its start (`:7393`): when the session had no active turn, it reads the thread's pending start (`getPendingTurnStartByThreadId`, `ProjectionTurns.ts:299`) and dispatches the take-back for that exact message. A thread whose report was put back is not added to `turnsCutByRestart`, so it gets no "interrupted by a restart" note and no continue. + - **A failed start.** `reportFailedStart` (`ProviderCommandReactor.ts:3456`) with `beforeSend`, for a report. +- The send is the one that exists. The provider reactor's startup runs before the child reactor's (`OrchestrationReactor.ts:25`), so `reportsQueuedBeforeRestart` (`ChildThreadReactor.ts:557`) finds the report at the front and sends it through `thread.follow-up.send-queued`. That decision checks the report's own epochs, stamps the current chain epoch, carries `fromThread` on the start, and lifts no hold. +- The turns projection drops a pending start when its message goes back on the queue or is marked not run, so a stale row can't bind to a later turn. +- Removed: `reportCutBeforeItsTurn`, the resend inside `thread.restart.continue` (`decider.ts:5665`), and "any later assistant message means it was answered". + +Why put the report back instead of keeping it queued until the provider has the turn: keeping it queued means every reader of the queue has to know an entry can be in flight (the drain at a turn's end, the handler for a new entry, steering, a move's drain, the restart read), and the report would show as waiting while its turn is already starting. Putting it back touches only the two places a start dies, and from there the queue's own rules do the rest. + +**Rule B. A message has at most one start that no turn has claimed, and once a turn claims it, the turn's id is its identity.** + +- A decision that emits `thread.turn-start-requested` for a message that owes a report replaces that message's unbound owed entry, if there is one. Entries already bound to a turn belong to earlier attempts and are left to their own turn's end. +- The session update that marks a turn running and names its message (`turnStartedBy.messageId`, the builder's rule for findings 1, 2 and 7) binds in the same decision: + - the message's unbound owed entry gets the turn's id and is keyed by the turn from then on; + - a parent's running request bound to that message records the turn in a new optional `answeringTurnId`, through `thread.child-request-updated`. A retry, a resend or a continue that reuses the message overwrites it with the new turn. +- Every reader matches by turn id and none looks a turn up by its message: + - the turn end (`childDeliveryForTurnEnd`, `childThreadDelivery.ts:134`): `request.answeringTurnId === end.turnId`, or the owed entry's turn; + - the stopped-session backstop (`ChildThreadReactor.ts:373`): `requestTurnId` is `request.answeringTurnId`, compared with `stopRequestedTurnId`; + - startup (`settleOwedReportsFromPreviousProcess`, `ChildThreadReactor.ts:519`): a bound entry is settled against its own turn row; an unbound one never started, and rule A has already dealt with it or it is removed; + - `finishedTurnAfterRestart` (`childThreadDelivery.ts:500`). +- `listByThreadId` orders checkpointed turns first and older first (`ProjectionTurns.ts:206`), which is why "the first turn with this message" picked an old attempt. No reader depends on that order any more. +- A request made before this change has no `answeringTurnId`. For those only, the newest turn with that message is used, never the first. + +**Rule C. Nothing automatic restarts a report's turn.** `thread.restart.continue` continues or notes a turn the user asked for, as before step 2. `thread.turn.resend` stays for the user's Resend and the provider fallback. Neither is used to deliver a report. + +How each finding ends up: + +| Finding | With these rules | +| ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 3. A report that waited behind another agent's turn is rejected after a restart because that agent answered | The pending start names the message. The take-back needs no guess about what was answered. | +| 4. A restart undoes the user's Stop | The Stop moved the parent's delivery epoch, so the take-back finds the report stale and marks it not run. A report that is put back is sent by the queue's own decision, which checks again and lifts no hold. | +| 5. A second queued report displaces the one being recovered | The first is back at the front before the child reactor reads any queue. It goes first, and the second follows when its turn ends. | +| 6. Attempts that reuse a message are confused | An unbound attempt is the only one for its message. A bound one is known by its turn. A Stop that names a retry's turn matches that request's `answeringTurnId`. | + +What existing behavior this touches: + +- **The user's own queued messages.** Nothing. The take-back ignores them, and a user's turn the restart cut off is continued or noted as today. +- **Room hand-offs and replies.** Nothing. A hand-off cut before its start is closed by `closeRequestsFromPreviousProcess` as today. +- **Steering.** A report that was put back is a queued report like any other. In a thread with no parent it can be steered into a running turn, and steering still takes it off the queue only after the provider has it. +- **Retry and resend.** Each is a new attempt for its message under rule B. Their own behavior does not change. +- **A failed start, with no restart.** New: a report whose turn could not start waits at the front of the queue instead of sitting in the chat unheard. The queue is not sent on by itself after a failure (rule 10), so this can't loop. +- **Older clients.** `putBack` and `answeringTurnId` are optional fields on things that exist. An older client places a put-back entry last, which only changes the order it shows. No new event type. + +Tests, each named for the finding it pins: + +- **3.** Decider: in a room, agent B answers, a report for agent A is taken off the queue and its start requested; the take-back puts it back at the front. Reactor startup: a pending start names the report and the session is `starting`; after start-up the report is queued first, sent once, and the thread has no restart note. +- **4.** Decider: the user stops the parent after the report left the queue; the take-back queues nothing, marks the message not run, and emits no `agent-requests-reset` and no turn start. A take-back that does put a report back emits no reset either. +- **5.** Reactor startup: report A starting, report B queued. A is sent first and is not refused, and B is sent when A's turn ends. +- **6, reports.** A message's first turn was reported; its resend was cut off before it started. Startup settles nothing against the first turn and sends no second report for it. The resend's turn reports once when it ends. +- **6, requests.** A request's first turn stopped on a usage limit, a retry reuses the message and starts a second turn, and the user stops that turn. The backstop says "The user stopped", with the turn rows listed in the repository's order. +- **A failed start.** A report whose start fails is back at the front, and the next message queued in that idle thread sends the report first. +- **Left alone.** A user's message cut before its start gets today's continue or note. A hand-off cut before its start is closed as today. + ### What a child and its parent are told - **Attached child preamble** (`ProviderCommandReactor.ts:2268`). Today: "Another agent started this thread from the thread "X", and your final reply goes back to it automatically. Work in this thread's own checkout, and end with the answer it needs." Add: "If you take more turns later that the user did not start, for example when a thread you started reports back, the reply that ends each one goes back too and wakes that thread. Keep those replies short when nothing has changed." diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index ef7279955..c38d58641 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -2554,6 +2554,13 @@ export const OrchestrationQueuedFollowUp = Schema.Struct({ overtakes: Schema.optional(MessageId), /** See OrchestrationMessage.afterMove: kept so the message is written with it when sent. */ afterMove: Schema.optional(Schema.Literal(true)), + /** + * A child's report whose turn start died before the provider took it, put + * back (`thread.turn-start.take-back`): it goes ahead of every other + * message an agent queued, behind an earlier one put back. The user's own + * queued messages keep their place. Absent: queued in the usual order. + */ + putBack: Schema.optional(Schema.Literal(true)), /** * Carried from another computer by a move (docs/design/fleet.md, Part 3e): * written by the user there, not here, so sending it doesn't lift the @@ -3021,6 +3028,14 @@ export const OrchestrationChildRequest = Schema.Struct({ launch: Schema.optional(ChildThreadLaunch), /** `awaiting_background`: the finished turn whose last answer stands so far. */ candidateTurnId: Schema.optional(TurnId), + /** + * The child's turn that took `childMessageId`, recorded when the turn + * starts; a retry, resend or continue that runs the message again + * overwrites it. Every reader matches the request's turn by this + * (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", + * rule B). Absent: not started yet, or a request from before it was kept. + */ + answeringTurnId: Schema.optional(TurnId), /** The child is on a linked computer: see RemoteChildRequest. */ remote: Schema.optional(RemoteChildRequest), /** @@ -5673,13 +5688,14 @@ const ThreadChildRequestSettleCommand = Schema.Struct({ }); /** - * Child threads, server only: a child's report taken off its parent's queue - * to start a turn that a restart cut off before the provider took it goes - * back on the queue, as it was, so the parent's agent still hears it. Never - * a report whose delivery was cancelled since, and never the user writing. + * Child threads, server only: a child's report whose turn start died before + * the provider took it (a restart, a failed start) goes back to the front of + * the queue, or, when it can no longer be delivered, is marked not run + * (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", + * rule A). Never a turn start, and never the user writing. */ -const ThreadFollowUpRestoreCommand = Schema.Struct({ - type: Schema.Literal("thread.follow-up.restore"), +const ThreadTurnStartTakeBackCommand = Schema.Struct({ + type: Schema.Literal("thread.turn-start.take-back"), commandId: CommandId, threadId: ThreadId, messageId: MessageId, @@ -6230,7 +6246,7 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadChildRequestUpdateCommand, ThreadChildRequestSettleCommand, ThreadChildReportSettleCommand, - ThreadFollowUpRestoreCommand, + ThreadTurnStartTakeBackCommand, ThreadChildNotesDeliveredCommand, ThreadRemoteChildUpdateCommand, ThreadRemoteCancelsDeliveredCommand, @@ -6676,6 +6692,8 @@ export const ThreadChildRequestUpdatedPayload = Schema.Struct({ * (docs/design/lead-chat.md, "Usage limits"). Absent: unchanged. */ childMessageId: Schema.optional(MessageId), + /** See OrchestrationChildRequest.answeringTurnId. Absent: unchanged. */ + answeringTurnId: Schema.optional(TurnId), updatedAt: IsoDateTime, }); @@ -7234,6 +7252,13 @@ export const ThreadSessionSetPayload = Schema.Struct({ owedReport: Schema.optional(OwedChildReport), /** See TurnStartedBy. */ turnStartedBy: Schema.optional(TurnStartedBy), + /** + * The message this turn took owed the parent a report: its entry, keyed by + * the message until now, is keyed by the session's active turn from here + * on (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", + * rule B). + */ + owedReportBinds: Schema.optional(MessageId), }); /** The user closed this error's notice; see `OrchestrationSession.lastErrorDismissedAt`. */ diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 0deb77e7d..49fac151b 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -592,6 +592,7 @@ export const childRequestStateOn = { readonly candidateTurnId?: TurnId | undefined; readonly remote?: RemoteChildRequest | undefined; readonly childMessageId?: MessageId | undefined; + readonly answeringTurnId?: TurnId | undefined; }, ): OrchestrationChildRequestState => { const changes = (entry: OrchestrationChildRequest) => @@ -599,6 +600,8 @@ export const childRequestStateOn = { (entry.status !== update.status || entry.candidateTurnId !== update.candidateTurnId || (update.childMessageId !== undefined && entry.childMessageId !== update.childMessageId) || + (update.answeringTurnId !== undefined && + entry.answeringTurnId !== update.answeringTurnId) || (update.remote !== undefined && !sameRemoteRequest(entry.remote, update.remote))); return state.open.some(changes) ? { @@ -616,6 +619,9 @@ export const childRequestStateOn = { ...(update.childMessageId !== undefined ? { childMessageId: update.childMessageId } : {}), + ...(update.answeringTurnId !== undefined + ? { answeringTurnId: update.answeringTurnId } + : {}), }; }), } @@ -757,15 +763,41 @@ export const childRequestStateOn = { } } }, - /** A turn starts that owes the parent a report (docs/design/agent-autonomy-no-limits.md, rule 3). */ + /** + * A turn starts that owes the parent a report (docs/design/agent-autonomy- + * no-limits.md, rule 3). A message has at most one start no turn has + * claimed: a new start for it replaces that entry where it stands. + */ owedAdded: ( state: OrchestrationChildRequestState, entry: OwedChildReport, ): OrchestrationChildRequestState => { const owed = state.owedReports ?? []; - return owed.some((listed) => isOwedReport(listed, entry)) - ? state - : { ...state, owedReports: [...owed, entry] }; + const at = owed.findIndex((listed) => isOwedReport(listed, entry)); + if (at < 0) return { ...state, owedReports: [...owed, entry] }; + if (sameOwedReport(owed[at]!, entry)) return state; + return { ...state, owedReports: owed.map((listed, index) => (index === at ? entry : listed)) }; + }, + /** + * The turn that took a message claims its owed entry: from now on the + * entry is keyed by that turn ("Restart and turn binding", rule B). + */ + owedBound: ( + state: OrchestrationChildRequestState, + messageId: MessageId, + turnId: TurnId, + ): OrchestrationChildRequestState => { + const owed = state.owedReports ?? []; + const at = owed.findIndex((listed) => isOwedReport(listed, { messageId })); + if (at < 0) return state; + const { deliveryEpoch, attachmentEpoch, createdAt } = owed[at]!; + const bound = { turnId, deliveryEpoch, attachmentEpoch, createdAt }; + return { + ...state, + owedReports: owed + .filter((listed, index) => index === at || !isOwedReport(listed, { turnId })) + .map((listed) => (isOwedReport(listed, { messageId }) ? bound : listed)), + }; }, /** An owed report was settled, delivered or dropped. */ owedRemoved: ( @@ -794,6 +826,12 @@ export function isOwedReport(entry: OwedReportKey, key: OwedReportKey): boolean : "turnId" in entry && entry.turnId === key.turnId; } +const sameOwedReport = (left: OwedChildReport, right: OwedChildReport) => + isOwedReport(left, right) && + left.deliveryEpoch === right.deliveryEpoch && + left.attachmentEpoch === right.attachmentEpoch && + left.createdAt === right.createdAt; + /** An owed report's key alone, as events name it. */ export const owedReportKeyOf = (entry: OwedReportKey): OwedReportKey => "messageId" in entry ? { messageId: entry.messageId } : { turnId: entry.turnId }; diff --git a/packages/shared/src/queuedFollowUps.ts b/packages/shared/src/queuedFollowUps.ts index f5ee11b9d..2ad9b92e1 100644 --- a/packages/shared/src/queuedFollowUps.ts +++ b/packages/shared/src/queuedFollowUps.ts @@ -1,12 +1,16 @@ import type { OrchestrationQueuedFollowUp } from "@threadlines/contracts"; +import { isAgentOrigin } from "./roomAgentRequests.ts"; + /** * A thread's queue after `followUp` was queued: one already there with the * same message id is replaced where it stands (a report handed to another - * agent keeps its turn in line); a new one goes last, except a message - * Threadlines wrote because the thread moved or its move didn't happen - * (`afterMove`, docs/design/fleet.md, Part 3e), which goes ahead of every - * message the user queued, behind any other one like it. Every reader of + * agent keeps its turn in line); a child's report put back after its start + * died (`putBack`) goes ahead of every other message an agent queued; a new + * one goes last, except a message Threadlines wrote because the thread moved + * or its move didn't happen (`afterMove`, docs/design/fleet.md, Part 3e), + * which goes ahead of every message the user queued, behind any other one + * like it. Every reader of * `thread.follow-up-queued` (server read models, clients) applies it, so they * agree on what goes next. */ @@ -15,32 +19,24 @@ export function withQueuedFollowUp( followUp: OrchestrationQueuedFollowUp, ): ReadonlyArray<OrchestrationQueuedFollowUp> { const at = current.findIndex((queued) => queued.messageId === followUp.messageId); - if (at >= 0 && (current[at]!.afterMove === true) === (followUp.afterMove === true)) { + if ( + at >= 0 && + (current[at]!.afterMove === true) === (followUp.afterMove === true) && + (current[at]!.putBack === true) === (followUp.putBack === true) + ) { return current.map((queued, index) => (index === at ? followUp : queued)); } const rest = current.filter((queued) => queued.messageId !== followUp.messageId); + if (followUp.putBack === true) { + // Ahead of every other message an agent queued, behind one put back + // earlier; the user's own keep their place. + const before = rest.findIndex((queued) => isAgentOrigin(queued) && queued.putBack !== true); + return before < 0 + ? [...rest, followUp] + : [...rest.slice(0, before), followUp, ...rest.slice(before)]; + } if (followUp.afterMove !== true) return [...rest, followUp]; const ahead = rest.filter((queued) => queued.afterMove === true); const behind = rest.filter((queued) => queued.afterMove !== true); return [...ahead, followUp, ...behind]; } - -/** - * Of the queued messages `include` picks, the one that arrived first. In an - * idle thread agents' messages run in the order they arrived - * (docs/design/agent-autonomy-no-limits.md, rule 10), which is their - * `createdAt`, not their place: a report put back after a restart keeps the - * time it first arrived. - */ -export function firstArrived<Queued extends { readonly createdAt: string }>( - queued: ReadonlyArray<Queued>, - include: (entry: Queued) => boolean, -): Queued | undefined { - let first: Queued | undefined; - for (const entry of queued) { - if (include(entry) && (first === undefined || entry.createdAt < first.createdAt)) { - first = entry; - } - } - return first; -} From 393e13a7cd7495790a2aea3750418a9141e819d5 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:33:13 -0500 Subject: [PATCH 09/16] docs: note what was added to rule A while building, and the bind's field The put-back report waits for the next thing that moves the queue, so a start that keeps failing can't loop; the bind rides on thread.session-set as owedReportBinds. --- docs/design/agent-autonomy-no-limits.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/design/agent-autonomy-no-limits.md b/docs/design/agent-autonomy-no-limits.md index 9091baeaf..202aa3920 100644 --- a/docs/design/agent-autonomy-no-limits.md +++ b/docs/design/agent-autonomy-no-limits.md @@ -158,6 +158,7 @@ Written after Astra's second review of step 2 as built (`feat/child-reports-stag - **Restart.** `settleSessionsFromPreviousProcess` (`ProviderCommandReactor.ts:7322`), at the point where it already handles an outside agent's message cut before its start (`:7393`): when the session had no active turn, it reads the thread's pending start (`getPendingTurnStartByThreadId`, `ProjectionTurns.ts:299`) and dispatches the take-back for that exact message. A thread whose report was put back is not added to `turnsCutByRestart`, so it gets no "interrupted by a restart" note and no continue. - **A failed start.** `reportFailedStart` (`ProviderCommandReactor.ts:3456`) with `beforeSend`, for a report. - The send is the one that exists. The provider reactor's startup runs before the child reactor's (`OrchestrationReactor.ts:25`), so `reportsQueuedBeforeRestart` (`ChildThreadReactor.ts:557`) finds the report at the front and sends it through `thread.follow-up.send-queued`. That decision checks the report's own epochs, stamps the current chain epoch, carries `fromThread` on the start, and lifts no hold. +- A report put back is not sent the moment it lands on the queue. It waits for the next thing that moves the queue: the startup send above, a new message queued in the thread, or a turn's end. Sent on by itself, a start that keeps failing would put it back and send it again without end. (Added while building: the failed-start test hit that loop.) - The turns projection drops a pending start when its message goes back on the queue or is marked not run, so a stale row can't bind to a later turn. - Removed: `reportCutBeforeItsTurn`, the resend inside `thread.restart.continue` (`decider.ts:5665`), and "any later assistant message means it was answered". @@ -166,7 +167,7 @@ Why put the report back instead of keeping it queued until the provider has the **Rule B. A message has at most one start that no turn has claimed, and once a turn claims it, the turn's id is its identity.** - A decision that emits `thread.turn-start-requested` for a message that owes a report replaces that message's unbound owed entry, if there is one. Entries already bound to a turn belong to earlier attempts and are left to their own turn's end. -- The session update that marks a turn running and names its message (`turnStartedBy.messageId`, the builder's rule for findings 1, 2 and 7) binds in the same decision: +- The session update that marks a turn running and names its message (`turnStartedBy.messageId`, the builder's rule for findings 1, 2 and 7) binds in the same decision (as built: `owedReportBinds` on `thread.session-set`): - the message's unbound owed entry gets the turn's id and is keyed by the turn from then on; - a parent's running request bound to that message records the turn in a new optional `answeringTurnId`, through `thread.child-request-updated`. A retry, a resend or a continue that reuses the message overwrites it with the new turn. - Every reader matches by turn id and none looks a turn up by its message: From c90d3d3d4192435c0aee8772ae34ea5f3df33fb3 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:51:25 -0500 Subject: [PATCH 10/16] fix(server): the third review of step 2 (child reports) - A writer that names a turn's message corrects an earlier provider-start classification of the same turn: a person's message drops the turn's owed entry, an owing message takes it over, and a parent's request records the turn either way. - Retry after a report's failed start sends the report that was put back, never an earlier message of the user's. - The user's own session stop holds a thread with a family; the server's own session stops carry a cause (family for thread.children.stop, cleanup for archive, the sweeper and a link) and leave no new hold. - Startup drops an owed turn a Stop named instead of reporting it cut off. - A report's start is taken back before the session is marked interrupted at startup, and before a failed start's failure is recorded. - The startup send of a queued report gets its own command id each startup. - A continue after a restart is judged by the cut turn's own message, so a check-back is never continued. - Archiving a child moves its attachment epoch, ending what it owed. - The plan doc lists what was fixed and the known limits left. --- apps/server/src/links/LinkRequests.ts | 3 + .../Layers/ChildThreadReactor.test.ts | 42 ++++++ .../Layers/ChildThreadReactor.ts | 9 +- .../Layers/ProviderCommandReactor.test.ts | 2 + .../Layers/ProviderCommandReactor.ts | 46 +++++-- .../Layers/ThreadAutoArchiveSweeper.ts | 2 + apps/server/src/orchestration/childReports.ts | 9 ++ .../src/orchestration/childThreadDelivery.ts | 16 ++- .../src/orchestration/continueTurns.test.ts | 10 ++ .../server/src/orchestration/continueTurns.ts | 14 +- .../decider.childThreads.test.ts | 113 +++++++++++++++- apps/server/src/orchestration/decider.ts | 123 +++++++++++++++--- apps/server/src/ws.ts | 14 +- docs/design/agent-autonomy-no-limits.md | 19 +++ packages/contracts/src/orchestration.ts | 6 + 15 files changed, 386 insertions(+), 42 deletions(-) diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 887fa0b60..1472d1731 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -1269,6 +1269,8 @@ const make = Effect.gen(function* () { const stopped = yield* engine .dispatch({ type: "thread.session.stop", + // A link's stop leaves no Stop hold here. + cause: "cleanup", commandId: CommandId.make( `server:link-stop:${deviceId}:${thread.id}:${turnKeyOf(thread)}${ retry === undefined ? "" : `:retry:${retry}` @@ -1340,6 +1342,7 @@ const make = Effect.gen(function* () { const stopped = yield* dispatchUnlessRefused( { type: "thread.session.stop", + cause: "cleanup", commandId: linkCommandId( deviceId, row.requestId, diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts index 3f23b73f7..95375bdf0 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts @@ -403,6 +403,48 @@ describe("ChildThreadReactor", () => { ), ); + it.effect( + "after a restart, sends nothing for a turn a Stop named before the process stopped (round 3, finding 4)", + () => + withReactor( + [ + parentWith([]), + thread(CHILD, { + session: { + threadId: CHILD, + status: "interrupted", + providerName: "claudeAgent", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: null, + stopRequestedTurnId: TurnId.make("stopped-turn"), + updatedAt: now, + }, + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + owedReports: [ + { + turnId: TurnId.make("stopped-turn"), + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: now, + }, + ], + }, + }), + ], + {}, + (harness) => + Effect.sync(() => { + const settles = harness.dispatched.filter( + (command) => command.type === "thread.child-report.settle", + ); + expect(settles).toHaveLength(1); + expect(settles[0]).not.toHaveProperty("text"); + }), + ), + ); + it.effect("resumes a setup the previous process left unfinished", () => withReactor([parentWith([request({ status: "starting" })])], {}, (harness) => Effect.gen(function* () { diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index a38a7f1e0..739cd8891 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -604,13 +604,18 @@ export const makeChildThreadReactor = Effect.gen(function* () { reports, (report) => Effect.gen(function* () { + // Its own id each startup: a send an earlier startup tried, whose + // start then died and was put back, must not replay that receipt. + const createdAt = yield* nowIso; yield* dispatch( { type: "thread.follow-up.send-queued", - commandId: CommandId.make(`server:child-report-after-restart:${report.messageId}`), + commandId: CommandId.make( + `server:child-report-after-restart:${report.messageId}:${createdAt}`, + ), threadId: report.threadId, messageId: report.messageId, - createdAt: yield* nowIso, + createdAt, }, "send a report queued before a restart", ); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 08d6f0531..a79e9bf1c 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -6155,6 +6155,8 @@ describe("ProviderCommandReactor", () => { type: "thread.session.set", commandId: CommandId.make("cmd-session-set-cut"), threadId, + // Its turn took the user's message, as the reactor names it. + turnStartedBy: { messageId: asMessageId("user-message-cut") }, session: { threadId, status: "running", diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 1d9aee1be..7688ebcd9 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -3501,18 +3501,21 @@ const make = Effect.gen(function* () { : beforeSend ? markNotRun("failed") : Effect.void; + // Only a turn the provider never took: one it took ends (and settles + // what it owes) by its own turn end, whatever failed after. A child's + // report goes back to the front of the queue, before the failure is + // recorded, so a stop in between can't leave it out of the queue. + const reportStart = beforeSend && message.fromThread?.kind === "report"; return mark.pipe( + Effect.andThen( + reportStart + ? takeBackReportStart(event.payload.threadId, event.payload.messageId, "failed-start") + : Effect.void, + ), Effect.andThen(handleTurnStartFailure(cause)), Effect.andThen(failHandOffForFailedStart(detail)), - // Only a turn the provider never took: one it took ends (and settles - // what it owes) by its own turn end, whatever failed after. A child's - // report goes back to the front of the queue instead. Effect.andThen( - !beforeSend - ? Effect.void - : message.fromThread?.kind === "report" - ? takeBackReportStart(event.payload.threadId, event.payload.messageId, "failed-start") - : settleChildWorkForUnstartedTurn(detail), + beforeSend && !reportStart ? settleChildWorkForUnstartedTurn(detail) : Effect.void, ), ); }; @@ -7381,7 +7384,13 @@ const make = Effect.gen(function* () { const takeBackReportCutByRestart = (threadId: ThreadId) => Effect.gen(function* () { const pending = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ threadId }); - if (Option.isNone(pending)) return false; + if (Option.isNone(pending)) { + // An earlier startup put it back and stopped before it was done. + const thread = yield* resolveThread(threadId); + return (thread?.queuedFollowUps ?? []).some( + (queued) => queued.putBack === true && queued.fromThread?.kind === "report", + ); + } return yield* takeBackReportStart(threadId, pending.value.messageId, "restart"); }).pipe(Effect.orElseSucceed(() => false)); @@ -7459,6 +7468,11 @@ const make = Effect.gen(function* () { if (session.activeTurnId === null) { yield* markOutsideMessageCutBeforeStart(thread.id, sessionSlotParticipantId(session)); } + // A child's report cut before its start goes back on the queue first, + // for the same reason, and is sent from there: no restart note and no + // continue for it. + const reportPutBack = + session.activeTurnId === null && (yield* takeBackReportCutByRestart(thread.id)); yield* setThreadSession({ threadId: thread.id, session: { @@ -7473,9 +7487,7 @@ const make = Effect.gen(function* () { createdAt, }); yield* takeBackOutsideQueued(thread.id, createdAt); - // A child's report cut before its start goes back on the queue and is - // sent from there: no restart note and no continue for it. - if (session.activeTurnId === null && (yield* takeBackReportCutByRestart(thread.id))) { + if (reportPutBack) { continue; } // Read now: startup expires the questions the previous process left. @@ -7508,12 +7520,22 @@ const make = Effect.gen(function* () { ); for (const { threadId, turnId, participantId, waitingOnUser } of cut) { const createdAt = yield* nowIso; + // The message the cut turn was started with, from its turn record: + // a check-back's turn has none and is never continued. + const turnRow = + turnId === null + ? undefined + : yield* projectionTurnRepository.getByTurnId({ threadId, turnId }).pipe( + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ); yield* orchestrationEngine .dispatch({ type: "thread.restart.continue", commandId: serverCommandId("restart-continue"), threadId, turnId, + ...(turnRow !== undefined ? { turnMessageId: turnRow.pendingMessageId } : {}), participantId, waitingOnUser, continueAfterRestart: settingOn, diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts index b813ed37e..a536bd21d 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -168,6 +168,8 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti yield* orchestrationEngine .dispatch({ type: "thread.session.stop", + // Cleanup: the sweeper's stop leaves no Stop hold. + cause: "cleanup", commandId: CommandId.make(`thread-auto-archive-stop:${threadId}:${randomUUID()}`), threadId, createdAt: new Date(nowMs).toISOString(), diff --git a/apps/server/src/orchestration/childReports.ts b/apps/server/src/orchestration/childReports.ts index baa3c6ac7..f56467954 100644 --- a/apps/server/src/orchestration/childReports.ts +++ b/apps/server/src/orchestration/childReports.ts @@ -80,6 +80,15 @@ export interface TurnStartOrigin { readonly requestKind?: OrchestrationMessage["requestKind"]; } +/** + * Whether a message's own turn answers someone other than the thread's parent + * (rule 2): a person's, an outside agent's, the parent's request, a hand-off. + * A continue is judged by what it continues, so it never counts here. + */ +export function messageAnswersSomeoneElse(message: TurnStartOrigin): boolean { + return message.trigger === undefined && answersSomeoneElse(message); +} + /** Whether a message's own turn answers someone other than the thread's parent (rule 2). */ function answersSomeoneElse(origin: TurnStartOrigin): boolean { return ( diff --git a/apps/server/src/orchestration/childThreadDelivery.ts b/apps/server/src/orchestration/childThreadDelivery.ts index e314f6497..700571b61 100644 --- a/apps/server/src/orchestration/childThreadDelivery.ts +++ b/apps/server/src/orchestration/childThreadDelivery.ts @@ -365,7 +365,8 @@ export function staleOwedReports( * settled against that turn alone: a completed turn is delivered, a failed * one delivers its failure, and one the restart cut off says so. One no turn * claimed never started: it goes with nothing said (its message's start was - * put back or marked not run, "Restart and turn binding", rule A). + * put back or marked not run, "Restart and turn binding", rule A), and so + * does one a Stop named before the process stopped. */ export function childReportAfterRestart( child: OrchestrationThread, @@ -377,11 +378,14 @@ export function childReportAfterRestart( const text = turnId === null ? undefined - : turn?.state === "completed" - ? reportReplyText(child, turnId) - : turn?.state === "error" - ? reportFailureText(child, child.session?.lastError ?? "Its turn did not finish.") - : `'${child.title}' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.`; + : turn?.state !== "completed" && stoppedOnPurpose(child, turnId) + ? // A turn a Stop named was stopped on purpose, restart or not (rule 6). + undefined + : turn?.state === "completed" + ? reportReplyText(child, turnId) + : turn?.state === "error" + ? reportFailureText(child, child.session?.lastError ?? "Its turn did not finish.") + : `'${child.title}' was interrupted by a Threadlines restart. Send it a message with thread_send to continue.`; return { type: "thread.child-report.settle", commandId: reportSettleCommandId(child, entry), diff --git a/apps/server/src/orchestration/continueTurns.test.ts b/apps/server/src/orchestration/continueTurns.test.ts index 58026da97..ac8c4b6bb 100644 --- a/apps/server/src/orchestration/continueTurns.test.ts +++ b/apps/server/src/orchestration/continueTurns.test.ts @@ -167,4 +167,14 @@ describe("restartContinueVerdict", () => { // The agent never got the message: "continue" would lose it. expect(verdict(cutThread([typed]), { turnStarted: false }).kind).toBe("note"); }); + + it("judges a continue by the turn the restart cut, not the newest message (finding 7)", () => { + const typed = userMessage("typed", minutesAgo(30), { composer: "typed" }); + // A check-back's turn was cut: it started with no message, so no continue. + expect(verdict(cutThread([typed]), { turnMessageId: null }).kind).toBe("note"); + // The person's own turn was cut: it continues. + expect(verdict(cutThread([typed]), { turnMessageId: MessageId.make("typed") }).kind).toBe( + "continue", + ); + }); }); diff --git a/apps/server/src/orchestration/continueTurns.ts b/apps/server/src/orchestration/continueTurns.ts index c193955fc..860b31508 100644 --- a/apps/server/src/orchestration/continueTurns.ts +++ b/apps/server/src/orchestration/continueTurns.ts @@ -1,4 +1,5 @@ import type { + MessageId, MessageTrigger, OrchestrationMessage, OrchestrationSession, @@ -100,6 +101,12 @@ export function restartContinueVerdict( readonly waitingOnUser: boolean; readonly settingOn: boolean; readonly now: string; + /** + * The message the cut turn was started with, when known: null for a turn + * the provider started. A continue is judged by that turn, never by the + * newest message. + */ + readonly turnMessageId?: MessageId | null | undefined; }, ): RestartContinueVerdict { const stopped = { kind: "note", detail: RESTART_STOPPED_DETAIL } as const; @@ -125,7 +132,12 @@ export function restartContinueVerdict( ) { return stopped; } - const startedBy = latestTurnStartFor(thread, participantId); + const startedBy = + input.turnMessageId === undefined + ? latestTurnStartFor(thread, participantId) + : input.turnMessageId === null + ? undefined + : thread.messages.find((message) => message.id === input.turnMessageId); if (startedBy === undefined || !userAskedForTurn(startedBy)) { return stopped; } diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 0e86651f2..1026648a7 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -578,7 +578,11 @@ describe("decider child threads", () => { .filter((event) => "threadId" in event.payload && event.payload.threadId === id) .map((event) => event.type); expect(eventsFor(willCheckBack.id)).toEqual(["thread.parent-attachment-set"]); - expect(eventsFor(savedCheckBack.id)).toEqual(["thread.archived"]); + // Archived with its parent, it owes it nothing more: its epoch moves. + expect(eventsFor(savedCheckBack.id)).toEqual([ + "thread.archived", + "thread.parent-attachment-set", + ]); expect(threadIn(archived.model, willCheckBack.id).archivedAt).toBeNull(); }); @@ -2445,6 +2449,113 @@ describe("decider child reports", () => { ]); }); + it("lets the writer that names a person's message undo a turn first taken for the provider's (round 3, finding 1)", async () => { + const family = await answeredFamily(); + // The person's message is being prepared; ingestion sees the turn start + // first and, the session no longer starting, takes it for the provider's. + const asked = await run(family, turnStart("typed", { composer: "typed" })); + const taken = await run(asked.model, providerTurn("child-turn-2")); + expect(threadIn(taken.model, CHILD).childRequests.owedReports).toMatchObject([ + { turnId: TurnId.make("child-turn-2") }, + ]); + // The send's acknowledgement names the message for the same turn. + const named = await run(taken.model, { + type: "thread.session.set", + commandId: CommandId.make("session-named"), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make("child-turn-2"), updatedAt: at(31) }), + turnStartedBy: { messageId: MessageId.make("typed") }, + createdAt: at(31), + }); + expect(threadIn(named.model, CHILD).childRequests.owedReports).toBeUndefined(); + // A message that owes a report takes the turn's entry over instead. + const scheduled = await run( + family, + turnStart("scheduled", { scheduledTaskId: "task-1" as never }), + ); + const takenAgain = await run(scheduled.model, providerTurn("child-turn-3")); + const namedAgain = await run(takenAgain.model, { + type: "thread.session.set", + commandId: CommandId.make("session-named-again"), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make("child-turn-3"), updatedAt: at(31) }), + turnStartedBy: { messageId: MessageId.make("scheduled") }, + createdAt: at(31), + }); + expect(threadIn(namedAgain.model, CHILD).childRequests.owedReports).toEqual([ + expect.objectContaining({ turnId: TurnId.make("child-turn-3") }), + ]); + }); + + it("retries a report that was put back, never an earlier message of the user's (round 3, finding 2)", async () => { + const { model: starting, report } = await reportStarting(); + const failed = { + ...starting, + threads: starting.threads.map((entry) => + entry.id === PARENT + ? { + ...entry, + messages: [ + { + id: MessageId.make("publish"), + role: "user" as const, + text: "Publish the release.", + composer: "typed" as const, + turnId: null, + streaming: false, + createdAt: at(1), + updatedAt: at(1), + }, + ...entry.messages, + ], + session: session(PARENT, { + status: "error", + activeTurnId: null, + lastError: "spawn failed", + }), + } + : entry, + ), + }; + const putBack = await run(failed, takeBack(report.messageId)); + const retried = await run(putBack.model, { + type: "thread.turn.retry", + commandId: CommandId.make("retry"), + threadId: PARENT, + createdAt: at(60), + }); + const started = (retried.events as ReadonlyArray<OrchestrationEvent>).find( + (event) => event.type === "thread.turn-start-requested", + ); + expect(started?.payload).toMatchObject({ messageId: report.messageId }); + }); + + it("holds a parent the user stops from its session stop, but not one stopped with its family (round 3, finding 3)", async () => { + const family = await answeredFamily(); + const stop = (cause?: "family") => ({ + type: "thread.session.stop" as const, + commandId: CommandId.make(`session-stop-${cause ?? "user"}`), + threadId: PARENT, + ...(cause !== undefined ? { cause } : {}), + createdAt: at(15), + }); + expect(threadIn((await run(family, stop())).model, PARENT).agentRequests.hold).toBe(true); + expect(threadIn((await run(family, stop("family"))).model, PARENT).agentRequests.hold).toBe( + false, + ); + }); + + it("ends what an archived child owed, so restoring it brings no old report back (round 3, finding 8)", async () => { + const owing = (await run(await answeredFamily(), providerTurn("child-turn-2"))).model; + const archived = await run(owing, { + type: "thread.archive", + commandId: CommandId.make("archive-child"), + threadId: CHILD, + }); + expect(threadIn(archived.model, CHILD).childRequests.owedReports).toBeUndefined(); + expect(threadIn(archived.model, CHILD).parentAttachmentEpoch).toBe(1); + }); + it("hands a leaving agent's queued follow-up report to the thread's own agent, and takes its answers off", async () => { const reviewer = "reviewer" as never; const queued = (id: string, followUp: boolean) => ({ diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index deae9373f..119bd0eab 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -51,7 +51,11 @@ import { import { secretRequestIdOfAnswerMessage } from "@threadlines/shared/secretRequests"; import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; -import { isAttachedChild, passCeilingRefusal } from "@threadlines/shared/childThreads"; +import { + isAttachedChild, + isOwedReport, + passCeilingRefusal, +} from "@threadlines/shared/childThreads"; import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; @@ -120,6 +124,7 @@ import { import { continuedTurnMessage, decideChildReportSettle, + messageAnswersSomeoneElse, owedReportStamps, settleWaitingAnswer, turnStartOwesReport, @@ -1983,6 +1988,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" updatedAt: occurredAt, }, })), + // An archived thread owes its parent nothing more: its attachment + // epoch moves, as a separate does, so no report it owed comes back + // after it is restored (docs/design/agent-autonomy-no-limits.md). + ...[thread, ...plan.archive] + .filter((archived) => archived.parentThreadId !== null && archived.attachedToParent) + .map((archived): PlannedOrchestrationEvent => ({ + ...baseFor(archived.id), + type: "thread.parent-attachment-set", + payload: { + threadId: archived.id, + attached: true, + attachmentEpoch: archived.parentAttachmentEpoch + 1, + at: occurredAt, + }, + })), ...childDeletionEvents(readModel, thread, baseFor, occurredAt, true, "archived"), // Its agents' settings cards waiting for an answer go with it. ...[thread, ...plan.archive].flatMap((archived) => @@ -3253,6 +3273,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" type: "thread.session.stop", commandId: command.commandId, threadId: childId, + // Stopped with its family: no new Stop hold. + cause: "family", createdAt: command.createdAt, }), ), @@ -4168,6 +4190,26 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: `Thread '${command.threadId}' has no failed turn to retry.`, }); } + // A child's report whose start failed was put back on the queue + // ("Restart and turn binding", rule A): that is the failed turn, so the + // user's Retry sends it, never an earlier message of theirs. + const putBack = (targetThread.queuedFollowUps ?? []).find( + (queued) => queued.putBack === true, + ); + if (command.type === "thread.turn.retry" && putBack !== undefined) { + return yield* decideCommandSequence({ + commands: [ + { + type: "thread.follow-up.send-queued", + commandId: command.commandId, + threadId: command.threadId, + messageId: putBack.messageId, + createdAt: command.createdAt, + }, + ], + readModel, + }); + } if ( command.type === "thread.turn.resend" && command.chainEpoch !== undefined && @@ -5242,8 +5284,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }); // In a room, stopping the session ends the agents' chain the same way // Stop does, so a turn still being prepared for an agent is dropped. + // The user's own session stop holds a family like their Stop does; one + // the server makes (with its family, as cleanup) leaves no new hold. const chainStop = [ - ...decideAgentChainStop(thread, base, command.createdAt), + ...decideAgentChainStop(thread, base, command.createdAt, { + holdsFamily: + command.cause === undefined && + (thread.childRequests.open.length > 0 || + attachedChildrenOf(readModel, thread.id).length > 0), + }), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), // Stop is the user's say: a goal paused for a wait stays as Stop @@ -5306,9 +5355,19 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // The turn claims the message that started it ("Restart and turn // binding", rule B): its owed report is keyed by the turn from here on, // and a parent's request it answers records the turn, so every later - // reader knows the turn by its id, never by its message. + // reader knows the turn by its id, never by its message. A writer that + // names the message may come after one that took the same turn for the + // provider's (Claude says a turn started before its send returns): the + // name wins, whether or not the turn is new. + const namedTurnId = + command.session.status === "running" && + command.session.activeTurnId !== null && + command.turnStartedBy !== undefined && + "messageId" in command.turnStartedBy + ? command.session.activeTurnId + : null; const startedMessageId = - startedTurnId !== null && + namedTurnId !== null && command.turnStartedBy !== undefined && "messageId" in command.turnStartedBy ? command.turnStartedBy.messageId @@ -5320,12 +5379,39 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ) ? startedMessageId : null; + // Named for a message that owes nothing (a person's, a request's): a + // report recorded for the turn as the provider's goes. + const namedMessage = + startedMessageId === null + ? undefined + : thread.messages.find((message) => message.id === startedMessageId); + const providerEntryCorrected: ReadonlyArray<PlannedOrchestrationEvent> = + namedTurnId !== null && + owedReportBinds === null && + namedMessage !== undefined && + messageAnswersSomeoneElse(namedMessage) && + (thread.childRequests.owedReports ?? []).some((entry) => + isOwedReport(entry, { turnId: namedTurnId }), + ) + ? [ + { + ...childEventBase(command, command.createdAt)(thread.id), + type: "thread.child-report-dropped", + payload: { + threadId: thread.id, + owed: { turnId: namedTurnId }, + turnId: namedTurnId, + createdAt: command.createdAt, + }, + }, + ] + : []; const parentForTurn = startedMessageId !== null && thread.parentThreadId !== null ? readModel.threads.find((entry) => entry.id === thread.parentThreadId) : undefined; const answeredRequests: ReadonlyArray<PlannedOrchestrationEvent> = - parentForTurn === undefined || startedTurnId === null + parentForTurn === undefined || namedTurnId === null ? [] : parentForTurn.childRequests.open .filter( @@ -5334,7 +5420,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" request.remote === undefined && request.status === "running" && request.childMessageId === startedMessageId && - request.answeringTurnId !== startedTurnId, + request.answeringTurnId !== namedTurnId, ) .map((request) => ({ ...childEventBase(command, command.createdAt)(parentForTurn.id), @@ -5343,22 +5429,22 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" threadId: parentForTurn.id, requestId: request.requestId, status: "running" as const, - answeringTurnId: startedTurnId, + answeringTurnId: namedTurnId, updatedAt: command.createdAt, }, })); - const turnStartEvents: ReadonlyArray<PlannedOrchestrationEvent> = - startedTurnId === null + const turnStartEvents: ReadonlyArray<PlannedOrchestrationEvent> = [ + ...(startedTurnId === null ? [] - : [ - ...settleWaitingAnswer( - readModel, - thread, - childEventBase(command, command.createdAt), - command.createdAt, - ), - ...answeredRequests, - ]; + : settleWaitingAnswer( + readModel, + thread, + childEventBase(command, command.createdAt), + command.createdAt, + )), + ...providerEntryCorrected, + ...answeredRequests, + ]; const sessionSetEvent = { ...withEventBase({ aggregateKind: "thread", @@ -5762,6 +5848,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" waitingOnUser: command.waitingOnUser, settingOn: command.continueAfterRestart, now: command.createdAt, + ...(command.turnMessageId !== undefined ? { turnMessageId: command.turnMessageId } : {}), }); if (verdict.kind === "movedOn") { return yield* new OrchestrationCommandInvariantError({ diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c8d4cdb7c..6cc230c5b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1387,7 +1387,12 @@ const makeCoreRpcLayer = ( threadId, createdAt: yield* nowIso, }); - yield* dispatchNormalizedCommand(stopCommand); + // Cleanup: an archive's stop leaves no Stop hold. + yield* dispatchNormalizedCommand( + stopCommand.type === "thread.session.stop" + ? { ...stopCommand, cause: "cleanup" as const } + : stopCommand, + ); }).pipe( Effect.catchCause((cause) => Effect.logWarning("failed to stop provider session during archive", { @@ -1479,7 +1484,12 @@ const makeCoreRpcLayer = ( createdAt: yield* nowIso, }); - yield* dispatchNormalizedCommand(stopCommand); + // Cleanup: an archive's stop leaves no Stop hold. + yield* dispatchNormalizedCommand( + stopCommand.type === "thread.session.stop" + ? { ...stopCommand, cause: "cleanup" as const } + : stopCommand, + ); }).pipe( Effect.catchCause((cause) => Effect.logWarning("failed to stop provider session during archive", { diff --git a/docs/design/agent-autonomy-no-limits.md b/docs/design/agent-autonomy-no-limits.md index 202aa3920..69f4b65a7 100644 --- a/docs/design/agent-autonomy-no-limits.md +++ b/docs/design/agent-autonomy-no-limits.md @@ -198,6 +198,25 @@ What existing behavior this touches: - **A failed start, with no restart.** New: a report whose turn could not start waits at the front of the queue instead of sitting in the chat unheard. The queue is not sent on by itself after a failure (rule 10), so this can't loop. - **Older clients.** `putBack` and `answeringTurnId` are optional fields on things that exist. An older client places a put-back entry last, which only changes the order it shows. No new event type. +Fixed after Astra's third review of step 2 (3fddb66bc), as built: + +- A writer that names a turn's message wins over an earlier writer that took the same turn for the provider's, whether or not the turn is new: a person's message drops the turn's owed entry, a message that owes a report takes the entry over. +- The user's Retry after a report's failed start sends that report, not an earlier message of theirs. +- The user's own `thread.session.stop` holds a thread with a family, as their Stop does. The server's own session stops say why (`cause`: `family` for `thread.children.stop`, `cleanup` for archive, the sweeper and a link) and leave no new hold. +- At startup a turn a Stop named is dropped, not reported as cut off by the restart. +- A report's start is taken back before the session is marked interrupted at startup, and before a failed start's failure is recorded, so a stop in between can't leave it out of the queue. +- The startup send of a queued report has its own command id each startup. +- A continue after a restart is judged by the turn the restart cut (its turn record's message), so a check-back's turn is never continued. +- Archiving a child moves its attachment epoch, as separating does, so no report it owed comes back after it is restored. + +Known limits, accepted (T3 Code has no crash recovery at all): + +- A process that stops after a report's start was taken back but before the session was marked interrupted gives the parent a "turn interrupted by a restart" note at the next startup. The report itself is still at the front of the queue and is sent. +- A parent whose session was neither starting nor running when the process stopped (a check-back of its own held the active turn, say) gets no take-back at startup: a report taken off its queue in that moment stays in the chat, unheard by the agent until something else wakes it. +- A turn the provider starts with no trigger and no synthetic mark (a Codex goal) while a message is being prepared is taken for that message's turn. The driver gives no signal. +- Session updates stored before turn binding carry no `turnStartedBy`. Replaying them does not bind turns, which matters only if the turns projection were rebuilt from the event log. +- Only a child's report is taken back. Other agent messages cut before their start behave as before (a hand-off is closed as failed at startup). + Tests, each named for the finding it pins: - **3.** Decider: in a room, agent B answers, a report for agent A is taken off the queue and its start requested; the take-back puts it back at the front. Reactor startup: a pending start names the report and the session is `starting`; after start-up the report is queued first, sent once, and the thread has no restart note. diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index c38d58641..7b6c45656 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -4871,6 +4871,12 @@ const ThreadRestartContinueCommand = Schema.Struct({ commandId: CommandId, threadId: ThreadId, turnId: Schema.NullOr(TurnId), + /** + * The message the cut turn was started with, from its turn record: null for + * a turn the provider started (a check-back), which is never continued. + * Absent: not known, and the newest message that starts a turn stands in. + */ + turnMessageId: Schema.optional(Schema.NullOr(MessageId)), participantId: Schema.NullOr(ThreadParticipantId), waitingOnUser: Schema.Boolean, continueAfterRestart: Schema.Boolean, From a16e29db3a51574562fe4be3b4bf3c13842a94e8 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:14:29 -0500 Subject: [PATCH 11/16] fix(server): only the writer that sent a message names its turn Fourth review of step 2. - Ingestion records every turn start as the provider's, provisionally, and never names a pending message. The reactor names the message it sent, with the turn's id (turnStartedBy.turnId), and that corrects the record whether or not the turn is new. An unmarked provider turn during a request's preparation (a Codex goal) can no longer answer that request. - The naming correction judges a continue by the turn it continues, so a continue of a person's turn drops its provisional report. - Retry sends a put-back report only when no message was tried since it was put back; otherwise it retries that message. - A restart continue judges an unnamed cut turn by the start still pending. - The plan doc says exactly what a stop cause changes, lists this round's fixes and the known limits left. --- .../Layers/ProjectionPipeline.ts | 8 +- .../Layers/ProviderCommandReactor.test.ts | 4 +- .../Layers/ProviderCommandReactor.ts | 33 +++-- .../Layers/ProviderRuntimeIngestion.test.ts | 139 +++++++++++++++++- .../Layers/ProviderRuntimeIngestion.ts | 41 ++---- apps/server/src/orchestration/childReports.ts | 9 -- .../decider.childThreads.test.ts | 78 ++++++++++ apps/server/src/orchestration/decider.ts | 75 ++++++---- apps/server/src/orchestration/projector.ts | 5 +- docs/design/agent-autonomy-no-limits.md | 14 +- packages/contracts/src/orchestration.ts | 25 ++-- 11 files changed, 328 insertions(+), 103 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 0ea4dfda9..eeee6a9b6 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1499,20 +1499,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti // See the in-memory projector: a provider-started turn's report, // and the turn claiming its message's report. ...(event.payload.owedReport !== undefined || - (event.payload.owedReportBinds !== undefined && - event.payload.session.activeTurnId !== null) + event.payload.owedReportBinds !== undefined ? { childRequests: ((state) => { const owedReport = event.payload.owedReport; const binds = event.payload.owedReportBinds; - const activeTurnId = event.payload.session.activeTurnId; const added = owedReport === undefined ? state : childRequestStateOn.owedAdded(state, owedReport); - return binds === undefined || activeTurnId === null + return binds === undefined ? added - : childRequestStateOn.owedBound(added, binds, activeTurnId); + : childRequestStateOn.owedBound(added, binds.messageId, binds.turnId); })(existingRow.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE), } : {}), diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index a79e9bf1c..1f6bc8b25 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -6155,8 +6155,8 @@ describe("ProviderCommandReactor", () => { type: "thread.session.set", commandId: CommandId.make("cmd-session-set-cut"), threadId, - // Its turn took the user's message, as the reactor names it. - turnStartedBy: { messageId: asMessageId("user-message-cut") }, + // The process stops before the reactor names the message: the + // turn is judged by the start still pending (round 4, finding 7). session: { threadId, status: "running", diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 7688ebcd9..fc3393445 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -1261,23 +1261,23 @@ const make = Effect.gen(function* () { if (!thread || !session) { return; } + // Only this writer, which sent the message, names its turn, by id + // ("Restart and turn binding", rule B). + const turnStartedBy = { messageId: input.messageId, turnId: input.turnId }; + // The turn already ended, or the session moved on: nothing is marked + // running, and the turn stays as it was recorded (a known limit: a turn + // that ends before its send is acknowledged keeps the provider's). if ( session.status === "stopped" || session.status === "error" || - session.status === "interrupted" + session.status === "interrupted" || + (session.activeTurnId !== null && session.activeTurnId !== input.turnId) || + (thread.latestTurn?.turnId === input.turnId && thread.latestTurn.state !== "running") ) { return; } - if (session.activeTurnId !== null && session.activeTurnId !== input.turnId) { - return; - } - - if (thread.latestTurn?.turnId === input.turnId && thread.latestTurn.state !== "running") { - return; - } - const updatedAt = yield* nowIso; yield* setThreadSession({ threadId: input.threadId, @@ -1289,7 +1289,7 @@ const make = Effect.gen(function* () { updatedAt, }, createdAt: updatedAt, - turnStartedBy: { messageId: input.messageId }, + turnStartedBy, }); }); @@ -7529,13 +7529,24 @@ const make = Effect.gen(function* () { Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), ); + // Not named yet when the process stopped (the send's acknowledgement + // never came): the start still pending is the message it was for. + const pendingStart = + turnRow === undefined || turnRow.pendingMessageId !== null + ? Option.none() + : yield* projectionTurnRepository + .getPendingTurnStartByThreadId({ threadId }) + .pipe(Effect.orElseSucceed(() => Option.none())); + const turnMessageId = + turnRow?.pendingMessageId ?? + (Option.isSome(pendingStart) ? pendingStart.value.messageId : null); yield* orchestrationEngine .dispatch({ type: "thread.restart.continue", commandId: serverCommandId("restart-continue"), threadId, turnId, - ...(turnRow !== undefined ? { turnMessageId: turnRow.pendingMessageId } : {}), + ...(turnRow !== undefined ? { turnMessageId } : {}), participantId, waitingOnUser, continueAfterRestart: settingOn, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 6c96bbe63..36d26d332 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -20,6 +20,8 @@ import { } from "@threadlines/contracts"; import { ApprovalRequestId, + ChildRequestBatchId, + ChildRequestId, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, EnvironmentId, @@ -1657,6 +1659,127 @@ describe("ProviderRuntimeIngestion", () => { expect(owed).toMatchObject([{ messageId: "fix-message-3" }, { turnId: "background-turn" }]); }); + it("never lets an unmarked provider turn during a request's preparation answer that request (round 4)", async () => { + const harness = await createHarness(); + const createdAt = "2026-01-01T00:00:00.000Z"; + const parent = asThreadId("thread-1"); + const child = asThreadId("child-goal"); + const requestId = ChildRequestId.make("request-goal"); + const childMessageId = asMessageId("request-goal-message"); + const modelSelection = { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + }; + const dispatch = (command: Parameters<typeof harness.engine.dispatch>[0]) => + Effect.runPromise(harness.engine.dispatch(command)); + // The parent's agent asks during its own turn. + await dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-goal-parent-running"), + threadId: parent, + session: { + threadId: parent, + status: "running", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: asTurnId("parent-turn"), + updatedAt: createdAt, + lastError: null, + }, + createdAt, + }); + await dispatch({ + type: "thread.child.start", + commandId: CommandId.make("cmd-goal-child-start"), + threadId: parent, + batchId: ChildRequestBatchId.make("batch-goal"), + from: { participantId: null }, + callerTurnId: asTurnId("parent-turn"), + mode: "auto", + children: [ + { + requestId, + childThreadId: child, + childMessageId, + launch: { + title: "Watch CI", + prompt: "Watch CI until it is green.", + modelSelection, + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + reportBack: true, + runSetup: false, + workspace: { kind: "project_folder" }, + }, + }, + ], + createdAt, + }); + await dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-goal-child-create"), + threadId: child, + projectId: asProjectId("project-1"), + title: "Watch CI", + modelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + parentThreadId: parent, + attachedToParent: true, + createdAt, + }); + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "ready", + runtimeMode: "approval-required", + threadId: child, + createdAt, + updatedAt: createdAt, + }); + // The parent's request is being prepared in the child. + await dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-goal-request-turn"), + threadId: child, + message: { + messageId: childMessageId, + role: "user", + text: "Watch CI until it is green.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + fromThread: { threadId: parent, requestId, kind: "request" }, + createdAt: "2026-01-01T00:00:01.000Z", + }); + // Codex starts a goal's turn, with no trigger and no synthetic mark, and ends it. + for (const [type, id] of [ + ["turn.started", "evt-goal-started"], + ["turn.completed", "evt-goal-completed"], + ] as const) { + harness.emit({ + type, + eventId: asEventId(id), + provider: ProviderDriverKind.make("codex"), + threadId: child, + createdAt: "2026-01-01T00:00:02.000Z", + turnId: asTurnId("goal-turn"), + ...(type === "turn.completed" ? { payload: { state: "completed" } } : {}), + } as never); + await harness.drain(); + } + const parentThread = await waitForThread( + harness.readModel, + (entry) => entry.session?.status !== undefined, + 10_000, + parent, + ); + // The request still waits for its own turn. + expect(parentThread.childRequests.open).toMatchObject([{ requestId, status: "running" }]); + }); + it("maps turn started/completed events into thread session updates", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; @@ -1758,12 +1881,26 @@ describe("ProviderRuntimeIngestion", () => { createdAt: now, turnId: asTurnId(`turn-${threadId}-${id}`), }); - await waitForThread( + const running = await waitForThread( harness.readModel, (thread) => thread.session?.activeTurnId === `turn-${threadId}-${id}`, 10_000, threadId, ); + // The reactor names the message its send started the turn for. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-carried-named-${threadId}-${id}`), + threadId, + session: running.session!, + turnStartedBy: { + messageId: asMessageId(`carried-${threadId}-${id}`), + turnId: asTurnId(`turn-${threadId}-${id}`), + }, + createdAt: now, + }), + ); harness.emit({ type: "turn.completed", eventId: asEventId(`evt-${threadId}-${id}-completed`), diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 04ec3a245..b28f483f5 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -3443,40 +3443,25 @@ const make = Effect.gen(function* () { } } - // A turn that starts now: the message it was asked with, or none (the - // provider started it: a check-back, a goal, background work that - // finished), so the decision knows what it owes a parent (rule 2) and - // the turn record is bound to the right message. A check-back says so - // itself, and is never the pending message's turn. + // A turn that starts now is recorded as the provider's, provisionally: + // this handler can't tell a message's turn from one the provider + // started (a check-back, a goal, background work that finished), so it + // never names a message. The reactor, which sent the message, names it + // with the turn's id once the provider took it, and that corrects this + // ("Restart and turn binding", rule B). The pending start is read only + // so the sweep leaves that message's report alone. const pendingTurnStart = event.type === "turn.started" ? yield* projectionTurnRepository .getPendingTurnStartByThreadId({ threadId: thread.id }) .pipe(Effect.orElseSucceed(() => Option.none())) : Option.none(); - const turnStartFields = (nextActiveTurnId: TurnId | null) => { - if ( - event.type !== "turn.started" || - nextActiveTurnId === null || - (activeTurnId !== null && sameId(activeTurnId, nextActiveTurnId)) - ) { - return {}; - } - // A turn Claude opened by itself (a background agent finishing, a - // check-back) says so; Threadlines starts a message's turn through - // the provider, never that way. - const providerOpened = - turnTriggerOf(event)?.kind === "check-back" || - event.raw?.method === "claude/synthetic-turn-start"; - const turnStartedBy: TurnStartedBy = - !providerOpened && - thread.session?.status === "starting" && - Option.isSome(pendingTurnStart) - ? { messageId: pendingTurnStart.value.messageId } - : { provider: true }; - return { turnStartedBy }; - }; - + const turnStartFields = (nextActiveTurnId: TurnId | null) => + event.type !== "turn.started" || + nextActiveTurnId === null || + (activeTurnId !== null && sameId(activeTurnId, nextActiveTurnId)) + ? {} + : { turnStartedBy: { provider: true } satisfies TurnStartedBy }; const conflictsWithActiveTurn = activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; diff --git a/apps/server/src/orchestration/childReports.ts b/apps/server/src/orchestration/childReports.ts index f56467954..baa3c6ac7 100644 --- a/apps/server/src/orchestration/childReports.ts +++ b/apps/server/src/orchestration/childReports.ts @@ -80,15 +80,6 @@ export interface TurnStartOrigin { readonly requestKind?: OrchestrationMessage["requestKind"]; } -/** - * Whether a message's own turn answers someone other than the thread's parent - * (rule 2): a person's, an outside agent's, the parent's request, a hand-off. - * A continue is judged by what it continues, so it never counts here. - */ -export function messageAnswersSomeoneElse(message: TurnStartOrigin): boolean { - return message.trigger === undefined && answersSomeoneElse(message); -} - /** Whether a message's own turn answers someone other than the thread's parent (rule 2). */ function answersSomeoneElse(origin: TurnStartOrigin): boolean { return ( diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 1026648a7..dab6c0367 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -2556,6 +2556,84 @@ describe("decider child reports", () => { expect(threadIn(archived.model, CHILD).parentAttachmentEpoch).toBe(1); }); + it("drops a continue's provisional report when its name says it continues a person's turn (round 4, finding 1)", async () => { + const family = await answeredFamily(); + const typed = await run(family, turnStart("typed", { composer: "typed" })); + const idle = { + ...typed.model, + threads: typed.model.threads.map((entry) => + entry.id === CHILD + ? { ...entry, session: session(CHILD, { status: "ready", activeTurnId: null }) } + : entry, + ), + }; + const continued = await run( + idle, + turnStart("switch", { trigger: "accountSwitch", createdAt: at(25) }), + ); + // Recorded as the provider's at first, then named by the reactor. + const provisional = await run(continued.model, providerTurn("continue-turn")); + expect(threadIn(provisional.model, CHILD).childRequests.owedReports).toMatchObject([ + { turnId: TurnId.make("continue-turn") }, + ]); + const named = await run(provisional.model, { + type: "thread.session.set", + commandId: CommandId.make("session-named-continue"), + threadId: CHILD, + session: session(CHILD, { activeTurnId: TurnId.make("continue-turn"), updatedAt: at(31) }), + turnStartedBy: { messageId: MessageId.make("switch"), turnId: TurnId.make("continue-turn") }, + createdAt: at(31), + }); + expect(threadIn(named.model, CHILD).childRequests.owedReports).toBeUndefined(); + }); + + it("retries the message whose start failed last, not a report put back before it (round 4, finding 2)", async () => { + const { model: starting, report } = await reportStarting(); + const failed = (model: OrchestrationReadModel) => ({ + ...model, + threads: model.threads.map((entry) => + entry.id === PARENT + ? { + ...entry, + session: session(PARENT, { + status: "error", + activeTurnId: null, + lastError: "spawn failed", + }), + } + : entry, + ), + }); + // A fails to start and is put back. + const putBack = await run(failed(starting), takeBack(report.messageId)); + // The user types B, and B fails while it is prepared. + const typed = await run(failed(putBack.model), { + type: "thread.turn.start", + commandId: CommandId.make("turn-b"), + threadId: PARENT, + message: { + messageId: MessageId.make("message-b"), + role: "user", + text: "Ship it.", + attachments: [], + }, + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + composer: "typed", + createdAt: at(70), + }); + const retried = await run(failed(typed.model), { + type: "thread.turn.retry", + commandId: CommandId.make("retry-b"), + threadId: PARENT, + createdAt: at(80), + }); + const started = (retried.events as ReadonlyArray<OrchestrationEvent>).find( + (event) => event.type === "thread.turn-start-requested", + ); + expect(started?.payload).toMatchObject({ messageId: MessageId.make("message-b") }); + }); + it("hands a leaving agent's queued follow-up report to the thread's own agent, and takes its answers off", async () => { const reviewer = "reviewer" as never; const queued = (id: string, followUp: boolean) => ({ diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 119bd0eab..0fbc5d746 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -124,7 +124,6 @@ import { import { continuedTurnMessage, decideChildReportSettle, - messageAnswersSomeoneElse, owedReportStamps, settleWaitingAnswer, turnStartOwesReport, @@ -4191,12 +4190,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }); } // A child's report whose start failed was put back on the queue - // ("Restart and turn binding", rule A): that is the failed turn, so the - // user's Retry sends it, never an earlier message of theirs. + // ("Restart and turn binding", rule A). When it is the last start that + // failed (nothing started from a message since it was put back), the + // user's Retry sends it, never an earlier message of theirs; a message + // tried since is retried itself. const putBack = (targetThread.queuedFollowUps ?? []).find( (queued) => queued.putBack === true, ); - if (command.type === "thread.turn.retry" && putBack !== undefined) { + const triedSincePutBack = + putBack !== undefined && + turnMessages.some( + (message) => + message.role === "user" && + Date.parse(message.createdAt) > Date.parse(putBack.createdAt), + ); + if (command.type === "thread.turn.retry" && putBack !== undefined && !triedSincePutBack) { return yield* decideCommandSequence({ commands: [ { @@ -5355,41 +5363,58 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // The turn claims the message that started it ("Restart and turn // binding", rule B): its owed report is keyed by the turn from here on, // and a parent's request it answers records the turn, so every later - // reader knows the turn by its id, never by its message. A writer that - // names the message may come after one that took the same turn for the - // provider's (Claude says a turn started before its send returns): the - // name wins, whether or not the turn is new. - const namedTurnId = - command.session.status === "running" && - command.session.activeTurnId !== null && - command.turnStartedBy !== undefined && - "messageId" in command.turnStartedBy - ? command.session.activeTurnId - : null; - const startedMessageId = - namedTurnId !== null && - command.turnStartedBy !== undefined && - "messageId" in command.turnStartedBy - ? command.turnStartedBy.messageId + // reader knows the turn by its id, never by its message. Only the writer + // that sent the message names it, and every other start was recorded as + // the provider's: the name corrects that, whether or not the turn is + // still running (it names the turn by its id). + const named = + command.turnStartedBy !== undefined && "messageId" in command.turnStartedBy + ? command.turnStartedBy : null; + const namedTurnId = + named === null + ? null + : (named.turnId ?? + (command.session.status === "running" ? command.session.activeTurnId : null)); + const startedMessageId = named !== null && namedTurnId !== null ? named.messageId : null; const owedReportBinds = startedMessageId !== null && + namedTurnId !== null && (thread.childRequests.owedReports ?? []).some( (entry) => "messageId" in entry && entry.messageId === startedMessageId, ) - ? startedMessageId + ? { messageId: startedMessageId, turnId: namedTurnId } : null; - // Named for a message that owes nothing (a person's, a request's): a - // report recorded for the turn as the provider's goes. + // Named for a message that owes nothing (a person's, a request's, a + // continue of either): a report recorded for the turn as the + // provider's goes. Judged as the turn's start was (rule 2). const namedMessage = startedMessageId === null ? undefined : thread.messages.find((message) => message.id === startedMessageId); + const namedOwesNothing = + namedMessage !== undefined && + turnStartOwesReport(readModel, thread, namedMessage, { + origin: + namedMessage.trigger === undefined + ? undefined + : continuedTurnMessage(thread, namedMessage.participantId ?? null, namedMessage.id), + answersRequest: ( + (thread.parentThreadId === null + ? undefined + : readModel.threads.find((entry) => entry.id === thread.parentThreadId) + )?.childRequests.open ?? [] + ).some( + (request) => + request.childThreadId === thread.id && + request.status === "running" && + request.childMessageId === namedMessage.id, + ), + }) === undefined; const providerEntryCorrected: ReadonlyArray<PlannedOrchestrationEvent> = namedTurnId !== null && owedReportBinds === null && - namedMessage !== undefined && - messageAnswersSomeoneElse(namedMessage) && + namedOwesNothing && (thread.childRequests.owedReports ?? []).some((entry) => isOwedReport(entry, { turnId: namedTurnId }), ) diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index dd1045db0..955164bba 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -1826,13 +1826,12 @@ export function projectEvent( const owedReport = payload.owedReport; const binds = payload.owedReportBinds; - const activeTurnId = payload.session.activeTurnId; const withOwed = updateChildRequests(nextBase, payload.threadId, (state) => { const added = owedReport === undefined ? state : childRequestStateOn.owedAdded(state, owedReport); - return binds === undefined || activeTurnId === null + return binds === undefined ? added - : childRequestStateOn.owedBound(added, binds, activeTurnId); + : childRequestStateOn.owedBound(added, binds.messageId, binds.turnId); }); return { ...withOwed, diff --git a/docs/design/agent-autonomy-no-limits.md b/docs/design/agent-autonomy-no-limits.md index 69f4b65a7..829aee663 100644 --- a/docs/design/agent-autonomy-no-limits.md +++ b/docs/design/agent-autonomy-no-limits.md @@ -198,22 +198,22 @@ What existing behavior this touches: - **A failed start, with no restart.** New: a report whose turn could not start waits at the front of the queue instead of sitting in the chat unheard. The queue is not sent on by itself after a failure (rule 10), so this can't loop. - **Older clients.** `putBack` and `answeringTurnId` are optional fields on things that exist. An older client places a put-back entry last, which only changes the order it shows. No new event type. -Fixed after Astra's third review of step 2 (3fddb66bc), as built: +Fixed after Astra's third and fourth reviews of step 2 (3fddb66bc, c90d3d3d4), as built: -- A writer that names a turn's message wins over an earlier writer that took the same turn for the provider's, whether or not the turn is new: a person's message drops the turn's owed entry, a message that owes a report takes the entry over. -- The user's Retry after a report's failed start sends that report, not an earlier message of theirs. -- The user's own `thread.session.stop` holds a thread with a family, as their Stop does. The server's own session stops say why (`cause`: `family` for `thread.children.stop`, `cleanup` for archive, the sweeper and a link) and leave no new hold. +- **Only the writer that sent a message names it.** Ingestion records every turn start as the provider's, provisionally, and never names a pending message. The reactor names the message it sent, with the turn's id, once the provider took the turn (`turnStartedBy: { messageId, turnId }`). That name corrects the provisional record whether or not the turn is new: a message that owes a report takes the turn's entry over, and one that owes nothing (a person's, a request's, or a continue of either, judged by the turn it continues as rule 2 says) drops it. A parent's request records the turn either way. A turn the provider starts with no trigger (a Codex goal) while a message is being prepared stays the provider's, so it can never answer that message's request. +- The user's Retry after a report's failed start sends that report, unless a message was tried since it was put back: then that message is retried. +- The user's own `thread.session.stop` holds a thread with a family, as their Stop does. The server's own session stops say why (`cause`: `family` for `thread.children.stop`, `cleanup` for archive, the sweeper and a link). A cause only leaves out that family reason for the hold: the agents' chain hold (a room, an agent's message in the queue) applies to every session stop as before. - At startup a turn a Stop named is dropped, not reported as cut off by the restart. - A report's start is taken back before the session is marked interrupted at startup, and before a failed start's failure is recorded, so a stop in between can't leave it out of the queue. - The startup send of a queued report has its own command id each startup. -- A continue after a restart is judged by the turn the restart cut (its turn record's message), so a check-back's turn is never continued. +- A continue after a restart is judged by the turn the restart cut: its turn record's message, or, when the reactor had not named it yet, the start still pending. A check-back's turn is never continued. - Archiving a child moves its attachment epoch, as separating does, so no report it owed comes back after it is restored. Known limits, accepted (T3 Code has no crash recovery at all): - A process that stops after a report's start was taken back but before the session was marked interrupted gives the parent a "turn interrupted by a restart" note at the next startup. The report itself is still at the front of the queue and is sent. -- A parent whose session was neither starting nor running when the process stopped (a check-back of its own held the active turn, say) gets no take-back at startup: a report taken off its queue in that moment stays in the chat, unheard by the agent until something else wakes it. -- A turn the provider starts with no trigger and no synthetic mark (a Codex goal) while a message is being prepared is taken for that message's turn. The driver gives no signal. +- Crash only: a parent whose active turn belonged to a check-back when the process stopped gets no take-back at startup, so a report taken off its queue in that moment stays in the chat, unheard by the agent until something else wakes it. Taking it back from the pending start alone is not safe: a report whose turn the provider took but the reactor had not yet named looks the same, and would run twice. +- A turn that ends before the reactor's acknowledgement of its send (the provider fails it at once) keeps the provider's record: in a child, a person's failed turn can report its failure upward, and a request it was for settles through the stopped-session backstop instead of at the turn's end. - Session updates stored before turn binding carry no `turnStartedBy`. Replaying them does not bind turns, which matters only if the turns projection were rebuilt from the event log. - Only a child's report is taken back. Other agent messages cut before their start behave as before (a hand-off is closed as failed at startup). diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 7b6c45656..10339f667 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -3095,16 +3095,17 @@ export const OwedChildReport = Schema.Union([ export type OwedChildReport = typeof OwedChildReport.Type; /** - * What started the turn a session update marks running, from the writer that - * knows: the message it was asked with, or the provider with no message (a - * check-back, a goal, background work that finished). The decision records - * the report a provider-started turn owes a parent (docs/design/ - * agent-autonomy-no-limits.md, rules 2 and 3), and the turn record is bound - * to the pending message only when this names it. Absent: the writer can't - * tell, and the pending message, if any, is taken as the turn's. + * What started a turn (docs/design/agent-autonomy-no-limits.md, "Restart and + * turn binding"). Only the writer that sent a message names it: the reactor, + * once the provider took the turn for it, with the turn's id (`turnId`, which + * may have ended or been superseded by then). Every other turn start is + * recorded as the provider's, provisionally: a report a provider-started turn + * owes a parent is recorded, and the naming update corrects it. The turn + * record is bound to the pending message only when a writer names it. + * Absent: nothing to say about what started the turn. */ export const TurnStartedBy = Schema.Union([ - Schema.Struct({ messageId: MessageId }), + Schema.Struct({ messageId: MessageId, turnId: Schema.optional(TurnId) }), Schema.Struct({ provider: Schema.Literal(true) }), ]); export type TurnStartedBy = typeof TurnStartedBy.Type; @@ -7259,12 +7260,12 @@ export const ThreadSessionSetPayload = Schema.Struct({ /** See TurnStartedBy. */ turnStartedBy: Schema.optional(TurnStartedBy), /** - * The message this turn took owed the parent a report: its entry, keyed by - * the message until now, is keyed by the session's active turn from here - * on (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", + * The message a turn took owed the parent a report: its entry, keyed by + * the message until now, is keyed by that turn from here on + * (docs/design/agent-autonomy-no-limits.md, "Restart and turn binding", * rule B). */ - owedReportBinds: Schema.optional(MessageId), + owedReportBinds: Schema.optional(Schema.Struct({ messageId: MessageId, turnId: TurnId })), }); /** The user closed this error's notice; see `OrchestrationSession.lastErrorDismissedAt`. */ From 53e3ecff6519a3ed7c42306f570894fe01441e22 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:42:45 -0500 Subject: [PATCH 12/16] feat(server): hold child thread requests and continues to the sender's access ceiling Stage 1 step 3 of docs/design/agent-autonomy-no-limits.md. - Carries requestCeiling (and passBlocked when under a lead pass) on local and linked child requests, continues (usage-limit reset, restart, account switch), and retries/resends. - Checks the ceiling at send time, at every stored-message turn start, and again in ProviderCommandReactor after rereading the thread. - Advertises enforcesRequestCeiling on PeerDescriptor, refuses narrower sends to older peers, records launchedAccess on remoteOrigin, and holds older-sender and pre-upgrade queued requests to it. - Adds nullable-column migration 124 for projection_thread_messages (request_ceiling, pass_blocked) and projection_threads (stops_with_parent). --- apps/server/src/links/LinkRequests.ts | 9 + .../src/links/RemoteChildReactor.test.ts | 117 ++++++ apps/server/src/links/RemoteChildReactor.ts | 31 +- apps/server/src/links/peerRoute.ts | 1 + apps/server/src/mcp/threadToolHandlers.ts | 15 + .../Layers/ChildThreadReactor.ts | 2 + .../Layers/ProjectionPipeline.ts | 4 + .../Layers/ProjectionSnapshotQuery.ts | 19 + .../Layers/ProviderCommandReactor.ts | 47 +++ .../orchestration/Layers/ThreadBootstrap.ts | 1 + .../orchestration/Services/ThreadBootstrap.ts | 3 + .../src/orchestration/childThreadDecisions.ts | 31 ++ .../decider.childThreads.test.ts | 358 ++++++++++++++++++ apps/server/src/orchestration/decider.ts | 258 ++++++++++++- apps/server/src/orchestration/projector.ts | 10 + .../Layers/ProjectionThreadMessages.ts | 18 + .../persistence/Layers/ProjectionThreads.ts | 5 + apps/server/src/persistence/Migrations.ts | 2 + .../124_ChildAccessAndStopColumns.ts | 35 ++ .../Services/ProjectionThreadMessages.ts | 3 + .../persistence/Services/ProjectionThreads.ts | 1 + packages/shared/src/childThreads.test.ts | 54 +++ packages/shared/src/childThreads.ts | 75 ++++ 23 files changed, 1086 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/124_ChildAccessAndStopColumns.ts diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 1472d1731..8addfdc64 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -928,6 +928,10 @@ const make = Effect.gen(function* () { environmentLabel: input.parent.environmentLabel, threadId: input.parent.threadId, threadTitle: input.parent.threadTitle, + launchedAccess: { + runtimeMode: launch.runtimeMode, + interactionMode: launch.interactionMode, + }, }; // Still open, and the link still lets it go on; a link that no // longer does ends it here, with the reason. @@ -957,6 +961,10 @@ const make = Effect.gen(function* () { kind: "request", environmentId: input.parent.environmentId, }, + requestCeiling: { + runtimeMode: launch.runtimeMode, + interactionMode: launch.interactionMode, + }, createdAt: row.createdAt, checkpoint: () => mayGoOn, }), @@ -1130,6 +1138,7 @@ const make = Effect.gen(function* () { kind: "request", environmentId: origin.environmentId, }, + ...(input.ceiling !== undefined ? { requestCeiling: input.ceiling } : {}), createdAt: row.createdAt, }, "queue a linked computer's message", diff --git a/apps/server/src/links/RemoteChildReactor.test.ts b/apps/server/src/links/RemoteChildReactor.test.ts index d55c8c464..6d6f5beaa 100644 --- a/apps/server/src/links/RemoteChildReactor.test.ts +++ b/apps/server/src/links/RemoteChildReactor.test.ts @@ -107,6 +107,8 @@ interface LinkedComputer { readonly watch?: ReadonlyArray<PeerWatchEvent>; /** It says how threads are filed and takes `peer.thread.wrap` (`PeerDescriptor.threadFiling`). */ readonly threadFiling?: boolean; + /** It enforces `PeerSendInput.ceiling` (`PeerDescriptor.enforcesRequestCeiling`). */ + readonly enforcesRequestCeiling?: boolean; } /** @@ -265,6 +267,9 @@ const makeComputer = Effect.gen(function* () { linked.start ?? (() => Effect.succeed({ status: "started" as const, threadId: REMOTE_CHILD })), ), + "peer.request.send": answer("peer.request.send", () => + Effect.succeed({ status: "queued" as const }), + ), } as unknown as PeerClient; const layer = RemoteChildReactorLive.pipe( Layer.provide( @@ -278,6 +283,9 @@ const makeComputer = Effect.gen(function* () { describe: () => Effect.succeed({ threadFiling: linked.threadFiling === true, + ...(linked.enforcesRequestCeiling === true + ? { enforcesRequestCeiling: true } + : {}), } as unknown as PeerDescriptor), noteRemoteLabel: () => undefined, }), @@ -758,4 +766,113 @@ it.layer(NodeServices.layer)("RemoteChildReactor", (it) => { assert.lengthOf((yield* computer.stored).childRequests?.open ?? [], 1); }), ); + + it.effect( + "carries the sender's ceiling to an updated peer, and refuses a narrower sender to an older peer", + () => + Effect.gen(function* () { + const submitSend = ( + computer: Effect.Success<typeof makeComputer>, + requestId: ChildRequestId, + runtimeMode: "auto-accept-edits" | "full-access", + ) => + Effect.gen(function* () { + yield* computer.askForThread; + yield* computer.recordRemote("running", { + status: "accepted", + threadId: REMOTE_CHILD, + }); + yield* computer.engine.dispatch({ + type: "thread.remote-child.update", + commandId: CommandId.make(`record-${requestId}`), + threadId: PARENT, + child: { + environmentId: MAC_MINI, + label: "Mac mini", + threadId: REMOTE_CHILD, + title: "Remote worker", + handle: "Claude", + attachmentEpoch: 0, + cachedStatus: "idle", + updatedAt: AT, + }, + createdAt: AT, + }); + yield* computer.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make(`mode-${requestId}`), + threadId: PARENT, + runtimeMode, + createdAt: AT, + }); + yield* computer.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make(`session-${requestId}`), + threadId: PARENT, + session: { + threadId: PARENT, + status: "running", + providerName: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runtimeMode, + activeTurnId: TurnId.make("turn-1"), + lastError: null, + updatedAt: AT, + }, + createdAt: AT, + }); + yield* computer.engine.dispatch({ + type: "thread.child.send", + commandId: CommandId.make(`send-${requestId}`), + threadId: PARENT, + requestId, + from: { participantId: null }, + callerTurnId: TurnId.make("turn-1"), + childThreadId: REMOTE_CHILD, + childMessageId: MessageId.make(`msg-${requestId}`), + text: "Check the build.", + createdAt: AT, + }); + }); + + // Narrow sender -> older peer (no enforcesRequestCeiling): refused and settled failed. + const older = yield* makeComputer; + yield* submitSend(older, ChildRequestId.make("req-older-narrow"), "auto-accept-edits"); + yield* older.boot({ enforcesRequestCeiling: false }); + yield* eventually( + Effect.map( + older.stored, + (parent) => + !(parent.childRequests?.open ?? []).some( + (entry) => entry.requestId === ChildRequestId.make("req-older-narrow"), + ), + ), + "narrow send to older peer settles failed", + ); + assert.deepEqual(older.callsTo("peer.request.send"), []); + + // Widest sender -> older peer: allowed, no ceiling can be broken. + const widest = yield* makeComputer; + yield* submitSend(widest, ChildRequestId.make("req-older-wide"), "full-access"); + yield* widest.boot({ enforcesRequestCeiling: false }); + yield* eventually( + Effect.sync(() => widest.callsTo("peer.request.send").length === 1), + "widest send to older peer goes through", + ); + + // Narrow sender -> updated peer: carries ceiling. + const updated = yield* makeComputer; + yield* submitSend(updated, ChildRequestId.make("req-updated-narrow"), "auto-accept-edits"); + yield* updated.boot({ enforcesRequestCeiling: true }); + yield* eventually( + Effect.sync(() => updated.callsTo("peer.request.send").length === 1), + "narrow send to updated peer goes through with ceiling", + ); + assert.deepEqual( + (updated.callsTo("peer.request.send")[0]?.payload as { readonly ceiling?: unknown }) + ?.ceiling, + { runtimeMode: "auto-accept-edits", interactionMode: "default" }, + ); + }), + ); }); diff --git a/apps/server/src/links/RemoteChildReactor.ts b/apps/server/src/links/RemoteChildReactor.ts index 917b54521..620fddde3 100644 --- a/apps/server/src/links/RemoteChildReactor.ts +++ b/apps/server/src/links/RemoteChildReactor.ts @@ -55,7 +55,13 @@ import { type ThreadId, TurnId, } from "@threadlines/contracts"; -import { remoteChildOf, sameRemoteThreadFiling } from "@threadlines/shared/childThreads"; +import { + effectiveRequestCeiling, + isWidestMode, + olderPeerCeilingRefusal, + remoteChildOf, + sameRemoteThreadFiling, +} from "@threadlines/shared/childThreads"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -98,7 +104,10 @@ export class RemoteChildReactor extends Context.Service< const nowIso = Effect.map(DateTime.now, DateTime.formatIso); /** What the reactor needs of a parent, read from its stored row. */ -type Parent = Pick<OrchestrationThread, "id" | "title" | "participants" | "childRequests"> & +type Parent = Pick< + OrchestrationThread, + "id" | "title" | "runtimeMode" | "interactionMode" | "participants" | "childRequests" +> & Pick<OrchestrationThread, "move" | "pendingMove"> & { readonly archivedAt: string | null; readonly deletedAt: string | null; @@ -243,6 +252,8 @@ const make = Effect.gen(function* () { : { id: found.value.threadId, title: found.value.title, + runtimeMode: found.value.runtimeMode, + interactionMode: found.value.interactionMode, participants: found.value.participants ?? [], childRequests: found.value.childRequests ?? EMPTY_CHILD_REQUEST_STATE, move: found.value.move ?? null, @@ -857,11 +868,27 @@ const make = Effect.gen(function* () { }); return true; } + const ceiling = request.requestCeiling ?? effectiveRequestCeiling(parent); + // An older peer can't enforce a ceiling: only a sender with the widest + // access sends it work (docs/design/agent-autonomy-no-limits.md, "Access"). + if (!isWidestMode(ceiling)) { + const descriptor = yield* client.describe(environmentId as EnvironmentId); + if (descriptor.enforcesRequestCeiling !== true) { + const reason = olderPeerCeilingRefusal(remote.label); + yield* settleRequest(parent, request, { + outcome: "failed", + text: reason, + error: reason, + }); + return true; + } + } const answer = yield* client.withPeer(environmentId as EnvironmentId, (peer) => peer["peer.request.send"]({ requestId: request.requestId, threadId: remote.threadId!, text, + ceiling, }), ); if (answer.status === "queued") { diff --git a/apps/server/src/links/peerRoute.ts b/apps/server/src/links/peerRoute.ts index feb398b8e..004dd27d3 100644 --- a/apps/server/src/links/peerRoute.ts +++ b/apps/server/src/links/peerRoute.ts @@ -226,6 +226,7 @@ export const makePeerRpcLayer = (input: { moveOutsideWork: true, moveFamilies: true, moveLinkLineage: true, + enforcesRequestCeiling: true, moveAdoptsChildren: true, threadFiling: true, outsideAgents: true, diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index 004259121..e1adf74b8 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -57,8 +57,11 @@ import { type ChildRequestRefusal, childSendRefusal, childStartRefusal, + effectiveRequestCeiling, isAttachedChild, + isWidestMode, leadPassRefusal, + olderPeerCeilingRefusal, ownChildRefusal, remoteChildOf, withinModeCeiling, @@ -2160,6 +2163,18 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { detail: `This computer is no longer linked to ${child.label}.`, } satisfies ThreadSendResult; } + // An older peer can't enforce our ceiling; refuse early when we know it. + if ( + computer.descriptor !== null && + computer.descriptor.enforcesRequestCeiling !== true && + !isWidestMode(effectiveRequestCeiling(thread)) + ) { + return { + outcome: "not_allowed", + detail: olderPeerCeilingRefusal(computer.label), + threadId: child.threadId, + } satisfies ThreadSendResult; + } const callerTurnId = thread.session?.activeTurnId ?? NO_TURN; const key = [ scope.threadId, diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index 739cd8891..72177ae6a 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -24,6 +24,7 @@ import * as Stream from "effect/Stream"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import { effectiveRequestCeiling } from "@threadlines/shared/childThreads"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { childHasLiveWork, @@ -267,6 +268,7 @@ export const makeChildThreadReactor = Effect.gen(function* () { // when it asked (an approval can come much later). launch: clampLaunchToCeiling(launch, parent), fromThread: { threadId: parent.id, requestId, kind: "request" }, + requestCeiling: request.requestCeiling ?? effectiveRequestCeiling(parent), createdAt: request.createdAt, }), ); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index eeee6a9b6..64b254c09 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1816,6 +1816,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ? { requestError: event.payload.requestError } : {}), ...(event.payload.afterMove === true ? { afterMove: true as const } : {}), + ...(event.payload.requestCeiling !== undefined + ? { requestCeiling: event.payload.requestCeiling } + : {}), + ...(event.payload.passBlocked === true ? { passBlocked: true as const } : {}), isStreaming: event.payload.streaming, createdAt: previousMessage?.createdAt ?? event.payload.createdAt, updatedAt: event.payload.updatedAt, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 9020410c7..2e8ecba6f 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -3,6 +3,7 @@ import { ChatSkillReferenceList, CheckpointRef, IsoDateTime, + LeadPassCeiling, MessageId, NonNegativeInt, OrchestrationCheckpointFile, @@ -173,6 +174,7 @@ type ThreadLineageRow = Pick< | "parentThreadId" | "parentTurnId" | "attachedToParent" + | "stopsWithParent" | "parentAttachmentEpoch" | "handedBackAt" | "handedBackTurnId" @@ -199,6 +201,7 @@ const threadLineageFields = (row: ThreadLineageRow) => ({ parentThreadId: row.parentThreadId ?? null, parentTurnId: row.parentTurnId ?? null, attachedToParent: (row.attachedToParent ?? 0) > 0, + ...((row.stopsWithParent ?? 0) > 0 ? { stopsWithParent: true as const } : {}), parentAttachmentEpoch: row.parentAttachmentEpoch ?? 0, handedBackAt: row.handedBackAt ?? null, handedBackTurnId: row.handedBackTurnId ?? null, @@ -243,6 +246,7 @@ const shellLineageFields = (row: ThreadLineageRow) => { parentThreadId: row.parentThreadId ?? null, parentTurnId: row.parentTurnId ?? null, attachedToParent: (row.attachedToParent ?? 0) > 0, + ...((row.stopsWithParent ?? 0) > 0 ? { stopsWithParent: true as const } : {}), handedBackAt: row.handedBackAt ?? null, handedBackTurnId: row.handedBackTurnId ?? null, awaitedChildThreadCount: awaitedChildRequestCount(childRequests), @@ -286,6 +290,8 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( trigger: Schema.NullOr(MessageTrigger), notSent: Schema.NullOr(Schema.Number), afterMove: Schema.optional(Schema.NullOr(Schema.Number)), + requestCeiling: Schema.optional(Schema.NullOr(Schema.fromJsonString(LeadPassCeiling))), + passBlocked: Schema.optional(Schema.NullOr(Schema.Number)), }), ); const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan.mapFields( @@ -676,6 +682,8 @@ function mapThreadMessageRow( ...(row.trigger !== null ? { trigger: row.trigger } : {}), ...(row.notSent === 1 ? { notSent: true as const } : {}), ...(row.afterMove === 1 ? { afterMove: true as const } : {}), + ...(row.requestCeiling != null ? { requestCeiling: row.requestCeiling } : {}), + ...(row.passBlocked === 1 ? { passBlocked: true as const } : {}), turnId: row.turnId, streaming: row.isStreaming === 1, createdAt: row.createdAt, @@ -979,6 +987,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", @@ -1053,6 +1062,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", @@ -1129,6 +1139,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", @@ -1198,6 +1209,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { message_trigger AS "trigger", not_sent AS "notSent", after_move AS "afterMove", + request_ceiling AS "requestCeiling", + pass_blocked AS "passBlocked", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -1260,6 +1273,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { message_trigger AS "trigger", not_sent AS "notSent", after_move AS "afterMove", + request_ceiling AS "requestCeiling", + pass_blocked AS "passBlocked", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -1994,6 +2009,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", @@ -2060,6 +2076,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { message_trigger AS "trigger", not_sent AS "notSent", after_move AS "afterMove", + request_ceiling AS "requestCeiling", + pass_blocked AS "passBlocked", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -3845,6 +3863,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index fc3393445..d46893516 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -58,6 +58,7 @@ import { isOwedReport, notesFor, remoteChildOf, + requestCeilingRefusalWords, withinModeCeiling, } from "@threadlines/shared/childThreads"; import { settingsChangeNotesFor } from "@threadlines/shared/settingsChangeState"; @@ -282,6 +283,13 @@ interface EnsureSessionOptions { * raised its access after the decider let the pass through. */ readonly passCeiling?: LeadPassCeiling; + /** + * The turn carries a parent's work or continues one (docs/design/ + * agent-autonomy-no-limits.md, "Access"): it runs only while the thread is + * within this ceiling, checked on the same read of the thread the session + * starts from. + */ + readonly requestCeiling?: LeadPassCeiling; /** * A turn that isn't from outside: an agent outside text reached * (OrchestrationOutsideWork) starts fresh for it, a new runtime with a @@ -1499,6 +1507,14 @@ const make = Effect.gen(function* () { detail: PASS_ABOVE_CEILING_DETAIL, }); } + const requestCeiling = options?.requestCeiling; + if (requestCeiling !== undefined && !withinModeCeiling(thread, requestCeiling)) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(undefined), + method: "thread.turn.start", + detail: requestCeilingRefusalWords(thread.title), + }); + } const sessionKey = participantSessionKey(threadId, participantId); const shedsOutsideWork = options?.shedOutsideWork === true && @@ -2522,6 +2538,8 @@ const make = Effect.gen(function* () { readonly fromThread?: ThreadMessageOrigin | undefined; /** An outside agent's turn: runs only within its ceiling. */ readonly fromOutside?: OutsideTurnOrigin | undefined; + /** A parent request's (or its continue's) access limit. */ + readonly requestCeiling?: LeadPassCeiling | undefined; /** * A person sent it from the app (`sentFrom`): an agent outside text * reached starts fresh for it (EnsureSessionOptions.shedOutsideWork). @@ -2586,6 +2604,7 @@ const make = Effect.gen(function* () { // resend of a pass carries no origin on its turn. const storedMessage = thread.messages.find((message) => message.id === input.messageId); const passCeiling = storedMessage?.fromThread?.ceiling ?? input.fromThread?.ceiling; + const requestCeiling = storedMessage?.requestCeiling ?? input.requestCeiling; // Marked as never sent while this turn was prepared (a retry the user // made just before the mark landed): it stays unsent. if (passCeiling !== undefined && storedMessage?.notSent === true) { @@ -2603,6 +2622,7 @@ const make = Effect.gen(function* () { ...(forkFrom !== undefined ? { forkFrom } : {}), ...(input.fromOutside !== undefined ? { outsideCeiling: input.fromOutside } : {}), ...(passCeiling !== undefined ? { passCeiling } : {}), + ...(requestCeiling !== undefined ? { requestCeiling } : {}), ...(input.sentByPerson === true && input.fromOutside === undefined ? { shedOutsideWork: true } : {}), @@ -2647,6 +2667,30 @@ const make = Effect.gen(function* () { detail: PASS_ABOVE_CEILING_DETAIL, }); } + // A parent's request (or its continue) goes only to a runtime within its + // ceiling, re-read on the thread now (the user may have widened it while + // the session was prepared). + const latestForCeiling = + requestCeiling === undefined ? undefined : ((yield* resolveThread(input.threadId)) ?? thread); + if ( + requestCeiling !== undefined && + latestForCeiling !== undefined && + ((activeSession !== undefined && + exceedsRuntimeMode(activeSession.runtimeMode, requestCeiling.runtimeMode)) || + !withinModeCeiling( + { + runtimeMode: latestForCeiling.runtimeMode, + interactionMode: latestForCeiling.interactionMode, + }, + requestCeiling, + )) + ) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(activeSession?.provider), + method: "thread.turn.start", + detail: requestCeilingRefusalWords(latestForCeiling.title), + }); + } // In a room, what the other agents said and changed since this agent's // conversation was last caught up. Built now, from the thread as it stands // when the turn is sent; the cursor is only kept for the conversation it @@ -3740,6 +3784,9 @@ const make = Effect.gen(function* () { ...(event.payload.fromOutside !== undefined ? { fromOutside: event.payload.fromOutside } : {}), + ...(event.payload.requestCeiling !== undefined + ? { requestCeiling: event.payload.requestCeiling } + : {}), sentByPerson: message.sentFrom !== undefined, createdAt: event.payload.createdAt, }).pipe( diff --git a/apps/server/src/orchestration/Layers/ThreadBootstrap.ts b/apps/server/src/orchestration/Layers/ThreadBootstrap.ts index 2386dbbd5..c82894c2f 100644 --- a/apps/server/src/orchestration/Layers/ThreadBootstrap.ts +++ b/apps/server/src/orchestration/Layers/ThreadBootstrap.ts @@ -734,6 +734,7 @@ const make = Effect.gen(function* () { runtimeMode: launch.runtimeMode, interactionMode: launch.interactionMode, ...(input.fromThread !== undefined ? { fromThread: input.fromThread } : {}), + ...(input.requestCeiling !== undefined ? { requestCeiling: input.requestCeiling } : {}), ...(input.lineage.kind === "scheduled" ? { scheduledTaskId: input.lineage.scheduledRun.taskId } : {}), diff --git a/apps/server/src/orchestration/Services/ThreadBootstrap.ts b/apps/server/src/orchestration/Services/ThreadBootstrap.ts index e796e47d1..fcf6d9515 100644 --- a/apps/server/src/orchestration/Services/ThreadBootstrap.ts +++ b/apps/server/src/orchestration/Services/ThreadBootstrap.ts @@ -25,6 +25,7 @@ import type { ChildRequestId, ChildThreadLaunch, IsoDateTime, + LeadPassCeiling, MessageId, OrchestrationCommand, OrchestrationDispatchCommandError, @@ -99,6 +100,8 @@ export interface ChildBootstrapInput { readonly launch: ChildThreadLaunch; /** The first message's origin, `kind: "request"`; none for a scheduled run. */ readonly fromThread?: ThreadMessageOrigin | undefined; + /** The sender's access limit kept on the first message (MessageAccessFields). */ + readonly requestCeiling?: LeadPassCeiling | undefined; /** When the request was made; the child is created with this stamp. */ readonly createdAt: IsoDateTime; /** diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 11285b250..796902b1b 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -41,8 +41,10 @@ import { childAttachRefusal, childSendRefusal, childStartRefusal, + effectiveRequestCeiling, isAttachedChild, isSettingUpChildStart, + narrowerModeCeiling, ownChildRefusal, remoteChildOf, leadPassRefusal, @@ -453,6 +455,7 @@ export function decideChildStart( } } } + const requestCeiling = effectiveRequestCeiling(parent); return command.children.map((child): PlannedEvent => ({ ...baseFor(parent.id), type: "thread.child-request-submitted", @@ -468,6 +471,7 @@ export function decideChildStart( status: command.mode === "ask" ? "awaiting_user" : "starting", childThreadId: child.childThreadId, childMessageId: child.childMessageId, + requestCeiling, launch: child.launch, ...(child.launch.target !== undefined ? { @@ -614,6 +618,10 @@ export function decideChildSend( requestId: command.requestId, kind: "request" as const, }; + const accessFields = { + requestCeiling: effectiveRequestCeiling(parent), + ...(parent.childRequests.passCeiling !== undefined ? { passBlocked: true as const } : {}), + }; return [ ...(checkout === undefined ? [] @@ -673,6 +681,7 @@ export function decideChildSend( status: "queued", childThreadId: child.id, childMessageId: command.childMessageId, + ...accessFields, createdAt: command.createdAt, }, createdAt: command.createdAt, @@ -688,6 +697,7 @@ export function decideChildSend( text: command.text, attachments: [], fromThread, + ...accessFields, turnId: null, streaming: false, createdAt: command.createdAt, @@ -704,6 +714,7 @@ export function decideChildSend( text: command.text, attachments: [], fromThread, + ...accessFields, runtimeMode: child.runtimeMode, interactionMode: child.interactionMode, createdAt: command.createdAt, @@ -837,6 +848,10 @@ function decideRemoteChildSend( ) { return refuse("That thread is still being set up. Send it a message once it has started."); } + const accessFields = { + requestCeiling: effectiveRequestCeiling(parent), + ...(parent.childRequests.passCeiling !== undefined ? { passBlocked: true as const } : {}), + }; return [ { ...baseFor(parent.id), @@ -854,6 +869,7 @@ function decideRemoteChildSend( childThreadId: remoteChild.threadId, childMessageId: command.childMessageId, text: command.text, + ...accessFields, remote: { environmentId: remoteChild.environmentId, label: remoteLabelOf(parent, remoteChild.environmentId, remoteChild.label), @@ -1297,6 +1313,19 @@ export function decideRemoteRequestQueue( if (thread.messages.some((message) => message.id === command.messageId)) { return refuse("That message was already sent."); } + // Older senders send no ceiling: hold the request to the thread's access + // now, or to the access the link started the thread with if narrower + // (docs/design/agent-autonomy-no-limits.md, "Access", sequence 2). + const requestCeiling = + command.requestCeiling ?? + narrowerModeCeiling(origin.launchedAccess, { + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + }); + const accessFields = { + requestCeiling, + ...(command.passBlocked === true ? { passBlocked: true as const } : {}), + }; return [ { ...baseFor(thread.id), @@ -1308,6 +1337,7 @@ export function decideRemoteRequestQueue( text: command.text, attachments: [], fromThread: command.fromThread, + ...accessFields, turnId: null, streaming: false, createdAt: command.createdAt, @@ -1324,6 +1354,7 @@ export function decideRemoteRequestQueue( text: command.text, attachments: [], fromThread: command.fromThread, + ...accessFields, runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode, createdAt: command.createdAt, diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index dab6c0367..a1c9ef8b7 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -2685,3 +2685,361 @@ describe("decider child reports", () => { expect(threadIn(left.model, PARENT).queuedFollowUps?.[0]?.participantId).toBeUndefined(); }); }); + +describe("child thread access ceilings (stage 1 step 3)", () => { + const run = async (model: OrchestrationReadModel, command: OrchestrationCommand) => { + const decided = await Effect.runPromise( + decideOrchestrationCommand({ command, readModel: model }), + ); + const events = Array.isArray(decided) ? decided : [decided]; + let next = model; + for (const event of events) { + next = await Effect.runPromise( + projectEvent(next, { + ...event, + sequence: next.snapshotSequence + 1, + } as OrchestrationEvent), + ); + } + return { events: events as ReadonlyArray<OrchestrationEvent>, model: next }; + }; + + const threadIn = (model: OrchestrationReadModel, id: ThreadId) => + model.threads.find((entry) => entry.id === id)!; + + it("unqueues a parent's request and fails it when the child was widened before its turn starts", async () => { + const start = readModel([ + thread(PARENT, { + runtimeMode: "auto-accept-edits", + session: session(PARENT, { status: "running", activeTurnId: CALLER_TURN }), + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + runtimeMode: "auto-accept-edits", + session: session(CHILD, { status: "ready", activeTurnId: null }), + }), + ]); + const requestId = ChildRequestId.make("req-wide"); + const messageId = MessageId.make("msg-wide"); + const sent = await run(start, { + type: "thread.child.send", + commandId: CommandId.make("send-wide"), + threadId: PARENT, + requestId, + from: PRIMARY, + callerTurnId: CALLER_TURN, + childThreadId: CHILD, + childMessageId: messageId, + text: "Check the build.", + createdAt: at(10), + }); + expect(threadIn(sent.model, CHILD).queuedFollowUps?.[0]?.requestCeiling).toEqual({ + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }); + // The user widens the child before the queued request runs. + const widened = await run(sent.model, { + type: "thread.runtime-mode.set", + commandId: CommandId.make("widen-child"), + threadId: CHILD, + runtimeMode: "full-access", + createdAt: at(15), + }); + const drained = await run(widened.model, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("drain-wide"), + threadId: CHILD, + messageId, + createdAt: at(20), + }); + expect(threadIn(drained.model, CHILD).queuedFollowUps ?? []).toHaveLength(0); + expect(drained.events.some((event) => event.type === "thread.turn-start-requested")).toBe( + false, + ); + // The parent's open request settles failed with the ceiling refusal. + expect(threadIn(drained.model, PARENT).childRequests.open).toHaveLength(0); + const settled = drained.events.find((event) => event.type === "thread.child-request-settled"); + expect(settled?.payload).toMatchObject({ requestId, outcome: "failed" }); + }); + + it("refuses a usage-limit continue when the child was widened, and settles the held request failed", async () => { + const requestId = ChildRequestId.make("req-limit"); + const requestMessageId = MessageId.make("msg-limit"); + const limitAt = at(20); + const resetAt = at(30); + const start = readModel([ + thread(PARENT, { + runtimeMode: "auto-accept-edits", + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + open: [ + { + requestId, + batchId: ChildRequestBatchId.make("batch-limit"), + kind: "send", + from: PRIMARY, + callerTurnId: CALLER_TURN, + deliveryEpoch: 0, + status: "running", + childThreadId: CHILD, + childMessageId: requestMessageId, + requestCeiling: { + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }, + createdAt: at(5), + }, + ], + }, + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + runtimeMode: "full-access", + messages: [ + { + id: requestMessageId, + role: "user", + text: "Do the check.", + fromThread: { threadId: PARENT, requestId, kind: "request" }, + requestCeiling: { + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }, + turnId: null, + streaming: false, + createdAt: at(5), + updatedAt: at(5), + }, + ], + session: session(CHILD, { + status: "error", + activeTurnId: null, + lastError: "Usage limit reached", + lastErrorAt: limitAt, + continueAtReset: { resetsAt: resetAt, at: resetAt }, + }), + }), + ]); + const fired = await run(start, { + type: "thread.continue-at-reset.fire", + commandId: CommandId.make("fire-continue"), + threadId: CHILD, + messageId: MessageId.make("msg-continue"), + lastErrorAt: limitAt, + createdAt: at(35), + }); + expect(threadIn(fired.model, CHILD).session?.continueAtReset ?? null).toBeNull(); + expect(fired.events.some((event) => event.type === "thread.turn-start-requested")).toBe(false); + expect(threadIn(fired.model, PARENT).childRequests.open).toHaveLength(0); + const settled = fired.events.find((event) => event.type === "thread.child-request-settled"); + expect(settled?.payload).toMatchObject({ requestId, outcome: "failed" }); + }); + + it("holds an older linked computer's request (and pre-upgrade queued work) to launchedAccess (sequence 2)", async () => { + const REMOTE_ENV = EnvironmentId.make("env-old"); + const REMOTE_PARENT = ThreadId.make("remote-parent"); + const remoteOrigin = { + linkDeviceId: "dev-old", + environmentId: REMOTE_ENV, + environmentLabel: "Old Mac", + threadId: REMOTE_PARENT, + threadTitle: "Old parent", + launchedAccess: { + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }, + }; + const fromThread = { + threadId: REMOTE_PARENT, + requestId: ChildRequestId.make("req-remote-1"), + kind: "request" as const, + environmentId: REMOTE_ENV, + }; + // 1) Widened child: no ceiling in -> gets launchedAccess -> turn refused. + const widenedModel = readModel([ + thread(CHILD, { + runtimeMode: "full-access", + remoteOrigin, + session: session(CHILD, { status: "ready", activeTurnId: null }), + }), + ]); + const queuedWidened = await run(widenedModel, { + type: "thread.remote-request.queue", + commandId: CommandId.make("remote-q-wide"), + threadId: CHILD, + messageId: MessageId.make("remote-msg-wide"), + text: "Check logs.", + fromThread, + createdAt: at(10), + }); + expect(threadIn(queuedWidened.model, CHILD).queuedFollowUps?.[0]?.requestCeiling).toEqual( + remoteOrigin.launchedAccess, + ); + const triedWidened = await run(queuedWidened.model, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("remote-send-wide"), + threadId: CHILD, + messageId: MessageId.make("remote-msg-wide"), + createdAt: at(15), + }); + expect(triedWidened.events.some((event) => event.type === "thread.turn-start-requested")).toBe( + false, + ); + expect(threadIn(triedWidened.model, CHILD).queuedFollowUps ?? []).toHaveLength(0); + + // 2) Unchanged child: runs as today. + const unchangedModel = readModel([ + thread(CHILD, { + runtimeMode: "auto-accept-edits", + remoteOrigin, + session: session(CHILD, { status: "ready", activeTurnId: null }), + }), + ]); + const queuedUnchanged = await run(unchangedModel, { + type: "thread.remote-request.queue", + commandId: CommandId.make("remote-q-ok"), + threadId: CHILD, + messageId: MessageId.make("remote-msg-ok"), + text: "Check logs.", + fromThread, + createdAt: at(10), + }); + const triedUnchanged = await run(queuedUnchanged.model, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("remote-send-ok"), + threadId: CHILD, + messageId: MessageId.make("remote-msg-ok"), + createdAt: at(15), + }); + expect( + triedUnchanged.events.some((event) => event.type === "thread.turn-start-requested"), + ).toBe(true); + + // 3) Pre-upgrade queued entry (no requestCeiling on entry or message) on a widened child. + const preUpgradeId = MessageId.make("remote-msg-legacy"); + const legacyModel = readModel([ + thread(CHILD, { + runtimeMode: "full-access", + remoteOrigin, + session: session(CHILD, { status: "ready", activeTurnId: null }), + messages: [ + { + id: preUpgradeId, + role: "user", + text: "Legacy work.", + fromThread, + turnId: null, + streaming: false, + createdAt: at(5), + updatedAt: at(5), + }, + ], + queuedFollowUps: [ + { + messageId: preUpgradeId, + text: "Legacy work.", + attachments: [], + fromThread, + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(5), + }, + ], + }), + ]); + const triedLegacy = await run(legacyModel, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("remote-send-legacy"), + threadId: CHILD, + messageId: preUpgradeId, + createdAt: at(20), + }); + expect(triedLegacy.events.some((event) => event.type === "thread.turn-start-requested")).toBe( + false, + ); + expect(threadIn(triedLegacy.model, CHILD).queuedFollowUps ?? []).toHaveLength(0); + }); + + it("propagates a pass block to a child's turn and lifts it on the parent's next unblocked request", async () => { + const passCeiling = { + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }; + const start = readModel([ + thread(PARENT, { + runtimeMode: "auto-accept-edits", + session: session(PARENT, { status: "running", activeTurnId: CALLER_TURN }), + childRequests: { ...EMPTY_CHILD_REQUEST_STATE, passCeiling }, + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + runtimeMode: "auto-accept-edits", + session: session(CHILD, { status: "ready", activeTurnId: null }), + }), + ]); + const req1 = ChildRequestId.make("req-pass-1"); + const msg1 = MessageId.make("msg-pass-1"); + const sent = await run(start, { + type: "thread.child.send", + commandId: CommandId.make("send-pass-1"), + threadId: PARENT, + requestId: req1, + from: PRIMARY, + callerTurnId: CALLER_TURN, + childThreadId: CHILD, + childMessageId: msg1, + text: "Handle passed work.", + createdAt: at(10), + }); + expect(threadIn(sent.model, CHILD).queuedFollowUps?.[0]?.passBlocked).toBe(true); + const started = await run(sent.model, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("drain-pass-1"), + threadId: CHILD, + messageId: msg1, + createdAt: at(15), + }); + expect(threadIn(started.model, CHILD).childRequests.passCeiling).toEqual(passCeiling); + + // Parent's pass block lifts when user writes there; next request has no passBlocked -> lifts child's block. + const parentCleared: OrchestrationReadModel = { + ...started.model, + threads: started.model.threads.map((entry) => + entry.id === PARENT + ? { + ...entry, + childRequests: { ...EMPTY_CHILD_REQUEST_STATE, open: [] }, + } + : entry.id === CHILD + ? { ...entry, session: session(CHILD, { status: "ready", activeTurnId: null }) } + : entry, + ), + }; + const req2 = ChildRequestId.make("req-pass-2"); + const msg2 = MessageId.make("msg-pass-2"); + const sent2 = await run(parentCleared, { + type: "thread.child.send", + commandId: CommandId.make("send-pass-2"), + threadId: PARENT, + requestId: req2, + from: PRIMARY, + callerTurnId: CALLER_TURN, + childThreadId: CHILD, + childMessageId: msg2, + text: "Normal work now.", + createdAt: at(25), + }); + expect(threadIn(sent2.model, CHILD).queuedFollowUps?.[0]?.passBlocked).toBeUndefined(); + const started2 = await run(sent2.model, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("drain-pass-2"), + threadId: CHILD, + messageId: msg2, + createdAt: at(30), + }); + expect(threadIn(started2.model, CHILD).childRequests.passCeiling).toBeUndefined(); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 0fbc5d746..b1872044b 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -52,9 +52,12 @@ import { secretRequestIdOfAnswerMessage } from "@threadlines/shared/secretReques import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; import { + effectiveRequestCeiling, isAttachedChild, isOwedReport, + narrowerModeCeiling, passCeilingRefusal, + requestCeilingRefusal, } from "@threadlines/shared/childThreads"; import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; @@ -97,6 +100,7 @@ import { personWrote, childArchivePlan, childDeletionEvents, + childReportMessageId, childRevertRefusal, childrenArchivedWith, decideChildDeliveriesStop, @@ -363,6 +367,72 @@ function resetChildRequestsForUser( ]; } +/** + * The access limit a stored or incoming message carries into `thread` + * (docs/design/agent-autonomy-no-limits.md, "Access"): its recorded + * `requestCeiling`, or, for a parent's request queued or started before the + * ceiling existed, the parent's access now (on this computer) or the narrower + * of the link's launch access and this thread's access (over a link). + */ +function storedRequestCeiling( + readModel: OrchestrationReadModel, + thread: OrchestrationThread, + message: { + readonly requestCeiling?: OrchestrationMessage["requestCeiling"]; + readonly fromThread?: OrchestrationMessage["fromThread"]; + }, +): OrchestrationMessage["requestCeiling"] { + if (message.requestCeiling !== undefined) { + return message.requestCeiling; + } + const origin = message.fromThread; + if (origin?.kind !== "request" || origin.ceiling !== undefined) { + return undefined; + } + if (origin.environmentId === undefined) { + const parent = readModel.threads.find((entry) => entry.id === origin.threadId); + return parent === undefined ? undefined : effectiveRequestCeiling(parent); + } + return narrowerModeCeiling(thread.remoteOrigin?.launchedAccess, { + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + }); +} + +/** + * The access limit and pass block a continue inherits from the turn it + * continues (docs/design/agent-autonomy-no-limits.md, "Access"): every + * continue (usage limit reset, restart, account switch) keeps the ceiling of + * the message that started that turn. + */ +function continuedMessageAccess( + readModel: OrchestrationReadModel, + thread: OrchestrationThread, + participantId: ThreadParticipantId | null, + excludeMessageId: MessageId, + originMessageId?: MessageId | null, +): { + readonly requestCeiling: OrchestrationMessage["requestCeiling"]; + readonly passBlocked: true | undefined; +} { + const origin = + originMessageId !== undefined && originMessageId !== null + ? (thread.messages.find((entry) => entry.id === originMessageId) ?? + continuedTurnMessage(thread, participantId, excludeMessageId)) + : continuedTurnMessage(thread, participantId, excludeMessageId); + if (origin === undefined) { + return { requestCeiling: undefined, passBlocked: undefined }; + } + const requestCeiling = + origin.requestCeiling ?? + origin.fromThread?.ceiling ?? + storedRequestCeiling(readModel, thread, origin); + return { + requestCeiling, + passBlocked: origin.passBlocked === true ? (true as const) : undefined, + }; +} + /** * A pass whose ceiling is under the thread's access when its turn would * start (docs/design/lead-chat.md, "Access"): it never runs and its message @@ -3728,6 +3798,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: passStartRefusal, }); } + // A parent's request (and any continue of its turn) never starts above + // the sender's access ceiling (docs/design/agent-autonomy-no-limits.md). + const continuedStartAccess = + command.trigger !== undefined && isContinueTrigger(command.trigger) + ? continuedMessageAccess( + readModel, + targetThread, + command.participantId ?? null, + command.message.messageId, + ) + : { requestCeiling: undefined, passBlocked: undefined }; + const turnRequestCeiling = + command.requestCeiling ?? + continuedStartAccess.requestCeiling ?? + storedRequestCeiling(readModel, targetThread, command); + const turnPassBlocked = + command.passBlocked === true || continuedStartAccess.passBlocked === true + ? (true as const) + : undefined; + const requestStartRefusal = requestCeilingRefusal(turnRequestCeiling, targetThread); + if (requestStartRefusal !== null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: requestStartRefusal, + }); + } // An outside agent's turn (docs/design/outside-agents.md): only in a // thread it started (any thread at Work), never above its ceiling, // never into a busy thread (an answer's own turn passes over its @@ -3888,6 +3984,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.composer !== undefined ? { composer: command.composer } : {}), ...(command.sentFrom !== undefined ? { sentFrom: command.sentFrom } : {}), ...(command.trigger !== undefined ? { trigger: command.trigger } : {}), + ...(turnRequestCeiling !== undefined ? { requestCeiling: turnRequestCeiling } : {}), + ...(turnPassBlocked === true ? { passBlocked: true as const } : {}), // Named as the turn is sent (recordTurnModel). A queued message an // agent wrote is already recorded, with its own stamps; sending it // must not restamp it. @@ -4033,6 +4131,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" : {}), ...(command.fromThread !== undefined ? { fromThread: command.fromThread } : {}), ...(command.fromOutside !== undefined ? { fromOutside: command.fromOutside } : {}), + ...(turnRequestCeiling !== undefined ? { requestCeiling: turnRequestCeiling } : {}), + ...(turnPassBlocked === true ? { passBlocked: true as const } : {}), ...(command.scheduledTaskId !== undefined ? { scheduledTaskId: command.scheduledTaskId } : {}), @@ -4079,10 +4179,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }, ] : []; - // A lead chat's pass starting its turn: until the user writes, no - // threads may be started from here, and its ceiling holds what this - // thread sends on (docs/design/lead-chat.md, "No fan-out"). - const passCeiling = command.fromThread?.ceiling; + // A lead chat's pass (or a parent's request sent while its own pass + // block was active) starting its turn: until the user writes, or the + // parent sends a fresh unblocked request, no threads may be started from + // here, and its ceiling holds what this thread sends on. + const passCeiling = + command.fromThread?.ceiling ?? (turnPassBlocked === true ? turnRequestCeiling : undefined); const passStartedEvents: ReadonlyArray<PlannedOrchestrationEvent> = passCeiling !== undefined ? [ @@ -4099,7 +4201,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }, }, ] - : []; + : command.fromThread?.kind === "request" && + command.fromThread.ceiling === undefined && + turnPassBlocked !== true + ? resetChildRequestsForUser(targetThread, turnBase, command.createdAt) + : []; // A turn starting while the thread waited to continue after a usage // limit ends that wait; the request it held won't get its continue. // (The continue itself, which the fire starts, answers it instead.) @@ -4268,6 +4374,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: `${retryPassRefusal} Send it yourself to run it.`, }); } + const retryRequestCeiling = storedRequestCeiling(readModel, targetThread, lastUserMessage); + const retryRequestRefusal = requestCeilingRefusal(retryRequestCeiling, targetThread); + if (retryRequestRefusal !== null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: retryRequestRefusal, + }); + } // A failed turn is retried with the agent that failed it: the slot // still holds that agent's session. const retryParticipantId = sessionSlotParticipantId(session); @@ -4348,6 +4462,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" runtimeMode: targetThread.runtimeMode, interactionMode: targetThread.interactionMode, ...(lastUserMessage.skills !== undefined ? { skills: lastUserMessage.skills } : {}), + ...(retryRequestCeiling !== undefined ? { requestCeiling: retryRequestCeiling } : {}), + ...(lastUserMessage.passBlocked === true ? { passBlocked: true as const } : {}), chainEpoch: targetThread.agentRequests.chainEpoch, createdAt: command.createdAt, // A resend runs the same message again, so its turn owes what that @@ -4661,6 +4777,64 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command.createdAt, ); } + // A parent's request runs only within the sender's ceiling (or, for work + // queued before the ceiling existed, the parent's access now / the link's + // launch access). If the thread was widened since, the request is taken + // back and the parent's open request settles failed. + const existingStoredMessage = targetThread.messages.find( + (message) => message.id === queued.messageId, + ); + const queuedRequestCeiling = + queued.requestCeiling ?? + existingStoredMessage?.requestCeiling ?? + storedRequestCeiling(readModel, targetThread, queued); + const queuedPassBlocked = + queued.passBlocked === true || existingStoredMessage?.passBlocked === true + ? (true as const) + : undefined; + const queuedCeilingRefusal = requestCeilingRefusal(queuedRequestCeiling, targetThread); + if (queuedCeilingRefusal !== null) { + const settledParent = + fromThread?.kind === "request" && fromThread.environmentId === undefined + ? (() => { + const parent = readModel.threads.find((entry) => entry.id === fromThread.threadId); + const open = parent?.childRequests.open.find( + (entry) => + entry.requestId === fromThread.requestId && + entry.childThreadId === targetThread.id, + ); + return parent !== undefined && open !== undefined + ? { parentId: parent.id, requestId: open.requestId } + : null; + })() + : null; + const settledEvents = + settledParent === null + ? [] + : yield* decideCommandSequence({ + readModel, + commands: [ + { + type: "thread.child-request.settle", + commandId: command.commandId, + threadId: settledParent.parentId, + requestId: settledParent.requestId, + outcome: "failed", + reply: { + messageId: childReportMessageId(settledParent.requestId), + text: queuedCeilingRefusal, + turnId: null, + }, + error: queuedCeilingRefusal, + createdAt: command.createdAt, + }, + ], + }); + return [ + { ...unqueuedEvent, payload: { ...unqueuedEvent.payload, reason: "cancelled" } }, + ...settledEvents, + ]; + } // A message an agent queued carries no model: its agent's current one // applies (the thread's own model for the thread's own agent), so a // model change since it was queued is honored. @@ -4800,6 +4974,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" runtimeMode, interactionMode, ...(fromThread !== undefined ? { fromThread } : {}), + ...(queuedRequestCeiling !== undefined ? { requestCeiling: queuedRequestCeiling } : {}), + ...(queuedPassBlocked === true ? { passBlocked: true as const } : {}), // Only the user's own queued message carries it. ...(!agentQueued && queued.composer !== undefined ? { composer: queued.composer } : {}), ...(!agentQueued && queued.sentFrom !== undefined ? { sentFrom: queued.sentFrom } : {}), @@ -4858,11 +5034,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" (entry) => entry.requestId === queued.requestId, ); const sentEvents: PlannedOrchestrationEvent[] = turnEvents - .filter( - (event) => - event.type !== "thread.agent-requests-reset" && - event.type !== "thread.child-requests-reset", - ) + .filter((event) => event.type !== "thread.agent-requests-reset") .map((event): PlannedOrchestrationEvent => { if ( event.type !== "thread.message-sent" || @@ -5793,7 +5965,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" return cleared; } // A Codex goal the limit paused picks up by itself once it is active; in - // a room it belongs to the agent holding the slot. + // a room it belongs to the agent holding the slot. Otherwise the continue + // keeps the access ceiling of the turn it continues: if the thread was + // widened above it while waiting, the wait ends and any held request + // settles failed (docs/design/agent-autonomy-no-limits.md, "Access"). + const continuedAccess = continuedMessageAccess( + readModel, + thread, + participantId, + command.messageId, + ); + if (thread.goal?.status !== "usageLimited") { + const continueCeilingRefusal = requestCeilingRefusal( + continuedAccess.requestCeiling, + thread, + ); + if (continueCeilingRefusal !== null) { + const ended = yield* decideHeldRequestsEnd({ + readModel, + child: thread, + outcome: "failed", + why: continueCeilingRefusal, + createdAt: command.createdAt, + }); + return [cleared, ...ended]; + } + } const continueCommand: OrchestrationCommand = thread.goal?.status === "usageLimited" ? { @@ -5817,6 +6014,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode, trigger: "usageLimitReset", + ...(continuedAccess.requestCeiling !== undefined + ? { requestCeiling: continuedAccess.requestCeiling } + : {}), + ...(continuedAccess.passBlocked === true ? { passBlocked: true as const } : {}), createdAt: command.createdAt, }; const continued = yield* decideCommandSequence({ @@ -5904,6 +6105,37 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }, }; } + const restartAccess = continuedMessageAccess( + readModel, + thread, + verdict.participantId, + command.messageId, + command.turnMessageId, + ); + const restartCeilingRefusal = requestCeilingRefusal(restartAccess.requestCeiling, thread); + if (restartCeilingRefusal !== null) { + return { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.activity-appended", + payload: { + threadId: command.threadId, + activity: { + id: command.activityId, + tone: "error", + kind: "provider.session.restart-interrupted", + summary: "Turn interrupted by a server restart", + payload: { detail: restartCeilingRefusal }, + turnId: command.turnId, + createdAt: command.createdAt, + }, + }, + }; + } return yield* decideCommandSequence({ commands: [ { @@ -5920,6 +6152,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode, trigger: "serverRestart", + ...(restartAccess.requestCeiling !== undefined + ? { requestCeiling: restartAccess.requestCeiling } + : {}), + ...(restartAccess.passBlocked === true ? { passBlocked: true as const } : {}), createdAt: command.createdAt, }, ], diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 955164bba..18f044e1f 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -1522,6 +1522,10 @@ export function projectEvent( : {}), ...(payload.requestError !== undefined ? { requestError: payload.requestError } : {}), ...(payload.afterMove === true ? { afterMove: true as const } : {}), + ...(payload.requestCeiling !== undefined + ? { requestCeiling: payload.requestCeiling } + : {}), + ...(payload.passBlocked === true ? { passBlocked: true as const } : {}), turnId: payload.turnId, streaming: payload.streaming, createdAt: payload.createdAt, @@ -1566,6 +1570,12 @@ export function projectEvent( ...(entry.afterMove === true || message.afterMove === true ? { afterMove: true as const } : {}), + ...(entry.requestCeiling === undefined && message.requestCeiling !== undefined + ? { requestCeiling: message.requestCeiling } + : {}), + ...(entry.passBlocked === true || message.passBlocked === true + ? { passBlocked: true as const } + : {}), } : entry, ) diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts index 50060df01..e67c1070d 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -7,6 +7,7 @@ import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; import { IsoDateTime, + LeadPassCeiling, SideTurnId, ChatAttachmentListLenient, ChatSkillReferenceList, @@ -64,6 +65,8 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields( trigger: Schema.NullOr(MessageTrigger), notSent: Schema.NullOr(Schema.Number), afterMove: Schema.NullOr(Schema.Number), + requestCeiling: Schema.NullOr(Schema.fromJsonString(LeadPassCeiling)), + passBlocked: Schema.NullOr(Schema.Number), }), ); @@ -100,6 +103,8 @@ function toProjectionThreadMessage( ...(row.trigger !== null ? { trigger: row.trigger } : {}), ...(row.notSent === 1 ? { notSent: true as const } : {}), ...(row.afterMove === 1 ? { afterMove: true as const } : {}), + ...(row.requestCeiling !== null ? { requestCeiling: row.requestCeiling } : {}), + ...(row.passBlocked === 1 ? { passBlocked: true as const } : {}), }; } @@ -146,6 +151,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { message_trigger, not_sent, after_move, + request_ceiling, + pass_blocked, is_streaming, created_at, updated_at @@ -191,6 +198,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { ${row.trigger ?? null}, ${row.notSent === true ? 1 : null}, ${row.afterMove === true ? 1 : null}, + ${row.requestCeiling !== undefined ? JSON.stringify(row.requestCeiling) : null}, + ${row.passBlocked === true ? 1 : null}, ${row.isStreaming ? 1 : 0}, ${row.createdAt}, ${row.updatedAt} @@ -234,6 +243,11 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { message_trigger = COALESCE(projection_thread_messages.message_trigger, excluded.message_trigger), not_sent = COALESCE(excluded.not_sent, projection_thread_messages.not_sent), after_move = COALESCE(excluded.after_move, projection_thread_messages.after_move), + request_ceiling = COALESCE( + projection_thread_messages.request_ceiling, + excluded.request_ceiling + ), + pass_blocked = COALESCE(projection_thread_messages.pass_blocked, excluded.pass_blocked), is_streaming = excluded.is_streaming, created_at = CASE WHEN ${appendText ? 1 : 0} = 1 THEN projection_thread_messages.created_at @@ -284,6 +298,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { message_trigger AS "trigger", not_sent AS "notSent", after_move AS "afterMove", + request_ceiling AS "requestCeiling", + pass_blocked AS "passBlocked", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" @@ -325,6 +341,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { message_trigger AS "trigger", not_sent AS "notSent", after_move AS "afterMove", + request_ceiling AS "requestCeiling", + pass_blocked AS "passBlocked", is_streaming AS "isStreaming", created_at AS "createdAt", updated_at AS "updatedAt" diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index 6c56c6a8c..e2b3760ff 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -127,6 +127,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { parent_thread_id, parent_turn_id, attached_to_parent, + stops_with_parent, parent_attachment_epoch, handed_back_at, handed_back_turn_id, @@ -196,6 +197,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { ${row.parentThreadId ?? null}, ${row.parentTurnId ?? null}, ${row.attachedToParent ?? null}, + ${row.stopsWithParent ?? null}, ${row.parentAttachmentEpoch ?? null}, ${row.handedBackAt ?? null}, ${row.handedBackTurnId ?? null}, @@ -269,6 +271,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { parent_thread_id = excluded.parent_thread_id, parent_turn_id = excluded.parent_turn_id, attached_to_parent = excluded.attached_to_parent, + stops_with_parent = excluded.stops_with_parent, parent_attachment_epoch = excluded.parent_attachment_epoch, handed_back_at = excluded.handed_back_at, handed_back_turn_id = excluded.handed_back_turn_id, @@ -341,6 +344,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", @@ -415,6 +419,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { parent_thread_id AS "parentThreadId", parent_turn_id AS "parentTurnId", attached_to_parent AS "attachedToParent", + stops_with_parent AS "stopsWithParent", parent_attachment_epoch AS "parentAttachmentEpoch", handed_back_at AS "handedBackAt", handed_back_turn_id AS "handedBackTurnId", diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index a3a3473a3..0e377f4c2 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -143,6 +143,7 @@ import Migration0120 from "./Migrations/120_ThreadAdoptedFromLink.ts"; import Migration0121 from "./Migrations/121_ProjectionThreadSecretRequests.ts"; import Migration0122 from "./Migrations/122_ProjectBriefs.ts"; import Migration0123 from "./Migrations/123_ProjectNotes.ts"; +import Migration0124 from "./Migrations/124_ChildAccessAndStopColumns.ts"; /** * Migration loader with all migrations defined inline. @@ -278,6 +279,7 @@ export const migrationEntries = [ [121, "ProjectionThreadSecretRequests", Migration0121], [122, "ProjectBriefs", Migration0122], [123, "ProjectNotes", Migration0123], + [124, "ChildAccessAndStopColumns", Migration0124], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/124_ChildAccessAndStopColumns.ts b/apps/server/src/persistence/Migrations/124_ChildAccessAndStopColumns.ts new file mode 100644 index 000000000..14bec64e0 --- /dev/null +++ b/apps/server/src/persistence/Migrations/124_ChildAccessAndStopColumns.ts @@ -0,0 +1,35 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Child-thread access ceilings and loose-thread stop tracking + * (docs/design/agent-autonomy-no-limits.md, "Access" and "Stop"): + * - `projection_thread_messages.request_ceiling` (JSON `LeadPassCeiling`) and + * `pass_blocked` (1 or null): kept on the message so a continue or retry + * after a restart holds the same access ceiling. + * - `projection_threads.stops_with_parent` (1 or null): a thread started + * without report back stays in its starter's Stop reach until a person + * writes in it or puts it back. + * + * Nullable columns with no defaults; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const messageColumns = yield* sql<{ readonly name: string }>` + SELECT name FROM pragma_table_info('projection_thread_messages') + `; + if (!messageColumns.some((column) => column.name === "request_ceiling")) { + yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN request_ceiling TEXT`; + } + if (!messageColumns.some((column) => column.name === "pass_blocked")) { + yield* sql`ALTER TABLE projection_thread_messages ADD COLUMN pass_blocked INTEGER`; + } + + const threadColumns = yield* sql<{ readonly name: string }>` + SELECT name FROM pragma_table_info('projection_threads') + `; + if (!threadColumns.some((column) => column.name === "stops_with_parent")) { + yield* sql`ALTER TABLE projection_threads ADD COLUMN stops_with_parent INTEGER`; + } +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts index 01e0f023a..c5a910312 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadMessages.ts @@ -17,6 +17,7 @@ import { ThreadParticipantId, TurnId, IsoDateTime, + MessageAccessFields, MessageAgentModel, MessageComposer, MessageSentFrom, @@ -83,6 +84,8 @@ export const ProjectionThreadMessage = Schema.Struct({ notSent: Schema.optional(Schema.Literal(true)), /** See OrchestrationMessage.afterMove. Once set, kept. */ afterMove: Schema.optional(Schema.Literal(true)), + /** See MessageAccessFields. Written with the message and kept. */ + ...MessageAccessFields, isStreaming: Schema.Boolean, createdAt: IsoDateTime, updatedAt: IsoDateTime, diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 026c1110e..88bcc0c97 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -187,6 +187,7 @@ export const ProjectionThread = Schema.Struct({ parentThreadId: Schema.optional(Schema.NullOr(ThreadId)), parentTurnId: Schema.optional(Schema.NullOr(TurnId)), attachedToParent: Schema.optional(Schema.NullOr(NonNegativeInt)), + stopsWithParent: Schema.optional(Schema.NullOr(NonNegativeInt)), parentAttachmentEpoch: Schema.optional(Schema.NullOr(NonNegativeInt)), handedBackAt: Schema.optional(Schema.NullOr(IsoDateTime)), handedBackTurnId: Schema.optional(Schema.NullOr(TurnId)), diff --git a/packages/shared/src/childThreads.test.ts b/packages/shared/src/childThreads.test.ts index 129720f5c..bac9f5ca9 100644 --- a/packages/shared/src/childThreads.test.ts +++ b/packages/shared/src/childThreads.test.ts @@ -16,10 +16,13 @@ import { childRequestStateOn, childSendRefusal, childStartRefusal, + effectiveRequestCeiling, isHandedBackCompletion, isStillGoing, + isWidestMode, remoteChildrenOf, remoteChildStartsOf, + requestCeilingRefusal, stillGoingInputOfShell, stopReachOf, type StillGoingInput, @@ -357,3 +360,54 @@ describe("isStillGoing", () => { ); }); }); + +describe("request ceiling helpers", () => { + it("refuses a send when the child has more access than its parent", () => { + const parent = caller({ runtimeMode: "auto-accept-edits", interactionMode: "default" }); + const wideChild = { + id: CHILD, + title: "Worker", + parentThreadId: PARENT, + attachedToParent: true, + archivedAt: null, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + }; + expect(childSendRefusal(parent, wideChild, { from: PRIMARY, callerTurnId: TURN })).toEqual({ + outcome: "not_allowed", + detail: + "'Worker' has more access than this thread has now. Do the work here, or tell the user, who can send it there.", + }); + expect( + childSendRefusal( + parent, + { ...wideChild, runtimeMode: "approval-required" }, + { from: PRIMARY, callerTurnId: TURN }, + ), + ).toBeNull(); + }); + + it("narrows effectiveRequestCeiling by passCeiling and detects widest access", () => { + expect( + effectiveRequestCeiling({ + runtimeMode: "full-access", + interactionMode: "default", + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + passCeiling: { runtimeMode: "auto-accept-edits", interactionMode: "plan" }, + }, + }), + ).toEqual({ runtimeMode: "auto-accept-edits", interactionMode: "plan" }); + expect(isWidestMode({ runtimeMode: "full-access", interactionMode: "default" })).toBe(true); + expect(isWidestMode({ runtimeMode: "full-access", interactionMode: "plan" })).toBe(false); + expect(isWidestMode({ runtimeMode: "auto-accept-edits", interactionMode: "default" })).toBe( + false, + ); + expect( + requestCeilingRefusal( + { runtimeMode: "auto-accept-edits", interactionMode: "default" }, + { title: "Worker", runtimeMode: "full-access", interactionMode: "default" }, + ), + ).toContain("'Worker' has more access"); + }); +}); diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 49fac151b..bd512e625 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -42,6 +42,8 @@ export interface ChildRequestCaller { readonly id: ThreadId; readonly parentThreadId: ThreadId | null; readonly attachedToParent: boolean; + readonly runtimeMode?: RuntimeMode | undefined; + readonly interactionMode?: ProviderInteractionMode | undefined; readonly session: { readonly participantId?: ThreadParticipantId | null | undefined; readonly activeTurnId: TurnId | null; @@ -147,6 +149,7 @@ export function childSendRefusal( thread: ChildRequestCaller, child: { readonly id: ThreadId; + readonly title?: string | undefined; readonly parentThreadId: ThreadId | null; readonly attachedToParent: boolean; readonly archivedAt: string | null; @@ -190,6 +193,24 @@ export function childSendRefusal( }; } } + // A parent's work never runs in a child with more access than the parent + // has now (docs/design/agent-autonomy-no-limits.md, "Access"). + if ( + child !== null && + thread.runtimeMode !== undefined && + thread.interactionMode !== undefined && + child.runtimeMode !== undefined && + child.interactionMode !== undefined && + !withinModeCeiling( + { runtimeMode: child.runtimeMode, interactionMode: child.interactionMode }, + { runtimeMode: thread.runtimeMode, interactionMode: thread.interactionMode }, + ) + ) { + return { + outcome: "not_allowed", + detail: requestCeilingRefusalWords(child.title ?? "That thread"), + }; + } return null; } @@ -388,6 +409,60 @@ export function leadPassRefusal( return null; } +/** The widest access a thread can have: no ceiling can be broken above this. */ +export const WIDEST_MODE_CEILING: LeadPassCeiling = { + runtimeMode: "full-access", + interactionMode: "default", +}; + +/** Whether `modes` is the widest access there is. */ +export function isWidestMode(modes: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; +}): boolean { + return withinModeCeiling(WIDEST_MODE_CEILING, modes); +} + +/** The access limit a thread's outgoing requests carry: its own, or its pass's if narrower. */ +export function effectiveRequestCeiling(thread: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly childRequests: { readonly passCeiling?: LeadPassCeiling | undefined }; +}): LeadPassCeiling { + return narrowerModeCeiling(thread.childRequests.passCeiling, { + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + }); +} + +/** Refusal wording when a receiving thread has more access than a parent's request allows. */ +export function requestCeilingRefusalWords(title: string): string { + return `'${title}' has more access than this thread has now. Do the work here, or tell the user, who can send it there.`; +} + +/** Refusal wording when a linked computer is too old to enforce a narrower sender's ceiling. */ +export function olderPeerCeilingRefusal(label: string): string { + return `${label} runs an older Threadlines that can't hold this thread's access limit. Update it, or send the work yourself.`; +} + +/** + * Why a request or its continue can't start a turn in `thread` now: the + * thread has more access than `ceiling` allows (docs/design/ + * agent-autonomy-no-limits.md, "Access"). + */ +export function requestCeilingRefusal( + ceiling: LeadPassCeiling | undefined, + thread: { + readonly title: string; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, +): string | null { + return ceiling === undefined || withinModeCeiling(thread, ceiling) + ? null + : requestCeilingRefusalWords(thread.title); +} + /** * Why a stored message can't start a turn in `thread` now: it is a pass whose * ceiling is under the thread's access at this moment. Every decision that From ad4554e7a7126eede1d31fd0f8def4f14b39fb4c Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:28:23 -0500 Subject: [PATCH 13/16] feat(server): stop reaches families, loose threads, and saved check-backs Stop now stops attached and flagged loose threads in one decision without putting new holds on children, marks saved check-backs dormant when their runtime ends, waits on in-flight reports before moving, lets delete name exact child ids, and carries chainEpoch on fallback resends. --- apps/server/src/guide/topics.ts | 6 +- apps/server/src/mcp/threadToolHandlers.ts | 15 +- apps/server/src/moves/MoveQueue.ts | 9 +- .../Layers/ProjectionPipeline.ts | 16 +- .../Layers/ProviderCommandReactor.ts | 8 +- .../Layers/ProviderRuntimeIngestion.test.ts | 78 ++++ .../Layers/ProviderRuntimeIngestion.ts | 33 +- .../orchestration/Layers/ThreadBootstrap.ts | 1 + .../orchestration/agentRequestDecisions.ts | 13 +- .../src/orchestration/childThreadDecisions.ts | 177 ++++++-- .../decider.childThreads.test.ts | 392 +++++++++++++++++- .../orchestration/decider.threadMoves.test.ts | 88 +++- apps/server/src/orchestration/decider.ts | 166 ++++++-- apps/server/src/orchestration/projector.ts | 19 +- .../src/orchestration/threadMoveDecisions.ts | 76 +++- .../outsideAgents/connectToolHandlers.test.ts | 19 + .../src/outsideAgents/connectToolHandlers.ts | 27 +- .../Layers/ProviderSessionReaper.test.ts | 62 +++ .../provider/Layers/ProviderSessionReaper.ts | 42 +- apps/web/src/store.ts | 4 +- docs/design/child-threads.md | 6 +- packages/contracts/src/orchestration.ts | 10 +- packages/shared/src/checkBacks.ts | 17 +- packages/shared/src/childThreads.ts | 9 + packages/shared/src/roomAgentRequests.ts | 9 +- 25 files changed, 1181 insertions(+), 121 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index e34af8b97..bf622610a 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -111,9 +111,9 @@ Whether the thread's agent may bring in another model on its own is {place:threa Once a thread it started has finished, the agent can wrap it up itself (thread_wrap), so you don't have to. It moves to Wrapped as with your own Wrap up, and its answer counts as seen. You can reopen it, and it comes back by itself when it gets new work. A thread still working or waiting for you isn't wrapped up. -A thread that keeps working after its answer went back (a check-back woke it, or a reviewer it asked replied) doesn't wake the parent. Its latest reply is passed to the parent's agent at that agent's next turn, and the thread then wraps up by itself. A thread the agent stops with thread_stop wraps up by itself too, and its check-backs end, as with your Stop. +A thread that takes another turn on its own after its answer went back (a check-back woke it, or a reviewer it asked replied) wakes its parent with that reply too, and then wraps up by itself. A thread the agent stops with thread_stop wraps up by itself too, and its check-backs end, as with your Stop. -{place:threads.agentThreads} decides this: Off, Ask me first (a card in the chat lists the threads and you decide), or Automatic. The same setting covers agents creating or changing scheduled tasks. There's no limit on how many threads an agent starts or how many messages it sends them, so an agent can keep a team of threads going for hours without you writing. Stop on the parent stops its agent and its threads' answers coming back, but the threads keep working; "Stop N working threads" in the parent's menu stops them too. +{place:threads.agentThreads} decides this: Off, Ask me first (a card in the chat lists the threads and you decide), or Automatic. The same setting covers agents creating or changing scheduled tasks. There's no limit on how many threads an agent starts or how many messages it sends them, so an agent can keep a team of threads going for hours without you writing. Stop on a thread stops its agent and every thread under it that is still going (including a thread it started without report back until you write in it, and any thread that only holds a check-back); "Stop N working threads" in the thread's menu and the Stop button on the family tab row stop those threads while leaving the thread itself running. A thread can't be reverted while threads under it are still going. A started thread works in a worktree of its own; in a project without git it shares the project's folder. With {place:threads.agentThreadsShareWorktrees} on, an agent can instead put a thread in a checkout that already exists: its own, or that of a thread it started. The new thread sees the files as they are there, uncommitted changes included, which suits a reviewer for work another thread just finished. An agent can also move an idle thread into such a checkout with a message, and the thread keeps its conversation. The thread the checkout belongs to must not be working at that moment. No worktree or branch is made and the project's setup script does not run. The two threads then share one set of files, so only one should work at a time. The thread's row under the message box reads Shared worktree. This works on one computer only, and not for threads an outside agent starts. @@ -141,7 +141,7 @@ A project's lead chat is a thread set up to coordinate the project; see the lead Any thread can be the lead. The first time a thread in a project with no lead starts threads of its own, a line under its tabs offers to make it the lead; close it and it doesn't come back for that project. Or use "Make this the lead chat" in a thread's menu (right-click its row, or click the title above the chat), or the command palette. The project's menu in the project picker has Open lead chat, or New lead chat, which starts a thread in the project folder and makes it the lead. "Go to lead chat" in the command palette opens it. -The lead can also pass a message to a thread you started by hand in the project. That is one-way: the thread works on it and answers there, not back in the lead, and it can't start threads of its own for it until you write there. The lead can't pass work into a room, a thread another thread still owns, or one you stopped. A pass never runs with more access than the lead had. +The lead can also pass a message to a thread you started by hand in the project. That is one-way: the thread works on it and answers there, not back in the lead, and it can't start threads of its own for it until you write there (and neither can the threads it messages). The lead can't pass work into a room, a thread another thread still owns, or one you stopped. A pass never runs with more access than the lead had. When an agent asks to start several threads, the card has a checkbox per thread, so you can start some and leave the rest; the agent is told which. diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index e1adf74b8..64c94e4a6 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -50,7 +50,6 @@ import { TurnId, } from "@threadlines/contracts"; import { placeMarkdownLink } from "@threadlines/shared/appPlaces"; -import { hasLiveCheckBack } from "@threadlines/shared/checkBacks"; import { areFilesystemPathsEqual } from "@threadlines/shared/path"; import { saferRuntimeMode } from "@threadlines/shared/runtimeMode"; import { @@ -77,6 +76,7 @@ import { checkoutMoveRefusal, childHasLiveWork, pendingChildRequest, + threadIsStillGoing, } from "../orchestration/childThreadDecisions.ts"; import type { ProjectPlace } from "../project/projectPlace.ts"; import { linkMessageId, linkThreadId } from "../links/linkIds.ts"; @@ -333,17 +333,10 @@ const remoteLabel = (thread: OrchestrationThread, environmentId: string) => ?.remote?.label ?? "the other computer"; -/** Whether a child has anything to stop: work in flight, a check-back that - * would wake it later, or work its parent still waits on. */ +/** Whether a child has anything to stop: the shared "still going" test, or + * an open request its parent still waits on. */ const childHasWork = (child: OrchestrationThread, parent: OrchestrationThread) => - child.latestTurn?.state === "running" || - hasLiveCheckBack(child) || - (child.session !== null && - (child.session.activeTurnId !== null || - child.session.status === "running" || - child.session.status === "starting" || - (child.session.pendingBackgroundTaskCount ?? 0) > 0)) || - (child.queuedFollowUps ?? []).some((entry) => entry.fromThread?.threadId === parent.id) || + threadIsStillGoing(child) || parent.childRequests.open.some( (request) => request.childThreadId === child.id && request.status !== "awaiting_user", ); diff --git a/apps/server/src/moves/MoveQueue.ts b/apps/server/src/moves/MoveQueue.ts index 0eb8aca32..07754ee73 100644 --- a/apps/server/src/moves/MoveQueue.ts +++ b/apps/server/src/moves/MoveQueue.ts @@ -65,6 +65,7 @@ import { isRestorePaid, moveWaitsOf, PARENT_DIDNT_MOVE_WORDS, + reportWaitThreads, restoreMessageText, sameMoveStatus, sharedCheckoutBusyThreads, @@ -542,8 +543,12 @@ export const makeMoveQueue = ( context.thread.pendingMove?.targetTakes, ); // Whatever those threads do next (a command run interrupted, a - // workflow or a voice chat ending) is a reason to look again. - entry.waitsOnThreads = new Set(sharedCheckoutBusyThreads(context.view, context.thread)); + // workflow or a voice chat ending, or a family report settling) is a + // reason to look again. + entry.waitsOnThreads = new Set([ + ...sharedCheckoutBusyThreads(context.view, context.thread), + ...reportWaitThreads(context.view, context.thread), + ]); // One of them changed while this look read it: look again. if ( [...entry.waitsOnThreads].some((other) => (lastSequenceOf.get(other) ?? 0) > readFrom) diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 64b254c09..ed2309d0e 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -566,6 +566,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti parentThreadId: event.payload.parentThreadId ?? null, parentTurnId: event.payload.parentTurnId ?? null, attachedToParent: event.payload.attachedToParent === true ? 1 : 0, + stopsWithParent: event.payload.stopsWithParent === true ? 1 : null, ...(event.payload.reportsTo !== undefined ? { childRequests: { @@ -904,7 +905,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti event.payload.outcome, ) : event.type === "thread.agent-requests-held" - ? agentRequestStateOn.held(state, event.payload.chainEpoch) + ? agentRequestStateOn.held(state, event.payload.chainEpoch, { + keepHold: event.payload.keepHold === true, + }) : agentRequestStateOn.reset(state); yield* projectionThreadRepository.upsert({ ...existingRow.value, agentRequests }); return; @@ -1038,6 +1041,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti } : {}), attachedToParent: event.payload.attached ? 1 : 0, + ...(event.payload.attached ? { stopsWithParent: null } : {}), parentAttachmentEpoch: event.payload.attachmentEpoch, // See the in-memory projector: taken back over its link. ...(event.payload.adoptedBy !== undefined @@ -1401,9 +1405,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti return; } const { followUp } = event.payload; + const madeOwn = followUp.composer !== undefined || followUp.sentFrom !== undefined; yield* projectionThreadRepository.upsert({ ...existingRow.value, queuedFollowUps: withQueuedFollowUp(existingRow.value.queuedFollowUps ?? [], followUp), + ...(madeOwn ? { stopsWithParent: null } : {}), updatedAt: event.occurredAt, }); return; @@ -1437,8 +1443,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti if (Option.isNone(existingRow)) { return; } + const madeOwn = + (event.type === "thread.message-sent" && + event.payload.role === "user" && + (event.payload.composer !== undefined || event.payload.sentFrom !== undefined)) || + ((event.type === "thread.follow-up-submitted" || + event.type === "thread.follow-up-accepted") && + (event.payload.composer !== undefined || event.payload.sentFrom !== undefined)); yield* projectionThreadRepository.upsert({ ...existingRow.value, + ...(madeOwn ? { stopsWithParent: null } : {}), updatedAt: event.occurredAt, // An outside answer marks the agent that asked (see the projector). ...(event.type === "thread.user-input-response-requested" && diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index d46893516..bae083780 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -50,6 +50,7 @@ import { type TurnId, type TurnStartedBy, } from "@threadlines/contracts"; +import { markCheckBacksDormant } from "@threadlines/shared/checkBacks"; import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed"; import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/projectLead"; import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings"; @@ -5208,11 +5209,9 @@ const make = Effect.gen(function* () { )); if (runtime === undefined || !holdsCheckBacks) { // Nothing is running that could come back: the list was stale. Jobs - // saved to disk outlive the session, so they stay. + // saved to disk outlive the session, so they stay listed as dormant. const thread = yield* resolveThread(threadId); - const kept = (thread?.checkBacks ?? []).filter( - (checkBack) => checkBack.participantId === participantId && checkBack.durable, - ); + const kept = markCheckBacksDormant(thread?.checkBacks ?? [], participantId); yield* orchestrationEngine .dispatch({ type: "thread.check-backs.set", @@ -6562,6 +6561,7 @@ const make = Effect.gen(function* () { commandId: serverCommandId("native-session-resend"), threadId, messageId: payload.value.resendMessageId, + ...(payload.value.chainEpoch !== undefined ? { chainEpoch: payload.value.chainEpoch } : {}), createdAt: yield* nowIso, }) .pipe( diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 36d26d332..61e71da49 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -8665,4 +8665,82 @@ describe("ProviderRuntimeIngestion", () => { expect(thread.session?.status).toBe("error"); expect(thread.session?.lastError).toBe("runtime still processed"); }); + + it("marks saved check-backs dormant on session exit and clears dormant when the runtime reports them again", async () => { + const harness = await createHarness(); + const threadId = asThreadId("thread-1"); + const now = "2026-01-01T00:00:00.000Z"; + + harness.emit({ + type: "session.check-backs.updated", + eventId: asEventId("evt-cb-live"), + provider: ProviderDriverKind.make("claudeAgent"), + threadId, + createdAt: now, + payload: { + checkBacks: [ + { + id: "ephemeral-1", + scheduledFor: "2026-01-01T00:10:00.000Z", + exact: true, + recurring: false, + description: "One-off", + durable: false, + }, + { + id: "saved-1", + scheduledFor: "2026-01-01T01:00:00.000Z", + exact: true, + recurring: true, + description: "Saved watcher", + durable: true, + }, + ], + }, + }); + await waitForThread(harness.readModel, (entry) => (entry.checkBacks?.length ?? 0) === 2); + + // Session exits: non-durable check-back drops, saved one becomes dormant. + harness.emit({ + type: "session.exited", + eventId: asEventId("evt-cb-exit"), + provider: ProviderDriverKind.make("claudeAgent"), + threadId, + createdAt: "2026-01-01T00:01:00.000Z", + payload: { exitKind: "graceful" }, + }); + const afterExit = await waitForThread( + harness.readModel, + (entry) => entry.checkBacks?.length === 1 && entry.checkBacks[0]?.dormant === true, + ); + expect(afterExit.checkBacks).toEqual([ + expect.objectContaining({ id: "saved-1", durable: true, dormant: true }), + ]); + + // Runtime restarts and reports the saved job afresh: dormant clears. + harness.emit({ + type: "session.check-backs.updated", + eventId: asEventId("evt-cb-revived"), + provider: ProviderDriverKind.make("claudeAgent"), + threadId, + createdAt: "2026-01-01T00:02:00.000Z", + payload: { + checkBacks: [ + { + id: "saved-1", + scheduledFor: "2026-01-01T01:00:00.000Z", + exact: true, + recurring: true, + description: "Saved watcher", + durable: true, + }, + ], + }, + }); + const revived = await waitForThread( + harness.readModel, + (entry) => entry.checkBacks?.length === 1 && entry.checkBacks[0]?.dormant !== true, + ); + expect(revived.checkBacks?.[0]?.dormant).toBeUndefined(); + }); }); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index b28f483f5..6e4c4407f 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -44,7 +44,7 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { countUnifiedDiffStats, type DiffLineStats } from "@threadlines/shared/diffStats"; import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; -import { sameCheckBacks } from "@threadlines/shared/checkBacks"; +import { markCheckBacksDormant, sameCheckBacks } from "@threadlines/shared/checkBacks"; import { areFilesystemPathsEqual } from "@threadlines/shared/path"; import { ASSISTANT_STREAM_FLUSH_INTERVAL_MS } from "@threadlines/shared/threadLimits"; import { @@ -2724,6 +2724,7 @@ const make = Effect.gen(function* () { threadId: input.thread.id, reason: "turn_failed", ...(startedBy !== undefined ? { resendMessageId: startedBy } : {}), + chainEpoch: input.thread.agentRequests.chainEpoch, ...(input.participantId !== null ? { participantId: input.participantId } : {}), createdAt: input.now, }), @@ -3001,10 +3002,12 @@ const make = Effect.gen(function* () { const next = event.payload.partial ? [ ...reported, - ...current.filter( - (listed) => - listed.durable && !reported.some((checkBack) => checkBack.id === listed.id), - ), + ...current + .filter( + (listed) => + listed.durable && !reported.some((checkBack) => checkBack.id === listed.id), + ) + .map(({ dormant: _dormant, ...listed }) => listed), ].toSorted((left, right) => left.scheduledFor.localeCompare(right.scheduledFor)) : reported; if (!sameCheckBacks(current, next)) { @@ -3396,6 +3399,26 @@ const make = Effect.gen(function* () { yield* clearSettledSubagentResultState(`${thread.id}:`); } else { yield* sealSubagentResultState(`${thread.id}:`); + // The runtime ended: any check-backs still listed for this agent + // can no longer fire until the agent runs again (saved jobs stay + // listed as dormant; session-only ones are gone). + const participantId = event.participantId ?? null; + const current = (thread.checkBacks ?? []).filter( + (checkBack) => checkBack.participantId === participantId, + ); + if (current.length > 0) { + const dormant = markCheckBacksDormant(thread.checkBacks ?? [], participantId); + if (!sameCheckBacks(current, dormant)) { + yield* orchestrationEngine.dispatch({ + type: "thread.check-backs.set", + commandId: providerCommandId(event, "check-backs-dormant"), + threadId: thread.id, + participantId, + checkBacks: dormant, + createdAt: now, + }); + } + } } } diff --git a/apps/server/src/orchestration/Layers/ThreadBootstrap.ts b/apps/server/src/orchestration/Layers/ThreadBootstrap.ts index c82894c2f..446cbe200 100644 --- a/apps/server/src/orchestration/Layers/ThreadBootstrap.ts +++ b/apps/server/src/orchestration/Layers/ThreadBootstrap.ts @@ -685,6 +685,7 @@ const make = Effect.gen(function* () { parentThreadId: input.lineage.parentThreadId, parentTurnId: input.lineage.parentTurnId, attachedToParent: launch.reportBack, + ...(!launch.reportBack ? { stopsWithParent: true as const } : {}), } : input.lineage.kind === "remote" ? { remoteOrigin: input.lineage.remoteOrigin } diff --git a/apps/server/src/orchestration/agentRequestDecisions.ts b/apps/server/src/orchestration/agentRequestDecisions.ts index 5f37746b7..4d48820ae 100644 --- a/apps/server/src/orchestration/agentRequestDecisions.ts +++ b/apps/server/src/orchestration/agentRequestDecisions.ts @@ -1019,6 +1019,12 @@ export function decideAgentChainStop( * writes (docs/design/agent-autonomy-no-limits.md, "Stop"). */ readonly holdsFamily?: boolean; + /** + * Stopped with its family or as cleanup: bump `chainEpoch` and clear + * queued agent work without putting a new hold on the thread (any hold it + * already had stays). + */ + readonly keepHold?: boolean; } = {}, ): ReadonlyArray<PlannedEvent> { const state = thread.agentRequests; @@ -1037,7 +1043,12 @@ export function decideAgentChainStop( { ...base(), type: "thread.agent-requests-held", - payload: { threadId: thread.id, chainEpoch: state.chainEpoch + 1, createdAt }, + payload: { + threadId: thread.id, + chainEpoch: state.chainEpoch + 1, + ...(options.keepHold === true ? { keepHold: true as const } : {}), + createdAt, + }, }, ...state.open.map((request) => settledEvent(base, thread, request, "stopped", createdAt)), // Every answer an agent asked for stops; the user's own go on. diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 796902b1b..84fe12a29 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -38,16 +38,19 @@ import { type RemoteChildThread, } from "@threadlines/contracts"; import { + attachedDescendantsOf, childAttachRefusal, childSendRefusal, childStartRefusal, effectiveRequestCeiling, isAttachedChild, isSettingUpChildStart, + isStillGoing, narrowerModeCeiling, ownChildRefusal, remoteChildOf, leadPassRefusal, + stopReachOf, withinModeCeiling, } from "@threadlines/shared/childThreads"; import { @@ -1750,6 +1753,41 @@ export function childHasLiveWork( ); } +/** + * The shared "still going" test (`isStillGoing`, docs/design/ + * agent-autonomy-no-limits.md, "Stop") over a loaded thread: what Stop + * targets, what "Stop N working threads" counts, and what holds a revert. + */ +export function threadIsStillGoing(thread: OrchestrationThread): boolean { + const session = thread.session; + const latestTurnId = thread.latestTurn?.turnId ?? null; + return isStillGoing({ + turnInFlight: + thread.latestTurn?.state === "running" || + session?.status === "running" || + session?.status === "starting", + queuedCount: (thread.queuedFollowUps ?? []).length, + waitsOnUser: + collectOpenPendingRequests(thread.activities, APPROVAL_ACTIVITY_KINDS).length > 0 || + countPendingUserInputs(thread.activities).pendingUserInputCount > 0 || + thread.proposedPlans.some( + (plan) => + latestTurnId !== null && + plan.turnId === latestTurnId && + plan.implementedAt === null && + plan.dismissedAt === null, + ) || + hasPendingSettingsChange(thread.settingsRequests ?? []) || + hasPendingSecretRequest(thread.secretRequests ?? []) || + awaitingInvite(thread.agentRequests) !== undefined, + backgroundWork: hasBackgroundWork(session, "any"), + openRequestCount: thread.childRequests.open.length, + waitsForReset: (session?.continueAtReset ?? null) !== null, + sideAnswerRunning: hasLiveSideTurn(thread), + checkBacks: thread.checkBacks, + }); +} + /** * The turn a parent's agent cut off with thread_stop is over as far as that * parent is concerned: it chose to end it, so nothing from it is owed back. @@ -1809,21 +1847,45 @@ export function decideChildrenStop( if (pendingIds.length > 0 && isAttachedChild(parent)) { return refuse("This thread was started by another thread, so it cannot stop threads itself."); } - const targets = - command.childThreadIds === undefined - ? attachedChildrenOf(readModel, parent.id).filter( - (child) => childHasLiveWork(child) || requestsFor(parent, child.id).length > 0, - ) - : command.childThreadIds - .filter((id) => !isRemote(id) && !pendingIds.includes(id)) - .map((id) => findThread(readModel, id)); + const hasOpenParentRequest = (child: OrchestrationThread) => { + if (child.parentThreadId === null) return false; + const owner = findThread(readModel, child.parentThreadId); + return owner !== null && requestsFor(owner, child.id).length > 0; + }; const children: OrchestrationThread[] = []; - for (const child of targets) { - const refusal = ownChildRefusal(parent, child); - if (refusal !== null || child === null) { - return refuse(refusal?.detail ?? "That thread is gone."); - } + const seenChildIds = new Set<ThreadId>(); + const addChild = (child: OrchestrationThread) => { + if (seenChildIds.has(child.id)) return; + seenChildIds.add(child.id); children.push(child); + }; + if (command.childThreadIds === undefined) { + // Stop's reach: every attached thread under parent, plus flagged loose + // threads (reportBack: false not yet written in by the user), that is + // still going or has an open request on its parent. + for (const { thread: member } of stopReachOf(readModel.threads, parent.id)) { + if (member.archivedAt !== null) continue; + if (threadIsStillGoing(member) || hasOpenParentRequest(member)) { + addChild(member); + } + } + } else { + for (const id of command.childThreadIds.filter( + (entry) => !isRemote(entry) && !pendingIds.includes(entry), + )) { + const child = findThread(readModel, id); + const refusal = ownChildRefusal(parent, child); + if (refusal !== null || child === null) { + return refuse(refusal?.detail ?? "That thread is gone."); + } + addChild(child); + for (const { thread: member } of stopReachOf(readModel.threads, child.id)) { + if (member.archivedAt !== null) continue; + if (threadIsStillGoing(member) || hasOpenParentRequest(member)) { + addChild(member); + } + } + } } if (remoteTargets.length > 0 && isAttachedChild(parent)) { return refuse("This thread was started by another thread, so it cannot stop threads itself."); @@ -1839,35 +1901,55 @@ export function decideChildrenStop( const remoteRequests = parent.childRequests.open.filter( (request) => request.remote !== undefined && stoppedIds.has(request.childThreadId), ); + // Settle open requests on every parent whose child is being stopped + // (walking from parent down covers both direct children and any nested ones). + const ownersWithStoppedChildren = [ + parent, + ...children.filter((child) => + child.childRequests.open.some((request) => stoppedIds.has(request.childThreadId)), + ), + ]; return { events: [ - ...settleOpenRequests( - readModel, - baseFor, - parent, - parent.childRequests.open.filter((request) => stoppedIds.has(request.childThreadId)), - "stopped", - command.createdAt, - (titles) => - `${quotedList(titles)} ${titles.length === 1 ? "was" : "were"} stopped, so no answer will come back.`, + ...ownersWithStoppedChildren.flatMap((owner) => + settleOpenRequests( + readModel, + baseFor, + owner, + owner.childRequests.open.filter((request) => stoppedIds.has(request.childThreadId)), + "stopped", + command.createdAt, + (titles) => + `${quotedList(titles)} ${titles.length === 1 ? "was" : "were"} stopped, so no answer will come back.`, + ), ), - // An answer a child gave just before it was stopped does not come back - // either: queued ones are taken back, and one already on its way to a - // turn is cut off by moving the child's delivery epoch. - ...children.flatMap((child): ReadonlyArray<PlannedEvent> => [ - ...unqueueReportsFrom(baseFor, parent, child.id, command.createdAt), - { - ...baseFor(child.id), - type: "thread.parent-attachment-set", - payload: { - threadId: child.id, - attached: true, - attachmentEpoch: child.parentAttachmentEpoch + 1, - at: command.createdAt, + // An answer an attached child gave just before it was stopped does not + // come back either: queued ones are taken back, and one already on its + // way to a turn is cut off by moving the child's attachment epoch. A + // loose thread (stopsWithParent) was never attached and reports to nobody. + ...children.flatMap((child): ReadonlyArray<PlannedEvent> => { + if (!child.attachedToParent) { + return []; + } + const owner = + child.parentThreadId === null ? null : findThread(readModel, child.parentThreadId); + return [ + ...(owner !== null + ? unqueueReportsFrom(baseFor, owner, child.id, command.createdAt) + : []), + { + ...baseFor(child.id), + type: "thread.parent-attachment-set", + payload: { + threadId: child.id, + attached: true, + attachmentEpoch: child.parentAttachmentEpoch + 1, + at: command.createdAt, + }, }, - }, - ...stoppedTurnHandedBack(baseFor, child, command.createdAt), - ]), + ...stoppedTurnHandedBack(baseFor, child, command.createdAt), + ]; + }), // A child on a linked computer: the same, kept on the parent, and its // computer is told to drop the requests and stop its session. ...remoteCancelEvents(baseFor, parent, remoteRequests, command.createdAt, true), @@ -2028,11 +2110,17 @@ export function childDeletionEvents( createdAt: string, withChildren: boolean, verb: "deleted" | "archived" = "deleted", + deletedChildIds?: ReadonlySet<ThreadId>, ): ReadonlyArray<PlannedEvent> { // Children deleted along with it need nothing; the rest (all of them, or - // with `withChildren` the archived ones) are separated. + // with `withChildren` the archived ones, or with `deletedChildIds` any not + // named in the list) are separated. const familyEvents = attachedChildrenOf(readModel, thread.id) - .filter((child) => !withChildren || child.archivedAt !== null) + .filter((child) => + deletedChildIds !== undefined + ? !deletedChildIds.has(child.id) + : !withChildren || child.archivedAt !== null, + ) .map((child): PlannedEvent => ({ ...baseFor(child.id), type: "thread.parent-attachment-set", @@ -2124,6 +2212,7 @@ export function agentWrapRefusal( } if ( childHasLiveWork(child) || + (child.childRequests.owedReports ?? []).length > 0 || hasPendingSettingsChange(child.settingsRequests ?? []) || hasPendingSecretRequest(child.secretRequests ?? []) || awaitingInvite(child.agentRequests) !== undefined || @@ -2190,9 +2279,15 @@ export function childRevertRefusal( readModel: OrchestrationReadModel, thread: OrchestrationThread, ): string | null { + // Any attached thread under this one that is still going (by Stop's test, + // excluding loose threads which report to nobody) can still wake it about + // work a revert would take back (docs/design/agent-autonomy-no-limits.md). if ( thread.childRequests.open.length > 0 || - (thread.queuedFollowUps ?? []).some((queued) => queued.fromThread?.kind === "report") + (thread.queuedFollowUps ?? []).some((queued) => queued.fromThread?.kind === "report") || + attachedDescendantsOf(readModel.threads, thread.id).some( + ({ thread: child }) => child.archivedAt === null && threadIsStillGoing(child), + ) ) { return "Finish or stop its threads first: their answers are about work a revert would take back."; } diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index a1c9ef8b7..9cf2d6581 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -17,6 +17,7 @@ import { type OrchestrationReadModel, type OrchestrationSession, type OrchestrationThread, + OutsideAgentConnectionId, ProjectId, ProviderInstanceId, ThreadId, @@ -26,7 +27,11 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import { describe, expect, it } from "vite-plus/test"; -import { childReportMessageId, isCancelledReport } from "./childThreadDecisions.ts"; +import { + childReportMessageId, + childRevertRefusal, + isCancelledReport, +} from "./childThreadDecisions.ts"; import { reportRecipient } from "./childReports.ts"; import { decideOrchestrationCommand } from "./decider.ts"; import { projectEvent } from "./projector.ts"; @@ -3042,4 +3047,389 @@ describe("child thread access ceilings (stage 1 step 3)", () => { }); expect(threadIn(started2.model, CHILD).childRequests.passCeiling).toBeUndefined(); }); + + it("stops an idle child with a saved check-back, and revert unlocks once it is dormant (sequence 1)", async () => { + const savedJob: OrchestrationCheckBack = { + id: "saved-job-1", + participantId: null, + scheduledFor: "2026-10-05T10:00:00.000Z", + exact: true, + recurring: true, + description: "Check deploy status", + durable: true, + }; + const start = readModel([ + thread(PARENT, { + session: session(PARENT, { status: "ready", activeTurnId: null }), + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + session: session(CHILD, { status: "ready", activeTurnId: null }), + checkBacks: [savedJob], + }), + ]); + + expect(childRevertRefusal(start, threadIn(start, PARENT))).toContain( + "Finish or stop its threads first", + ); + + const stopped = await run(start, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-seq-1"), + threadId: PARENT, + createdAt: at(10), + }); + expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); + expect(threadIn(stopped.model, CHILD).agentRequests.hold).toBe(false); + expect( + stopped.events.some( + (event) => + event.type === "thread.session-stop-requested" && event.payload.threadId === CHILD, + ), + ).toBe(true); + expect( + stopped.events.some( + (event) => + event.type === "thread.check-back-cancel-requested" && event.payload.threadId === CHILD, + ), + ).toBe(true); + + // Once the child's runtime exits and marks the saved job dormant, revert is allowed. + const dormant = await run(stopped.model, { + type: "thread.check-backs.set", + commandId: CommandId.make("mark-dormant-seq-1"), + threadId: CHILD, + participantId: null, + checkBacks: [{ ...savedJob, dormant: true }], + createdAt: at(15), + }); + expect(childRevertRefusal(dormant.model, threadIn(dormant.model, PARENT))).toBeNull(); + }); + + it("stops flagged loose threads with their starter until a person writes in one (sequence 3)", async () => { + const looseIds = [1, 2, 3, 4, 5].map((index) => ThreadId.make(`loose-${index}`)); + let model = readModel([ + thread(PARENT, { session: session(PARENT, { status: "ready", activeTurnId: null }) }), + ]); + for (const [index, looseId] of looseIds.entries()) { + const created = await run(model, { + type: "thread.create", + commandId: CommandId.make(`create-loose-${index}`), + threadId: looseId, + projectId, + title: `Loose ${index + 1}`, + modelSelection: modelSelectionOf(threadIn(model, PARENT)), + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + parentThreadId: PARENT, + parentTurnId: CALLER_TURN, + attachedToParent: false, + stopsWithParent: true, + createdAt: at(index + 1), + }); + model = { + ...created.model, + threads: created.model.threads.map((entry) => + entry.id === looseId + ? { + ...entry, + session: session(looseId, { + status: "running", + activeTurnId: TurnId.make(`loose-turn-${index}`), + }), + } + : entry, + ), + }; + expect(threadIn(model, looseId).stopsWithParent).toBe(true); + } + + // Stop on the parent reaches all 5 flagged loose threads. + const firstStop = await run(model, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-all-loose"), + threadId: PARENT, + createdAt: at(20), + }); + const stoppedFirst = new Set( + firstStop.events + .filter((event) => event.type === "thread.session-stop-requested") + .map((event) => event.payload.threadId), + ); + for (const looseId of looseIds) { + expect(stoppedFirst.has(looseId)).toBe(true); + } + + // A person writes in loose-1: its flag clears for good, so Stop leaves it alone. + const claimed = await run(model, { + type: "thread.turn.start", + commandId: CommandId.make("person-claims-loose-1"), + threadId: looseIds[0]!, + message: { + messageId: MessageId.make("msg-claim-loose-1"), + role: "user", + text: "I'll take this thread from here.", + attachments: [], + }, + composer: "typed", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "auto-accept-edits", + createdAt: at(30), + }); + expect(threadIn(claimed.model, looseIds[0]!).stopsWithParent).toBeUndefined(); + const secondStop = await run(claimed.model, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-remaining-loose"), + threadId: PARENT, + createdAt: at(35), + }); + const stoppedSecond = new Set( + secondStop.events + .filter((event) => event.type === "thread.session-stop-requested") + .map((event) => event.payload.threadId), + ); + expect(stoppedSecond.has(looseIds[0]!)).toBe(false); + for (const looseId of looseIds.slice(1)) { + expect(stoppedSecond.has(looseId)).toBe(true); + } + }); + + it("stops a 3-level subtree without putting new holds on children, keeps existing holds, and skips holds on cleanup", async () => { + const GRANDCHILD = ThreadId.make("grandchild"); + const HELD_SIBLING = ThreadId.make("held-sibling"); + const start = readModel([ + thread(PARENT, { + session: session(PARENT, { status: "running", activeTurnId: CALLER_TURN }), + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + session: session(CHILD, { status: "running", activeTurnId: TurnId.make("child-turn") }), + // Even with an agent message queued, a family stop does not add a hold. + queuedFollowUps: [ + { + messageId: MessageId.make("queued-agent-msg"), + text: "Queued from parent", + attachments: [], + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + fromThread: { + threadId: PARENT, + requestId: ChildRequestId.make("req-queued"), + kind: "request", + }, + createdAt: at(2), + }, + ], + }), + thread(GRANDCHILD, { + parentThreadId: CHILD, + attachedToParent: true, + session: session(GRANDCHILD, { + status: "running", + activeTurnId: TurnId.make("grandchild-turn"), + }), + }), + thread(HELD_SIBLING, { + parentThreadId: PARENT, + attachedToParent: true, + agentRequests: { ...EMPTY_AGENT_REQUEST_STATE, hold: true, chainEpoch: 2 }, + session: session(HELD_SIBLING, { + status: "running", + activeTurnId: TurnId.make("held-turn"), + }), + }), + ]); + + const stopped = await run(start, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-3-levels"), + threadId: PARENT, + createdAt: at(10), + }); + const stoppedIds = new Set( + stopped.events + .filter((event) => event.type === "thread.session-stop-requested") + .map((event) => event.payload.threadId), + ); + expect(stoppedIds.has(CHILD)).toBe(true); + expect(stoppedIds.has(GRANDCHILD)).toBe(true); + expect(stoppedIds.has(HELD_SIBLING)).toBe(true); + expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); + expect(threadIn(stopped.model, CHILD).agentRequests.hold).toBe(false); + expect(threadIn(stopped.model, GRANDCHILD).agentRequests.hold).toBe(false); + expect(threadIn(stopped.model, HELD_SIBLING).agentRequests.hold).toBe(true); + + // A cleanup stop (archive/sweeper) never adds a hold either. + const cleanup = await run(start, { + type: "thread.session.stop", + commandId: CommandId.make("cleanup-stop"), + threadId: CHILD, + cause: "cleanup", + createdAt: at(12), + }); + expect(threadIn(cleanup.model, CHILD).agentRequests.hold).toBe(false); + }); + + it("refuses sending work to a child the user stopped, and refuses a fallback resend after Stop", async () => { + const start = readModel([ + thread(PARENT, { + session: session(PARENT, { status: "running", activeTurnId: CALLER_TURN }), + nativeSession: "carried", + messages: [ + { + id: MessageId.make("m-fallback"), + role: "user", + text: "Try again", + turnId: null, + streaming: false, + createdAt: at(1), + updatedAt: at(1), + }, + ], + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + agentRequests: { ...EMPTY_AGENT_REQUEST_STATE, hold: true, chainEpoch: 1 }, + session: session(CHILD, { status: "ready", activeTurnId: null }), + }), + ]); + + // Parent can't send to a held child. + const sendExit = await Effect.runPromiseExit( + decideOrchestrationCommand({ + readModel: start, + command: { + type: "thread.child.send", + commandId: CommandId.make("send-to-held-child"), + threadId: PARENT, + requestId: ChildRequestId.make("req-held"), + from: PRIMARY, + callerTurnId: CALLER_TURN, + childThreadId: CHILD, + childMessageId: MessageId.make("m-held"), + text: "Do more work", + createdAt: at(5), + }, + }), + ); + expect(Exit.isFailure(sendExit)).toBe(true); + + // Fallback records chainEpoch 0; Stop bumps chainEpoch and sets hold; resend with 0 is refused. + const fellBack = await run(start, { + type: "thread.native-session.fall-back", + commandId: CommandId.make("fallback-with-epoch"), + threadId: PARENT, + reason: "turn_failed", + resendMessageId: MessageId.make("m-fallback"), + chainEpoch: 0, + createdAt: at(6), + }); + const fallbackActivity = threadIn(fellBack.model, PARENT).activities.at(-1); + expect(fallbackActivity?.payload).toMatchObject({ + reason: "turn_failed", + resendMessageId: "m-fallback", + chainEpoch: 0, + }); + + const stopped = await run(fellBack.model, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-before-resend"), + threadId: PARENT, + createdAt: at(7), + }); + expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); + + expect( + await refused(stopped.model, { + type: "thread.turn.resend", + commandId: CommandId.make("stale-fallback-resend"), + threadId: PARENT, + messageId: MessageId.make("m-fallback"), + chainEpoch: 0, + createdAt: at(8), + }), + ).toBe(true); + expect(threadIn(stopped.model, PARENT).agentRequests.hold).toBe(true); + }); + + it("deletes only the attached unarchived children named in alsoDelete and separates the rest", async () => { + const LISTED = ThreadId.make("child-listed"); + const RACED = ThreadId.make("child-raced"); + const ARCHIVED = ThreadId.make("child-archived"); + const start = readModel([ + thread(PARENT), + thread(LISTED, { parentThreadId: PARENT, attachedToParent: true }), + thread(RACED, { parentThreadId: PARENT, attachedToParent: true }), + thread(ARCHIVED, { + parentThreadId: PARENT, + attachedToParent: true, + archivedAt: at(1), + }), + ]); + + const deleted = await run(start, { + type: "thread.delete", + commandId: CommandId.make("delete-with-also-delete"), + threadId: PARENT, + alsoDelete: [LISTED, ARCHIVED], + }); + expect(threadIn(deleted.model, PARENT).deletedAt).not.toBeNull(); + expect(threadIn(deleted.model, LISTED).deletedAt).not.toBeNull(); + expect(threadIn(deleted.model, RACED).deletedAt).toBeNull(); + expect(threadIn(deleted.model, RACED).attachedToParent).toBe(false); + expect(threadIn(deleted.model, ARCHIVED).deletedAt).toBeNull(); + expect(threadIn(deleted.model, ARCHIVED).attachedToParent).toBe(false); + }); + + it("leaves a descendant raised above an outside agent's access limit running on Stop", async () => { + const RAISED = ThreadId.make("child-raised"); + const WITHIN = ThreadId.make("child-within"); + const start = readModel([ + thread(PARENT, { + runtimeMode: "auto-accept-edits", + session: session(PARENT, { status: "running", activeTurnId: CALLER_TURN }), + }), + thread(WITHIN, { + parentThreadId: PARENT, + attachedToParent: true, + runtimeMode: "auto-accept-edits", + session: session(WITHIN, { status: "running", activeTurnId: TurnId.make("within-turn") }), + }), + thread(RAISED, { + parentThreadId: PARENT, + attachedToParent: true, + runtimeMode: "full-access", + session: session(RAISED, { status: "running", activeTurnId: TurnId.make("raised-turn") }), + }), + ]); + + const stopped = await run(start, { + type: "thread.turn.interrupt", + commandId: CommandId.make("outside-stop"), + threadId: PARENT, + fromOutside: { + connectionId: OutsideAgentConnectionId.make("conn-1"), + name: "Outside Helper", + access: "work", + maxRuntimeMode: "auto-accept-edits", + }, + createdAt: at(10), + }); + const stoppedIds = new Set( + stopped.events + .filter((event) => event.type === "thread.session-stop-requested") + .map((event) => event.payload.threadId), + ); + expect(stoppedIds.has(WITHIN)).toBe(true); + expect(stoppedIds.has(RAISED)).toBe(false); + }); }); + +function modelSelectionOf(entry: OrchestrationThread) { + return entry.modelSelection; +} diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 36e13b1e3..46daa2d17 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -2961,7 +2961,9 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h)) }); it("the parent keeps a child that moved alone as its thread there, reaches it, and hears its answer", async () => { - let model = await movedAlone(await asked(await parentWorking(await withChild(await seeded())))); + // A child waits for an open parent request before freezing, so project the + // request after moving alone to pin move-complete's defensive cleanup. + let model = await asked(await movedAlone(await parentWorking(await withChild(await seeded())))); // Its frozen copy here takes no message: it would never reach it. expect((await apply(model, sendTo(CHILD, ChildRequestId.make("r-frozen")))).refusal).toContain( "moving to Mac mini", @@ -3582,7 +3584,7 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h)) }; it("lands under its parent, and the move it left on completes then", async () => { - const moving = await movedAlone(await asked(await withChild(await seeded()))); + const moving = await asked(await movedAlone(await withChild(await seeded()))); let { model, refusal } = await apply(moving, backFromThere(completesChild)); expect(refusal).toBeNull(); expect(threadOf(model, ARRIVED)).toMatchObject({ @@ -3981,4 +3983,86 @@ describe("a parent arriving beside threads it started here (Part 3f, (g))", () = [THIRD.environmentId, "thread-adopted"], ]); }); + + it("holds parent and child moves while a report is owed or a parent request is open (sequence 4)", async () => { + const CHILD = ThreadId.make("thread-child-seq4"); + const TAKES: ThreadMoveTakes = { threadState: true, families: true, linkLineage: true }; + const base = ( + await apply(await seeded(), { + type: "thread.create", + commandId: nextCommandId(), + threadId: CHILD, + projectId: PROJECT, + title: "Worker", + modelSelection, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: `/worktrees/${CHILD}`, + parentThreadId: THREAD, + attachedToParent: true, + createdAt: now, + } as OrchestrationCommand) + ).model; + + // An owed report on the child holds both the child's move and the parent's move. + const owing: OrchestrationReadModel = { + ...base, + threads: base.threads.map((entry) => + entry.id === CHILD + ? { + ...entry, + childRequests: { + ...entry.childRequests, + owedReports: [ + { + turnId: TurnId.make("child-turn-1"), + deliveryEpoch: 0, + attachmentEpoch: 0, + createdAt: now, + }, + ], + }, + } + : entry, + ), + }; + expect( + threadMoveRefusals(owing, threadOf(owing, CHILD), TAKES).some( + (entry) => entry.kind === "wait" && entry.code === "background", + ), + ).toBe(true); + expect( + threadMoveRefusals(owing, threadOf(owing, THREAD), TAKES).some( + (entry) => entry.kind === "wait" && entry.code === "background", + ), + ).toBe(true); + + // An open request on the parent for the child also holds the child's move. + const openOnParent = await project(base, "thread.child-request-submitted", { + threadId: THREAD, + request: { + requestId: ChildRequestId.make("req-seq4"), + batchId: ChildRequestBatchId.make("req-seq4"), + kind: "send", + from: { participantId: null }, + callerTurnId: TurnId.make("parent-turn-1"), + deliveryEpoch: 0, + status: "running", + childThreadId: CHILD, + childMessageId: MessageId.make("m-seq4"), + createdAt: now, + }, + createdAt: now, + }); + expect( + threadMoveRefusals(openOnParent, threadOf(openOnParent, CHILD), TAKES).some( + (entry) => entry.kind === "wait" && entry.code === "background", + ), + ).toBe(true); + + // Once both clear, neither thread waits on family reports. + expect(threadMoveRefusals(base, threadOf(base, CHILD), TAKES)).toEqual([]); + expect(threadMoveRefusals(base, threadOf(base, THREAD), TAKES)).toEqual([]); + }); }); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index b1872044b..ce0861c8b 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -52,12 +52,14 @@ import { secretRequestIdOfAnswerMessage } from "@threadlines/shared/secretReques import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; import { + attachedDescendantsOf, effectiveRequestCeiling, isAttachedChild, isOwedReport, narrowerModeCeiling, passCeilingRefusal, requestCeilingRefusal, + stopReachOf, } from "@threadlines/shared/childThreads"; import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; @@ -123,6 +125,8 @@ import { isOpenParentRequest, isStaleReport, settleParentRequestsForUnqueued, + stoppedTurnHandedBack, + threadIsStillGoing, withinModeCeiling, } from "./childThreadDecisions.ts"; import { @@ -1253,7 +1257,11 @@ function endCheckBacksOnStop( base: () => Omit<OrchestrationEvent, "sequence" | "type" | "payload">, createdAt: string, ): ReadonlyArray<PlannedOrchestrationEvent> { - const agents = new Set((thread.checkBacks ?? []).map((checkBack) => checkBack.participantId)); + const agents = new Set( + (thread.checkBacks ?? []) + .filter((checkBack) => checkBack.dormant !== true) + .map((checkBack) => checkBack.participantId), + ); return [...agents].map((participantId) => ({ ...base(), type: "thread.check-back-cancel-requested" as const, @@ -1735,6 +1743,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ? { parentTurnId: command.parentTurnId } : {}), attachedToParent: command.attachedToParent === true, + ...(command.stopsWithParent === true && command.attachedToParent !== true + ? { stopsWithParent: true as const } + : {}), ...(reportsTo !== undefined ? { reportsTo } : {}), } : {}), @@ -1974,8 +1985,23 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }, }; // Child threads: its family is separated (or deleted with it), and a - // child's parent stops waiting on it. + // child's parent stops waiting on it. `alsoDelete` names the exact + // threads the dialog confirmed (docs/design/agent-autonomy-no-limits.md): + // only attached, unarchived descendants in that list are deleted; any + // other attached thread under it is separated and kept. const withChildren = command.withChildren === true; + const alsoDeleteTargets = + command.alsoDelete === undefined + ? undefined + : attachedDescendantsOf(readModel.threads, thread.id) + .map((entry) => entry.thread) + .filter( + (child) => child.archivedAt === null && command.alsoDelete!.includes(child.id), + ); + const deletedChildIdSet = + alsoDeleteTargets === undefined + ? undefined + : new Set(alsoDeleteTargets.map((child) => child.id)); const familyEvents = [ ...childDeletionEvents( readModel, @@ -1983,6 +2009,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" childEventBase(command, occurredAt), occurredAt, withChildren, + "deleted", + deletedChildIdSet, ), // Threads it asked for on linked computers: their requests are dropped // there; the threads keep running, like separated children here. @@ -1994,20 +2022,28 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" false, ), ]; - // Only the children the user was shown: the ones not archived. An - // archived child is separated instead and lives on in the archive. - const childDeletes = withChildren - ? yield* decideCommandSequence({ - readModel, - commands: attachedChildrenOf(readModel, thread.id) - .filter((child) => child.archivedAt === null) - .map((child): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({ - type: "thread.delete", - commandId: command.commandId, - threadId: child.id, - })), - }) - : []; + // Only the children the user was shown: the ones listed in `alsoDelete`, + // or with `withChildren` alone the direct unarchived children. Archived + // or unlisted children are separated instead and kept. + const childrenToDelete = + alsoDeleteTargets !== undefined + ? [...alsoDeleteTargets].toReversed() + : withChildren + ? attachedChildrenOf(readModel, thread.id).filter((child) => child.archivedAt === null) + : []; + const childDeletes = + childrenToDelete.length > 0 + ? yield* decideCommandSequence({ + readModel, + commands: childrenToDelete.map( + (child): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({ + type: "thread.delete", + commandId: command.commandId, + threadId: child.id, + }), + ), + }) + : []; const leadEvents = leadClearEvents(readModel, [thread.id], command.commandId, occurredAt); return familyEvents.length === 0 && childDeletes.length === 0 && leadEvents.length === 0 ? deletedEvent @@ -5107,14 +5143,42 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" commandId: command.commandId, }); // In a room, Stop also ends the agents' chain of requests; with child - // threads, it ends what this thread was owed by its children, and a - // parent's requests still queued here are taken back. Every agent's - // check-backs end with it. + // threads, it ends what this thread was owed by its children, and stops + // every thread in its Stop reach that is still going (attached threads + // and flagged loose threads, docs/design/agent-autonomy-no-limits.md). + // Every agent's check-backs end with it. + const baseFor = childEventBase(command, command.createdAt); + const hasOpenParentRequest = (child: OrchestrationThread) => { + if (child.parentThreadId === null) return false; + const owner = readModel.threads.find( + (entry) => entry.id === child.parentThreadId && entry.deletedAt === null, + ); + return ( + owner !== undefined && + owner.childRequests.open.some((request) => request.childThreadId === child.id) + ); + }; + // Walk Stop's reach before settling anything so settling a parent first + // cannot hide threads underneath it. + const descendantsToStop = stopReachOf(readModel.threads, thread.id) + .map((entry) => entry.thread) + .filter((child) => { + if (child.archivedAt !== null) return false; + if (!threadIsStillGoing(child) && !hasOpenParentRequest(child)) return false; + if ( + command.fromOutside !== undefined && + outsideStopRefusal(child, command.fromOutside) !== null + ) { + return false; + } + return true; + }); const chainStop = [ ...decideAgentChainStop(thread, base, command.createdAt, { holdsFamily: thread.childRequests.open.length > 0 || - attachedChildrenOf(readModel, thread.id).length > 0, + attachedChildrenOf(readModel, thread.id).length > 0 || + isAttachedChild(thread), }), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), @@ -5140,9 +5204,58 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command.commandId, command.createdAt, ); - return chainStop.length > 0 || waitEnd.length > 0 - ? [interruptEvent, ...chainStop, ...waitEnd] - : interruptEvent; + const ownEvents: ReadonlyArray<PlannedOrchestrationEvent> = [ + interruptEvent, + ...chainStop, + ...waitEnd, + ]; + if (descendantsToStop.length === 0) { + return ownEvents.length > 1 ? ownEvents : interruptEvent; + } + // Attached threads stopped with their parent owe nothing more and get + // their running turn stamped handed back, like `thread.children.stop`. + // Loose threads (stopsWithParent) were never attached and only stop. + const descendantPrepEvents: PlannedOrchestrationEvent[] = descendantsToStop.flatMap( + (child): ReadonlyArray<PlannedOrchestrationEvent> => + !child.attachedToParent + ? [] + : [ + { + ...baseFor(child.id), + type: "thread.parent-attachment-set", + payload: { + threadId: child.id, + attached: true, + attachmentEpoch: child.parentAttachmentEpoch + 1, + at: command.createdAt, + }, + }, + ...stoppedTurnHandedBack(baseFor, child, command.createdAt), + ], + ); + let nextReadModel = readModel; + let nextSequence = readModel.snapshotSequence; + for (const event of [...ownEvents, ...descendantPrepEvents]) { + nextSequence += 1; + nextReadModel = yield* projectEvent(nextReadModel, { + ...event, + sequence: nextSequence, + } as OrchestrationEvent).pipe(Effect.orDie); + } + const descendantStops = yield* decideCommandSequence({ + readModel: nextReadModel, + commands: descendantsToStop.map( + (child): Extract<OrchestrationCommand, { type: "thread.session.stop" }> => ({ + type: "thread.session.stop", + commandId: command.commandId, + threadId: child.id, + // Stopped with its family: no new Stop hold (any existing hold stays). + cause: "family", + createdAt: command.createdAt, + }), + ), + }); + return [...ownEvents, ...descendantPrepEvents, ...descendantStops]; } case "thread.realtime.start": { @@ -5471,10 +5584,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" holdsFamily: command.cause === undefined && (thread.childRequests.open.length > 0 || - attachedChildrenOf(readModel, thread.id).length > 0), + attachedChildrenOf(readModel, thread.id).length > 0 || + isAttachedChild(thread)), + keepHold: command.cause !== undefined, }), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), + ...(command.cause !== "cleanup" + ? endCheckBacksOnStop(thread, base, command.createdAt) + : []), // Stop is the user's say: a goal paused for a wait stays as Stop // leaves it, never resumed when the waits Stop ends are over. ...goalTakenByUser(thread, command), diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 18f044e1f..595b1471d 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -479,6 +479,7 @@ export function projectEvent( parentThreadId: payload.parentThreadId ?? null, parentTurnId: payload.parentTurnId ?? null, attachedToParent: payload.attachedToParent ?? false, + ...(payload.stopsWithParent === true ? { stopsWithParent: true as const } : {}), ...(payload.reportsTo !== undefined ? { childRequests: { ...EMPTY_CHILD_REQUEST_STATE, reportsTo: payload.reportsTo } } : {}), @@ -945,7 +946,9 @@ export function projectEvent( ).pipe( Effect.map((payload) => updateAgentRequests(nextBase, payload.threadId, (state) => - agentRequestStateOn.held(state, payload.chainEpoch), + agentRequestStateOn.held(state, payload.chainEpoch, { + keepHold: payload.keepHold === true, + }), ), ), ); @@ -1245,6 +1248,7 @@ export function projectEvent( ...withOwed, threads: updateThread(withOwed.threads, payload.threadId, { attachedToParent: payload.attached, + ...(payload.attached ? { stopsWithParent: undefined } : {}), parentAttachmentEpoch: payload.attachmentEpoch, // Taken back by the thread that started it over a link, which // moved here (ThreadAdoptedFromLink): this computer's child now. @@ -1582,10 +1586,14 @@ export function projectEvent( : [...thread.messages, message]; const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES); + const madeOwn = + payload.role === "user" && + (payload.composer !== undefined || payload.sentFrom !== undefined); return { ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { messages: cappedMessages, + ...(madeOwn ? { stopsWithParent: undefined } : {}), updatedAt: event.occurredAt, }), }; @@ -1601,6 +1609,9 @@ export function projectEvent( Effect.map((payload) => ({ ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { + ...(payload.composer !== undefined || payload.sentFrom !== undefined + ? { stopsWithParent: undefined } + : {}), updatedAt: payload.createdAt, }), })), @@ -1663,6 +1674,9 @@ export function projectEvent( ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { messages: messages.slice(-MAX_THREAD_MESSAGES), + ...(payload.composer !== undefined || payload.sentFrom !== undefined + ? { stopsWithParent: undefined } + : {}), updatedAt: payload.createdAt, }), }; @@ -1679,6 +1693,9 @@ export function projectEvent( ...nextBase, threads: updateThread(nextBase.threads, payload.threadId, { queuedFollowUps: withQueuedFollowUp(thread.queuedFollowUps ?? [], payload.followUp), + ...(payload.followUp.composer !== undefined || payload.followUp.sentFrom !== undefined + ? { stopsWithParent: undefined } + : {}), updatedAt: payload.followUp.createdAt, }), }; diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 670d73050..5e7cdb57e 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -41,7 +41,11 @@ import { type ThreadNativeSessionFellBackPayload, type ThreadPendingMove, } from "@threadlines/contracts"; -import { withinModeCeiling } from "@threadlines/shared/childThreads"; +import { + attachedDescendantsOf, + isAttachedChild, + withinModeCeiling, +} from "@threadlines/shared/childThreads"; import { hasLiveCommandRun } from "@threadlines/shared/commandRuns"; import { threadPullRequestAutomationArmed } from "@threadlines/shared/linkedPullRequests"; import { @@ -419,7 +423,7 @@ export function threadMoveRefusals( // What goes away on its own. found.push( - ...workWaits(thread, { + ...workWaits(readModel, thread, { rooms: takesRooms, families: takesFamilies, sendable: thread.queuedFollowUps ?? [], @@ -448,11 +452,41 @@ export function sharedCheckoutBusyThreads( candidate.deletedAt === null && (candidate.move ?? null) === null && checkoutOf(readModel, candidate) === checkout && - busyInFolder(candidate), + busyInFolder(readModel, candidate), ) .map((candidate) => candidate.id); } +/** + * Other threads whose events can clear a family-report wait on `thread`: + * its attached parent while the parent holds an open request for it, and any + * attached child that still owes a report. The move queue watches these so a + * waiting move wakes as soon as the report settles. + */ +export function reportWaitThreads( + readModel: ThreadMoveView, + thread: OrchestrationThread, +): ReadonlyArray<ThreadId> { + const ids: ThreadId[] = []; + if (isAttachedChild(thread) && thread.parentThreadId !== null) { + const parent = readModel.threads.find( + (entry) => entry.id === thread.parentThreadId && entry.deletedAt === null, + ); + if ( + parent !== undefined && + parent.childRequests.open.some((request) => request.childThreadId === thread.id) + ) { + ids.push(parent.id); + } + } + for (const { thread: child } of attachedDescendantsOf(readModel.threads, thread.id)) { + if ((child.childRequests.owedReports ?? []).length > 0) { + ids.push(child.id); + } + } + return ids; +} + /** * What `thread` is doing now that goes away on its own (docs/design/fleet.md, * Parts 3b and 3f), as its move's waits: a turn and what it asks of the user, @@ -463,6 +497,7 @@ export function sharedCheckoutBusyThreads( * a move in the same folder waits on (`busyInFolder`), so the two can't drift. */ function workWaits( + readModel: ThreadMoveView, thread: OrchestrationThread, options: { readonly rooms: boolean; @@ -500,16 +535,34 @@ function workWaits( found.push(wait("side_turn", ROOM_CHAIN_WORDS)); } } - // Waiting on the threads it started (Part 3f, (g)): "Move when it's done" - // waits for their answers; a start waiting for the user's OK, for them. + // Waiting on the threads it started, or owing a report in either direction + // (docs/design/agent-autonomy-no-limits.md, "Access", sequence 4): a parent + // waits while any attached child still owes it a report, and a child waits + // while it has an owed report or its parent has an open request for it. if (options.families) { const open = thread.childRequests.open; if (open.some((request) => request.status === "awaiting_user")) { found.push(wait("approval")); } + const parent = + isAttachedChild(thread) && thread.parentThreadId !== null + ? readModel.threads.find( + (entry) => entry.id === thread.parentThreadId && entry.deletedAt === null, + ) + : undefined; + const parentAwaitsChild = + parent !== undefined && + parent.childRequests.open.some((request) => request.childThreadId === thread.id); + const childOwesReport = (thread.childRequests.owedReports ?? []).length > 0; + const attachedChildOwesReport = attachedDescendantsOf(readModel.threads, thread.id).some( + ({ thread: child }) => (child.childRequests.owedReports ?? []).length > 0, + ); if ( open.some((request) => request.status !== "awaiting_user") || - options.sendable.some((entry) => isFamilyQueued(thread, entry)) + options.sendable.some((entry) => isFamilyQueued(thread, entry)) || + parentAwaitsChild || + childOwesReport || + attachedChildOwesReport ) { found.push(wait("background", FAMILY_WAIT_WORDS)); } @@ -536,7 +589,7 @@ function workWaits( * (Part 3f, (g)), or a parent waiting for its child's own move while the * child waits for the parent's held message (Part 3f, (h)). */ -function busyInFolder(thread: OrchestrationThread): boolean { +function busyInFolder(readModel: ThreadMoveView, thread: OrchestrationThread): boolean { const pending = thread.pendingMove ?? null; const queued = thread.queuedFollowUps ?? []; const sendable = @@ -548,7 +601,7 @@ function busyInFolder(thread: OrchestrationThread): boolean { return ( sendable.length > 0 || (pending === null && waitingPlanOf(thread) !== null) || - workWaits(thread, { rooms: true, families: true, sendable }).length > 0 + workWaits(readModel, thread, { rooms: true, families: true, sendable }).length > 0 ); } @@ -2641,7 +2694,12 @@ export function decideNativeSessionFallBack( } const payload: ThreadNativeSessionFellBackPayload = { reason: command.reason, - ...(command.resendMessageId !== undefined ? { resendMessageId: command.resendMessageId } : {}), + ...(command.resendMessageId !== undefined + ? { + resendMessageId: command.resendMessageId, + chainEpoch: command.chainEpoch ?? thread.agentRequests.chainEpoch, + } + : {}), ...(participantId !== undefined ? { participantId } : {}), }; // The thread's own agent's, or (a room) one agent's own record. diff --git a/apps/server/src/outsideAgents/connectToolHandlers.test.ts b/apps/server/src/outsideAgents/connectToolHandlers.test.ts index 68c2c4beb..1e1dfbe6b 100644 --- a/apps/server/src/outsideAgents/connectToolHandlers.test.ts +++ b/apps/server/src/outsideAgents/connectToolHandlers.test.ts @@ -969,6 +969,25 @@ describe("connect tools: review fixes", () => { expect((yield* racing.handlers.thread_stop(CALLER, { threadId: "racing" })).outcome).toBe( "not_allowed", ); + + // Stopping a parent names any child left running above this connection's access limit. + const parent = ownThread("parent-stop", { + runtimeMode: "auto-accept-edits", + session: { ...running!, threadId: ThreadId.make("parent-stop") }, + }); + const raisedChild = ownThread("raised-child", { + title: "Deploy prod", + parentThreadId: ThreadId.make("parent-stop"), + attachedToParent: true, + runtimeMode: "full-access", + session: { ...running!, threadId: ThreadId.make("raised-child") }, + }); + const familyWorld = yield* makeWorld({ threads: [parent, raisedChild] }); + const stopped = yield* familyWorld.handlers.thread_stop(CALLER, { + threadId: "parent-stop", + }); + expect(stopped.outcome).toBe("stopped"); + expect(stopped.detail).toContain("Deploy prod"); }), ); }); diff --git a/apps/server/src/outsideAgents/connectToolHandlers.ts b/apps/server/src/outsideAgents/connectToolHandlers.ts index 5089a111f..d16dfa698 100644 --- a/apps/server/src/outsideAgents/connectToolHandlers.ts +++ b/apps/server/src/outsideAgents/connectToolHandlers.ts @@ -107,10 +107,16 @@ import { childWorktreeBranch, derivedUuid } from "../orchestration/childRequestI import { makeSingleFlight } from "../orchestration/Layers/BootstrapTurnStartRuns.ts"; import { ForwardedGrantCap } from "./forwardedCalls.ts"; import { type FoundComputer, type OtherComputersShape, peerAgentOf } from "./OtherComputers.ts"; +import { + isStillGoing, + stillGoingInputOfShell, + stopReachOf, +} from "@threadlines/shared/childThreads"; import { OUTSIDE_ALREADY_QUEUED, outsideCeilingDetail, outsideQueuedOf, + outsideStopRefusal, outsideTurnBusy, } from "../orchestration/outsideTurns.ts"; import type { OrchestrationEngineShape } from "../orchestration/Services/OrchestrationEngine.ts"; @@ -2343,20 +2349,37 @@ export const makeConnectToolHandlers = ( request === null ? Effect.succeed(result) : forget(caller, request.requestId).pipe(Effect.as(result)); + const origin = outsideOrigin(caller, gated.grant); const stopped = yield* deps.engine .dispatch({ type: "thread.turn.interrupt", commandId, threadId: thread.id, ...(turnId !== undefined ? { turnId } : {}), - fromOutside: outsideOrigin(caller, gated.grant), + fromOutside: origin, createdAt: isoOf(yield* nowMillis), }) .pipe(Effect.result); if (stopped._tag === "Success") { + // Threads under this one above this agent's limit were left running + // by the decider; name them in the answer. + const projectThreads = yield* deps + .listThreads({ projectIds: [thread.projectId] }) + .pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<OrchestrationThreadShell>)); + const leftRunning = stopReachOf(projectThreads, thread.id) + .map((entry) => entry.thread) + .filter( + (child) => + isStillGoing(stillGoingInputOfShell(child)) && + outsideStopRefusal(child, origin) !== null, + ); + const detail = + leftRunning.length === 0 + ? "Stopped. A later thread_send starts it again." + : `Stopped. Left running (above your access limit): ${leftRunning.map((entry) => `'${entry.title}'`).join(", ")}.`; return yield* answered({ outcome: "stopped", - detail: "Stopped. A later thread_send starts it again.", + detail, threadId: thread.id, }); } diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index a12374df9..fc8bec548 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -1264,4 +1264,66 @@ describe("ProviderSessionReaper", () => { reapedThreadId, ]); }); + + it("marks saved check-backs dormant when reaping an idle session", async () => { + const threadId = ThreadId.make("thread-reaper-saved-check-back"); + const now = "2026-01-01T00:00:00.000Z"; + const savedJob: OrchestrationCheckBack = { + id: "saved-job-reap", + participantId: null, + scheduledFor: "2999-01-01T00:00:00.000Z", + exact: true, + recurring: true, + description: "Nightly check", + durable: true, + }; + const harness = await createHarness({ + readModel: makeReadModel([ + { + id: threadId, + session: { + threadId, + status: "ready", + providerName: "claudeAgent", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + checkBacks: [savedJob], + }, + ]), + }); + const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository)); + await runtime!.runPromise( + repository.upsert({ + threadId, + providerName: "claudeAgent", + providerInstanceId: null, + adapterKey: "claudeAgent", + runtimeMode: "full-access", + status: "running", + lastSeenAt: "2026-04-14T00:00:00.000Z", + resumeCursor: { opaque: "resume-saved-check-back" }, + runtimePayload: null, + }), + ); + + const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); + scope = await Effect.runPromise(Scope.make("sequential")); + await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); + + await waitFor(() => + harness.dispatch.mock.calls.some(([command]) => command.type === "thread.check-backs.set"), + ); + await Effect.runPromise(drainFibers); + const setCommand = harness.dispatch.mock.calls + .map(([command]) => command) + .find((command) => command.type === "thread.check-backs.set"); + expect(setCommand).toMatchObject({ + type: "thread.check-backs.set", + threadId, + checkBacks: [{ ...savedJob, dormant: true }], + }); + }); }); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index ed7bbb5d6..c18d5b1ec 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -12,7 +12,11 @@ import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import { runtimeCheckBackOwed } from "@threadlines/shared/checkBacks"; +import { + markCheckBacksDormant, + runtimeCheckBackOwed, + sameCheckBacks, +} from "@threadlines/shared/checkBacks"; import { parseParticipantSessionKey, sessionKeyThreadId, @@ -58,6 +62,7 @@ const holdsForCheckBack = ( type ThreadShellWithSession = { readonly session?: OrchestrationSession | null; + readonly checkBacks?: ReadonlyArray<OrchestrationCheckBack> | undefined; }; type StopProjectionReason = "inactivity_threshold" | "startup_binding_stopped" | "startup_orphaned"; @@ -188,13 +193,36 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = createdAt: input.nowIso, }) .pipe(Effect.asVoid); + // The runtime has ended: mark any check-backs still listed for this + // agent dormant (dropping session-only ones, keeping saved jobs dormant). + const participantId = parseParticipantSessionKey(input.binding.threadId).participantId; + const currentCheckBacks = (input.thread?.checkBacks ?? []).filter( + (checkBack) => checkBack.participantId === participantId, + ); + if (currentCheckBacks.length > 0) { + const dormant = markCheckBacksDormant(input.thread?.checkBacks ?? [], participantId); + if (!sameCheckBacks(currentCheckBacks, dormant)) { + yield* orchestrationEngine + .dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make( + `provider-session-reaper:check-backs-dormant:${input.binding.threadId}:${randomUUID()}`, + ), + threadId: sessionKeyThreadId(input.binding.threadId), + participantId, + checkBacks: dormant, + createdAt: input.nowIso, + }) + .pipe(Effect.asVoid, Effect.ignoreCause({ log: true })); + } + } return true; }); /** * An agent's check-backs whose runtime is gone (the server stopped with * it) can't fire: they are cleared with a note in the chat. Durable ones - * outlive the runtime and stay. + * outlive the runtime and stay listed as dormant until the next run. */ const dropOrphanedCheckBacks = (input: { readonly binding: ProviderRuntimeBindingWithMetadata; @@ -204,7 +232,11 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = Effect.gen(function* () { const participantId = parseParticipantSessionKey(input.binding.threadId).participantId; const lost = runtimeCheckBacks(input.thread, participantId); - if (lost.length === 0) return; + const current = (input.thread.checkBacks ?? []).filter( + (checkBack) => checkBack.participantId === participantId, + ); + const dormant = markCheckBacksDormant(input.thread.checkBacks ?? [], participantId); + if (lost.length === 0 && sameCheckBacks(current, dormant)) return; const threadId = sessionKeyThreadId(input.binding.threadId); yield* orchestrationEngine.dispatch({ type: "thread.check-backs.set", @@ -213,9 +245,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = ), threadId, participantId, - checkBacks: (input.thread.checkBacks ?? []).filter( - (checkBack) => checkBack.participantId === participantId && checkBack.durable, - ), + checkBacks: dormant, createdAt: input.nowIso, }); for (const checkBack of lost) { diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 206d0da75..87d0f8b5c 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -3711,7 +3711,9 @@ function applyEnvironmentOrchestrationEvent( case "thread.agent-requests-held": return updateAgentRequestState(state, event.payload.threadId, (current) => - agentRequestStateOn.held(current, event.payload.chainEpoch), + agentRequestStateOn.held(current, event.payload.chainEpoch, { + keepHold: event.payload.keepHold === true, + }), ); case "thread.agent-requests-reset": diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 7518f29cc..f137daec6 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -328,7 +328,7 @@ Pure rules live in `packages/shared/src/childThreads.ts` (refusals, limits, fami **Pickup** uses the existing queue: an idle parent starts a turn via `maybeSendNextQueuedFollowUp`. A parent whose agent the report is for is working: the report is steered into that running turn (`steerQueuedAgentMessage`, on providers that can steer), with the same preamble a report turn gets, and `send-queued` with `steeredTurnId` records it in that turn and takes it off the queue. Waiting behind the turn instead left the report queued for as long as the turn ran (an hour, in practice) while the agent fetched it itself, then sent it again as a turn of its own. A report that cannot be steered (the turn just ended, the provider can't steer, another room agent holds the thread) waits behind the current turn, and the user's own queued messages still go first. -**Late replies.** A child can keep working after its answer went back, with no request open: a check-back wakes it, or an agent it asked (a reviewer in its own room) replies and it acts on that. That work is not a report and wakes nobody. Instead, at the parent agent's next turn, `childThreadContext` adds each attached local child whose newest turn finished after its handed-back one, with nothing open, nothing running, and no message from the user since the hand-back (`lateReplyOf` in childThreadDelivery.ts), with its last reply clipped to 4,000 chars. The agent it is for is the one its last report went to (`lateReplyRecipient`). Once the turn is sent, `thread.child-notes.delivered` carries `lateReplies`, and the decider records each child handed back as of that turn, only while it is still the child's newest. It is read from the threads at turn start, never recorded when the child's turn ends, so a restart loses nothing, and a child that keeps checking back can't wake its parent in a loop. A child on a linked computer is not covered: this computer can't read its turns at turn start. +**Follow-up reports.** Every later turn an attached local child takes on its own after its answer went back (a check-back, a reviewer's reply, a scheduled run, background work that finished) owes its parent a report and wakes the parent when it ends (docs/design/agent-autonomy-no-limits.md). Turns a person or an outside agent started, or a hand-off to another agent in the same thread, do not report. Late replies are gone on this computer. **Before sending any `fromThread.kind = "report"` turn**, the reactor re-checks all of these: @@ -351,7 +351,7 @@ If any check fails, the entry is unqueued `cancelled`. This catches answers dequ Each of these settles open requests and also unqueues the matching queued report entries. -- **Stop on the parent** (`turn.interrupt` / `session.stop`). `decideAgentChainStop` extends to settle every open child request `stopped`, unqueue every queued report, and add a note. Children keep running. "Stop N working threads" stops them on demand. +- **Stop on the parent** (`turn.interrupt`). Puts the hold on the parent, settles its open requests `stopped`, unqueues queued reports, cancels its check-backs, and in the same decision stops every thread in its Stop reach that is still going (attached threads and threads started without report back that the user has not written in yet) with cause `family`, which moves their epochs and ends their check-backs without putting a new hold on them. "Stop N working threads" (`thread.children.stop`) and the Stop button on the family tab row stop those threads while leaving the parent itself running. - **`thread_stop` on a child** also records the turn it cut off as handed back (`stoppedTurnHandedBack`), only when that turn is running: the parent's agent ended it, so nothing is owed back and the child wraps itself once the interrupt lands. A finished turn (the user's) is never stamped. On a linked computer, the child's computer records the same after a stop the link asked for (`stopIfWorking` in LinkRequests.ts). - **Wrap the parent** (done-override `done`). The parent's open requests settle `cancelled`, queued reports are unqueued, and a note is added. Children keep running. - **Separate** (`thread.parent-attachment.set { attached: false }`, user). That child's open requests on the parent settle `cancelled`, its queued reports are unqueued, and a note is added. The parent's queued request messages inside the child stay; they're the child's to run now. @@ -362,7 +362,7 @@ Each of these settles open requests and also unqueues the matching queued report Nothing is restored. Later sends report back again. -- **Delete the parent.** Decider cascade (`decideCommandSequence`, like `project.delete`). Attached children are separated, unless the command carries `withChildren: true`, in which case they're deleted. The confirm dialog gets "Also delete its N threads". Deleting a child settles its open requests `cancelled` and unqueues its reports. The client winds down only the thread the user named. The server decides which children go, and a child can leave the family between the dialog and the delete, so the cleanup for each deleted child runs off its own `thread.deleted` event: `ThreadDeletionReactor` stops its runtime and deletes its terminal history, and each client drops its draft and terminal state when the removal arrives. A child the server keeps loses nothing. +- **Delete the parent.** Decider cascade (`decideCommandSequence`, like `project.delete`). Attached children are separated, unless the command names them in `alsoDelete` (the exact unarchived attached threads the dialog listed — any other attached child, including one started in between, is separated and kept) or carries `withChildren: true` from an older client. The confirm dialog gets "Also delete its N threads". Deleting a child settles its open requests `cancelled` and unqueues its reports. The client winds down only the thread the user named. Cleanup for each deleted child runs off its own `thread.deleted` event: `ThreadDeletionReactor` stops its runtime and deletes its terminal history, and each client drops its draft and terminal state when the removal arrives. A child the server keeps loses nothing. - **Archive the parent.** The cascade is decided on the server: - attached children that are settled (no turn in flight, no open requests of their own, no pending approvals, no background work, no command running in their terminal, no check-back owed that would die with their session) are archived and stamped `archivedWithParentAt`; - live attached children are separated first. diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 10339f667..66e8837fb 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1225,6 +1225,8 @@ export const ThreadNativeSessionFellBackPayload = Schema.Struct({ reason: ThreadNativeSessionFellBackReason, /** `turn_failed`: the message the refused turn sent, sent again once on a seeded session. */ resendMessageId: Schema.optional(MessageId), + /** Stop count when the refused turn ran: a resend that arrives after a Stop is refused. */ + chainEpoch: Schema.optional(NonNegativeInt), /** A room agent's carried session (OrchestrationThreadParticipant.nativeSession). Absent: the thread's own agent's. */ participantId: Schema.optional(ThreadParticipantId), }); @@ -6207,6 +6209,7 @@ const ThreadNativeSessionFallBackCommand = Schema.Struct({ threadId: ThreadId, reason: ThreadNativeSessionFellBackReason, resendMessageId: Schema.optional(MessageId), + chainEpoch: Schema.optional(NonNegativeInt), /** A room agent's carried session. Absent: the thread's own agent's. */ participantId: Schema.optional(ThreadParticipantId), createdAt: IsoDateTime, @@ -6666,10 +6669,15 @@ export const ThreadAgentRequestSettledPayload = Schema.Struct({ settledAt: IsoDateTime, }); -/** Stop in a room: the hold goes on and the chain epoch moves to `chainEpoch`. */ +/** + * Stop in a room or family: the chain epoch moves to `chainEpoch` and the hold + * goes on. `keepHold`: the thread was stopped with its family or as cleanup, + * so the epoch moves without adding a new hold (any existing hold stays). + */ export const ThreadAgentRequestsHeldPayload = Schema.Struct({ threadId: ThreadId, chainEpoch: NonNegativeInt, + keepHold: Schema.optional(Schema.Literal(true)), createdAt: IsoDateTime, }); diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index 8a0aa821f..b364eb95d 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -38,12 +38,27 @@ export function sameCheckBacks( checkBack.description === other.description && checkBack.prompt === other.prompt && checkBack.cron === other.cron && - checkBack.durable === other.durable + checkBack.durable === other.durable && + (checkBack.dormant === true) === (other.dormant === true) ); }) ); } +/** + * The agent's check-backs after its runtime ended: jobs that die with the + * runtime are gone, and saved jobs stay listed as dormant so they no longer + * count as live until that agent runs again and reports its list afresh. + */ +export function markCheckBacksDormant( + current: ReadonlyArray<OrchestrationCheckBack>, + participantId: ThreadParticipantId | null, +): ReadonlyArray<OrchestrationCheckBack> { + return current + .filter((checkBack) => checkBack.participantId === participantId && checkBack.durable) + .map((checkBack) => (checkBack.dormant === true ? checkBack : { ...checkBack, dormant: true })); +} + /** * Whether any of a thread's agents holds a check-back that dies with its * runtime (not saved to outlive it), however old. A parent's archive diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index bd512e625..b67b8882f 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -155,6 +155,7 @@ export function childSendRefusal( readonly archivedAt: string | null; readonly runtimeMode?: RuntimeMode | undefined; readonly interactionMode?: ProviderInteractionMode | undefined; + readonly agentRequests?: { readonly hold: boolean } | undefined; } | null, input: { readonly from: RoomAgentRef; @@ -169,6 +170,14 @@ export function childSendRefusal( if (ownRefusal !== null) { return ownRefusal; } + // A child the user stopped holds its queue until the user writes there: + // sending it work would sit unseen (docs/design/agent-autonomy-no-limits.md). + if (child !== null && child.agentRequests?.hold === true) { + return { + outcome: "refused", + detail: "The user stopped that thread. It takes work again once they write there.", + }; + } // Work the lead chat passed on keeps its ceiling when it is handed down: // a pass never reaches a thread with more access than the lead's. const passCeiling = thread.childRequests.passCeiling; diff --git a/packages/shared/src/roomAgentRequests.ts b/packages/shared/src/roomAgentRequests.ts index f1eeba0de..0d429f312 100644 --- a/packages/shared/src/roomAgentRequests.ts +++ b/packages/shared/src/roomAgentRequests.ts @@ -242,8 +242,13 @@ export const agentRequestStateOn = { held: ( state: OrchestrationAgentRequestState, chainEpoch: number, - ): OrchestrationAgentRequestState => - state.hold && state.chainEpoch === chainEpoch ? state : { ...state, hold: true, chainEpoch }, + options?: { readonly keepHold?: boolean | undefined }, + ): OrchestrationAgentRequestState => { + const hold = options?.keepHold === true ? state.hold : true; + return state.hold === hold && state.chainEpoch === chainEpoch + ? state + : { ...state, hold, chainEpoch }; + }, reset: (state: OrchestrationAgentRequestState): OrchestrationAgentRequestState => !state.hold && !state.invitesPaused ? state : { ...state, hold: false, invitesPaused: false }, }; From a56b804556642d36481a795d5c108582960ebb18 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:52:01 -0500 Subject: [PATCH 14/16] test(server): expect saved check-backs to stay dormant without a capable runtime --- .../src/orchestration/Layers/ProviderCommandReactor.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 1f6bc8b25..b3b3a12a7 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -5224,7 +5224,8 @@ describe("ProviderCommandReactor", () => { expect(harness.stopSession.mock.calls.length).toBe(0); const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId); - expect(thread?.checkBacks).toEqual([saved]); + // The running provider can't fire Claude's saved job, so it stays listed as dormant. + expect(thread?.checkBacks).toEqual([{ ...saved, dormant: true }]); }); it("clears a stale check-back list but keeps the jobs saved to disk", async () => { @@ -5271,7 +5272,8 @@ describe("ProviderCommandReactor", () => { return thread?.checkBacks?.length === 1; }); const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId); - expect(thread?.checkBacks).toEqual([saved]); + // The runtime is gone, so the saved job stays listed as dormant until it runs again. + expect(thread?.checkBacks).toEqual([{ ...saved, dormant: true }]); expect(harness.stopSession.mock.calls.length).toBe(0); }); From e4852e8bfbfea8c389053ae21d1e92bd49ded593 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:45:12 -0500 Subject: [PATCH 15/16] fix(server): close Stage 1 access, dormant check-back, stop, and move-freeze edge cases Carry requestCeiling and passBlocked across accountSwitch continues, mark saved check-backs dormant for non-slot room agents and archived/switched threads on exit or reap, bump chainEpoch on family/cleanup stops of starting or loose threads without adding holds, drop child follow-up reports targeting frozen/quiescing parents, skip carried-session fallback resend when the user already stopped the turn, narrow ask-mode requestCeiling on approval, save launchedAccess on moved-alone remoteOrigin, and report remote queued ceiling refusals as failed. --- apps/server/src/links/LinkMoves.test.ts | 4 + apps/server/src/links/LinkMoves.ts | 6 + apps/server/src/links/LinkRequests.ts | 25 ++- .../Layers/ChildThreadReactor.ts | 7 +- .../Layers/ProviderRuntimeIngestion.test.ts | 151 +++++++++++++++++ .../Layers/ProviderRuntimeIngestion.ts | 67 +++++--- apps/server/src/orchestration/childReports.ts | 3 + .../decider.childThreads.test.ts | 152 ++++++++++++++++++ apps/server/src/orchestration/decider.ts | 18 ++- .../Layers/ProviderSessionReaper.test.ts | 76 +++++++++ .../provider/Layers/ProviderSessionReaper.ts | 59 ++++--- 11 files changed, 505 insertions(+), 63 deletions(-) diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index f5901dce0..1b3a03e6c 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -2128,6 +2128,10 @@ describe("a thread moving across its link (Part 3f, (h))", () => { environmentLabel: "Windows PC", threadId: PARENT_THERE, threadTitle: "Ship it", + launchedAccess: { + runtimeMode: "auto-accept-edits", + interactionMode: "default", + }, }); assert.equal(imported.movedFrom.environmentId, WINDOWS); assert.equal(imported.movedFrom.environmentPinned, true); diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index 487e98b58..5170dff70 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -2364,6 +2364,10 @@ const make = Effect.gen(function* () { projectId: string, pinnedEnvironmentId: string | null, fromLabel: string, + launchedAccess: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, ) => Effect.gen(function* () { const lineage = row.manifest.linkLineage; @@ -2388,6 +2392,7 @@ const make = Effect.gen(function* () { environmentLabel: fromLabel, threadId: remoteParent.threadId, threadTitle: remoteParent.title, + launchedAccess, }; return { remoteOrigin }; } @@ -2771,6 +2776,7 @@ const make = Effect.gen(function* () { land.project.id, authority.pinnedEnvironmentId, fromLabel, + { runtimeMode: capped.runtimeMode, interactionMode: capped.interactionMode }, ); if (across.left !== undefined) familyLeft.push(across.left); // The threads it started here that may be its children again (Part 3f, diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 8addfdc64..220c28db3 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -60,7 +60,7 @@ import { TurnId, } from "@threadlines/contracts"; import { hasLiveCheckBack } from "@threadlines/shared/checkBacks"; -import { sameRemoteThreadFiling } from "@threadlines/shared/childThreads"; +import { requestCeilingRefusal, sameRemoteThreadFiling } from "@threadlines/shared/childThreads"; import { remoteThreadFilingOf } from "@threadlines/shared/threadFiling"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; @@ -2135,13 +2135,26 @@ const make = Effect.gen(function* () { const deviceId = thread?.remoteOrigin?.linkDeviceId; if (thread === undefined || deviceId === undefined) return; const rows = yield* openRowsForThread(thread); + const storedMessage = thread.messages.find( + (entry) => entry.id === event.payload.messageId, + ); + const ceilingRefusal = !thread.agentRequests.hold + ? requestCeilingRefusal( + storedMessage?.requestCeiling ?? thread.remoteOrigin?.launchedAccess, + thread, + ) + : null; for (const row of rows) { if (row.messageId !== event.payload.messageId) continue; - yield* settle( - row, - "cancelled", - `Your message to '${thread.title}' on ${ownLabel()} was taken back before it ran.`, - ); + if (ceilingRefusal !== null) { + yield* settle(row, "failed", ceilingRefusal); + } else { + yield* settle( + row, + "cancelled", + `Your message to '${thread.title}' on ${ownLabel()} was taken back before it ran.`, + ); + } } return; } diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index 72177ae6a..62bb65f4c 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -24,7 +24,7 @@ import * as Stream from "effect/Stream"; import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { effectiveRequestCeiling } from "@threadlines/shared/childThreads"; +import { effectiveRequestCeiling, narrowerModeCeiling } from "@threadlines/shared/childThreads"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { childHasLiveWork, @@ -268,7 +268,10 @@ export const makeChildThreadReactor = Effect.gen(function* () { // when it asked (an approval can come much later). launch: clampLaunchToCeiling(launch, parent), fromThread: { threadId: parent.id, requestId, kind: "request" }, - requestCeiling: request.requestCeiling ?? effectiveRequestCeiling(parent), + requestCeiling: narrowerModeCeiling( + request.requestCeiling, + effectiveRequestCeiling(parent), + ), createdAt: request.createdAt, }), ); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 61e71da49..df50c659e 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -8743,4 +8743,155 @@ describe("ProviderRuntimeIngestion", () => { ); expect(revived.checkBacks?.[0]?.dormant).toBeUndefined(); }); + + it("marks a non-slot room agent's saved check-back dormant on session exit", async () => { + const harness = await createHarness(); + const threadId = asThreadId("thread-1"); + const astraId = ThreadParticipantId.make("11111111-1111-4111-8111-111111111111"); + const now = "2026-01-01T00:00:00.000Z"; + + // Astra holds a saved check-back while the primary agent (participantId: null) holds the slot. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make("cmd-non-slot-cb"), + threadId, + participantId: astraId, + checkBacks: [ + { + id: "saved-astra", + participantId: astraId, + scheduledFor: "2026-01-01T01:00:00.000Z", + exact: true, + recurring: true, + description: "Astra watcher", + durable: true, + }, + ], + createdAt: now, + }), + ); + + harness.emit({ + type: "session.exited", + eventId: asEventId("evt-non-slot-exit"), + provider: ProviderDriverKind.make("claudeAgent"), + threadId, + participantId: astraId, + createdAt: "2026-01-01T00:01:00.000Z", + payload: { exitKind: "graceful" }, + }); + const afterExit = await waitForThread( + harness.readModel, + (entry) => + entry.checkBacks?.some( + (cb) => cb.id === "saved-astra" && cb.participantId === astraId && cb.dormant === true, + ) === true, + ); + expect(afterExit.checkBacks).toEqual([ + expect.objectContaining({ id: "saved-astra", participantId: astraId, dormant: true }), + ]); + }); + + it("does not schedule a carried-session fallback resend when the user already stopped the turn", async () => { + const harness = await createHarness(); + const threadId = ThreadId.make("thread-carried-stopped"); + const msgId = asMessageId("msg-carried-stopped"); + const turnId = asTurnId("turn-carried-stopped"); + const now = "2026-01-01T00:00:00.000Z"; + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.import", + commandId: CommandId.make("cmd-import-carried-stopped"), + threadId, + projectId: asProjectId("project-1"), + title: "Moved here", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + movedFrom: { + environmentId: EnvironmentId.make("environment-windows"), + label: "Windows PC", + threadId: ThreadId.make("thread-there-stopped"), + movedAt: now, + }, + messages: [], + activities: [], + nativeSession: "carried", + createdAt: now, + }), + ); + harness.setProviderSession({ + provider: ProviderDriverKind.make("codex"), + status: "ready", + runtimeMode: "approval-required", + threadId, + createdAt: now, + updatedAt: now, + }); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-carried-start"), + threadId, + message: { messageId: msgId, role: "user", text: "Do the thing", attachments: [] }, + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: now, + }), + ); + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-carried-turn-started"), + provider: ProviderDriverKind.make("codex"), + threadId, + turnId, + createdAt: "2026-01-01T00:00:01.000Z", + }); + await waitForThread( + harness.readModel, + (entry) => entry.session?.activeTurnId === turnId, + 10_000, + threadId, + ); + + // User presses Stop while the turn is running. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.interrupt", + commandId: CommandId.make("cmd-carried-stop"), + threadId, + turnId, + createdAt: "2026-01-01T00:00:02.000Z", + }), + ); + + // Carried session then reports turn failure (encrypted content refused). + harness.emit({ + type: "turn.completed", + eventId: asEventId("evt-carried-turn-failed"), + provider: ProviderDriverKind.make("codex"), + threadId, + turnId, + createdAt: "2026-01-01T00:00:03.000Z", + payload: { + state: "failed", + errorMessage: + '{"error":{"message":"The encrypted content could not be verified.","code":"invalid_encrypted_content"}}', + }, + }); + const fellBack = await waitForThread( + harness.readModel, + (entry) => entry.nativeSession === "fell_back", + 10_000, + threadId, + ); + const activity = fellBack.activities.find( + (entry) => entry.kind === "thread.native-session-fell-back", + ); + expect(activity?.payload).toEqual({ reason: "turn_failed" }); + }); }); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 6e4c4407f..f1265006d 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -2708,9 +2708,12 @@ const make = Effect.gen(function* () { Effect.orElseSucceed(() => undefined), ); // The message that started this turn. Only that one goes again; a turn - // whose message isn't known (one the provider started) sends nothing - // again, and the line tells the user to. + // whose message isn't known (one the provider started) or that the user + // already stopped sends nothing again, and the line tells the user to. const startedBy = endedTurn?.pendingMessageId ?? undefined; + const stoppedByUser = + input.thread.agentRequests.hold || input.thread.session?.stopRequestedTurnId === input.turnId; + const resendMessageId = stoppedByUser ? undefined : startedBy; if (rejected) { // Off the ingestion queue: ending the session waits for its process, // whose last events come through here. @@ -2723,8 +2726,9 @@ const make = Effect.gen(function* () { commandId: providerCommandId(input.event, "native-session-fall-back"), threadId: input.thread.id, reason: "turn_failed", - ...(startedBy !== undefined ? { resendMessageId: startedBy } : {}), - chainEpoch: input.thread.agentRequests.chainEpoch, + ...(resendMessageId !== undefined + ? { resendMessageId, chainEpoch: input.thread.agentRequests.chainEpoch } + : {}), ...(input.participantId !== null ? { participantId: input.participantId } : {}), createdAt: input.now, }), @@ -3092,6 +3096,41 @@ const make = Effect.gen(function* () { ); return; } + // A runtime that ended can no longer fire any check-back still listed + // for its agent (saved jobs stay listed as dormant; session-only ones + // drop). Handle before the slot, active-session, and archive guards so + // non-slot room agents, switched providers, and archived threads never + // leave saved check-backs looking live. + if (event.type === "session.exited") { + const exitThread = + thread ?? + Option.getOrUndefined( + yield* projectionSnapshotQuery + .getThreadDetailById(event.threadId, { includeArchived: true }) + .pipe(Effect.orElseSucceed(() => Option.none())), + ); + if (exitThread !== undefined) { + const participantId = event.participantId ?? null; + const current = (exitThread.checkBacks ?? []).filter( + (checkBack) => checkBack.participantId === participantId, + ); + if (current.length > 0) { + const dormant = markCheckBacksDormant(exitThread.checkBacks ?? [], participantId); + if (!sameCheckBacks(current, dormant)) { + yield* orchestrationEngine + .dispatch({ + type: "thread.check-backs.set", + commandId: providerCommandId(event, "check-backs-dormant"), + threadId: exitThread.id, + participantId, + checkBacks: dormant, + createdAt: event.createdAt, + }) + .pipe(Effect.asVoid, Effect.ignoreCause({ log: true })); + } + } + } + } if (!thread) return; if (event.sideTurnId !== undefined) { yield* recordMcpAppCall(event, thread.id); @@ -3399,26 +3438,6 @@ const make = Effect.gen(function* () { yield* clearSettledSubagentResultState(`${thread.id}:`); } else { yield* sealSubagentResultState(`${thread.id}:`); - // The runtime ended: any check-backs still listed for this agent - // can no longer fire until the agent runs again (saved jobs stay - // listed as dormant; session-only ones are gone). - const participantId = event.participantId ?? null; - const current = (thread.checkBacks ?? []).filter( - (checkBack) => checkBack.participantId === participantId, - ); - if (current.length > 0) { - const dormant = markCheckBacksDormant(thread.checkBacks ?? [], participantId); - if (!sameCheckBacks(current, dormant)) { - yield* orchestrationEngine.dispatch({ - type: "thread.check-backs.set", - commandId: providerCommandId(event, "check-backs-dormant"), - threadId: thread.id, - participantId, - checkBacks: dormant, - createdAt: now, - }); - } - } } } diff --git a/apps/server/src/orchestration/childReports.ts b/apps/server/src/orchestration/childReports.ts index baa3c6ac7..5734622df 100644 --- a/apps/server/src/orchestration/childReports.ts +++ b/apps/server/src/orchestration/childReports.ts @@ -178,6 +178,9 @@ export function reportDropReason( return "Its delivery was cancelled since the turn started."; } if (parent.archivedAt !== null) return "The parent is archived."; + if ((parent.move ?? null) !== null || parent.pendingMove?.stage === "quiescing") { + return "The parent is moving to another computer."; + } if (isWrappedByHand(parent)) return "The parent is wrapped up."; if (parent.agentRequests.hold || child.agentRequests.hold) return "The user stopped one of them."; return null; diff --git a/apps/server/src/orchestration/decider.childThreads.test.ts b/apps/server/src/orchestration/decider.childThreads.test.ts index 9cf2d6581..67de8e37a 100644 --- a/apps/server/src/orchestration/decider.childThreads.test.ts +++ b/apps/server/src/orchestration/decider.childThreads.test.ts @@ -3428,6 +3428,158 @@ describe("child thread access ceilings (stage 1 step 3)", () => { expect(stoppedIds.has(WITHIN)).toBe(true); expect(stoppedIds.has(RAISED)).toBe(false); }); + + it("carries requestCeiling and passBlocked across accountSwitch continues, and refuses if widened", async () => { + const narrowCeiling = { + runtimeMode: "auto-accept-edits" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }; + const originalMsgId = MessageId.make("m-orig-acct"); + const origTurnId = TurnId.make("t-orig-acct"); + const base = readModel([ + thread(PARENT, { runtimeMode: "auto-accept-edits" }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + runtimeMode: "auto-accept-edits", + messages: [ + { + id: originalMsgId, + role: "user", + text: "Narrow passed work", + turnId: null, + streaming: false, + fromThread: { threadId: PARENT, requestId: REQUEST, kind: "request" }, + requestCeiling: narrowCeiling, + passBlocked: true, + createdAt: at(1), + updatedAt: at(1), + }, + ], + latestTurn: { + turnId: origTurnId, + state: "error", + requestedAt: at(1), + startedAt: at(1), + completedAt: at(2), + assistantMessageId: null, + }, + session: session(CHILD, { status: "error", activeTurnId: null }), + }), + ]); + + // Still narrow: accountSwitch continues, carrying both requestCeiling and passBlocked. + const switched = await run(base, { + type: "thread.turn.start", + commandId: CommandId.make("acct-switch-ok"), + threadId: CHILD, + message: { + messageId: MessageId.make("m-acct-switch"), + role: "user", + text: "Continue after account switch", + attachments: [], + }, + trigger: "accountSwitch", + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(5), + }); + const switchMsg = threadIn(switched.model, CHILD).messages.at(-1); + expect(switchMsg?.requestCeiling).toEqual(narrowCeiling); + expect(switchMsg?.passBlocked).toBe(true); + expect(threadIn(switched.model, CHILD).childRequests.passCeiling).toEqual(narrowCeiling); + + // Widened before accountSwitch: refused by the ceiling. + const widened: OrchestrationReadModel = { + ...base, + threads: base.threads.map((entry) => + entry.id === CHILD ? { ...entry, runtimeMode: "full-access" } : entry, + ), + }; + expect( + await refused(widened, { + type: "thread.turn.start", + commandId: CommandId.make("acct-switch-widened"), + threadId: CHILD, + message: { + messageId: MessageId.make("m-acct-switch-widened"), + role: "user", + text: "Continue after account switch", + attachments: [], + }, + trigger: "accountSwitch", + runtimeMode: "full-access", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: at(6), + }), + ).toBe(true); + }); + + it("bumps chainEpoch without adding a hold on family stop of a starting single-agent child or loose thread", async () => { + const LOOSE = ThreadId.make("loose-starting"); + const start = readModel([ + thread(PARENT, { session: session(PARENT, { status: "ready", activeTurnId: null }) }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + session: session(CHILD, { status: "starting", activeTurnId: null }), + }), + thread(LOOSE, { + parentThreadId: PARENT, + attachedToParent: false, + stopsWithParent: true, + session: session(LOOSE, { status: "starting", activeTurnId: null }), + }), + ]); + + const stopped = await run(start, { + type: "thread.turn.interrupt", + commandId: CommandId.make("stop-starting-children"), + threadId: PARENT, + createdAt: at(10), + }); + expect(threadIn(stopped.model, CHILD).agentRequests.chainEpoch).toBe(1); + expect(threadIn(stopped.model, CHILD).agentRequests.hold).toBe(false); + expect(threadIn(stopped.model, LOOSE).agentRequests.chainEpoch).toBe(1); + expect(threadIn(stopped.model, LOOSE).agentRequests.hold).toBe(false); + }); + + it("drops a child follow-up report when the parent is frozen for a move", async () => { + const turnId = TurnId.make("child-owed-turn"); + const start = readModel([ + thread(PARENT, { + move: { + transferId: "move-1" as never, + target: { environmentId: EnvironmentId.make("env-remote"), label: "Mac mini" }, + agent: model, + startedAt: at(1), + phase: "sending", + cancelRequested: false, + }, + }), + thread(CHILD, { + parentThreadId: PARENT, + attachedToParent: true, + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + owedReports: [{ turnId, deliveryEpoch: 0, attachmentEpoch: 0, createdAt: at(1) }], + }, + }), + ]); + + const settled = await run(start, { + type: "thread.child-report.settle", + commandId: CommandId.make("settle-frozen-parent"), + threadId: CHILD, + owed: { turnId }, + turnId, + text: "Late report after freeze", + createdAt: at(5), + }); + expect(threadIn(settled.model, CHILD).childRequests.owedReports ?? []).toEqual([]); + expect(threadIn(settled.model, PARENT).messages).toEqual([]); + expect(threadIn(settled.model, PARENT).queuedFollowUps ?? []).toEqual([]); + }); }); function modelSelectionOf(entry: OrchestrationThread) { diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index ce0861c8b..e29c0093e 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -3834,10 +3834,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: passStartRefusal, }); } - // A parent's request (and any continue of its turn) never starts above - // the sender's access ceiling (docs/design/agent-autonomy-no-limits.md). + // A parent's request (and any continue of its turn, including account + // switch) never starts above the sender's access ceiling + // (docs/design/agent-autonomy-no-limits.md). const continuedStartAccess = - command.trigger !== undefined && isContinueTrigger(command.trigger) + command.trigger !== undefined ? continuedMessageAccess( readModel, targetThread, @@ -5579,13 +5580,16 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // Stop does, so a turn still being prepared for an agent is dropped. // The user's own session stop holds a family like their Stop does; one // the server makes (with its family, as cleanup) leaves no new hold. + const inFamily = + thread.childRequests.open.length > 0 || + attachedChildrenOf(readModel, thread.id).length > 0 || + isAttachedChild(thread); const chainStop = [ ...decideAgentChainStop(thread, base, command.createdAt, { holdsFamily: - command.cause === undefined && - (thread.childRequests.open.length > 0 || - attachedChildrenOf(readModel, thread.id).length > 0 || - isAttachedChild(thread)), + inFamily || + (command.cause !== undefined && + (thread.stopsWithParent === true || thread.session?.status === "starting")), keepHold: command.cause !== undefined, }), ...childStopEvents(readModel, thread, command, command.createdAt), diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index fc8bec548..215846e51 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -9,6 +9,7 @@ import { ProviderInstanceId, type ProviderSession, } from "@threadlines/contracts"; +import { participantSessionKey } from "@threadlines/shared/threadParticipants"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -1326,4 +1327,79 @@ describe("ProviderSessionReaper", () => { checkBacks: [{ ...savedJob, dormant: true }], }); }); + + it("marks a non-slot room agent's saved check-backs dormant when reaping its idle runtime", async () => { + const threadId = ThreadId.make("11111111-1111-4111-8111-111111111111"); + const astraId = ThreadParticipantId.make("22222222-2222-4222-8222-222222222222"); + const astraSessionKey = participantSessionKey(threadId, astraId); + const now = "2026-01-01T00:00:00.000Z"; + const savedJob: OrchestrationCheckBack = { + id: "saved-job-non-slot", + participantId: astraId, + scheduledFor: "2999-01-01T00:00:00.000Z", + exact: true, + recurring: true, + description: "Astra nightly check", + durable: true, + }; + const harness = await createHarness({ + // Astra's runtime is alive and idle so the inactivity sweep (not startup orphan cleanup) reaps it. + activeProviderSessions: [ + makeProviderSession({ + threadId: astraSessionKey, + provider: ProviderDriverKind.make("claudeAgent"), + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + status: "ready", + }), + ], + readModel: makeReadModel([ + { + id: threadId, + // Primary agent (participantId: null) holds the slot, not Astra. + session: { + threadId, + status: "ready", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: now, + }, + checkBacks: [savedJob], + }, + ]), + }); + const repository = await runtime!.runPromise(Effect.service(ProviderSessionRuntimeRepository)); + await runtime!.runPromise( + repository.upsert({ + threadId: astraSessionKey, + providerName: "claudeAgent", + providerInstanceId: null, + adapterKey: "claudeAgent", + runtimeMode: "full-access", + status: "running", + lastSeenAt: "2026-04-14T00:00:00.000Z", + resumeCursor: { opaque: "resume-non-slot-cb" }, + runtimePayload: null, + }), + ); + + const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); + scope = await Effect.runPromise(Scope.make("sequential")); + await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); + + await waitFor(() => + harness.dispatch.mock.calls.some(([command]) => command.type === "thread.check-backs.set"), + ); + await Effect.runPromise(drainFibers); + const setCommand = harness.dispatch.mock.calls + .map(([command]) => command) + .find((command) => command.type === "thread.check-backs.set"); + expect(setCommand).toMatchObject({ + type: "thread.check-backs.set", + threadId, + participantId: astraId, + checkBacks: [{ ...savedJob, dormant: true }], + }); + }); }); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts index c18d5b1ec..f534abfe8 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.ts @@ -170,6 +170,39 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = : { ...thread, session: null }; }); + const markReapedCheckBacksDormant = (input: { + readonly binding: ProviderRuntimeBindingWithMetadata; + readonly thread: ThreadShellWithSession | undefined; + readonly nowIso: string; + }) => + Effect.gen(function* () { + // The runtime has ended: mark any check-backs still listed for this + // agent dormant (dropping session-only ones, keeping saved jobs dormant). + const participantId = parseParticipantSessionKey(input.binding.threadId).participantId; + const currentCheckBacks = (input.thread?.checkBacks ?? []).filter( + (checkBack) => checkBack.participantId === participantId, + ); + if (currentCheckBacks.length === 0) { + return; + } + const dormant = markCheckBacksDormant(input.thread?.checkBacks ?? [], participantId); + if (sameCheckBacks(currentCheckBacks, dormant)) { + return; + } + yield* orchestrationEngine + .dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make( + `provider-session-reaper:check-backs-dormant:${input.binding.threadId}:${randomUUID()}`, + ), + threadId: sessionKeyThreadId(input.binding.threadId), + participantId, + checkBacks: dormant, + createdAt: input.nowIso, + }) + .pipe(Effect.asVoid, Effect.ignoreCause({ log: true })); + }); + const dispatchStoppedProjection = (input: { readonly binding: ProviderRuntimeBindingWithMetadata; readonly thread: ThreadShellWithSession | undefined; @@ -193,29 +226,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = createdAt: input.nowIso, }) .pipe(Effect.asVoid); - // The runtime has ended: mark any check-backs still listed for this - // agent dormant (dropping session-only ones, keeping saved jobs dormant). - const participantId = parseParticipantSessionKey(input.binding.threadId).participantId; - const currentCheckBacks = (input.thread?.checkBacks ?? []).filter( - (checkBack) => checkBack.participantId === participantId, - ); - if (currentCheckBacks.length > 0) { - const dormant = markCheckBacksDormant(input.thread?.checkBacks ?? [], participantId); - if (!sameCheckBacks(currentCheckBacks, dormant)) { - yield* orchestrationEngine - .dispatch({ - type: "thread.check-backs.set", - commandId: CommandId.make( - `provider-session-reaper:check-backs-dormant:${input.binding.threadId}:${randomUUID()}`, - ), - threadId: sessionKeyThreadId(input.binding.threadId), - participantId, - checkBacks: dormant, - createdAt: input.nowIso, - }) - .pipe(Effect.asVoid, Effect.ignoreCause({ log: true })); - } - } + yield* markReapedCheckBacksDormant(input); return true; }); @@ -478,7 +489,7 @@ const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) = reason: "inactivity_threshold", }), !thread?.session || thread.session.status === "stopped" - ? Effect.void + ? markReapedCheckBacksDormant({ binding, thread, nowIso }) : dispatchStoppedProjection({ binding, thread, From ca9da4f8ad159cb3a0852df93f1c948fa457b5bc Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:18:59 -0500 Subject: [PATCH 16/16] fix(server): emit session/exited when Codex app-server dies from a signal Effect's ChildProcessSpawner fails child.exitCode when a process ends from a signal (like SIGKILL or OOM), instead of resolving with a numeric code. CodexSessionRuntime had no error handler on that fiber, so a signal-killed Codex app-server never emitted session/exited, stayed stuck in running, and never notified a parent thread. Handle failed child.exitCode results and report the signal name. --- .../Layers/CodexSessionRuntime.test.ts | 44 +++++++++++++++++++ .../provider/Layers/CodexSessionRuntime.ts | 33 +++++++++----- 2 files changed, 66 insertions(+), 11 deletions(-) diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts index cea5b73b8..a2e106765 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts @@ -2169,4 +2169,48 @@ process.stdin.on("end", () => process.exit(0)); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), Effect.timeout("20 seconds")), ); }); + + it("emits session/exited when the app-server process is killed by a signal", async () => { + if (process.platform === "win32") return; + await Effect.runPromise( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const runtime = yield* makeCodexSessionRuntime({ + threadId: ThreadId.make("signal-exit-thread"), + serverPort: 0, + binaryPath: process.execPath, + cwd: process.cwd(), + runtimeMode: "full-access", + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, { + ...spawner, + spawn: () => + spawner.spawn( + ChildProcess.make(process.execPath, [ + fileURLToPath( + new URL( + "../../../../../packages/effect-codex-app-server/test/fixtures/codex-app-server-mock-peer.ts", + import.meta.url, + ), + ), + ]), + ), + }), + ); + const exited = yield* Deferred.make<ProviderEvent>(); + yield* runtime.events.pipe( + Stream.runForEach((event) => + event.method === "session/exited" ? Deferred.succeed(exited, event) : Effect.void, + ), + Effect.forkScoped, + ); + yield* runtime.start(); + assert.ok(runtime.process); + process.kill(runtime.process.pid, "SIGKILL"); + const exitEvent = yield* Deferred.await(exited); + assert.equal(exitEvent.method, "session/exited"); + assert.equal(exitEvent.message, "Codex App Server exited with signal SIGKILL."); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), Effect.timeout("10 seconds")), + ); + }); }); diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 237e2f35d..ecf200d42 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -98,6 +98,19 @@ import { } from "../codexAppServerArgs.ts"; const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError); +const SIGNAL_EXIT_PATTERN = /receipt of signal:\s*'([^']+)'/i; + +function formatCodexExitError(error: unknown): string { + const detail = + error instanceof Error + ? `${error.message} ${error.cause instanceof Error ? error.cause.message : ""}` + : String(error); + const match = SIGNAL_EXIT_PATTERN.exec(detail); + if (match?.[1]) { + return `Codex App Server exited with signal ${match[1]}.`; + } + return "Codex App Server exited unexpectedly."; +} const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse); const decodeV2ReviewStartResponse = Schema.decodeUnknownEffect( EffectCodexSchema.V2ReviewStartResponse, @@ -2906,26 +2919,24 @@ const makeCodexSessionRuntimeIn = ( ); yield* child.exitCode.pipe( - Effect.flatMap((exitCode) => + Effect.result, + Effect.flatMap((result) => Ref.get(closedRef).pipe( Effect.flatMap((closed) => { if (closed) { return Effect.void; } + const exitCode = Result.isSuccess(result) ? Number(result.success) : undefined; const nextStatus = exitCode === 0 ? "closed" : "error"; + const reason = Result.isSuccess(result) + ? exitCode === 0 + ? "Codex App Server exited." + : `Codex App Server exited with code ${exitCode}.` + : formatCodexExitError(result.failure); return updateSession(sessionRef, { status: nextStatus, activeTurnId: undefined, - }).pipe( - Effect.andThen( - emitSessionEvent( - "session/exited", - exitCode === 0 - ? "Codex App Server exited." - : `Codex App Server exited with code ${exitCode}.`, - ), - ), - ); + }).pipe(Effect.andThen(emitSessionEvent("session/exited", reason))); }), ), ),