Skip to content

fix(status): gate sleeping worktrees on live PTYs - #9665

Closed
OrcaWin wants to merge 1 commit into
mainfrom
OrcaWin/cross-client-agent-status-spinner
Closed

OrcaWin wants to merge 1 commit into
mainfrom
OrcaWin/cross-client-agent-status-spinner

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • fix sleeping worktree cards that stayed green when retained/fresh done metadata outlived every live PTY
  • make remote worktree.ps liveness depend on connected runtime leaves or PTYs with current persisted/explicit pane ownership, not saved wake hints, shutdown hints, or unowned provider records
  • keep the sidebar, Hide sleeping, paired desktop clients, and mobile/web runtime projection on the same live-PTY/browser contract

Deterministic reproduction: after sleep, the runtime graph had no connected leaves, the live PTY layout was empty, and retained done rows remained. Hide sleeping correctly classified the worktree inactive, while resolveWorktreeStatus promoted the retained row to green done. Both Windows and paired macOS showed the same wrong dot because they consumed the same runtime-owned state.

Screenshots

Not included. This removes an incorrect transient/persisted status dot; deterministic store/runtime tests cover the exact state transitions without relying on screenshots.

Testing

  • pnpm lint — full CI lint passed
  • pnpm typecheck
  • pnpm test — full CI test suite passed
  • pnpm build — unpacked-app build and packaged CLI smoke passed in CI
  • Added or updated high-quality tests that catch the regression

Validation on current main:

  • 818 focused tests passed across orca-runtime, worktree-status, and use-worktree-activity-status; one unrelated known Windows path fixture was excluded by test name
  • changed-file oxfmt --check and oxlint passed
  • all three TypeScript configurations passed
  • 44 reliability gates passed
  • max-lines ratchet passed with no new bypasses
  • git diff --check passed

Coverage includes empty versus absent live-PTY layouts, saved PTY/session wake hints, unowned provider records, connected graph leaves, explicit pre-persistence ownership, layout-before-tab reconnect ordering, multi-pane sleep/wake, failed reattach, true live background PTYs, stale done/waiting/working rows, browser activity, and immediate sleep/wake transitions without TTL expiry or sleeps.

AI Review Report

The requested internal review skill is not installed in this Windows session, so four manual merge-base-anchored adversarial rounds checked:

  1. Scope: the final commit changes only five sleeping-status/runtime-liveness files; all Codex finality, Stop handling, spinner, reduced-motion, relay, and unrelated markdown changes were removed.
  2. Semantics: compared Hide sleeping, resolveWorktreeStatus, StatusIndicator inputs, worktree.ps, and the live-PTY invariant from fix: gate worktree status on live PTYs so sleep reports inactive #1603. Retained/fresh completion can no longer promote an otherwise sleeping card.
  3. Remote ownership: checked current-main runtime graph/session changes, reconnect ordering, stale provider samples, persisted layouts, explicit spawn-time bindings, multiple panes, browser-only activity, and paired clients consuming the same state.
  4. Performance/elegance: verified linear indexing only when worktree.ps runs, no per-card timers or render-loop work, clean formatting/types/lint/gates, and no provider-specific behavior.

Cross-platform review covered macOS, Linux, Windows, local, SSH, WSL, paired runtimes, and mobile/web projections. No shortcuts, labels, filesystem paths, shell behavior, or platform-specific Electron behavior changed.

Security Audit

  • no dependencies, auth flows, secrets, IPC methods, shell commands, Git commands, or external process execution were added
  • runtime-owned PTY identifiers are only used for in-memory ownership/liveness attribution
  • no new untrusted input reaches command execution or filesystem APIs

No security follow-up is required.

Notes

  • This PR intentionally does not change reduced-motion spinner behavior or Codex intermediate-Stop/finality behavior; those can be revisited separately.
  • Strict ownership can briefly report inactive for malformed legacy snapshots that have neither a persisted layout binding nor an explicit runtime pane binding. Normal reconnect and pre-persistence orderings have dedicated fallbacks and tests.
  • The added worktree.ps indexing is O(tabs + layout PTYs + live PTYs). A synthetic Windows run over 1,000 tabs and 4,000 PTYs measured about 0.275 ms per call; it is not a renderer hot path.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Updates runtime worktree summaries to resolve PTY ownership from persisted session layouts and current pane bindings, count only live attached PTYs, and apply saved worktree status. Tests cover sleep/wake, reconnect, remote panes, missing layouts, stale ownership, and deferred reattach hints. Renderer status resolution now suppresses retained or fresh completion when no live PTY exists, with coverage for cached summaries and sleep/wake transitions.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and directly reflects the main change: gating sleeping worktrees on live PTYs.
Description check ✅ Passed The description follows the template and includes summary, screenshots, testing, AI review, security audit, notes, and cross-platform confirmation.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 36da927c-ac01-49d2-b3f7-2b7f1ad56fb4

📥 Commits

Reviewing files that changed from the base of the PR and between 995ee88 and 8c4f4bf.

📒 Files selected for processing (20)
  • src/main/agent-hooks/codex-stop-finality.test.ts
  • src/main/agent-hooks/codex-stop-finality.ts
  • src/main/agent-hooks/server-codex-stop-finality.test.ts
  • src/main/agent-hooks/server-runtime-codex-stop-finality.integration.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/index.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-server.test.ts
  • src/relay/agent-hook-server.ts
  • src/renderer/src/components/AgentWorkingSpinner.test.tsx
  • src/renderer/src/components/sidebar/use-worktree-activity-status.test.tsx
  • src/renderer/src/lib/agent-spinner-clock.test.ts
  • src/renderer/src/lib/worktree-status.test.ts
  • src/renderer/src/lib/worktree-status.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.ts

Comment thread src/main/agent-hooks/server.ts Outdated
Comment on lines +887 to +898
if (
previous?.payload.state === 'done' &&
previous.payload.agentType === 'codex' &&
effectivePayload.payload.state === 'done' &&
effectivePayload.payload.agentType === 'codex' &&
effectivePayload.hookEventName === 'Stop' &&
previous.turnId !== undefined &&
previous.turnId === effectivePayload.turnId &&
equivalentParsedAgentStatusPayload(previous.payload, effectivePayload.payload)
) {
return previous
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Add a "why" comment for the redundant-Stop dedupe.

This block (matching turnId + equivalent payload on an already-done codex Stop) is non-obvious — it's undocumented while the adjacent deferral-trigger block (899-921) and deferCodexStop both carry explanatory "Why:" comments.

As per path instructions, **/*.{ts,tsx}: "For non-obvious TypeScript code, add a concise comment explaining why the constraint exists, not how the code works."

📝 Suggested comment
+    // Why: a duplicate/replayed Stop for the same turn that's already been
+    // confirmed done must not re-publish or re-emit a completion signal.
     if (
       previous?.payload.state === 'done' &&
📝 Committable suggestion

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

Suggested change
if (
previous?.payload.state === 'done' &&
previous.payload.agentType === 'codex' &&
effectivePayload.payload.state === 'done' &&
effectivePayload.payload.agentType === 'codex' &&
effectivePayload.hookEventName === 'Stop' &&
previous.turnId !== undefined &&
previous.turnId === effectivePayload.turnId &&
equivalentParsedAgentStatusPayload(previous.payload, effectivePayload.payload)
) {
return previous
}
// Why: a duplicate/replayed Stop for the same turn that's already been
// confirmed done must not re-publish or re-emit a completion signal.
if (
previous?.payload.state === 'done' &&
previous.payload.agentType === 'codex' &&
effectivePayload.payload.state === 'done' &&
effectivePayload.payload.agentType === 'codex' &&
effectivePayload.hookEventName === 'Stop' &&
previous.turnId !== undefined &&
previous.turnId === effectivePayload.turnId &&
equivalentParsedAgentStatusPayload(previous.payload, effectivePayload.payload)
) {
return previous
}

Source: Path instructions

Comment thread src/main/agent-hooks/server.ts Outdated
Comment on lines +899 to +921
if (
options?.codexStopConfirmed !== true &&
this.codexStopFinalityResolver !== null &&
previous?.payload.state !== 'done' &&
effectivePayload.payload.agentType === 'codex' &&
effectivePayload.payload.state === 'done' &&
effectivePayload.hookEventName === 'Stop'
) {
// Why: relay ordering can deliver an old turn's Stop after the next turn
// is already working; provider identity is stronger than arrival order.
if (
previous?.turnId &&
effectivePayload.turnId &&
previous.turnId !== effectivePayload.turnId
) {
return previous
}
this.deferCodexStop(effectivePayload)
// Why: reconnect can replay Stop after connection cleanup removed the
// prior row; return timing metadata to the HTTP retry path without
// publishing completion before terminal authority confirms it.
return previous ?? this.attachStatusTiming(effectivePayload, now)
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for existing coverage of "Stop arrives while previous status is already
# 'done' from an older/different turn" in the Codex finality test suite.
rg -n -B3 -A15 "previous.*'done'|payload.state === 'done'" src/main/agent-hooks/server-codex-stop-finality.test.ts

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant file and inspect the surrounding implementation.
ast-grep outline src/main/agent-hooks/server.ts --view expanded | sed -n '1,220p'

echo '--- server.ts around the cited lines ---'
sed -n '860,960p' src/main/agent-hooks/server.ts

echo '--- nearby codex stop finality tests ---'
fd -a 'server-codex-stop-finality.test.ts' src/main || true

Repository: stablyai/orca

Length of output: 11216


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search for the exact branch and related Stop/done handling across the repo.
rg -n -C 4 "codexStopConfirmed|codexStopFinalityResolver|deferCodexStop|hookEventName === 'Stop'|previous\?\.payload\.state !== 'done'" src/main

Repository: stablyai/orca

Length of output: 7779


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the test file that covers Codex stop finality if present.
fd -a 'server-codex-stop-finality.test.ts' .

Repository: stablyai/orca

Length of output: 226


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read the specific function body around the stop-finality branch.
python3 - <<'PY'
from pathlib import Path
p = Path('src/main/agent-hooks/server.ts')
text = p.read_text()
needle = "if (\n      options?.codexStopConfirmed !== true"
idx = text.find(needle)
print("idx", idx)
print(text[idx-500:idx+1200] if idx != -1 else "needle not found")
PY

Repository: stablyai/orca

Length of output: 1862


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the function and any codex-stop finality tests around the branch.
python3 - <<'PY'
from pathlib import Path
p = Path('src/main/agent-hooks/server.ts')
lines = p.read_text().splitlines()
for i in range(860, 960):
    if i <= len(lines):
        print(f"{i+1:4d}: {lines[i]}")
PY

echo '--- tests ---'
fd -a 'server-codex-stop-finality.test.ts' src/main . 2>/dev/null || true

Repository: stablyai/orca

Length of output: 4846


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the Codex stop finality tests for same-turn vs cross-turn cases.
sed -n '1,260p' src/main/agent-hooks/server-codex-stop-finality.test.ts

echo '--- search for turnId / done / Stop coverage ---'
rg -n -C 3 "turnId|codexStop|Stop|done|finality" src/main/agent-hooks/server-codex-stop-finality.test.ts

Repository: stablyai/orca

Length of output: 20518


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the rest of applyNormalizedStatus to confirm what happens after the branch.
sed -n '960,1100p' src/main/agent-hooks/server.ts

Repository: stablyai/orca

Length of output: 5058


Deferral should still run for cross-turn Stop arrivals

previous?.payload.state !== 'done' blocks finality arbitration when the cached row is already terminal, so an out-of-order Stop for a new turn falls through to the normal done path without confirmation. Move the turn-id mismatch handling ahead of that guard, or defer any codex Stop with a resolver whenever the incoming turn differs from the cached row.

Comment thread src/main/agent-hooks/server.ts Outdated
Comment on lines +973 to +989
private deferCodexStop(payload: AgentHookEventPayload): void {
const existing = this.pendingCodexStops.get(payload.paneKey)
if (
existing &&
(payload.isReplay === true ||
(existing.payload.turnId === payload.turnId &&
equivalentParsedAgentStatusPayload(existing.payload.payload, payload.payload)))
) {
return
}
if (existing && existing.payload.turnId === payload.turnId) {
// Why: transcript discovery may enrich the same Stop while terminal
// finality is pending; retain the richer payload without restarting it.
existing.payload = payload
return
}
this.clearPendingCodexStop(payload.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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show relevant ranges around deferCodexStop and nearby helpers.
sed -n '880,1035p' src/main/agent-hooks/server.ts

printf '\n==== SEARCH turnId / pendingCodexStops ====\n'
rg -n "pendingCodexStops|deferCodexStop|clearPendingCodexStop|equivalentParsedAgentStatusPayload|turnId" src/main/agent-hooks/server.ts

Repository: stablyai/orca

Length of output: 9147


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '==== payload parsing around turnId ====\n'
sed -n '1450,1595p' src/main/agent-hooks/server.ts

printf '\n==== equivalentParsedAgentStatusPayload ====\n'
sed -n '260,340p' src/main/agent-hooks/server.ts

printf '\n==== pendingCodexStops type ====\n'
sed -n '450,520p' src/main/agent-hooks/server.ts

Repository: stablyai/orca

Length of output: 11815


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '==== applyNormalizedStatus callers / stop handling ====\n'
rg -n "applyNormalizedStatus\\(|codexStopConfirmed|hookEventName === 'Stop'|state === 'done'" src/main/agent-hooks/server.ts

printf '\n==== turnId parsing / normalization helpers ====\n'
rg -n "turnId" src/main/agent-hooks/server.ts | sed -n '1,120p'

printf '\n==== any tests or comments about no turnId ====\n'
rg -n "turnId|Stop finality|pendingCodexStops|Codex Stop" -g '*.{ts,tsx,js,jsx}' .

Repository: stablyai/orca

Length of output: 16624


Guard the merge on a real turnId.
existing.payload.turnId === payload.turnId also matches undefined === undefined, so a second Codex Stop without turn_id can overwrite the first pending stop in the same pane and reuse its finality wait. Only merge when both stops carry the same defined turnId.

Comment thread src/main/agent-hooks/server.ts Outdated
Comment on lines +973 to +1031
private deferCodexStop(payload: AgentHookEventPayload): void {
const existing = this.pendingCodexStops.get(payload.paneKey)
if (
existing &&
(payload.isReplay === true ||
(existing.payload.turnId === payload.turnId &&
equivalentParsedAgentStatusPayload(existing.payload.payload, payload.payload)))
) {
return
}
if (existing && existing.payload.turnId === payload.turnId) {
// Why: transcript discovery may enrich the same Stop while terminal
// finality is pending; retain the richer payload without restarting it.
existing.payload = payload
return
}
this.clearPendingCodexStop(payload.paneKey)
const resolver = this.codexStopFinalityResolver
if (!resolver) {
this.applyNormalizedStatus(payload, { codexStopConfirmed: true })
return
}
const controller = new AbortController()
const pending = {
controller,
payload,
// Why: replay plus terminal absence is a reconnect gap, not completion;
// only a fresh Stop with no runtime-observed row may stand on its own.
acceptUnavailableCompletion:
payload.isReplay !== true && !this.runtimeObservedStatusPaneKeys.has(payload.paneKey)
}
this.pendingCodexStops.set(payload.paneKey, pending)
void resolver({
paneKey: payload.paneKey,
connectionId: payload.connectionId,
...(payload.turnId ? { turnId: payload.turnId } : {}),
signal: controller.signal
})
.then((result) => {
if (controller.signal.aborted || this.pendingCodexStops.get(payload.paneKey) !== pending) {
return
}
this.pendingCodexStops.delete(payload.paneKey)
if (
result === 'confirmed' ||
(result === 'terminal-unavailable' && pending.acceptUnavailableCompletion)
) {
this.applyNormalizedStatus(pending.payload, { codexStopConfirmed: true })
}
})
.catch((err) => {
if (!controller.signal.aborted) {
console.error('[agent-hooks] Codex Stop finality check failed', err)
}
if (this.pendingCodexStops.get(payload.paneKey) === pending) {
this.pendingCodexStops.delete(payload.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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether waitForTerminal can resolve with satisfied:false (inconclusive)
# under normal operation, and whether anything else re-drives a stuck pane.
rg -n -B5 -A20 "function createCodexStopFinalityResolver" src/main/agent-hooks/codex-stop-finality.ts
rg -n "inconclusive" src/main/agent-hooks/codex-stop-finality.test.ts

Repository: stablyai/orca

Length of output: 1342


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the resolver and the surrounding stop-handling flow.
sed -n '1,140p' src/main/agent-hooks/codex-stop-finality.ts
printf '\n---\n'
sed -n '940,1075p' src/main/agent-hooks/server.ts
printf '\n---\n'
rg -n "deferCodexStop\\(|pendingCodexStops|applyNormalizedStatus\\(|clearPendingCodexStop\\(" src/main/agent-hooks/server.ts

Repository: stablyai/orca

Length of output: 8412


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect tests and type definitions for the resolver contract and stop handling.
sed -n '1,220p' src/main/agent-hooks/codex-stop-finality.test.ts
printf '\n---\n'
sed -n '1,220p' src/main/agent-hooks/server.ts | sed -n '1,120p'
printf '\n---\n'
rg -n "CodexStopFinalityResolver|terminal-unavailable|inconclusive|codexStopConfirmed" src/main/agent-hooks -g '!**/*.map'

Repository: stablyai/orca

Length of output: 13611


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the call sites around deferCodexStop and how pending stops are cleared.
sed -n '880,940p' src/main/agent-hooks/server.ts
printf '\n---\n'
sed -n '1240,1315p' src/main/agent-hooks/server.ts
printf '\n---\n'
sed -n '1,380p' src/main/agent-hooks/server-codex-stop-finality.test.ts

Repository: stablyai/orca

Length of output: 18288


Handle inconclusive Codex finality results explicitly

inconclusive (and resolver rejections) currently clear the pending Stop without applying completion, so the pane can stay on working until another hook/replay happens. Either requeue the Stop for a later finality check or fail open to done here.

@OrcaWin
OrcaWin force-pushed the OrcaWin/cross-client-agent-status-spinner branch from 8c4f4bf to 7c198a6 Compare July 21, 2026 04:03
@OrcaWin OrcaWin changed the title fix(status): make cross-client agent state authoritative fix(status): gate sleeping worktrees on live PTYs Jul 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4cae54d5-c328-44db-8cbe-d0a71bc1cad6

📥 Commits

Reviewing files that changed from the base of the PR and between 8c4f4bf and 7c198a6.

📒 Files selected for processing (5)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/renderer/src/components/sidebar/use-worktree-activity-status.test.tsx
  • src/renderer/src/lib/worktree-status.test.ts
  • src/renderer/src/lib/worktree-status.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/lib/worktree-status.ts
  • src/renderer/src/components/sidebar/use-worktree-activity-status.test.tsx
  • src/renderer/src/lib/worktree-status.test.ts

Comment on lines +12491 to +12493
for (const tab of tabs) {
savedTabOwnerById.set(tab.id, { worktreeId, title: tab.title })
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Extract full title fallbacks and ensure title is a string to prevent runtime errors.

tab.title can be undefined, which would result in storing title: undefined in the map. Later, this undefined value would be passed to getSavedTabWorktreeStatus, which strictly expects a string, potentially causing a crash downstream in detectAgentStatusFromTitle.
Additionally, tab.title alone drops user-set customTitle or generatedTitle overrides. Extract the complete title with proper fallbacks.

🐛 Proposed fix
-      for (const tab of tabs) {
-        savedTabOwnerById.set(tab.id, { worktreeId, title: tab.title })
-      }
+      for (const tab of tabs) {
+        const title =
+          (tab as any).customTitle?.trim() ||
+          (tab as any).generatedTitle?.trim() ||
+          tab.title?.trim() ||
+          (tab as any).defaultTitle?.trim() ||
+          ''
+        savedTabOwnerById.set(tab.id, { worktreeId, title })
+      }
📝 Committable suggestion

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

Suggested change
for (const tab of tabs) {
savedTabOwnerById.set(tab.id, { worktreeId, title: tab.title })
}
for (const tab of tabs) {
const title =
(tab as any).customTitle?.trim() ||
(tab as any).generatedTitle?.trim() ||
tab.title?.trim() ||
(tab as any).defaultTitle?.trim() ||
''
savedTabOwnerById.set(tab.id, { worktreeId, title })
}

Comment on lines +12538 to +12561
const persistedTabId = savedLayoutTabIdByPtyId.get(pty.ptyId)
const persistedOwner = persistedTabId
? (savedTabOwnerById.get(persistedTabId) ??
(pty.tabId === persistedTabId
? {
worktreeId: pty.worktreeId,
title: getLatestPtyTitle(pty) ?? ''
}
: undefined))
: undefined
const parsedPaneKey = parsePaneKey(pty.paneKey ?? '')
const hasExplicitRuntimeOwner =
pty.tabId !== null && parsedPaneKey?.tabId === pty.tabId && parsedPaneKey.leafId.length > 0
const savedTabOwner = pty.tabId ? savedTabOwnerById.get(pty.tabId) : undefined
const hasSavedLayout =
pty.tabId !== null && Object.hasOwn(session?.terminalLayoutsByTabId ?? {}, pty.tabId)
const runtimeOwner =
hasExplicitRuntimeOwner && !hasSavedLayout
? {
worktreeId: savedTabOwner?.worktreeId ?? pty.worktreeId,
title: savedTabOwner?.title ?? getLatestPtyTitle(pty) ?? ''
}
: undefined
const owner = persistedOwner ?? runtimeOwner

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Merge static tab titles with the live PTY title to preserve background agent status.

When savedTabOwnerById.get returns a match, the current logic uses its static title and completely ignores the live pty.lastOscTitle. This prevents unmounted PTYs running background agents from reporting 'working' or 'permission' statuses, causing them to fall back to an inaccurate 'active' status.

To maintain perfect parity with mounted leaves (getLeafWorktreeStatus), use getLatestAgentCandidateTitle to merge the static layout title with the PTY's live title updates.

🐛 Proposed fix
-      const persistedTabId = savedLayoutTabIdByPtyId.get(pty.ptyId)
-      const persistedOwner = persistedTabId
-        ? (savedTabOwnerById.get(persistedTabId) ??
-          (pty.tabId === persistedTabId
-            ? {
-                worktreeId: pty.worktreeId,
-                title: getLatestPtyTitle(pty) ?? ''
-              }
-            : undefined))
-        : undefined
-      const parsedPaneKey = parsePaneKey(pty.paneKey ?? '')
-      const hasExplicitRuntimeOwner =
-        pty.tabId !== null && parsedPaneKey?.tabId === pty.tabId && parsedPaneKey.leafId.length > 0
-      const savedTabOwner = pty.tabId ? savedTabOwnerById.get(pty.tabId) : undefined
-      const hasSavedLayout =
-        pty.tabId !== null && Object.hasOwn(session?.terminalLayoutsByTabId ?? {}, pty.tabId)
-      const runtimeOwner =
-        hasExplicitRuntimeOwner && !hasSavedLayout
-          ? {
-              worktreeId: savedTabOwner?.worktreeId ?? pty.worktreeId,
-              title: savedTabOwner?.title ?? getLatestPtyTitle(pty) ?? ''
-            }
-          : undefined
-      const owner = persistedOwner ?? runtimeOwner
+      const persistedTabId = savedLayoutTabIdByPtyId.get(pty.ptyId)
+      const parsedPaneKey = parsePaneKey(pty.paneKey ?? '')
+      const hasExplicitRuntimeOwner =
+        pty.tabId !== null && parsedPaneKey?.tabId === pty.tabId && parsedPaneKey.leafId.length > 0
+      const hasSavedLayout =
+        pty.tabId !== null && Object.hasOwn(session?.terminalLayoutsByTabId ?? {}, pty.tabId)
+
+      let owner: { worktreeId: string; title: string } | undefined
+      if (persistedTabId || (hasExplicitRuntimeOwner && !hasSavedLayout)) {
+        const targetTabId = persistedTabId || pty.tabId!
+        const savedTabOwner = savedTabOwnerById.get(targetTabId)
+        if (savedTabOwner || pty.tabId === targetTabId) {
+          owner = {
+            worktreeId: savedTabOwner?.worktreeId ?? pty.worktreeId,
+            title: getLatestAgentCandidateTitle(
+              { title: pty.title, updatedAt: pty.titleUpdatedAt },
+              { title: pty.lastOscTitle, updatedAt: pty.lastOscTitleAt },
+              { title: savedTabOwner?.title, updatedAt: 0 }
+            ) ?? ''
+          }
+        }
+      }
📝 Committable suggestion

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

Suggested change
const persistedTabId = savedLayoutTabIdByPtyId.get(pty.ptyId)
const persistedOwner = persistedTabId
? (savedTabOwnerById.get(persistedTabId) ??
(pty.tabId === persistedTabId
? {
worktreeId: pty.worktreeId,
title: getLatestPtyTitle(pty) ?? ''
}
: undefined))
: undefined
const parsedPaneKey = parsePaneKey(pty.paneKey ?? '')
const hasExplicitRuntimeOwner =
pty.tabId !== null && parsedPaneKey?.tabId === pty.tabId && parsedPaneKey.leafId.length > 0
const savedTabOwner = pty.tabId ? savedTabOwnerById.get(pty.tabId) : undefined
const hasSavedLayout =
pty.tabId !== null && Object.hasOwn(session?.terminalLayoutsByTabId ?? {}, pty.tabId)
const runtimeOwner =
hasExplicitRuntimeOwner && !hasSavedLayout
? {
worktreeId: savedTabOwner?.worktreeId ?? pty.worktreeId,
title: savedTabOwner?.title ?? getLatestPtyTitle(pty) ?? ''
}
: undefined
const owner = persistedOwner ?? runtimeOwner
const persistedTabId = savedLayoutTabIdByPtyId.get(pty.ptyId)
const parsedPaneKey = parsePaneKey(pty.paneKey ?? '')
const hasExplicitRuntimeOwner =
pty.tabId !== null && parsedPaneKey?.tabId === pty.tabId && parsedPaneKey.leafId.length > 0
const hasSavedLayout =
pty.tabId !== null && Object.hasOwn(session?.terminalLayoutsByTabId ?? {}, pty.tabId)
let owner: { worktreeId: string; title: string } | undefined
if (persistedTabId || (hasExplicitRuntimeOwner && !hasSavedLayout)) {
const targetTabId = persistedTabId || pty.tabId!
const savedTabOwner = savedTabOwnerById.get(targetTabId)
if (savedTabOwner || pty.tabId === targetTabId) {
owner = {
worktreeId: savedTabOwner?.worktreeId ?? pty.worktreeId,
title:
getLatestAgentCandidateTitle(
{ title: pty.title, updatedAt: pty.titleUpdatedAt },
{ title: pty.lastOscTitle, updatedAt: pty.lastOscTitleAt },
{ title: savedTabOwner?.title, updatedAt: 0 }
) ?? ''
}
}
}

@OrcaWin
OrcaWin marked this pull request as draft October 27, 2026 09:47
@OrcaWin

OrcaWin commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator Author

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-07-21T04:20:39Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

@nwparker

Copy link
Copy Markdown
Contributor

Closing as superseded by merged PR #9874: #9874

The merged replacement explicitly supersedes this PR and preserves its live-PTY liveness rule while adding host-authoritative sleep teardown and verification. The branch has no commits after that merge.

Verified during the repository-wide issue/PR audit. The original branch is preserved.

@nwparker nwparker closed this Nov 16, 2026
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.

2 participants