Skip to content

feat(droid): preserve terminal ownership during child work - #47841

Open
noter wants to merge 3 commits into
stablyai:mainfrom
codeious:ac/05-d2a-droid-child-work
Open

noter wants to merge 3 commits into
stablyai:mainfrom
codeious:ac/05-d2a-droid-child-work

Conversation

@noter

@noter noter commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Droid starts helpers (subagents) in a terminal, their hooks looked like the main session's. Orca now keeps the terminal tied to the main Droid session while helpers run.

What Changed

Rebased onto main at 845867a. It depends on #47839, #47838; until they merge, this diff also shows their commits. Review only this PR's commit 2b90ad63ad.

  • Child hooks describe their own work, not the pane's lead session or resume target.
  • Keeps a provider-owned roster of child sessions and leases background work until the lead wakes.
  • Recovers mission ancestry from transcripts when a hook omits its caller.
  • Routes admission and resume ownership through provider-neutral registrations.
  • Leaves SessionEnd and process exit to a later PR.
  • Builds on fix(droid): keep a Task worker's hooks off the pane's agent row #47836 (merged, closed [Bug]: Droid subagent hooks end or reset the terminal's main session row #47826). That fix drops a Task worker's prompts and stops during the root's turn and reports a worker that outlives the root's Stop as the root itself. This PR replaces its root-turn worker set with the child roster: children show as subagents on the row, a background child keeps the row working after the root's Stop until the root wakes (10 s lease), and a finished child's late hooks stay out.
  • Keeps fix(droid): keep a Task worker's hooks off the pane's agent row #47836's droid-subagent-hooks.test.ts. Three cases change on purpose (a worker shows as a subagent; a background worker's Stop holds the lease, then settles; a finished worker's late hooks stay out). Two cases caught gaps that are now fixed: a prompt from an unseen root session takes the pane, and a sub-session with no lead in the pane settles when its own work ends.

Review fixes since the first push:

  • A lead Stop keeps the reply text it carries, so the turn's last message is not lost when a child holds the row open.
  • A child's AskUser or high-risk PreToolUse shows the row as waiting, not working.
  • A provisional lead stays repointable when a later hook names its real parent.
  • The WSL relay re-arms background-child leases after it replays its spool on startup.

Why

On main, #47836 keeps a Task worker's hooks off the row only while the root's turn is open. A worker that outlives the root's Stop reports as the root, so its own Stop marks the row done while the root has not read its result yet, and the row never shows which children are running.

Linked Issue

Follows #47836, which closed #47826; this PR covers the child-work cases listed above.

Visual Proof

N/A: verified by replaying recorded Droid hook sequences, not screenshots.

Testing

Local macOS only.

  • ORCA_CODE_QUALITY_BASE=ac/02-f5-hook-state-slots pnpm check:changed passed on this commit after the rebase (format, oxlint, typecheck, tests importing the change, selected ratchets).
  • Full unit suite (pnpm test --maxWorkers=6) on this branch: 1323 test files passed, 3 failed, 15 skipped. The failing files also fail on main at 845867a on this machine: agent-cli-update-timeout (timing), bot-upcoming-copy (locale), worktree-removal-real-git (temp-dir cleanup).
  • Golden E2E journeys ran on the previous stack tip (main at 59f3122): 8 passed, 4 skipped (Windows-only), and golden-fresh-profile-terminal failed the same way on main. Not rerun after the rebase.

Not run: Linux, Windows, or SSH remote hosts.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Changed test files:

  • src/shared/agent-hook-listener/normalization/agent-hook-listener-droid-ownership.test.ts (replays src/shared/__fixtures__/droid-subagent-hooks.jsonl, recorded from Droid 0.238.0 and 0.244.0)
  • src/shared/agent-hook-listener/providers/droid/droid-subagent-hooks.test.ts (from fix(droid): keep a Task worker's hooks off the pane's agent row #47836; updated as described above)

Performance

Small per-hook map lookups. A transcript read happens only when a child hook omits its caller.

Risk

Level: Medium

Affects Droid terminal status only. A wrong ownership decision would show the wrong session as working or resume the wrong one. Back out with a plain revert. New main-blocking-helper baseline rows need reviewer signoff.

AI Disclosure

Review

Self-reviewed this PR's single commit for correctness, security, and performance. Merge order:

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Considered security, macOS/Linux/Windows paths, SSH remote hosts, mobile compatibility, folder workspaces, and performance. Execution coverage is limited to the checks listed under Testing.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Merge message

feat(droid): preserve terminal ownership during child work

Droid child hooks still ended or reset the main session's terminal
row once a child outlived the root's turn. Replace the root-turn
worker set with a provider-owned roster of child sessions, lease
background work until the lead wakes, recover mission ancestry from
transcripts when hooks omit their caller, and route ownership
provider-neutrally.

@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

Droid hook normalization now classifies lead and child sessions, tracks child status, and derives pane status from lead and child activity. Provider-owned maps and session handling are delegated through shared interfaces. Lease expiry is generalized across Claude and Droid providers and wired into server and relay paths. The changes also add a keyed process-exit watch and tests for restarted watches.

Severity of issue fixed: Medium

Merge Risk: Moderate · up to 9db66

Droid terminals can still show the wrong status in some subagent sequences. A real lead's hooks may be ignored, or a row may stay "working" after child work ends. These are narrow edge cases, but they should be fixed or consciously accepted before merging.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description follows the repository template and covers the ELI5, what changed, why, testing, performance, risk, review, and checklist sections. It explains the Droid child-hook ownership fix, link… 1) Add a real linked issue in the 'Linked Issue' section using 'Fixes #', or state the reason no issue exists. 2) Reconcile the commit reference: the description names 2b90ad6 and the objectives name 59c5468. Use one commit ha…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title 'feat(droid): preserve terminal ownership during child work' matches the main change: Droid child/subagent hooks no longer overwrite or reset the lead session's terminal row, via a provider-…
Linked Issues check Passed The only linked issue, #47826, is closed and completed. Under the assessment rules it supplies background only, so no active directly linked target remains and no linked-issue coding requirements appl…
Out of Scope Changes check Passed Most changes connect to Droid child-session ownership or to the provider-neutral lease mechanism that the PR introduces: provider-hook-state-slots.ts, provider-hook-session.ts, droid-hook-session.ts, …
Full details: Title check

Explanation

The title 'feat(droid): preserve terminal ownership during child work' matches the main change: Droid child/subagent hooks no longer overwrite or reset the lead session's terminal row, via a provider-owned roster of child sessions and lease handling. It is concise, specific, and uses the conventional commit format. The title does not mention the lease and transcript-recovery parts, which is acceptable because it need not cover every detail.

Full details: Linked Issues check

Explanation

The only linked issue, #47826, is closed and completed. Under the assessment rules it supplies background only, so no active directly linked target remains and no linked-issue coding requirements apply. The PR objectives and the issue text were used as context. The PR still implements the behavior described in #47826: child Droid hooks are admitted as child work through a provider-owned roster (droid-sessions.ts, droid-session-status.ts), and child Stop or SessionStart events no longer end or reset the lead row (droid-events.ts). The replay test droid-subagent-hooks.test.ts and the fixture-based ownership test cover these cases. This is informational only and does not affect the verdict.

Full details: Out of Scope Changes check

Explanation

Most changes connect to Droid child-session ownership or to the provider-neutral lease mechanism that the PR introduces: provider-hook-state-slots.ts, provider-hook-session.ts, droid-hook-session.ts, droid-lease-expiry.ts, agent-lease-expiry-timers.ts, hook-lease-expiry-timers.ts, listener-state.ts, pane-state-claims.ts, normalize-hook-payload.ts, provider-dispatch.ts, and droid-transcript-origin.ts. The Claude owed-notification timer replacement (claude-owed-notification-expiry-timers.ts), the server cleanup and lifecycle changes, and the WSL guest retry-scheduler and server changes follow from routing lease expiry through the shared mechanism. The fixtures, test-support files, and baseline entries support the replay tests. The PR description states that the diff also contains commits from earlier stack PRs #47837 through #47840, including agent-process-exit-watch.ts and its test and the config test guard. Those files are attributable to earlier stack PRs and are not unrelated to this PR. Attribution rests on the author's disclosure and was not verified against commit history, so this is a PASS with that dependency noted.

Full details: Description check

Explanation

The description follows the repository template and covers the ELI5, what changed, why, testing, performance, risk, review, and checklist sections. It explains the Droid child-hook ownership fix, links the predecessor PR #47836, and states the risk level and back-out method. Gaps remain. The 'Linked Issue' section says 'Follows #47836' and names no issue with 'Fixes #', although the template requires an issue link for outside contributors. The 'Visual Proof' section is marked N/A with a reason. The 'Testing' section leaves the manual-testing and lint/typecheck/build checkboxes unchecked, and the 'Performance' section gives a reasoned answer. The 'Merge message' section and the 'AI Disclosure' placeholder are extra or unfilled. The description also cites two different commit hashes (2b90ad6 and 59c5468) and the objectives cite a different commit, so the reviewer cannot tell which commit to review. The Testing section says 'Not run: Linux, Windows, or SSH remote hosts', which does not meet the template's note on the platforms tested.

Resolution

  1. Add a real linked issue in the 'Linked Issue' section using 'Fixes #<number>', or state the reason no issue exists. 2) Reconcile the commit reference: the description names 2b90ad6 and the objectives name 59c5468. Use one commit hash. 3) Confirm whether the pnpm lint, typecheck, test, and build checks passed, and tick the matching checklist items. 4) Tick or explain the unchecked 'I manually tested these changes locally' item. 5) Remove or move the 'Merge message' section outside the description. 6) Fill in the AI Disclosure section if an AI model was used, or confirm the author is a StablyAI team member. 7) Note the platforms tested in the Testing section and the outcome of the golden E2E failure on the branch.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 9

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Arm expiry for background-child leases restored from the spool. · agent-hook-server.ts:129-138

src/wsl-guest/agent-hooks/server/agent-hook-server.ts:129-138
Minor · Functional Correctness · Quick win

Arm expiry for background-child leases restored from the spool.

Startup replays spooled Droid hooks through drainRelayHookSpool and applyEvent, and that path never calls armLeaseExpiry. The live request path does. A replayed lead Stop can therefore store a pane whose background-child lease exists but has no scheduled expiry. The pane keeps the leased state until a later live hook for that pane re-arms the lease. If no later hook arrives, the pane stays in that state.

After the relay starts listening, arm expiry for each pane that has a retained background-child lease. Use the same source, env, and version the live path would pass to armLeaseExpiry.

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2d0446f1-44b2-4818-99ee-a11ef4c03927
Commits

Reviewing files that changed from the base of the PR and between 50f0c54 and 59c5468.

Files selected for processing: 46

  • config/main-blocking-helper-baseline.txt
  • config/scripts/test-runtime/environment/vitest-real-agent-home-write-guard.ts
  • src/main/agent-hooks/installation/remote-managed-hook-installers.ts
  • src/main/agent-hooks/server/server-cleanup.ts
  • src/main/agent-hooks/server/server-lifecycle.ts
  • src/main/agent-hooks/server/server-status-row-mutation.ts
  • src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts
  • src/main/droid/droid-hook-config.ts
  • src/main/droid/droid-hook-file-remote.ts
  • src/main/droid/droid-hook-script.ts
  • src/main/droid/droid-hook-status.ts
  • src/main/droid/droid-hooks-file.test-fixture.ts
  • src/main/droid/droid-org-policy.ts
  • src/main/droid/hook-service.test.ts
  • src/main/droid/hook-service.ts
  • src/shared/__fixtures__/droid-subagent-hooks.jsonl
  • src/shared/__fixtures__/droid-subagent-hooks.meta.json
  • src/shared/agent-hook-listener/hook-normalization-policy.ts
  • src/shared/agent-hook-listener/leases/agent-lease-expiry-timers.ts
  • src/shared/agent-hook-listener/leases/hook-lease-expiry-timers.ts
  • src/shared/agent-hook-listener/listener-state.ts
  • src/shared/agent-hook-listener/normalization/agent-hook-listener-droid-driver.test-support.ts
  • src/shared/agent-hook-listener/normalization/agent-hook-listener-droid-ownership.test.ts
  • src/shared/agent-hook-listener/normalization/hook-prompt-identity.ts
  • src/shared/agent-hook-listener/normalization/normalize-hook-payload.ts
  • src/shared/agent-hook-listener/pane-provider-session.ts
  • src/shared/agent-hook-listener/pane-state-claims.ts
  • src/shared/agent-hook-listener/provider-dispatch.ts
  • src/shared/agent-hook-listener/provider-hook-session.ts
  • src/shared/agent-hook-listener/providers/claude/background-tasks/claude-owed-notification-expiry-timers.ts
  • src/shared/agent-hook-listener/providers/droid/droid-events.ts
  • src/shared/agent-hook-listener/providers/droid/droid-hook-session.ts
  • src/shared/agent-hook-listener/providers/droid/droid-lease-expiry.ts
  • src/shared/agent-hook-listener/providers/droid/droid-probe-log-replay.test-fixture.ts
  • src/shared/agent-hook-listener/providers/droid/droid-session-status.ts
  • src/shared/agent-hook-listener/providers/droid/droid-sessions.ts
  • src/shared/agent-hook-listener/providers/droid/droid-transcript-origin.ts
  • src/shared/agent-hook-listener/state/provider-hook-state-slots.ts
  • src/shared/agent-hook-listener/transport/agent-hook-policy-read-paths.ts
  • src/shared/agent-status/process/agent-process-exit-watch.test.ts
  • src/shared/agent-status/process/agent-process-exit-watch.ts
  • src/shared/droid/droid-org-settings-path.ts
  • src/wsl-guest/agent-hooks/results/agent-hook-result-retry-scheduler.ts
  • src/wsl-guest/agent-hooks/server/agent-hook-request.ts
  • src/wsl-guest/agent-hooks/server/agent-hook-server.ts
  • src/wsl-guest/commands/wsl-hook-fs-bridge.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

if (existing !== null) {
await writeTextFileRemoteAtomic(sftp, `${path}.bak`, existing)
}
await writeHooksJsonRemote(sftp, path, config, { serialized })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Heavy lift

Reject a changed remote file before publishing the merged configuration.

If Droid saves hooks.json while Line 19 awaits the backup write, this call overwrites that save. config and existing still describe the earlier file. writeHooksJsonRemote checks whether the current file equals the desired output, not whether it equals the merge input. The backup also contains the earlier file.

Carry the raw merge input from readRemoteDroidHookFiles into a conflict-aware write. If the target changed, reread both files and reapply the mutation before retrying. This preserves the concurrent save and keeps unchanged installs idempotent.

Comment thread src/main/droid/droid-org-policy.ts Outdated
* is an empty policy, which is what Factory documents for an invalid one.
*/
export function orgAllowsManagedHooksOnly(orgSettingsPath: string): boolean {
return readHooksJson(orgSettingsPath)?.allowManagedHooksOnly === true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Report org hooks.hooksDisabled as a disabled-hooks state in hook coverage.

Organization settings can turn off every hook with hooks.hooksDisabled: true. The org policy readers read only allowManagedHooksOnly (droid-org-policy.ts:26 and :35). resolveDroidHookCoverage adds a disabled reason only for member-level settings (droid-hook-status.ts:23-28). With an org hooksDisabled: true and a complete Orca hook set in a member file, coverage returns installed and no reason, but Droid runs no hooks.

Pass the org hooks.hooksDisabled value into coverage. Add it to the reasons that produce partial, using the same handling as allowManagedHooksOnly.

Comment thread src/main/droid/hook-service.ts Outdated
getDroidManagedScriptFileName()
)
// hooks.json shadows the legacy entry before we remove it, avoiding double registration.
writeHooksJson(configPath, files.hooksFile, { preserveMode: true })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Security & Privacy · Quick win

Create the migrated hooks file with owner-only permissions.

On POSIX, an existing settings.json can have mode 0600 while hooks.json is absent. Installation copies user hook commands into the new file. preserveMode: true cannot preserve a mode for an absent target. With umask 0022, the writer creates that file as 0644 because Node defaults to mode 0666. (nodejs.org)

If a user hook contains an inline credential and the parent directories are traversable, other local users can now read it. Set defaultMode: 0o600 for the new file. Existing-file modes will still be preserved.

Proposed fix

--- "a/src/main/droid/hook-service.ts"
+++ "b/src/main/droid/hook-service.ts"
@@ -109,7 +109,10 @@
       getDroidManagedScriptFileName()
     )
     // hooks.json shadows the legacy entry before we remove it, avoiding double registration.
-    writeHooksJson(configPath, files.hooksFile, { preserveMode: true })
+    writeHooksJson(configPath, files.hooksFile, {
+      preserveMode: true,
+      defaultMode: 0o600
+    })
     if (settingsChanged) {
       writeHooksJson(getSettingsJsonPath(), files.settings, { preserveMode: true })
     }
Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
writeHooksJson(configPath, files.hooksFile, { preserveMode: true })
writeHooksJson(configPath, files.hooksFile, {
preserveMode: true,
defaultMode: 0o600
})

hasTranscriptPromptEvidence: false,
eventName: input.eventName,
hostTurnSignals: readHostTurnSignals(source, hookPayload, undefined),
replyCandidate: undefined

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Keep the Droid reply candidate when the session normalization branch returns early.

Droid lead events reach normalizeProviderEvent through sessionNormalization. Their normalize() call writes state.eventReplyCandidate through resolveToolState. The early branch returns replyCandidate: undefined and does not clear the field, so reply text from a lead Stop is no longer delivered. The branch also leaves the stale value in state until the next normal call. Capture and clear the field after normalize() and return the captured value.

Suggested fix

--- "a/src/shared/agent-hook-listener/provider-dispatch.ts"
+++ "b/src/shared/agent-hook-listener/provider-dispatch.ts"
@@ -66,16 +66,19 @@
   sessionNormalization?: HookSessionNormalization
 }): ProviderDispatchResult {
   const { state, source, promptText, paneKey, hookPayload, envelope, extractedPrompt } = input
   if (input.sessionNormalization) {
+    const payload = input.sessionNormalization.normalize()
+    const replyCandidate = state.eventReplyCandidate
+    state.eventReplyCandidate = undefined
     return {
-      payload: input.sessionNormalization.normalize(),
+      payload,
       resolvedPromptText: promptText,
       hasTranscriptPromptEvidence: false,
       eventName: input.eventName,
       hostTurnSignals: readHostTurnSignals(source, hookPayload, undefined),
-      replyCandidate: undefined
+      replyCandidate
     }
   }
   // Ephemeral side chats share the pane but must not replace its recorded main turn.
   const codexEventName =
     source === 'codex'

export const CLAUDE_OWED_NOTIFICATION_LEASE_PROVIDER: AgentLeaseExpiryProvider = {
lease(state, paneKey) {
// Only an idle main agent has one: the lease does not run while it is in a turn.
const idleSince = mainAgentIdleSince(state.claudeLeadStateByPaneKey.get(paneKey))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Data Integrity & Integration · Quick win

Restrict the Claude owed-notification lease to Claude rows.

lease does not check the current row's provider. Stale Claude lead or owed-task state can therefore return a Claude lease for a pane that now holds a Droid row. Because the lease selector returns the first defined lease, and the Claude provider is listed before the Droid provider, that Claude deadline can replace the Droid deadline. When the timer fires, settle publishes the Droid row with a Claude-built payload.

Return no lease unless the stored row belongs to Claude. The row check uses the same stored row that restate settles.

Suggested fix

--- "a/src/shared/agent-hook-listener/providers/claude/background-tasks/claude-owed-notification-expiry-timers.ts"
+++ "b/src/shared/agent-hook-listener/providers/claude/background-tasks/claude-owed-notification-expiry-timers.ts"
@@ -9,9 +9,12 @@
 
 /** Restates a Claude row whose owed task notifications expired without another event. */
 export const CLAUDE_OWED_NOTIFICATION_LEASE_PROVIDER: AgentLeaseExpiryProvider = {
   lease(state, paneKey) {
+    if (state.lastStatusByPaneKey.get(paneKey)?.payload.agentType !== 'claude') {
+      return undefined
+    }
     // Only an idle main agent has one: the lease does not run while it is in a turn.
     const idleSince = mainAgentIdleSince(state.claudeLeadStateByPaneKey.get(paneKey))
     const deadline =
       idleSince === undefined
         ? undefined

eventName === 'PreToolUse' ||
eventName === 'PostToolUse'
) {
showChild(sessions, id, 'working')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Preserve child input waits at PreToolUse.

When a child calls AskUser, this branch records working. The combined row therefore stays working instead of showing the child's input wait. The lead path recognizes the same tool as waiting.

Apply the AskUser and high-risk tool classification before this general working branch. Keep ordinary child tool calls working.

Comment on lines +134 to +135
if (known.provisional) {
confirmOrRepointLead(known, parentId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Functional Correctness · Heavy lift

A confirmed lead cannot move to a later root, so that root's hooks are dropped.

When a child event arrives before its parent's own event, the parent becomes the pane's provisional lead. A child event confirms it. After that, a later event that names the parent's parent (L) does not reach the repoint path. The parent's event then matches leadId, is not recorded as a child, and adoptChild returns undefined. Hooks from L are also skipped, because L is unknown to the pane. If Droid reports nested work with immediate parent IDs in this order, the pane can track the wrong root and drop the real root's hooks.

The correction must make the pane follow the true root. A later event that names a different root must either move the pane's lead to that root or record the confirmed lead as a child of it. The root's hooks must then be admitted. The choice between these two approaches is open for the author.

Confirm Droid's caller contract for nested children before merging. This concern applies only if Droid can report an immediate parent ID for a grandchild, followed by that parent's own event naming a higher ancestor.

Scope

This finding covers only the confirmed-lead repoint path in adoptChild. It does not cover SessionEnd or process-exit handling, which the PR defers.

Comment on lines +157 to +158
createSessions(state, paneKey, sessionId, false)
clearPaneTurnCacheState(state, paneKey)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Preserve known child ownership on a parentless start.

If a known child sends SessionStart without calling_session_id and its transcript is unreadable, this branch makes the child the lead and clears the lead's prompt and tool caches. Later hooks from the real lead are skipped.

Check sessions.children and sessions.finished before replacing the lead. Keep initialization for an unknown parentless lead start.

const unseen = sessionId !== sessions?.leadId && !sessions?.children.has(sessionId)
const parentId =
(isStart ? readString(hookPayload, 'calling_session_id') : undefined) ??
(isStart || unseen ? readDroidTranscriptCallingSessionId(hookPayload) : undefined)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Retry transcript recovery for a provisional lead.

If the first child hook arrives before its transcript is readable, the child becomes the provisional lead. Later ordinary hooks from that child have unseen === false, so this expression never reads its now-readable ancestry. The real lead's hooks are then skipped, and the child's Stop can mark the pane done.

Retry origin discovery while the lead is provisional. Keep parentless genuine lead hooks usable.

@noter
noter force-pushed the ac/05-d2a-droid-child-work branch from 59c5468 to 9db667e Compare November 26, 2026 11:29
…ng its end

AgentProcessExitWatch probes a pane's agent process after it reports a
session end, backing off from 250 ms to 8 s for at most 90 s, and stops as
soon as the probe confirms the exit, has nothing to check, or the pane no
longer holds what the watch started for. A probe that settles after a stop
or restart is ignored.

Hook providers whose SessionEnd can precede the process exit (a /clear also
ends a session) use it to end the row only once the process is gone.
…se timers

Provider-owned pane maps now register with ProviderHookStateSlots, so pane
teardown, moves and claim checks reach them without each map being listed
in listener-state by hand. Claude's two claim-bearing maps and its prompt
turn order move onto slots.

Claude's owed-notification timers become one lease provider behind a
generic AgentLeaseExpiryTimers, which main and the WSL relay both arm
after every stored row. Claude rows restate exactly as before.
Child hooks describe their own work, not the pane's lead or resume target.
Keep a provider-owned roster and lease background work until the lead wakes.
Recover mission ancestry from transcripts when hooks omit their caller.
Route admission and resume ownership through provider-neutral registrations.
Replace the root-turn worker set with the roster: workers that outlive the
root's Stop stay on show, and a finished worker's late hooks stay out.
A prompt from an unseen root still takes the pane; a sub-session with no
lead in the pane settles when its own work ends.
Leave SessionEnd and process-exit handling unchanged for the next slice.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d7ab6dba-be7a-4922-ba0e-73072e43a214
Commits

Reviewing files that changed from the base of the PR and between 59c5468 and 9db667e.

Files selected for processing: 14

  • config/main-blocking-helper-baseline.txt
  • src/main/agent-hooks/server/server-cleanup.ts
  • src/shared/agent-hook-listener/listener-state.ts
  • src/shared/agent-hook-listener/normalization/agent-hook-listener-droid-ownership.test.ts
  • src/shared/agent-hook-listener/pane-provider-session.ts
  • src/shared/agent-hook-listener/provider-dispatch.ts
  • src/shared/agent-hook-listener/providers/claude/background-tasks/claude-owed-notification-expiry-timers.ts
  • src/shared/agent-hook-listener/providers/droid/droid-events.ts
  • src/shared/agent-hook-listener/providers/droid/droid-session-status.ts
  • src/shared/agent-hook-listener/providers/droid/droid-sessions.ts
  • src/shared/agent-hook-listener/providers/droid/droid-subagent-hooks.test.ts
  • src/shared/agent-hook-listener/providers/droid/droid-worker-sessions.ts
  • src/wsl-guest/agent-hooks/results/agent-hook-result-retry-scheduler.ts
  • src/wsl-guest/agent-hooks/server/agent-hook-server.ts
Files with no reviewable changes: 1

  • src/shared/agent-hook-listener/providers/droid/droid-worker-sessions.ts
Files skipped from review as they are similar to previous changes: 1

  • config/main-blocking-helper-baseline.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +187 to +190
verdict:
stoppedByUser && status.stateName === 'done'
? droidVerdictFields('cancellation', Date.now())
: undefined

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Minor · Functional Correctness · Quick win

Retain cancellation while child work keeps the row active.

If a background child survives an earlier turn, it can remain active when the user interrupts the lead's next turn. The combined status stays working, so this condition drops droidVerdictFields('cancellation', ...).

applyDroidLeadEvent stores only state: 'done'. After the child stops and the lease expires, no state contains the cancellation verdict.

Store cancellation in the lead status independently of the combined row state. Preserve that verdict when the row finally becomes done, and clear it when a new lead turn starts.

Comment on lines +103 to +105
const root = chainRoot(sessions, parentId)
if (root !== sessions.leadId) {
recordChild(sessions, sessions.leadId, root)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Functional Correctness · Heavy lift

Keep the pane lead when a stopped child is the only link to it.

When a child stops, droid-session-status.ts:56 deletes its children entry, including its parentId. If a later session names that stopped child as its caller, adoptChild reaches repointProvisionalLead while the lead is still provisional. chainRoot then returns the stopped child, because it has no parent entry. The code records the real lead as a child of the stopped session and sets leadId to that session (droid-sessions.ts:102-109).

The pane's lead then becomes a finished session. Later hooks from the real lead take the child path, so the real lead no longer owns the row's status.

The ancestry of a stopped child must still resolve to the pane's real lead when a later session names that child. Keep this ancestry, or resolve the lead by another path, before repointing. Choose the retention approach that keeps cleanup bounded.

): DroidPaneSessions | undefined {
const id = previous?.providerSession?.id
return id && previous.payload.agentType === 'droid' && !previous.agentPresence?.ended
? createSessions(state, paneKey, id, false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Functional Correctness · Quick win

Restore the lead status with the session identity.

If the previous Droid row is done, this creates a confirmed lead with lead === undefined. A later child's activity makes the row working. When that child stops, outlivedStop is false, so no lease starts. resolveDroidRowStatus then defaults the confirmed lead to working indefinitely.

Restore the lead status from previous.payload.mainAgent, or from an unambiguous lead-only row. Preserve the working state when the restored lead was still working.

@noter
noter force-pushed the ac/05-d2a-droid-child-work branch from 9db667e to 2b90ad6 Compare November 26, 2026 11:47

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Droid subagent hooks end or reset the terminal's main session row

1 participant