Skip to content

fix(gateway): preserve terminal task run identity - #121192

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
Alix-007:alix/task-terminal-open-completion-race
Aug 13, 2026
Merged

vincentkoc merged 1 commit into
openclaw:mainfrom
Alix-007:alix/task-terminal-open-completion-race

Conversation

@Alix-007

@Alix-007 Alix-007 commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Related: #121070

What Problem This Solves

Fixes an issue where a terminal opened through the Gateway MCP loopback could survive its task's completion when another child session had a task with the same run ID.

Gateway tool resolution dropped the prepared run ID. Forwarding it exposed a second issue: terminal ownership used the registry's global preferred run-ID match, then discarded a mismatched child session without searching the correct scope.

Why This Change Was Made

The Gateway now forwards its existing prepared runId. Terminal ownership resolves the task through the canonical task-registry scope { runId, childSessionKey }, then records the exact private task ID used by lifecycle cleanup.

This is the complete owner-boundary repair. It adds no config, protocol, SDK, migration, persistence, identity, fallback, or cache surface. The detached-task runtime retains its existing global lookup because it has a different ownership contract.

This change was developed with AI assistance and rewritten by a maintainer after ClawSweeper found the cross-child collision.

User Impact

Completing one Gateway/loopback task now closes that task's PTY even when another child session reuses the same run ID. The sibling task's terminal remains live and writable.

Evidence

  • Red/green collision regression: before the rewrite, the terminal lookup received only shared-run; the new duplicate-run-ID test failed because the child session was absent. After the rewrite, both terminal and Gateway regressions pass and assert lookup by ("shared-run", childSessionKey).
  • Focused tests: 86 assertions passed across terminal-tool, Gateway resolver/exclusion, terminal session lifecycle, runtime subscriptions, task status access, and the two registry cross-scope collision cases.
  • Changed gate: Blacksmith Testbox tbx_01kzwqhv8vfftahjzk8tj8thq4, run https://github.com/openclaw/openclaw/actions/runs/31668517679, completed with exit 0. Core production/test typechecks, changed-file lint/format, import-cycle, dead-code, database-first, SDK, and repository guards passed.
  • Autoreview: .agents/skills/autoreview/scripts/autoreview --mode uncommitted --engine codex --model gpt-5.6-sol --thinking high --stream-engine-output reported no accepted/actionable findings; overall correctness 0.98.
  • Static: git diff --check passed.

Exact-head MCP-to-real-PTY collision proof

Exact commit: ae68f2d4e2f8b659af6c7754aa74eed1fced3246

The transient harness traversed real loopback HTTP /mcp -> bound shared-run grant -> production Gateway resolver -> production terminal tool -> real @lydell/node-pty -> production task-registry observer cleanup.

It deliberately created two tasks with the same run ID in different child sessions. Task 1 was the registry's global preferred match, so the pre-rewrite lookup would leave task 2's terminal unbound. On the rewritten head, terminalizing task 2 reduced live PTYs from two to one; task 1 stayed writable and emitted output after cleanup.

Harness SHA-256: fc8842e6788a2ee81a9f148f1eb218395927f2917ad05e46a2231fc14aad03d6

Verdict SHA-256: 49aafa97112e9d068de81f70fee9697342318ff8e56b9b3c761bebc8c74bc752

{
  "schemaVersion": 1,
  "verdict": "pass",
  "targetSha": "ae68f2d4e2f8b659af6c7754aa74eed1fced3246",
  "boundary": [
    "real-loopback-http-/mcp",
    "bound-runId-grant",
    "production-gateway-tool-resolver",
    "production-terminal-tool",
    "real-node-pty",
    "production-task-registry-observer-cleanup"
  ],
  "assertions": {
    "exactGrantPublishedOnlyTerminal": true,
    "duplicateRunIdAcrossChildSessions": true,
    "globalPreferredTaskBelongsToOtherChild": true,
    "distinctRealPtyProcesses": true,
    "completedTaskTerminalClosed": true,
    "siblingTerminalRemainedWritable": true,
    "siblingOutputObservedAfterCleanup": true
  },
  "observations": {
    "httpStatus": 200,
    "taskCount": 2,
    "ptyProcessCount": 2,
    "sessionCountBeforeCleanup": 2,
    "sessionCountAfterCleanup": 1,
    "capturedTerminalCalls": 7,
    "emittedTerminalEvents": 0
  },
  "redaction": {
    "bearerTokensIncluded": false,
    "filesystemPathsIncluded": false,
    "terminalOutputIncluded": false
  }
}

The earlier Linux public proof remains available at https://github.com/Alix-007/openclaw/actions/runs/31376607923 and establishes the same production MCP-to-PTY boundary on the contributor branch before the collision rewrite.

Dependency contract

Direct sibling Codex inspection on commit 414782450952a196bbb64b1605a458c2531c47b6:

  • codex-rs/core/src/session/mcp.rs:292-303 forwards server, tool, arguments, and request metadata into the MCP manager.
  • codex-rs/core/src/mcp_tool_call.rs:576-607 adds Codex thread/sandbox/trace metadata, but carries no OpenClaw task-row identity.
  • codex-rs/core/src/session/mod.rs:3267-3276 shows the same MCP call contract.

Therefore OpenClaw must preserve the prepared run ID at tool construction and resolve its own exact child-session task scope.

Scope

  • Production: +35/-8
  • Tests: +131/-7
  • Config/default surfaces: 0

The positive production delta is the canonical scoped status projection needed to enforce the task-ownership boundary. No changelog entry is included because contributor PRs leave changelog updates to the landing workflow.

Punchcard-Session: calm-workshop-cedar-hx

@clawsweeper

clawsweeper Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: S labels Aug 9, 2026
@Alix-007

Alix-007 commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 9, 2026
@clawsweeper

clawsweeper Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 13, 2026, 1:12 AM ET / 05:12 UTC.

ClawSweeper review

What this changes

The PR forwards Gateway loopback run identity into terminal creation and binds task-owned PTYs using both run ID and child session.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

Keep open. Current main does not contain the PR head, and the prior cross-child lookup blocker is resolved by carrying the prepared run ID and selecting the task within its child-session scope.

Priority: P1
Reviewed head: ae68f2d4e2f8b659af6c7754aa74eed1fced3246

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is a focused owner-boundary repair with direct collision coverage and strong exact-head runtime evidence.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides exact-head after-fix live output for an injected duplicate-run collision through loopback HTTP, production resolution, a real PTY, and task-observer cleanup.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides exact-head after-fix live output for an injected duplicate-run collision through loopback HTTP, production resolution, a real PTY, and task-observer cleanup.
Evidence reviewed 7 items Gateway-to-terminal identity propagation: The changed Gateway construction forwards the already prepared run ID into the general OpenClaw tool factory; that factory passes it to terminal creation.
Scoped ownership repair: The new status-access projection searches the registry by run ID and child session, then returns only the private task fields needed for terminal lifecycle binding.
Lifecycle owner: Gateway cleanup derives the exact terminal task ID only when a task first becomes terminal, then closes sessions bound to that task ID.
Findings None None.
Security None None.

How this fits together

Gateway MCP requests construct tools for an agent session, including terminals. The task registry later emits a terminal task transition, and Gateway cleanup closes the PTY recorded with that exact task ID.

flowchart LR
  A[Gateway MCP request] --> B[Prepared run identity]
  B --> C[Gateway tool resolution]
  C --> D[Terminal task lookup]
  D --> E[Child-session task scope]
  E --> F[PTY task binding]
  F --> G[Terminal task cleanup]
Loading

Before merge

  • Resolve merge risk (P1) - Production code grows by 27 net lines; the narrow scoped projection is warranted because folding it into the global lookup would either preserve ambiguous selection or broaden the general status-access contract.
Agent review details

Security

None.

PR surface

Source +27, Tests +124. Total +151 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 35 8 +27
Tests 2 131 7 +124
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 166 15 +151

Review metrics

Metric Value Why it matters
Production versus test delta production +35/-8 (net +27); tests +131/-7 (net +124) The production growth is the scoped task-status projection and Gateway propagation needed to bind cleanup to the correct task; the test growth covers both direct terminal and Gateway paths.

Root-cause cluster

Relationship: canonical
Canonical: #121192
Summary: This is the active canonical repair for the remaining duplicate-run-ID gap in task-owned terminal cleanup.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Merge the scoped ownership repair (recommended)
    Accept the small dedicated status projection after exact-head checks pass, since a global preferred run-ID lookup cannot safely bind a PTY when run IDs collide.

Technical review

Best possible solution:

Retain the narrow child-session projection and land it after exact-head quality checks are green; the global run-ID lookup must not regain terminal ownership responsibility.

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

Yes—source inspection reconstructs the collision: the former global run-ID lookup could select another child session and then discard it without finding the matching task. The PR body also supplies an exact-head after-fix collision trace.

Is this the best way to solve the issue?

Yes—the fix preserves the prepared Gateway fact and resolves ownership at the task-registry scope that owns child-session identity, rather than adding a terminal-side fallback or changing unrelated detached-task behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f8fcfe34b9f4.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides exact-head after-fix live output for an injected duplicate-run collision through loopback HTTP, production resolution, a real PTY, and task-observer cleanup.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A collision can leave a completed task's terminal process alive, affecting Gateway task completion behavior.
  • merge-risk: 🚨 availability: An incorrect ownership lookup would leave a PTY running after its task reaches a terminal state.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides exact-head after-fix live output for an injected duplicate-run collision through loopback HTTP, production resolution, a real PTY, and task-observer cleanup.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides exact-head after-fix live output for an injected duplicate-run collision through loopback HTTP, production resolution, a real PTY, and task-observer cleanup.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the merged task-terminal cleanup repair that established task-ID lifecycle closure. (role: introduced terminal task-cleanup behavior; confidence: high; commits: 01ca7548693d, 8dad2bf0ce3e; files: src/agents/tools/terminal-tool.ts, src/gateway/server-runtime-subscriptions.ts, src/gateway/terminal/session-manager.ts)
  • vincentkoc: Committed the current PR head and is assigned in the supplied PR timeline after the cross-child repair rewrite. (role: recent area reviewer and committer; confidence: high; commits: ae68f2d4e2f8; files: src/tasks/task-status-access.ts, src/agents/tools/terminal-tool.ts)
  • Masato Hoshino: Blame attributes the preexisting global terminal lookup and Gateway tool-construction lines to the current-base commit. (role: current-base contributor; confidence: medium; commits: 4c12c973edc5; files: src/agents/tools/terminal-tool.ts, src/gateway/tool-resolution.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Let the exact-head quality checks already in progress complete before landing.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-08-09T19:43:43.277Z sha bea5ea569c8e1cfa4cca52020b25977c6e17b21d :: needs real behavior proof before merge. :: [P1] Forward the run ID through Gateway tool resolution | [P1] Scope the run lookup before choosing its task
  • reviewed 2026-08-09T20:46:46.244Z sha bea5ea569c8e1cfa4cca52020b25977c6e17b21d :: needs real behavior proof before merge. :: [P1] Forward the run ID through Gateway tool resolution
  • reviewed 2026-08-10T04:49:06.122Z sha 3b7e72f5b3c35109d7128ca2697931ee4b4cbc0d :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-10T04:55:27.507Z sha 3b7e72f5b3c35109d7128ca2697931ee4b4cbc0d :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-10T10:56:09.999Z sha 3b7e72f5b3c35109d7128ca2697931ee4b4cbc0d :: needs maintainer review before merge. :: none
  • reviewed 2026-08-13T04:20:34.045Z sha 3e32755af9e6ad9eaff457476370d770382b50d1 :: needs changes before merge. :: [P1] Scope task lookup to the terminal's child session

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 9, 2026
@Alix-007
Alix-007 force-pushed the alix/task-terminal-open-completion-race branch from bea5ea5 to 105795f Compare August 10, 2026 03:15
@openclaw-barnacle openclaw-barnacle Bot removed the agents Agent runtime and tooling label Aug 10, 2026
@Alix-007 Alix-007 changed the title fix(gateway): close task terminals across lifecycle races fix(gateway): preserve terminal task run identity Aug 10, 2026
@Alix-007

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@Alix-007
Alix-007 force-pushed the alix/task-terminal-open-completion-race branch from 105795f to 3b7e72f Compare August 10, 2026 03:35
@Alix-007

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 10, 2026
@Alix-007

Copy link
Copy Markdown
Contributor Author

Maintainer proof request for exact head 3b7e72f5b3c35109d7128ca2697931ee4b4cbc0d:

All exact-head CI checks are green. A synthetic merge into current upstream main at 627e5bb06306cc5218e7e64247626456e8767881 is clean (result tree 8d0c16e7f0a5f1462b3b4bdd07e948647b854d90), so the remaining gate is only changed-boundary runtime proof. The contributor-dispatchable exact-head workflow has no Gateway terminal proof kind, and current Mantis scenarios do not cover MCP terminal ownership.

Please run one maintainer Testbox/Crabbox harness through the real chain: /mcp HTTP -> request-bound runId grant -> Gateway resolver -> createOpenClawTools -> createTerminalTool -> real node-pty -> task observer/cleanup. Use two tasks sharing one child session but carrying distinct run-1/run-2 identities, open their terminals through MCP, complete task 2, and capture a redacted exact-head trace showing task 2's terminal closes while the sibling remains live and writable. Please upload an inspectable artifact and link it in the PR body so the proof gate can refresh automatically.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 10, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants