Skip to content

feat(orchestration): coordinator-driven release of settled worker terminals (STA-905) - #12355

Merged
Jinwoo-H merged 4 commits into
mainfrom
brennan/sta-905-should-coordinator-created-orchestration-worker-terminals
Aug 4, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
brennan/sta-905-should-coordinator-created-orchestration-worker-terminals

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Coordinator-created orchestration worker terminals no longer accumulate after worker_done (STA-905). After processing each accepted report, the coordinator either reuses the exact worker terminal for a follow-up Dispatch (cleanup ownership transfers to the new Dispatch) or runs the new orca orchestration worker-release --dispatch <id>, which freezes an inspectable output archive first — the exact hook-reported provider transcript when available, otherwise a bounded, redacted terminal tail — and then closes only the exact coordinator-owned agent terminal. worker-retain records a durable user-requested debugging exception, and worker-list reports terminal accounting (active / reclaimable / retained / release_pending / release_unknown / released) separately from Task status.

Durable state is a new schema-v23 worker_terminal_resources record (ownership + release state machines keyed to pane key and process incarnation) with a conservative backfill: legacy rows become releasable only with unique, exact, same-operation creation evidence. External --terminal reuse, transferred ownership, user-taken-over terminals (real keystrokes now durably relinquish orchestration ownership on the terminal-owning runtime), and unprovable identities are always retained. Release is an idempotent mutation with durable retry receipts; a startup/reconnect reconciler finishes only previously requested releases and defers while terminal inventory is incomplete. Federated (connected-server) dispatches fail closed with a typed retained/federation_unsupported receipt. Worker outcome fields never change after release, and setup terminals, configured sibling tabs, and coordinator terminals are never touched.

Screenshots

No UI change (main-process, CLI, and skill-guide behavior). New user-facing CLI copy, verified live:

$ orca orchestration worker-release --dispatch ctx_15756805a09b --json
{ "state": "released", "processAction": "closed_agent_terminal",
  "archive": { "source": "transcript", "status": "captured" }, ... }

$ orca orchestration worker-list
ctx_1a54980c6580 task=task_17bb5b9a6dd4 [failed] terminal=retained
ctx_15756805a09b task=task_17bb5b9a6dd4 [succeeded] terminal=released
Terminals: retained=1 released=1

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

23 new RPC tests (orchestration-worker-release.test.ts) cover: succeeded/failed release with exact single close, duplicate-release idempotency, active-worker rejection without recorded intent, external/user-takeover/identity-changed retention, missing-terminal release_unknown plus retry-to-completion, capture-failure retaining the live PTY, exited-PTY explicit-empty archives, archived worker-read with source-pinned cursors and dcap redaction, exact-reuse ownership transfer with old-Dispatch fencing, reconciler recovery and defer-on-incomplete-inventory, backfill uniqueness, and a 50-worker resource regression (live terminals do not grow with settled passes; controls survive). Migration and guidance tests updated; CLI help/spec gates extended.

Full suite: 44,318 passed. 7 failures in 4 files are pre-existing on this base — each fails identically with this diff stashed (local node 26 vs the repo's node 24 pin).

Live QA on an isolated orca serve runtime with a real claude worker: coordinator received worker_done, worker-release returned released with a real provider-transcript archive, exactly one claude process exited, the worktree's setup/coordinator/externally-reused terminals all survived, worker-read served the archived transcript after the PTY was gone, duplicate release returned already_released, and worker-list separated Task outcome from terminal state.

AI Review Report

The implementation plan was fact-checked against the codebase by four parallel exploration agents before any code was written; every claimed behavior (worker_done settlement ordering, reused_agent_terminal labeling, mutation-receipt contract, close-path routing) was verified with file:line evidence, and the review's findings were folded into the implementation: workerRelease/workerRetain are registered in ORCHESTRATION_MUTATION_METHODS so replayed Deliveries dedupe; exited PTYs with zeroed tails produce explicit empty archives instead of silent success; user takeover is recorded durably on the runtime from the renderer's real-keystroke signal only (xterm auto-replies, programmatic prompt delivery, resize, and output are excluded); and release_unknown never falls back to a broad terminal close.

Cross-platform was explicitly checked for macOS, Linux, and Windows: no keyboard shortcuts or shortcut labels are involved; no filesystem paths are constructed by hand (transcript paths come from provider metadata; archives live in the orchestration SQLite DB, whose existing POSIX-vs-Windows-DACL hardening is unchanged); terminal close routes through the existing host-authoritative runtime.closeTerminal path, which covers native, WSL, and SSH-provider PTYs; SSH-disconnect close errors map to release_pending/release_unknown rather than a local guess; and folder workspaces need no Git metadata at any release step. Git-provider surfaces are untouched.

Security Audit

Reviewed input handling, IPC, and data exposure. The release/retain RPCs validate Dispatch state and exact process identity (pane key + incarnation) before any effect and only ever close the recorded handle — no path or command construction from user input. Archived terminal output passes the existing dispatch-capability redaction before persistence; the archive is stored in the permission-hardened orchestration DB, and provider transcript paths are never exposed through CLI receipts or worker-list (cursors are Dispatch-scoped and source-pinned, so a cursor cannot cross into another session). The new workerTerminalUserInput RPC is fail-safe by construction: any caller can only narrow automation (mark a resource user-owned), never trigger a close. Release mutations use the existing durable request ledger (payload-hash mismatch rejection, replay receipts). Known limitation stated in the guide/tests: redaction covers dispatch capability tokens only — the archive is not a general secret filter, matching the pre-existing live terminal-read behavior.

Notes

  • Ticket AC offered automatic close or an enabled-by-default retention policy; per discussion, this ships explicit coordinator-driven release (skill guide + guidance tests enforce the loop wording). If compliance still leaves PTY growth, the bounded default policy remains a separate follow-up.
  • Deliberate deferrals: federated worker-server release RPCs (currently typed retained/federation_unsupported, fail-closed); mobile/remote-viewing keystrokes do not count as takeover (they arrive via terminal.send, indistinguishable from programmatic sends); stopped/abandoned workers reject release (worker-stop already closed, or identity is uncertain) — abandoned-worker residual cleanup stays with STA-2911.
  • Existing settled rows are backfilled conservatively; the current production backlog of live worker PTYs is intentionally not auto-closed (STA-2650/STA-2911 territory).
  • The transcript-pin archive path is live-verified but has no unit fixture (needs a provider-format transcript fixture); terminal-tail archive paths are unit-covered.

…minals (STA-905)

After processing each accepted worker_done, coordinators now either reuse the
exact worker terminal (ownership transfers to the new Dispatch) or run
worker-release, which freezes an inspectable output archive (provider
transcript pin or bounded redacted terminal tail) before closing only the
exact coordinator-owned agent terminal. worker-retain records a durable
user-requested exception; worker-list reports terminal accounting separately
from Task status.

Schema v23 adds worker_terminal_resources ownership/release records with a
conservative backfill (owned only for unique exact creation evidence).
External, transferred, user-taken-over, and unproven identities are always
retained; releases are idempotent mutations with durable retry receipts, and
a startup/reconnect reconciler finishes only previously requested releases.
Real user keystrokes durably relinquish orchestration ownership on the
terminal-owning runtime. Federated dispatch release fails closed with a typed
retained receipt.
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added coordinator-controlled worker terminal release, retention, and reuse behavior. Added durable ownership and archive storage with schema version 23 migration and recovery reconciliation. Added RPC and CLI commands for release, retention, listing, archived reads, and user takeover reporting. Worker output remains readable through transcript pins or bounded redacted terminal archives after release. Updated orchestration guidance and tests to enforce settled-worker cleanup rules.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the coordinator-driven release of settled worker terminals.
Description check ✅ Passed The description follows the template, explains the change, testing, AI review, security audit, platform checks, and known limitations.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (4)
src/main/runtime/orchestration/db.ts (3)

5625-5635: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Prefer exact JSON membership over LIKE for prior owners.

LIKE treats _ as a single-character wildcard. Dispatch ids contain _ (for example ctx_...), so the pattern can match a non-identical id. Use json_each for exact membership.

♻️ Proposed change
   getWorkerTerminalResourceFormerlyOwnedBy(
     dispatchId: string
   ): WorkerTerminalResourceRow | undefined {
     return this.db
       .prepare(
         `SELECT * FROM worker_terminal_resources
-          WHERE prior_owner_dispatch_ids LIKE ?
+          WHERE EXISTS (
+            SELECT 1 FROM json_each(prior_owner_dispatch_ids) p WHERE p.value = ?
+          )
           ORDER BY updated_at DESC LIMIT 1`
       )
-      .get(`%"${dispatchId}"%`) as WorkerTerminalResourceRow | undefined
+      .get(dispatchId) as WorkerTerminalResourceRow | undefined
   }

5691-5712: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse WORKER_RELEASABLE_STATES for the releasable-state gate.

worker-terminal-ownership.ts exports WORKER_RELEASABLE_STATES with the same ['succeeded', 'failed'] set. Import it here so the release rule stays in one place.


5909-5943: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Replace the per-row resource lookup with a single join.

listWorkerTerminalResources runs one getWorkerTerminalResourceByOwner query for every worker dispatch row. For a Run with many dispatches this becomes an N+1 read on a command path. A LEFT JOIN worker_terminal_resources ON owner_dispatch_id = w.dispatch_id returns the same data in one statement. Select the resource columns with a distinct alias prefix so the row mapper can rebuild the WorkerTerminalResourceRow shape.

src/main/runtime/orchestration/worker-terminal-release-reconciliation.ts (1)

45-48: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Log the swallowed failure cause.

The catch block discards the error. A repeated archive or endpoint failure then shows only as a rising pending count, with no cause to diagnose. Log the resource id and the error, without transcript content.

♻️ Proposed change
-    } catch {
+    } catch (error) {
       // Archive or endpoint failure: durable intent stays requested; a later discovery retries.
+      console.warn(
+        '[orchestration] worker terminal release retry failed',
+        { resourceId: resource.id, dispatchId: resource.owner_dispatch_id },
+        error
+      )
       result.pending += 1
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2f35620b-5b8e-4b90-a34c-86e05a8cd528

📥 Commits

Reviewing files that changed from the base of the PR and between 7de40ff and 145f8fa.

📒 Files selected for processing (29)
  • config/scripts/orchestration-skill-guidance.test.mjs
  • skill-guides/orchestration.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/handler-group-manifest.ts
  • src/cli/handlers/orchestration.ts
  • src/cli/help.ts
  • src/cli/index.test.ts
  • src/cli/specs/orchestration-worker-specs.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/orchestration-db-retention-pagination.test.ts
  • src/main/runtime/orchestration/worker-output-archive.ts
  • src/main/runtime/orchestration/worker-terminal-ownership.ts
  • src/main/runtime/orchestration/worker-terminal-release-reconciliation.ts
  • src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-control.ts
  • src/main/runtime/rpc/methods/orchestration-worker-legacy-federated-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-methods.ts
  • src/main/runtime/rpc/methods/orchestration-worker-output.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.ts
  • src/main/runtime/rpc/methods/orchestration-worker-topology.ts
  • src/main/runtime/rpc/methods/orchestration-workers.ts
  • src/main/runtime/rpc/methods/orchestration.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/lib/worker-terminal-takeover-report.ts
  • src/shared/orchestration-rpc-contract.ts
  • src/shared/orchestration-worker-output.ts

Comment on lines +84 to +93
{
path: ['orchestration', 'worker-retain'],
summary: 'Keep one supervised worker terminal live for debugging',
usage:
'orca orchestration worker-retain --dispatch <dispatch_id> [--retry-request <id>] [--json]',
allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'],
notes: [
'Records a durable user-requested exception, so later release calls leave the terminal running.',
'Performs no process or filesystem action.'
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Add a retention-clear operation before documenting later release.

worker-retain makes later worker-release calls return retained, so a user cannot release the terminal after debugging. This leaves retained worker terminals live indefinitely.

  • src/cli/specs/orchestration-worker-specs.ts#L84-L93: add a command or flag that clears durable retention.
  • src/cli/handlers/orchestration.ts#L984-L992: route the retention-clear operation to a runtime mutation.
  • skill-guides/orchestration.md#L235-L235: document the actual command to release a retained terminal after debugging.
  • src/cli/bundled-skill-guides.ts#L33-L33: keep the bundled guide aligned with skill-guides/orchestration.md.
  • config/scripts/orchestration-skill-guidance.test.mjs#L238-L273: add coverage for retain, clear retention, and successful release.
📍 Affects 5 files
  • src/cli/specs/orchestration-worker-specs.ts#L84-L93 (this comment)
  • src/cli/handlers/orchestration.ts#L984-L992
  • skill-guides/orchestration.md#L235-L235
  • src/cli/bundled-skill-guides.ts#L33-L33
  • config/scripts/orchestration-skill-guidance.test.mjs#L238-L273

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/runtime/rpc/methods/orchestration-worker-release.test.ts (1)

451-453: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: assert the suffix with endsWith.

suffix is a local constant, so the ast-grep ReDoS hint is a false positive. A plain string check removes the linter noise and reads more directly.

♻️ Proposed simplification
     expect(read.terminal.tail).toHaveLength(1)
-    expect(read.terminal.tail[0]).toMatch(new RegExp(`${suffix}$`))
+    expect(read.terminal.tail[0].endsWith(suffix)).toBe(true)
     expect(read.terminal.truncated).toBe(true)

Source: Linters/SAST tools


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c47bc29a-26b0-41f5-b1cb-e4090a2fada8

📥 Commits

Reviewing files that changed from the base of the PR and between 145f8fa and 4aa66b6.

📒 Files selected for processing (17)
  • config/scripts/orchestration-skill-guidance.test.mjs
  • skill-guides/orchestration.md
  • src/cli/bundled-skill-guides.ts
  • src/cli/handlers/orchestration.ts
  • src/cli/specs/orchestration-worker-specs.ts
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/worker-output-archive.ts
  • src/main/runtime/orchestration/worker-terminal-ownership.ts
  • src/main/runtime/orchestration/worker-terminal-release-reconciliation.ts
  • src/main/runtime/orchestration/worker-transcript-read.test.ts
  • src/main/runtime/orchestration/worker-transcript-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.ts
  • src/renderer/src/lib/worker-terminal-takeover-report.test.ts
  • src/renderer/src/lib/worker-terminal-takeover-report.ts
🚧 Files skipped from review as they are similar to previous changes (10)
  • src/cli/specs/orchestration-worker-specs.ts
  • config/scripts/orchestration-skill-guidance.test.mjs
  • skill-guides/orchestration.md
  • src/main/runtime/rpc/methods/orchestration-worker-release.ts
  • src/cli/bundled-skill-guides.ts
  • src/main/runtime/orchestration/worker-output-archive.ts
  • src/main/runtime/orchestration/worker-terminal-ownership.ts
  • src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/orchestration/db.ts

Comment on lines +103 to +106
if (endOffset !== undefined && (await stat(filePath)).size < endOffset) {
return { ok: false, reason: 'source_changed', warnings: [] }
}
const page = await readNativeChatTranscriptTailFile(filePath, limit, decode, false, endOffset)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Revalidate the pinned boundary after the transcript read.

Both checks run before the file is opened and scanned. If the transcript truncates after this check, an archived read can return a successful partial result instead of source_changed. Revalidate that the source still reaches endOffset after the bounded read before returning success.

  • src/main/runtime/orchestration/worker-transcript-read.ts#L103-L106: revalidate the boundary after readNativeChatTranscriptTailFile completes.
  • src/main/runtime/orchestration/worker-transcript-read.ts#L124-L128: revalidate the boundary after the forward scan completes and map a shrink to source_changed.
📍 Affects 1 file
  • src/main/runtime/orchestration/worker-transcript-read.ts#L103-L106 (this comment)
  • src/main/runtime/orchestration/worker-transcript-read.ts#L124-L128

@brennanb2025

brennanb2025 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Electron QA passed on commit 4aa66b62e3.

  • Ran a real coordinator-supervised Codex worker to succeeded, then released dispatch ctx_ce70622834eb.
  • Visible result: archive transcript [captured], terminal=released, the worker tab closed, and Resource Manager returned from 2 terminal sessions to 1.
  • Backing-state verification: ownership/release state released, archive source/status transcript/captured, archived transcript remained readable, and only the coordinator terminal stayed live.

STA-905 Electron worker release evidence

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Provider orchestration validation passed with no confusion observed.

Provider Result Clarification Protocol Changes
Claude Opus 4.8 Passed None Exactly one correct worker_done None
Codex gpt-5.6-sol xhigh Passed None Exactly one correct worker_done None

Both providers independently:

  • Inspected the requested worker-release implementation.
  • Correctly identified coordinator-requested release, archive-before-close, and final dispatch-terminal-process identity revalidation.
  • Returned the exact required three-sentence response.
  • Recorded succeeded; both Tasks and Dispatches reached completed.
  • Sent no questions, escalations, duplicate completions, or extra actions.

Audit run: run_46c5101429c6. The two temporary validation terminals were closed afterward, and no files were modified.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts (1)

26-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared release test fixture.

This setup() body duplicates setup() in src/main/runtime/rpc/methods/orchestration-worker-release.test.ts lines 28-98 almost line for line. The two copies already differ: the release test also maps term_reminted in getTerminalPaneKey, getTerminalProcessIncarnation, and getOrchestrationDispatchAuthority. The copies will keep drifting as the runtime surface changes.

Move the fixture into a dedicated module, for example orchestration-worker-release-fixture.ts, and import it from both test files. Use a concrete domain name, not helpers, utils, or common.

As per coding guidelines: "Do not use vague names such as helpers, utils, common, misc, or shared-stuff for files, folders, or modules; use concrete domain names instead."

Source: Coding guidelines

src/main/runtime/orchestration/worker-output-archive.ts (1)

56-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Record why the provider transcript capture was skipped.

readWorkerTranscript(...).catch(() => null) discards the thrown error, and the !snapshot.ok case discards snapshot.reason. When a provider session exists but the transcript cannot be read, the archive falls back to the terminal tail with no record of the cause. The fallback warning at Line 103 is emitted only when the terminal tail is also empty, so a non-empty tail archive gives the reader no reason at all.

Carry the reason into the terminal-tail warnings so worker-read can explain the fallback.

♻️ Proposed change to preserve the fallback reason
   const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, args.attachedAtMs)
+  const transcriptWarnings: string[] = []
   if (session) {
     const snapshot = await readWorkerTranscript({
       agent: session.agent,
       sessionId: session.providerSession.id,
       transcriptPath: session.providerSession.transcriptPath,
       limit: MAX_WORKER_TRANSCRIPT_MESSAGE_LIMIT
-    }).catch(() => null)
+    }).catch((error) => {
+      transcriptWarnings.push(
+        `Provider transcript capture failed: ${error instanceof Error ? error.message : String(error)}.`
+      )
+      return null
+    })
     if (snapshot?.ok && snapshot.messages.length > 0) {

Then include transcriptWarnings in the terminal_tail warnings array, and push snapshot.reason when snapshot is present but not ok.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 62ab6663-3b96-47c2-883a-4e5abd449709

📥 Commits

Reviewing files that changed from the base of the PR and between 4aa66b6 and 06a16e2.

📒 Files selected for processing (9)
  • config/reliability-gates.jsonc
  • src/main/runtime/orchestration/db.ts
  • src/main/runtime/orchestration/worker-output-archive.ts
  • src/main/runtime/rpc/methods/orchestration-worker-archive-read.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts
  • src/main/runtime/rpc/methods/orchestration-worker-release.test.ts
  • src/main/runtime/rpc/orchestration-mutation-executor.ts
  • src/main/runtime/rpc/orchestration-mutation-ledger.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts
  • src/main/runtime/orchestration/db.ts

Comment on lines +52 to +57
const content = JSON.parse(archive.content) as
| WorkerTranscriptPinArchive
| WorkerTranscriptSnapshotArchive
return isTranscriptSnapshot(content)
? readFrozenTranscript(args, archive, content)
: readLegacyPinnedTranscript(args, content)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the archive JSON parse.

JSON.parse(archive.content) is unguarded. If a stored archive row is truncated or corrupt, this throws a raw SyntaxError instead of a typed OrchestrationError. The caller then receives a generic failure with no recovery guidance, on the exact path a user takes to inspect a released worker.

🐛 Proposed fix to return a typed error
-    const content = JSON.parse(archive.content) as
-      | WorkerTranscriptPinArchive
-      | WorkerTranscriptSnapshotArchive
+    let content: WorkerTranscriptPinArchive | WorkerTranscriptSnapshotArchive
+    try {
+      content = JSON.parse(archive.content)
+    } catch {
+      throw new OrchestrationError(
+        'archive_unavailable',
+        `The preserved output archive for Dispatch ${args.dispatchId} is unreadable.`
+      )
+    }
     return isTranscriptSnapshot(content)
       ? readFrozenTranscript(args, archive, content)
       : readLegacyPinnedTranscript(args, content)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const content = JSON.parse(archive.content) as
| WorkerTranscriptPinArchive
| WorkerTranscriptSnapshotArchive
return isTranscriptSnapshot(content)
? readFrozenTranscript(args, archive, content)
: readLegacyPinnedTranscript(args, content)
let content: WorkerTranscriptPinArchive | WorkerTranscriptSnapshotArchive
try {
content = JSON.parse(archive.content)
} catch {
throw new OrchestrationError(
'archive_unavailable',
`The preserved output archive for Dispatch ${args.dispatchId} is unreadable.`
)
}
return isTranscriptSnapshot(content)
? readFrozenTranscript(args, archive, content)
: readLegacyPinnedTranscript(args, content)

Comment on lines +177 to +184
const pendingClose = deferred<Awaited<ReturnType<OrcaRuntimeService['closeTerminal']>>>()
vi.mocked(runtime.closeTerminal).mockReturnValue(pendingClose.promise)

const first = reconcileRequestedWorkerTerminalReleases(runtime)
await vi.waitFor(() => expect(runtime.closeTerminal).toHaveBeenCalledTimes(1))
const second = reconcileRequestedWorkerTerminalReleases(runtime)
expect(second).toBe(first)
pendingClose.resolve({ handle: 'term_worker', tabId: 'tab-worker', ptyKilled: true })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Resolve the declared return type of OrcaRuntimeService.closeTerminal.
set -euo pipefail

rg -nP -C 6 '\bcloseTerminal\s*\(' --type=ts src/main/runtime/orca-runtime.ts
rg -nP -C 8 'RuntimeTerminalClose' --type=ts src/shared src/main

Repository: stablyai/orca

Length of output: 13335


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the test file around both mocked call sites and definitions of helper/types used.
sed -n '1,230p' src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts

# Check whether runtime.closeTerminal in this file is the Claude Agent Teams method or notifier.closeTerminal.
rag -n "closeTerminal|RuntimeTerminalClose|closed|ptyKilled|tabId|handle" src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts

Repository: stablyai/orca

Length of output: 9586


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
# Read-only check: compare the two mocked resolution shapes in the test to RuntimeTerminalClose.
from pathlib import Path
text = Path("src/main/runtime/rpc/methods/orchestration-worker-release-recovery.test.ts").read_text()

shapes = {
    "setup-closeTerminal": ("{ handle: 'term_worker', closed: true }", "closed")
}
for line in text.splitlines():
    line = line.strip()
    if "RuntimeTerminalClose" in line:
        print("found RuntimeTerminalClose literal:", line)
        shapes["literal"] = line
    if '.mockResolvedValue({ ' in line:
        parts = [a.strip() for a in line.splitlines()]
        print("mockResolvedValue start:", line)
PY

rg -n "RuntimeTerminalClose|closeTerminal\\(" src/shared/runtime-types.ts src/main/runtime/orca-runtime.ts src/main/runtime/claude-agent-teams-types.ts || true

Repository: stablyai/orca

Length of output: 1610


Fix the closeTerminal mock shape in setup().

OrcaRuntimeService.closeTerminal returns Promise<RuntimeTerminalClose>, and RuntimeTerminalClose is { handle, tabId, closeMode?, ptyKilled }, so the later fixture at line 184 is correct. The setup mock at line 81 should use the same { handle: 'term_worker', tabId: ..., ptyKilled: true } shape instead of { handle, closed: true }; the as never cast hides this type mismatch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants