Repository navigation
refactor(renderer): decompose App.tsx into an app-shell module - #14607
Conversation
App.tsx was 2831 lines behind an `eslint-disable max-lines` and a grandfathered entry in the max-lines ratchet baseline. It is now 92 lines: a root element, the shared providers, and three children. The body is split by concern into src/renderer/src/app-shell/: - use-app-chrome-layout — titlebar/sidebar/workbench layout derivations - use-floating-workspace-panel — overlay open state, persistence, return focus - use-app-startup-hydration — the boot chain (order preserved verbatim) - use-app-session-persistence — session writer + shutdown checkpoint - use-persisted-ui-writer / use-document-appearance / use-runtime-graph-sync / use-window-visibility-effects - use-onboarding-and-feature-tips — first-run education gating - use-global-keybindings + app-command-handlers — window shortcut dispatch - use-app-shell-services — app-level subscriptions that outlive any surface - AppWorkspaceShell / AppRootSurfaces / AppBackgroundServices / titlebar parts Two startup branches that no longer needed to sit inline moved to src/renderer/src/startup/: startup-ssh-connection-restore and startup-degraded-recovery. No behavior change. Sibling order of root overlays and modals is preserved so stacking is unchanged; the sidebar's virtualized scroll refs still live above the sidebar's remount boundary. The source-assertion tests in app-startup-routing.test.ts follow the code to its new files. The one that claimed to check "first-window startup services before terminal reconnect" was matching the degraded-recovery block, not the success path; it now asserts the success path, and the degraded ordering keeps its own dedicated test. Removes the disable comment and drops App.tsx from config/max-lines-baseline.txt.
📝 WalkthroughWalkthroughThe renderer startup flow now uses dedicated hydration, SSH restoration, and degraded-recovery modules. Application services manage persistence, synchronization, appearance, onboarding, visibility, and background gates. Window chrome, keyboard commands, floating workspace behavior, and layout state are separated into app-shell modules. Workspace content and global modals use dedicated shell and surface hosts with lazy loading and recoverable boundaries. Startup routing tests now inspect the extracted modules. Merge Risk: 🟡 Moderate · up to This refactor preserves the app shell structure but still has bounded runtime risks: cancelled startup recovery may publish stale SSH state, and failed window-state or session writes may surface as unhandled promise rejections. The PR should receive explicit owner follow-up on these async error and cancellation paths before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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: 2
🧹 Nitpick comments (5)
src/renderer/src/app-shell/app-command-handlers.ts (1)
99-114: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated terminal shortcut-capture notification rule across two app-shell modules. Both sites re-implement the same guard (
context === 'terminal'plus theterminalShortcutPolicy ?? 'orca-first'default) and the sameshowTerminalShortcutCaptureNotificationcall withplatform: shortcutPlatform. Two copies of the default policy literal can drift, and a change to the capture rule must be applied twice.
src/renderer/src/app-shell/app-command-handlers.ts#L99-L114: extract the guard and theshowTerminalShortcutCaptureNotificationcall into one exported helper, for examplenotifyTerminalShortcutCapture({ actionId, context, terminalShortcutPolicy, keybindings }), and call it fromclaim.src/renderer/src/app-shell/use-global-keybindings.ts#L122-L131: replace the localnotifyTerminalCapturebody with a call to that exported helper so the'orca-first'default is defined once.src/renderer/src/app-shell/use-global-keybindings.ts (1)
233-238: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueBuild the handler map only after an alias chord matches.
This line allocates a new
Mapwith every action closure on each keydown that reaches it, including plain keystrokes in the main workbench terminal. The loop then discards the map when no alias id matches. Match first, then build the map for the matched id.♻️ Proposed reordering
- const handlers = createAppCommandHandlers(state, input, context) for (const actionId of PLUGIN_COMMAND_ALIAS_ACTION_IDS) { - if (matchShortcut(actionId) && handlers.get(actionId)?.()) { + if (!matchShortcut(actionId)) { + continue + } + if (createAppCommandHandlers(state, input, context).get(actionId)?.()) { return } }src/renderer/src/app-shell/AppWorkspaceShell.tsx (1)
27-30: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueUse
React.RefObjectfor the scroll refs.
@types/[email protected]retainsMutableRefObject, but marks it deprecated. React 19useRefreturnsRefObject. Update these annotations and the matching sidebar and hook types.VirtualizedScrollAnchoralready includesnull.src/renderer/src/startup/startup-ssh-connection-restore.ts (1)
66-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLower the log level for the routine state poll.
Line 68 logs at
warnfor every eager target on every startup, including the success case. This is a normal-path diagnostic, not a warning. Useconsole.debugor the startup diagnostic logger so real warnings stay visible.♻️ Proposed change
const state = await window.api.ssh.getState({ targetId }) - console.warn(`[ssh-restore] Polled state for ${targetId}: status=${state?.status}`) + console.debug(`[ssh-restore] Polled state for ${targetId}: status=${state?.status}`) if (state?.status === 'connected') {src/renderer/src/app-shell/use-document-appearance.ts (1)
11-33: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueNarrow the theme effect dependency to
settings?.theme.The effect depends on the whole
settingsobject. Any unrelated settings change tears down and re-adds theprefers-color-schemelistener and re-applies the theme. Depend onsettings?.themeinstead, which matches the only value the effect reads.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 3f33f35d-51ad-4542-9026-8d08b019877e
📒 Files selected for processing (26)
config/max-lines-baseline.txtsrc/renderer/src/App.tsxsrc/renderer/src/app-shell/AppBackgroundServices.tsxsrc/renderer/src/app-shell/AppRootSurfaces.tsxsrc/renderer/src/app-shell/AppWorkspaceShell.tsxsrc/renderer/src/app-shell/TitlebarLeftControls.tsxsrc/renderer/src/app-shell/TitlebarMainStrip.tsxsrc/renderer/src/app-shell/WindowControls.tsxsrc/renderer/src/app-shell/app-command-handlers.tssrc/renderer/src/app-shell/app-window-chrome.tssrc/renderer/src/app-shell/use-app-chrome-layout.tssrc/renderer/src/app-shell/use-app-session-persistence.tssrc/renderer/src/app-shell/use-app-shell-services.tssrc/renderer/src/app-shell/use-app-startup-hydration.tssrc/renderer/src/app-shell/use-document-appearance.tssrc/renderer/src/app-shell/use-floating-workspace-panel.tssrc/renderer/src/app-shell/use-global-keybindings.tssrc/renderer/src/app-shell/use-lazy-modal-mounts.tssrc/renderer/src/app-shell/use-onboarding-and-feature-tips.tssrc/renderer/src/app-shell/use-persisted-ui-writer.tssrc/renderer/src/app-shell/use-runtime-graph-sync.tssrc/renderer/src/app-shell/use-window-visibility-effects.tssrc/renderer/src/app-startup-routing.test.tssrc/renderer/src/components/dashboard/agent-dashboard-performance-isolation.test.tssrc/renderer/src/startup/startup-degraded-recovery.tssrc/renderer/src/startup/startup-ssh-connection-restore.ts
💤 Files with no reviewable changes (1)
- config/max-lines-baseline.txt
| const localWrite = patchWorkspaceSessionByHost(window.api.session, patch, state) | ||
| void localWrite | ||
| const hydratedTargetIds = Array.from(state.remoteWorkspaceHydratedTargetIds).filter( | ||
| (targetId) => state.remoteWorkspaceSyncStatusByTargetId[targetId]?.phase !== 'conflict' | ||
| ) | ||
| if (hydratedTargetIds.length > 0) { | ||
| void localWrite | ||
| .then(() => window.api.remoteWorkspace?.setForConnectedTargets({ hydratedTargetIds })) | ||
| .then((results) => { | ||
| for (const { targetId, result } of results ?? []) { | ||
| applyRemoteWorkspacePatchStatus(targetId, result) | ||
| } | ||
| }) | ||
| .catch((err) => { | ||
| for (const targetId of hydratedTargetIds) { | ||
| useAppStore.getState().setRemoteWorkspaceSyncStatus(targetId, { | ||
| phase: 'error', | ||
| direction: 'push', | ||
| message: err instanceof Error ? err.message : 'Workspace upload failed' | ||
| }) | ||
| } | ||
| }) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check whether patchWorkspaceSessionByHost can reject.
set -euo pipefail
fd -a 'workspace-session-host-persistence.ts' src/renderer/src \
--exec rg -nP -C6 'export (async )?function patchWorkspaceSessionByHost' {}Repository: stablyai/orca
Length of output: 669
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -a 'workspace-session-host-persistence.ts' src/renderer/src | head -n1)"
cat -n "$file" | sed -n '210,285p'
printf '\n-- call sites --\n'
rg -n -C4 'patchWorkspaceSessionByHost\(' src/renderer/src
printf '\n-- related tests and rejection paths --\n'
rg -n -C5 'patchWorkspaceSessionByHost|splitWorkspaceSessionByHost|workspace session write failed|Local workspace session' src/renderer test tests 2>/dev/null || trueRepository: stablyai/orca
Length of output: 46018
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '-- SessionApi definition --'
rg -n -C8 'type SessionApi|interface SessionApi|patch:.*WorkspaceSessionPatch|patch\(.*WorkspaceSessionPatch' src shared
printf '%s\n' '-- persistence callback body --'
file="$(fd -a 'use-app-session-persistence.ts' src/renderer/src | head -n1)"
cat -n "$file" | sed -n '75,112p'
printf '%s\n' '-- static path verifier --'
python3 - <<'PY'
from pathlib import Path
files = list(Path("src/renderer/src").rglob("use-app-session-persistence.ts"))
assert files, "persistence hook not found"
text = files[0].read_text()
start = text.index("const localWrite = patchWorkspaceSessionByHost")
branch = text.index("if (hydratedTargetIds.length > 0)", start)
end = text.index("\n }", branch) + len("\n }")
body = text[start:end]
print(body)
assert "void localWrite" in body
assert ".catch(" in body
assert body.index(".catch(") > branch
print("The visible catch is nested under the hydratedTargetIds > 0 branch.")
PYRepository: stablyai/orca
Length of output: 12862
Handle local session write rejection.
patchWorkspaceSessionByHost returns api.patch(local) unchanged. When hydratedTargetIds is empty, no rejection handler is attached. Add an explicit catch to localWrite so a failed local write does not become an unhandled rejection.
| useEffect(() => { | ||
| // Why: maximize-changed only fires on transitions; seed from main on mount so a startup-maximized window shows the right icon. | ||
| let cancelled = false | ||
| void window.api.ui.isMaximized().then((value) => { | ||
| if (!cancelled) { | ||
| setMaximized(value) | ||
| } | ||
| }) | ||
| const unsubscribe = window.api.ui.onMaximizeChanged(setMaximized) | ||
| return () => { | ||
| cancelled = true | ||
| unsubscribe() | ||
| } | ||
| }, []) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Handle rejection from window.api.ui.isMaximized().
void ... .then(...) has no rejection path. If the IPC call rejects, the renderer logs an unhandled promise rejection. Add a catch so the component keeps its default state.
The same call can also resolve after an onMaximizeChanged event and overwrite the newer value. Ignoring the seed once an event has arrived removes that window.
🛡️ Proposed fix
let cancelled = false
- void window.api.ui.isMaximized().then((value) => {
- if (!cancelled) {
- setMaximized(value)
- }
- })
- const unsubscribe = window.api.ui.onMaximizeChanged(setMaximized)
+ let receivedChange = false
+ void window.api.ui
+ .isMaximized()
+ .then((value) => {
+ if (!cancelled && !receivedChange) {
+ setMaximized(value)
+ }
+ })
+ .catch(() => undefined)
+ const unsubscribe = window.api.ui.onMaximizeChanged((value) => {
+ receivedChange = true
+ setMaximized(value)
+ })📝 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.
| useEffect(() => { | |
| // Why: maximize-changed only fires on transitions; seed from main on mount so a startup-maximized window shows the right icon. | |
| let cancelled = false | |
| void window.api.ui.isMaximized().then((value) => { | |
| if (!cancelled) { | |
| setMaximized(value) | |
| } | |
| }) | |
| const unsubscribe = window.api.ui.onMaximizeChanged(setMaximized) | |
| return () => { | |
| cancelled = true | |
| unsubscribe() | |
| } | |
| }, []) | |
| useEffect(() => { | |
| // Why: maximize-changed only fires on transitions; seed from main on mount so a startup-maximized window shows the right icon. | |
| let cancelled = false | |
| let receivedChange = false | |
| void window.api.ui | |
| .isMaximized() | |
| .then((value) => { | |
| if (!cancelled && !receivedChange) { | |
| setMaximized(value) | |
| } | |
| }) | |
| .catch(() => undefined) | |
| const unsubscribe = window.api.ui.onMaximizeChanged((value) => { | |
| receivedChange = true | |
| setMaximized(value) | |
| }) | |
| return () => { | |
| cancelled = true | |
| unsubscribe() | |
| } | |
| }, []) |
|
Hold: the required React Doctor reports three render-phase ref writes in newly added files:
These patterns existed inline before the split, but moving them into new files brings them into the changed-lines purity gate. React may replay or discard render work, so the PR cannot pass the required gate as-is. Please move these writes to commit/event-safe paths while preserving the terminal-workbench latch and current shortcut-state behavior, then rerun Review notes: the structural extraction preserved root surface order, startup/SSH/degraded-recovery ordering, and sidebar scroll-ref ownership. Focused routing/performance tests pass (25/25), as does the max-lines ratchet. |
React Doctor's changed-lines purity gate flags three render-phase ref writes in the new app-shell files. The patterns predate the split, but moving them into new files brings them into the gate. - use-app-chrome-layout: the terminal-workbench latch becomes state set during render (the pattern use-lazy-modal-mounts already uses). The `canMountTerminalWorkbenchNow ||` term keeps the current render correct, so the latch only has to be visible to the next one. - use-app-startup-hydration: the onboarding callback ref syncs in an effect declared before the boot chain, so it lands first on mount. The callback is a `useCallback([])`, so its identity never actually changes. - use-global-keybindings: the shortcut-state mirror syncs in useLayoutEffect, which commits before any key event can read it. Key events are discrete, so handlers always observe committed state. All three now hold committed state only, so nothing can leak from a render React discards — the behavior the gate is protecting. pnpm run check:react-doctor:changed: 0 errors (was 3).
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/app-shell/use-app-startup-hydration.ts (1)
239-280: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftPropagate cancellation through startup recovery.
restoreSshConnectionsForStartuphas noAbortSignal, so a cancelled pass can publish late SSH state and deferred targets. Add signal checks before and after SSH reconnects and state polls. Prevent latereconnectSshTargetForRendererStartupresults from publishing state.
reconnectPersistedTerminalsresolves early when aborted. Keep explicit guards after each awaited startup step. SethydrationSucceededand start deferred refreshes only when the pass is still active.
🧹 Nitpick comments (1)
src/renderer/src/app-shell/use-app-startup-hydration.ts (1)
121-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the redundant
fetchKeybindings()catch.
fetchKeybindings()already catches and logswindow.api.keybindings.get()failures. This empty catch adds no recovery and obscures the action contract. Remove it unless this caller needs separate error handling.Based on learnings, callers can rely on
fetchKeybindings()without adding a redundant catch wrapper.Proposed cleanup
const keybindingsPromise = timeRendererStartupStep('fetch-keybindings', () => actions.fetchKeybindings() ) - keybindingsPromise.catch(() => {})Source: Learnings
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ec3d915c-c525-4610-8465-63d01b2f53b4
📒 Files selected for processing (4)
src/renderer/src/app-shell/use-app-chrome-layout.tssrc/renderer/src/app-shell/use-app-startup-hydration.tssrc/renderer/src/app-shell/use-global-keybindings.tssrc/renderer/src/app-startup-routing.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/app-startup-routing.test.ts
The tab-intent capture rides remote-workspace-relay-sync.ts, the shared store instance lives in remote-workspace-tab-intent-store.ts, the observation and reconcile handlers stay in remote-workspace.ts, and the session-write subscriber wiring moves to app-shell/use-app-session-persistence.ts (stablyai#14607 decomposed App.tsx). A live pre-request tab that a newer snapshot omits now survives the merge (stablyai#14844); the ledger continues to discriminate deliberate closes from never-uploaded creations at the apply boundary. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01AqNqAZQTwmAkwGcHj5TYXk
…yai#14607) * refactor(renderer): decompose App.tsx into an app-shell module App.tsx was 2831 lines behind an `eslint-disable max-lines` and a grandfathered entry in the max-lines ratchet baseline. It is now 92 lines: a root element, the shared providers, and three children. The body is split by concern into src/renderer/src/app-shell/: - use-app-chrome-layout — titlebar/sidebar/workbench layout derivations - use-floating-workspace-panel — overlay open state, persistence, return focus - use-app-startup-hydration — the boot chain (order preserved verbatim) - use-app-session-persistence — session writer + shutdown checkpoint - use-persisted-ui-writer / use-document-appearance / use-runtime-graph-sync / use-window-visibility-effects - use-onboarding-and-feature-tips — first-run education gating - use-global-keybindings + app-command-handlers — window shortcut dispatch - use-app-shell-services — app-level subscriptions that outlive any surface - AppWorkspaceShell / AppRootSurfaces / AppBackgroundServices / titlebar parts Two startup branches that no longer needed to sit inline moved to src/renderer/src/startup/: startup-ssh-connection-restore and startup-degraded-recovery. No behavior change. Sibling order of root overlays and modals is preserved so stacking is unchanged; the sidebar's virtualized scroll refs still live above the sidebar's remount boundary. The source-assertion tests in app-startup-routing.test.ts follow the code to its new files. The one that claimed to check "first-window startup services before terminal reconnect" was matching the degraded-recovery block, not the success path; it now asserts the success path, and the degraded ordering keeps its own dedicated test. Removes the disable comment and drops App.tsx from config/max-lines-baseline.txt. * refactor(renderer): move app-shell ref writes out of render React Doctor's changed-lines purity gate flags three render-phase ref writes in the new app-shell files. The patterns predate the split, but moving them into new files brings them into the gate. - use-app-chrome-layout: the terminal-workbench latch becomes state set during render (the pattern use-lazy-modal-mounts already uses). The `canMountTerminalWorkbenchNow ||` term keeps the current render correct, so the latch only has to be visible to the next one. - use-app-startup-hydration: the onboarding callback ref syncs in an effect declared before the boot chain, so it lands first on mount. The callback is a `useCallback([])`, so its identity never actually changes. - use-global-keybindings: the shortcut-state mirror syncs in useLayoutEffect, which commits before any key event can read it. Key events are discrete, so handlers always observe committed state. All three now hold committed state only, so nothing can leak from a render React discards — the behavior the gate is protecting. pnpm run check:react-doctor:changed: 0 errors (was 3).
What
src/renderer/src/App.tsxwas 2831 lines behind aneslint-disable max-linesand a grandfathered entry inconfig/max-lines-baseline.txt. It is now 92 lines — a root element, the shared providers, and three children — and the disable comment and baseline entry are both gone.How it's split
New
src/renderer/src/app-shell/, one module per concern — every file well under its oxlint budget:use-app-chrome-layoutuse-floating-workspace-paneluse-app-startup-hydrationuse-app-session-persistenceuse-persisted-ui-writeractiveViewpreferenceuse-document-appearanceuse-runtime-graph-syncuse-window-visibility-effectsuse-onboarding-and-feature-tipsuse-global-keybindings+app-command-handlersuse-app-shell-servicesuse-lazy-modal-mountsAppWorkspaceShell/AppRootSurfaces/AppBackgroundServices/TitlebarLeftControls/TitlebarMainStrip/WindowControlsTwo startup branches that no longer needed to sit inline moved to
src/renderer/src/startup/:startup-ssh-connection-restoreandstartup-degraded-recovery.Behavior
No behavior change. Specifically preserved:
scrollTop 0if they moved down with the component).useShallowbundle each, rather than one per action.Tests
app-startup-routing.test.tsasserts on source text, so its needles follow the code to its new files. While repointing it: the test named "waits for first-window startup services before terminal reconnect" was matchingawait window.api.app.awaitFirstWindowStartupServices(), a string that only appears in the degraded recovery block — so it duplicated the test below it and never covered the success path it names. It now asserts the success path's step ordering; degraded ordering keeps its own dedicated test.Verification
pnpm run lint(includescheck:max-lines-ratchet— 341 grandfathered, no new bypasses) ✅pnpm run typecheck✅pnpm test— 52,353 passed ✅pnpm run build:electron-vite✅tab-sidebar-closed-overlap(Cmd+B path, titlebar/tab overlap, Back-button separation)workspace-back-forward-navigation(history buttons + shortcuts + settings-view guard)golden-quit-relaunch-session(startup hydration + shutdown checkpoint round-trip)golden-worktree-create-switch(creation surface layout)