Repository navigation
feat(orchestration): orchestrate native-born structured chat sessions - #18827
Conversation
There was a problem hiding this comment.
ℹ️ Minor suggestions only — the orchestration change itself is thorough and well-pinned by tests; two defer-able cleanups/observations below.
Reviewed changes
- Structured worker identity registry (
structured-worker-identity.ts+structured-worker-authority.ts) — a second authority source mapping a session id to a bearer handle, a random persisted pane key, and a host scope, consulted by the four runtime getters before they give up onptysById. - Structured delivery lane (
structured-mailbox-pointer-delivery.ts,structured-session-pointer-delivery.ts,structured-pointer-operation-id.ts) — sibling to the PTY pointer path with the same eligibility rules, but the nudge travels as a session turn and mail is consumed only on anaccepteddispatch. - Worker lifecycle (
orchestration-structured-worker-*.ts,orchestration-local-worker-start.ts) — start with a resume-capable hold, preamble-as-turn, stop/abandon/release settlement, journal archive round-trip, and the observation vocabularylive/unverifiable/exited. - Schema v30→v31 —
structured_pointer_operationstable,worker_terminal_archivesrebuilt to admitstructured_journal, migration file renamed tomigrate-v13-latest.ts. - Renderer cleanup — the "Orchestration paused" notice and its
orchestrationDispatchStatusprop are removed, since the notice gated only ondispatchStatusand rendered over live bridge chat.
ℹ️ Orphaned renderer subscription left behind
Removing NativeChatOrchestrationPausedNotice and the orchestrationDispatchStatus prop also removed the last consumer of chatPaneDispatchStatus, but the selector and its plumbing were left in place. The value is still subscribed (use-terminal-pane-chat-state.ts:59), threaded through use-terminal-pane-projection.ts into TerminalPaneProjectionController, and read by nothing. It's a redundant reactive subscription to agentStatusByPaneKey[...].orchestration.dispatchStatus that should be deleted with the notice.
Technical details
# Remove orphaned chatPaneDispatchStatus
## Affected sites
- `src/renderer/src/components/terminal-pane/use-terminal-pane-chat-state.ts:59` — the `useAppStore` selector that computes the value.
- `src/renderer/src/components/terminal-pane/use-terminal-pane-chat-state.ts:283` — returns it in the projection.
- `src/renderer/src/components/terminal-pane/use-terminal-pane-projection.ts:28` and `:217` — destructures and re-exposes it on `TerminalPaneProjectionController`.
## Required outcome
- Delete the selector and its plumbing so the dead subscription and the `TerminalPaneProjectionController` field no longer exist.ℹ️ Restart leaves a surviving structured worker without its hold and redrive
The release path documents (and deliberately defers) that a restarted runtime is not rebound to a structured worker's hold or redrive subscription. A worker that survives a restart therefore keeps no resume-capable hold — its provider child is evictable by the 15s release clock, which is the exact idle-parked-worker kill the hold exists to prevent — and parked mail waits for the next arrival rather than a turn-settle edge. No mail is lost (the DB stays the source of truth and unknown retains), so this degrades rather than corrupts, but it's worth tracking as an explicit follow-up issue so the gap isn't forgotten.
Technical details
# Rebind restarted structured workers
## Affected sites
- `src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts` — the comment that names the gap ("NOT yet handled, and deliberately follow-up: rebinding a restarted runtime to a structured worker's hold and redrive subscription").
## Required outcome
- On startup recovery, re-establish the `orchestration:dispatch:<id>` hold and the `orchestration:redrive:<sessionId>` subscription for any structured worker that still owns a live session.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughThe PR adds native structured worker startup for local Claude and Codex sessions. It introduces structured worker identities, authority checks, child environment variables, lifecycle operations, journal reads, archives, and mailbox pointer delivery. Worker RPCs now support structured worker start, stop, abandon, observation, release, and output reads. The orchestration database adds structured pointer operations and structured journal archives. Terminal resolution can require an unambiguous result. The native chat paused notice and its localization are removed. Merge Risk: 🟡 Moderate · up to Structured workers add session-based orchestration, delivery, persistence, and lifecycle behavior. Known issues can strand worker mail after restart or rejection, affect existing database upgrades, mislabel archived output, and leave UI tab state inconsistent; these should be resolved before merge. 🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
Full details: Description checkExplanation The description provides extensive technical context, rationale, behavior changes, security details, and testing results, but it does not follow the required template completely. The mandatory Linked Issue section has no issue reference, and required sections such as ELI5, Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist are missing or not completed in the specified format. Resolution Add the required template sections and complete them. Include a valid issue reference after ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 234009d4-2f41-46e4-b4ed-b45c9009a705
📒 Files selected for processing (74)
src/cli/handlers/orchestration/terminal-identity.tssrc/cli/handlers/orchestration/worker-launch-handler.tssrc/cli/selectors.tssrc/cli/specs/orchestration-worker-specs.tssrc/main/claude/claude-structured-launch-resolution.tssrc/main/codex/codex-structured-child-environment.test.tssrc/main/codex/codex-structured-child-environment.tssrc/main/codex/codex-structured-session-acquire.tssrc/main/runtime/orca-runtime-adopt-terminal-orphans-from-inventory.tssrc/main/runtime/orca-runtime-get-orchestration-dispatch-authority.tssrc/main/runtime/orca-runtime-get-pty-record-for-pane-key.tssrc/main/runtime/orca-runtime-get-terminal-interactive-wait.tssrc/main/runtime/orca-runtime-stop-requested-pty-ids.tssrc/main/runtime/orca-runtime-subscribe-to-terminal-resize.tssrc/main/runtime/orca-runtime-write-orchestration-pointer-pty.tssrc/main/runtime/orchestration/adopted-structured-pointer-delivery.test.tssrc/main/runtime/orchestration/db/attach-orchestration-db-methods.tssrc/main/runtime/orchestration/db/contract-constants.tssrc/main/runtime/orchestration/db/dispatch-row-writer-boundary.test.tssrc/main/runtime/orchestration/db/messages/structured-pointer-operation-store.tssrc/main/runtime/orchestration/db/orchestration-db-methods.tssrc/main/runtime/orchestration/db/schema/create-core-tables-sql.tssrc/main/runtime/orchestration/db/schema/migrate-v13-latest.tssrc/main/runtime/orchestration/db/schema/migrate.tssrc/main/runtime/orchestration/db/schema/structured-pointer-schema-migration.test.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.tssrc/main/runtime/orchestration/mailbox-delivery-target.tssrc/main/runtime/orchestration/mailbox-notification-coordinator.tssrc/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.tssrc/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.tssrc/main/runtime/orchestration/structured-mailbox-pointer-delivery.tssrc/main/runtime/orchestration/structured-mailbox-pointer-host.tssrc/main/runtime/orchestration/structured-pointer-operation-id.test.tssrc/main/runtime/orchestration/structured-pointer-operation-id.tssrc/main/runtime/orchestration/structured-session-pointer-delivery.test.tssrc/main/runtime/orchestration/structured-session-pointer-delivery.tssrc/main/runtime/orchestration/structured-worker-journal-archive.tssrc/main/runtime/orchestration/worker-output-archive.tssrc/main/runtime/orchestration/worker-terminal-ownership.tssrc/main/runtime/rpc/methods/orchestration-local-worker-start.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-abandon.test.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.test.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-session.test.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-session.tssrc/main/runtime/rpc/methods/orchestration-worker-archive-read.tssrc/main/runtime/rpc/methods/orchestration-worker-control.tssrc/main/runtime/rpc/methods/orchestration-worker-legacy-federated-read.tssrc/main/runtime/rpc/methods/orchestration-worker-observation.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-release-receipts.tssrc/main/runtime/rpc/methods/orchestration-worker-start-schema.tssrc/main/runtime/rpc/methods/orchestration-worker-stop.tssrc/main/runtime/rpc/methods/orchestration-worker-topology.tssrc/main/runtime/rpc/methods/orchestration-workers.tssrc/main/runtime/rpc/methods/structured-agent-session-create.tssrc/main/runtime/rpc/methods/structured-agent-session.tssrc/main/runtime/rpc/methods/terminal/terminal-query-methods.tssrc/main/runtime/rpc/methods/terminal/unary-schemas.tssrc/main/runtime/structured-worker-authority.tssrc/main/runtime/structured-worker-child-identity-env.tssrc/main/runtime/structured-worker-hook-attestation.test.tssrc/main/runtime/structured-worker-identity.test.tssrc/main/runtime/structured-worker-identity.tssrc/main/runtime/structured-worker-mail-routing.test.tssrc/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.test.tsxsrc/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.tsxsrc/renderer/src/components/native-chat/NativeChatResolvedView.tsxsrc/renderer/src/components/native-chat/NativeChatStructuredSession.tsxsrc/renderer/src/components/native-chat/NativeChatView.tsxsrc/renderer/src/components/native-chat/native-chat-view-types.tssrc/renderer/src/components/terminal-pane/TerminalPaneNativeChatPortal.tsxsrc/renderer/src/i18n/locales/en.json
💤 Files with no reviewable changes (5)
- src/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.tsx
- src/renderer/src/components/terminal-pane/TerminalPaneNativeChatPortal.tsx
- src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
- src/renderer/src/i18n/locales/en.json
- src/renderer/src/components/native-chat/NativeChatOrchestrationPausedNotice.test.tsx
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| if (!structuredDispatchDelivered(outcome.state)) { | ||
| this.retain( | ||
| mailboxHandle, | ||
| sessionId, | ||
| retainReasonForDispatch(outcome.state as Exclude<StructuredDispatchState, 'accepted'>), | ||
| reservedTypes | ||
| ) | ||
| return |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Discard the stored operation after a rejected dispatch.
resolveStructuredPointerOperation reuses the same ID for the same session and payload. The host only redispatches IDs whose journal state is unknown; a rejected ID replays its failed ledger outcome. Retained mail can therefore remain blocked until the ID expires or the payload changes.
Delete the operation for rejected, but retain it for unknown to prevent duplicate turns. Add a regression test for rejected retries.
Proposed fix
if (!structuredDispatchDelivered(outcome.state)) {
+ if (outcome.state === 'rejected') {
+ db.deleteStructuredPointerOperation(mailboxHandle)
+ }
this.retain(
mailboxHandle,
sessionId,📝 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.
| if (!structuredDispatchDelivered(outcome.state)) { | |
| this.retain( | |
| mailboxHandle, | |
| sessionId, | |
| retainReasonForDispatch(outcome.state as Exclude<StructuredDispatchState, 'accepted'>), | |
| reservedTypes | |
| ) | |
| return | |
| if (!structuredDispatchDelivered(outcome.state)) { | |
| if (outcome.state === 'rejected') { | |
| db.deleteStructuredPointerOperation(mailboxHandle) | |
| } | |
| this.retain( | |
| mailboxHandle, | |
| sessionId, | |
| retainReasonForDispatch(outcome.state as Exclude<StructuredDispatchState, 'accepted'>), | |
| reservedTypes | |
| ) | |
| return |
| if (args.structuredWorker) { | ||
| const content = captureStructuredWorkerArchive( | ||
| args.structuredWorker, | ||
| args.structuredWorker.agent ?? 'claude' |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Recover the provider from the durable session record.
rehydrate creates StructuredWorkerIdentity.agent as null. Startup release recovery then reaches captureWorkerOutputArchive, which stores claude in the archive when the durable provider is Codex. The journal messages remain unchanged, but archived provider metadata is incorrect. Read record.provider with readStructuredAgentSessionRecord(identity.sessionId). If the record is unavailable, fail with archive_failed so the worker remains retained instead of guessing.
| // NOT yet handled, and deliberately follow-up: rebinding a restarted runtime to a structured | ||
| // worker's hold and redrive subscription. Until that exists, a worker that survives a restart | ||
| // keeps no hold, so its child is evictable and its parked mail waits for the next arrival | ||
| // rather than a settle edge. |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Restore the structured worker hold and journal redrive during restart recovery.
ensureStructuredAgentSessionHost() creates empty in-memory holds, while OrchestrationStructuredMailboxPointerDelivery stores parked mail only in parkedUntilTurnSettle and retries it from onTurnSettled(). Restart recovery does not restore either resource. A surviving worker can therefore become evictable, and parked mail can remain unread until a later arrival or explicit check. Rebind the hold and journal-settle redrive for each restored session before recovery completes.
Isolated Electron QA — native-born structured workers (PR 18827)Isolated Exercised Passed (seen, not inferred)
Gaps (do not overstate)
ClaudeCodexFull writeup: |
Orchestration resolves every worker through a terminal handle and a pane key backed by a live PTY. A session created directly as structured has neither, so it was not refused by orchestration — it was invisible. A coordinator could not start one, address one, or receive `worker_done` from one. Add a second authority source rather than a parameter channel. A registry maps a session id to the same three facts the PTY path supplies — a bearer handle, a pane key and a host scope — and the four runtime getters consult it before giving up on `ptysById`. `orchestration.send` and `verifyDispatchCapability` are untouched: authority stays host-derived and the CLI still cannot assert who it is. PTY handles short-circuit on the handle prefix, so the terminal path is unchanged. Mail travels as a session turn instead of as bytes, on a sibling lane that keeps the PTY lane's outstanding-run, waiter, reserved-type and batch rules. Orchestration's database stays the source of truth; the send is best-effort, exactly as the byte write is, and mail is consumed only on a proven-accepted dispatch. Delivery waits for the session to be between turns, because one provider refuses a mid-turn start outright and the other cannot acknowledge one inside the ack window. Security properties, each pinned by test: the pane key's leaf is random and persisted rather than derived, since `check` is identity-gated and accepts a caller-supplied pane key; the handle is a random bearer token; the child env carries no pane key, which would otherwise flow into hook pipelines that assume a PTY leaf; hook attestation stays closed for structured handles; and process continuity comes from record lineage, never the runtime fence, which the host bumps during its own crash recovery. Also remove the "Orchestration paused" notice, which gated only on dispatch status and rendered over bridge chat where orchestration always worked; refuse the implicit-sender fallback when a worktree has more than one candidate leaf instead of guessing; and collapse the archive kinds to one named type with a compile-time assertion that the capture set cannot drift ahead of the storable set.
…timeline The structured pointer gate read a bounded 40-item tail page. A settled turn is tombstoned rather than rewritten, so an idle worker with any real history carries no turnLifecycle item at all and the "full page, no lifecycle item" guard read it as busy forever: every nudge after the worker's first substantial turn parked on a settle edge that had already passed, and the preamble tells workers not to poll. The attention gate had the mirror bug — a prompt older than the tail window was missed and the nudge was delivered into a session blocked on a human. Both facts now come from `journal.snapshot()`, the fully reduced timeline, via a new narrow `readGateFacts` host read; the policy module stays pure and still projects through the shared helpers the chat view reads. Also: - Park `session-not-attached` on the journal edge, so mail that arrives during a transient detach is redriven by the re-attach reset instead of sitting unread. - Resolve a structured worker's provider from the durable agent-session record when the registry entry was rehydrated, so a restarted Codex worker is no longer reported and archived as Claude. - Clear `structured_pointer_operations` in every `orchestration reset` scope. - Drop the per-chat-pane dispatch-status store subscription left behind by the removed paused notice, and re-pin the two terminal-pane ratchets it moves. - Hoist the identical pointer batch selection out of both delivery lanes into `selectOrchestrationPointerBatch`. - Refuse the pre-graph-ready focus-based guess for `requireUnambiguous` callers, matching the ready path. - Move the host teardown phase list into the teardown module it belongs to, which is what keeps the host inside its max-lines budget.
2ef4be9 to
0ae89d4
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The follow-up commit since the prior review fixes the structured idle gate, resolves the restarted-worker provider gap, and removes the orphaned renderer subscription.
- Fixed the idle gate to read the full reduced timeline —
structuredSessionIsBetweenTurns(items, pageMayHaveMore)becamestructuredSessionGateFacts(items)overhost.journalSnapshot(), so an idle worker with real history is no longer read as busy forever, and a pending approval/question scrolled out of the tail window is no longer missed. - Parked
session-not-attachedon the journal edge — mail arriving during a transient detach is now redriven by the re-attachresetevent (onTurnSettled→onJournalActivity,parkedUntilTurnSettle→parkedUntilJournalEdge). - Resolved the provider off the durable record —
structuredWorkerAgentreads a rehydrated worker's provider from the agent-session record, so a restarted Codex worker is no longer archived/reported as Claude. - Cleared
structured_pointer_operationsin every reset scope, with tests covering each. - Removed the orphaned
chatPaneDispatchStatussubscription and its plumbing, re-pinning the two terminal-pane ratchet tests. - Hoisted
selectOrchestrationPointerBatchintomailbox-pointer-eligibility.ts, shared by both delivery lanes. - Refused the focus-based guess for
requireUnambiguouscallers, matching the ready path. - Moved the host teardown phase list into
structured-agent-session-host-teardown.ts(behavior-preserving).
Both prior concerns are resolved: the orphaned subscription is gone, and the restarted-worker provider mislabel is fixed. The restart hold/redrive rebind gap remains the documented deliberate follow-up, which is unchanged and out of scope here.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…settled unknown `commitStructuredAgentSessionCreate` answers `agent_session_operation_unknown` when `attach` SUCCEEDED and only the tab publish failed, so `created.ok === false` is not proof that nothing exists. The worker start read it that way and skipped `discardCreatedSession`, leaving a live provider child that took no hold, has no `bindingsByDispatchId` entry and no published tab — the outer `releaseStructuredWorkerSession` no-ops without a binding, and a session that never had a holder never starts the eviction clock, so nothing in the runtime ever retires it. A throw out of the commit half is past `attach` for the same reason; the pre-commit half refuses rather than throwing. Cleanup now asks whether the create MAY have committed, via the existing `isDefinitiveAgentSessionCreateRefusal` predicate. Also: - Strengthen the pre-ready `requireUnambiguous` test so it actually pins the guard: the snapshot now carries a focused terminal, so deleting the `? [] :` ternary turns the test red instead of leaving the refusal to the ambiguous `listTerminals` fallback. - Correct the guard's justification comment, which cited `orchestration check` as covered. `check` resolves through the `--terminal` scope and still guesses; the guard covers the implicit `--from` sender, and a structured worker is covered by the `ORCA_TERMINAL_HANDLE` baked into its child.
…rantees the code does not give The send-time owner re-check reads `target.refusal`, the snapshot the resolver already admitted, so `decideStructuredPointerDelivery` can only agree with the resolve-time answer and `owner-not-settled-native` is unreachable from that call site. What actually fences an owner that moved is `expectedRuntimeFence`, which a handoff bumps. Say that, so nobody later drops the fence trusting a re-check that is structurally a tautology. `discardCreatedSession` was credited with retiring "a published background tab that no dispatch owns". It hides the DURABLE tab reference and closes the session; the live tab snapshot keeps the row, so the background tab this start published stays on screen until the app restarts. Same for stop and release. The comment now describes what the two calls do — including that both are no-ops on a session that was never attached, which is what makes the non-definitive-refusal path safe to reach unconditionally.
…rker settles Starting a structured worker always publishes a real `agent-session:<id>` tab, but every settlement path only called `setSessionTabVisibility(sessionId, false)` plus `host.close(sessionId)`. That clears the DURABLE restore index and leaves the LIVE snapshot untouched, so stop, release and the half-started discard all left a dead "Claude Chat" / "Codex Chat" tab in the worktree's tab bar for the rest of the app session — five dispatches, five dead tabs — and opening one re-attached the released session, respawning a provider child outside orchestration's hold accounting. The snapshot-pruning half of `closeStructuredAgentSessionTab` is extracted into `structured-agent-session-tab-retirement.ts` and exposed on the runtime as `retireStructuredAgentSessionTabFromSnapshot`, so the user-initiated tab close and the three settlements share one implementation instead of a second copy. The settlement side is best-effort BY CONSTRUCTION: it runs only after the close is already proven, calls the runtime method optionally, and swallows any throw. It talks to no renderer, so the startup release reconciler can call it too. Nothing here can turn a proven stop into `release_unknown`.
…veness from lying Five defects in the structured-worker lanes, each with the same shape: a check that answered from something other than what it claimed to measure. - The pointer lane gated a WORKER's `dispatch:` mailbox on its RUN's outstanding delivery. Delivery rows exist only for a `run:` address, so that row belongs to the coordinator — and a coordinator holds one for exactly as long as it is acting on received mail, which is when it replies to its workers. The gate is gone; there is no coordinator mailbox in this lane to protect. - `dispatch-rejected` now parks on the journal edge. A rejection consumes no mail and nothing else redrives the mailbox, so an unparked pointer left the worker idle on durable mail until unrelated mail happened to arrive. - The released journal archive bounded forward — keeping the HEAD — before capping newest-first, so a long worker's archive ended at its early exploration and dropped the answer it was released for, under a warning that said the oldest messages had gone. One newest-first pass now, and the warning is true. - The durable pointer operation id was reused on a matching BODY fingerprint, and the body names only the unread count. Two unrelated same-size batches collided, the host replayed its ledger answer as `accepted` with no turn sent, and the lane marked the new mail delivered. Reuse is keyed on the batch's message ids. - `worker-read` on a structured worker hardcoded `terminal: 'running'` and emitted no `liveness`, so a runtime that could not see the session reported the worker as alive. It now carries the observed verdict, as the PTY branch does. Also: the live journal cursor is an index into a re-derived tail window, so the page's oldest item joins its source identity — a slid window now answers `source_changed` instead of silently resuming past the items it skipped. And a stop that reached no host reports `processAction: 'none'`, after installing the host the way release already does.
…se that never landed `worker-read` on a released structured worker hardcoded `liveness: 'exited'`. The archive is frozen BEFORE the close, so it proves nothing about the provider child, and the read is served for `release_state` in `releasing` / `unknown` too — the two states that exist precisely to record a close that did NOT land. A coordinator that read `exited` from a `release_unknown` worker would start a replacement over the same worktree while the original child was still attached, which is the outcome docs/reference/ssh-execution-boundary.md rule 2 exists to prevent, and it contradicts the release receipt's own "the structured session close was not proven" text. The verdict now comes from the resource row the read already holds: only a settled `released` row is `exited`, everything else is `unverifiable` — which the existing mapping renders as `terminal: 'unknown'`, the same way the live branch does.
…le it never delivered Two ways a structured `worker-start` handed the coordinator a receipt that did not describe the worker it got. `sendStructuredWorkerPreamble` threw only on a refusal and on `rejected`, so a submission that settled `unknown` fell through as success: the start pushed `dispatch_input: accepted` and marked the dispatch ready. `unknown` is not rare — `dispatchSafely` converts ANY thrown adapter call (provider child gone, transport dropped, ack window missed) into it, and `performSend` still returns ok. The worker then has no task spec while its coordinator blocks in `check --wait --types worker_done` until timeout. This PR's own mail lane already states the rule — "`pending` is not yet an acknowledgement; only `accepted` may consume mail" — so the preamble now applies it too, and raises `operation_unknown` for the states that prove neither delivery nor failure, which is the code `failWorkerStartWithReceipt` turns into the `outcome_unknown` receipt whose nextCommands send the coordinator to look. `rejected` stays a proven failure. `--structured` also accepted `--model` / `--effort` and dropped them: structured session creation takes no launch preferences, while `launch.receipt.effective` echoes whatever was requested either way, so `--model opus` ran on the workspace default and the receipt still said `opus`. Refused now, for the same reason `--terminal` refuses them, and the spec note records that refusal along with the new-child/new-top-level one it never mentioned. Tests: the refusal guard had no coverage at all, and `structured-mailbox-pointer-host` — where the full-timeline gate read lives — had none either; reinstating the bounded tail there left the whole repo green. Both are covered now, and the vacuous "never selects an exact provider session" case is re-pointed at the absent `ORCA_PANE_KEY` that actually keeps that selector shut.
…LI, and stop four settlements lying A structured worker's provider child runs `orca orchestration ...` exactly like a PTY worker's agent does, but it was handed the ambient PATH. On packaged Linux the CLI installs as `orca-ide` so it never claims GNOME Orca's /usr/bin/orca (#7904), so bare `orca` execs the screen reader and the worker can never read mail, reply or send worker_done; on packaged macOS/Windows the bundled launcher is only reachable from the app's own resources dir. The PTY lane already solves this inside `buildPtyHostEnv`; that block is now its own module and both lanes call it. Also: - a worker start that fails AFTER its session exists now discards the session, so a failed start stops stranding a dead chat tab that the durable restore index republishes on every launch; - a structured worker's resource reconciles to `released` after settlement forgot its identity, instead of answering `unverifiable` for the life of the DB; - `closeAttempted` is set only once a close is issued, so a tab-visibility failure can no longer report `closed_agent_terminal` for a running child; - `forgetSession` prunes only what the settled worker parked, not every sibling whose target momentarily fails to resolve; - release settles with an explicitly empty, warned archive when the journal is unreadable AND the session is proven exited — closing the chat tab is routine, and `archive_failed` there wedged release on evidence that could never arrive; - the new migration test uses mkdtemp and cleans up, so it stops failing Windows CI and leaking.
|
Too many files changed for review (174 files, 100 file limit). Bypass the limit by tagging |
Review status: 8 rounds of adversarial review, 20 defects found and fixedThis branch went through a repeated review-and-fix loop, each round run by a fresh reviewer against the previous round's output. Every round found real defects — including defects in the previous round's own fixes — so the loop was continued until a round came back with nothing material. Two full readiness reviews bracket the session. The branch was also rebased onto current The defect that mattered mostThe idle gate read every settled worker as permanently busy. The delivery gate asked a bounded 40-item journal tail page whether a turn was running. But a settled turn is tombstoned, not rewritten to Both facts now come from Also found and fixedDelivery and mail
Lifecycle and honesty
Platform
Hygiene
Security invariantsAll eight were re-verified every round and hold at HEAD: the pane key's leaf is random and persisted (never derived — Worth a reviewer's attention before merge
Verification at
|
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Seven fix commits landed since the prior review (0ae89d460a). Each addresses a real defect in the initial structured-worker implementation, and every fix carries an exact test with the reasoning pinned in a comment.
- CLI reachability extracted and applied to structured workers —
prependOrcaCliDirToChildPathwas factored out ofbuildPtyHostEnvand reused instructuredWorkerChildIdentityEnv, so a structured worker's provider child reaches Orca's own CLI (not GNOME's/usr/bin/orcaon packaged Linux) while an ordinary chat session's env passes through untouched. - Settlement receipts no longer lie —
stopStructuredWorkerreturnscloseAttempted, so stop/release receipts reportnonewhen no close was issued; the archived read keysexitedoff the settled release row; liveness is read off the durable agent-session record rather than the in-memory registry, and the structured host is reinstalled before a post-restart stop. - Nudge idempotency re-keyed on the batch — operation-id reuse now hashes the message IDs rather than the pointer body, closing the silent-mail-loss path where two same-size batches shared a fingerprint and the host answered
acceptedfrom its ledger without sending a turn. - Parked mailboxes remember their session —
forgetSessiondrops only the settled worker's own parked entries (no longer pruning siblings), and a rejected dispatch now parks on the journal edge. - Archive bounds the tail, not the head —
boundWorkerTranscriptTailpreserves the worker's final answer, and a session already closed settles with an empty warned archive instead of wedging release. - Chat-tab retirement on settlement — a pure
structured-agent-session-tab-retirement.tsshared across stop/release/discard/user close, plus discard of a half-started session whose create settledunknown. --model/--effortrefused for structured starts, matching the launch options a structured session cannot honour.
The restart hold/redrive rebind gap remains the documented deliberate follow-up and is unchanged by these commits.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/main/runtime/orchestration/structured-mailbox-pointer-delivery.ts (1)
228-235: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winDiscard the structured pointer operation after a rejected dispatch.
A journal-edge retry reuses the stored operation ID. The session API replays rejected submissions instead of redispatching them, so the mail remains unread. Delete the stored operation or mint a new operation ID when dispatch returns
rejected, before parking the retry.src/main/runtime/rpc/methods/orchestration-worker-release-completion.ts (1)
75-78: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftRestore both structured-worker resources during restart recovery.
completeWorkerTerminalReleaseOnceinstalls only the host. Restart restoration does not recreate thebindingsByDispatchIdentry that provideshost.hold(...)andsubscribeForRedrive(...). A recovered dispatch has no hold and noorchestration:redrive:${sessionId}subscriber. The child can be evicted, and parked mail can remain undelivered because journal activity no longer callsonJournalActivity. Add a recovery-specific rebind for both resources and route settlement through the existing cleanup path.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 6133958e-bed4-44ac-979f-e5db0d19656e
📒 Files selected for processing (47)
src/cli/specs/orchestration-worker-specs.tssrc/main/claude/claude-structured-launch-resolution.tssrc/main/cli/orca-cli-child-path.test.tssrc/main/cli/orca-cli-child-path.tssrc/main/codex/codex-structured-child-environment.tssrc/main/ipc/pty/host-env/assembly.tssrc/main/ipc/pty/host-env/path.tssrc/main/runtime/orca-runtime-adopt-terminal-orphans-from-inventory.tssrc/main/runtime/orca-runtime-close-mobile-session-tab.tssrc/main/runtime/orca-runtime-close-structured-agent-session-tab.tssrc/main/runtime/orca-runtime-process-incarnation-liveness.test.tssrc/main/runtime/orca-runtime-subscribe-to-terminal-resize.tssrc/main/runtime/orchestration/db/messages/structured-pointer-operation-store.tssrc/main/runtime/orchestration/db/schema/create-core-tables-sql.tssrc/main/runtime/orchestration/db/schema/migrate-v13-latest.tssrc/main/runtime/orchestration/db/schema/structured-pointer-schema-migration.test.tssrc/main/runtime/orchestration/orchestration-reset-db.test.tssrc/main/runtime/orchestration/structured-mailbox-pointer-delivery.test.tssrc/main/runtime/orchestration/structured-mailbox-pointer-delivery.tssrc/main/runtime/orchestration/structured-mailbox-pointer-host.test.tssrc/main/runtime/orchestration/structured-pointer-operation-id.test.tssrc/main/runtime/orchestration/structured-pointer-operation-id.tssrc/main/runtime/orchestration/structured-session-pointer-delivery.test.tssrc/main/runtime/orchestration/structured-session-pointer-delivery.tssrc/main/runtime/orchestration/structured-worker-journal-archive.test.tssrc/main/runtime/orchestration/structured-worker-journal-archive.tssrc/main/runtime/orchestration/worker-transcript-payload.tssrc/main/runtime/rpc/methods/orchestration-local-worker-start.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.test.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-lifecycle.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-session.test.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-session.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-start-failure.test.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-start-refusals.test.tssrc/main/runtime/rpc/methods/orchestration-worker-archive-read.tssrc/main/runtime/rpc/methods/orchestration-worker-control.tssrc/main/runtime/rpc/methods/orchestration-worker-release-completion.tssrc/main/runtime/rpc/methods/orchestration-worker-stop.tssrc/main/runtime/rpc/methods/orchestration-workers.tssrc/main/runtime/rpc/methods/structured-worker-stop-receipt.test.tssrc/main/runtime/rpc/methods/structured-worker-tab-retirement.test.tssrc/main/runtime/structured-agent-session-tab-retirement.tssrc/main/runtime/structured-worker-authority.tssrc/main/runtime/structured-worker-child-identity-env.test.tssrc/main/runtime/structured-worker-child-identity-env.tssrc/main/runtime/structured-worker-identity.test.tssrc/main/runtime/structured-worker-mail-routing.test.ts
🚧 Files skipped from review as they are similar to previous changes (12)
- src/main/runtime/orchestration/db/schema/migrate-v13-latest.ts
- src/main/runtime/orca-runtime-subscribe-to-terminal-resize.ts
- src/main/runtime/structured-worker-mail-routing.test.ts
- src/main/runtime/rpc/methods/orchestration-local-worker-start.ts
- src/main/runtime/rpc/methods/orchestration-structured-worker-session.test.ts
- src/main/runtime/orchestration/structured-pointer-operation-id.ts
- src/main/runtime/orchestration/structured-session-pointer-delivery.test.ts
- src/cli/specs/orchestration-worker-specs.ts
- src/main/runtime/orchestration/db/messages/structured-pointer-operation-store.ts
- src/main/runtime/orchestration/orchestration-reset-db.test.ts
- src/main/runtime/orchestration/structured-pointer-operation-id.test.ts
- src/main/runtime/orca-runtime-adopt-terminal-orphans-from-inventory.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| const platform = opts.platform ?? process.platform | ||
| // Why: matches node:path's `delimiter` for the running platform, but stays correct when a test | ||
| // drives a foreign platform through the seam. | ||
| const pathDelimiter = platform === 'win32' ? ';' : delimiter |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- src/main/cli/orca-cli-child-path.ts ---'
cat -n src/main/cli/orca-cli-child-path.ts | sed -n '1,90p'
printf '%s\n' '--- related test ---'
cat -n src/main/cli/orca-cli-child-path.test.ts | sed -n '70,120p'
printf '%s\n' '--- package/runtime declarations for delimiter and platform seam ---'
rg -n --glob '*.ts' --glob '*.json' 'from .node:path|from .path.|delimiter|platform' src/main/cli package.json tsconfig.json 2>/dev/null | head -120Repository: stablyai/orca
Length of output: 17342
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions
Length of output: 31562
Use the selected platform for the delimiter.
When platform is "linux" or "darwin", use ':' instead of the host delimiter. Windows hosts otherwise produce ';' for simulated POSIX paths.
Proposed fix
- const pathDelimiter = platform === 'win32' ? ';' : delimiter
+ const pathDelimiter = platform === 'win32' ? ';' : ':'📝 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.
| const pathDelimiter = platform === 'win32' ? ';' : delimiter | |
| const pathDelimiter = platform === 'win32' ? ';' : ':' |
| mailbox_handle TEXT PRIMARY KEY, | ||
| session_id TEXT NOT NULL, | ||
| operation_id TEXT NOT NULL, | ||
| batch_fingerprint TEXT NOT NULL, |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Verify migrations for the renamed pointer column and the widened archive CHECK.
set -euo pipefail
fd -t f -g '*migrate*' src/main/runtime/orchestration/db/schema | while IFS= read -r file; do
echo "===== $file"
rg -n -C 6 'structured_pointer_operations|batch_fingerprint|body_fingerprint|worker_terminal_archives|structured_journal' "$file" || true
done
echo "===== pointer operation store SQL"
fd -t f -g 'structured-pointer-operation-store*' src | while IFS= read -r file; do
echo "===== $file"
rg -n -C 4 'batch_fingerprint|body_fingerprint|INSERT|SELECT' "$file"
done
echo "===== any remaining references to the old column name"
rg -n 'body_fingerprint' src || echo 'none'Repository: stablyai/orca
Length of output: 3647
Add a migration for existing structured_pointer_operations tables.
The archive table already has a rebuild for the widened kind CHECK. However, CREATE TABLE IF NOT EXISTS structured_pointer_operations does not rename an existing body_fingerprint column. On upgraded databases, putStructuredPointerOperation writes batch_fingerprint and fails because that column is missing. Add an explicit rename or table migration for existing structured_pointer_operations tables.
| const active = nextTabs.find((candidate) => candidate.isActive) ?? nextTabs[0] ?? null | ||
| return { | ||
| ...snapshot, | ||
| snapshotVersion: snapshot.snapshotVersion + 1, | ||
| activeTabId: active?.id ?? null, | ||
| activeTabType: active?.type ?? null, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Compare the extracted retirement helper with the original close path and its consumers.
set -euo pipefail
echo "===== original close path"
fd -t f -g 'orca-runtime-close-structured-agent-session-tab*' src | while IFS= read -r file; do
echo "----- $file"
cat -n "$file"
done
echo "===== other snapshot mutators: do they rewrite isActive when promoting?"
rg -n -C 6 'isActive' src/main/runtime --glob '*.ts' --glob '!*.test.ts'
echo "===== consumers of activeTabId vs isActive"
rg -n -C 4 'activeTabId' src/renderer src/shared mobile --glob '*.ts' --glob '*.tsx' --glob '!*.test.*' | head -80Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "===== retirement helper"
cat -n src/main/runtime/structured-agent-session-tab-retirement.ts
echo "===== helper tests and direct callers"
rg -n -C 8 'retireStructuredAgentSessionTabFrom|retireStructuredAgentSessionTabFromSnapshot' src --glob '*.{ts,tsx}' --glob '!*.test.*'
fd -t f -e ts -e tsx src | rg 'structured-agent-session-tab-retirement|structured-agent.*retire|close-structured-agent'Repository: stablyai/orca
Length of output: 17047
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "===== snapshot storage and emission definitions"
rg -n -C 12 'storeMobileSessionSnapshot|emitMobileSessionTabsSnapshot' src/main/runtime --glob '*.ts' | head -160
echo "===== projection finalization callers"
rg -n -C 10 'finalizeRuntimeMobileSessionTabsResult' src/main/runtime --glob '*.ts'Repository: stablyai/orca
Length of output: 23205
Set the promoted tab’s isActive flag.
When the retired tab is active, retireStructuredAgentSessionTabFrom falls back to nextTabs[0] and writes its ID to activeTabId, but leaves every tab’s isActive value unchanged. The stored and emitted snapshot can therefore contain conflicting active-tab state. Map nextTabs so only active.id has isActive: true.
Source: Linters/SAST tools
The release-completion module imported ./orchestration-worker-release-receipts twice, which trips import/no-duplicates in audit:code-quality:native. The changed-file gate does not load that config, so only whole-tree CI saw it.
…no-op The activate:false branch for an already-published session returns without writing the snapshot or emitting, so it cannot re-surface a client whose mirror lost the tab. Orchestration is safe from this only incidentally.
|
Re-validation of PR #18827 at 8aed3e9. This run supersedes the earlier QA at Open question — background structured worker tab, unaided: NO (both claude and codex).
Full writeup: First paint (settings already on)Claude: tab bar immediately after background
|
… a flag `worker-start --structured` was an explicit opt-in that REFUSED --on, --terminal, --model/--effort and worktree-creating placements. The flag, its spec entry and the `structured` RPC param are gone: the mode now follows the user's setting for new agent tabs, so a local claude/codex worker is a structured chat session whenever the user's own default says agent tabs open as one. A setting is a preference, not a demand, so none of those combinations refuses any more. A dispatch that cannot be structured starts an ordinary PTY terminal worker and the receipt names the mode that ran and why, so the fallback is never silent: - a remote --on, an existing --terminal, a new-child/new-top-level worktree and --model/--effort are decided from the request; - the agent, TUI launch customization, Codex-on-Windows and the runtime capability are decided by the shared launch route; - WSL, remoteness and the Windows start-time gate are settled by the executing host's own agentSession.createSupport, asked once the worktree resolves and before anything is created, so a refusal is a terminal worker rather than a failed start. The decision is the renderer's, lifted rather than copied: `resolveAgentLaunchRoute`'s structured half and the settings predicate now live in shared/structured-native-chat-launch-route, which both surfaces call, and the TUI launch customization test moves to shared beside it. `getClientSettings` gains the two native-chat default booleans it was missing. No security invariant moves: the structured worker registry, bearer handle, persisted pane key, the absence of ORCA_PANE_KEY from the child env, hook attestation and lineage-derived process incarnation are untouched.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior review, the worker mode became the user's own default rather than a --structured flag.
- Made the worker mode settings-driven — removed
--structuredandassertStructuredWorkerStartSupported;orchestration-worker-start-mode.tsnow derives the mode from the settings default (decideWorkerStartMode), then re-checks the resolved worktree against the executing host (resolveWorkerStartModeOnHost/downgradeWorkerStartModeForHost) before anything is created, so a refusal degrades to a terminal worker instead of a failed start. - Extracted the shared launch route —
structured-native-chat-launch-route.tsholdsprefersStructuredNativeChatByDefaultandresolveStructuredNativeChatSupport, andtui-agent-launch-customization.tsholds the custom-command/args/env check, both used by orchestration and the renderer so the two surfaces cannot drift. - Refactored the renderer onto the shared module —
resolveAgentLaunchRouteanddecideInitialAgentTabViewModenow call the shared predicates; I diffed the old inline conjuncts against the new shared checks and the behavior is preserved point-for-point. - Made the fallback non-silent — the start and failure receipts carry a
modefield (mode/preferred/reason/detail), and the CLI always prints the human line naming which mode ran and why.
The settings-driven fallback is a deliberate product choice documented in the PR and the CLI spec notes, and each reason maps to a tested case (orchestration-worker-start-mode.test.ts). The two prior Pullfrog concerns (orphaned chatPaneDispatchStatus subscription, restarted-worker provider relabeling) remain resolved; the restart hold/redrive rebind gap is still the documented deliberate follow-up and is unchanged here.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The mode a worker runs in is a runtime implementation detail. An agent should be taught the same verbs, run the same commands and read the same receipts whether it is a structured chat session or a PTY terminal — otherwise a settings-driven fallback silently changes what the agent can do. The real leak was `canDispatchSubWorkers`, which was forced false for a structured worker. That was not a wording choice: `worker-start` resolved `--from` through `showTerminal`, which needs a live PTY or renderer leaf, so a `structworker_` coordinator genuinely could not dispatch. Rather than withhold the capability, the one fact the command needs from `--from` — its worktree id — now comes from `getOrchestrationDispatchAuthority`, the same authority the pane-key and process-incarnation getters already answer structured handles from. Sub-dispatch is gated on depth alone, identically for both modes. `showTerminal` itself is deliberately NOT taught structured handles: it returns a ptyId, a leaf id and a pane runtime id, and synthesising those for a session with no PTY would hand every caller of a public terminal verb something that looks writable and is not. `inspectWorkerTerminal` already returns `terminal: null` for exactly that reason. Also neutralised three agent-visible refusals that named the worker's kind: a `worker-read --source terminal` on a worker with no terminal now names the sources that do work, and both archive refusals say "transcript output" rather than "structured chat output" (the PTY `transcript_pin` branch said "structured" too). New tests pin both properties: the two preambles are byte-identical once the handle and per-dispatch ids are normalised, and a structured coordinator starts a worker with `showTerminal` rejecting.
… a prompt worker-show reported observation.agentWait: null for every structured worker. The field's own contract says null means Orca looked and found no wait, and absent means it never looked — and nothing looks here: a structured worker parks on a journal question item, which no terminal prompt scan can see. So null was a false negative on the one field a coordinator is explicitly told to read, and it was mode-dependent: the same worker as a PTY would have reported the wait. Absent is both the honest value and a state a PTY worker already reaches (an older host, an unreadable pane, a probe that did not answer), so it discloses nothing about which mode ran.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This commit stops the worker mode from leaking into the agent contract: a worker is now taught the same verbs and reads the same receipts whether it runs as a structured chat session or a PTY terminal.
- Lifted the structured sub-dispatch gate —
canDispatchSubWorkersis now gated on depth alone for both modes, instead of being forced false for a structured worker. - Resolved
--fromthrough the dispatch authority — newresolveDispatchCallerWorktreeId(orchestration-caller-workspace.ts) pulls astructworker_coordinator's worktree id fromgetOrchestrationDispatchAuthority, the same authority the pane-key and process-incarnation getters already answer structured handles from, so a structured coordinator can actually dispatch sub-workers.showTerminalis deliberately left unaware of structured handles. - Neutralised three agent-visible refusals —
worker-read --source terminaland both archive refusals now name the sources that do work ("transcript output") instead of disclosing the worker's kind. - Pinned mode opacity by test —
orchestration-worker-mode-opacity.test.tsasserts the two preambles are byte-identical after normalising the handle and per-dispatch ids, and that a structured coordinator starts a sub-worker withshowTerminalrejecting.
The pre-existing restart hold/redrive rebind gap remains the documented deliberate follow-up and is unchanged here.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… kind The note said "the receipt mode field names the mode used and why", which is an instruction to read a field no verb behaves differently for — the one thing the mode was not supposed to become. It now says what a caller actually needs: the dispatch always starts, the options passed are the ones honoured, and every worker is driven the same way. The receipt still carries the mode for operators and telemetry; nothing tells an agent to look at it.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This commit stops a structured worker's observation from falsely claiming it was checked for a human-answerable prompt.
agentWaitis now absent, not null, for structured workers —inspectWorkerTerminal's structured branch droppedagentWait: null. Null is the contract's "Orca looked and found no wait", but nothing ever looks for a structured worker's parked journal question (it is invisible to every terminal prompt scan), so null was a false negative a coordinator could act on. Absence correctly signals "never looked", matching the field's documented semantics.- Pinned by test — a new opacity test asserts
'agentWait' in observation === falsefor a structured worker, the exact distinction the contract draws between absent and null.
The consumers already handle absence (observation.agentWait !== undefined ? … : {}), and the CLI spec documents the absent-vs-null distinction, so the change is consistent end to end.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Two commits since the prior review (3fb592d087). Both close agent-visible gaps in the structured-worker surface, and each is pinned by an exact test.
- Reached structured workers through group addresses —
@all,@idle,@codex, and@worktree:<id>now enumerate live structured workers alongsidelistTerminals.resolveGroupAddresswidened to the smallerOrchestrationAddressableAgentshape rather than teachinglistTerminalsabout sessions it cannot summarize (its result is published to paired clients underremote-wire-compatibility), and@idle/@codexstatus reads the full reduced journal viastructuredWorkerAgentStatus, so a busy worker is never woken mid-turn and an unreadable session never reads as idle. - Made
getAgentStatusForHandleanswer structured handles — it short-circuits to the journal-derived status instead of returning null from the PTY probe, which is what silently dropped every structured worker from@idle. - Refused rather than guessed for a session with no identity — a non-worker structured session's child now carries
ORCA_STRUCTURED_SESSION(a marker that names nothing), and the CLI'sresolveOrchestrationTerminalHandlerefuses withno_active_sender_terminalinstead of guessing a sibling pane — a destructivecheckpreviously consumed that sibling's oldest unread batch, andrequireUnambiguousdid not save it because with a single terminal pane the guess still resolved. Explicit--from/--terminalandORCA_TERMINAL_HANDLE(every worker child) are unaffected. - Extracted
readStructuredSessionGateFactsintostructured-mailbox-pointer-host.tsso the pointer lane and group addressing cannot disagree about the idle gate.
Delivery of a bare structworker_ recipient handle is already covered by the direct-mail lane (resolveStructuredWorkerDirectMailboxTarget), so a group send to a between-dispatch worker still lands as a session turn.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one minor test-coverage nit inline.
Reviewed changes
One commit since the prior review (61577d7a). It stops two surfaces from lying about a worker that has no terminal.
- Gave terminal verbs a truthful refusal for a structured handle —
getLiveLeafForHandlenow throwsstructuredWorkerTerminalRefusal(terminal_unsupported_for_agent_session) for a live structured worker instead ofterminal_handle_stale, which falsely claimed the handle died and sent callers hunting for a remint that cannot exist. A PTY handle, or a structured handle this runtime no longer owns, still gets the stale error; the new code is passed through byrpc/errors.tsand the message names the structured equivalents (orca terminal read,worker-read --source transcript,orca orchestration send). - Reworded the worker-start spec notes — dropped the false promise of "the same worker-read sources" and instead states "not every worker has a terminal" with the always-working alternatives (
--source auto/--source transcript), keeping the worker kind unnamed so mode opacity is preserved.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| registerWorker() | ||
| hostRef.current = null | ||
| expect(structuredWorkerTerminalRefusal('term_gone', null).message).toBe('terminal_handle_stale') |
There was a problem hiding this comment.
This case does not exercise what its name and comment claim. It registers a structworker_ worker and nulls the host, but then calls structuredWorkerTerminalRefusal('term_gone', ...) — a PTY-style handle that short-circuits isStructuredWorkerHandle before the record lookup, so the assertion is identical to the preceding PTY test. It would still pass if the "no longer owns" branch regressed to returning terminal_unsupported_for_agent_session for a released structured handle.
| registerWorker() | |
| hostRef.current = null | |
| expect(structuredWorkerTerminalRefusal('term_gone', null).message).toBe('terminal_handle_stale') | |
| const handle = registerWorker() | |
| hostRef.current = null | |
| expect(structuredWorkerTerminalRefusal(handle, null).message).toBe('terminal_handle_stale') |
Isolated Electron QA @
|
| # | Check | Verdict | What I saw |
|---|---|---|---|
| 1 | Self-identity (run-current / task-list from worker, no --from) |
PASS | Env ORCA_TERMINAL_HANDLE=structworker_…, no --from. run-current exit 0 (ok: true). Never no_active_sender_terminal. After the worker bound its own Run, task-list exit 0. Live worker also ran orca orchestration check from its own Bash tool. |
| 2 | Sub-dispatch (task-create then worker-start, no --from) |
FAIL (nesting, not identity) | task-create succeeded (created_by_terminal_handle = structured handle). worker-start failed: Sub-worker dispatch is not permitted at depth 2 (max 1). Identity worked; this worker was already depth 1. |
| 3 | Group addressing @all / @idle |
PASS | Both sends exit 0. Live structured worker received both (qa-parity-all, qa-parity-idle) and said so in chat. Receipt to_handle was run:run_bbfc2c0cecdc (the Run it bound), not a raw structworker_ handle. terminal list still lists only the PTY. |
| 4 | worktree rm without --force |
PASS (refused; different guard) | Exit 1: Refusing to delete protected worktree path: …/structured-orch-qa. Did not --force. Live-session teardown copy was not reached (this checkout is the running app). |
| 5 | dispatch --inject |
PASS | Did not return no_agent_detected. Returned: already has active dispatch ctx_bb075a81373e. |
| 6 | terminal read |
PASS | ok: true, status: running, journal tail (preamble + assistant + tool results). Not terminal_handle_stale. |
| 7 | terminal send --text hi |
PASS | terminal_unsupported_for_agent_session: agent session, not a terminal — points at terminal read / worker-read --source transcript / orchestration send. Not handle stale. |
Renderer console: 0 errors.
First paint (settings seeded, empty profile)
Project loaded
Structured Claude worker (group-address receipt visible)
PTY coordinator tab (qa-pty) next to Claude Chat
Structured chat after focusing the tab
…y work Four defects and two follow-ups from the delta review. The `worktree rm` refusal was a dead end in the desktop UI. Its message matched no matcher in `classifyWorktreeForceDeleteReason`, and an ordinary desktop delete already passes `force=true` for the dirty-file skip, so classification returned null unconditionally: the toast showed raw CLI wording with no Force Delete button, and a user with a live chat session was stuck unless they knew to reach for the CLI. That is the #11960 shape `shared/worktree/removal.ts` documents, so the refusal now has its own prefix, matcher, `WorktreeForceDeleteReason` and toast copy, classified BEFORE the `force` guard and nulled once the waiver is spent — exactly how `unstopped-pty` is handled, with matcher and hint kept in the same file as that contract requires. The copy says Force Delete will close a running conversation rather than borrowing the "could not confirm" wording, because Orca watched these sessions stay attached; there is no doubt to waive. Structured `terminal read` cursors were unsound and are now refused. The PTY cursor indexes an append-only completed-line buffer with a monotone count; a session journal is a BOUNDED tail re-projected on every read, so a saved index addressed different lines as the journal grew — and `truncated` could never fire to say so, because it tests `cursor < oldestCursor` and `oldestCursor` was always 0. A poller got wrong or duplicated lines under `truncated:false`. Separately, a streaming turn's lines counted as completed with `partialLine` hardcoded empty, so a mid-turn cursor consumed a half-written line whose growth was never redelivered — the `"hel"`/`"hello"` hazard the PTY reader guards against. The journal does have stable item identity, but `terminal.read`'s cursor is a number on the wire and cannot carry it, so a cursor read now refuses and names `worker-read --source transcript`, which already has that contract including `source_changed`. No cursor space is advertised either: `nextCursor` is null and the cursor fields are absent, rather than claiming an index the next read cannot honour. The header claim that all four fields kept their meanings was true of the shape and false of the invariants; it now says which ones hold. Two fixes had no test at their real seam, which is the same failure that produced this whole set — the runtime tested directly, the seam tested by neither. The group-addressing test hand-composed the recipient list itself, so deleting the composition at the call site left it green; it now drives `sendGroupMessage` with no PTY terminals at all. Nothing referenced `isLiveStructuredAgent`, so the `dispatch --inject` fix had no red-then-green at all; it now has one driving `RuntimeTerminalAgentPresence.isRunning`. Both were ablated and confirmed red. Folder-workspace removals sweep and kill PTYs without `requirePhysicalStop`, so the structured sweep no-opped there and left a live session bound to a workspace about to be forgotten. They now close best-effort under an explicit `closeStructuredSessions` flag, kept separate from `requirePhysicalStop` because the two questions differ: that one asks whether a stop must be PROVEN before files are touched, and it is what licenses a refusal. These paths do not refuse — the root is shared so no checkout vanishes under the child, and one of them is a never-throw forget a refusal would wedge. Reconciliation sweeps set neither and still close nothing. Also: the force close is raced against the same sweep deadline every PTY surface is bounded by, so a wedged provider close reports the timeout instead of hanging `worktree rm --force` forever; and the refusal now prints a count and the providers instead of raw session ids, which our own marker rationale treats as one tab-id hop from a credential.
The folder and orphan removal callers now pass closeStructuredSessions so a live structured session is closed best-effort rather than left bound to a workspace Orca has forgotten. These three exact-args characterizations describe that call and had not been updated.
There was a problem hiding this comment.
Important
Two must-address issues on this delta: a missing i18n key that fails verify:localization-catalog, and a --force timeout that throws instead of warning.
Reviewed changes
- Closed the
worktree rmrefusal's desktop dead end — the running-agent-session refusal now has its ownRUNNING_AGENT_SESSION_REMOVAL_PREFIX, arunning-agent-sessionclassifier branch (decided before theforceguard, nulled once the waiver is spent) and Force-Delete toast copy, matchingunstopped-pty. - Refused structured
terminal readcursors — a numeric cursor can't be re-anchored to a re-projected journal tail, so cursor reads now throw and nameworker-read --source transcript; no cursor space is advertised (nextCursor: null, cursor fields absent), and a mid-turn read no longer counts a growing line as completed. - Closed the two test seams that had no test at their real boundary — group addressing now drives
sendGroupMessagewith zero PTY terminals, and agent presence drivesRuntimeTerminalAgentPresence.isRunningagainstisLiveStructuredAgent. - Made folder-workspace removals close structured sessions best-effort — a new
closeStructuredSessionsdep, kept separate fromrequirePhysicalStop, so the sweep no longer no-ops on a path that forgets the workspace. - Raced the force close against the sweep deadline and dropped raw session ids from the refusal copy (count + providers instead, since a session id is one tab-id hop from the pane-key credential).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| // provider round trip, and a wedged one would otherwise hang `worktree rm --force` forever with | ||
| // no timeout error at all. On expiry the force path reports the timeout exactly as the PTY | ||
| // sweeps do rather than proceeding as if the sessions had closed. | ||
| const { closed, unstopped } = await settleBeforeDeadline( |
There was a problem hiding this comment.
Passing deadlineError unconditionally makes the structured sweep fail-closed under --force. Under allowUnverifiedStop the three PTY sweeps also pass deadlineError, but their timeouts are caught by settleSweepsForForcedRemoval (line 203) and turned into a warning plus continued removal. This sweep is awaited directly at line 106, so a structured host.close that outlives the deadline throws Timed out waiting for physical PTY teardown: … Retry with force delete (--force), which the classifier maps to unstopped-pty and tells a user who already forced to force again — the #11960 wedge this path exists to prevent.
Technical details
# Fold the structured sweep into forced settlement
## Affected sites
- src/main/runtime/worktree-teardown.ts:321 — `settleBeforeDeadline(..., deadline, deadlineError)` passes `deadlineError` unconditionally, so a timeout throws even when `allowUnverifiedStop` is set.
- src/main/runtime/worktree-teardown.ts:106 — the sweep is awaited directly, so that throw bypasses the `allowUnverifiedStop` handling below.
- src/main/runtime/forced-sweep-settlement.ts:75 — `settleSweepsForForcedRemoval` reconciles only the three PTY sweeps; the structured sweep is not a member.
## Required outcome
- Under `--force` (`requirePhysicalStop && allowUnverifiedStop`), a structured-session close that exceeds the sweep deadline must warn and let removal continue (matching the PTY sweeps), never throw a timeout that fails `worktree rm --force`.
## Suggested approach (optional)
- Pass `deps.requirePhysicalStop && !deps.allowUnverifiedStop ? deadlineError : undefined` (or otherwise gate on the waiver) so the force path falls back to `{ closed: 0, unstopped: live }`, or add the structured sweep as a fourth member of `settleSweepsForForcedRemoval`.
Live
|
| Step | Result |
|---|---|
| 1. Create throwaway git worktree through Orca | PASS |
2. worker-start --agent claude → mode.mode = "structured" and session live |
PASS |
3. worktree rm without --force names count + provider, no session id |
PASS |
| 4. Worktree still on disk; worker still alive | PASS |
5. worktree rm --force succeeds and actually closes the provider child |
PASS |
| 6. Desktop delete toast offers Force Delete (not raw-error-only) | PASS |
Step 3 exact refusal
Refusing to remove worktree with running agent sessions: 45be2f43-fe63-4452-8da9-7b7be7b9a509::/Users/brennanbenson/orca/workspaces/main/qa-rm-throwaway — 1 running agent session (claude). Retry with force delete (--force) to remove it anyway.
This is not Refusing to delete protected worktree path. Count + provider (1 running agent session (claude)), no session id.
Step 5
--force returned {"removed":true}. Disk gone. Claude child PID 27440 (claude --session-id=059a0d4e-…, parent = isolated Electron) gone. worker-show observation went live → exited. worktree show → selector_not_found.
Step 6 desktop toast
Triggered via the Delete Workspace dialog (not CLI). Store: canForceDelete: true, forceDeleteReason: "running-agent-session".
Copy: This workspace still has running agent sessions, so Orca stopped before deleting any files. Force Delete will close them and discard any work they hold. Buttons: View + Force Delete.
…ing silently `worker-read --source transcript` for a structured worker fingerprinted only the oldest item's id, so `source_changed` fired when the window slid off the front and could NOT fire when the page's contents changed under a stable oldest item — which is the normal case, because the journal is a reduced, mutable timeline. A `running` tool item gains its `[tool result]` at its original sequence once later items exist, the 60ms delta coalescer revises a message in place, settlement can rewrite an item smaller, and a pending approval projects to null until it resolves and then appears in the MIDDLE of the array. Two silent failures followed, both returning ok. Omission: a caller handed a coalesced `hel`, resuming past it, never received the revision to `hello world` — the same defect we refused to ship on the terminal read path, already shipped here. Duplication: a resolved approval inserted ahead of a saved index, which was still accepted, so the caller re-read content it already had. The blast radius is the coordinator polling loop, the verb's primary consumer. The anchor is now the oldest item PLUS every item whose projected message sits below the caller's position, by id and revision. `createWorkerOutputSourceIdentity` already takes an arbitrary string array and the cursor is already opaque base64url carrying its own position, so neither the wire shape nor the `source_changed` contract changes. Prefix-scoped rather than whole-page deliberately: fingerprinting every item on the page would flip the identity every 60ms with the coalescer window during an active turn, making the cursor unusable exactly while the worker is working — that trades a silent bug for a useless verb. Tail growth the caller has not read cannot invalidate; any change to what it already holds does. Position-dependence is safe because `p` rides in the same opaque payload as the identity, and the returned cursor is stamped with the identity of its own end, which is precisely what the next read recomputes. The frozen archive keeps a constant identity: no item can be revised under a caller there, so it has no prefix to fingerprint. Both silent shapes are pinned across a page boundary with the journal mutating between reads — a static-journal test passes either way. Two ablations at the real call site: reverting to the oldest-item-only anchor turns both red, and widening the prefix to the whole page turns the tail-growth case red, which is what proves the scoping is real in both directions.
…ending a dead end The refusal told a peer to "page it with `orca orchestration worker-read --source transcript`", which is wrong three ways and this file said so itself: its own header explains that this verb exists BECAUSE `worker-read` demands a dispatch id and coordinator standing "a peer does not have" — and then the refusal sent that same peer there. The verb it named is also a window index over the same bounded page, so it is not a paging answer even for a caller who can reach it; under load it now answers `source_changed` on most polls, which is better than the silent hole it had before but still not what the sentence promised. The refusal now says what actually works — the tail is bounded and newest-last, so poll it and diff — and names no alternative, because there is none. That is the honest framing: a durable cursor is not achievable here at all, rather than blocked on the wire shape. The journal is a reduced, MUTABLE timeline: an item's projected text changes at its original sequence after later items exist, the delta coalescer revises repeatedly, settlement can rewrite an item smaller, a pending approval renders as nothing and then as something, and `sequence` resets on epoch rollover. No index, numeric or opaque, survives that. So the docstring's "pagination with a real anchor lives on `worker-read --source transcript`" is gone too — there is no real anchor there — and the file now records why no windowed alternative should be built later: a broken cursor fails UNSAFE, as a silent hole in a poller's output, while diffing a bounded tail fails safe as a harmless re-read, and a second paging-shaped verb would invite the PTY assumptions this one cannot honour. The test asserted the old advice, so it now pins the contract instead: the refusal explains the working approach and must never name `worker-read`. `worker-read --source transcript` remains a good bounded snapshot for a coordinator reading a worker it dispatched; only the "or page it with" clause was false.
There was a problem hiding this comment.
Important
The cursor fix in this delta is clean and I found no new issues in it. I'm withholding approval because two must-address findings from the prior review are still open and unchanged by this commit: the runningAgentSession i18n key is still missing from en.json (fails verify:localization-catalog, part of pnpm lint), and the structured sweep still passes deadlineError unconditionally so a --force close that outlives the deadline throws instead of warning. A third open thread (the structured-worker-terminal-refusal.test.ts "no longer owns" case still passing 'term_gone') is a test-coverage nit. These are tracked in the existing threads and are not re-raised inline.
Reviewed changes
The single commit since the prior review (45e23ee) fixes a silent misdelivery in the structured worker-read --source transcript cursor.
- Re-anchored the
source_changedidentity on the held prefix — the old anchor fingerprinted only the oldest journal item's id, so an in-place revision under a stable oldest item (arunningtool gaining its[tool result], the delta coalescer revising a message) resumed past the revision with no error, and a resolved approval inserting into the middle of the array re-served already-delivered content.structuredJournalPrefixIdentitynow fingerprints the oldest item (the window-slide detector) plus every projected item below the cursor position byitemIdandrevision, scoped to the prefix the caller already holds rather than the whole page so the coalescer's 60ms tail revisions don't invalidate the cursor mid-turn. - Stamped the returned cursor with its own end —
pageMessagesnow writesidentityAt(end), so the next read's check recomputes exactly the prefix a caller was handed and catches both omission and duplication. - Kept the archive path position-independent — archived reads use a constant
identityAt: () => sourceIdentitysince the archive is frozen before close and nothing can revise under a caller. - Pinned the mutating-journal cases by test —
structured-worker-read-cursor.test.tsmutates the journal between reads across five cases (in-place revision, mid-array insertion, allowed tail-only growth, exactly-once delivery, window slide); a static-journal test would pass under either anchor.
I traced the index-alignment claim the prefix identity depends on: projectStructuredItemToNativeChat(item) !== null selects exactly the items projectStructuredItemsToNativeChat keeps, in order, and boundWorkerTranscriptMessages returns a head prefix of that array, so message index i maps to item i for every index a cursor can name. The implementation is consistent, and the new test file passes (5/5).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
No new issues in this delta. It corrects a misleading refusal message; approval remains held by the three open threads from the prior review (each unchanged by this commit).
Reviewed changes
- Stopped the
terminal readcursor refusal from steering a peer at a dead end — the message previously recommendedworker-read --source transcript, which a peer reachingterminal readcannot run (no dispatch id, no coordinator standing) and which is a window index over the same bounded tail rather than an append-only anchor. It now says to read without--cursorand poll-and-diff, names no paging alternative, and the header documents why the refusal is permanent: a broken cursor fails unsafe (a silent hole in a poller's output) while diffing a bounded newest-last tail fails safe (a harmless re-read). - Pinned the new wording by test — the cursor-refusal test now asserts the message still says
not line-addressable, that it instructspoll it and diff, and that it never mentionsworker-read.
The change is message- and comment-scoped (structured-worker-terminal-read.ts + its test). The sibling structured-worker-terminal-refusal.ts (terminal.show surface) still names worker-read --source transcript, which is correct there — that caller has dispatch context — so the fix is scoped to the one surface where the redirect was wrong. structured-worker-terminal-read.test.ts passes (9/9).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Carries main's #19040 through this branch's two extractions, which would otherwise have silently reverted it: both conflicts are the same shape, where main fixed code this branch had already moved elsewhere. - resolveStructuredNativeChatSupport no longer refuses a launch that has saved session options. Main removed that term from resolveAgentLaunchRoute directly; this branch had lifted the whole predicate into the shared module, so taking either conflict side kept the refusal alive. The blocker member, the unused input field, the orchestration blocker-to-reason entry and the case pinning it are removed with it. Main's own routing test failed on this merge before the port and passes after, which is what proves the port is load-bearing rather than cosmetic. - The structured create fingerprint now goes through attachFingerprintFields. Same shape again: main replaced the inline field list in structured-agent-session.ts, but this branch had moved that computation into structured-agent-session-create.ts. Options stay out of the digest, which is main's point: they are the session's initial state, not its identity, so a retry after the user reselects a model replays instead of conflicting.
The structured-session removal refusal introduced a translate() key with no en.json entry. Nothing local catches that: typecheck passes, and the full suite passes, because a missing key falls back to its inline default at runtime. Only verify:localization-catalog fails on it, which is why CI's static analysis reddened on a branch that was green everywhere else. Fallback wording mirrors the sibling unstoppedPtyLive string, since the two refusals differ only in what is still running and what Force Delete does to it.
There was a problem hiding this comment.
Important
This delta is a clean origin/main merge with no new issues, but I'm withholding approval because two must-address findings from prior reviews remain open and unchanged by the merge: the runningAgentSession i18n key is still absent from src/renderer/src/i18n/locales/en.json (fails verify:localization-catalog, part of pnpm lint), and the structured sweep still passes deadlineError unconditionally so a --force close that outlives the deadline throws instead of warning. A third minor test-coverage thread (structured-worker-terminal-refusal.test.ts "no longer owns" case still passing 'term_gone') is also still open. All three are tracked in their existing threads and are not re-raised here.
Reviewed changes
The single commit since the prior review is a merge of origin/main into the branch. The net reconciliation in PR-owned files is mechanical and correct:
- Adopted main's extracted
attachFingerprintFields— the create path (structured-agent-session-create.ts) now computes its host fingerprint via the shared helper instead of an inline copy that hardcodedexpectedRuntimeFence: nulland omittedproviderHandle. This aligns the create fingerprint with whatadmitAttachOrRefuserecomputes on the attach path; the old inline form would have diverged for a non-null fence. I tracedresolveStructuredAgentSessionCreateIntent→ fullAgentSessionAttachParams, soattachFingerprintFields({ ...resolved, envelope })reconstructs a valid params shape. - Picked up the
initial-session-optionsremoval (#19040) —resolveStructuredNativeChatSupportno longer blocks structured routing on saved session options, and the worker-start mode decision (orchestration-worker-start-mode.ts) follows suit, keeping the shared launch-route module in lockstep with main.
The remainder of the merge is main's own CI/SSH/WSL/cloud/relay commits and is out of scope.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…red child The refuse-rather-than-guess marker landed after these expectations were written, and all three assert exact env equality on the unregistered path — the one branch that now carries ORCA_STRUCTURED_SESSION. One of the two files was added by this same branch, so this is a self-inflicted drift; the other predates the branch and was broken by it. The marker's presence is still pinned positively by structured-worker-child-identity-env.test.ts and the CLI's orchestration-structured-session-no-identity.test.ts, so relaxing these three exact-equality checks loses no coverage of the security property.
Carries the durable multi-agent workflow work (#16904) through this branch. Both PRs touch the same subsystem, so most of this is deciding which of two independent solutions to the same problem survives. #16904 did not generalize past the PTY assumption anywhere, so nothing here is redundant: it hardens the first authority source, this branch adds a second under the same contracts. Schema. Both sides independently wrote a `current < 31` migration from a shared base of 30, with different bodies, and main went on to 38. Version 31 therefore means two different schemas, and the skew checker asserts main's five v31 columns for anything stamped >= 31 — so a database written by this branch failed the completeness check and replayed the whole chain from v6. That is the checker working correctly, not a defect, and the replay is row-safe (every DROP in the chain is a copy-forward rebuild gated on shape, and there is no DELETE or TRUNCATE anywhere in it). Nothing shipped stamped 31 with this branch's content: the commit is in no tag and no release branch. So the migration renumbers to 39 in its own file. It no longer creates `structured_pointer_operations` — that is redundant, because `createTables` runs unconditionally on every open, ahead of migration. Only the widened archive CHECK needs a migration, since IF NOT EXISTS cannot widen a constraint on an existing table. The gratuitous rename of migrate-v13-v30.ts is reverted, which removes a conflict outright. Batch selection. Both sides changed the same region: this branch extracted it verbatim into `selectOrchestrationPointerBatch`, main edited it in place and dropped the JS post-filter. Main is right, and provably so — the unfiltered waiter returns early, so every surviving waiter contributes a concrete type list that SQL excludes byte-exactly (`messages.type` is TEXT with no NOCASE collation), and the trailing slice sits behind an identical SQL LIMIT. Nothing can reach the post-pass in a filtering state, for either lane, and selection is synchronous throughout so no waiter can register inside it. The extraction survives and main's lane now calls it, so the two lanes cannot drift again. The docblock claimed the post-filter caught a mid-selection waiter; that hazard does not exist and the claim is gone. Nothing covered this, so it now has tests against a real database rather than a stub. Delivery gate. This branch gated only `run:` mailboxes, on the premise that a delivery row exists only for a `run:` address. Main made that false — deliveries are keyed by any mailbox handle — and generalized correctly, keying the lookup on the exact handle being nudged, so a coordinator's run delivery cannot suppress the nudges it sends its workers. Adopted. It is worth more here than in the PTY lane: a structured nudge costs a whole provider turn. Archive kind. Main's new `summarizeWorkerOutputArchive` is a two-way switch that JSON-parses every non-transcript_pin kind as a terminal tail, so this branch's `structured_journal` reached `content.lines.every(...)` and threw, at three live call sites. A structured session's journal reports as `transcript`: it IS the session's transcript, and a third source value would both leak the structured/terminal split into a CLI surface this PR keeps uniform and widen a shape that reaches paired clients. PTY pointer refusal. Main shipped the same fix independently and narrower, so this branch's hunk is dropped. Its guard fires only when a session is bound, which is exactly the set the blanket refusal covered — an unbound pty is always admitted, so a denial implies a binding. Also: this branch's release-receipt extraction gives way to main's, with the structured lease check moved into main's lease module; the worker RPC tree moves into main's orchestration/{worker,messaging,federation} layout, with this branch's structured branches replayed into the new homes. pnpm tc clean. Verified by grepping the MERGED files, not the diffs, that main's migration registrations, its six durability attach calls, its reset delete, its fleet-status additions and its dispatch-pointer support all survived — each of those would have been dropped silently by a keep-ours resolution, with no conflict marker and a green typecheck. Both merged files crossed the 300-line cap, which must be split rather than disabled. Four extractions, each a whole step rather than an arbitrary cut: assertExplicitWorkerTerminalUsable (the three refusals that must happen before anything is created), deliverWorkerDispatchPreamble (one preamble, two transports), tearDownFailedWorkerStart (undo what a failed start created), and stopStructuredWorkerForRelease (the close half of a release for a worker with no terminal to close). One thing this merge restores rather than adds: `canDispatchSubWorkers` on the local worker's dispatch preamble. The shared ancestor passed it; main's extraction of startLocalWorker does not, and `buildDispatchPreamble` treats its absence as false, so a locally started worker on main is no longer taught the sub-dispatch verbs. With the default nested depth of 1 that section applied to every first-generation worker, and main still passes the same argument at three other call sites, so this reads as a line lost while moving ~300 lines rather than a decision. Restored here for both lanes, since a worker is taught the same verbs whichever mode it runs in.
Ten commits, of which six are store/selector performance work that touches nothing here. Two conflicts, both in skill-guide expectations, and both taken from main: they assert the wording of a guide rewrite that main has now reverted (#19126), and this branch never authored them — the only commit on this side that touches those files is the previous merge, which carried main's own content at the time. Worth noting for the PR description rather than the code: main's #19121 makes worker lineage survive an app restart, which is the limitation this branch documents as deferred. Whether it closes that gap for a structured worker needs checking separately; the structured lane keeps no hold across a restart for its own reasons, so the two are not obviously the same fix.
There was a problem hiding this comment.
Important
The merge reconciliation in this delta is clean and I found no new issues in it. I'm withholding approval because one must-address finding from an earlier commit is still open and unchanged by these merges — it stays tracked in its existing thread and is not re-raised inline.
Reviewed changes
- Merged
origin/maintwice (ed25b3efd7,4cc4395781), pulling in #16904 (durable multi-agent workflows — the orchestration RPC methods move intoorchestration/worker,messaging,runs,federationsubdirectories, plus schema v31–v38), #19121 (worker lineage across restart), #18986, #18741, and a batch of perf/test commits. - Ported the structured-worker branches onto the re-organized structure —
startLocalWorkerstill resolves a structured coordinator's worktree throughresolveDispatchCallerWorktreeId(nevershowTerminal), and the take-over RPC resolvessessionId→pane key with the resume-fence sweep gated onchanged > 0. - Moved the journal-archive rebuild to schema v39 —
migrate-v39.tsrebuildsworker_terminal_archivesto admitstructured_journal;structured_pointer_operationsstays increateTables; the migration test stampsuser_version = 38so only v39 runs and proves old rows survive. - Re-keyed the structured delivery gate onto
hasOutstandingMailboxDelivery, keyed on the exact handle being nudged (an improvement over the oldrun:-only check), and corrected the archive-source mapping sostructured_journalreports as atranscriptsource.
The reconciliation preserves structured-worker behavior: 57 targeted tests across the touched paths pass, including the mode-opacity, delivery, lifecycle, abandon, and schema-migration suites.
⚠️ worktree rm --force can still throw on a slow structured close
sweepStructuredSessions still passes deadlineError unconditionally to settleBeforeDeadline (worktree-teardown.ts:325), and that sweep is awaited directly at line 106 before settleSweepsForForcedRemoval runs — so a structured host.close that outlives the sweep deadline throws Timed out waiting for physical PTY teardown… and fails worktree rm --force, violating the #11960 "force never wedges" contract, whereas the three PTY sweeps reconcile their timeouts under force into a warning + continued removal. This was raised in a prior review and is unchanged by these merges; it is the sole remaining blocker. The minor test-coverage nit in structured-worker-terminal-refusal.test.ts (the "no longer owns" case passes 'term_gone') is also still open.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
This delta's change is clean and I found no new issues in it. I'm withholding approval because the sole remaining blocker from earlier commits — sweepStructuredSessions passing deadlineError unconditionally, so a --force close that outlives the deadline throws instead of warning (worktree-teardown.ts:321) — is still open and unchanged by this commit; it stays in its existing thread and is not re-raised here. The minor test-coverage nit in structured-worker-terminal-refusal.test.ts is likewise still open.
Reviewed changes
- Required positive exit evidence before settling a structured close —
closeStructuredAgentSessionChildnow settles only whenobserveStructuredWorker(...).status === 'exited'(a released claim with death evidence), where it previously settled for anything that was notlive. Anunverifiableobservation — no durable record, a terminal owner, an uninstalled host, or a restarted session with no attached child — is no longer reported asstopped: truewith its tab retired on unproven death, and the observation'sreasonis now surfaced on the retained outcome. - Pinned each retention path by test — the lifecycle suite's
it.eachcovershasSession: false,runtimeKind: 'tui',claimStatus: 'released', andrecord: null; the stop-receipt suite adds the restarted-worker case (close with no attached session reportsstop_unknownwhile still issuing the close); the teardown harness now records release + death evidence on close so its assertions mirror the real host.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
This delta is a clean origin/main merge with no new issues, but approval stays withheld: the sole remaining blocker from earlier commits — sweepStructuredSessions passing deadlineError unconditionally (worktree-teardown.ts:325), so a --force close that outlives the deadline throws instead of warning — is still open and unchanged by the merge. The minor test-coverage nit in structured-worker-terminal-refusal.test.ts is likewise still open. Both stay in their existing threads and are not re-raised here.
Reviewed changes
The single commit since the prior review (d70eb61b2f) is a merge of origin/main into the branch. The net reconciliation in PR-owned files is mechanical and correct:
- Adopted main's late-dispatch settlement in the shared host —
structured-agent-session-host.tspicks upsettleStructuredAgentSessionLateDispatch(main's #19140) exposed assettleLateDispatch, plus thestatusFeedonStatusChangedcallback, thereplay: truerestore publish, and theattachContext→lifetimeContext()collapse. The PR's ownjournalSnapshotmethod andstructuredAgentSessionHostTeardownPhasesextraction are preserved verbatim (both still resolve fromrequireSession(...).journal.snapshot()and the extracted teardown module). - Renderer link-action popover flows in —
NativeChatResolvedView.tsxandNativeChatStructuredSession.tsxswap touseNativeChatLinkActions(main's #19130). The PR's removal of the "Orchestration paused" notice is intact;NativeChatOrchestrationPausedNoticeno longer exists anywhere insrc/.
No PR-authored commits and no behavioral surface to the PR's own orchestration logic in this delta — the PR-owned structured-worker-* and orchestration/* files are untouched by the merge.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Reviewed through Merged main in Same-model review/fix/re-review and independent initial/final readiness, plus a fresh merged-head integration review, found no remaining proven in-scope issue. Historical severity review classified the fixed issue as P2. The fix adds no observer calls, polling, subprocesses, or retained state. Validation:
Grok validated the isolated background Electron app at Full-app evidence from the adopted PTY chat (no paused banner; this frame does not prove mailbox consumption): Provider screenshots containing worker identifiers were excluded from this comment. The improved latest Claude ACK screenshot and a stop before worker completion were not finished when Grok stalled; those are explicit accepted gaps. The observed stop calls were post-completion no-ops, while release performed the close. Live Electron/SSH QA was not repeated after the main merge. CI is green on Coverage limits: native Windows/WSL was not run (accepted for this review), nor live mobile/older-client compatibility or an exhaustive restart/network-fault matrix. No merge performed. |
…stablyai#18827) * feat(orchestration): orchestrate native-born structured chat sessions Orchestration resolves every worker through a terminal handle and a pane key backed by a live PTY. A session created directly as structured has neither, so it was not refused by orchestration — it was invisible. A coordinator could not start one, address one, or receive `worker_done` from one. Add a second authority source rather than a parameter channel. A registry maps a session id to the same three facts the PTY path supplies — a bearer handle, a pane key and a host scope — and the four runtime getters consult it before giving up on `ptysById`. `orchestration.send` and `verifyDispatchCapability` are untouched: authority stays host-derived and the CLI still cannot assert who it is. PTY handles short-circuit on the handle prefix, so the terminal path is unchanged. Mail travels as a session turn instead of as bytes, on a sibling lane that keeps the PTY lane's outstanding-run, waiter, reserved-type and batch rules. Orchestration's database stays the source of truth; the send is best-effort, exactly as the byte write is, and mail is consumed only on a proven-accepted dispatch. Delivery waits for the session to be between turns, because one provider refuses a mid-turn start outright and the other cannot acknowledge one inside the ack window. Security properties, each pinned by test: the pane key's leaf is random and persisted rather than derived, since `check` is identity-gated and accepts a caller-supplied pane key; the handle is a random bearer token; the child env carries no pane key, which would otherwise flow into hook pipelines that assume a PTY leaf; hook attestation stays closed for structured handles; and process continuity comes from record lineage, never the runtime fence, which the host bumps during its own crash recovery. Also remove the "Orchestration paused" notice, which gated only on dispatch status and rendered over bridge chat where orchestration always worked; refuse the implicit-sender fallback when a worktree has more than one candidate leaf instead of guessing; and collapse the archive kinds to one named type with a compile-time assertion that the capture set cannot drift ahead of the storable set. * fix(orchestration): answer the structured idle gate from the reduced timeline The structured pointer gate read a bounded 40-item tail page. A settled turn is tombstoned rather than rewritten, so an idle worker with any real history carries no turnLifecycle item at all and the "full page, no lifecycle item" guard read it as busy forever: every nudge after the worker's first substantial turn parked on a settle edge that had already passed, and the preamble tells workers not to poll. The attention gate had the mirror bug — a prompt older than the tail window was missed and the nudge was delivered into a session blocked on a human. Both facts now come from `journal.snapshot()`, the fully reduced timeline, via a new narrow `readGateFacts` host read; the policy module stays pure and still projects through the shared helpers the chat view reads. Also: - Park `session-not-attached` on the journal edge, so mail that arrives during a transient detach is redriven by the re-attach reset instead of sitting unread. - Resolve a structured worker's provider from the durable agent-session record when the registry entry was rehydrated, so a restarted Codex worker is no longer reported and archived as Claude. - Clear `structured_pointer_operations` in every `orchestration reset` scope. - Drop the per-chat-pane dispatch-status store subscription left behind by the removed paused notice, and re-pin the two terminal-pane ratchets it moves. - Hoist the identical pointer batch selection out of both delivery lanes into `selectOrchestrationPointerBatch`. - Refuse the pre-graph-ready focus-based guess for `requireUnambiguous` callers, matching the ready path. - Move the host teardown phase list into the teardown module it belongs to, which is what keeps the host inside its max-lines budget. * fix(orchestration): discard a structured worker session whose create settled unknown `commitStructuredAgentSessionCreate` answers `agent_session_operation_unknown` when `attach` SUCCEEDED and only the tab publish failed, so `created.ok === false` is not proof that nothing exists. The worker start read it that way and skipped `discardCreatedSession`, leaving a live provider child that took no hold, has no `bindingsByDispatchId` entry and no published tab — the outer `releaseStructuredWorkerSession` no-ops without a binding, and a session that never had a holder never starts the eviction clock, so nothing in the runtime ever retires it. A throw out of the commit half is past `attach` for the same reason; the pre-commit half refuses rather than throwing. Cleanup now asks whether the create MAY have committed, via the existing `isDefinitiveAgentSessionCreateRefusal` predicate. Also: - Strengthen the pre-ready `requireUnambiguous` test so it actually pins the guard: the snapshot now carries a focused terminal, so deleting the `? [] :` ternary turns the test red instead of leaving the refusal to the ambiguous `listTerminals` fallback. - Correct the guard's justification comment, which cited `orchestration check` as covered. `check` resolves through the `--terminal` scope and still guesses; the guard covers the implicit `--from` sender, and a structured worker is covered by the `ORCA_TERMINAL_HANDLE` baked into its child. * docs(orchestration): stop two structured-worker comments claiming guarantees the code does not give The send-time owner re-check reads `target.refusal`, the snapshot the resolver already admitted, so `decideStructuredPointerDelivery` can only agree with the resolve-time answer and `owner-not-settled-native` is unreachable from that call site. What actually fences an owner that moved is `expectedRuntimeFence`, which a handoff bumps. Say that, so nobody later drops the fence trusting a re-check that is structurally a tautology. `discardCreatedSession` was credited with retiring "a published background tab that no dispatch owns". It hides the DURABLE tab reference and closes the session; the live tab snapshot keeps the row, so the background tab this start published stays on screen until the app restarts. Same for stop and release. The comment now describes what the two calls do — including that both are no-ops on a session that was never attached, which is what makes the non-definitive-refusal path safe to reach unconditionally. * fix(orchestration): retire a structured worker's chat tab when the worker settles Starting a structured worker always publishes a real `agent-session:<id>` tab, but every settlement path only called `setSessionTabVisibility(sessionId, false)` plus `host.close(sessionId)`. That clears the DURABLE restore index and leaves the LIVE snapshot untouched, so stop, release and the half-started discard all left a dead "Claude Chat" / "Codex Chat" tab in the worktree's tab bar for the rest of the app session — five dispatches, five dead tabs — and opening one re-attached the released session, respawning a provider child outside orchestration's hold accounting. The snapshot-pruning half of `closeStructuredAgentSessionTab` is extracted into `structured-agent-session-tab-retirement.ts` and exposed on the runtime as `retireStructuredAgentSessionTabFromSnapshot`, so the user-initiated tab close and the three settlements share one implementation instead of a second copy. The settlement side is best-effort BY CONSTRUCTION: it runs only after the close is already proven, calls the runtime method optionally, and swallows any throw. It talks to no renderer, so the startup release reconciler can call it too. Nothing here can turn a proven stop into `release_unknown`. * fix(orchestration): stop a structured worker's nudges, archive and liveness from lying Five defects in the structured-worker lanes, each with the same shape: a check that answered from something other than what it claimed to measure. - The pointer lane gated a WORKER's `dispatch:` mailbox on its RUN's outstanding delivery. Delivery rows exist only for a `run:` address, so that row belongs to the coordinator — and a coordinator holds one for exactly as long as it is acting on received mail, which is when it replies to its workers. The gate is gone; there is no coordinator mailbox in this lane to protect. - `dispatch-rejected` now parks on the journal edge. A rejection consumes no mail and nothing else redrives the mailbox, so an unparked pointer left the worker idle on durable mail until unrelated mail happened to arrive. - The released journal archive bounded forward — keeping the HEAD — before capping newest-first, so a long worker's archive ended at its early exploration and dropped the answer it was released for, under a warning that said the oldest messages had gone. One newest-first pass now, and the warning is true. - The durable pointer operation id was reused on a matching BODY fingerprint, and the body names only the unread count. Two unrelated same-size batches collided, the host replayed its ledger answer as `accepted` with no turn sent, and the lane marked the new mail delivered. Reuse is keyed on the batch's message ids. - `worker-read` on a structured worker hardcoded `terminal: 'running'` and emitted no `liveness`, so a runtime that could not see the session reported the worker as alive. It now carries the observed verdict, as the PTY branch does. Also: the live journal cursor is an index into a re-derived tail window, so the page's oldest item joins its source identity — a slid window now answers `source_changed` instead of silently resuming past the items it skipped. And a stop that reached no host reports `processAction: 'none'`, after installing the host the way release already does. * fix(orchestration): stop a released structured archive claiming a close that never landed `worker-read` on a released structured worker hardcoded `liveness: 'exited'`. The archive is frozen BEFORE the close, so it proves nothing about the provider child, and the read is served for `release_state` in `releasing` / `unknown` too — the two states that exist precisely to record a close that did NOT land. A coordinator that read `exited` from a `release_unknown` worker would start a replacement over the same worktree while the original child was still attached, which is the outcome docs/reference/ssh-execution-boundary.md rule 2 exists to prevent, and it contradicts the release receipt's own "the structured session close was not proven" text. The verdict now comes from the resource row the read already holds: only a settled `released` row is `exited`, everything else is `unverifiable` — which the existing mapping renders as `terminal: 'unknown'`, the same way the live branch does. * fix(orchestration): stop a structured worker-start reporting a preamble it never delivered Two ways a structured `worker-start` handed the coordinator a receipt that did not describe the worker it got. `sendStructuredWorkerPreamble` threw only on a refusal and on `rejected`, so a submission that settled `unknown` fell through as success: the start pushed `dispatch_input: accepted` and marked the dispatch ready. `unknown` is not rare — `dispatchSafely` converts ANY thrown adapter call (provider child gone, transport dropped, ack window missed) into it, and `performSend` still returns ok. The worker then has no task spec while its coordinator blocks in `check --wait --types worker_done` until timeout. This PR's own mail lane already states the rule — "`pending` is not yet an acknowledgement; only `accepted` may consume mail" — so the preamble now applies it too, and raises `operation_unknown` for the states that prove neither delivery nor failure, which is the code `failWorkerStartWithReceipt` turns into the `outcome_unknown` receipt whose nextCommands send the coordinator to look. `rejected` stays a proven failure. `--structured` also accepted `--model` / `--effort` and dropped them: structured session creation takes no launch preferences, while `launch.receipt.effective` echoes whatever was requested either way, so `--model opus` ran on the workspace default and the receipt still said `opus`. Refused now, for the same reason `--terminal` refuses them, and the spec note records that refusal along with the new-child/new-top-level one it never mentioned. Tests: the refusal guard had no coverage at all, and `structured-mailbox-pointer-host` — where the full-timeline gate read lives — had none either; reinstating the bounded tail there left the whole repo green. Both are covered now, and the vacuous "never selects an exact provider session" case is re-pointed at the absent `ORCA_PANE_KEY` that actually keeps that selector shut. * fix(orchestration): let a structured worker actually reach the Orca CLI, and stop four settlements lying A structured worker's provider child runs `orca orchestration ...` exactly like a PTY worker's agent does, but it was handed the ambient PATH. On packaged Linux the CLI installs as `orca-ide` so it never claims GNOME Orca's /usr/bin/orca (stablyai#7904), so bare `orca` execs the screen reader and the worker can never read mail, reply or send worker_done; on packaged macOS/Windows the bundled launcher is only reachable from the app's own resources dir. The PTY lane already solves this inside `buildPtyHostEnv`; that block is now its own module and both lanes call it. Also: - a worker start that fails AFTER its session exists now discards the session, so a failed start stops stranding a dead chat tab that the durable restore index republishes on every launch; - a structured worker's resource reconciles to `released` after settlement forgot its identity, instead of answering `unverifiable` for the life of the DB; - `closeAttempted` is set only once a close is issued, so a tab-visibility failure can no longer report `closed_agent_terminal` for a running child; - `forgetSession` prunes only what the settled worker parked, not every sibling whose target momentarily fails to resolve; - release settles with an explicitly empty, warned archive when the journal is unreadable AND the session is proven exited — closing the chat tab is routine, and `archive_failed` there wedged release on evidence that could never arrive; - the new migration test uses mkdtemp and cleans up, so it stops failing Windows CI and leaking. * fix(orchestration): merge the duplicated release-receipts import The release-completion module imported ./orchestration-worker-release-receipts twice, which trips import/no-duplicates in audit:code-quality:native. The changed-file gate does not load that config, so only whole-tree CI saw it. * docs(runtime): note that a background structured tab re-publish is a no-op The activate:false branch for an already-published session returns without writing the snapshot or emitting, so it cannot re-surface a client whose mirror lost the tab. Orchestration is safe from this only incidentally. * feat(orchestration): make the worker mode the user's own default, not a flag `worker-start --structured` was an explicit opt-in that REFUSED --on, --terminal, --model/--effort and worktree-creating placements. The flag, its spec entry and the `structured` RPC param are gone: the mode now follows the user's setting for new agent tabs, so a local claude/codex worker is a structured chat session whenever the user's own default says agent tabs open as one. A setting is a preference, not a demand, so none of those combinations refuses any more. A dispatch that cannot be structured starts an ordinary PTY terminal worker and the receipt names the mode that ran and why, so the fallback is never silent: - a remote --on, an existing --terminal, a new-child/new-top-level worktree and --model/--effort are decided from the request; - the agent, TUI launch customization, Codex-on-Windows and the runtime capability are decided by the shared launch route; - WSL, remoteness and the Windows start-time gate are settled by the executing host's own agentSession.createSupport, asked once the worktree resolves and before anything is created, so a refusal is a terminal worker rather than a failed start. The decision is the renderer's, lifted rather than copied: `resolveAgentLaunchRoute`'s structured half and the settings predicate now live in shared/structured-native-chat-launch-route, which both surfaces call, and the TUI launch customization test moves to shared beside it. `getClientSettings` gains the two native-chat default booleans it was missing. No security invariant moves: the structured worker registry, bearer handle, persisted pane key, the absence of ORCA_PANE_KEY from the child env, hook attestation and lineage-derived process incarnation are untouched. * fix(orchestration): stop the worker mode leaking into the agent contract The mode a worker runs in is a runtime implementation detail. An agent should be taught the same verbs, run the same commands and read the same receipts whether it is a structured chat session or a PTY terminal — otherwise a settings-driven fallback silently changes what the agent can do. The real leak was `canDispatchSubWorkers`, which was forced false for a structured worker. That was not a wording choice: `worker-start` resolved `--from` through `showTerminal`, which needs a live PTY or renderer leaf, so a `structworker_` coordinator genuinely could not dispatch. Rather than withhold the capability, the one fact the command needs from `--from` — its worktree id — now comes from `getOrchestrationDispatchAuthority`, the same authority the pane-key and process-incarnation getters already answer structured handles from. Sub-dispatch is gated on depth alone, identically for both modes. `showTerminal` itself is deliberately NOT taught structured handles: it returns a ptyId, a leaf id and a pane runtime id, and synthesising those for a session with no PTY would hand every caller of a public terminal verb something that looks writable and is not. `inspectWorkerTerminal` already returns `terminal: null` for exactly that reason. Also neutralised three agent-visible refusals that named the worker's kind: a `worker-read --source terminal` on a worker with no terminal now names the sources that do work, and both archive refusals say "transcript output" rather than "structured chat output" (the PTY `transcript_pin` branch said "structured" too). New tests pin both properties: the two preambles are byte-identical once the handle and per-dispatch ids are normalised, and a structured coordinator starts a worker with `showTerminal` rejecting. * fix(orchestration): stop claiming a structured worker was checked for a prompt worker-show reported observation.agentWait: null for every structured worker. The field's own contract says null means Orca looked and found no wait, and absent means it never looked — and nothing looks here: a structured worker parks on a journal question item, which no terminal prompt scan can see. So null was a false negative on the one field a coordinator is explicitly told to read, and it was mode-dependent: the same worker as a PTY would have reported the wait. Absent is both the honest value and a state a PTY worker already reaches (an older host, an unreadable pane, a probe that did not answer), so it discloses nothing about which mode ran. * docs(cli): stop the worker-start spec pointing a caller at the worker kind The note said "the receipt mode field names the mode used and why", which is an instruction to read a field no verb behaves differently for — the one thing the mode was not supposed to become. It now says what a caller actually needs: the dispatch always starts, the options passed are the ones honoured, and every worker is driven the same way. The receipt still carries the mode for operators and telemetry; nothing tells an agent to look at it. * perf(orchestration): coalesce the structured redrive edge Every journal batch is a redrive candidate, because a settled turn is tombstoned rather than rewritten — there is no completed row to watch for. That is free while nothing is parked on the session, but once mail IS parked each batch re-resolved the dispatch, queried unread mail and read the host's gate facts, only to re-park because the turn was still running. A turn streaming tool calls paid that per batch. The edge now coalesces on a 300ms quiet window with a 2s starvation cap, so a streaming turn costs a handful of evaluations instead of one per batch and a settled turn still nudges promptly. Delivery semantics are untouched: the gate, the accepted/rejected/unknown handling and the retain rules all still run exactly as before, just fewer times. Nor is this the path fresh mail takes to an idle worker — that is `deliverForHandle` at enqueue time, which this does not touch — so the common case gains no latency. The mechanism is the session.tabs notify coalescer, generalised into `keyed-trailing-edge-coalescer` and called by both rather than duplicated; the session.tabs windows stay where they were, since 50ms is right for a spinner title and far too tight for a journal stream. Disposal drops the pending timer rather than flushing it, on the existing subscription disposer that every settlement already reaches, so a redrive can never fire for a session no dispatch owns. * fix(orchestration): deliver direct peer mail to a structured worker, and let a peer read it Two agent-to-agent verbs had no answer for a worker that IS a structured agent session, and both failed quietly. Mail addressed to a worker's own bearer handle — how agents mail each other outside a dispatch — fell between the lanes. The send stored durably and reported success, `getLiveTerminalPaneKey` resolved the recipient, and then neither lane claimed the mailbox: the structured resolver answered only `dispatch:` addresses, and the PTY lane refuses a structured handle outright. Nothing errored and nothing logged, so the worker never reacted and the peer waiting on a reply hung. The resolver now also answers a bare worker handle, preferring that worker's active dispatch so peer and coordinator nudges share one operation-ledger budget. A worker BETWEEN dispatches is still nudged, under a session-scoped key: a dispatch says nothing about whether delivery is safe — the idle gate and the lease fence do — and its own `check` reads exactly the direct mailbox the mail is sitting in. The dispatch caller key is left byte-identical, because the ledger is keyed on (callerKey, operationId) and reshaping it would re-mint nudges already in flight as second turns. `terminal read` had no structured branch, so the only peer-accessible read verb answered `terminal_handle_stale` for a live worker; `worker-read` is closed to a peer, which holds neither coordinator standing nor a dispatch id. It now serves the session's journal, projected to LINES and paged by the same reader the PTY tail uses, so the result stays a plain RuntimeTerminalRead and nothing an agent reads discloses which kind of worker answered. Bounding and dispatch-capability redaction are the archive path's, reused rather than rebuilt. A session that is not attached refuses with the existing not-attached code rather than returning an empty tail, which would read as "this worker has said nothing". `terminal.show` still refuses a structured handle. This is read-only on purpose: synthesising a ptyId/leafId/paneRuntimeId would hand every public terminal verb something that looks writable and is not. * fix(orchestration): stop three PTY-only probes answering for structured sessions Three defects, one shape: a probe that enumerates PTYs or resolves a pane was standing in for a question that is not about panes at all. `worktree rm` destroyed a live structured worker. `killAllProcessesForWorktree` sweeps the renderer graph, the provider session list and the local pty-registry, and a structured session is registered on none of them — so all three counted zero, nothing errored, and removal deleted the checkout out from under a running provider child, which kept running with its `cwd` gone while the dispatch still reported the worker live and exact. A fourth sweep now asks what the other three cannot: membership by `location.workspaceId`, which covers a plain chat session as well as a dispatched worker, and liveness by the same `live`/`unverifiable`/`exited` observation the rest of the structured surface uses. It REFUSES a destructive removal rather than auto-closing, on the same bargain and the same `--force` escape hatch as the unstopped-PTY gate — this is the verb that deletes a user's work, and a running agent is exactly what they would want to be told about. Force closes the sessions properly instead of orphaning a child. Best-effort reconciliation callers are excluded: they repair state, delete nothing, and must never be failed closed. Twelve coordinator verbs failed for a structured worker running as itself. `isLiveTerminalHandle` validated `ORCA_TERMINAL_HANDLE` with `terminal.show`, a PTY verb whose leaf lookup misses for a session that never had a pane; the pane remint that would have recovered it needs `ORCA_PANE_KEY`, which a structured child deliberately does not carry, so every one of them died on `no_active_sender_terminal` — including the ones the worker's own dispatch preamble tells it to run. The identity question gets its own probe, `terminal.resolveIdentity`: a handle and a boolean and nothing writable. `terminal.show` still refuses a structured handle, because synthesising ptyId/leafId/paneRuntimeId would hand every public terminal verb something that looks writable and is not. The PTY half is byte-for-byte today's check, `getLiveLeafForHandle` included, so its `rendererGraphEpoch` re-check still runs — that check is the whole reason the sender is validated at all, and a cheaper probe would have quietly started passing stale post-reload handles. A host that predates the method answers `method_not_found` and the client falls back to `terminal.show`, which is correct for that host: one without the identity probe has no structured workers to miss. `dispatch --inject` reported `no_agent_detected` for a structured worker, because `isTerminalRunningAgent` reaches `getLiveLeaf`, throws, and the catch returns false. A structured session IS the agent; there is no foreground process to recognise, so it answers before the PTY probes rather than through them. Also: a Run whose coordinator is structured now gets its `run:` mail. Both lanes declined and neither logged — the PTY lane because the owner is structured, the structured lane because the mailbox was not `dispatch:` — so each half believed the other owned it. The PTY lane's reasoning (a coordinator blocks in `check --wait`, where a waiter preempts pointer delivery) does not transfer: a structured coordinator is a chat session whose turn ends. Its `run:` deliveries take the `hasOutstandingRunDelivery` gate the PTY lane applies for exactly that mailbox, and only for that mailbox. The test that would have caught the twelve drives the CLI with `ORCA_TERMINAL_HANDLE=structworker_…` and no `--from`. Every existing orchestration CLI test passes `--from` explicitly, so the resolver a real worker goes through was never exercised — which is why the suite stayed green while the preamble failed on its first line. Two files crossed their line ceiling and are split rather than waived: `worktree-teardown.ts` sheds its two PTY-surface sweeps and the deadline arithmetic they share, and `orchestration.test.ts` — which sat exactly on 800 — sheds the two caller-identity suites this change rewrote. * fix(orchestration): arm the takeover signal for structured chat input `worker-release` closed a structured session a user had taken over, losing work mid-conversation, while `orchestration-worker-specs.ts:106` promised "Never closes … user-taken-over terminals". Every guard was already correct and simply never armed. `reportWorkerTerminalUserInput` has exactly one call site — the real-user-input signal on a PTY connection — so structured chat input never reached `orchestration.workerTerminalUserInput`, `markWorkerTerminalUserOwned` never ran, ownership stayed `owned` instead of `user_owned`, `retainedReason` never returned `user_takeover`, and `stopStructuredWorker` proceeded. The durable flag is reused as-is rather than given a parallel mechanism: it exists precisely so a restart, an SSH drop or a renderer remount cannot erase a takeover. Addressed by SESSION, never by pane key. A structured worker's pane key is a random identity credential — anyone holding it can read and consume that worker's mailbox, and session ids are embedded in tab ids in plain text — so it stays in main and the runtime resolves the session to it. Handing it to a renderer to echo back would make it learnable by anyone who can see a chat pane. The RPC gains an optional `sessionId` alongside `paneKey`; a host that predates it rejects the call, and the report is already best-effort with a catch, so that host degrades to exactly today's behaviour rather than failing a send. The signal fires from the composer send hook and only past `accepted`: the outbox dispatcher retries, and orchestration's own pointer nudges never pass through the composer at all — so neither can be mistaken for a user takeover. * fix(orchestration): reach structured workers through group addresses `orca orchestration send --to @all` — and `@idle`, `@claude`, `@codex`, `@worktree:<id>` — silently skipped every structured worker. Recipients came from `listTerminals`, which enumerates leaves and PTYs, and a structured session is on neither. The exclusion happened BEFORE per-recipient resolution, so the `SendRecipientWarning` machinery never ran: the caller got exit 0 and a receipt naming the workers that did resolve, and a broadcast "stop work" or "base moved" reached the PTY workers and nobody else. With every worker structured it degraded to `terminal_not_found`, which reads as "the group was empty". Fixed at the group-resolution site rather than inside `listTerminals`. That result is published to paired mobile and remote clients and to consumers that assume a summary carries a `ptyId` or is writable, so widening it is its own change under `docs/reference/remote-wire-compatibility.md`. Group addressing reads exactly three fields off a recipient, and `RuntimeTerminalSummary` already satisfies them structurally, so the resolver widens to that smaller shape and nothing here invents a `worktreePath` or a `branch`. Candidates are liveness- gated on the same observation the rest of the structured surface uses — mail addressed to a settled worker would be stored for a lane that will never deliver it — and once a worker IS a candidate, the existing per-recipient warnings cover it, so an unresolvable one is reported rather than dropped. `@idle` needed more than enumeration: `getAgentStatusForHandle` reaches a PTY probe that throws for a handle with no pane, so a structured worker would have been enumerated and then silently dropped from the one group address that selects on status. It now answers from the session's journal — and off the FULL reduced timeline, never a bounded tail. Settlement tombstones the running turn's lifecycle item rather than rewriting it, so on any page-sized read a long tool-calling turn looks identical to an idle session; `@idle` would then broadcast into a running turn, which Codex answers with `turn already running` and Claude queues behind. An unreadable session answers null, never idle. `terminal list` and `worktree ps` still omit structured workers; that is the wire-visible half and is deliberately not in this change. * fix(orchestration): refuse rather than guess when a chat session has no identity An ordinary structured chat session — not a dispatched worker — is spawned with no `ORCA_TERMINAL_HANDLE`, because `structuredWorkerChildIdentityEnv` early- returns for any session outside the worker registry. `orca orchestration check` then fell through to `terminal.resolveActive`, which picks the focused tab's active leaf or the first leaf in the worktree. It returned a valid handle, so nothing errored — and `check` is destructive by default, so it consumed another pane's oldest unacknowledged batch and marked it read. The rightful worker never saw that mail. `requireUnambiguous` does not fix this, only narrows it: it refuses when MULTIPLE leaves could be meant, and with exactly one terminal pane in the worktree the guess still resolves — to a sibling. "One terminal pane plus one chat tab" is a normal layout, so the common case stayed broken. The pinned test is that case. So the child now carries `ORCA_STRUCTURED_SESSION`, and every remaining route that would GUESS an implicit terminal refuses on it with an error naming the flag to pass. The marker names NOTHING — no handle, no pane key, no session id, no token — which is the whole reason it is safe: it cannot be replayed, cannot impersonate, and cannot flow into the hook-attestation, agent-row or mobile-projection pipelines the way a pane key would. That makes it a different decision from withholding `ORCA_PANE_KEY`, not a reversal of it. It also grants no CLI reachability, so packaged builds keep exactly today's exposure. The comment at `orca-runtime-adopt-terminal-orphans-from-inventory.ts` that justified the guess — "a structured worker is covered instead by the `ORCA_TERMINAL_HANDLE` its child is spawned with" — was true only for dispatched workers and false for every other structured session, a population this branch creates. It now says which case it covers and which case it does not. * fix(orchestration): stop two surfaces lying about a worker with no terminal `orca terminal <verb>` answered `terminal_handle_stale` for a structured worker's handle. Nothing went stale: the session is live and simply has no terminal, and it never had one — so callers acted on a false claim and went hunting for a remint that cannot exist. The refusal now carries its own code and names the structured equivalents (`orca terminal read`, `worker-read --source transcript`, `orca orchestration send`), so an agent that lands there learns what to run rather than what failed. A PTY handle that really did go stale keeps the old error, and so does a session this runtime no longer owns — that handle IS dead. `terminal.show` stays non-resolving: synthesising a ptyId/leafId/paneRuntimeId would hand every public terminal verb something that looks writable and is not. `orchestration-worker-specs.ts` promised "the same verbs, the same handle, and the same worker-read sources", and all three clauses were false for a worker with no terminal. A spec agents read must not carry a false promise, so it now states the limitation and the alternative that always works. Note this had to be reconciled with an invariant this branch already holds: the worker MODE must stay opaque, or a coordinator starts branching on something no verb it runs behaves differently for. So the note says "not every worker has a terminal" and points at `--source auto`/`--source transcript` WITHOUT naming a kind — the same mode-neutral wording `readStructuredWorkerOutput` already uses when it refuses `--source terminal`. Both properties are now pinned by tests, so neither can be restored by breaking the other. * fix(orchestration): close the review findings on the structured parity work Four defects and two follow-ups from the delta review. The `worktree rm` refusal was a dead end in the desktop UI. Its message matched no matcher in `classifyWorktreeForceDeleteReason`, and an ordinary desktop delete already passes `force=true` for the dirty-file skip, so classification returned null unconditionally: the toast showed raw CLI wording with no Force Delete button, and a user with a live chat session was stuck unless they knew to reach for the CLI. That is the stablyai#11960 shape `shared/worktree/removal.ts` documents, so the refusal now has its own prefix, matcher, `WorktreeForceDeleteReason` and toast copy, classified BEFORE the `force` guard and nulled once the waiver is spent — exactly how `unstopped-pty` is handled, with matcher and hint kept in the same file as that contract requires. The copy says Force Delete will close a running conversation rather than borrowing the "could not confirm" wording, because Orca watched these sessions stay attached; there is no doubt to waive. Structured `terminal read` cursors were unsound and are now refused. The PTY cursor indexes an append-only completed-line buffer with a monotone count; a session journal is a BOUNDED tail re-projected on every read, so a saved index addressed different lines as the journal grew — and `truncated` could never fire to say so, because it tests `cursor < oldestCursor` and `oldestCursor` was always 0. A poller got wrong or duplicated lines under `truncated:false`. Separately, a streaming turn's lines counted as completed with `partialLine` hardcoded empty, so a mid-turn cursor consumed a half-written line whose growth was never redelivered — the `"hel"`/`"hello"` hazard the PTY reader guards against. The journal does have stable item identity, but `terminal.read`'s cursor is a number on the wire and cannot carry it, so a cursor read now refuses and names `worker-read --source transcript`, which already has that contract including `source_changed`. No cursor space is advertised either: `nextCursor` is null and the cursor fields are absent, rather than claiming an index the next read cannot honour. The header claim that all four fields kept their meanings was true of the shape and false of the invariants; it now says which ones hold. Two fixes had no test at their real seam, which is the same failure that produced this whole set — the runtime tested directly, the seam tested by neither. The group-addressing test hand-composed the recipient list itself, so deleting the composition at the call site left it green; it now drives `sendGroupMessage` with no PTY terminals at all. Nothing referenced `isLiveStructuredAgent`, so the `dispatch --inject` fix had no red-then-green at all; it now has one driving `RuntimeTerminalAgentPresence.isRunning`. Both were ablated and confirmed red. Folder-workspace removals sweep and kill PTYs without `requirePhysicalStop`, so the structured sweep no-opped there and left a live session bound to a workspace about to be forgotten. They now close best-effort under an explicit `closeStructuredSessions` flag, kept separate from `requirePhysicalStop` because the two questions differ: that one asks whether a stop must be PROVEN before files are touched, and it is what licenses a refusal. These paths do not refuse — the root is shared so no checkout vanishes under the child, and one of them is a never-throw forget a refusal would wedge. Reconciliation sweeps set neither and still close nothing. Also: the force close is raced against the same sweep deadline every PTY surface is bounded by, so a wedged provider close reports the timeout instead of hanging `worktree rm --force` forever; and the refusal now prints a count and the providers instead of raw session ids, which our own marker rationale treats as one tab-id hop from a credential. * test: pin structured-session close on the folder-workspace removal path The folder and orphan removal callers now pass closeStructuredSessions so a live structured session is closed best-effort rather than left bound to a workspace Orca has forgotten. These three exact-args characterizations describe that call and had not been updated. * fix(orchestration): stop the structured worker-read cursor misdelivering silently `worker-read --source transcript` for a structured worker fingerprinted only the oldest item's id, so `source_changed` fired when the window slid off the front and could NOT fire when the page's contents changed under a stable oldest item — which is the normal case, because the journal is a reduced, mutable timeline. A `running` tool item gains its `[tool result]` at its original sequence once later items exist, the 60ms delta coalescer revises a message in place, settlement can rewrite an item smaller, and a pending approval projects to null until it resolves and then appears in the MIDDLE of the array. Two silent failures followed, both returning ok. Omission: a caller handed a coalesced `hel`, resuming past it, never received the revision to `hello world` — the same defect we refused to ship on the terminal read path, already shipped here. Duplication: a resolved approval inserted ahead of a saved index, which was still accepted, so the caller re-read content it already had. The blast radius is the coordinator polling loop, the verb's primary consumer. The anchor is now the oldest item PLUS every item whose projected message sits below the caller's position, by id and revision. `createWorkerOutputSourceIdentity` already takes an arbitrary string array and the cursor is already opaque base64url carrying its own position, so neither the wire shape nor the `source_changed` contract changes. Prefix-scoped rather than whole-page deliberately: fingerprinting every item on the page would flip the identity every 60ms with the coalescer window during an active turn, making the cursor unusable exactly while the worker is working — that trades a silent bug for a useless verb. Tail growth the caller has not read cannot invalidate; any change to what it already holds does. Position-dependence is safe because `p` rides in the same opaque payload as the identity, and the returned cursor is stamped with the identity of its own end, which is precisely what the next read recomputes. The frozen archive keeps a constant identity: no item can be revised under a caller there, so it has no prefix to fingerprint. Both silent shapes are pinned across a page boundary with the journal mutating between reads — a static-journal test passes either way. Two ablations at the real call site: reverting to the oldest-item-only anchor turns both red, and widening the prefix to the whole page turns the tail-growth case red, which is what proves the scoping is real in both directions. * docs(orchestration): stop the structured terminal-read refusal recommending a dead end The refusal told a peer to "page it with `orca orchestration worker-read --source transcript`", which is wrong three ways and this file said so itself: its own header explains that this verb exists BECAUSE `worker-read` demands a dispatch id and coordinator standing "a peer does not have" — and then the refusal sent that same peer there. The verb it named is also a window index over the same bounded page, so it is not a paging answer even for a caller who can reach it; under load it now answers `source_changed` on most polls, which is better than the silent hole it had before but still not what the sentence promised. The refusal now says what actually works — the tail is bounded and newest-last, so poll it and diff — and names no alternative, because there is none. That is the honest framing: a durable cursor is not achievable here at all, rather than blocked on the wire shape. The journal is a reduced, MUTABLE timeline: an item's projected text changes at its original sequence after later items exist, the delta coalescer revises repeatedly, settlement can rewrite an item smaller, a pending approval renders as nothing and then as something, and `sequence` resets on epoch rollover. No index, numeric or opaque, survives that. So the docstring's "pagination with a real anchor lives on `worker-read --source transcript`" is gone too — there is no real anchor there — and the file now records why no windowed alternative should be built later: a broken cursor fails UNSAFE, as a silent hole in a poller's output, while diffing a bounded tail fails safe as a harmless re-read, and a second paging-shaped verb would invite the PTY assumptions this one cannot honour. The test asserted the old advice, so it now pins the contract instead: the refusal explains the working approach and must never name `worker-read`. `worker-read --source transcript` remains a good bounded snapshot for a coordinator reading a worker it dispatched; only the "or page it with" clause was false. * fix(i18n): add the missing worktree-removal agent-session refusal string The structured-session removal refusal introduced a translate() key with no en.json entry. Nothing local catches that: typecheck passes, and the full suite passes, because a missing key falls back to its inline default at runtime. Only verify:localization-catalog fails on it, which is why CI's static analysis reddened on a branch that was green everywhere else. Fallback wording mirrors the sibling unstoppedPtyLive string, since the two refusals differ only in what is still running and what Force Delete does to it. * test(codex): expect the no-identity marker on an unregistered structured child The refuse-rather-than-guess marker landed after these expectations were written, and all three assert exact env equality on the unregistered path — the one branch that now carries ORCA_STRUCTURED_SESSION. One of the two files was added by this same branch, so this is a self-inflicted drift; the other predates the branch and was broken by it. The marker's presence is still pinned positively by structured-worker-child-identity-env.test.ts and the CLI's orchestration-structured-session-no-identity.test.ts, so relaxing these three exact-equality checks loses no coverage of the security property. * fix(orchestration): require exit evidence before settling structured close --------- Co-authored-by: Merge Sim <sim@local>




















What
Orchestration can now start, dispatch to, mail, read, stop and release a native-born structured native chat session (Claude or Codex) as a worker.
There is no flag. The worker mode follows the user's own setting for new agent tabs: with structured native chat on by default, a local Claude/Codex worker starts as a structured chat session. Where a dispatch cannot be structured, it starts as a normal terminal worker anyway and says why — fallback, never refusal, and never silent.
Before this, a structured session was not merely refused by orchestration — it was invisible. Orchestration resolves every worker through a terminal handle and a pane key backed by a live PTY; a session created directly as structured is published as
{type:'agent-session', id:'agent-session:<sessionId>', sessionId, agent}with noptyId,leafId,paneKeyorterm_handle, so nothing in the dispatch, mail, or lifecycle paths could name it.How
A second authority source, not a parameter channel.
orchestration.sendandverifyDispatchCapabilityare untouched. They keep deriving sender identity host-side and keep ignoring anything the CLI claims. Instead, a registry (structured-worker-identity.ts) maps a session id to the same three facts the PTY path supplies — a bearer handle, a pane key, and a host scope — and the four runtime getters consult it before giving up onptysById:getOrchestrationDispatchAuthoritygetTerminalPaneKeygetTerminalProcessIncarnationgetLiveTerminalPaneKeyPTY handles short-circuit on the
structworker_prefix, so the existing terminal path is untouched.Delivery is a sibling lane to the PTY pointer path, not a fork of it: same outstanding-run, waiter, reserved-type and batch-limit rules. The nudge travels as a session turn instead of as bytes, because a structured session has no PTY to type into. Orchestration's database stays the source of truth — the send is best-effort, exactly as the byte write is today, and mail is consumed only on a proven-accepted dispatch.
Readiness is attach returning
ok. There is no boot-then-idle gap to wait through, so the structured branch skipstui-idleentirely.Security properties
These are the crux of the change and each is pinned by test:
orchestration.checkis identity-gated, not capability-gated: it falls back to a caller-suppliedterminalPaneKey, and dispatch lookup matchesassignee_pane_keydirectly. A derivable leaf would let anyone who learns a session id — tab ids embed it in plain text — read and consume that worker's mailbox with no token. PTY pane keys are safe only because their leaf is a random UUID; these match that.term_-prefixed, becauseissueHandlerevalidates the renderer graph epoch and a main-mintedterm_leaf would evaporate on window reload.ORCA_PANE_KEYis not injected into the structured child. OnlyORCA_TERMINAL_HANDLEandORCA_CLI_COMMAND. Claude structured sessions run hooks, and a pane key there would flow into hook-attestation and agent-row pipelines that all assume a pane key names a PTY leaf.launchTokenHashandptyIdempty, and the test covers a fabricated empty-ptyIdreceipt.identity_unproven.Delivery correctness
dispatchState === 'accepted'. Bothrejectedandunknownretain — a dead provider child settlesunknown, neverrejected, so treating it as delivered would be silent mail loss.turn already running, the other accepts the frame but cannot acknowledge inside the dispatch ack window. Waiting is the one contract that holds for both, and it preserves orchestration's existing idle-edge-only policy.completedrow, and the history tail page can lie if a running lifecycle item is paged out behind a burst of tool calls — so a full page carrying no lifecycle item reads as busy.Also in this change
dispatchStatusand never checked for a structured session, so it also rendered over bridge chat — a live TUI where orchestration works normally.worker-releaseand leaks the dispatch's resources.What this changes for you
Starting a worker
Before —
orca orchestration worker-startcould only ever create a TUI terminal worker. If you had structured native chat set as your default for new agent tabs, your orchestration workers ignored that and came up as terminal agents anyway.After — the worker mode follows your own setting. With structured native chat on by default, a local Claude/Codex worker starts as a structured chat session. There is no flag. Where a dispatch cannot be structured — a remote
--on, a reused--terminal, a worktree-creating placement,--model/--effort, a non-Claude/Codex agent, WSL, Codex on Windows — it still starts, as a terminal worker, and the receipt names which mode ran and why. Nothing is refused for being unstructurable, and nothing falls back silently.Orchestrating a structured chat session at all
Before — a session created directly as structured chat was invisible to orchestration, not merely refused. It could not be started as a worker, could not be named as a dispatch target, and could not receive mail. Orchestration resolves every worker through a terminal handle and pane key backed by a live PTY, and a structured session has neither.
After — structured sessions are first-class orchestration workers:
worker-start, dispatch, mail,worker_done,worker-show,worker-read,worker-stop,worker-abandon,worker-releaseall work.Mail to a worker whose pane is in structured chat
Before — if a worker's pane was adopted into Structured Chat, orchestration mail to it silently queued. The chat pane showed an "Orchestration paused" banner — which was also shown over ordinary bridge chat, where orchestration worked perfectly well.
After — mail is delivered into the session as a turn. The banner is gone, because it is no longer true anywhere.
A worker reporting back
Before — a structured worker running the
worker_doneline it was taught would fail capability verification, and the message was converted to a rejection. The dispatch never settled, the coordinator'scheck --waitblocked to its timeout, and the worker could retry in a loop.After — a structured worker's identity resolves host-side like any other, so
send,check,ask,replyandworker_doneall behave identically to a terminal worker's.Reading, stopping and releasing a structured worker
Before —
worker-readthrewworker_identity_changedfor a worker whose identity had not changed.worker-stopreturned three separate "could not confirm" receipts and never actually stopped the provider child.worker-releasefailed witharchive_failed, so the dispatch's resources were never freed.After — read serves the session journal, stop routes to the real session close and only settles on a proven exit, and release archives the journal instead of failing.
This is the one change here that is not scoped to structured sessions. It alters shipped
orcaCLI behaviour for ordinary PTY terminal workers.What changed. When an orchestration command has to work out which terminal the caller is — an implicit
--from, i.e. no--fromflag and noORCA_TERMINAL_HANDLEin the environment — it used to fall back through three guesses in order:activeLeafId(the last-focused pane),All three answer "which terminal am I?" with someone else's pane. For an identity claim, all three are now skipped, and the command refuses with
no_active_terminal— surfaced by the CLI asno_active_sender_terminalwith guidance — whenever more than one terminal in that worktree could have been meant. The same refusal applies on the graph-not-ready path, which had the identical arbitrary pick.Who notices. Anyone running
orca orchestration send/ask/ a lifecycle verb without--fromand withoutORCA_TERMINAL_HANDLEset, in a worktree containing more than one terminal. That used to succeed silently against an arbitrary terminal; it now fails with an actionable error telling you to pass--from. A worktree with a single terminal is unaffected, and any caller that passes--fromor has the env var — which is every agent Orca launches — is unaffected.Why it is worth the break. The arbitrary pick was a real misattribution, not a cosmetic one: a bare
send --type worker_donecould settle a sibling's context-only dispatch — a tier with no capability token to reject on — and every message sent that way was attributed to the sibling terminal.Scope. Only the implicit-sender resolution opts in (
resolveImplicitOrchestrationSender).orca terminal …and every othergetTerminalHandlecaller pass no option and are byte-for-byte unchanged.orchestration checkresolves through the--terminalscope, which still guesses and is untouched by this PR.What an agent sees
Before — n/a (structured workers did not exist).
After — nothing mode-specific. The dispatch preamble is byte-identical either way, a structured worker can dispatch sub-workers exactly like a terminal one, and the orchestration skill guide needs no "if structured…" caveat anywhere. The worker mode is a runtime detail, not part of the orchestration contract.
CLI parity — what works, and what does not
An audit after the first review round found that structured workers were second-class across the CLI in ways the earlier description overclaimed. Nine of eleven gaps are fixed here; two are deferred with reasons. A later round then found a silent-misdelivery defect in one of this PR's own new verbs, fixed below. This section is the honest picture.
Fixed in this PR
orca worktree rmno longer destroys a live structured session. It previously ran three PTY-derived sweeps and nothing else, so a worktree containing only structured sessions looked empty: removal proceeded, the provider child kept running with itscwddeleted, the dispatch stayeddispatched, andworker-showreported the worker healthy and live. Uncommitted work was lost. A new sweep now refuses without--force, and closes properly with it. This is a new failure on a destructive verb — see the behaviour-change note below.run-create,task-create,worker-start, the gate verbs,dispatch, …) resolved the caller by validatingORCA_TERMINAL_HANDLEthroughterminal.show, which has no structured branch, so every one failed withno_active_sender_terminal— including the sub-dispatch commands the preamble itself teaches. A new read-onlyterminal.resolveIdentityanswers for both lanes.dispatch --to … --injectno longer reportsno_agent_detectedfor a session that has an agent.@all,@idle,@claude,@codex,@worktree:) no longer silently omits structured workers.@idlereads liveness from the full journal timeline, because a bounded page reads a busy worker as idle.run:mail now nudges a structured coordinator. Both delivery lanes previously declined it, each believing the other owned that mailbox.worker-releaseno longer closes a session a user has taken over. The takeover signal was PTY-only, so theuser_ownedguard was intact but never armed — and the spec explicitly promises the opposite.orchestration checkno longer consumes a sibling's mailbox. Such sessions have no orchestration identity, socheckresolved to a neighbouring pane and destructively consumed its batch. They now carry a marker and the command refuses instead of guessing.orca terminalverbs refuse with an accurate reason pointing at the structured equivalent, instead of claiming the handle went stale.orca orchestration worker-read --source transcriptno longer silently misdelivers. Its cursor fingerprinted only the oldest item on the page, so it could not detect the page being revised underneath a poller. A coordinator watching a worker could skip lines it never saw, or re-read lines it already had, with no signal either way — the failure was silent in both directions. The cursor now anchors on the oldest item plus every item below the caller's position, by id and revision. Ablated both ways: reverting to the old anchor reddens exactly the two silent shapes (in-place revision, mid-array insert) and nothing else; widening the anchor to the whole page reddens unread-tail growth. The frozen archive keeps a constant identity, since nothing there can be revised under a caller.Not fixed — deferred, with reasons
terminal listandworktree psdo not show structured workers, so a worktree with a busy structured worker reads as idle to an agent — while the desktop sidebar already shows it running. An investigation split this into two changes rather than one, and both ship separately from this PR.worktree psshould get them: it is main-process only and needs no wire change —RuntimeWorktreeAgentRowis already a non-PTY shape (paneKey,state,agentType, with noptyId,connectedorwritable), both inputs already exist, and the status mapping is already written in the renderer and simply never crosses into main.terminal listshould not. Every safe consumer of a terminal summary checksptyId, but the breaking ones key offconnectedor mere row presence, which no added field can qualify: mobile mounts a terminal WebView per row that can never receive a frame; aconnected && !inSessionTabscheck goes permanently true and pins shipped mobile clients to a fast refresh cadence with no exit; and in main, a worktree holding one PTY plus one structured session starts refusing caller identity claims from the row count alone. The plugin projection has no field that can carrywritable: falseat all. The follow-up instead publishes an honest partial-listing count — "N agent sessions not listed" — which needs no handle and no pane key.terminal readon a structured worker does not support cursor paging, and no windowed read should be added later. It returns the recent tail; a cursor read refuses. An earlier revision of this section gave the wrong reason — it claimed the journal had stable item identity and onlyterminal.read's numeric cursor stood in the way, and the refusal text acted on that by pointing callers at another verb. Both are corrected here. The journal is a reduced, mutable timeline: a tool item gains its result text at its original sequence after later items already exist, the delta coalescer revises items repeatedly, settlement can rewrite an item smaller, a pending approval renders as nothing and then as something, andsequenceresets on epoch rollover. No bare position index survives that, numeric or opaque. The decisive point is the failure direction: a broken cursor fails unsafe, as a silent hole in a poller's output (precisely the defect fixed above), while diffing a bounded tail fails safe, as a harmless re-read. The refusal now states the approach that works — the tail is bounded and newest-last, so poll it and diff — and deliberately names no alternative verb, because there is none. Read this together with theworker-readcursor fix above: they are one decision, not two. What makes that cursor sound is not merely that it is opaque, but that it is opaque enough to carry a fingerprint of the already-delivered prefix — so a revision under the caller is detected and answered withsource_changedrather than silently skipped.terminal.read's cursor is a barenumberwith nowhere to put that fingerprint, and its result shape has nosource_changedto answer with, so the same revision would pass undetected. Both surfaces refuse loudly rather than misdeliver; only one of them can page at all.orca worktree rmcan now refuseRemoving a worktree that contains a live structured chat session now fails unless
--forceis passed. This is deliberate and mirrors the existing unstopped-PTY gate, but it is a new refusal on a command people run frequently, and it is the change most likely to surprise.--forcecloses the sessions properly rather than orphaning their provider children.Merged with the durable multi-agent workflow work (#16904)
That PR landed in this same subsystem, so a good part of this branch is now a decision about which of two independent solutions survives. It never generalized past the PTY assumption anywhere, so nothing here became redundant: it hardens the first authority source, this branch adds a second under the same contracts.
current < 31migration from a shared base of 30, with different bodies, and main went on to 38 — so 31 named two different schemas, and a database written by this branch failed the skew checker and replayed from v6. That is the checker working correctly, and the replay is row-safe (everyDROPin the chain is a copy-forward rebuild gated on shape; noDELETE, noTRUNCATE). Nothing shipped stamped 31 with this content — the commit is in no tag and no release branch — so the migration renumbers to 39. It no longer createsstructured_pointer_operations, becausecreateTablesruns unconditionally on every open ahead of migration; only the widened archiveCHECKneeds a migration, sinceIF NOT EXISTScannot widen a constraint.summarizeWorkerOutputArchiveJSON-parses every non-transcript_pinkind as a terminal tail, so this branch'sstructured_journalreachedcontent.lines.every(...)and threw, at three live call sites. A structured session's journal now reports astranscript— it is the session's transcript, and a thirdsourcewould leak the structured/terminal split into a CLI surface this PR keeps uniform.LIMIT. Main's simplification is adopted, its lane now calls the shared selector, and the helper's docblock no longer claims to catch a mid-selection waiter, which cannot happen. Nothing covered any of this, so it now has tests against a real database.run:mailboxes on the premise that a delivery row exists only for arun:address. Main made that false and generalized correctly, keying the lookup on the exact handle being nudged. Adopted — and worth more here than in the PTY lane, since a structured nudge costs a whole provider turn.One regression this merge restores, which is main's rather than this branch's: the shared ancestor passed
canDispatchSubWorkerson the local worker's dispatch preamble; main's extraction ofstartLocalWorkerdoes not, andbuildDispatchPreambletreats its absence as false. So a locally started worker on main is no longer taught the sub-dispatch verbs, and with the default nested depth of 1 that applied to every first-generation worker. Main still passes the same argument at three other call sites, so this reads as a line lost while moving ~300 lines. Restored here for both lanes. Worth fixing on main independently of this PR.Notes for reviewers
terminal.resolveIdentityis new, and a client hitting an older host getsmethod_not_foundand falls back toterminal.show— safe, because a host without the probe has no structured workers to miss.orchestration.workerTerminalUserInputwidened from a requiredpaneKeytopaneKey | sessionId; an older host rejects the new shape at validation and the report, being best-effort, degrades silently to today's behaviour. Worth reviewing as a pair.ORCA_STRUCTURED_SESSION=1is a new child-env contract. It carries nothing else — no handle, no pane key, no session id, no token — and deliberately does not add the CLI PATH prepend, so it can only ever cause a refusal, never enable a command that previously could not run. The session id is omitted on purpose: a session id is one tab-id hop from the pane key, and the pane key is a credential.getLiveLeafForHandlethrows a different error for structured handles, which changesclassifyTerminalProcessInspectionFailurefromterminal_goneto unclassified for those handles. That is an improvement —terminal_gonewas itself a false claim, since the session is alive — but it is a classification change at a widely-called choke point.@idleperforms a full journal reduction per structured worker per group send. Required for correctness; negligible at current worker counts, but relevant if fan-out grows.max-lines. Noteorchestration.test.tswas sitting at exactly 800 lines before this branch touched it — one line from breaking for anyone.Why a structured worker gets a handle and a pane key
A structured session has no PTY, so it is fair to ask why it is given a terminal-shaped handle and a pane key at all.
Because those are not a claim that a terminal exists — they are orchestration's identity primitive. Dispatch rows, mail routing, capability verification and the worker-lifecycle verbs are all keyed on a handle plus a pane key. Every worker needs one. Giving a structured session those two facts is not dressing it up as a terminal; it is giving it the same identity every other worker already has.
The alternative — teaching orchestration a second kind of target — would push the distinction all the way out to the agents. A worker would have to know which kind it is before choosing a verb, a coordinator would have to branch on it, and the orchestration skill guide would need an "if structured… otherwise…" caveat on most of its commands. That guide is loaded into every orchestrating agent's context, so the cost is paid on every session, in exchange for a distinction that is irrelevant to the work the agent is doing. It is also a reliable source of bugs: agents branching on a runtime detail they cannot verify will get it wrong.
So the uniformity is deliberate, and it is scoped to the contract layer: what an agent is taught, what it runs, and what it reads back. The orchestration skill guide required no changes for this PR, which is the practical evidence that the abstraction holds.
Where the abstraction deliberately stops. The moment something asks a process question rather than an identity question, a structured session answers honestly or refuses — it never fabricates:
terminal.showdoes not resolve a structured handle. It returns aptyId, a leaf id and a pane runtime id, and synthesising those would hand every caller of a public terminal verb something that looks writable and is not.worker-showreturnsterminal: nullfor a structured worker rather than inventing a terminal summary.live/unverifiable/exited. Squashing that intoconnected: booleanwould report a running worker asexitedon loss of contact — the inversiondocs/reference/ssh-execution-boundary.mdforbids.ptyIdandlaunchTokenHashempty, which is what keeps hook attestation closed for a session that has no PTY, no launch secret and no hook to attest with.The one fact
worker-startgenuinely needs from a coordinator — its worktree id — is resolved from the dispatch authority rather than by routing throughshowTerminal, precisely so that no fake terminal has to be produced to get it.A consequence worth stating: because the pane key is part of orchestration's identity, and
orchestration.checkis identity-gated rather than capability-gated, the pane key is effectively a credential. That is why a structured worker's pane-key leaf is randomly minted and persisted rather than derived from anything guessable, and why there is a test that fails if it is ever "simplified" back to a derivable value.Agents cannot tell which mode they are in
The worker mode is an implementation detail of the runtime, not part of the orchestration contract. Neither a worker nor a coordinator is taught, or asked to read, anything that differs by mode.
canDispatchSubWorkersis depth-only. A structured worker dispatches sub-workers exactly like a PTY one — proven withshowTerminalmocked to reject and asserted never called.worker-readpresents uniformly; a coordinator never branches on mode.Three residual asymmetries are documented rather than hidden, none referenced by any instruction an agent reads:
modeexists in theworker-startreceipt JSON (the CLI prints the reason for humans; nothing tells an agent to read the field);worker-showreturnsterminal: nullfor a structured worker; andterminal.showdoes not resolve a structured worker handle, becauseconnected/writablederive from a single boolean that cannot express the three-valued liveness verdict andptyIdhas no honest value.Tab visibility (resolved by #18906)
A structured worker's tab was initially invisible in the renderer: the session was addressable and its transcript readable, but the tab never reached the tab bar.
That was a pre-existing renderer defect which this change was simply the first to make reachable — the normal user launch path self-heals, and orchestration has no renderer-side launcher to do so. A publication epoch is inherited rather than minted per generation, so once a live publisher's epoch had been retired by a transient interloper, every later frame reusing it was dropped permanently.
Fixed separately in #18906, now merged and included here.
Out of scope
canDispatchSubWorkersis depth-only and mode-independent.--on, a reused--terminal, a worktree-creating placement,--model/--effort, a non-Claude/Codex agent, WSL and Codex-on-Windows each fall back to a terminal worker with a named reason in the receipt.Testing
pnpm tcclean,oxlintclean,oxfmtclean.Merged with
main, which landed a native-chat routing fix in that span. Both conflicts were the same shape: main fixed code this branch had already extracted elsewhere, so keeping either conflict side alone would have silently reverted it. Main's own routing test was red on the merge before the ports and green after, which is what proves they are load-bearing rather than cosmetic. Full suite after the merge: 1920 files / 20111 tests passed, 0 failed,pnpm tcclean, tree clean.Unit and integration coverage for the identity registry, the four getters, the delivery lane, operation-id lifetime, the hold, stop/abandon/release settlement, the archive round-trip, and the v31 migration's old-row survival. The security invariants above each have a dedicated pin, and the
ptyId-emptiness pin was ablated to confirm it actually reddens.Validated in isolated Electron instances against real Claude and Codex sessions, with instance ownership proven each time and the structured-chat settings seeded before first paint.
Verified in the running app for both providers: a structured worker starts, its dispatch preamble is visible in the chat,
worker_donesettles the dispatch,worker-readreturns the session journal,worker-stop/worker-releasesettle, and the "Orchestration paused" banner is absent.Precisely what the mail evidence covers. The structured nudge — a user turn reading "You have N orchestration messages…" — was observed directly for Codex. For Claude, the worker under test was parked on
orchestration check --wait, so the mail reached it through the long-poll waiter rather than the structured pointer lane; an open waiter deliberately suppresses pointer delivery, so that run did not exercise this PR's delivery path for Claude. That case is being re-run against a Claude worker with no waiter open, including a mid-turn send retained and delivered once on settle. Screenshots are on the PR.Structured sessions require a local execution host and no WSL, so this cannot be a mobile, Windows/WSL or SSH change; those lanes were skipped by design rather than overlooked.