Skip to content

refactor(agents): own background commands and yield waits by the chat - #200097

Merged
obviyus merged 1 commit into
mainfrom
obviyus/own-by-chat
Nov 16, 2026
Merged

obviyus merged 1 commit into
mainfrom
obviyus/own-by-chat

Conversation

@obviyus

@obviyus obviyus commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Background commands, sessions_yield waits and exec-exit wakes were owned by the run that started them. A run id names one attempt, and a chat gets a new one on every turn. So every follow-up run lost the commands of the earlier runs:

  • A later turn could not yield on a command that an earlier turn started. listYieldAwaitableExecs(runId) matched originRunId === runId, so sessions_yield returned nothing_pending and the model started to poll.
  • A paused subagent task continued only when the wake named the paused run. fix(agents): keep a yielded subagent's command wakes on its task after a follow-up run #200046 patched one caller of this: it moved the running commands to the new run (moveRunningSessionsToRun).
  • Child completions compared the captured requester session id and lifecycle revision. After a reset or a compaction successor, a private completion was withheld with "Subagent results from the previous session were not delivered".

Why This Change Was Made

The bug class is "address work by an id that changes". The chat's session key is the only id that survives edits, resets, compaction and follow-up runs. This PR makes the key the owner:

  • listYieldAwaitableExecs, awaitExecsForYield and openExecYieldResume are keyed by the chat: agent id plus session key, so a raw shared key such as global stays separate per agent. A yield awaits every wake-armed command of the chat, including commands from earlier runs.
  • Reply admission continues the task that is paused in the chat, whichever run paused it (continuesPausedTask replaces pausedRunId).
  • Child and harness completions, and the failure notice of a required completion, go to the requester chat as it is now. The reads of completionRequesterSessionId / LifecycleRevision, the settle-receipt exact compare, the collector and agents_wait incarnation filters, and the reset replacement notice are deleted.
  • Deleted: ProcessSession.originRunId, moveRunningSessionsToRun (the fix(agents): keep a yielded subagent's command wakes on its task after a follow-up run #200046 patch), matchesSubagentRequesterSession, recordRequesterReplacementNotice, listCollectorRunsForRequesterIncarnation (now listCollectorRunsForRequester).
  • Kept as a fact only: an exec wake still names the starting run in inputProvenance.runId (ProcessSession.startedByRunId), because plugins use it (fix(exec): plugin tools can tell which run started a background exec completion wake #179816). It routes nothing.
  • The requester id fields are still written for one release, so a downgrade keeps working. No schema, stored-row or protocol change.

Production delta: −227 lines in src (+127 / −354); whole PR −427.

User Impact

  • A chat can start a background command in one turn and wait for it with sessions_yield in a later turn. The exit continues the chat.
  • A yielded subagent always continues its paused task when one of its commands exits, also after a follow-up run.
  • A subagent result reaches the parent chat after /new or compaction instead of being withheld.

Evidence

Real agent on an isolated source Gateway (ocx src, scratch state, port and HOME, scrubbed env), Claude Opus through the shared Claude proxy. base = merge base 96ad377596ca, head = this PR.

Journey base head
J1: #200046 incident (paused child, A's exit continues the task in run 2, then B, started by run 1, exits) parent got child-final (with the #200046 patch) parent got child-final (patch deleted); registry generation=4 delivery=delivered
J2: run 1 starts a background command; run 2 calls sessions_yield {"status":"nothing_pending"} {"status":"yielded"}; the exit wakes the chat, which replies j2-woke
J3: parent spawns a child and does not yield ordinary completion (subagent_announce) ordinary completion (subagent_announce)
J1 parent side: parent yields on its child private completion (subagent_settle) private completion (subagent_settle)

Head arms ran on the production code of 3793f6d; later commits change only tests, docs and the failure-notice path of a required completion, which unit tests cover.

A /new while the parent is yielded on a running child interrupts the child on both arms, so that journey does not separate them and is not a claim of this PR.

Unit: openclaw-tools.requester-yield.test.ts now awaits a command with no starting run (fails on base). The delivery tests assert that a private completion reaches a replacement parent session.

Gates: oxfmt, oxlint on changed files, pnpm tsgo:core, pnpm check:test-types, ocx test on src/agents/subagents/, requester-yield, exec background and notify suites, agents_wait, harness completion, session reactivation and adoption, src/cron/isolated-agent. Build, full suites and cross-OS checks: hosted CI on this head. src/gateway/server-startup-post-attach.test.ts fails the same way on the merge base 059db8a; this PR does not touch it.

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L labels Nov 16, 2026
@obviyus
obviyus force-pushed the obviyus/own-by-chat branch from 313c7e9 to 00069fa Compare November 16, 2026 12:29
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head 00069fa47c41fd8a4eb5e188405be62849b289b9, but the PR head is now 52cf035e59adc4518745fa017c740ffd883655ae. Its old verdict and PR readiness labels are no longer current.

Next step
Comment @clawsweeper re-review when the current head is ready; pushes after the first review are not reviewed automatically.

Review history (1 earlier review cycle)
  • reviewed 2026-11-16T12:49:19.263Z sha 00069fa :: needs changes before merge. :: [P2] Include the agent in chat-owned exec wait selection | [P2] Exclude commands whose retained wake cannot resume the requester | [P2] Complete the affected consumer-test cutover | [P3] Update the documented requester-isolation guarantees

@obviyus
obviyus force-pushed the obviyus/own-by-chat branch 2 times, most recently from 3793f6d to 52cf035 Compare November 16, 2026 13:11
@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 16, 2026
@obviyus
obviyus force-pushed the obviyus/own-by-chat branch from 52cf035 to c5581ea Compare November 16, 2026 13:40
A run id names one attempt. Background commands, yield waits and exec-exit
wakes now belong to the chat (session key), so a later run on the same chat
sees the commands an earlier run started, and an exit continues the task that
is paused in the chat, whichever run paused it.

- Delete moveRunningSessionsToRun and run-keyed yield ownership; key
  listYieldAwaitableExecs and execYieldResumes by session key.
- Reply admission continues the paused task without matching a run id.
- Child completions go to the requester chat key; stop reading the captured
  requester incarnation (settle receipts, harness completion, collectors,
  agents_wait, PR workspace adoption). The requester id fields are still
  written for one release.
- Delete the reset replacement notice that withheld private completions.
- Exec wakes still name the starting run in inputProvenance.runId for plugins;
  it routes nothing.

Co-authored-by: obviyus <[email protected]>
@obviyus
obviyus force-pushed the obviyus/own-by-chat branch from c5581ea to d19eb40 Compare November 16, 2026 13:47
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the red jobs on d19eb4085abd (CI run 43879204855, both attempts) are not caused by this PR.

  • checks-node-changed-compact-small-3-1, checks-node-changed-compact-large-10-2, checks-node-changed-compact-small-19: src/agents/embedded-agent-runner/run.shared-integration.test.ts and run.prepared-harness-source-delivery.integration.test.ts fail with TypeError: undefined is not an object (evaluating '(readCapturedPreparedModelRuntimeCatalog(preparedModelRuntime) ?? preparedModelRuntime.modelCatalog).providerOutcomes'). CI tests the merge with main, which brings in fix(agents): explain when a listed model rejects a chat request #200073. The same failure reproduces on current main 60c112a1bfa9 without this PR (ocx test: 3 failed in run.shared-integration, 7 failed in run.prepared-harness-source-delivery). This PR's head does not contain fix(agents): explain when a listed model rejects a chat request #200073 and passes both files.
  • src/gateway/server-startup-post-attach.test.ts ("announces prepared readiness only before close"): fails the same way on the merge base 059db8a7c5aa and on main 60c112a1bfa9. This PR does not touch it.
  • checks-node-changed-compact-large-11, src/cron/isolated-agent/run.fallback-transcript.test.ts: the CI run returns outputText: "answered" with no provider request recorded. That is another file's fixture text (isolated-agent.session-model-strictness.integration.test.ts), so this is a cross-file leak in the shard. The exact 9-file shard set from the CI log passes on this head and on main under the Bun runtime (OPENCLAW_VITEST_RUNTIME=bun ocx test …: 143/143 on both). The test also passes on the head merged with main.

Exact-head proof: local ClawSweeper review is ready on d19eb4085abd. Real-model E2E journeys J1 to J3 (base vs head) are in the PR body.

@obviyus
obviyus merged commit 5d35af1 into main Nov 16, 2026
210 of 221 checks passed
@obviyus
obviyus deleted the obviyus/own-by-chat branch November 16, 2026 14:50
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 5d35af1.

obviyus added a commit that referenced this pull request Nov 16, 2026
@obviyus

obviyus commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up on the override: a probe PR (#200143) reverted this change on current main and touched the same cron files, so CI selected the same lane. CI run 43891181442 still fails src/cron/isolated-agent/run.fallback-transcript.test.ts ("continues one cron user turn when the primary times out after provider dispatch"), plus the same embedded-runner and post-attach failures. This PR did not cause these reds.

vincentkoc added a commit that referenced this pull request Nov 16, 2026
…tgres-compaction-watched-prompt-20261116

* commit '9e810f7101557b006d5ff223d955f14dc43329f0': (23 commits)
  chore(ui): refresh control ui locales (#200164)
  fix(update): stop reporting unset git config keys as failing checks (#200153)
  test: consolidate redundant coverage (198793, part 2) (#198936)
  revert: skills-used full-transcript scan on every chat history page (#200159)
  refactor(sessions): follow the chat by key for stored delivery references (#200099)
  fix(update): bridge 2026.11.5-beta.4 updaters (#200152)
  fix(gateway): avoid filesystem stalls during catalog refresh (#200136)
  fix(ci): match update refusal probe to selected candidate (#200043)
  fix(agents): keep read-only steering carriers when publishing suppressed user envelopes (#200156)
  test: consolidate suites while retaining recovery owners (#198933)
  test: consolidate redundant coverage (198789, part 2) (#198932)
  refactor(cli): consolidate camera command tests (#200144)
  fix(cli): avoid initializing provider runtime during cleanup (#200139)
  fix(ui): show mobile destinations without the drawer exit delay (#198879)
  chore(ui): refresh control ui locales (#200146)
  fix(knowledge): keep historical claims distinct and reject changed retries (#200140)
  fix(ui): align dropdown arrows on mobile New Session
  improve(sessions): archive inactive transcripts by default (#199899)
  refactor(agents): own background commands and yield waits by the chat (#200097)
  fix(models): guessed non-chat models leave the default picker instead of being refused (#200102)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…openclaw#200097)

## What Problem This Solves

Background commands, `sessions_yield` waits and exec-exit wakes were owned by the run that started them. A run id names one attempt, and a chat gets a new one on every turn. So every follow-up run lost the commands of the earlier runs:

- A later turn could not yield on a command that an earlier turn started. `listYieldAwaitableExecs(runId)` matched `originRunId === runId`, so `sessions_yield` returned `nothing_pending` and the model started to poll.
- A paused subagent task continued only when the wake named the paused run. openclaw#200046 patched one caller of this: it moved the running commands to the new run (`moveRunningSessionsToRun`).
- Child completions compared the captured requester session id and lifecycle revision. After a reset or a compaction successor, a private completion was withheld with "Subagent results from the previous session were not delivered".

## Why This Change Was Made

The bug class is "address work by an id that changes". The chat's session key is the only id that survives edits, resets, compaction and follow-up runs. This PR makes the key the owner:

- `listYieldAwaitableExecs`, `awaitExecsForYield` and `openExecYieldResume` are keyed by the chat: agent id plus session key, so a raw shared key such as `global` stays separate per agent. A yield awaits every wake-armed command of the chat, including commands from earlier runs.
- Reply admission continues the task that is paused in the chat, whichever run paused it (`continuesPausedTask` replaces `pausedRunId`).
- Child and harness completions, and the failure notice of a required completion, go to the requester chat as it is now. The reads of `completionRequesterSessionId` / `LifecycleRevision`, the settle-receipt exact compare, the collector and `agents_wait` incarnation filters, and the reset replacement notice are deleted.
- Deleted: `ProcessSession.originRunId`, `moveRunningSessionsToRun` (the openclaw#200046 patch), `matchesSubagentRequesterSession`, `recordRequesterReplacementNotice`, `listCollectorRunsForRequesterIncarnation` (now `listCollectorRunsForRequester`).
- Kept as a fact only: an exec wake still names the starting run in `inputProvenance.runId` (`ProcessSession.startedByRunId`), because plugins use it (openclaw#179816). It routes nothing.
- The requester id fields are still written for one release, so a downgrade keeps working. No schema, stored-row or protocol change.

Production delta: −227 lines in `src` (+127 / −354); whole PR −427.

## User Impact

- A chat can start a background command in one turn and wait for it with `sessions_yield` in a later turn. The exit continues the chat.
- A yielded subagent always continues its paused task when one of its commands exits, also after a follow-up run.
- A subagent result reaches the parent chat after `/new` or compaction instead of being withheld.

## Evidence

Real agent on an isolated source Gateway (`ocx src`, scratch state, port and HOME, scrubbed env), Claude Opus through the shared Claude proxy. base = merge base `2baaa3c275a3`, head = this PR.

| Journey | base | head |
|---|---|---|
| J1: openclaw#200046 incident (paused child, A's exit continues the task in run 2, then B, started by run 1, exits) | parent got `child-final` (with the openclaw#200046 patch) | parent got `child-final` (patch deleted); registry `generation=4 delivery=delivered` |
| J2: run 1 starts a background command; run 2 calls `sessions_yield` | `{"status":"nothing_pending"}` | `{"status":"yielded"}`; the exit wakes the chat, which replies `j2-woke` |
| J3: parent spawns a child and does not yield | ordinary completion (`subagent_announce`) | ordinary completion (`subagent_announce`) |
| J1 parent side: parent yields on its child | private completion (`subagent_settle`) | private completion (`subagent_settle`) |

Head arms ran on the production code of `3793f6d`; later commits change only tests, docs and the failure-notice path of a required completion, which unit tests cover.

A `/new` while the parent is yielded on a running child interrupts the child on both arms, so that journey does not separate them and is not a claim of this PR.

Unit: `openclaw-tools.requester-yield.test.ts` now awaits a command with no starting run (fails on base). The delivery tests assert that a private completion reaches a replacement parent session.

Gates: oxfmt, oxlint on changed files, `pnpm tsgo:core`, `pnpm check:test-types`, `ocx test` on `src/agents/subagents/`, requester-yield, exec background and notify suites, agents_wait, harness completion, session reactivation and adoption, `src/cron/isolated-agent`. Build, full suites and cross-OS checks: hosted CI on this head. `src/gateway/server-startup-post-attach.test.ts` fails the same way on the merge base `113d415`; this PR does not touch it.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 18, 2026
…pinner (#201157)

Related: #199079

## What Problem This Solves

When a hidden subagent finishes, fails, times out or is stopped, the servers and `nohup … &` processes it started keep running, with nothing left to manage them. Its parent's sidebar row keeps spinning, because the leftover processes still count on the dead child. Archiving a chat had the same gap. On 2026-11-18 a stopped worker left an isolated Gateway, a mock server and an HTTP server running until someone killed them by hand. The process-lifetime audit reproduced this on every subagent end path and on archive.

## User Impact

- A hidden subagent's `yieldMs` commands, `background: true` services and leftover processes (`cmd &`, `nohup`) stop when its task ends: it finishes, fails, times out or is stopped. A subagent waiting in `sessions_yield` keeps the command it waits on, and that command's exit still wakes it.
- Archiving a chat stops its processes, as reset and delete already do. If the stop cannot be confirmed, the archive fails with a retryable error and the chat stays unarchived.
- The parent row and the agent header stop spinning once the child's own run ends. A child's processes still show on its own row.
- **Behavior change:** to keep a service after a subagent ends, use `durable: true` or start it from the parent. Main chats, visible spawned sessions and the one-shot `agent --local` hand-off are unchanged.

## Why This Change Was Made

The chat stays the only owner of its processes (#199079, #200097), and `stopSessionExecProcesses` stays the only stop. Two chat ends never called it:
- **Subagent task end:** one subscriber on the registry's persistence publication derives "task ended" from the stored rows. All rows ended; none yielded, steer-restart or a visible session. It then stops the child's scope keys (key and session id, the same keys the row counts). Every end path writes its terminal row through that bus, so a new end path is covered automatically.
- **Archive:** calls the same stop after the lifecycle drain.
- **Sidebar:** one helper, `childShowsParentWorking`, replaces the two duplicated fold rules (session tree and team header). A child folds into its parent only while its run is visible, or while it is a yielded subagent waiting on its own command. No protocol change.
- **Text:** the `background` exec description and the background-process and subagent docs.

## Evidence

- **Contract table** (`subagent-task-end-processes.lifecycle.test.ts`, real processes: a service, a hand-off and a survivor per row). Complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5, the branch passes. The yielded child and the visible-session child keep their processes on both. About 20 s of test time.
- **Archive** (`server.sessions.archive-lifecycle.test.ts -t "archive stops the chat"`): both processes stop; an unconfirmed stop returns retryable `UNAVAILABLE` and does not archive. Base fails, the branch passes.
- **Sidebar** (`app-sidebar-session-tree.test.ts`): a `historical` child with processes does not spin its parent or the team header; `paused` and `active` children do. Base fails, the branch passes.
- tsgo core/ui/core-test, oxlint, format and `agent-tools.prefix-stability.test.ts`: green.

**Fault matrix rerun** (isolated Gateways, `env -i`, service marker set, scripted model; base `c8da4b7fbc40` → this branch). R2 = `yieldMs`, R3 = `background:true`, R4 = `nohup &`. L = alive and counted, C = clean.

| Cell | Base R2/R3/R4 | Head R2/R3/R4 |
|---|---|---|
| Subagent normal completion | L/L/L | **C/C/C** |
| Subagent model failure (400) | L/L/L | **C/C/C** |
| Subagent kill | C/L/L | **C/C/C** |
| Parent delete, child running | C/L/L | **C/C/C** |
| Parent delete, child completed | C/L/L | **C/C/C** |
| Archive | C/L/L | **C/C/C** |
| Subagent yielded on its hand-off | kept | kept (`paused`, count 1; exit resumes it) |
| Main chat: completion / abort / failure | L/L/L | unchanged by design |

A `setsid` double fork stays untracked on macOS, unchanged (follow-up).

**Real model** (`openai/gpt-6.2-sol`, this branch): a hidden subagent started a `background:true` HTTP server and a `nohup` process and was then killed. Both processes were gone afterwards, and the child row went from count 2 to no count.

**Control UI**, screenshot taken 12 s after the kill without a reload (base used the scripted model):

| Before (base) | After (this branch) |
| --- | --- |
| ![Base: parent row still spinning after the worker was killed](https://github.com/user-attachments/assets/70a79031-46d9-40ff-87f3-de7b98bcec88) | ![Branch: parent row shows a static dot after the worker was killed](https://github.com/user-attachments/assets/bf5fb28d-4485-4869-8593-8148fbdc3870) |
| ![Still spinning highlighted](https://github.com/user-attachments/assets/9501efca-61a2-42be-8d9d-7e5f11b7f7ff) | ![Stopped highlighted](https://github.com/user-attachments/assets/a6947c14-1553-4798-8bb8-82729f8966b2) |

## Merge danger and blast radius

- Two-way door: no stored rows, schema, config or protocol change; a revert fully restores the old lifetime.
- Hidden subagents that start services meant to outlive them now lose them at task end. Archive stops a chat's dev server.
- The stop touches only an ended hidden child's scope, and its `assertCurrent` re-derives the condition, so a resumed child is not stopped. An unconfirmed stop is logged and retried on the next publication for that child; a publication never throws.
- Cost: one map lookup per changed run per registry publication.
- Size: production +134/−18. The design estimated about +60 of logic; the rest is import formatting, the hoisted archive key list and the review fix that bounds the stop by the task's end time (a reset child key keeps its later processes). Tests: +376/−4.

## Left for later

PR 2: group kill for adopted survivors, the relay on macOS without the marker, a required `scopeKey` with a single factory and a teardown census, cron run sessions, `canStop: false` on killed children. PR 3: crash recovery for adopted survivors (needs approval) and Linux `cgroup.kill`.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…pinner (openclaw#201157)

Related: openclaw#199079

## What Problem This Solves

When a hidden subagent finishes, fails, times out or is stopped, the servers and `nohup … &` processes it started keep running, with nothing left to manage them. Its parent's sidebar row keeps spinning, because the leftover processes still count on the dead child. Archiving a chat had the same gap. On 2026-11-18 a stopped worker left an isolated Gateway, a mock server and an HTTP server running until someone killed them by hand. The process-lifetime audit reproduced this on every subagent end path and on archive.

## User Impact

- A hidden subagent's `yieldMs` commands, `background: true` services and leftover processes (`cmd &`, `nohup`) stop when its task ends: it finishes, fails, times out or is stopped. A subagent waiting in `sessions_yield` keeps the command it waits on, and that command's exit still wakes it.
- Archiving a chat stops its processes, as reset and delete already do. If the stop cannot be confirmed, the archive fails with a retryable error and the chat stays unarchived.
- The parent row and the agent header stop spinning once the child's own run ends. A child's processes still show on its own row.
- **Behavior change:** to keep a service after a subagent ends, use `durable: true` or start it from the parent. Main chats, visible spawned sessions and the one-shot `agent --local` hand-off are unchanged.

## Why This Change Was Made

The chat stays the only owner of its processes (openclaw#199079, openclaw#200097), and `stopSessionExecProcesses` stays the only stop. Two chat ends never called it:
- **Subagent task end:** one subscriber on the registry's persistence publication derives "task ended" from the stored rows. All rows ended; none yielded, steer-restart or a visible session. It then stops the child's scope keys (key and session id, the same keys the row counts). Every end path writes its terminal row through that bus, so a new end path is covered automatically.
- **Archive:** calls the same stop after the lifecycle drain.
- **Sidebar:** one helper, `childShowsParentWorking`, replaces the two duplicated fold rules (session tree and team header). A child folds into its parent only while its run is visible, or while it is a yielded subagent waiting on its own command. No protocol change.
- **Text:** the `background` exec description and the background-process and subagent docs.

## Evidence

- **Contract table** (`subagent-task-end-processes.lifecycle.test.ts`, real processes: a service, a hand-off and a survivor per row). Complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5, the branch passes. The yielded child and the visible-session child keep their processes on both. About 20 s of test time.
- **Archive** (`server.sessions.archive-lifecycle.test.ts -t "archive stops the chat"`): both processes stop; an unconfirmed stop returns retryable `UNAVAILABLE` and does not archive. Base fails, the branch passes.
- **Sidebar** (`app-sidebar-session-tree.test.ts`): a `historical` child with processes does not spin its parent or the team header; `paused` and `active` children do. Base fails, the branch passes.
- tsgo core/ui/core-test, oxlint, format and `agent-tools.prefix-stability.test.ts`: green.

**Fault matrix rerun** (isolated Gateways, `env -i`, service marker set, scripted model; base `70d9c782b6ca` → this branch). R2 = `yieldMs`, R3 = `background:true`, R4 = `nohup &`. L = alive and counted, C = clean.

| Cell | Base R2/R3/R4 | Head R2/R3/R4 |
|---|---|---|
| Subagent normal completion | L/L/L | **C/C/C** |
| Subagent model failure (400) | L/L/L | **C/C/C** |
| Subagent kill | C/L/L | **C/C/C** |
| Parent delete, child running | C/L/L | **C/C/C** |
| Parent delete, child completed | C/L/L | **C/C/C** |
| Archive | C/L/L | **C/C/C** |
| Subagent yielded on its hand-off | kept | kept (`paused`, count 1; exit resumes it) |
| Main chat: completion / abort / failure | L/L/L | unchanged by design |

A `setsid` double fork stays untracked on macOS, unchanged (follow-up).

**Real model** (`openai/gpt-6.2-sol`, this branch): a hidden subagent started a `background:true` HTTP server and a `nohup` process and was then killed. Both processes were gone afterwards, and the child row went from count 2 to no count.

**Control UI**, screenshot taken 12 s after the kill without a reload (base used the scripted model):

| Before (base) | After (this branch) |
| --- | --- |
| ![Base: parent row still spinning after the worker was killed](https://github.com/user-attachments/assets/70a79031-46d9-40ff-87f3-de7b98bcec88) | ![Branch: parent row shows a static dot after the worker was killed](https://github.com/user-attachments/assets/bf5fb28d-4485-4869-8593-8148fbdc3870) |
| ![Still spinning highlighted](https://github.com/user-attachments/assets/9501efca-61a2-42be-8d9d-7e5f11b7f7ff) | ![Stopped highlighted](https://github.com/user-attachments/assets/a6947c14-1553-4798-8bb8-82729f8966b2) |

## Merge danger and blast radius

- Two-way door: no stored rows, schema, config or protocol change; a revert fully restores the old lifetime.
- Hidden subagents that start services meant to outlive them now lose them at task end. Archive stops a chat's dev server.
- The stop touches only an ended hidden child's scope, and its `assertCurrent` re-derives the condition, so a resumed child is not stopped. An unconfirmed stop is logged and retried on the next publication for that child; a publication never throws.
- Cost: one map lookup per changed run per registry publication.
- Size: production +134/−18. The design estimated about +60 of logic; the rest is import formatting, the hoisted archive key list and the review fix that bounds the stop by the task's end time (a reset child key keeps its later processes). Tests: +376/−4.

## Left for later

PR 2: group kill for adopted survivors, the relay on macOS without the marker, a required `scopeKey` with a single factory and a teardown census, cron run sessions, `canStop: false` on killed children. PR 3: crash recovery for adopted survivors (needs approval) and Linux `cgroup.kill`.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…pinner (#201157)

Related: #199079

## What Problem This Solves

When a hidden subagent finishes, fails, times out or is stopped, the servers and `nohup … &` processes it started keep running, with nothing left to manage them. Its parent's sidebar row keeps spinning, because the leftover processes still count on the dead child. Archiving a chat had the same gap. On 2026-11-18 a stopped worker left an isolated Gateway, a mock server and an HTTP server running until someone killed them by hand. The process-lifetime audit reproduced this on every subagent end path and on archive.

## User Impact

- A hidden subagent's `yieldMs` commands, `background: true` services and leftover processes (`cmd &`, `nohup`) stop when its task ends: it finishes, fails, times out or is stopped. A subagent waiting in `sessions_yield` keeps the command it waits on, and that command's exit still wakes it.
- Archiving a chat stops its processes, as reset and delete already do. If the stop cannot be confirmed, the archive fails with a retryable error and the chat stays unarchived.
- The parent row and the agent header stop spinning once the child's own run ends. A child's processes still show on its own row.
- **Behavior change:** to keep a service after a subagent ends, use `durable: true` or start it from the parent. Main chats, visible spawned sessions and the one-shot `agent --local` hand-off are unchanged.

## Why This Change Was Made

The chat stays the only owner of its processes (#199079, #200097), and `stopSessionExecProcesses` stays the only stop. Two chat ends never called it:
- **Subagent task end:** one subscriber on the registry's persistence publication derives "task ended" from the stored rows. All rows ended; none yielded, steer-restart or a visible session. It then stops the child's scope keys (key and session id, the same keys the row counts). Every end path writes its terminal row through that bus, so a new end path is covered automatically.
- **Archive:** calls the same stop after the lifecycle drain.
- **Sidebar:** one helper, `childShowsParentWorking`, replaces the two duplicated fold rules (session tree and team header). A child folds into its parent only while its run is visible, or while it is a yielded subagent waiting on its own command. No protocol change.
- **Text:** the `background` exec description and the background-process and subagent docs.

## Evidence

- **Contract table** (`subagent-task-end-processes.lifecycle.test.ts`, real processes: a service, a hand-off and a survivor per row). Complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5, the branch passes. The yielded child and the visible-session child keep their processes on both. About 20 s of test time.
- **Archive** (`server.sessions.archive-lifecycle.test.ts -t "archive stops the chat"`): both processes stop; an unconfirmed stop returns retryable `UNAVAILABLE` and does not archive. Base fails, the branch passes.
- **Sidebar** (`app-sidebar-session-tree.test.ts`): a `historical` child with processes does not spin its parent or the team header; `paused` and `active` children do. Base fails, the branch passes.
- tsgo core/ui/core-test, oxlint, format and `agent-tools.prefix-stability.test.ts`: green.

**Fault matrix rerun** (isolated Gateways, `env -i`, service marker set, scripted model; base `c8da4b7fbc40` → this branch). R2 = `yieldMs`, R3 = `background:true`, R4 = `nohup &`. L = alive and counted, C = clean.

| Cell | Base R2/R3/R4 | Head R2/R3/R4 |
|---|---|---|
| Subagent normal completion | L/L/L | **C/C/C** |
| Subagent model failure (400) | L/L/L | **C/C/C** |
| Subagent kill | C/L/L | **C/C/C** |
| Parent delete, child running | C/L/L | **C/C/C** |
| Parent delete, child completed | C/L/L | **C/C/C** |
| Archive | C/L/L | **C/C/C** |
| Subagent yielded on its hand-off | kept | kept (`paused`, count 1; exit resumes it) |
| Main chat: completion / abort / failure | L/L/L | unchanged by design |

A `setsid` double fork stays untracked on macOS, unchanged (follow-up).

**Real model** (`openai/gpt-6.2-sol`, this branch): a hidden subagent started a `background:true` HTTP server and a `nohup` process and was then killed. Both processes were gone afterwards, and the child row went from count 2 to no count.

**Control UI**, screenshot taken 12 s after the kill without a reload (base used the scripted model):

| Before (base) | After (this branch) |
| --- | --- |
| ![Base: parent row still spinning after the worker was killed](https://github.com/user-attachments/assets/70a79031-46d9-40ff-87f3-de7b98bcec88) | ![Branch: parent row shows a static dot after the worker was killed](https://github.com/user-attachments/assets/bf5fb28d-4485-4869-8593-8148fbdc3870) |
| ![Still spinning highlighted](https://github.com/user-attachments/assets/9501efca-61a2-42be-8d9d-7e5f11b7f7ff) | ![Stopped highlighted](https://github.com/user-attachments/assets/a6947c14-1553-4798-8bb8-82729f8966b2) |

## Merge danger and blast radius

- Two-way door: no stored rows, schema, config or protocol change; a revert fully restores the old lifetime.
- Hidden subagents that start services meant to outlive them now lose them at task end. Archive stops a chat's dev server.
- The stop touches only an ended hidden child's scope, and its `assertCurrent` re-derives the condition, so a resumed child is not stopped. An unconfirmed stop is logged and retried on the next publication for that child; a publication never throws.
- Cost: one map lookup per changed run per registry publication.
- Size: production +134/−18. The design estimated about +60 of logic; the rest is import formatting, the hoisted archive key list and the review fix that bounds the stop by the task's end time (a reset child key keeps its later processes). Tests: +376/−4.

## Left for later

PR 2: group kill for adopted survivors, the relay on macOS without the marker, a required `scopeKey` with a single factory and a teardown census, cron run sessions, `canStop: false` on killed children. PR 3: crash recovery for adopted survivors (needs approval) and Linux `cgroup.kill`.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit cf21361)

Release adaptation: Preserve stable process capacity and receipt documentation. The acquired archive drain fences the captured process scope without adding turn-time authority rechecks.
Companion audit: #199079 and #200097 process owners are present. 8d21848 is archive fixture isolation only, 0a26c24 changes unrelated sidebar semantics, and later retained-work/worker changes are independent.

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant