Skip to content

fix: stop a finished subagent's leftover processes and its parent's spinner - #201157

Merged
obviyus merged 11 commits into
mainfrom
openclaw/amber-shell-2
Nov 18, 2026
Merged

obviyus merged 11 commits into
mainfrom
openclaw/amber-shell-2

Conversation

@obviyus

@obviyus obviyus commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

Step 0, ps excerpts and the real-model output: see the evidence comment below.

  • 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 Branch: parent row shows a static dot after the worker was killed
Still spinning highlighted Stopped highlighted

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 +105/−17. The logic is about +60, as the design estimated; the rest is import formatting and the hoisted archive key list. Tests: about +330 lines.

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.

obviyus and others added 5 commits November 18, 2026 14:58
A hidden subagent whose task ended and an archived chat no longer
hold background services or leftover processes.

Co-authored-by: obviyus <[email protected]>
…pinner

OpenClaw-Publication: 24ad1b6a-89a6-80ca-a39b-fdb63e069304
@clawsweeper

clawsweeper Bot commented Nov 18, 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.

@obviyus

obviyus commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator Author

Detailed evidence

Step 0: source facts the fix relies on (verified on origin/main c8da4b7)
  1. Both terminal writers publish on the persistence phase: completeSubagentRunAttempt and markSubagentRunTerminated (publishTermination) both commit through mutateSubagentRuns → publishRows → publishSubagentRunsAfterAtomicStore → publishSubagentRunChanges(keys, runIds, "persistence"). The restore path publishes without run ids, so it does not trigger stops (crash recovery stays out of scope).
  2. A subagent's exec scope key is its child session key: resolveProcessToolScopeKey({ scopeKey: options.exec?.scopeKey, sessionKey: runSessionKey ?? sessionKey, … }), and no production path sets exec.scopeKey (ExecToolRoutingDefaults has no such field).
  3. subagentRunState is paused for a yielded child (isSubagentRunPausedForContinuation) and historical once it ended (session-utils-display.ts). The real-model run below observed active → null after the kill, and the matrix observed paused while yielded and historical after completion and failure.

Evidence

Contract tests (real child processes, red on base, green on this branch).

  • src/agents/subagents/registry/subagent-task-end-processes.lifecycle.test.ts: one row per end cause. Each child runs a background: true service, a yieldMs hand-off and a cmd & survivor. The rows are complete, error, timeout, killed, and parent reset of a yielded child: base fails all 5 (pids alive), the branch passes all 5 (pids dead, nothing live in the child scope). Two rows must keep their processes: a yielded child, and a visible spawnMode: "session" child. Both keep them on base and on the branch. Wall time: about 20 s of tests (78 s with startup) at --maxWorkers=1.
  • src/gateway/server.sessions.archive-lifecycle.test.ts (-t "archive stops the chat"): archive stops a service and a survivor. When the stop is not confirmed, the archive returns retryable UNAVAILABLE and the chat stays unarchived. Base fails both; the branch passes both (about 15 s).
  • ui/src/components/app-sidebar-session-tree.test.ts: a historical child with leftover processes does not spin its parent; paused and active children do. The same three cases cover the team header (summarizeTeamSessionSlots). Two existing cases encoded the old rule and now use a paused worker, or expect only the hidden worker to fold. Base fails 3 cases; the branch passes all of them.
  • tsgo:core, tsgo:ui, tsgo:core:test, oxlint and format on the changed files, plus agent-tools.prefix-stability.test.ts (the tool description changed): all green.

Phase-1 fault matrix, rerun on isolated Gateways (env -i, scratch HOME/state/config, random ports, OPENCLAW_SERVICE_MARKER set so survivors are adopted as on the managed macOS Gateway, scripted model). Base is a build of c8da4b7fbc40; head is this branch. R2 = yieldMs hand-off, R3 = background: true, R4 = nohup … &, R6 = double fork with setsid. L = alive and counted, C = clean, U = alive and untracked.

Cell Base R2 / R3 / R4 Head R2 / R3 / R4 Head child row
Subagent normal completion L / L / L (count 3) C / C / C done, historical, no count
Subagent model failure (400) L / L / L (count 3) C / C / C failed, historical, no count
Subagent kill (sessions.abort(child)) C / L / L (count 2) C / C / C killed, no count
Parent delete, child running C / L / L (count 2) C / C / C killed, no count
Parent delete, child completed C / L / L (count 2) C / C / C (already clean at task end) done, no count
Archive after completion C / L / L (archived, count 2) C / C / C archived, no count
Subagent yielded on its hand-off R2 alive, count 1 R2 alive, count 1, paused; its exit resumes the child unchanged (kept)
Main chat: completion / chat.abort / model failure L / L / L (count 3 / 2 / 3) L / L / L, unchanged by design unchanged
R6 setsid double fork, every cell U U (unchanged; Linux cgroup.kill is a follow-up)
ps excerpts (subagent kill cell)
### base cell=s3 (after sessions.abort(child) [subagent kill])
99151 99149 99144  00:17 perl -e sleep 1800 LA_s3c_R3_bgservice
99154     1 99145  00:17 perl -e sleep 1800 LA_s3c_R4_adopted
99158     1 99157  00:17 perl -MPOSIX … LA_s3c_R6_setsid
{"key": "agent:main:subagent:8b6d…", "status": "killed", "backgroundProcessCount": 2}

### head cell=s3 (after sessions.abort(child) [subagent kill])
20832     1 20831  00:23 perl -MPOSIX … LA_s3c_R6_setsid
{"key": "agent:main:subagent:32c5…", "status": "killed", "backgroundProcessCount": null}

### head cell=e9 (archive)
before: R2, R3, R4 alive, {"backgroundProcessCount": 3, "archived": false}
after:  only R6 alive,   {"archived": true, "backgroundProcessCount": null}
Real-model journey output

Real-model journey (openai/gpt-6.2-sol, embedded runtime, isolated Gateway on this branch). The parent spawned a hidden subagent through sessions_spawn. The subagent started a background: true Node HTTP server, a nohup perl … & process and a foreground command, and was then stopped with sessions.abort(child).

before kill
49189 49185 49166 00:13 node -e require('http').createServer(…).listen(0,'127.0.0.1') LA_rm_R3_server
49609     1 49560 00:10 perl -e sleep 1800 LA_rm_R4_adopted
50472 50471 50446 00:05 perl -e sleep 1800 LA_rm_R1_fg
{"key": "agent:main:explicit:la-rm", "status": "done", "backgroundProcessCount": null}                     <- parent
{"key": "agent:main:subagent:000c…", "status": "running", "backgroundProcessCount": 2, "subagentRunState": "active"}

after kill (14 s later)
(no LA_rm process)
{"key": "agent:main:explicit:la-rm", "status": "done", "backgroundProcessCount": null}                     <- parent
{"key": "agent:main:subagent:000c…", "status": "killed", "backgroundProcessCount": null}

On base the same journey (phase 1 audit) left the service and the survivor alive, with the killed child at count 2.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 18, 2026
obviyus and others added 3 commits November 18, 2026 17:07
…eanup

A retained terminal row can outlive a reset of its child session. Bound the
task-end stop by the task's recorded end so a later publication of the old
row never stops processes the replacement session started afterwards.

Co-authored-by: obviyus <[email protected]>
OpenClaw-Publication: ab2d2636-afec-8781-9afd-535090138b4d
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR stops ordinary processes when hidden subagents end or chats are archived, and changes how child activity animates parent rows.

Example: A hidden subagent starts an HTTP server and a nohup process, then is killed.

  • Before: Both processes remain alive and the parent keeps showing activity.
  • After: Both tracked processes stop, the child's process count clears, and the parent stops spinning.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Strong production-path proof supports the central repair, but a source-visible UI regression and attributed exact-head test failures block merge.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied isolated-Gateway traces exercise terminal cleanup, archive, yielded-child preservation, and a real-model subagent kill; inspected before/after screenshots show the parent indicator clearing without reload.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Finished hidden workers leave services running and keep their parents looking busy; archiving also leaves processes behind.
Reason: The reported incident and Gateway proof establish user value, and maintainer authorship supplies direction for the documented lifetime change.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep open: this PR addresses a demonstrated cleanup failure, but it also hides persistent children's background activity from collapsed sections and leaves existing cancellation tests failing.

Priority: P2
Reviewed head: 2429fd0af17d6a05567b369b60953679c016a5f7

Before merge

  • Preserve background activity in persistent-child aggregates (P2) - For an idle persistent child with backgroundProcessCount=1 and no subagentRunState, childShowsParentWorking returns false. Applying it to the full tree summary changes the parent's runningChildCount from 1 to 0. If that parent is inside a collapsed Coding section and has no own active work, app-sidebar-session-section-render.tsx uses rowDemandsVisibility on the parent and removes the section's running indicator while the child's service is still alive. Preserve persistent-child background counts in the full aggregate and restrict the ended-child exclusion to hidden subagents; subagentSummary already separates the parent's leading-ring presentation.
  • Update the existing cancellation tests for task-end service cleanup (P2) - The new persistence subscriber stops a killed child's non-durable service, but subagent-control.commands.test.ts still calls expectServiceSurvives(service) at line 608 in all four parent-cancellation cases. Exact-head CI reports four failures at that assertion: https://github.com/openclaw/openclaw/actions/runs/44296536095/job/134775793378. Update those cases to await and assert terminal service cleanup while retaining their cancellation-ordering and cleanup-error assertions, and audit the suite's other service-survival expectations against the new lifetime.

Findings

  • [P2] Preserve background activity in persistent-child aggregates — ui/src/components/app-sidebar-session-tree.ts:48-49
  • [P2] Update the existing cancellation tests for task-end service cleanup — src/agents/subagents/registry/subagent-registry.ts:630
Agent review details

How this fits together

The subagent registry publishes terminal run facts, the existing exec owner stops matching processes, and the Control UI derives session and ancestor activity from Gateway rows.

flowchart TD
  A[Subagent terminal publication] --> C[Existing exec cleanup owner]
  B[Chat archive request] --> C
  C --> D[Scoped process registry]
  D --> E[Gateway session rows]
  E --> F[Sidebar activity summaries]
Loading

Technical review

Best possible solution:

Keep cleanup in the existing exec owner, preserve persistent-child background aggregates, and update the cancellation suite to the accepted service lifetime.

Do we have a high-confidence way to reproduce the issue?

Current-main source lacks both cleanup calls, and the supplied isolated-Gateway process traces demonstrate surviving services before the fix; no target code was executed during this review.

Is this the best way to solve the issue?

Reusing terminal publications and stopSessionExecProcesses is a focused repair, but the activity predicate must preserve ordinary children's background aggregates.

Full review comments:

  • [P2] Preserve background activity in persistent-child aggregates — ui/src/components/app-sidebar-session-tree.ts:48-49
    For an idle persistent child with backgroundProcessCount=1 and no subagentRunState, childShowsParentWorking returns false. Applying it to the full tree summary changes the parent's runningChildCount from 1 to 0. If that parent is inside a collapsed Coding section and has no own active work, app-sidebar-session-section-render.tsx uses rowDemandsVisibility on the parent and removes the section's running indicator while the child's service is still alive. Preserve persistent-child background counts in the full aggregate and restrict the ended-child exclusion to hidden subagents; subagentSummary already separates the parent's leading-ring presentation.
    Confidence: 0.97
  • [P2] Update the existing cancellation tests for task-end service cleanup — src/agents/subagents/registry/subagent-registry.ts:630
    The new persistence subscriber stops a killed child's non-durable service, but subagent-control.commands.test.ts still calls expectServiceSurvives(service) at line 608 in all four parent-cancellation cases. Exact-head CI reports four failures at that assertion: https://github.com/openclaw/openclaw/actions/runs/44296536095/job/134775793378. Update those cases to await and assert terminal service cleanup while retaining their cancellation-ordering and cleanup-error assertions, and audit the suite's other service-survival expectations against the new lifetime.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2f5bb506ef61.

Provenance checked

  • Process lifetime and chat ownership changes intended behavior with a stated reason (237111e: Keep deliberately detached processes alive, tracked, and manageable rather than killing them when their creating command finishes.)
  • Archive lifecycle keeps the original intent (b4104e2: Make archive own stopping and draining active session work before committing archive metadata.)
  • Background activity summaries changes intended behavior with a stated reason (0185de8: Expose background work on its owning row and retain activity in collapsed sections and child aggregates.)
  • Retained terminal subagent history keeps the original intent (5e113ea: Avoid re-killing inert historical children during reset while retaining cleanup for actual unfinished work.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/agents/subagents/registry/subagent-control.commands.test.ts src/agents/subagents/registry/subagent-task-end-processes.lifecycle.test.ts --maxWorkers=1
  • pnpm test src/gateway/server.sessions.archive-lifecycle.test.ts --maxWorkers=1
  • pnpm --dir ui test --run src/components/app-sidebar-session-tree.test.ts
  • pnpm --dir ui test --run src/e2e/sidebar-background-work.e2e.test.ts
  • git diff --check

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 237111e adds src/agents/bash-process-control.ts:190 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 237111eabf61; files: src/agents/bash-process-control.ts)
  • Peter Steinberger: Raw commit 0185de8 adds ui/src/components/app-sidebar-session-tree.ts:47 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0185de8e8f0c; files: ui/src/components/app-sidebar-session-tree.ts)

PR surface

Source +116, Tests +370, Docs +7. Total +493 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 9 134 18 +116
Tests 3 372 2 +370
Docs 2 11 4 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 517 24 +493

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: The demonstrated failure leaves tracked services running after hidden task completion or archive, with a limited lifecycle and UI blast radius.
  • add merge-risk: 🚨 compatibility: Hidden subagents' non-durable services now stop at task end, and archive stops chat services; the maintainer-authored PR explicitly accepts this behavior change.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The demonstrated failure leaves tracked services running after hidden task completion or archive, with a limited lifecycle and UI blast radius.
  • merge-risk: 🚨 compatibility: Hidden subagents' non-durable services now stop at task end, and archive stops chat services; the maintainer-authored PR explicitly accepts this behavior change.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 18, 2026, 6:56 AM ET / 11:56 UTC.

The Stop result still reports only request-owned commands; the service it
leaves now stops when the hidden child's task ends.

Co-authored-by: obviyus <[email protected]>
obviyus and others added 2 commits November 18, 2026 17:28
OpenClaw-Publication: 864eec57-c154-898d-b099-29ea080a7e53
@obviyus
obviyus merged commit cf21361 into main Nov 18, 2026
119 checks passed
@obviyus
obviyus deleted the openclaw/amber-shell-2 branch November 18, 2026 12:15
@obviyus

obviyus commented Nov 18, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in cf21361.

  • Bug: a hidden subagent that finished, failed or was stopped left its background: true services and nohup & processes running, counted on the dead child, so the parent kept spinning. Archive had the same gap.
  • Fix: a hidden child's task end, derived from its stored registry rows, stops its processes (bounded by the task's end time); archive calls the same stop. The sidebar folds a child into its parent only while its run is visible or it is yielded on its own command.
  • Proof: a contract table over every end cause (red on base, green here), archive and sidebar tests, the fault matrix rerun on isolated Gateways, a real gpt-6.2-sol kill journey, and the Control UI before/after above. The local review was clean and CI green on 8f5afff1.

Follow-ups (PR 2 and 3) are listed under "Left for later" in the body.

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 app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant