Skip to content

[Bug]: Defer full worktree scan until after session restore - #9446

Merged
brennanb2025 merged 15 commits into
stablyai:mainfrom
Crosery:fix/defer-startup-worktree-scan
Jul 23, 2026
Merged

brennanb2025 merged 15 commits into
stablyai:mainfrom
Crosery:fix/defer-startup-worktree-scan

Conversation

@Crosery

@Crosery Crosery commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Defer the full startup worktree refresh until after persisted session hydration and terminal reconnect.

The startup-critical path now:

  • Reads the persisted workspace session before enumerating Git worktrees.
  • Scans only local repositories that have persisted terminal sessions to restore.
  • Recognizes tab-level PTYs, split-pane PTYs, and remote session IDs.
  • Normalizes legacy raw worktree IDs and canonical worktree: workspace keys before recovery selection.
  • Excludes folder workspaces, SSH repositories, and runtime-owned worktrees from local Git recovery scans.
  • Keeps the existing full worktree and lineage refresh after startup hydration.

This avoids starting one Git worktree enumeration per configured repository before the session restore path can proceed.

Screenshots

No visual change.

Testing

  • pnpm lint: ordinary oxlint passes; lint:switch-exhaustiveness is blocked by existing errors at src/renderer/src/components/skills/skill-freshness-group.tsx:101 and src/main/daemon/daemon-server.ts:680. Both files are unchanged in this PR and the errors reproduce on the rebased stably/main commit.
  • pnpm typecheck
  • pnpm test: 3,055 test files passed, 32,416 tests passed
  • pnpm build
  • Added or updated high-quality regression tests for startup ordering, raw/canonical session key matching, runtime owner exclusion, SSH preservation, deterministic recovery ordering, split-pane sessions, remote sessions, and folder workspaces
  • Focused startup, hydration, and host-persistence tests: 57 passed
  • Changed-file oxlint and oxfmt checks passed
  • Changed-file diagnostics: 0

AI Review Report

The review checked:

  • Cross-platform behavior for macOS, Linux, and Windows. The change uses existing execution-host and workspace identity helpers and adds no platform-specific shortcut, label, path, shell, or Electron behavior.
  • Local, SSH, and runtime compatibility. Recovery selection normalizes raw and canonical worktree keys, checks both supported runtime-owner map key forms, preserves SSH-owned sessions, and still limits early Git enumeration to repositories resolved to the local execution host.
  • Agent and integration compatibility. Terminal persistence is inspected through existing tab, split-layout, and remote-session fields; no agent provider, Git provider, or integration behavior changes.
  • Performance risk. The full repository scan remains outside the startup-critical path, and deterministic sorting applies only to the small set of recovery repository IDs.
  • Regression risk. Tests cover the review findings, including mixed raw/canonical session keys and startup ordering assertions using one source coordinate system.
  • UI quality. No visual or interaction behavior changes.

The review found and fixed three issues in the initial patch: mixed coordinate systems in the startup ordering test, raw/canonical session key mismatches, and nondeterministic repository ID ordering.

Security Audit

No new input handling, command execution, path resolution, authentication, secrets, dependency, or IPC behavior is introduced. The selector only reads persisted session data and filters existing repository records by normalized workspace identity and execution-host ownership.

Notes

The full worktree refresh is intentionally retained after terminal reconnect so existing catalog freshness and hydration-purge behavior remain available.

X handle: none.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR reduces renderer startup latency by deferring the full “scan all repos / enumerate all Git worktrees” refresh until after session hydration + terminal reconnect, and instead doing a selective worktree refresh only for local repos that have persisted terminal sessions to restore.

Changes:

  • Added collectWorktreeRecoveryRepoIdsFromSession to derive the minimal set of repo IDs that need early worktree enumeration for terminal reconnect.
  • Updated App.tsx startup flow to session-get before any full worktree refresh, then selectively fetchWorktrees(repoId) for the recovery subset (local-only), keeping the existing full refresh later.
  • Added regression tests for extraction logic and updated startup ordering assertions.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
src/renderer/src/lib/workspace-session-hydration-keys.ts Adds helper to extract repo IDs for selective “recovery” worktree refresh from persisted session state.
src/renderer/src/lib/workspace-session-hydration-keys.test.ts Adds unit tests covering folder exclusion, split-pane PTYs, remote sessions, and runtime-owned session filtering.
src/renderer/src/App.tsx Reorders startup to read session first, selectively refresh needed local worktrees, then perform full refresh after hydration/reconnect.
src/renderer/src/app-startup-routing.test.ts Updates startup ordering test and adds coverage for selective recovery extraction.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1476bdef-7a10-4677-bfd6-47beea095d94

📥 Commits

Reviewing files that changed from the base of the PR and between 018674d85bcce613b03406a7ccf94c64c396ba7b and 9b857c933c907a19d3b990bf31df060dfb9a9dec.

📒 Files selected for processing (4)
  • src/renderer/src/App.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/lib/workspace-session-hydration-keys.test.ts
  • src/renderer/src/lib/workspace-session-hydration-keys.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/lib/workspace-session-hydration-keys.test.ts
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/lib/workspace-session-hydration-keys.ts

📝 Walkthrough

Walkthrough

Renderer startup now hydrates the persisted workspace session before worktree enumeration, derives recoverable repository IDs, filters them to the local execution host, and fetches only that recovery set during the critical startup path. A new helper handles terminal, split-pane, remote, shutdown, and runtime-owned session cases. Tests cover recovery ID selection and the revised startup ordering, while the first full worktree scan remains after session hydration and terminal reconnect.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main change: deferring the full worktree scan until after session restore.
Description check ✅ Passed All required template sections are present and substantively filled, including testing, AI review, security audit, screenshots, and notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 073a4fe9-5429-487e-88d8-87a8d5621383

📥 Commits

Reviewing files that changed from the base of the PR and between 5848550 and 3515bf8.

📒 Files selected for processing (4)
  • src/renderer/src/App.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/lib/workspace-session-hydration-keys.test.ts
  • src/renderer/src/lib/workspace-session-hydration-keys.ts

@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@Crosery

Crosery commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Thanks for taking a look. I addressed the review findings, added regression tests, and rebased the branch onto the latest main to resolve the merge conflict. The focused tests, full test suite, typecheck, and build pass. The current head is 9b857c9 and the PR is ready for another review.

@Crosery
Crosery force-pushed the fix/defer-startup-worktree-scan branch 3 times, most recently from 9b857c9 to 04bea0e Compare July 21, 2026 03:47
@brennanb2025
brennanb2025 force-pushed the fix/defer-startup-worktree-scan branch from 04bea0e to 3c65b78 Compare July 21, 2026 04:06
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the thoughtful startup performance fix! I rebased the branch onto current main and tightened the selective scan so it covers every repository referenced by persisted workspace state—including editor, browser, active-workspace, and sleeping-agent state—not only terminals with live PTYs. The scan still skips unrelated and runtime-owned repositories, now uses the existing bounded-concurrency limit to avoid Git-process fan-out, and retains the deferred full refresh after reconnect; 116 focused startup/hydration tests, full typecheck, changed-file lint/type-aware lint, formatting, and the max-lines ratchet all pass.

Round 1 review fixes for the selective pre-hydration fetch:

- The prefetch filter gated on LOCAL_EXECUTION_HOST_ID, which excluded
  SSH repos. Old full-scan code populated worktreesByRepo for disconnected
  SSH repos via the local metadata fallback (no network), so hydrateTabsSession
  / editor / browser preserved their chrome. Excluding SSH dropped that chrome
  at hydration and setHydrationSucceeded made the loss durable. Include SSH by
  excluding only runtime-owned repos (which hydrate via placeholders instead).
- collectWorktreeHydrationRepoIdsFromSession never collected activeRepoId, so a
  repo referenced only by active-repo state (no active worktree, no tabs) was
  not prefetched, breaking hydrateWorkspaceSession's main-worktree fallback.
…scan

Round 2 review fix. The selective pre-hydration fetch only populates
session-referenced repos, so the one-shot pruneLastVisitedTimestamps at
startup no longer sees non-session repos and keeps their deleted-worktree
entries (the prune defers unloaded repos to preserve SSH focus recency).
The old full pre-hydration scan had populated all local repos before the
prune. Re-run the prune after the deferred fetchAllWorktrees so stale
lastVisitedAtByWorktreeId entries are dropped once every repo is
authoritative; disconnected SSH stays non-authoritative and is kept.
…eration

Round 3 review fix. collectWorktreeHydrationRepoIdsFromSession collected
repo ids from lastVisitedAtByWorktreeId and defaultTerminalTabsAppliedByWorktreeId,
which accumulate one entry per worktree ever focused / given default tabs.
On the long-lived large profile this fix targets (stablyai#9441), those maps
reference nearly every repo, so the 'selective' pre-hydration fetch
degenerated back toward the full all-repos scan the fix removed.

Split the keyed-field list: repo enumeration now scans only chrome-bearing
fields (open tabs/editors/browser), while folder-key detection keeps
scanning all fields. The history maps hydrate unfiltered regardless, and
the deferred re-prune reaps their stale entries, so no data or recency is
lost. Also pin the round-2 re-prune ordering in the routing test.
brennanb2025
brennanb2025 previously approved these changes Jul 22, 2026

@brennanb2025 brennanb2025 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.

Thanks for the thoughtful fix — deferring the full scan off the startup-critical path is the right call, and it held up well under review. I validated it against a synthetic 40-repo / 360-worktree profile: startup lands at ~2.4s with the selective pre-hydration fetch at ~214ms, and session restore, sidebar, and worktree switching all behave at that scale.

I pushed three commits on top that keep the new selective fetch honest:

  • Keep SSH repos in the pre-hydration fetch. The local-only filter would drop SSH workspaces' tab/editor/browser state at hydration and the session writer then persists that loss. A disconnected SSH repo resolves through the local metadata fallback (no network on the startup path), so including it is cheap; only runtime-owned repos stay excluded.
  • Exclude the per-worktree history maps from repo enumeration. lastVisitedAtByWorktreeId and defaultTerminalTabsAppliedByWorktreeId reference roughly every repo a long-lived profile ever touched, which quietly turned the selective fetch back into the full scan this PR removes. On my rig this took the pre-hydration fetch from ~900ms to ~214ms.
  • Re-run the visit-timestamp prune after the deferred full scan, since the startup prune now only sees session-referenced repos.

While root-causing the exit itself we also found the reason it was silent — main has no unhandledRejection handler, so one failed async task during a heavy restore kills the process with no crash report. That fix ships separately in #9970 so this PR stays scoped to the startup scan.

@brennanb2025

Copy link
Copy Markdown
Contributor

Doing a few more rounds of review on this before it lands — the pushed commits and validation notes above still stand.

@brennanb2025

Copy link
Copy Markdown
Contributor

Additional deep correctness/performance review pushed in 05d54fddbd.

Confirmed and fixed three issues:

  • Empty persisted chrome-map entries (for example, tabsByWorktree[id] = [] after the last tab closes) were still counted as recovery state. A 326-entry regression fixture now selects only the one live repo instead of scheduling 327 pre-hydration Git scans.
  • The selective loop discarded execution-host identity when repo IDs collide across local/runtime hosts, allowing the focused runtime to hijack a local recovery fetch. fetchWorktrees now accepts the exact host for this path.
  • A startup hydration failure left sidebar/Automations refresh gates closed for the rest of the process. Degraded mode now releases the gate without enabling session persistence.

Validation: 241 focused startup/worktree/sidebar tests pass; 146 expanded hydration, host-split, SSH-routing, and persistence tests pass; typecheck passes; changed-file oxlint/React Doctor/formatting pass; max-lines, reliability, scrollbar, skill-manifest gates pass; and the production Electron build passes. Full lint remains blocked by the unchanged switch-exhaustiveness error in skill-freshness-group.tsx; localization is also blocked by unrelated missing catalog keys. A full-suite attempt under unsupported Node 26 produced known localStorage initialization failures and load-sensitive integration timeouts, so the focused suites and Node 24 CI are the meaningful signal.

…ktree-scan

# Conflicts:
#	src/renderer/src/store/slices/worktree-helpers.ts
#	src/renderer/src/store/slices/worktrees.ts
…ktree-scan

# Conflicts:
#	src/renderer/src/App.tsx
#	src/renderer/src/app-startup-routing.test.ts
@brennanb2025
brennanb2025 merged commit 90255ab into stablyai:main Jul 23, 2026
2 checks passed
brennanb2025 added a commit that referenced this pull request Jul 24, 2026
…urvival harness (#9992)

* fix(win-e2e): survive the agent-CLI feature-wall modal in harness driving

The modal renders off an async capability check and can be up at (or appear
right after) the harness's first interaction, swallowing every click until
closed — both crash-survival attempts on #9446 timed out exactly there, while
the app itself was healthy. Add its 'Close' button to the overlay dismiss
list, dismiss overlays before ensureTerminal's first probe, and retry the
first New-workspace click through a dismissal pass instead of hanging the
full 60s.

* fix(win-e2e): scope modal dismissal and bound retries

* fix(win-e2e): keep overlay retries inside composer

* fix(win-e2e): seed blank terminal selection

* fix(win-e2e): avoid input during terminal restore

* fix(win-e2e): bound whole create path by caller timeout

createWorkspaceFromSeededRepo gave the composer wait and create-button retry
fresh fixed 15s windows, so the create path could overrun the caller's
timeoutMs. Thread one shared deadline through every step and cover a fast
first click followed by a blocked submission.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…#9446)

* perf(startup): defer full worktree scan until after session restore

* fix(startup): normalize worktree recovery session keys

* fix(startup): preserve persisted workspace hydration

* fix(startup): keep SSH repos in pre-hydration worktree fetch

Round 1 review fixes for the selective pre-hydration fetch:

- The prefetch filter gated on LOCAL_EXECUTION_HOST_ID, which excluded
  SSH repos. Old full-scan code populated worktreesByRepo for disconnected
  SSH repos via the local metadata fallback (no network), so hydrateTabsSession
  / editor / browser preserved their chrome. Excluding SSH dropped that chrome
  at hydration and setHydrationSucceeded made the loss durable. Include SSH by
  excluding only runtime-owned repos (which hydrate via placeholders instead).
- collectWorktreeHydrationRepoIdsFromSession never collected activeRepoId, so a
  repo referenced only by active-repo state (no active worktree, no tabs) was
  not prefetched, breaking hydrateWorkspaceSession's main-worktree fallback.

* fix(startup): re-prune visit timestamps after deferred full worktree scan

Round 2 review fix. The selective pre-hydration fetch only populates
session-referenced repos, so the one-shot pruneLastVisitedTimestamps at
startup no longer sees non-session repos and keeps their deleted-worktree
entries (the prune defers unloaded repos to preserve SSH focus recency).
The old full pre-hydration scan had populated all local repos before the
prune. Re-run the prune after the deferred fetchAllWorktrees so stale
lastVisitedAtByWorktreeId entries are dropped once every repo is
authoritative; disconnected SSH stays non-authoritative and is kept.

* fix(startup): exclude unbounded history maps from hydration repo enumeration

Round 3 review fix. collectWorktreeHydrationRepoIdsFromSession collected
repo ids from lastVisitedAtByWorktreeId and defaultTerminalTabsAppliedByWorktreeId,
which accumulate one entry per worktree ever focused / given default tabs.
On the long-lived large profile this fix targets (stablyai#9441), those maps
reference nearly every repo, so the 'selective' pre-hydration fetch
degenerated back toward the full all-repos scan the fix removed.

Split the keyed-field list: repo enumeration now scans only chrome-bearing
fields (open tabs/editors/browser), while folder-key detection keeps
scanning all fields. The history maps hydrate unfiltered regardless, and
the deferred re-prune reaps their stale entries, so no data or recency is
lost. Also pin the round-2 re-prune ordering in the routing test.

* fix(startup): prevent competing full worktree scans

* fix(startup): keep selective hydration scans bounded

* fix(startup): ignore stale tab selection markers

* fix(startup): keep deferred worktree recovery selective

* test(windows): dismiss startup overlays before terminal setup

---------

Co-authored-by: Brennan Benson <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…urvival harness (stablyai#9992)

* fix(win-e2e): survive the agent-CLI feature-wall modal in harness driving

The modal renders off an async capability check and can be up at (or appear
right after) the harness's first interaction, swallowing every click until
closed — both crash-survival attempts on stablyai#9446 timed out exactly there, while
the app itself was healthy. Add its 'Close' button to the overlay dismiss
list, dismiss overlays before ensureTerminal's first probe, and retry the
first New-workspace click through a dismissal pass instead of hanging the
full 60s.

* fix(win-e2e): scope modal dismissal and bound retries

* fix(win-e2e): keep overlay retries inside composer

* fix(win-e2e): seed blank terminal selection

* fix(win-e2e): avoid input during terminal restore

* fix(win-e2e): bound whole create path by caller timeout

createWorkspaceFromSeededRepo gave the composer wait and create-button retry
fresh fixed 15s windows, so the create path could overrun the caller's
timeoutMs. Thread one shared deadline through every step and cover a fast
first click followed by a blocked submission.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants