refactor(comments): slim verbose comments in renderer state (store/hooks/lib) (#9545)

Collapse multi-line explanatory comment blocks into single-line "why" statements
per AGENTS.md ("Document the Why, Briefly"): drop restatements of the code and
mechanism narration; keep the non-obvious reason, external refs, and directives.

Comments-only — verified no code changed via a Babel/esbuild comment-strip
token-equality gate against origin/main; typecheck and oxlint clean.

Area: renderer — store, hooks, lib, runtime. 36 files changed, 1673 insertions(+), 5677 deletions(-).

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-20 03:18:32 -07:00
committed by GitHub
co-authored by Orca
parent 190de8223e
commit 0f7250879a
36 changed files with 1673 additions and 5677 deletions
+112 -450
View File
File diff suppressed because it is too large Load Diff
+15 -86
View File
@@ -14,14 +14,10 @@ function resolveActiveLeafId(
}
/**
* Pure helper used by the hook below — exported so the regression test for
* the codex-row-stays-bold race (docs/codex-agent-row-bold-stuck.md) can
* exercise the decision against a real test store without needing a DOM.
* Returns paneKeys to ack for the active tab/leaf; exported for the
* codex-row-bold regression test (docs/codex-agent-row-bold-stuck.md).
*
* Returns the list of paneKeys that should be acked given the active tab and
* exact active leaf. Split tabs can host multiple agent panes, so equality on
* `${tabId}:${leafId}` is required; tab-prefix matching would mark siblings
* read without ever displaying them.
* Why: split tabs host multiple agent panes, so match exact `${tabId}:${leafId}` — a tab-prefix match would ack undisplayed siblings.
*/
export function computeAutoAckTargets(
state: {
@@ -40,9 +36,7 @@ export function computeAutoAckTargets(
const liveEntry = state.agentStatusByPaneKey[targetKey]
if (liveEntry) {
const ackAt = state.acknowledgedAgentsByPaneKey[targetKey] ?? 0
// Why: use stateStartedAt (not updatedAt) so tool/prompt pings within the
// same state don't re-trigger ack work — keeping the comparison aligned
// with WorktreeCardAgents' is-unvisited rule.
// Why: compare stateStartedAt (not updatedAt) so same-state pings don't re-trigger ack, matching WorktreeCardAgents' is-unvisited rule.
if (ackAt < liveEntry.stateStartedAt) {
targets.push(targetKey)
}
@@ -93,8 +87,7 @@ export function shouldClearViewedAgentWorktreeUnread(
return true
}
// Why: worktree unread is coarse. Do not clear it for the visible pane if a
// hidden tab/pane in the same worktree still owns unread agent attention.
// Why: worktree unread is coarse — don't clear for the visible pane if a hidden tab/pane in the same worktree still owns unread attention.
for (const paneKey of Object.keys(state.unreadAgentCompletionPanes)) {
if (args.paneKeysToClear.has(paneKey)) {
continue
@@ -143,8 +136,7 @@ export function acknowledgeViewedAgentAttention(
state.acknowledgeAgents(args.paneKeys)
}
if (args.activeWorktreeId) {
// Why: focus-return auto-ack means the selected agent is now visible;
// clear the Dock-driving worktree unread state without requiring a click.
// Why: the selected agent is now visible, so clear the Dock-driving worktree unread without a click.
state.clearWorktreeUnread(args.activeWorktreeId)
}
state.clearTerminalTabUnread(args.activeTabId)
@@ -153,57 +145,12 @@ export function acknowledgeViewedAgentAttention(
}
}
// Why: an agent row counts as "already seen" when the user is actually looking
// at the tab it lives on. Without this effect, ack only fires via an explicit
// click in the dashboard — which misses the common case where the user is
// already on the terminal tab when the agent finishes or blocks. That leaves
// the dashboard bolded and Dock badge raised for an event the user literally
// just watched happen.
//
// The effect subscribes directly to the store (not via React selectors) so it
// sees every state change with no re-render amplification up the component
// tree. A reference-equality guard inside the callback bails out immediately
// when none of the seven slices we care about (activeView, activeTabId,
// agentStatusByPaneKey, retainedAgentsByPaneKey, acknowledgedAgentsByPaneKey,
// terminalLayoutsByTabId, unreadAgentCompletionPanes)
// have changed — so the Object.entries walk only runs for updates
// that could legitimately affect the ack decision.
//
// It acks whenever:
// - activeView is 'terminal' (the user isn't on Settings/Tasks), AND
// - activeTabId identifies a live tab, AND
// - at least one agentStatusByPaneKey entry OR retainedAgentsByPaneKey
// entry matches the active tab+leaf AND its ackAt < stateStartedAt, OR
// the active pane has unread agent-completion attention.
//
// Why both maps: the inline-agents list renders the union of live + retained
// rows (see useWorktreeAgentRows), so the ack scan must too. Without the
// retained walk, a `done` row whose live entry was torn down by the
// title-revert path (see pty-connection.ts:onAgentExited) migrates to the
// retained map carrying a fresh `done.stateStartedAt` and never gets
// auto-acked — leaving the inline row bold forever even while the user
// stares at the terminal. Codex hits this race reliably because its TUI
// reverts to a shell title within milliseconds of `Stop`.
//
// The ack ALSO requires the OS window to be visible and focused
// (document.visibilityState === 'visible' && document.hasFocus()) —
// otherwise a transition that arrives while the user is away would silently
// clear the bold-until-viewed signal for an event they never saw. A
// visibilitychange / focus listener re-runs the scan when the user returns
// so any transitions that failed the gate while away get acked the moment
// focus actually comes back.
//
// We ack ALL matching panes in one call (a tab can host split panes, each
// with its own paneKey), then clear the active unread surfaces. Returning focus
// to a visible agent counts as viewing it, without requiring a click/keystroke.
// Auto-ack an agent row as "seen" when the user is already on its tab, so the dashboard/Dock don't stay bold for an event they watched happen.
// Scans live + retained maps: Codex's title-revert (pty-connection.ts:onAgentExited) migrates `done` rows to retained mid-race — see docs/codex-agent-row-bold-stuck.md.
export function useAutoAckViewedAgent(): void {
useEffect(() => {
// Why: the root zustand store is created with plain `create()` (no
// subscribeWithSelector middleware), so subscribe has no selector form.
// Track the slice references we actually depend on and early-return on
// unrelated updates — terminal output, tab state, settings, etc. would
// otherwise invoke the scan on every store change. Initialize to
// `undefined` so the first call always runs at least once.
// Why: the store uses plain create() (no subscribeWithSelector), so manually track the slices we depend on to skip unrelated updates.
// Init to undefined so the first maybeAck() (on mount) always passes the ref guard and scans.
let lastActiveView: unknown = undefined
let lastActiveTabId: unknown = undefined
let lastAgentStatus: unknown = undefined
@@ -229,12 +176,7 @@ export function useAutoAckViewedAgent(): void {
if (s.activeView !== 'terminal') {
return
}
// Why: the auto-ack represents "the user saw this row" — but tab-active is
// only a proxy. If the OS window is hidden, minimized, or another app has
// focus, the user is demonstrably not looking at the inline agents list
// even with the terminal tab set. Without this gate, an agent finishing
// while the user is away silently clears the bold-until-viewed signal and
// the user returns to a card with no indication anything transitioned.
// Why: tab-active only proxies "seen"; gate on window visible+focused so away-time transitions don't silently clear the bold signal.
if (typeof document !== 'undefined') {
if (document.visibilityState !== 'visible') {
return
@@ -248,13 +190,7 @@ export function useAutoAckViewedAgent(): void {
return
}
const activeLeafId = resolveActiveLeafId(s, activeTabId)
// Why: advance the refs ONLY after all gates have passed — if the
// visibility gate (window hidden/unfocused or no activeTabId) caused an
// early return, leave the refs stale so the next call (e.g. triggered by
// the focus listener on return) sees a diff and actually runs the scan.
// Updating refs before the gates would consume the diff silently and
// leave the user returning to cards whose bold-until-viewed rows stay
// bold until some unrelated store change happens to bump the refs.
// Why: advance refs only after gates pass, else the diff is consumed and a gated-out transition never re-acks when focus returns.
lastActiveView = s.activeView
lastActiveTabId = s.activeTabId
lastAgentStatus = s.agentStatusByPaneKey
@@ -283,18 +219,11 @@ export function useAutoAckViewedAgent(): void {
})
}
}
// Why: run once on mount to catch the case where the app restores to a
// session whose current state already has agents on the visible tab.
// Why: run once on mount to catch a restored session that already has agents on the visible tab.
maybeAck()
// Why: store.subscribe fires on every state change. The reference-
// equality guard above bails out immediately for the common case
// (terminal output, timers, etc.) so the Object.entries walk only runs
// when one of the five slices we read has actually changed.
// Subscribe to all store changes; the ref-equality guard above skips unrelated updates.
const unsubscribe = useAppStore.subscribe(maybeAck)
// Why: focus/visibility don't flow through the zustand store, so a
// late-arriving transition that failed the gate above never re-evaluates
// when focus returns. Subscribe to the two DOM events so the ack scan
// reruns the moment the user is actually back on the window.
// Why: focus/visibility don't flow through zustand, so re-run the scan on these DOM events when focus returns.
const onVisibility = (): void => maybeAck()
const onFocus = (): void => maybeAck()
document.addEventListener('visibilitychange', onVisibility)
+104 -323
View File
@@ -1,7 +1,4 @@
/* eslint-disable max-lines -- Why: this hook co-locates every piece of state
the NewWorkspaceComposerCard reads or mutates, so both the full-page composer
and the global quick-composer modal can consume a single unified source of
truth without duplicating effects, derivation, or the create side-effect. */
/* eslint-disable max-lines -- Why: co-locates all NewWorkspaceComposerCard state so the full-page composer and quick-composer modal share one source of truth. */
/* oxlint-disable react-doctor/no-adjust-state-on-prop-change -- Why: composer state synchronizes selected repo metadata, setup policy, issue-command hooks, and provider link lookups from async runtime IPC. */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
@@ -217,30 +214,18 @@ export type UseComposerStateOptions = {
initialLinkedWorkItem?: LinkedWorkItemSummary | null
initialTaskSourceContext?: TaskSourceContext | null
initialWorkspaceStatus?: WorkspaceStatus
/** Seed the Start-from selection when the composer opens. Used by the
* Create-from → Quick fallback path so a PR pick that needs a setup
* decision still lands with the resolved PR head as the base branch. */
/** Seeds the Start-from selection on open; the Create-from → Quick fallback uses it so a PR pick lands with the resolved PR head as base. */
initialBaseBranch?: string
/** Why: the full-page composer persists drafts so users can navigate away
* without losing work; the quick-composer modal is transient and must not
* clobber or leak that long-running draft. */
/** The full-page composer persists drafts across navigation; the transient quick-composer modal must not clobber that draft. */
persistDraft: boolean
/** Invoked after a successful createWorktree. The caller usually closes its
* surface here (palette modal, full page, etc.). */
/** Invoked after a successful createWorktree; the caller usually closes its surface (palette modal, full page, etc.). */
onCreated?: () => void
/** Optional external repoId override — used by TaskPage's work-item list
* which drives repo selection from the page header, not the card. */
/** External repoId override — used by TaskPage's work-item list, which drives repo selection from the page header, not the card. */
repoIdOverride?: string
onRepoIdOverrideChange?: (value: string) => void
/** Telemetry surface that opened this composer. Threaded into
* `createWorktree` so `workspace_created.source` reflects the actual
* entry point (Cmd+J palette → `command_palette`, sidebar buttons →
* `sidebar`, keyboard shortcut → `shortcut`). Omitted callers default
* to `unknown` at the IPC boundary. */
/** Telemetry surface that opened this composer; threaded into createWorktree so workspace_created.source reflects the entry point. Defaults to unknown. */
telemetrySource?: WorkspaceCreateTelemetrySource
/** Quick-create launches a blank/draft agent session and does not run
* issueCommand automation, so it can skip the issue-command probe that the
* full composer needs for linked-item prompt previews. */
/** Quick-create skips the issueCommand probe (no automation), which the full composer needs for linked-item prompt previews. */
enableIssueAutomation?: boolean
createGateMode?: 'full' | 'quick'
}
@@ -283,24 +268,19 @@ export type ComposerCardProps = {
) => void
smartNameSelection: SmartWorkspaceNameSelection | null
onClearSmartNameSelection: () => void
/** True when the selected source is an existing LOCAL branch that can be
* reused (checked out) instead of branched off — gates the reuse checkbox. */
/** True when the selected source is an existing LOCAL branch that can be reused (checked out) — gates the reuse checkbox. */
canReuseSelectedBranch: boolean
/** Whether the selected existing local branch will be reused (checked out)
* rather than used as the base for a new branch. */
/** Whether the selected existing local branch is reused (checked out) rather than branched from. */
reuseSelectedBranch: boolean
onReuseSelectedBranchChange: (next: boolean) => void
/** Whether the "create multiple" toggle is shown — worktree (git) targets
* only; folder-workspace targets create-and-close as before. */
/** Whether the "create multiple" toggle shows — worktree (git) targets only; folder workspaces create-and-close. */
showCreateMultiple: boolean
/** When on, the modal stays open after each create and resets identity fields
* so the user can create several worktrees in a row. */
/** When on, the modal stays open after each create and resets identity fields to allow creating several in a row. */
createMultiple: boolean
onCreateMultipleChange: (next: boolean) => void
agentPrompt: string
onAgentPromptChange: (value: string) => void
/** Rendered issueCommand template to preview inside the empty prompt
* textarea when the user has linked a work item but not typed anything. */
/** Rendered issueCommand template previewed in the empty prompt when a work item is linked but nothing typed. */
linkedOnlyTemplatePreview: string | null
attachmentPaths: string[]
getAttachmentLabel: (pathValue: string) => string
@@ -331,8 +311,7 @@ export type ComposerCardProps = {
onNoteChange: (value: string) => void
baseBranch: string | undefined
onBaseBranchChange: (next: string | undefined) => void
/** Called when a PR is selected in the Start-from picker. Updates both
* baseBranch and linkedWorkItem/linkedPR in one pass. */
/** Called when a PR is selected in the Start-from picker; updates baseBranch and linkedWorkItem/linkedPR in one pass. */
onBaseBranchPrSelect: (
baseBranch: string,
item: GitHubWorkItem,
@@ -340,8 +319,7 @@ export type ComposerCardProps = {
branchNameOverride?: string,
compareBaseRef?: string
) => void
/** PR number selected via the Start-from picker (when applicable). Used so the
* field can render "PR #N" copy. */
/** PR number selected via the Start-from picker, so the field can render "PR #N" copy. */
baseBranchLinkedPrNumber: number | null
/** Absolute path of the selected repo, used by Start-from picker for SWR. */
selectedRepoPath: string | null
@@ -353,11 +331,9 @@ export type ComposerCardProps = {
selectedRepoConnectInProgress: boolean
onConnectSelectedRepo: () => Promise<void>
branchesEnabled?: boolean
/** Transient inline hint shown next to the Start-from trigger after a repo
* switch resets a prior selection (e.g. "was PR #8778"). Null when none. */
/** Inline hint next to the Start-from trigger after a repo switch resets a prior selection (e.g. "was PR #8778"). Null when none. */
startFromResetHint: string | null
/** Warning shown when a selected fork PR has "Allow edits from maintainers"
* off, so a push to the fork may be rejected. Null when none. */
/** Warning when a selected fork PR has "Allow edits from maintainers" off, so a push may be rejected. Null when none. */
forkPushWarning: string | null
setupConfig: SetupConfig | null
setupControlsEnabled?: boolean
@@ -370,8 +346,7 @@ export type ComposerCardProps = {
resolvedSetupDecision: 'run' | 'skip' | null
createError: WorkspaceCreateErrorDisplay | null
canUseSparseCheckout: boolean
/** Saved presets for the currently-selected repo. Empty array when no
* presets exist or when the repo is remote. */
/** Saved sparse presets for the selected repo; empty when none exist or the repo is remote. */
sparsePresets: SparsePreset[]
/** ID of the selected sparse preset. Null means sparse checkout is off. */
sparseSelectedPresetId: string | null
@@ -381,8 +356,7 @@ export type ComposerCardProps = {
export type UseComposerStateResult = {
cardProps: ComposerCardProps
/** Ref the consumer should attach to the composer wrapper so the global
* Enter-to-submit handler can scope its behavior to the visible composer. */
/** Attach to the composer wrapper so the global Enter-to-submit handler scopes to the visible composer. */
composerRef: React.RefObject<HTMLDivElement | null>
onComposerNodeChange: (node: HTMLDivElement | null) => void
promptTextareaRef: React.RefObject<HTMLTextAreaElement | null>
@@ -391,8 +365,7 @@ export type UseComposerStateResult = {
submitQuick: (agent: TuiAgent | null) => Promise<void>
/** Invoked by the Enter handler to re-check whether submission should fire. */
createDisabled: boolean
/** Selects the repo a nested Add Project flow just added, clearing any
* folder-group target so the composer lands on the new project. */
/** Selects the repo a nested Add Project flow just added, clearing any folder-group target so the composer lands on it. */
selectAddedProjectRepo: (repoId: string) => void
}
@@ -473,8 +446,7 @@ export function resolveSmartGitHubCreateNames({
nameIsAutoManaged: boolean
}): { workspaceName: string; displayName: string | undefined } {
if (resolutionKind === 'pr-start-point' && !nameIsAutoManaged && fallbackWorkspaceName) {
// Why: submit-time PR start-point resolution augments an already-linked PR;
// it must not reclaim a workspace name the user edited after selection.
// Why: submit-time PR start-point augments an already-linked PR; don't reclaim a name the user edited after selecting.
return { workspaceName: fallbackWorkspaceName, displayName: undefined }
}
return { workspaceName: smartWorkspaceName, displayName: smartDisplayName }
@@ -530,20 +502,13 @@ export function getInitialAutoManagedWorkspaceName({
initialName: string
initialLinkedWorkItem?: LinkedWorkItemSummary | null
}): string {
// Why: command-palette prefilled names are user input unless they exactly
// match the linked item seed Orca generated for a source selection.
// Why: a prefilled name counts as user input unless it exactly matches the linked-item seed Orca generated.
const candidateName = draftName ?? initialName
const seedName = getLinkedWorkItemSeedName(draftLinkedWorkItem ?? initialLinkedWorkItem)
return candidateName && seedName && candidateName === seedName ? candidateName : ''
}
// Why: both the full-page TaskPage composer and the Cmd+J modal can be
// mounted simultaneously. Without instance scoping, a single native file
// drop fires every subscriber and duplicates attachments/prompt edits across
// the background draft and the visible modal. Route drops to the
// most-recently-mounted composer only — the modal stacks on top, so the
// modal wins when both are present, and the page takes over once the modal
// closes.
// Why: page composer and Cmd+J modal can coexist, so route a native file drop to only the most-recently-mounted one, else it duplicates across both.
const composerDropStack: symbol[] = []
const EMPTY_SPARSE_PRESETS: SparsePreset[] = []
@@ -567,10 +532,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
initialProjectGroupId
} = options
// Why: each `useAppStore(s => s.someAction)` registers its own equality
// check that React has to re-run on every store mutation. Consolidating
// all stable actions into a single useShallow subscription turns 11 checks
// per store update into one.
// Why: fold stable actions into one useShallow subscription so a store mutation runs one equality check instead of 11.
const actions = useAppStore(
useShallow((s) => ({
setNewWorkspaceDraft: s.setNewWorkspaceDraft,
@@ -621,8 +583,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const runtimeStatusByEnvironmentId = useAppStore((s) => s.runtimeStatusByEnvironmentId)
const workspaceHostScope = useAppStore((s) => s.workspaceHostScope)
const eligibleRepos = useMemo(() => getComposerEligibleRepos(repos), [repos])
// Why: a runtime-owned SSH repo (the active repo right after creating a per-workspace-env) is not
// eligible, so seed from its local same-project sibling instead of falling back to another project.
// Why: a runtime-owned SSH repo (active right after creating a per-workspace-env) is ineligible; seed from its local same-project sibling, not another project.
const seedActiveRepoId = useMemo(
() => resolveComposerActiveRepoId(repos, eligibleRepos, activeRepoId),
[repos, eligibleRepos, activeRepoId]
@@ -634,9 +595,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const draftProjectHostSetupId = persistDraft
? (newWorkspaceDraft?.projectHostSetupId ?? null)
: null
// Why: Tasks can start work from Linear/Jira source contexts that are not
// repo-backed. Seed the run target from the logical project/source host so
// the modal does not silently fall back to the ambient active repo.
// Why: Tasks can start from non-repo Linear/Jira contexts; seed from the logical project/source host so the modal doesn't fall back to the active repo.
const initialRunSeed = resolveInitialWorkspaceRunSeed({
draftProjectId,
draftHostId,
@@ -786,8 +745,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
)
return getAgentLaunchPlatformForRepo(selectedRepo, projectRuntime)
}, [activeRepoId, projects, repos, selectedRepo, settings, worktreesByRepo])
// Why: SSH remotes deploy the CLI shim as plain `orca`, so the Linux-only
// `orca-ide` rename must not be applied to remote launch commands.
// Why: SSH remotes deploy the CLI shim as plain `orca`, so the Linux-only `orca-ide` rename must not apply to remote launch commands.
const selectedRepoIsRemote = selectedRepo ? repoIsRemote(selectedRepo) : false
const selectedRepoStartupShell = resolveLocalWindowsAgentStartupShell({
platform: selectedRepoAgentLaunchPlatform,
@@ -848,22 +806,16 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
if (!settings) {
return settings
}
// Why: composer probes and attachment uploads inspect the selected repo,
// even though workspace creation defaults still follow host scope.
// Why: probes and attachment uploads inspect the selected repo, even though creation defaults still follow host scope.
return getSettingsForRepoRuntimeOwner(
{ repos: selectedRepo ? [selectedRepo] : [], settings },
selectedRepo?.id ?? null
)
}, [selectedRepo, settings])
// Why: key the recipe load on the repo's stable identity, not the whole repo
// object. `updateRepo` (e.g. saving the setup-startup policy from this very
// composer, or a GitHub upstream backfill) replaces the selected repo object
// by reference; depending on the object would re-run this effect and silently
// reset the user's manually-chosen recipe via setSelectedEphemeralVmRecipeId(null).
// Why: key on repo id, not the repo object — updateRepo replaces it by reference and would re-run this effect, wiping the user's chosen recipe.
const selectedRecipeRepoId = selectedRepo?.id ?? null
const selectedRecipeRepoConnectionId = selectedRepo?.connectionId ?? null
// Why: the experimental toggle must hide the composer target and avoid probing
// repo recipes, since recipe discovery can surface setup errors for a hidden feature.
// Why: gate recipe probing on the experimental toggle, since discovery can surface setup errors for a hidden feature.
const ephemeralVmsEnabled = settings?.experimentalEphemeralVms === true
useEffect(() => {
let cancelled = false
@@ -1065,10 +1017,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
}
return initialLinkedWorkItem?.type === 'pr' ? initialLinkedWorkItem.number : null
})
// Why: GitLab parallels of linkedIssue/linkedPR. Kept as separate state
// (rather than reusing the GitHub slots with a provider discriminator) so
// the existing GitHub auto-name / linked-badge / persistence code paths
// stay untouched.
// Why: GitLab parallels of linkedIssue/linkedPR, kept as separate state so existing GitHub auto-name/badge/persistence paths stay untouched.
const [linkedGitLabIssue, setLinkedGitLabIssue] = useState<number | null>(() => {
if (persistDraft && newWorkspaceDraft?.linkedGitLabIssue !== undefined) {
return newWorkspaceDraft.linkedGitLabIssue
@@ -1096,33 +1045,22 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
Boolean(initialLinearBranchName)
)
const [smartNameMode, setSmartNameMode] = useState<SmartNameMode>('smart')
// Why (#5181): when the user picks an existing LOCAL branch, let them reuse it
// (check it out) instead of creating a new branch from it. `reuseEligibleBranch`
// is the local branch name eligible for reuse (null = not a reusable local
// branch, e.g. a remote-only ref or non-branch source); `reuseSelectedBranch`
// is the explicit checkbox value driving whether reuse actually happens.
// Why (#5181): reuseEligibleBranch = local branch name eligible for checkout-reuse (null if none); reuseSelectedBranch = the checkbox that enacts it.
const [reuseEligibleBranch, setReuseEligibleBranch] = useState<string | null>(null)
const [reuseSelectedBranch, setReuseSelectedBranch] = useState(false)
const [pushTarget, setPushTarget] = useState<GitPushTarget | undefined>(undefined)
// Why: when a repo switch wipes a prior Start-from selection, surface the
// reset inline (e.g. "was PR #8778") so the change is recoverable visually
// instead of slipping past the user. Cleared on any subsequent selection.
// Why: when a repo switch wipes a prior Start-from selection, surface the reset inline (e.g. "was PR #8778") so it doesn't slip past the user.
const [startFromResetHint, setStartFromResetHint] = useState<string | null>(null)
// Why: a fork PR with "Allow edits from maintainers" off can't be pushed to;
// warn (but don't block) so the maintainer isn't surprised by a rejected push.
// Why: a fork PR with "Allow edits from maintainers" off can't be pushed to; warn (don't block) so a rejected push isn't a surprise.
const [forkPushWarning, setForkPushWarning] = useState<string | null>(null)
const disabledTuiAgentKey = (settings?.disabledTuiAgents ?? []).join('\u0000')
const disabledTuiAgents = useMemo<TuiAgent[]>(
() => settings?.disabledTuiAgents ?? [],
// Why: settings IPC round-trips clone arrays; agent availability only
// changes when the disabled-agent content changes.
// Why: settings IPC clones arrays, so key on the disabled-agent content, not the array ref.
// eslint-disable-next-line react-hooks/exhaustive-deps
[disabledTuiAgentKey]
)
// Why: the long-form composer's agent selection is a required TuiAgent (not
// null/blank), so 'blank' preferences from global settings must collapse to
// the Claude default here — the blank-terminal affordance only lives in the
// quick-create flow.
// Why: the long-form composer requires a real TuiAgent, so a global 'blank' pref collapses to Claude (blank only exists in quick-create).
const enabledCatalogAgents = useMemo(
() =>
filterEnabledTuiAgents(
@@ -1140,10 +1078,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const [tuiAgent, setTuiAgent] = useState<TuiAgent>(
persistDraft ? (newWorkspaceDraft?.agent ?? fallbackDefaultAgent) : fallbackDefaultAgent
)
// Why: when the selected repo has a connectionId or runtime environment, read
// the per-host agent list instead of the local one. This ensures the Create
// Workspace dialog shows agents installed on the SSH host or paired runtime,
// not the local machine.
// Why: for a repo on an SSH host or runtime env, read the per-host agent list so the dialog shows the host's installed agents, not local.
const connectionId = selectedRepoConnectionId
const isRemote = typeof connectionId === 'string'
const runtimeEnvironmentId = selectedRepoSettings?.activeRuntimeEnvironmentId?.trim() || null
@@ -1185,10 +1120,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
} | null>(null)
const [creating, setCreating] = useState(false)
const [createError, setCreateError] = useState<WorkspaceCreateErrorDisplay | null>(null)
// Why: when checked, a successful worktree create keeps the modal open and
// resets identity fields so the user can queue another worktree without
// reopening. Defaults off; the modal unmounts on close, so reopening always
// starts unchecked.
// Why: when checked, a successful create keeps the modal open and resets identity fields so the user can queue another worktree.
const [createMultiple, setCreateMultiple] = useState(false)
const [advancedOpen, setAdvancedOpen] = useState(
persistDraft ? Boolean((newWorkspaceDraft?.note ?? '').trim()) : false
@@ -1216,16 +1148,12 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const nameRef = useRef<string>(name)
nameRef.current = name
const branchAutoNameRef = useRef<string>('')
// Why: tracks the note value we auto-prefilled from a Start-from PR pick, so
// a subsequent PR change can replace it without clobbering user-typed text.
// Why: the note we auto-prefilled from a Start-from PR pick, so a later PR change can replace it without clobbering user-typed text.
const lastAutoNoteRef = useRef<string>('')
// Why: read the latest note inside handleBaseBranchPrSelect without adding
// `note` to its deps (which would rebuild the callback on every keystroke).
// Why: let handleBaseBranchPrSelect read the latest note without adding it to deps (would rebuild the callback on every keystroke).
const noteRef = useRef<string>(note)
noteRef.current = note
// Why: PR selections in the Create From field resolve their checkout ref
// asynchronously. Submit must still know that the linked PR is a checkout
// source if Create is clicked before that resolver settles.
// Why: PR checkout refs resolve async, so submit can still see the linked PR as a checkout source if Create fires before the resolver settles.
const smartGitHubPrStartPointSelectionRef = useRef<SmartGitHubPrStartPointSelection | null>(null)
useEffect(() => {
const clearAutoManagedName = (): void => {
@@ -1248,11 +1176,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const promptTextareaRef = useRef<HTMLTextAreaElement | null>(null)
const promptCaretFrameRef = useRef<number | null>(null)
const nameInputRef = useRef<HTMLInputElement | null>(null)
// Why: the native-file-drop effect below subscribes once on mount and must
// read the latest agentPrompt when computing the caret-scoped insertion.
// Mirror the value into a ref so the listener sees fresh state without
// re-subscribing (which would reorder the composerDropStack and break
// multi-instance routing).
// Why: mirror agentPrompt into a ref so the once-mounted file-drop listener reads it fresh without re-subscribing, which would reorder composerDropStack.
const agentPromptRef = useRef(agentPrompt)
agentPromptRef.current = agentPrompt
const connectionIdRef = useRef(connectionId)
@@ -1260,11 +1184,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const selectedRepoConnectionIdRef = useRef(selectedRepoConnectionId)
selectedRepoConnectionIdRef.current = selectedRepoConnectionId
// Why: resolves the selected repo's owner/repo slug so a PR URL pasted
// into the workspace name field can be matched against the current repo.
// Pasting a PR URL from a different repo would otherwise recover only the
// PR number, mislinking the worktree to an unrelated PR with the same
// number in the selected repo.
// Why: the selected repo's slug, used to confirm a pasted PR URL belongs to this repo before linking (else a same-numbered foreign PR mislinks).
const [selectedRepoSlug, setSelectedRepoSlug] = useState<{ owner: string; repo: string } | null>(
null
)
@@ -1371,8 +1291,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const handleComposerNodeChange = useCallback(
(node: HTMLDivElement | null): void => {
// Why: the queued caret restoration targets composer descendants and
// must be canceled as soon as the composer root leaves the DOM.
// Why: cancel the queued caret restoration once the composer root (its target's ancestor) leaves the DOM.
if (!node) {
cancelPromptCaretFrame()
}
@@ -1446,10 +1365,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
() => normalizeSparseDirectoryLines(sparseDirectories),
[sparseDirectories]
)
// Why: a preset attribution should only ride along if what's about to be
// created actually equals the saved preset. If the user picked a preset and
// then edited the textarea, we want the worktree to be a "Custom" sparse
// checkout — not falsely tagged as the original preset.
// Why: only attribute the preset if the directories still match it; an edited selection is "Custom", not falsely tagged as the original preset.
const effectivePresetId = useMemo(() => {
if (!sparseSelectedPresetId) {
return null
@@ -1487,21 +1403,14 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
() => (linkedIssue.trim() ? parseGitHubIssueOrPRNumber(linkedIssue) : null),
[linkedIssue]
)
// Why: when the user pastes a PR URL straight into the workspace name field
// (without picking from the source picker), `linkedPR` stays null and the
// worktree card has no PR strip. Recover the PR number from the name on
// submit so create-from-PR worktrees always link back to their PR.
// Why: a PR URL pasted into the name field (not picked) leaves linkedPR null; recover the number so the worktree still links back to its PR.
const effectiveLinkedPR = useMemo<number | null>(() => {
if (linkedPR !== null) {
return linkedPR
}
const fromName = parseGitHubIssueOrPRLink(name)
if (fromName && fromName.type === 'pr') {
// Why: only adopt a number when the URL's owner/repo matches the
// selected repo. Pasting `github.com/other/repo/pull/1234` must not
// mislink the worktree to an unrelated PR #1234 in the current repo.
// If the slug hasn't resolved yet, suppress recovery rather than
// risking a cross-repo mislink.
// Why: adopt the number only when the URL slug matches the selected repo (and the slug has resolved), else a foreign PR URL mislinks to a same-numbered PR here.
if (
selectedRepoSlug &&
fromName.slug.owner.toLowerCase() === selectedRepoSlug.owner.toLowerCase() &&
@@ -1518,9 +1427,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
)
const setupPolicy: SetupRunPolicy = selectedRepo?.hookSettings?.setupRunPolicy ?? 'run-by-default'
const linkedWorkItemProvider = linkedWorkItem ? getLinkedWorkItemProvider(linkedWorkItem) : null
// Why: the "no prompt + linked item" path below rehydrates the issueCommand
// template into the main startup prompt. Linear starts never use that
// product-authored workflow text, so they should not wait for it either.
// Why: the no-prompt+linked-item path rehydrates the issueCommand template into the prompt, but Linear starts never use it, so they must not wait.
const willApplyIssueCommandAsPrompt =
enableIssueAutomation &&
!agentPrompt.trim() &&
@@ -1541,11 +1448,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const isSetupCheckPending = Boolean(repoId) && checkedHooksRepoId !== repoId
const shouldWaitForSetupCheck = Boolean(selectedRepo) && selectedRepoIsGit && isSetupCheckPending
// Why: when the user leaves the workspace name blank and provides no other
// seed source (prompt, linked issue/PR), pick a globally-unique marine
// creature name so the workspace gets a distinct, readable identifier
// instead of colliding on a literal "workspace" default — or on the same
// creature already used in another repo.
// Why: blank name with no other seed → globally-unique creature name so workspaces don't collide across repos or on a literal default.
const fallbackCreatureName = useMemo(
() => getSuggestedCreatureName(worktreesByRepo),
[worktreesByRepo]
@@ -1561,8 +1464,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
}),
[agentPrompt, fallbackCreatureName, linkedPR, name, parsedLinkedIssueNumber]
)
// Why: Linear starts may include only the neutral issue reference; repo
// issue-command templates are product-authored workflow direction.
// Why: exclude Linear — its starts may carry only a neutral issue ref, whereas repo issue-command templates are product-authored workflow direction.
const shouldApplyLinkedOnlyTemplate =
enableIssueAutomation &&
!agentPrompt.trim() &&
@@ -1700,8 +1602,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setRepoId(folderSourceRepos[0]?.id ?? '')
}, [folderSourceRepos, repoId, selectedProjectGroup, setRepoId])
// Why: the compact sparse dropdown is always visible under Advanced, so
// presets must load before sparse mode is enabled.
// Why: the sparse dropdown is always visible under Advanced, so presets must load before sparse mode is enabled.
useEffect(() => {
if (!repoId || !selectedRepoIsGit || selectedRepo?.connectionId) {
return
@@ -1718,9 +1619,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
sparsePresetsByRepo
])
// Why: detect agents for the selected repo. For local repos this runs once
// on mount (deduped by the store). For remote/runtime repos it re-runs when
// the selected repo changes so the agent list matches the correct host.
// Why: re-detect agents when the selected repo changes so the list matches the correct host (local runs once, deduped by the store).
useEffect(() => {
if (isRemote && selectedRepoSshStatus !== 'connected') {
return
@@ -1749,9 +1648,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
return () => {
cancelled = true
}
// Why: re-run when connectionId/runtimeEnvironmentId changes (user picks a
// different repo) so detection targets the correct host. Draft/settings deps
// are intentionally excluded — detection is a best-effort PATH snapshot.
// Why: deps narrowed to host identity (connectionId/runtimeEnvironmentId); detection is a best-effort PATH snapshot, so draft/settings are excluded.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [connectionId, runtimeEnvironmentId, isRemote, selectedRepoSshStatus, disabledTuiAgents])
@@ -1867,9 +1764,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
}
}, [folderTargetConnectionId])
// Why: warm the Start-from picker's PR cache on composer mount and whenever
// the selected repo changes so opening the picker paints instantly from
// cache.
// Why: warm the Start-from picker's PR cache so opening it paints instantly from cache.
const canPrefetchSelectedRepoWorkItems = canUseRepoBackedComposerSources({
connectionId: selectedRepoConnectionId,
status: selectedRepoSshStatus
@@ -1939,22 +1834,8 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
.listWorkItems({ repoPath: selectedRepo.path, repoId: selectedRepo.id, limit: 100 })
.then((envelope) => {
if (!cancelled) {
// Why: IPC payload omits repoId — stamp it here from the repo we
// queried so downstream consumers typed against GitHubWorkItem work.
// Cast through unknown: spreading a discriminated union loses the
// discriminant, so the union-preserving shape must be asserted.
// Why: the link popover intentionally does NOT surface
// `envelope.errors?.issues`. Per-surface error copy lives in the
// Tasks view (TaskPage) and the smart workspace-name field — a
// partial-failure banner inside the small
// @-mention popover would crowd the input and the user would
// already see the same error on the originating Tasks page. If a
// future UX decision flips this, add an error row to the popover's
// render output.
// Why: surface partial issues-side failures via devtools even though the
// popover intentionally omits a UI banner (see rationale above). A user
// hitting a 403 on a private upstream would otherwise see an empty popover
// and no diagnostic trail.
// Why: IPC omits repoId — stamp it from the queried repo below; cast through unknown since spreading the discriminated union loses the discriminant.
// Why: the @-mention popover deliberately shows no error banner (it would crowd the input and the user sees it on the Tasks page); log to devtools instead.
if (envelope.errors?.issues) {
console.warn(
'[composer/link] issues-side partial failure in @-mention popover:',
@@ -1999,10 +1880,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
let cancelled = false
setLinkDirectLoading(true)
// Why: Superset lets users paste a full GitHub URL or type a raw issue/PR
// number and still get a concrete selectable result. Full URLs carry
// issue-vs-PR intent, so preserve the URL route instead of probing by
// number only.
// Why: a full URL carries issue-vs-PR intent, so preserve the URL route instead of probing by number only.
const lookupRepoId = selectedRepo.id
const lookup =
normalizedLinkQuery.directLink !== undefined
@@ -2079,9 +1957,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const suggestedName =
getLinkedWorkItemWorkspaceName(normalizedItem)?.seedName ??
getLinkedWorkItemSuggestedName(normalizedItem)
// Why: a pasted URL/#123 in the field is the lookup query that found
// this item, not a deliberate name — replace it with the title-derived
// name or it silently becomes a slugified-URL workspace name.
// Why: a pasted URL/#123 is the lookup query, not a chosen name — replace with the title-derived name or it becomes a slugified-URL workspace name.
if (
suggestedName &&
shouldApplyWorkspaceSourceAutoName({
@@ -2243,9 +2119,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
...smartGitHubMetadata,
kind: 'metadata-only'
}
// Why: Create can be clicked before the debounced smart field commits
// its selected source. Commit the resolved item here so failures leave
// the form showing the title instead of the raw URL.
// Why: Create can fire before the debounced smart field commits; commit the resolved item here so the form shows the title, not the raw URL.
setLinkedIssue(
resolution.linkedIssueNumber !== null ? String(resolution.linkedIssueNumber) : ''
)
@@ -2285,8 +2159,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
settings
])
// Why: GitHub/GitLab review routing prefers one provider identity. Clear
// the opposite provider slots so stale hidden fields cannot win later.
// Why: review routing prefers one provider identity — clear the opposite provider slots so stale hidden fields can't win later.
const applyLinkedGitLabWorkItem = useCallback(
(item: GitLabWorkItem): void => {
smartGitHubPrStartPointSelectionRef.current = null
@@ -2306,9 +2179,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
title: item.title,
url: item.url
})
// Why: GitLabWorkItem.branchName lines up with GitHubWorkItem.branchName
// structurally; cast to the suggested-name helper's input shape so we
// reuse the existing naming heuristic without forking it.
// Why: GitLabWorkItem.branchName lines up structurally with GitHubWorkItem's; cast to reuse the naming heuristic without forking it.
const suggestedName = getLinkedWorkItemSuggestedName({
type: item.type === 'mr' ? 'pr' : 'issue',
number: item.number,
@@ -2371,8 +2242,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
lastAutoNameRef.current = ''
}
if (removedLinearItem) {
// Why: a Linear branch override belongs to its linked issue; unlinking
// must not leave provider metadata driving a later worktree create.
// Why: a Linear branch override belongs to its issue; unlinking must not leave it driving a later worktree create.
setBranchNameOverride(undefined)
setBranchNameOverridePreservesNameEdits(false)
branchAutoNameRef.current = ''
@@ -2381,10 +2251,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const handleNameValueChange = useCallback(
(nextName: string): void => {
// Why: linked GitHub items should keep refreshing the suggested workspace
// name only while the current value is still auto-managed. As soon as the
// user edits the field by hand, later issue/PR selections must stop
// clobbering it until they clear the field again.
// Why: linked items keep refreshing the suggested name only while it's auto-managed; a manual edit stops later picks from clobbering it until cleared.
if (!nextName.trim()) {
lastAutoNameRef.current = ''
} else if (name !== lastAutoNameRef.current) {
@@ -2441,13 +2308,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
if (folderPaths.length === 0) {
return
}
// Why: de-dup within a single drop — the OS occasionally delivers the
// same folder twice when a user drags from a selection that includes both
// the item and its parent, and we don't want to insert it multiple times.
// Why: de-dup within one drop — the OS can deliver the same folder twice when the selection includes an item and its parent.
const uniqueFolderPaths = Array.from(new Set(folderPaths))
// Why: wrap paths containing shell metacharacters in double quotes (and
// escape embedded quotes) so inserted folder refs stay a single token if
// pasted into a terminal. Simple paths stay unadorned to match OS drops.
// Why: quote paths with shell metacharacters so an inserted folder ref stays one token if pasted into a terminal; simple paths stay unadorned.
const formatPath = (p: string): string => {
if (/[\s"'$`\\()[\]{}*?!;&|<>#~]/.test(p)) {
return `"${p.replace(/(["\\$`])/g, '\\$1')}"`
@@ -2456,16 +2319,13 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
}
const insertion = uniqueFolderPaths.map(formatPath).join(' ')
const textarea = promptTextareaRef.current
// Why: compute selection, insertion, and caret target OUTSIDE the
// setAgentPrompt updater so the updater stays pure. React Strict Mode
// double-invokes updaters in dev, and batching can delay execution.
// Why: compute selection/insertion/caret outside the setAgentPrompt updater so it stays pure — Strict Mode double-invokes updaters in dev.
const current = agentPromptRef.current
const selStart = textarea?.selectionStart ?? current.length
const selEnd = textarea?.selectionEnd ?? current.length
const before = current.slice(0, selStart)
const after = current.slice(selEnd)
// Why: pad with single spaces when the caret sits directly against other
// text so the folder path doesn't merge into an adjacent word.
// Why: pad with spaces when the caret abuts text so the folder path doesn't merge into an adjacent word.
const needsLeadingSpace = before.length > 0 && !/\s$/.test(before)
const needsTrailingSpace = after.length > 0 && !/^\s/.test(after)
const padded = `${needsLeadingSpace ? ' ' : ''}${insertion}${needsTrailingSpace ? ' ' : ''}`
@@ -2481,9 +2341,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
textarea.setSelectionRange(caret, caret)
})
}
// Why: pass a plain value (not an updater) since `before`/`after` were
// already resolved from `agentPromptRef.current`; this keeps the state
// write side-effect-free under Strict-Mode double-render.
// Why: pass a plain value (not an updater) since before/after were already resolved, keeping the write pure under Strict-Mode double-render.
setAgentPrompt(before + padded + after)
},
[cancelPromptCaretFrame]
@@ -2591,12 +2449,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const applyLocalComposerDropRef = useRef(applyLocalComposerDrop)
applyLocalComposerDropRef.current = applyLocalComposerDrop
// Why: native OS file drops onto the composer are captured by the preload
// bridge (see `data-native-file-drop-target="composer"` markers) and relayed
// as a gesture-scoped IPC event. Files become attachments (matching the
// manual picker behavior); folders are pasted inline at the textarea caret
// so the user can reference them as working directories in their prompt
// without attaching a path we can't embed as file content.
// Why: native OS file drops relay via the preload bridge; files become attachments, folders paste inline at the caret since a path can't be embedded as file content.
const instanceIdRef = useRef<symbol>(Symbol('composer'))
useEffect(() => {
const instanceId = instanceIdRef.current
@@ -2605,10 +2458,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
if (data.target !== 'composer') {
return
}
// Why: only the top-of-stack composer (most recently mounted) owns the
// drop. Earlier subscribers stay bound to keep their own cleanup tidy
// but short-circuit so the event doesn't double-apply when page+modal
// are both alive.
// Why: only the top-of-stack composer owns the drop; earlier subscribers short-circuit so page+modal don't double-apply it.
if (!isCurrentComposerDropOwner(composerDropStack, instanceId)) {
return
}
@@ -2652,16 +2502,13 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setRepoId(value)
return
}
// Why: capture a short descriptor of the prior Start-from selection so
// the field can render an inline reset (e.g. "was PR #8778") after the
// repo changes and the selection is wiped.
// Why: capture a descriptor of the prior Start-from selection so the field can show an inline reset (e.g. "was PR #8778") after it's wiped.
let hint: string | null = null
if (!options.preserveStartFrom) {
if (linkedWorkItem?.type === 'pr' && baseBranch) {
hint = `was PR #${linkedWorkItem.number}`
} else if (linkedWorkItem?.type === 'mr' && baseBranch) {
// Why: GitLab MR convention is `!N`, not `#N` — match the
// upstream UI so the reset hint is recognizable.
// Why: GitLab MR convention is `!N`, not `#N` — match the upstream UI so the hint is recognizable.
hint = `was MR !${linkedWorkItem.number}`
} else if (baseBranch) {
hint = `was ${baseBranch}`
@@ -2678,32 +2525,25 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setLinkedPR(null)
setLinkedGitLabIssue(null)
setLinkedGitLabMR(null)
// Why: repo changes invalidate repo-scoped sources (GitHub/GitLab/branch),
// but a selected Linear issue is workspace-scoped source context and
// must survive choosing the implementation project.
// Why: a repo change invalidates repo-scoped sources, but a Linear issue is workspace-scoped and must survive choosing the implementation project.
if (!preserveLinearLinkedWorkItem) {
setLinkedWorkItem(null)
}
}
setSparseEnabled(false)
setSparseDirectories('')
// Why: presets are repo-scoped, so a stale selection from the prior
// repo would be meaningless after a repo switch.
// Why: presets are repo-scoped, so a prior-repo selection is meaningless after a switch.
setSparseSelectedPresetId(null)
// Why: the Start-from picker is repo-scoped, so any prior branch/PR
// selection is meaningless in the new repo. Resetting to undefined
// makes the field fall back to the new repo's effective base ref.
// Why: Start-from is repo-scoped; reset to undefined so the field falls back to the new repo's effective base ref.
if (!options.preserveStartFrom) {
setBaseBranch(undefined)
setCompareBaseRef(undefined)
setPushTarget(undefined)
// Why: Linear sources are workspace-scoped, so their canonical branch
// survives choosing a different implementation repo with the issue.
// Why: Linear sources are workspace-scoped, so their canonical branch survives choosing a different implementation repo.
setBranchNameOverride(preservedLinearBranchName)
setBranchNameOverridePreservesNameEdits(Boolean(preservedLinearBranchName))
branchAutoNameRef.current = preservedLinearBranchName ?? ''
// Why (#5181): reuse state is branch-scoped, so a repo switch must clear
// it even when a workspace-scoped Linear override is restored.
// Why (#5181): reuse state is branch-scoped, so a repo switch clears it even when a workspace-scoped Linear override is restored.
setReuseEligibleBranch(null)
setReuseSelectedBranch(false)
setForkPushWarning(null)
@@ -2736,8 +2576,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
if (!option || option.kind !== 'ready') {
return
}
// Why: switching the run host for the same logical project must not
// erase the task/PR source the user is starting from.
// Why: switching run host for the same project must not erase the task/PR source the user is starting from.
handleRepoChange(option.repoId, { preserveStartFrom: true })
},
[handleRepoChange, projectHostSetupOptions]
@@ -2790,12 +2629,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setSelectedProjectGroupId(null)
const preferredHostId =
selectedWorkspaceTarget.status === 'ready' ? selectedWorkspaceTarget.target.hostId : null
// Why: prefer the host the user is currently on, but treat it as a
// preference (focusedHostScope) rather than a hard hostId match. Pinning
// hostId made selecting a project that is only set up on a different host
// a silent no-op — the resolver returned '' (project-not-set-up-on-host)
// and the early return below swallowed the click. Falling back to any
// host the project is ready on lets cross-host selection work.
// Why: pass the current host as a preference (focusedHostScope), not a hard hostId — pinning made selecting a project set up only on another host a silent no-op.
const nextRepoId = resolveWorkspaceCreationRepoId({
eligibleRepos,
projects,
@@ -2824,9 +2658,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
)
const selectAddedProjectRepo = useCallback(
(nextRepoId: string): void => {
// Why: the nested Add Project flow hands back a repo id. Selecting it
// must also clear a folder-group target, whose onRepoChange handler
// only accepts repos inside the selected group.
// Why: clear the folder-group target when selecting the Add-Project repo, since the group's onRepoChange only accepts repos inside the group.
initialProjectGroupAppliedRef.current = true
setSelectedProjectGroupId(null)
setProjectError(null)
@@ -2864,9 +2696,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setCompareBaseRef(undefined)
setPushTarget(undefined)
setBranchNameOverride(undefined)
// Why (#5181): the Start-from picker means "create a new branch from this
// base", so it never offers branch reuse — clear any reuse state left over
// from a prior smart-field branch pick.
// Why (#5181): Start-from means "new branch from this base", so it never reuses — clear reuse state from a prior smart-field branch pick.
setBranchNameOverridePreservesNameEdits(false)
setReuseEligibleBranch(null)
setReuseSelectedBranch(false)
@@ -2890,14 +2720,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setBranchNameOverridePreservesNameEdits(Boolean(nextBranchNameOverride))
branchAutoNameRef.current = ''
setStartFromResetHint(null)
// Why: per spec, a PR selection in the Start-from picker is also a
// linkedWorkItem assignment. Reuse applyLinkedWorkItem so auto-name and
// linkedPR state stay in a single code path.
// Why: a Start-from PR pick is also a linkedWorkItem assignment; reuse applyLinkedWorkItem so auto-name and linkedPR stay one code path.
applyLinkedWorkItem(item, { preserveBranchNameOverride: Boolean(nextBranchNameOverride) })
// Why: starting a worktree from a PR is a strong hint for what the
// worktree's comment should surface (`orca worktree current`, sidebar).
// Prefill the note if it's empty or still equal to a prior auto-fill, so
// we don't overwrite anything the user has typed.
// Why: prefill the note from the PR (only when empty or still an auto-fill) so the sidebar surfaces it without clobbering user text.
const identity = resolveGitHubWorkItemIdentity(item)
if (identity.type === 'pr') {
const suggestedNote = `PR #${identity.number} — ${item.title}`
@@ -2911,9 +2736,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
[applyLinkedWorkItem]
)
// Why: GitLab parallel of handleBaseBranchPrSelect. Same shape, same
// semantics — except the note prefill uses GitLab's `!N` MR convention
// so a glance at the worktree sidebar makes the provider obvious.
// Why: GitLab parallel of handleBaseBranchPrSelect; note prefill uses GitLab's `!N` MR convention so the sidebar makes the provider obvious.
const handleBaseBranchMrSelect = useCallback(
(
nextBaseBranch: string,
@@ -2974,9 +2797,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setForkPushWarning(null)
branchAutoNameRef.current = ''
smartGitHubPrStartPointSelectionRef.current = null
// Why: provider items can come from a different source host than the
// selected run host. Resolve git refs against the run repo; keep item
// metadata/source context separate for provider identity.
// Why: provider items can come from a different source host than the run host — resolve refs against the run repo, keep item metadata for provider identity.
const runRepo = selectedRepo ?? eligibleRepos.find((repo) => repo.id === item.repoId)
applyLinkedWorkItem(normalizedItem)
if (identity.type !== 'pr' || !runRepo) {
@@ -3020,8 +2841,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
result.branchNameOverride,
result.compareBaseRef
)
// Why: a fork PR push lands on the contributor's fork; if they didn't
// allow maintainer edits, GitHub will reject it. Warn up front.
// Why: a fork PR push lands on the contributor's fork; without maintainer-edits allowed GitHub rejects it, so warn up front.
setForkPushWarning(getForkPushWarning(result))
})
.catch((error: unknown) => {
@@ -3049,11 +2869,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
]
)
// Why: GitLab parallel of handleSmartGitHubItemSelect. For a picked
// MR, resolves the base branch via worktrees:resolveMrBase (which uses
// refs/merge-requests/<iid>/head for fork MRs the same way the gh side
// uses refs/pull/<N>/head). Issue selections short-circuit since
// there's no branch-resolution step to run.
// Why: GitLab parallel of handleSmartGitHubItemSelect — resolves MR base via worktrees:resolveMrBase (refs/merge-requests/<iid>/head); issues short-circuit.
const handleSmartGitLabItemSelect = useCallback(
(item: GitLabWorkItem): void => {
if (isProjectGroupTarget) {
@@ -3082,8 +2898,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setBranchNameOverridePreservesNameEdits(false)
setForkPushWarning(null)
branchAutoNameRef.current = ''
// Why: MR metadata can be sourced from one host/account while the
// workspace is created on another host for the same logical project.
// Why: MR metadata can be sourced from one host/account while the workspace is created on another for the same logical project.
const runRepo = selectedRepo ?? eligibleRepos.find((repo) => repo.id === item.repoId)
if (item.type !== 'mr' || !runRepo) {
setCompareBaseRef(undefined)
@@ -3126,9 +2941,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
void resolveMrBase
.then((result) => {
if ('error' in result) {
// Why: without surfacing the failure the worktree silently falls
// back to the repo default branch (origin/master), so clear stale
// base state and tell the user — mirrors the GitHub PR path.
// Why: an unsurfaced failure silently falls back to the repo default branch, so clear stale base state and toast — mirrors the GitHub PR path.
setBaseBranch(undefined)
setCompareBaseRef(undefined)
setPushTarget(undefined)
@@ -3179,15 +2992,8 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setPushTarget(undefined)
setStartFromResetHint(null)
setForkPushWarning(null)
// Why (#5181): reuse an existing local branch (check it out) instead of
// branching off it. Default reuse ON when the worktree name was
// auto-derived from the branch, and preserve name edits so reuse survives
// renaming the worktree folder. Reuse is impossible when the branch is
// already checked out in another worktree (git allows it in only one), so
// gate eligibility on that and don't pin the override to a busy branch.
// Note: worktreesByRepo only covers visible worktrees; a branch busy only
// in a hidden external worktree falls through to the backend conflict
// check, which rejects it with a clear "already exists locally" error.
// Why (#5181): reuse (check out) an existing branch instead of branching off it; git allows a branch in only one worktree, so gate eligibility on that.
// Note: worktreesByRepo covers only visible worktrees; a branch busy in a hidden external worktree falls through to the backend "already exists locally" check.
const { reuseEligibleBranch: nextReuseEligibleBranch, defaultReuse } = selection
setReuseEligibleBranch(nextReuseEligibleBranch)
setReuseSelectedBranch(defaultReuse)
@@ -3211,10 +3017,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
return
}
setReuseSelectedBranch(next)
// Why (#5181): reuse pins the exact existing branch as the override and
// preserves it across worktree-name edits, so the folder can be named
// independently while the branch is checked out. Opting out drops the
// override so a fresh branch is created from the selected ref as base.
// Why (#5181): reuse pins the existing branch as override (preserved across name edits); opting out drops it so a fresh branch is created from the ref.
setBranchNameOverridePreservesNameEdits(next)
setBranchNameOverride(next ? reuseEligibleBranch : undefined)
if (next) {
@@ -3254,8 +3057,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const linkedLinearIssue = buildLinearIssueLinkedWorkItem(issue)
setLinkedWorkItem(linkedLinearIssue)
const suggestedName = getLinearIssueWorkspaceName(issue)
// Why: same lookup-text rule as applyLinkedWorkItem, plus the typed
// Linear identifier ("STA-123") that matched this issue.
// Why: same lookup-text rule as applyLinkedWorkItem, plus the typed Linear identifier ("STA-123") that matched this issue.
if (
shouldApplyWorkspaceSourceAutoName({
currentName: name,
@@ -3271,9 +3073,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setBranchNameOverridePreservesNameEdits(Boolean(linearBranchName))
setForkPushWarning(null)
branchAutoNameRef.current = linearBranchName ?? ''
// Why: match the GitHub issue/PR flow by drafting linked context for
// review instead of auto-submitting. Auto-filling the note here would
// turn a source selection into user-authored instructions.
// Why: don't prefill the note for a Linear pick — that would turn a source selection into user-authored instructions (matches the GitHub flow).
},
[isProjectGroupTarget, name]
)
@@ -3618,8 +3418,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
? submitTitleName?.displayName
: undefined
: smartGitHubCreateNames.displayName
// Why: the first-work hook only renames blank, auto-generated git workspaces
// that actually launch an agent. Persist that known-pending state for the card.
// Why: the first-work hook only renames blank, auto-generated git workspaces that launch an agent; persist that pending state for the card.
const pendingFirstAgentMessageRename =
selectedRepoIsGit &&
settings?.autoRenameBranchFromWork === true &&
@@ -3644,9 +3443,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const shouldSeedInitialAgentStatus =
tuiAgent === 'command-code' && submitStartupPrompt.trim().length > 0
// Why: backend startup is safe only when the launch command is
// self-contained. Agents that need post-ready paste/follow-up stay on
// the renderer path so prompt delivery is not skipped.
// Why: backend startup is safe only for self-contained launch commands; agents needing post-ready paste stay on the renderer path.
const composerTelemetry: AgentStartedTelemetry = {
agent_kind: tuiAgentToAgentKind(tuiAgent),
launch_source: telemetrySource === 'onboarding' ? 'onboarding' : 'new_workspace_composer',
@@ -3708,8 +3505,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
const worktree = result.worktree
const trimmedNote = note.trim()
// Why: linked source metadata is already included in createWorktree.
// Re-saving it here can trigger slow post-create PR push-target lookups.
// Why: linked source metadata is already in createWorktree; re-saving it can trigger slow post-create PR push-target lookups.
await applyWorktreeMeta(worktree.id, trimmedNote ? { comment: trimmedNote } : {})
const issueCommand =
@@ -3723,8 +3519,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
: undefined
const backendSpawnedStartup = result.startupTerminal?.spawned === true
if (startupPlan && !backendSpawnedStartup && !startupPlan.launchToken) {
// Why: delayed delivery must target the exact pane spawned from this
// queued startup, so both halves share one renderer-session token.
// Why: delayed delivery must target the exact pane from this queued startup, so both halves share one renderer-session token.
startupPlan.launchToken = createBrowserUuid()
}
const activation = activateAndRevealWorktree(worktree.id, {
@@ -3844,13 +3639,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
])
const resetForNextCreate = useCallback(() => {
// Why: with "create multiple" on, clear identity fields after each create so
// the next worktree starts clean. Context (repo, base branch, agent, project
// group) is intentionally retained for fast sequential creation. The
// PR-pick-derived refs (compare base, push target, branch override) are
// identity, not durable context, so they reset too — leaving them while the
// linked item is cleared would carry a half-set Start-from state (e.g. a
// silent fork push target) into the next worktree.
// Why: clears identity fields incl PR-pick-derived refs (else a half-set Start-from state — e.g. a silent fork push target — leaks into the next create); retains context (repo, base, agent, group) for fast sequential creates.
setName('')
lastAutoNameRef.current = ''
setAgentPrompt('')
@@ -3869,8 +3658,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
setStartFromResetHint(null)
setForkPushWarning(null)
setCreateError(null)
// Refocus the name field on the next frame (after the reset re-render) so the
// user can immediately type the next worktree name.
// Refocus after the reset re-render (next frame) so the user can type the next worktree name immediately.
requestAnimationFrame(() => nameInputRef.current?.focus())
}, [])
@@ -4039,8 +3827,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
? submitTitleName?.displayName
: undefined
: smartGitHubCreateNames.displayName
// Why: quick create uses the same blank-name creature branch flow; the card
// needs an explicit marker rather than guessing from the generated title.
// Why: quick create shares the blank-name flow; the card needs an explicit marker, not a guess from the title.
const pendingFirstAgentMessageRename =
selectedRepoIsGit &&
settings?.autoRenameBranchFromWork === true &&
@@ -4049,9 +3836,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
!effectiveBranchNameOverride &&
!createDisplayName
const trimmedNote = note.trim()
// Why: backend startup is safe only when the launch command is
// self-contained. Agents that need post-ready paste/follow-up stay on
// the renderer path so prompt delivery is not skipped.
// Why: agents needing post-ready paste/follow-up stay on the renderer path so prompt delivery isn't skipped.
const promptLinkedWorkItem = agent === null ? null : submitLinkedWorkItem
const { prompt: quickPrompt, draftPrompt: quickDraftPrompt } =
resolveQuickCreateLinkedWorkItemPrompt(promptLinkedWorkItem, trimmedNote)
@@ -4227,16 +4012,13 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
...(createMultiple ? { suppressTerminalFocusOnCompletion: true } : {})
}
// Why: git fetch + `git worktree add` can take 10–15s; holding the modal
// hostage to that made it feel frozen, so hand off to a background flow and
// close the modal immediately.
// Why: git fetch + `git worktree add` can take 10–15s; run in the background so the modal isn't frozen.
if (persistDraft) {
clearNewWorkspaceDraft()
}
runBackgroundWorktreeCreation(request)
if (createMultiple) {
// Why: keep the modal open and reset identity so the user can queue
// another worktree right away; the creation above runs in the background.
// Why: creation runs in the background, so reset identity to queue another worktree right away.
resetForNextCreate()
} else {
onCreated?.()
@@ -4365,8 +4147,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS
smartNameSelection?.kind === 'branch',
reuseSelectedBranch,
onReuseSelectedBranchChange: handleReuseSelectedBranchChange,
// Why: the "create multiple" toggle only applies to worktree (git) targets;
// folder-workspace targets keep the create-and-close behavior.
// Why: "create multiple" applies only to worktree (git) targets; folder-workspace keeps create-and-close.
showCreateMultiple: !isProjectGroupTarget,
createMultiple,
onCreateMultipleChange: setCreateMultiple,
+46 -174
View File
@@ -1,7 +1,4 @@
/* eslint-disable max-lines -- Why: the editor external-watch hook co-locates
target diffing, fs:changed dispatch, tombstone coalescing, and rename
correlation so the end-to-end event-to-store mutation contract stays
readable in one file. */
/* eslint-disable max-lines -- co-locates target diffing, fs:changed dispatch, tombstone coalescing, and rename correlation so the event-to-store contract stays in one file. */
import { useEffect, useRef } from 'react'
import { useAppStore, type AppState } from '@/store'
import { basename, joinPath } from '@/lib/path'
@@ -31,14 +28,7 @@ import {
import { isGitRepoKind } from '../../../shared/repo-kind'
import { markFileChangedOnDisk } from '@/components/editor/editor-changed-on-disk-mark'
// Why: atomic-write patterns (Claude Code's Edit tool, editors like vim,
// VSCode) land as a short burst of `update` events — or `delete + create` on
// renamers — within a few milliseconds for the same path. Dispatching an
// `ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT` per raw event fan-outs into N full
// `setContent` + document-repair rebuilds per mounted EditorPanel,
// which under split-pane + large markdown is enough to wedge the renderer
// and black out the window (issue #826). Coalescing per (worktreeId + path)
// on a short debounce collapses that burst into one reload notification.
// Why: atomic writes burst same-path events; one reload dispatch each fans out into N EditorPanel rebuilds that can wedge the renderer (issue #826), so debounce per (worktreeId+path).
const EXTERNAL_RELOAD_DEBOUNCE_MS = 75
const pendingExternalReloadTimers = new Map<string, ReturnType<typeof setTimeout>>()
@@ -115,9 +105,7 @@ let cachedSshConnectionStates: AppState['sshConnectionStates'] | null = null
let cachedWatchedTargetsSnapshot: WatchedTargetsSnapshot = { targets: [], targetsKey: '' }
export function getWatchedTargetKey(target: WatchedTarget): string {
// Why: SSH worktrees can exist in the store before their remote filesystem
// provider is ready. Include connectionId so a local/unknown placeholder
// watch is replaced by the real SSH watch when the repo metadata hydrates.
// Why: include connectionId so a local placeholder watch is replaced by the real SSH watch once an SSH worktree's provider metadata hydrates.
return `${target.worktreeId}::${target.worktreePath}::${target.connectionId ?? 'local'}::${target.runtimeEnvironmentId ?? 'client'}`
}
@@ -145,18 +133,14 @@ export function getEditorExternalWatchTargets(
}
const targetOwnersByWorktreeId = new Map<string, Set<string | null>>()
// Why: watcher ownership is scoped by both worktree and runtime owner.
// The same path can be open locally and in a runtime-backed workspace at
// once; reads/saves already route per tab owner, so live reloads must too.
// Why: watcher ownership is scoped by worktree + runtime owner — the same path can be open locally and in a runtime workspace, and reads/saves already route per owner.
for (const f of state.openFiles) {
let owners = targetOwnersByWorktreeId.get(f.worktreeId)
if (!owners) {
owners = new Set()
targetOwnersByWorktreeId.set(f.worktreeId, owners)
}
// Why: persisted/restored local tabs may have runtimeEnvironmentId
// undefined. New openFile calls resolve active-runtime inheritance before
// storing the tab, so an ownerless stored tab must stay local here.
// Why: persisted/restored tabs may have runtimeEnvironmentId undefined; new openFile calls resolve inheritance before storing, so an ownerless tab stays local.
owners.add(openFileRuntimeOwner(f))
}
const activeWorktreeId = state.activeWorktreeId
@@ -179,16 +163,13 @@ export function getEditorExternalWatchTargets(
((state.rightSidebarTab === 'explorer' && state.rightSidebarExplorerView === 'files') ||
(state.rightSidebarTab === 'source-control' && sourceControlCanConsumeWatch))
if (activeWorktreeNeedsSidebarWatch) {
// Why: this app-level watcher owns subscriptions for Explorer and Source
// Control so downstream consumers do not fight over watch/unwatch IPC.
// Why: this app-level watcher owns Explorer/Source-Control subscriptions so downstream consumers don't fight over watch/unwatch IPC.
let owners = targetOwnersByWorktreeId.get(activeWorktreeId)
if (!owners) {
owners = new Set()
targetOwnersByWorktreeId.set(activeWorktreeId, owners)
}
// Why: sidebar consumers are mounted for the selected worktree. Their
// watcher must follow that worktree's host owner, not the host currently
// focused in the UI.
// Why: sidebar watcher must follow the selected worktree's host owner, not the host currently focused in the UI.
owners.add(getRuntimeEnvironmentIdForWorktree(state, activeWorktreeId))
}
@@ -236,16 +217,7 @@ export function getEditorExternalWatchTargets(
return cachedWatchedTargetsSnapshot
}
// Why: macOS atomic writes (Claude Code Edit, vim :w, VSCode save) deliver a
// delete event immediately followed by a create event for the same path. When
// those two land in separate fs:changed payloads a few ms apart, the tab
// flickers struck-through for one render before the follow-up create clears
// it. Debouncing just the 'deleted' signal — keyed by absolute path — lets a
// same-path create in the next payload cancel the tombstone before it ever
// paints. Key by owner as well as path so local/runtime tabs for the same
// worktree file cannot cancel each other's tombstones. A naked delete still
// resolves to 'deleted' after the window. The in-payload rename correlation
// is unchanged.
// Why: macOS atomic writes split delete→create across payloads; debounce the 'deleted' signal so a same-path create cancels the tombstone before it paints. Key by owner+path so a local and runtime tab for the same file can't cancel each other's tombstones.
const EXTERNAL_MUTATION_DEBOUNCE_MS = 75
type PendingDeleteTimer = {
@@ -258,14 +230,7 @@ type PendingDeleteTimer = {
* has an editor tab open, and notifies the editor to reload clean tabs when
* their on-disk contents change.
*
* Why: the File Explorer panel's watcher hook is unmounted whenever the user
* switches the right sidebar to Source Control / Checks / Search. Relying on
* that panel to dispatch editor-reload notifications means terminal edits go
* unnoticed while any non-Explorer sidebar tab is active. Lifting the
* editor-reload subscription to an always-mounted hook mirrors VSCode's
* `TextFileEditorModelManager`, which subscribes to `fileService
* .onDidFilesChange` once at the workbench level and reloads non-dirty models
* regardless of which UI panel is visible.
* Why: the File Explorer watcher unmounts when the sidebar leaves Explorer, so lifting this to an always-mounted hook keeps terminal edits noticed everywhere.
*/
export function useEditorExternalWatch(): void {
const { targets, targetsKey } = useAppStore(getEditorExternalWatchTargets)
@@ -278,10 +243,7 @@ export function useEditorExternalWatch(): void {
((payload: FsChangedPayload, runtimeEnvironmentId?: string | null) => void) | null
>(null)
// Why: diff previous vs next targets so unchanged worktrees keep their
// existing subscription. Tearing down every subscription on each targetsKey
// change (e.g. opening/closing a tab in an already-watched worktree) causes
// a watcher churn that can drop events emitted during the gap.
// Why: diff prev vs next targets so unchanged worktrees keep their subscription; tearing down all on every targetsKey change churns watchers and drops events in the gap.
useEffect(() => {
const nextTargets = latestTargetsRef.current
const prev = targetsRef.current
@@ -346,22 +308,15 @@ export function useEditorExternalWatch(): void {
connectionId: target.connectionId
})
.catch((err) => {
// Why: remote SSH providers can disappear while tabs still reference
// the worktree. Watching should degrade to a diagnostic, not an
// uncaught renderer promise that looks like the terminal froze.
// Why: remote SSH providers can disappear while tabs still reference the worktree; degrade to a diagnostic, not an uncaught renderer promise.
warnExternalWatchFailure(target, err)
})
}
targetsRef.current = nextTargets
// Why: this effect is intentionally differential — it does not unwatch on
// cleanup. Final unmount unwatching lives in the separate [] effect below
// so that re-running on targetsKey changes doesn't tear down everything.
// Why: intentionally differential — no unwatch on cleanup; final unmount unwatching lives in the [] effect below so targetsKey changes don't tear down everything.
}, [targetsKey])
// Why: the fs:changed subscription and the final unmount unwatch are
// independent of which worktrees are currently watched. Keeping them in a
// single always-mounted effect avoids re-subscribing on every targetsKey
// change (which would otherwise miss events fired during re-subscription).
// Why: keep the fs:changed subscription in an always-mounted [] effect so it doesn't re-subscribe on every targetsKey change and miss events fired during the gap.
useEffect(() => {
const remoteWatchUnsubs = remoteWatchUnsubsRef.current
const { handleFsChanged, dispose } = createExternalWatchEventHandler(
@@ -380,9 +335,7 @@ export function useEditorExternalWatch(): void {
unsubscribe()
dispose()
fsChangedHandlerRef.current = null
// Why: final unmount must tear down every outstanding subscription.
// The differential watch effect above intentionally never unwatches on
// cleanup, so this is the only place that clears them.
// Why: the differential watch effect never unwatches on cleanup, so final unmount is the only place that tears down every subscription.
for (const target of targetsRef.current) {
const key = getWatchedTargetKey(target)
const remoteUnsubscribe = remoteWatchUnsubs.get(key)
@@ -397,21 +350,15 @@ export function useEditorExternalWatch(): void {
}
remoteWatchUnsubs.clear()
targetsRef.current = []
// Why: deliberately do NOT clear pendingExternalReloadTimers here.
// The map is module-scoped, so in React StrictMode (dev) the first
// mount's cleanup would otherwise drop timers scheduled by the second
// mount. A late `notifyEditorExternalFileChange` dispatch after unmount
// is also harmless — it's a window event with no EditorPanel listeners
// attached once the editor tree is torn down.
// Why: don't clear the module-scoped pendingExternalReloadTimers — StrictMode's first-mount cleanup would drop the second mount's timers; a late dispatch is harmless.
}
}, [])
}
/**
* Builds the fs:changed handler used by `useEditorExternalWatch`. Exported
* so tests can drive the full event pipeline — including the debounced
* tombstone coalescer — without mounting the hook. See
* `EXTERNAL_MUTATION_DEBOUNCE_MS` for the macOS atomic-write rationale.
* Builds the fs:changed handler used by `useEditorExternalWatch`. Exported so
* tests can drive the full event pipeline (including the tombstone coalescer)
* without mounting the hook.
*/
export function createExternalWatchEventHandler(
findTarget: (
@@ -422,10 +369,7 @@ export function createExternalWatchEventHandler(
handleFsChanged: (payload: FsChangedPayload, runtimeEnvironmentId?: string | null) => void
dispose: () => void
} {
// Why: coalesce 'deleted' tombstones across back-to-back payloads so a
// same-path create arriving in the next payload (macOS atomic write)
// cancels the tombstone before the tab flashes. Keyed by normalized
// absolute path, scoped per-target. See EXTERNAL_MUTATION_DEBOUNCE_MS.
// Why: coalesce 'deleted' tombstones so a same-path create cancels them before the tab flashes (macOS atomic write). See EXTERNAL_MUTATION_DEBOUNCE_MS.
const pendingDeletes = new Map<string, PendingDeleteTimer>()
const pendingKey = (
worktreeId: string,
@@ -441,8 +385,7 @@ export function createExternalWatchEventHandler(
if (!target) {
return
}
// Why: this app-level hook owns worktree watcher subscriptions. Other
// consumers listen here so they do not fight over watch/unwatch ownership.
// Why: this app-level hook owns watcher subscriptions; other consumers listen here so they don't fight over watch/unwatch ownership.
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
window.dispatchEvent(
new CustomEvent<WorktreeFileChangeEventDetail>(ORCA_WORKTREE_FILE_CHANGE_EVENT, {
@@ -451,9 +394,7 @@ export function createExternalWatchEventHandler(
)
}
// Why: collect create/update paths first so we can cancel any pending
// same-path delete before scheduling a new one. This is what absorbs
// the macOS atomic-write delete→create split across two payloads.
// Why: collect create/update paths first to cancel any pending same-path delete — this absorbs the macOS atomic-write delete→create split across two payloads.
const createOrUpdatePaths = new Set<string>()
for (const evt of payload.events) {
if (evt.isDirectory === true) {
@@ -472,14 +413,8 @@ export function createExternalWatchEventHandler(
}
}
// Why: when an external process removes (or `git mv`s) a file that's
// open in the editor, keep the tab alive and mark it as deleted/renamed
// so the user can see the mutation and still access their in-memory
// content. A paired create-event in the same batch signals a rename;
// a lone delete is a hard delete. Resurrection (same path comes back
// on disk) clears the mark further down.
// Why: snapshot openFiles once so the delete/rename helpers below share a
// consistent view and we don't pay N store reads per payload.
// Why: mark editor tabs deleted/renamed instead of closing them so the user keeps in-memory content; a paired create means rename, a lone delete is hard.
// Why: snapshot openFiles once so the delete/rename helpers share a consistent view without N store reads per payload.
const openFilesAtStart = useAppStore.getState().openFiles
const deletedOpenEditorIds = collectDeletedOpenEditorIds(
payload,
@@ -487,26 +422,19 @@ export function createExternalWatchEventHandler(
target.runtimeEnvironmentId,
openFilesAtStart
)
// Why: correlate creates to deletes by basename OR parent directory to
// avoid mislabelling unrelated create+delete pairs in a batched payload
// as "renamed". When we can't correlate, default to 'deleted' — that's
// the least misleading fallback (it preserves in-memory content and
// doesn't claim a rename target that doesn't exist).
// Why: correlate creates to deletes by basename to avoid mislabelling unrelated create+delete pairs as "renamed"; default to 'deleted' when we can't correlate.
const hasPairedCreate =
deletedOpenEditorIds.length > 0 &&
hasRenameCorrelatedCreate(payload, target.worktreeId, deletedOpenEditorIds, openFilesAtStart)
if (deletedOpenEditorIds.length > 0) {
if (hasPairedCreate) {
// Why: single-payload delete+create is already correct — the rename
// label is visible in one render tick, so no debounce is needed.
// Why: single-payload delete+create is already correct in one render tick, so no debounce needed.
const setExternalMutation = useAppStore.getState().setExternalMutation
for (const fileId of deletedOpenEditorIds) {
setExternalMutation(fileId, 'renamed')
}
} else {
// Why: defer the 'deleted' tombstone so a follow-up same-path create
// in the next payload can cancel it. Build a fileId → path map so we
// can key the timer by the deleted file's absolute path.
// Why: defer the 'deleted' tombstone so a follow-up same-path create in the next payload can cancel it (macOS atomic write).
const deletePathByFileId = buildDeletePathByFileId(
payload,
target.worktreeId,
@@ -527,12 +455,7 @@ export function createExternalWatchEventHandler(
}
const timer = setTimeout(() => {
pendingDeletes.delete(key)
// Why: the debounce widens the window between scheduling the
// tombstone and applying it; the tab may have been closed or
// switched out of edit mode in between. Re-check both before
// writing so we don't resurrect state for a dropped fileId or
// tombstone a non-edit tab (mirrors the scheduling-time filter
// in `collectDeletedOpenEditorIds`).
// Why: the debounce window lets the tab close or leave edit mode, so re-check before writing to avoid tombstoning a dropped or non-edit tab.
const state = useAppStore.getState()
const stillEditing = state.openFiles.some((f) => f.id === fileId && f.mode === 'edit')
if (stillEditing) {
@@ -544,13 +467,7 @@ export function createExternalWatchEventHandler(
}
}
// Why: if a previously-deleted file reappears at the same path (e.g.
// the user ran `git checkout`), clear the tombstone so the tab returns
// to its normal state and any non-dirty content gets reloaded below.
// `createOrUpdatePaths` was collected above. Scoped to deleted/renamed:
// a 'changed' mark means the file was rewritten while the tab was dirty,
// so a further update event must not clear it — it resolves via reload,
// save, or the reload path below.
// Why: a reappearing file (e.g. `git checkout`) clears its deleted/renamed tombstone — but not a 'changed' mark, which resolves via reload/save instead.
if (createOrUpdatePaths.size > 0) {
const state = useAppStore.getState()
for (const file of state.openFiles) {
@@ -569,17 +486,11 @@ export function createExternalWatchEventHandler(
const changedFiles = new Set<string>()
for (const evt of payload.events) {
if (evt.kind === 'overflow') {
// Why: overflow payloads omit per-path create/update info, so any
// stale tombstone must be cleared conservatively before we decide
// which clean tabs to reload. Otherwise a file that reappeared on
// disk during the overrun stays struck through until some later
// path-specific event happens to clear it.
// Why: overflow omits per-path info, so conservatively clear stale tombstones or a file that reappeared during the overrun stays struck through.
for (const notification of getOverflowExternalReloadTargets(target)) {
scheduleDebouncedExternalReload(notification)
}
// Why: `break` (not `return`) — the remaining code early-returns
// when changedFiles is empty, so breaking out is semantically
// equivalent and more robust to future code added after the loop.
// Why: `break` not `return` — changedFiles is empty so the rest early-returns anyway, and this is more robust to code added after the loop.
break
}
@@ -588,10 +499,7 @@ export function createExternalWatchEventHandler(
}
if (evt.kind === 'delete') {
// Why: delete events are already handled above by marking the tab
// as tombstoned. Feeding them into the reload pipeline would fire
// `readFile` against the ENOENT path and replace the in-memory
// content with "Error loading file..." — losing the user's view.
// Why: deletes are tombstoned above; feeding them into reload would read the ENOENT path and replace in-memory content with an error, losing the user's view.
continue
}
@@ -609,15 +517,9 @@ export function createExternalWatchEventHandler(
return
}
// Why: skip notifying for any tab with unsaved edits so external writes
// don't silently destroy the user's work. Mirrors the dirty guard in
// `useFileExplorerHandlers`. Read `openFiles` once per payload to avoid
// N store reads for large batched events.
// Why: read openFiles once per payload to avoid N store reads on large batches; consumers skip dirty tabs so external writes don't destroy unsaved work.
const openFilesSnapshot = useAppStore.getState().openFiles
// Why: a combined "Changes" tab matches no single path but renders every
// changed file's working-tree diff. This is per-worktree, not per-path, so
// compute it once instead of rescanning openFiles for each changed file in
// a large batched payload (e.g. a branch switch touching hundreds of files).
// Why: the combined "Changes" tab is per-worktree not per-path, so compute it once instead of rescanning openFiles per changed file in a large batched payload.
const hasCombinedDiffConsumer = openFilesSnapshot.some(
(f) =>
f.worktreeId === target.worktreeId &&
@@ -633,10 +535,7 @@ export function createExternalWatchEventHandler(
}
const matching = getOpenFilesForExternalFileChange(openFilesSnapshot, notification)
if (matching.length === 0) {
// Why: notify the combined-diff tab so its section reloads. Its own
// dirty/section guards make a blanket reload safe, and there is no
// in-memory editor content to clobber, so self-write suppression is
// unnecessary here.
// Why: combined-diff tab has no in-memory content to clobber and guards its own reload, so notify it directly without self-write suppression.
if (hasCombinedDiffConsumer) {
scheduleDebouncedExternalReload(notification)
}
@@ -644,15 +543,11 @@ export function createExternalWatchEventHandler(
}
const dirtyMatches = matching.filter((f) => f.isDirty)
if (dirtyMatches.length > 0) {
// Why: an external write landing on a dirty tab must not vanish
// silently (issue #7265) — the user was left with a stale tab and a
// save that clobbered the newer disk content. Mark the tab so the
// editor shows a changed-on-disk banner with an explicit reload path.
// Why: an external write on a dirty tab must not vanish silently (issue #7265) — mark it so the editor shows a changed-on-disk banner with a reload path.
scheduleChangedOnDiskMark(
target,
notification,
// Why: canAutoSaveOpenFile is exactly the set of tabs that can hold
// unsaved edits (edit + unstaged diff) — the tabs the banner serves.
// Why: canAutoSaveOpenFile is exactly the tabs that can hold unsaved edits (edit + unstaged diff) — the tabs the banner serves.
dirtyMatches.filter((dirtyFile) => canAutoSaveOpenFile(dirtyFile)).map((f) => f.id)
)
if (dirtyMatches.length === matching.length) {
@@ -661,8 +556,7 @@ export function createExternalWatchEventHandler(
}
continue
}
// Clean sibling tabs (e.g. an unstaged diff of the same path) still
// reload below; every notification consumer skips dirty files.
// Clean sibling tabs (e.g. an unstaged diff of the same path) still reload below; consumers skip dirty files.
}
const absolutePath = joinPath(notification.worktreePath, notification.relativePath)
const recentSelfWrite = getRecentSelfWrite(absolutePath, target.runtimeEnvironmentId)
@@ -675,8 +569,7 @@ export function createExternalWatchEventHandler(
}
const dispose = (): void => {
// Why: clear in-flight debounced tombstone timers so they don't fire
// after disposal and touch a no-longer-relevant store.
// Why: clear in-flight tombstone timers so they don't fire after disposal and touch a stale store.
for (const pending of pendingDeletes.values()) {
clearTimeout(pending.timer)
}
@@ -688,10 +581,7 @@ export function createExternalWatchEventHandler(
const inFlightEchoVerificationReads = new Map<string, ReturnType<typeof readRuntimeFileContent>>()
// Why: one save echo can arrive as a burst of watcher payloads (SSH poll +
// event streams), and each verification is a full-file read — on remote
// transports a network round-trip. Concurrent payloads for the same file
// share the in-flight read instead of stacking duplicates.
// Why: one save echo can arrive as a burst of payloads; share the in-flight full-file read so concurrent payloads for the same file don't stack duplicate reads.
function readFileForEchoVerification(args: {
runtimeEnvironmentId: string | null | undefined
filePath: string
@@ -726,8 +616,7 @@ function markTabsChangedOnDisk(fileIds: string[], connectionId: string | undefin
const state = useAppStore.getState()
for (const fileId of fileIds) {
const file = state.openFiles.find((f) => f.id === fileId)
// Why: echo verification resolves async — a save or reload may already
// have resolved the conflict; the helper only marks still-dirty tabs.
// Why: echo verification resolves async — the tab may have been closed since, so only mark files still open.
if (file) {
markFileChangedOnDisk(state, file, { connectionId, origin: 'live' })
}
@@ -744,9 +633,7 @@ function scheduleChangedOnDiskMark(
}
const absolutePath = joinPath(notification.worktreePath, notification.relativePath)
const recentSelfWrite = getRecentSelfWrite(absolutePath, target.runtimeEnvironmentId)
// Why: the fs event may be the echo of Orca's own save racing keystrokes
// typed during the write. Marking on the echo would show a false "changed
// on disk" banner, so verify disk really differs from our last write.
// Why: the fs event may be the echo of Orca's own save — verify disk really differs from our last write before showing a "changed on disk" banner.
if (!recentSelfWrite || recentSelfWrite.content === null) {
markTabsChangedOnDisk(fileIds, target.connectionId)
return
@@ -764,8 +651,7 @@ function scheduleChangedOnDiskMark(
}
})
.catch(() => {
// Why: unreadable disk state can't disprove an external change — keep
// the conflict visible rather than risk a silent overwrite.
// Why: unreadable disk state can't disprove an external change — keep the conflict visible rather than risk a silent overwrite.
markTabsChangedOnDisk(fileIds, target.connectionId)
})
}
@@ -782,9 +668,7 @@ function scheduleSelfWriteAwareExternalReload(
}
const runtimeEnvironmentId = file.runtimeEnvironmentId ?? target.runtimeEnvironmentId
// Why: a recent self-write stamp only proves the path changed recently; an
// agent can write a newer version inside the same TTL. Compare disk content
// with the saved text so we suppress only the echo of Orca's own write.
// Why: a self-write stamp only proves recent change; compare disk content so we suppress only Orca's own echo, not a newer agent write in the same TTL.
void readFileForEchoVerification({
runtimeEnvironmentId,
filePath: file.filePath,
@@ -811,8 +695,7 @@ function scheduleSelfWriteAwareExternalReload(
function hasCleanExternalReloadTarget(notification: ExternalWatchNotification): boolean {
const matching = getOpenFilesForExternalFileChange(useAppStore.getState().openFiles, notification)
// Why: one clean target is enough — every notification consumer skips dirty
// files per-file, so a dirty sibling tab no longer vetoes the reload.
// Why: one clean target is enough — consumers skip dirty files per-file, so a dirty sibling doesn't veto the reload.
return matching.some((file) => !file.isDirty)
}
@@ -834,11 +717,7 @@ export function getOverflowExternalReloadTargets(
continue
}
if (file.externalMutation) {
// Why: overflow gives no per-path resurrection signal, so fall back to
// "assume it may exist again" and clear the tombstone before reloading.
// If the file is still gone, EditorPanel will preserve the current in-
// memory view by showing the read failure instead of leaving a permanent
// stale "deleted" badge with no path to recovery.
// Why: overflow gives no per-path resurrection signal, so clear the tombstone and let a still-missing file surface as a read failure.
state.setExternalMutation(file.id, null)
}
notifications.push({
@@ -921,14 +800,7 @@ function collectDeletedOpenEditorIds(
* Returns true if the batched payload contains at least one file-create event
* whose basename matches a deleted open editor file.
*
* Why: a batched fs payload may include unrelated create+delete events. A
* blanket `events.some(kind === 'create')` would mislabel those as renames.
* Basename correlation catches the common `git mv` / `mv` case where the
* filename survives the move. We intentionally do NOT correlate by parent
* directory because editor save-as-temp patterns (`rm foo.md && touch
* foo.md.new`) routinely put unrelated creates in the same dir as a delete,
* which would produce false rename labels. When correlation fails the caller
* falls back to 'deleted', which is the least misleading default.
* Why: correlate by basename only, not parent dir — save-as-temp patterns (`rm foo.md && touch foo.md.new`) put unrelated creates in the same dir and would mislabel deletes as renames.
*/
function hasRenameCorrelatedCreate(
payload: FsChangedPayload,
File diff suppressed because it is too large Load Diff
+18 -63
View File
@@ -189,14 +189,9 @@ describe('detectAgentStatusFromTitle', () => {
})
// --- Cursor (cursor-agent) synthesized titles ---
// Why: cursor-agent's native OSC title stays literally "Cursor Agent" for
// the entire turn, so Orca synthesizes decorated titles from hook events
// to drive the existing spinner/unread pipeline. These tests pin the
// contract the main-process hook listener relies on.
// Why: cursor-agent's native title stays "Cursor Agent" all turn, so Orca synthesizes decorated titles for the spinner/unread pipeline.
it('treats the bare "Cursor Agent" native title as a no-op (not idle)', () => {
// Why: if the native title classified as idle, cursor's own per-turn
// re-emissions would trigger working→idle transitions between our
// synthesized working frames, stomping the spinner off mid-turn.
// Why: if the native title classified as idle, cursor's per-turn re-emissions would stomp the spinner off mid-turn.
expect(detectAgentStatusFromTitle('Cursor Agent')).toBeNull()
expect(detectAgentStatusFromTitle('cursor agent')).toBeNull()
expect(detectAgentStatusFromTitle(' Cursor Agent ')).toBeNull()
@@ -246,10 +241,7 @@ describe('detectAgentStatusFromTitle', () => {
expect(detectAgentStatusFromTitle('Codex Working')).toBe('working')
})
// Why: `containsAgentName` token-matches legacy agent names, so a cwd-path
// fragment like "~/codex-scratch" (hyphen-adjacent) or "opencode-blinker"
// (the worktree name that mislabeled Codex tabs as OpenCode) no longer mints
// an 'idle' agent signal. A bare "~/codex" path still has no strong keyword.
// Why: `containsAgentName` token-matches, so cwd-path fragments like "~/codex-scratch" no longer mint an 'idle' agent signal.
it('does not treat cwd-path agent-name fragments as agent activity', () => {
expect(detectAgentStatusFromTitle('~/codex-scratch')).toBeNull()
expect(detectAgentStatusFromTitle('~/codex already built')).toBeNull()
@@ -257,10 +249,7 @@ describe('detectAgentStatusFromTitle', () => {
expect(detectAgentStatusFromTitle('claude-scratch')).toBeNull()
})
// Why: short agent names are unsafe under substring detection. Telemetry now
// records explicit launch facts rather than widening OSC-title inference, so
// this detector must not grow aliases that turn ordinary shell titles like
// "timestamp ready" into agent activity.
// Why: short agent names are unsafe under substring detection; don't add aliases that turn "timestamp ready" into agent activity.
it('does not treat ordinary words containing "amp" as agent titles', () => {
expect(detectAgentStatusFromTitle('timestamp ready')).toBeNull()
expect(detectAgentStatusFromTitle('clamp working')).toBeNull()
@@ -280,15 +269,7 @@ describe('detectAgentStatusFromTitle', () => {
})
})
// Why: regression guard for the STRONG_WORKING_KEYWORDS_RE path-separator
// false positive. Before the lookarounds were widened to `[\w./\\-]`, a title
// like `~/codex/working` matched STRONG_WORKING_KEYWORDS_RE (because `/` is
// not in `[\w\-]`) and the function classified a plain path as 'working',
// driving spinners and agent counts off a shell cwd. The idle-side fallback
// at the bottom of `detectAgentStatusFromTitle` still returns 'idle' for
// agent-name-containing titles — that's the known `containsAgentName`
// substring gap documented in the test above — so the behavior this block
// pins is specifically "no path fragment is ever classified as 'working'."
// Why: regression guard — a path fragment like `~/codex/working` must never classify as 'working' (path separators aren't word boundaries).
describe('detectAgentStatusFromTitle path-separator rejection', () => {
test('rejects working keywords adjacent to POSIX path separators', () => {
expect(detectAgentStatusFromTitle('~/codex/working')).not.toBe('working')
@@ -314,9 +295,7 @@ describe('detectAgentStatusFromTitle path-separator rejection', () => {
expect(detectAgentStatusFromTitle('Aider thinking')).toBe('working')
})
// Why: path separators only need to be blocked on the LEFT of the keyword
// (where path fragments sit). Blocking them on the right would regress
// legitimate sentence-style titles where a keyword is followed by `.`/`!`/`?`.
// Why: block path separators only on the LEFT of the keyword; blocking the right would regress titles ending in `.`/`!`/`?`.
test('still accepts keywords followed by trailing punctuation', () => {
expect(detectAgentStatusFromTitle('Codex done.')).toBe('idle')
expect(detectAgentStatusFromTitle('Aider idle!')).toBe('idle')
@@ -355,12 +334,7 @@ describe('clearWorkingIndicators', () => {
expect(clearWorkingIndicators('Terminal 1')).toBe('Terminal 1')
})
// Why: clearWorkingIndicators must use the same hyphen/word-char-aware
// boundary as STRONG_WORKING_KEYWORDS_RE (agent-detection.ts). A prior
// implementation used plain `\b${keyword}\b` which — since `-` is a
// non-word char — would strip "working" out of "codex is-working-cap"
// even though detectAgentStatusFromTitle correctly refuses to classify
// that title as 'working'. The clearer and detector must stay symmetric.
// Why: clearWorkingIndicators must use the same hyphen-aware boundary as STRONG_WORKING_KEYWORDS_RE so clearer and detector stay symmetric.
it('does not strip working keywords inside hyphenated compounds', () => {
expect(clearWorkingIndicators('codex is-working-cap')).toBe('codex is-working-cap')
expect(clearWorkingIndicators('claude reworking diff')).toBe('claude reworking diff')
@@ -391,8 +365,7 @@ describe('normalizeTerminalTitle', () => {
})
it('collapses Grok rotating working titles to one stable label', () => {
// Grok interpolates a rotating status/tool phrase between the spinner and its
// name, so each frame is a distinct title; they must all fold to one label.
// Grok interpolates a rotating phrase between spinner and name, so each frame differs; all must fold to one label.
expect(normalizeTerminalTitle('⠋ - Waiting for response… - grok')).toBe('⠋ Grok')
expect(normalizeTerminalTitle('⠴ - Thinking - grok')).toBe('⠋ Grok')
expect(normalizeTerminalTitle('⠙ - Responding - grok')).toBe('⠋ Grok')
@@ -410,8 +383,7 @@ describe('normalizeTerminalTitle', () => {
expect(normalizeTerminalTitle('Fix the auth bug - grok')).toBe('Fix the auth bug - grok')
// Names "grok" mid-title but ends with another agent → not a Grok frame.
expect(normalizeTerminalTitle('⠋ debugging grok - claude')).toBe('⠋ debugging grok - claude')
// Claude/Codex task text ending in "grok" must not collapse — only the
// Grok frame shape "spinner - phrase - grok" is the rotating-frame signal.
// Only the Grok frame shape "spinner - phrase - grok" is the rotating-frame signal; task text ending in "grok" must not collapse.
expect(normalizeTerminalTitle('⠋ wire up grok')).toBe('⠋ wire up grok')
expect(normalizeTerminalTitle('⠋ Codex is thinking about grok')).toBe(
'⠋ Codex is thinking about grok'
@@ -511,10 +483,7 @@ describe('getAgentLabel', () => {
expect(getAgentLabel('android emulator ready')).toBeNull()
})
// Why: cwd/worktree titles embed agent-name fragments. Substring matching
// mislabeled a Codex tab whose title fell back to the "opencode-blinker"
// worktree name as OpenCode. Token matching must reject these fragments for
// every legacy agent name.
// Why: substring matching mislabeled cwd/worktree name fragments (e.g. "opencode-blinker") as agents; token-match to reject them.
it('does not label cwd/worktree path fragments as an agent', () => {
expect(getAgentLabel('opencode-blinker')).toBeNull()
expect(getAgentLabel('claude-scratch')).toBeNull()
@@ -534,9 +503,7 @@ describe('getAgentLabel', () => {
expect(getAgentLabel('Devin working')).toBe('Devin')
})
// Why: `cursor` is ordinary editor vocabulary in another agent's task title, so a
// bare token is not Cursor identity — a Claude tab working on cursor code was being
// mislabeled Cursor on the worktree card. Match Cursor's closed title set only.
// Why: "cursor" is ordinary editor vocabulary, so a bare token isn't Cursor identity; match Cursor's closed title set only.
it('labels Cursor by identity, not a bare "cursor" token in another agent title', () => {
expect(getAgentLabel('Cursor Agent')).toBe('Cursor')
expect(getAgentLabel('⠋ Cursor Agent')).toBe('Cursor')
@@ -555,8 +522,7 @@ describe('isClaudeAgent', () => {
expect(isClaudeAgent('OpenClaude ready')).toBe(false)
})
// Why: a braille Claude title merely mentioning a text cursor is still Claude, so its
// prompt-cache paths must fire; only Cursor's own identity titles are excluded.
// Why: a Claude title merely mentioning a text cursor is still Claude; only Cursor's own identity titles are excluded.
it('counts cursor-mentioning Claude braille titles as Claude, excludes real Cursor', () => {
expect(isClaudeAgent('⠋ preserve cursor visibility across replays')).toBe(true)
expect(isClaudeAgent('⠋ Cursor Agent')).toBe(false)
@@ -585,8 +551,7 @@ describe('isClaudeAgent', () => {
describe('createAgentStatusTracker', () => {
// --- Claude Code: real captured OSC title sequence (v2.1.86) ---
// CRITICAL: Claude Code changes the title to the TASK DESCRIPTION,
// not "Claude Code". The ✳ prefix is the only reliable idle indicator.
// Claude Code sets the title to the TASK DESCRIPTION, not "Claude Code"; ✳ prefix is the only reliable idle indicator.
it('fires on Claude Code working → idle (real captured titles)', () => {
const onBecameIdle = vi.fn()
const tracker = createAgentStatusTracker(onBecameIdle)
@@ -655,9 +620,7 @@ describe('createAgentStatusTracker', () => {
expect(onBecameIdle).toHaveBeenCalledTimes(1)
})
// Why: end-to-end tracker coverage for cursor — synthesized working frames
// interleaved with cursor's own "Cursor Agent" re-emissions must not fire
// onBecameIdle until the "Cursor ready" done frame arrives.
// Why: cursor's native "Cursor Agent" re-emissions between synthesized working frames must not fire onBecameIdle before the done frame.
it('fires on Cursor working → idle across native "Cursor Agent" re-emissions', () => {
const onBecameIdle = vi.fn()
const tracker = createAgentStatusTracker(onBecameIdle)
@@ -739,10 +702,7 @@ describe('createAgentStatusTracker', () => {
expect(onBecameIdle).not.toHaveBeenCalled()
})
// Why: reset() clears the tracker's working latch so stale working→idle
// transitions cannot fire after the owning transport is torn down. Without
// this guarantee, a reattach or late title delivery could surface a
// phantom idle notification for work the user already dismissed.
// Why: reset() clears the working latch so a late/reattach idle title can't fire a phantom notification after teardown.
it('reset() clears working state so a subsequent idle does not fire onBecameIdle', () => {
const onBecameIdle = vi.fn()
const tracker = createAgentStatusTracker(onBecameIdle)
@@ -758,8 +718,7 @@ describe('createAgentStatusTracker', () => {
const onBecameIdle = vi.fn()
const tracker = createAgentStatusTracker(onBecameIdle)
// Simulate raw PTY data chunks containing OSC title sequences
// Uses real title patterns: task description, NOT "Claude Code"
// Real title patterns: task description, NOT "Claude Code"
const oscTitle = (title: string): string => `\x1b]0;${title}\x07`
const chunks = [
@@ -804,9 +763,7 @@ describe('createAgentStatusTracker', () => {
describe('isExplicitAgentStatusFresh', () => {
it('treats the boundary (now - updatedAt == staleAfterMs) as fresh', () => {
// Why: the function uses `<=`, so equality at the boundary must remain
// fresh. Protecting this invariant keeps entries from flipping to stale
// one tick earlier than the configured TTL implies.
// Why: uses `<=`, so equality at the boundary stays fresh (not stale one tick before the TTL).
const staleAfterMs = 60_000
const now = 1_000_000
const entry = { updatedAt: now - staleAfterMs }
@@ -930,9 +887,7 @@ describe('agentTypeToIconAgent', () => {
})
it('returns null for arbitrary non-iconable strings', () => {
// Why: guards against hook payloads reporting agentTypes that AgentIcon
// cannot render (e.g. "totally-fake-agent"); returning null lets the
// caller fall back to a neutral glyph instead of a broken icon.
// Why: unknown agentTypes must return null so the caller falls back to a neutral glyph, not a broken icon.
expect(agentTypeToIconAgent('totally-fake-agent')).toBeNull()
})
})
+11 -48
View File
@@ -5,9 +5,7 @@ import type { WorktreeStatus } from './worktree-status'
import { tuiAgentToAgentKind } from '../../../shared/agent-kind'
import type { AgentKind } from '../../../shared/telemetry-events'
// Re-export from shared module so existing renderer imports continue to work.
// Why: the main process now needs the same agent detection logic for stat
// tracking. Moving to shared avoids duplicating the detection code.
// Re-export from shared so existing renderer imports work; main process now shares the detection logic.
export {
type AgentStatus,
detectAgentStatusFromTitle,
@@ -25,13 +23,7 @@ import { classifyTitleActivity, resolveTitleActivityLabel } from './pane-agent-e
type AgentQueryArgs = {
tabsByWorktree: Record<string, TerminalTab[]>
runtimePaneTitlesByTabId: Record<string, Record<number, string>>
// Why: title-scraped agent activity (pane titles, tab.title) survives sleep
// because runtimePaneTitlesByTabId is intentionally preserved under
// keepIdentifiers for wake recovery. Without the live-PTY map, slept tabs
// whose preserved titles still match a working pattern would surface as
// working agents through the title-bar count, dock badge, and per-worktree
// aggregates. Threading ptyIdsByTabId lets every title-scrape branch gate
// on actual liveness (`tabHasLivePty`).
// Why: gates title-scraped activity on liveness — preserved-under-sleep titles would otherwise surface slept tabs as working.
ptyIdsByTabId: Record<string, string[]>
worktreesByRepo: Record<string, Worktree[]>
}
@@ -57,20 +49,14 @@ export function getWorkingAgentsPerWorktree({
const result: Record<string, WorktreeAgents> = {}
for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) {
// Why: tabsByWorktree can retain orphaned entries for worktrees that no
// longer exist in git (e.g. deleted worktrees whose tab cleanup didn't
// complete, or worktrees removed outside Orca). worktreesByRepo is the
// source of truth — only include worktrees that still exist.
// Why: tabsByWorktree can retain orphaned entries for deleted worktrees; worktreesByRepo is the source of truth.
if (!validIds.has(worktreeId)) {
continue
}
const agents: WorkingAgentEntry[] = []
for (const tab of tabs) {
// Why: title-scraped activity must be gated on actual PTY liveness.
// runtimePaneTitlesByTabId is preserved under sleep (keepIdentifiers),
// so a slept tab whose pane titles still match a working pattern would
// surface as a working agent without this gate.
// Why: pane titles are preserved under sleep (keepIdentifiers), so gate on live PTY or slept tabs surface as working agents.
if (!tabHasLivePty(ptyIdsByTabId, tab.id)) {
continue
}
@@ -105,23 +91,10 @@ export function getWorkingAgentsPerWorktree({
return result
}
// Re-exported from shared so mobile shows the same agent labels (one source of
// truth). Kept re-exported here so existing `@/lib/agent-status` importers work.
// Re-export: shared so mobile shows the same agent labels; kept here for existing importers.
export { formatAgentTypeLabel } from '../../../shared/agent-type-label'
// Why: AgentIcon expects a TuiAgent, but AgentType is a broader union
// (WellKnownAgentType | (string & {})) that includes 'unknown' and arbitrary
// strings reported by hook payloads. Return null for the unknown case so
// AgentIcon renders a neutral "?" glyph — using 'claude' as a fallback
// caused Codex panes to briefly show the Claude icon before the hook fired.
// Why: we also guard against arbitrary strings (e.g. a hook reporting
// agentType: "weirdo") by checking membership in an explicit record. A
// blind `as TuiAgent` cast would pass values through that AgentIcon can't
// render, producing a broken icon or falling back to an unrelated glyph.
// Why: modeled as `Record<TuiAgent, true>` rather than a Set so the TypeScript
// compiler fails to build when a TuiAgent member is added to shared/types.ts
// without being added here — a Set<TuiAgent> is structurally permissive and
// would silently accept a subset of the union.
// Why: Record<TuiAgent, true> (not a Set) forces a build error if a TuiAgent member is added without being listed here.
const ICONABLE_AGENT_TYPES: Record<TuiAgent, true> = {
claude: true,
'claude-agent-teams': true,
@@ -159,6 +132,7 @@ const ICONABLE_AGENT_TYPES: Record<TuiAgent, true> = {
ante: true
}
// Why: return null (not a 'claude' fallback) for unknown so Codex panes don't flash the Claude icon before the hook fires.
export function agentTypeToIconAgent(agentType: AgentType | null | undefined): TuiAgent | null {
if (!agentType || agentType === 'unknown') {
return null
@@ -168,16 +142,13 @@ export function agentTypeToIconAgent(agentType: AgentType | null | undefined): T
: null
}
// Why: telemetry's `agent_kind` enum derives from the TuiAgent mapping. Share
// one resolver so the notes-send dropdown and the sidebar send path stamp
// identical agent_kind values on `agent_prompt_sent`.
// Why: shared resolver so all send paths stamp identical agent_kind on agent_prompt_sent telemetry.
export function agentKindForAgentType(agentType: AgentType | null | undefined): AgentKind {
const tuiAgent = agentTypeToIconAgent(agentType)
return tuiAgent ? tuiAgentToAgentKind(tuiAgent) : 'other'
}
// Why: the freshness gate moved into the pane-agent-evidence resolvers; the
// re-export keeps this module's many existing importers unchanged.
// Re-export: freshness gate moved into pane-agent-evidence; keeps existing importers unchanged.
export { isExplicitAgentStatusFresh } from './pane-agent-evidence'
/**
@@ -239,21 +210,13 @@ function countWorkingAgentsForTab(
runtimePaneTitlesByTabId: Record<string, Record<number, string>>,
ptyIdsByTabId: Record<string, string[]>
): number {
// Why: liveness precondition shared with getWorkingAgentsPerWorktree.
// runtimePaneTitlesByTabId is preserved under sleep (keepIdentifiers) and
// tab.ptyId is the wake-hint sessionId, not a liveness signal. Without
// this gate, slept tabs whose preserved titles still match a working
// pattern would inflate the title-bar agent count and dock badge.
// Why: pane titles are preserved under sleep (keepIdentifiers), so gate on live PTY or slept tabs inflate the agent count.
if (!tabHasLivePty(ptyIdsByTabId, tab.id)) {
return 0
}
let count = 0
const paneTitles = runtimePaneTitlesByTabId[tab.id]
// Why: split-pane tabs can host multiple concurrent agents, but the
// legacy tab title only reflects the last pane title update that won the
// tab label. Prefer pane-level titles whenever TerminalPane is mounted,
// and fall back to the tab title only for tabs we have not mounted yet
// (for example restored-but-unvisited worktrees).
// Why: split-pane tabs host multiple agents; the tab title only shows the last pane update, so prefer pane titles when mounted.
if (paneTitles && Object.keys(paneTitles).length > 0) {
for (const title of Object.values(paneTitles)) {
if (classifyTitleActivity(title) === 'working') {
+23 -71
View File
@@ -34,24 +34,19 @@ import { seedNativeChatAppliedSessionOptions } from '@/components/native-chat/na
export type LaunchAgentInNewTabArgs = {
agent: TuiAgent
worktreeId: string
/** The tab group the user clicked from. Keeps split-group launches in the
* pane the user initiated from instead of falling through to the active group. */
/** Tab group the user launched from; keeps split-group launches in that pane instead of the active group. */
groupId?: string
/** Optional initial prompt. Delivery depends on `promptDelivery` and the
* agent's prompt mode. */
/** Optional initial prompt; delivery depends on `promptDelivery` and the agent's prompt mode. */
prompt?: string
/** Optional CLI arguments appended to the selected agent command. */
agentArgs?: string | null
/** Force generated prompt text out of the shell launch command. `draft`
* leaves it editable; `submit-after-ready` sends it once the TUI is ready. */
/** How to deliver the prompt: `draft` leaves it editable, `submit-after-ready` sends it once the TUI is ready. */
promptDelivery?: 'auto-submit' | 'draft' | 'submit-after-ready'
/** Telemetry surface that initiated this launch. Defaults to the tab-bar
* quick-launch entry point so existing callers stay unchanged. */
/** Telemetry surface that initiated this launch. Defaults to the tab-bar quick-launch entry point. */
launchSource?: LaunchSource
/** User-authored Quick Command label for local tabs created from the tab bar. */
quickCommandLabel?: string | null
/** Shell platform that will execute the startup command. Defaults to the
* renderer OS; SSH and WSL worktrees run a Linux shell even from Windows. */
/** Shell platform for the startup command; defaults to renderer OS. SSH/WSL worktrees run Linux even from Windows. */
launchPlatform?: NodeJS.Platform
/** Called after the prompt is actually delivered to the agent input path. */
onPromptDelivered?: () => void
@@ -68,23 +63,11 @@ export type LaunchAgentInNewTabResult = {
* Create a new terminal tab and queue the agent's launch command, optionally
* with an initial prompt.
*
* Why: this is the single entry point for "launch agent X in a new tab" from
* the tab-bar quick-launch menu and the Source Control "send notes to agent"
* action. It mirrors the `+` button's path (`createNewTerminalTab`) — createTab,
* flip `activeTabType` to terminal, and persist the appended tab-bar order —
* then queues the agent startup through the same `pendingStartupByTabId`
* channel the new-workspace ("cmd+N") flow uses. TerminalPane consumes the
* queued command on first mount and the local PTY provider writes it once the
* shell is ready (see `pty-connection.ts`: startup-command path).
* Submission mode follows `promptInjectionMode`: argv/flag agents fold the
* prompt into the launch command; followup-path agents launch empty and get a
* post-ready draft paste. Callers can override via `promptDelivery`.
*
* Default submission mode follows `promptInjectionMode`: argv/flag agents
* include the prompt directly in the launch command, while followup-path
* agents launch empty and receive a post-ready draft paste. Generated contexts
* can override this with draft or submit-after-ready delivery.
*
* Returns `null` when no startup plan can be built — for example, a whitespace-
* only prompt on the trim-empty branch of `buildAgentStartupPlan`. Callers
* surface that as a launch failure (see `QuickLaunchButton.runLaunch`).
* Returns `null` when no startup plan can be built (e.g. a whitespace-only prompt).
*/
export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentInNewTabResult {
const {
@@ -110,8 +93,7 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
repo.connectionId ? undefined : getLocalProjectExecutionRuntimeContext(store, worktreeId)
)
: CLIENT_PLATFORM)
// Why: SSH remotes deploy the CLI shim as plain `orca`, so the Linux-only
// `orca-ide` rename must not be applied for remote launches.
// Why: SSH remotes deploy the shim as plain `orca`, so skip the Linux-only `orca-ide` rename for remote launches.
const isRemote = repo ? repoIsRemote(repo) : false
const queuedShell = resolveLocalWindowsAgentStartupShell({
platform: resolvedLaunchPlatform,
@@ -140,12 +122,7 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
const trimmedPrompt = prompt?.trim() ?? ''
const hasPrompt = trimmedPrompt.length > 0
const isFollowupPath = TUI_AGENT_CONFIG[agent].promptInjectionMode === 'stdin-after-start'
// Why: argv/flag agents fold the prompt into the launch command and
// auto-submit — keeping behavior consistent with the composer/tab-bar `+`
// mental model, where the prompt is "the first turn the user sent".
// Followup-path and generated-context launches can deliver a prompt via
// post-launch bracketed paste; callers decide whether that paste remains a
// draft or submits after readiness.
// argv/flag agents fold the prompt into the launch command; followup/generated launches deliver it via post-launch paste.
let startupPlan: AgentStartupPlan | null = null
let pasteDraftAfterLaunch: string | null = null
let submitPastedPrompt = false
@@ -153,8 +130,7 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
let promptDeliveryResult: Promise<{ delivered: boolean; failureNotified: boolean }> | undefined
if (hasPrompt && promptDelivery === 'submit-after-ready') {
// Why: generated multi-line prompts are too large to echo through a shell
// argv/prefill command. Launch cleanly, then paste+submit inside the TUI.
// Why: multi-line generated prompts are too large for a shell argv, so launch clean then paste+submit in the TUI.
startupPlan = buildAgentStartupPlan({
...startupPlanBase,
prompt: '',
@@ -210,8 +186,7 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
return null
}
// Why: host-owned paired tabs must receive the same initial-view decision as
// local tabs; the remote host cannot infer this client's draft/default choice.
// Why: the remote host can't infer this client's draft/default view choice, so decide it here for paired tabs too.
const viewModePromptDelivery =
hasPrompt && isFollowupPath && promptDelivery === 'auto-submit' ? 'draft' : promptDelivery
const initialViewModeProps = initialAgentTabViewModeProps(store.settings, {
@@ -231,23 +206,15 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
groupId,
hasPrompt,
startupPlan,
// Why: omission means terminal locally, but would let a paired host apply
// its own default; send the client's resolved terminal choice explicitly.
// Why: send the client's resolved terminal choice explicitly, else a paired host applies its own default.
viewMode: initialViewModeProps.viewMode ?? 'terminal',
onPromptDelivered
})
return { tabId: null, startupPlan, pasteDraftAfterLaunch: false }
}
// Why: queue the startup command BEFORE TerminalPane mounts — it captures
// `pendingStartupByTabId[tabId]` in useState on first render. If the queue
// lands after mount the agent binary never starts; the user sees a bare shell.
// Since both calls happen synchronously in the same React batch, the queue
// is in place by the time the pane commits.
// Why: the followup path pastes the prompt as an unsubmitted draft (submit
// stays false), so gate the initial chat view like a `draft` launch —
// otherwise a default `auto-submit` followup would open native chat with no
// submitted turn to render.
// Why: queue startup BEFORE TerminalPane mounts — it snapshots pendingStartupByTabId in useState on first render.
// Why: followup path pastes an unsubmitted draft, so gate the initial chat view like a draft launch, not auto-submit.
const tab = store.createTab(worktreeId, groupId, undefined, {
launchAgent: agent,
quickCommandLabel,
@@ -271,17 +238,10 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
request_kind: 'new'
}
})
// Why: schedule the bracketed-paste-after-ready follow-up immediately after
// the startup command is queued. Fire-and-forget so callers keep their
// synchronous `{ tabId, startupPlan }` signature. The helper short-circuits
// for agents with a `draftPromptFlag`, so calling it on the followup path
// is safe even when the draft was already injected via the native flag.
// Why: fire-and-forget the paste-after-ready delivery so callers keep the synchronous { tabId, startupPlan } signature.
// Why: safe to call unconditionally — the helper short-circuits (no paste) for native-prefill agents already holding the draft.
if (pasteDraftAfterLaunch !== null) {
// Why: surface silent paste failures — without onTimeout, a stalled agent
// readiness wait drops the user's notes with no feedback. Suppress when
// the user closed the tab or switched worktrees so the toast/telemetry
// don't fire for user-initiated cancellation (mirrors the 5s launch
// watchdog in QuickLaunchButton).
// Why: onTimeout surfaces silent paste failures — a stalled readiness wait would otherwise drop notes silently.
let failureNotified = false
const deliveryPromise = deliverLaunchPromptToAgentTab({
tabId: tab.id,
@@ -294,15 +254,11 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
const tabsForWorktree = state.tabsByWorktree[worktreeId] ?? []
const currentTab = tabsForWorktree.find((t) => t.id === tab.id)
if (currentTab?.ptyId === null) {
// Why: PTY never spawned — a genuine launch failure. Stay silent so
// the single notice comes from the caller (source-control dialog
// toast, or QuickLaunch's watchdog); leaving failureNotified false lets it fire.
// Why: PTY never spawned = genuine launch failure; stay silent so the caller emits the sole notice.
return
}
if (!currentTab || state.activeWorktreeId !== worktreeId) {
// Why: user-initiated cancellation (closed the tab or switched
// worktrees) — mark notified so the deferred source-control caller
// suppresses its generic "couldn't start" toast too, not just this nudge.
// Why: user cancelled (closed tab / switched worktrees); mark notified so the deferred caller suppresses its toast too.
failureNotified = true
return
}
@@ -341,14 +297,10 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
onPromptDelivered?.()
}
// Why: match the `+` button's `createNewTerminalTab` sequence — without
// `setActiveTabType('terminal')`, a worktree currently showing an editor
// file keeps rendering the editor and the new terminal tab stays invisible.
// Why: without setActiveTabType('terminal') a worktree showing an editor keeps rendering it and the new tab stays hidden.
store.setActiveTabType('terminal')
// Why: persist the tab-bar order with the new terminal appended. Without
// this, `reconcileTabOrder` falls back to terminals-first when the stored
// order is unset, which can jump the new tab to index 0 instead of the end.
// Why: persist tab-bar order so reconcileTabOrder doesn't fall back to terminals-first and jump the new tab to index 0.
const fresh = useAppStore.getState()
const termIds = (fresh.tabsByWorktree[worktreeId] ?? []).map((t) => t.id)
const editorIds = fresh.openFiles.filter((f) => f.worktreeId === worktreeId).map((f) => f.id)
@@ -1,6 +1,4 @@
/* oxlint-disable max-lines -- Why: output ordering, foreground settle, queue
state, and e2e diagnostics share one state machine; splitting it would make the
backlog/resume guarantees harder to audit. */
/* oxlint-disable max-lines -- Why: output ordering, foreground settle, queue state, and e2e diagnostics form one state machine; splitting it would make backlog/resume guarantees harder to audit. */
import { e2eConfig } from '@/lib/e2e-config'
import {
discardForegroundRenderSettle,
@@ -37,11 +35,7 @@ type WriteTerminalOutputOptions = {
foreground: boolean
beforeWrite?: TerminalOutputBeforeWrite
onParsed?: TerminalOutputParsedCallback
/** Parse-deferred delivery ACK (terminal-pty-ack-gate). The scheduler MUST
* invoke it exactly when the chunk's bytes are parsed by xterm OR discarded
* by any drop path. A missed credit permanently shrinks
* main's in-flight window for this PTY (the callback is fire-once, so
* double invocation is safe; omission is not). */
/** Parse-deferred delivery ACK (terminal-pty-ack-gate). MUST be invoked when the chunk is parsed OR discarded by any drop path; fire-once, so double invocation is safe but omission permanently shrinks main's in-flight window. */
ackCredit?: () => void
onBackgroundBacklogDropped?: () => void
latencySensitive?: boolean
@@ -98,20 +92,12 @@ const BACKGROUND_DRAIN_INTERVAL_MS = 16
const HIGH_PRIORITY_DRAIN_INTERVAL_MS = 4
const BACKGROUND_CHUNK_CHARS = 16 * 1024
const MAX_WRITES_PER_DRAIN = 2
// Why 8: with the parse-clock pacer, high-priority ticks fire only after
// xterm confirms the previous batch parsed, and Chromium clamps chained
// timers to ~4ms — so per-tick volume (8 x 16KB = 128KB ≈ 1.3ms of parse)
// sets the sustained ceiling (~30MB/s) while staying far inside
// DRAIN_TIME_BUDGET_MS. At 2 the ceiling was 8MB/s against a ~100MB/s
// parser (see pane-terminal-output-scheduler-throughput.bench.test.ts).
// Why 8: per-tick volume (8 x 16KB = 128KB ≈ 1.3ms parse) sets the sustained ceiling (~30MB/s) within DRAIN_TIME_BUDGET_MS; at 2 it was only 8MB/s against a ~100MB/s parser (see throughput bench).
const HIGH_PRIORITY_MAX_WRITES_PER_DRAIN = 8
const DRAIN_TIME_BUDGET_MS = 8
const LARGE_BACKLOG_CHARS = 512 * 1024
const SYNC_FOREGROUND_FLUSH_CHARS = 256 * 1024
// Why mutable: the cap scales with the user's scrollback setting (see
// terminalOutputBacklogCapChars); the terminal lifecycle configures it when
// settings are applied. The chunk-count cap stays fixed — it bounds queue
// bookkeeping, not retained content.
// Why mutable: the cap scales with the user's scrollback setting (terminalOutputBacklogCapChars), configured when settings apply; the chunk-count cap stays fixed.
let maxQueueChars = TERMINAL_OUTPUT_BACKLOG_MIN_CAP_CHARS
const MAX_BACKGROUND_QUEUE_CHUNKS = 4096
@@ -121,21 +107,16 @@ export function configureTerminalOutputBacklogCap(scrollbackRows: unknown): void
const PARSE_SETTLE_TIMEOUT_MS = 250
const FOREGROUND_COALESCE_DELAY_MS = 1000
const FOREGROUND_HOLD_SAFETY_DELAY_MS = 250
// Why: key repeat can tick every 30-50ms; one frame catches split restores
// without batching multiple typed-character redraws behind the fallback.
// Why: key repeat can tick every 30-50ms; one frame catches split restores without batching multiple typed-character redraws behind the fallback.
const LATENCY_SENSITIVE_FOREGROUND_COALESCE_DELAY_MS = 16
const LATENCY_SENSITIVE_FOREGROUND_HOLD_SAFETY_DELAY_MS = 32
const CURSOR_SHOW_SEQUENCE = '\x1b[?25h'
const CURSOR_HIDE_SEQUENCE = '\x1b[?25l'
const SYNCHRONIZED_OUTPUT_END_SEQUENCE = '\x1b[?2026l'
// Why: CAN aborts a partial escape sequence before resetting style and showing
// the lossy-backlog warning. Cap-agnostic wording: the byte limit scales with
// the scrollback setting.
// Why: leading CAN aborts any partial escape sequence before the style reset so the backlog warning renders cleanly.
const BACKGROUND_BACKLOG_WARNING =
'\x18\x1b[0m\r\n[Orca skipped hidden terminal output because the backlog grew too large.]\r\n'
// Why a separate foreground message: a visible pane hitting the cap means the
// drain could not keep up with a flood (starved renderer) — the output was
// skipped, not merely produced while hidden.
// Why a separate foreground message: a visible pane hitting the cap means the drain couldn't keep up with a flood (starved renderer), not merely output produced while hidden.
const FOREGROUND_BACKLOG_WARNING =
'\x18\x1b[0m\r\n[Orca skipped a burst of terminal output because the backlog grew too large.]\r\n'
const ALWAYS_REFRESH_FOREGROUND_SYNCHRONOUSLY = (): boolean => true
@@ -147,21 +128,14 @@ const backlogRecoveryByTerminal = new WeakMap<
>()
let drainTimer: ReturnType<typeof setTimeout> | null = null
let drainTimerDelayMs: number | null = null
// Why a MessageChannel for zero-delay drains: Chromium clamps nested
// setTimeout(0) to ~4ms, which stacks a dead gap onto every parse-clocked
// drain tick under flood (measured: standing queue ~18ms vs VS Code ~7ms).
// A posted message is still a macrotask — input events and paint are
// serviced between posts — so the cooperative yield survives without the
// clamp. Cancellation is by generation: posts carry the generation they
// were armed with and no-op when it has moved on.
// Why a MessageChannel for zero-delay drains: Chromium clamps nested setTimeout(0) to ~4ms; a posted macrotask isn't clamped yet still yields to input/paint. Cancellation is by generation.
let drainImmediatePending = false
let drainImmediateGeneration = 0
let useMessageChannelDrain = typeof MessageChannel !== 'undefined' && !isVitestEnv()
let drainChannel: MessageChannel | null = null
function isVitestEnv(): boolean {
// Why: vitest fake timers cannot advance MessageChannel macrotasks; the
// timer path keeps the existing suites' virtual clock authoritative.
// Why: vitest fake timers can't advance MessageChannel macrotasks; the timer path keeps the suites' virtual clock authoritative.
return typeof process !== 'undefined' && process.env?.VITEST === 'true'
}
@@ -190,9 +164,7 @@ export function setUseMessageChannelDrainForTesting(value: boolean | null): void
}
const debugEnabled = e2eConfig.exposeStore
// Why the cap is lossy: a hidden/backgrounded Chromium document can throttle
// timers while PTYs keep writing. Preserving unlimited hidden scrollback would
// let renderer memory grow until the app stalls or crashes.
// Why the cap is lossy: a backgrounded Chromium document throttles timers while PTYs keep writing, so unbounded hidden scrollback would grow renderer memory until the app crashes.
type TerminalOutputSchedulerDebugSnapshot = {
backgroundEnqueueCount: number
@@ -290,8 +262,7 @@ function exposeDebugApi(): void {
if (!debugEnabled || typeof window === 'undefined') {
return
}
// Why: the e2e repro needs to prove background output used the shared drain,
// but production must not accumulate diagnostic counters indefinitely.
// Why: the e2e repro must prove background output used the shared drain, but production must not accumulate diagnostic counters indefinitely.
const target = window as unknown as {
__terminalOutputSchedulerDebug?: TerminalOutputSchedulerDebugApi
}
@@ -458,9 +429,7 @@ function removeTransientCursorShowSequences(data: string): string {
if (synchronizedEndIndex === -1) {
break
}
// Why: keep the cursor hidden while xterm parses the synchronized
// repaint, then restore it after the frame ends so Windows never paints
// the cursor in the transient draw position.
// Why: keep the cursor hidden through the synchronized repaint, restoring it after the frame ends so Windows never paints it in the transient draw position.
result += data.slice(offset, showIndex)
result += data.slice(
showIndex + CURSOR_SHOW_SEQUENCE.length,
@@ -471,8 +440,7 @@ function removeTransientCursorShowSequences(data: string): string {
showIndex = data.indexOf(CURSOR_SHOW_SEQUENCE, offset)
continue
}
// Why: Codex can show the cursor before its final synchronized-frame
// placement. Place first so xterm cannot rasterize the stale cell.
// Why: Codex can show the cursor before its final synchronized-frame placement. Place first so xterm cannot rasterize the stale cell.
result += data.slice(offset, showIndex)
result += data.slice(showIndex + CURSOR_SHOW_SEQUENCE.length, nextPositionEnd)
result += CURSOR_SHOW_SEQUENCE
@@ -596,8 +564,7 @@ function takeQueuedChunk(entry: QueueEntry, limit: number): QueuedWrite | null {
foreground ??= chunk.foreground
forceForegroundRefresh ||= chunk.forceForegroundRefresh
followupForegroundRefresh ||= chunk.followupForegroundRefresh
// Why: one drained write can combine chunks from different renderer
// states or producers; preserve every forced policy and preparation hook.
// Why: one drained write can combine chunks from different renderer states or producers; preserve every forced policy and prep hook.
if (chunk.forceForegroundRefresh) {
if (shouldRefreshForegroundSynchronously === null) {
shouldRefreshForegroundSynchronously = chunk.shouldRefreshForegroundSynchronously
@@ -728,10 +695,7 @@ function enqueueChunk(
recordQueueDebugPressure()
}
// Fires the delivery ACK credits of every not-yet-consumed queued chunk.
// Every discard path MUST call this before clearing/replacing the queue —
// a dropped chunk still counts as consumed for main's in-flight window, or
// the window shrinks permanently and the PTY wedges behind lost credit.
// Why: every discard path MUST fire these before clearing/replacing the queue — a dropped chunk still counts as consumed, or main's in-flight window shrinks permanently and the PTY wedges.
function fireQueuedAckCredits(entry: QueueEntry): void {
for (let index = entry.chunkIndex; index < entry.chunks.length; index += 1) {
entry.chunks[index].ackCredit?.()
@@ -761,8 +725,7 @@ function replaceBacklogWithWarning(
): void {
const shouldNotify = !entry.backgroundBacklogDropped
if (shouldNotify) {
// Why: field visibility for cap tuning — how often drops happen and at
// what size decides whether the cap is too small (issue #2836 / #7017).
// Why: field visibility for cap tuning — drop frequency and size decide whether the cap is too small (issue #2836 / #7017).
recordRendererCrashBreadcrumb('terminal_output_backlog_dropped', {
foreground: warning === FOREGROUND_BACKLOG_WARNING,
droppedChars: entry.queuedChars,
@@ -829,18 +792,14 @@ function hasDrainableBacklog(): boolean {
return false
}
// Why no per-write scroll enforcement: xterm's BufferService.isUserScrolling
// natively owns live follow/pin semantics. App-side intent enforcement is
// limited to structural operations xterm cannot identify, such as replay.
// Why no per-write scroll enforcement: xterm's BufferService.isUserScrolling owns live follow/pin; app-side enforcement is limited to structural ops xterm can't identify, like replay.
function writeBackgroundTerminalChunk(
terminal: TerminalOutputTarget,
data: string,
onParsed?: TerminalOutputParsedCallback,
onWriteFailure?: () => void
): boolean {
// Why guarded: these callbacks run inside xterm's WriteBuffer loop, where an
// escaping throw permanently wedges the terminal (see
// xterm-write-callback-guard.ts).
// Why guarded: these callbacks run inside xterm's WriteBuffer loop, where an escaping throw permanently wedges the terminal (see xterm-write-callback-guard.ts).
const runOnParsed = onParsed
? (): void => runGuardedWriteCompletionStep('background-on-parsed', onParsed)
: undefined
@@ -867,8 +826,7 @@ function takeNextDrainableEntry(): QueueEntry | null {
if (!isEntryDrainable(entry)) {
continue
}
// Why: active/foreground output should be chosen first, not just widen the
// drain budget while older background terminals keep their insertion order.
// Why: active/foreground output should be chosen first, not left in insertion order behind older background terminals.
if (entry.highPriority) {
queuedByTerminal.delete(entry.terminal)
return entry
@@ -891,12 +849,7 @@ function takeNextDrainableEntry(): QueueEntry | null {
return null
}
// Why: the parse-completion pacer re-arms a zero-delay drain as soon as xterm
// reports the previous high-priority batch parsed. Without it, cadence is a
// fixed 4/16ms nap per <=32KB batch — a ~2-8 MB/s drip against xterm's
// ~100 MB/s parse rate (measured: scheduler-throughput bench + baseline-jul02).
// Only high-priority (visible-pane) backlogs are pacer-clocked; background
// panes keep the fixed cadence that protects the focused terminal.
// Why: re-arm a zero-delay drain once xterm confirms the previous high-priority batch parsed; the fixed 4/16ms cadence otherwise drips far below xterm's ~100 MB/s parse. Only visible panes are pacer-clocked; background keeps the fixed cadence to protect the focused terminal.
function makeParseClockPacer(): () => void {
return () => {
try {
@@ -904,8 +857,7 @@ function makeParseClockPacer(): () => void {
scheduleDrain(0)
}
} catch {
// Why: runs inside xterm's write-callback chain; a throw here would
// wedge the terminal (see xterm-write-callback-guard.ts).
// Why: runs inside xterm's write-callback chain; a throw here would wedge the terminal (see xterm-write-callback-guard.ts).
}
}
}
@@ -916,9 +868,7 @@ function composeParsedCallback(
ackCreditsParsed: (() => void) | undefined,
pacer: (() => void) | undefined
): TerminalOutputParsedCallback {
// Why always non-undefined: the write-completion callback doubles as the
// pipeline-health settle signal. A write with no callback could never settle
// the stall watch, forcing a probe round-trip for every healthy idle pane.
// Why always non-undefined: the callback doubles as the pipeline-health settle signal — with none, the stall watch could never settle, forcing a probe round-trip per healthy idle pane.
return () => {
try {
onParsed?.()
@@ -939,8 +889,7 @@ function composeWriteFailureCallback(
// A rejected write still consumed the main-owned delivery window.
ackCreditsParsed?.()
} finally {
// Why: a synchronous rejection proves undeliverability, but it proves
// nothing about parse progress. Recover without extending replay guards.
// Why: a synchronous rejection proves undeliverability but nothing about parse progress; recover without extending replay guards.
failTerminalWriteStallWatch(terminal)
}
}
@@ -959,13 +908,7 @@ function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' | null
}
const pacer = entry.highPriority ? makeParseClockPacer() : undefined
const ackCreditsParsed = registerTerminalOutputAckCredits(entry.terminal, queuedWrite.ackCredits)
// Why armed BEFORE the write: a wedged WriteBuffer (escaping callback throw,
// issue #2836) or a disposed xterm (write() silently drops its completion —
// verified against 6.1.0-beta.287) never runs the parsed callback below. The
// stall watch probe-certifies dead-vs-slow and hands the pane to recovery;
// the entry cleanup credits queued deliveries so main's in-flight window
// never leaks. Arming first keeps a synchronously-completing write able to
// settle its own watch.
// Why armed BEFORE the write: a wedged WriteBuffer (issue #2836) or disposed xterm (6.1.0-beta.287) never runs the parsed callback, so the watch must be live first to catch it.
armTerminalWriteStallWatch(entry.terminal, {
onCertifiedDead: () => discardTerminalOutput(entry.terminal)
})
@@ -997,8 +940,7 @@ function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' | null
composeWriteFailureCallback(entry.terminal, ackCreditsParsed)
)
if (!writeAccepted) {
// The failure callback credited the submitted chunk; credit and abandon
// the detached tail so the drain cannot retry a certified-dead xterm.
// Why: the failure callback credited the submitted chunk; credit and abandon the detached tail so the drain can't retry a certified-dead xterm.
fireQueuedAckCredits(entry)
entry.chunks.length = 0
entry.chunkIndex = 0
@@ -1009,8 +951,7 @@ function writeQueuedChunk(entry: QueueEntry): 'foreground' | 'background' | null
return null
}
} catch {
// Why: beforeWrite or write setup can fail before xterm owns the bytes.
// Cancel the armed watch without claiming parser failure.
// Why: beforeWrite or write setup can fail before xterm owns the bytes; cancel the armed watch without claiming parser failure.
cancelTerminalWriteStallWatch(entry.terminal)
ackCreditsParsed?.()
fireQueuedAckCredits(entry)
@@ -1065,8 +1006,7 @@ function drainQueuedOutput(): void {
clearForegroundCoalesce(entry)
clearForegroundHoldSafety(entry)
}
// Why: xterm parsing and DOM work share the renderer thread with input.
// Keep backlog draining cooperative so WSL/agent output cannot pin the UI.
// Why: xterm parsing and DOM work share the renderer thread with input; keep draining cooperative so WSL/agent output can't pin the UI.
if (writes > 0 && getDrainNow() - startedAt >= DRAIN_TIME_BUDGET_MS) {
break
}
@@ -1077,11 +1017,7 @@ function drainQueuedOutput(): void {
}
recordQueueDebugPressure()
if (queuedByTerminal.size > 0 && hasDrainableBacklog()) {
// Why 0 on the channel path: the 4ms high-priority interval existed to
// yield between ticks, but a posted message already yields — Chromium
// services input and paint between macrotasks. The explicit sleep only
// deepened the standing queue (~4ms per 128KB tick). Timer path keeps
// the interval so fake-timer tests retain stepwise drain semantics.
// Why 0 on the channel path: a posted message already yields (input/paint serviced between macrotasks), so the 4ms interval only deepened the queue; timer path keeps it for fake-timer tests.
scheduleDrain(
hasHighPriorityBacklog()
? useMessageChannelDrain
@@ -1098,15 +1034,13 @@ export function writeTerminalOutput(
options: WriteTerminalOutputOptions
): void {
exposeDebugApi()
// Why: recovery may be budget-delayed while PTY output keeps flowing. Main
// owns the authoritative buffer; credit delivery without waking dead xterm.
// Why: recovery may be budget-delayed while PTY output keeps flowing; main owns the authoritative buffer, so credit delivery without waking dead xterm.
if (isTerminalWritePipelineCertifiedDead(terminal)) {
options.ackCredit?.()
return
}
if (!data) {
// Why: an empty write still consumed its delivery — credit or main's
// in-flight window leaks.
// Why: an empty write still consumed its delivery — credit or main's in-flight window leaks.
options.ackCredit?.()
return
}
@@ -1132,20 +1066,16 @@ export function writeTerminalOutput(
debugState.foregroundWriteCount++
debugState.deferredForegroundEnqueueCount++
}
// Why: a visible pane's queue was previously uncapped — a flood the
// drain can't keep up with ballooned renderer memory without bound.
// Why: a visible pane's queue was previously uncapped — a flood the drain couldn't keep up with ballooned renderer memory without bound.
if (queueCapExceeded(queued)) {
replaceBacklogWithWarning(queued, FOREGROUND_BACKLOG_WARNING)
scheduleDrain(0)
return
}
if (options.holdForeground) {
// Why: synchronized-output start/body chunks contain transient cursor
// moves. Holding them prevents Chromium from rasterizing those states.
// Why: synchronized-output start/body chunks contain transient cursor moves; holding them prevents Chromium from rasterizing those states.
if (options.latencySensitive === true) {
// Why: Codex composer redraws can split the end marker from the
// input-triggered frame; keep cursor protection without adding a
// human-visible fallback delay to typed characters.
// Why: Codex composer redraws can split the end marker from the input-triggered frame; keep cursor protection without a human-visible fallback delay on typed chars.
queued.foregroundHoldSafetyDelayMs = Math.min(
queued.foregroundHoldSafetyDelayMs,
LATENCY_SENSITIVE_FOREGROUND_HOLD_SAFETY_DELAY_MS
@@ -1163,8 +1093,7 @@ export function writeTerminalOutput(
clearForegroundHoldSafety(queued)
const shouldShortenCoalesceForLatencySensitiveForeground = options.latencySensitive === true
if (shouldShortenCoalesceForLatencySensitiveForeground) {
// Why: user input echo must not inherit the normal synchronized-frame
// restore fallback; wait briefly for the restore, then paint.
// Why: user input echo must not inherit the normal synchronized-frame restore fallback; wait briefly for the restore, then paint.
queued.foregroundCoalesceDelayMs = Math.min(
queued.foregroundCoalesceDelayMs,
LATENCY_SENSITIVE_FOREGROUND_COALESCE_DELAY_MS
@@ -1178,9 +1107,7 @@ export function writeTerminalOutput(
scheduleDrain(0)
return
}
// Why: TUI synchronized-output end markers can be split from the
// immediate cursor-restoring bytes by the PTY transport. Wait only
// until the restore arrives; the timer is a bounded fallback.
// Why: the PTY transport can split TUI synchronized-output end markers from the cursor-restoring bytes; wait for the restore, with the timer as bounded fallback.
scheduleForegroundCoalesceRelease(queued, {
rescheduleEarlier: shouldShortenCoalesceForLatencySensitiveForeground
})
@@ -1211,9 +1138,7 @@ export function writeTerminalOutput(
if (queueCapExceeded(entry)) {
replaceBacklogWithWarning(entry, FOREGROUND_BACKLOG_WARNING)
}
// Why: returning from a hidden window can have megabytes queued. Keep
// byte order, but drain it asynchronously so the first foreground frame
// is not pinned behind the entire backlog.
// Why: returning from a hidden window can have megabytes queued — keep byte order but drain async so the first foreground frame isn't pinned behind the whole backlog.
scheduleDrain(0)
return
}
@@ -1243,9 +1168,7 @@ export function writeTerminalOutput(
if (queueCapExceeded(queued)) {
replaceBacklogWithWarning(queued, FOREGROUND_BACKLOG_WARNING)
}
// Why: visible command floods are throughput work, not keystroke echo.
// Queue them behind a zero-delay drain so one IPC callback cannot pin
// the renderer in xterm.write while input and paint are waiting.
// Why: visible command floods are throughput work, not keystroke echo — queue behind a zero-delay drain so one IPC callback can't pin the renderer while input/paint wait.
scheduleDrain(0)
return
}
@@ -1275,8 +1198,7 @@ export function writeTerminalOutput(
}
)
} catch (error) {
// beforeWrite can throw before xterm owns the callback; consume the
// delivery here. xterm write throws are caught by the foreground writer.
// Why: beforeWrite can throw before xterm owns the callback, so consume the delivery here (xterm write throws are caught by the foreground writer).
ackCreditsParsed?.()
cancelTerminalWriteStallWatch(terminal)
throw error
@@ -1303,9 +1225,7 @@ export function writeTerminalOutput(
if (debugEnabled) {
debugState.backgroundEnqueueCount++
}
// Why: non-focused panes can produce output continuously. Letting every
// pane call xterm.write immediately schedules one xterm WriteBuffer timer
// per pane, which starves the focused terminal on the shared renderer thread.
// Why: letting every non-focused pane call xterm.write immediately spawns a WriteBuffer timer per pane, starving the focused terminal on the shared renderer thread.
scheduleDrain(
entry.highPriority || entry.queuedChars > LARGE_BACKLOG_CHARS ? 0 : BACKGROUND_FLUSH_DELAY_MS
)
@@ -1388,8 +1308,7 @@ export function flushTerminalOutput(
return
}
} catch {
// Why: pre-write hooks/setup failed before xterm owned these bytes.
// Cancel the watch; consumed + abandoned chunks still credit delivery.
// Why: pre-write hooks/setup failed before xterm owned these bytes; cancel the watch, but consumed + abandoned chunks still credit delivery.
cancelTerminalWriteStallWatch(terminal)
ackCreditsParsed?.()
fireQueuedAckCredits(entry)
@@ -1443,8 +1362,7 @@ export function registerTerminalBacklogRecovery(
export function waitForTerminalOutputParsed(terminal: TerminalOutputTarget): Promise<void> {
flushTerminalOutput(terminal)
if (isTerminalWritePipelineCertifiedDead(terminal)) {
// A dead pipeline cannot settle; recovery owns it and serializers must not
// enqueue probe writes while a bounded remount retry is pending.
// Why: a dead pipeline cannot settle; recovery owns it and serializers must not enqueue probe writes during a pending remount retry.
return Promise.resolve()
}
@@ -1462,8 +1380,7 @@ export function waitForTerminalOutputParsed(terminal: TerminalOutputTarget): Pro
resolve()
}
const finishParsed = (): void => {
// Why: serializer/startup probes share xterm's FIFO with replay guards;
// their completion is real parser progress even though they carry no bytes.
// Why: serializer/startup probes share xterm's FIFO with replay guards; their completion is real parser progress despite carrying no bytes.
recordTerminalParseProgress(terminal)
finish()
}
@@ -1471,8 +1388,7 @@ export function waitForTerminalOutputParsed(terminal: TerminalOutputTarget): Pro
try {
terminal.write('', finishParsed)
} catch {
// Why: a synchronous rejection means this concrete xterm cannot accept
// even an empty FIFO probe; recovery must replace it before reuse.
// Why: a synchronous rejection means this xterm can't accept even an empty FIFO probe; recovery must replace it before reuse.
failTerminalWriteStallWatch(terminal)
finish()
}
@@ -1483,15 +1399,13 @@ export function discardTerminalOutput(terminal: TerminalOutputTarget): void {
exposeDebugApi()
const entry = queuedByTerminal.get(terminal)
if (entry) {
// Why: discarded queued chunks still consumed their deliveries — credit
// them or main's in-flight window leaks (see fireQueuedAckCredits).
// Why: discarded chunks still consumed their deliveries — credit them or main's in-flight window leaks (fireQueuedAckCredits).
fireQueuedAckCredits(entry)
}
discardInFlightTerminalOutputAckCredits(terminal)
queuedByTerminal.delete(terminal)
discardForegroundRenderSettle(terminal)
// Why: cleanup must cancel the watch without masquerading as parse progress;
// replay guards use real completions to distinguish slow from wedged.
// Why: cancel the watch without masquerading as parse progress; replay guards use real completions to tell slow from wedged.
cancelTerminalWriteStallWatch(terminal)
recordQueueDebugPressure()
}
@@ -14,24 +14,14 @@ const lazyArabicShapingJoinerByTerminal = new WeakMap<
LazyArabicShapingJoinerState
>()
// Why: xterm draws every cell's glyph in isolation, so Arabic output shows
// disconnected letterforms in logical (reversed) order — upstream has no
// BiDi/shaping support (xtermjs/xterm.js#701, Orca #5262). Joining each RTL
// run into one cell range makes both renderers (WebGL atlas, DOM row factory)
// draw the run as a single string, letting the browser apply contextual
// shaping and BiDi ordering inside the run's grid-aligned cell box. The
// terminal buffer and PTY stream are untouched, and xterm itself un-joins any
// range that holds the cursor or a partially selected span, so cursor
// visibility and selection stay cell-accurate.
// Why: xterm lacks BiDi/shaping (xterm.js#701, Orca #5262); joining each RTL run into one cell lets the browser shape and reorder it.
// Every strong-RTL script block sits at or above U+0590, so plain ASCII/Latin
// segments bail out with a single charCodeAt sweep and no per-char decode.
// Every strong-RTL block sits at/above U+0590, so ASCII/Latin bails out with a single charCodeAt sweep.
const RTL_SCAN_FLOOR = 0x0590
export function isStrongRtlCodePoint(codePoint: number): boolean {
return (
// Hebrew, Arabic, Syriac, Arabic Sup, Thaana, NKo, Samaritan, Mandaic,
// Syriac Sup, Arabic Extended-B/A — one contiguous strong-RTL span.
// One contiguous strong-RTL span (Hebrew through Arabic Extended-A).
(codePoint >= 0x0590 && codePoint <= 0x08ff) ||
// Hebrew + Arabic presentation forms (legacy shaped codepoints).
(codePoint >= 0xfb1d && codePoint <= 0xfdff) ||
@@ -64,10 +54,7 @@ function containsStrongRtlText(text: string): boolean {
return false
}
// Neutral characters may sit inside an RTL run (so a multi-word phrase joins
// as one unit and keeps right-to-left word order) but never start or end one:
// ASCII space/digits/punctuation and NBSP. ASCII letters are strong LTR and
// always break a run so paths like `test.txt` never get pulled into one.
// Neutrals may sit inside a run but never open/close it; ASCII letters break runs so paths like test.txt aren't pulled in.
function isRunNeutralCharCode(charCode: number): boolean {
if (charCode < 0x20) {
return false
@@ -80,16 +67,7 @@ function isRunNeutralCharCode(charCode: number): boolean {
return charCode === 0xa0
}
// ZWNJ/ZWJ shape within a word (mandatory in Persian/Kurdish orthography) and
// RLM/ALM assert RTL context — breaking the run on them would split one word
// into two joined chunks laid out in swapped visual order. Transparent: never
// opens, closes, extends, or counts toward a run. LRM (U+200E) is strong LTR
// and intentionally still breaks the run.
// The zero-width Cf controls inside the RTL blocks (Arabic number signs
// U+0600–0605, end of ayah U+06DD, Syriac abbreviation mark U+070F, disputed
// end of ayah U+08E2) and BOM/ZWNBSP U+FEFF are width-0 in xterm, so like
// combining marks they must never open or count a run (an empty joined cell
// range blanks the following glyph in WebGL) — and they have no shape to join.
// Run-transparent format controls: breaking on them would split a word, or open an empty joined range that blanks a glyph.
function isRtlRunTransparentCodePoint(codePoint: number): boolean {
return (
codePoint === 0x200c ||
@@ -104,35 +82,22 @@ function isRtlRunTransparentCodePoint(codePoint: number): boolean {
)
}
// Why: a combining mark renders inside its base's cell, so a run opened at a
// mark starts mid-cell — xterm rounds that to an empty joined cell range and
// the WebGL renderer then draws an empty glyph over the next character. Marks
// may extend and count only after a spacing RTL letter opened the run.
// Why: opening a run at a combining mark (renders in its base cell) makes an empty joined range that blanks a glyph in WebGL.
const COMBINING_MARK = /\p{Mn}/u
function canOpenRtlRun(codePoint: number): boolean {
return !COMBINING_MARK.test(String.fromCodePoint(codePoint))
}
/**
* Character-joiner handler for xterm's registerCharacterJoiner API. Receives
* one attribute-homogeneous segment of a row and returns [start, end) string
* ranges that should render as single joined units.
* Character-joiner handler for xterm's registerCharacterJoiner API: returns the
* [start, end) ranges of a row segment that should render as joined units. A run
* spans the first to last strong-RTL code point, tunneling neutrals; runs of
* fewer than two RTL code points are skipped (isolated forms already render).
*
* A run spans from the first strong-RTL code point to the last one of a
* cluster, tunneling through neutral characters between RTL words. Runs with
* fewer than two RTL code points are skipped: an isolated Arabic letter
* already renders in its correct (isolated) form cell-by-cell.
*
* Known upstream limitation (affects every joiner, ligatures too): a
* standalone width-0 cell (e.g. RLM at line start) makes xterm's
* CharacterJoinerService skip the cell without advancing its string index,
* shifting the run's cell range by one — fix belongs upstream in xterm.js.
*
* Known upstream limitation #2: the WebGL renderer un-joins a range for the
* cursor or a partial selection but not for decorations, so a search-match
* highlight inside a joined run renders all-or-nothing — the whole run when
* the match covers the run's first cell, otherwise not at all. Same class as
* ligatures today, extended here to phrase-length runs.
* Known xterm limitations: a standalone width-0 cell (e.g. RLM at line start)
* shifts the run's cell range by one; and the WebGL renderer un-joins for
* cursor/selection but not decorations, so a search-match highlight inside a run
* renders all-or-nothing.
*/
export function findRtlJoinRanges(text: string): [number, number][] {
const length = text.length
@@ -142,9 +107,7 @@ export function findRtlJoinRanges(text: string): [number, number][] {
break
}
}
// Why: xterm merges other joiners' results into the returned array in
// place, so this must be a fresh array on every call — never a shared
// constant. The non-RTL fast path above keeps the allocation the only cost.
// Why: xterm merges other joiners' results into this array in place, so it must be freshly allocated each call.
const ranges: [number, number][] = []
if (i === length) {
return ranges
@@ -189,8 +152,7 @@ export function findRtlJoinRanges(text: string): [number, number][] {
runRtlCount++
}
} else if (runStart !== -1) {
// Non-RTL above the floor (box drawing, CJK, emoji, …) breaks the run
// so TUI borders and East Asian text keep per-cell rendering.
// Non-RTL above the floor (box drawing, CJK, emoji) breaks the run so TUI borders and CJK keep per-cell rendering.
closeRun()
}
i += codeUnitLength - 1
@@ -199,20 +161,12 @@ export function findRtlJoinRanges(text: string): [number, number][] {
return ranges
}
/** Register the RTL shaping joiner on a terminal. Returns a cleanup that
* deregisters the joiner — `Terminal.dispose()` does not remove registered
* character joiners, so disposePane() must call this to avoid leaking the
* registration (xtermjs/xterm.js#3289). */
/** Register the RTL shaping joiner; returns a cleanup deregistering it — Terminal.dispose() leaks joiners (xtermjs/xterm.js#3289). */
export function registerArabicShapingJoiner(
terminal: ArabicShapingTerminal,
isShapingActive: () => boolean
): () => void {
// Why: the DOM renderer sizes a joined span with one letter-spacing value
// that the browser applies after every character, so a joined run whose
// shaped width differs from its cell budget blows out the whole row's grid
// alignment. Join only while the WebGL renderer is live (checked per render
// call, so context-loss/GPU-setting fallbacks revert to per-cell rendering
// on their own refresh); DOM-rendered panes keep xterm's unshaped default.
// Why: DOM renderer letter-spacing breaks grid alignment for joined runs, so join only while WebGL is the live renderer.
const joinerId = terminal.registerCharacterJoiner((text) =>
isShapingActive() ? findRtlJoinRanges(text) : []
)
@@ -221,9 +175,7 @@ export function registerArabicShapingJoiner(
}
}
/** Configure RTL shaping without registering an xterm character joiner until
* output actually contains RTL text. Any registered joiner makes xterm scan
* every visible cell on every repaint, even when its handler returns no ranges. */
/** Configure lazy RTL shaping; defer joiner registration since any joiner makes xterm rescan every cell each repaint. */
export function configureLazyArabicShapingJoiner(
terminal: ArabicShapingTerminal,
isShapingActive: () => boolean
@@ -267,8 +219,7 @@ export function ensureArabicShapingJoinerForText(
return
}
// Why: PTY/replay chunks can split supplementary-plane RTL code points
// between their surrogate halves; retain only that one boundary code unit.
// Why: PTY/replay chunks can split a supplementary-plane RTL code point across surrogate halves; keep the boundary unit.
const scanText = state.trailingHighSurrogate + text
const finalCharacter = scanText.at(-1) ?? ''
const finalCodeUnit = finalCharacter.charCodeAt(0)
@@ -283,7 +234,6 @@ export function ensureArabicShapingJoinerForText(
try {
state.cleanup = registerArabicShapingJoiner(terminal, state.isShapingActive)
} catch {
// Why: shaping is optional; a registration race with pane disposal must
// never drop the PTY/replay bytes that triggered it or retry every chunk.
// Why: shaping is optional; swallow a registration race with pane disposal rather than drop bytes.
}
}
+10 -55
View File
@@ -1,37 +1,16 @@
// Typed renderer-side wrapper around the preload bridge.
//
// Renderer call sites import `track` from this module rather than reaching
// for `window.api.telemetryTrack` directly, because this wrapper is what
// gives them the `EventMap`-based type safety. The preload bridge is
// deliberately typed as a loose `(name: string, props: Record<string,
// unknown>) => Promise<void>` so it can cross the IPC boundary without
// pretending the renderer's types are load-bearing — the main-side
// validator is the single enforcement point.
//
// The renderer does NOT bundle `posthog-node` or any PostHog SDK. There is
// one PostHog client in the process tree and it lives in main. That
// invariant is what keeps the vendor out of the renderer's attack surface.
// Typed renderer-side wrapper around the preload bridge: gives call sites EventMap type safety, while main stays the single validator.
// Security invariant: the renderer bundles no PostHog SDK — the sole client lives in main, off the renderer's attack surface.
import type { EventName, EventProps } from '../../../shared/telemetry-events'
import type { TelemetryConsentState } from '../../../shared/telemetry-consent-types'
// Re-exported so renderer call sites can import the mapper from this lib
// alongside `track`. The implementation lives in `src/shared/agent-kind.ts`
// because main-process telemetry emission needs the same mapping when it
// receives a `TuiAgent`-derived agent kind through the spawn IPC.
// Re-exported so renderer call sites can import the mapper alongside `track` (impl is shared because main needs the same mapping).
export { tuiAgentToAgentKind } from '../../../shared/agent-kind'
// Why: single source-of-truth for the privacy doc URL linked from the two
// telemetry surfaces (FirstLaunchBanner, PrivacyPane). Keeping it here — in
// the shared telemetry lib — prevents the surfaces from drifting if the doc
// ever moves.
// Single source-of-truth for the privacy doc URL so FirstLaunchBanner and PrivacyPane can't drift.
export const PRIVACY_URL = 'https://www.onorca.dev/docs/telemetry'
// Why: the IPC boundary is untyped at runtime, so a malformed payload from
// main would otherwise let the Privacy pane render on garbage. Validate the
// `effective` discriminant (and `reason` when disabled) before trusting it;
// fall through to `pending_banner` otherwise, matching the bridge-missing
// fail-closed behavior below.
// Why: the IPC boundary is untyped at runtime, so validate before the Privacy pane trusts a payload from main.
function isTelemetryConsentState(x: unknown): x is TelemetryConsentState {
if (!x || typeof x !== 'object') {
return false
@@ -48,13 +27,7 @@ function isTelemetryConsentState(x: unknown): x is TelemetryConsentState {
}
export function track<N extends EventName>(name: N, props: EventProps<N>): void {
// Why: telemetry must never throw into the renderer. A missing bridge
// (tests, early init, sandboxed iframe) would turn `window.api.telemetryTrack`
// into a synchronous TypeError that defeats the documented fire-and-forget
// contract. Log (do not rethrow) on both the sync throw and any promise
// rejection so IPC failures leave a diagnostic breadcrumb while preserving
// the fire-and-forget contract — silent swallowing would let disk state
// drift out of sync with UI state with zero signal to anyone debugging.
// Why: telemetry is fire-and-forget and must never throw into the renderer; log (don't rethrow/silently swallow) so IPC failures leave a breadcrumb.
try {
void window.api?.telemetryTrack?.(name, props as Record<string, unknown>)?.catch((err) => {
console.warn('[telemetry] IPC track failed', err)
@@ -64,10 +37,7 @@ export function track<N extends EventName>(name: N, props: EventProps<N>): void
}
}
// Returns a Promise so callers that need to order a subsequent settings
// write after the opt-in event can `await` it. Most call sites ignore the
// return value; the fire-and-forget contract is preserved by resolving
// (not rejecting) on any bridge error.
// Returns a Promise (resolves, never rejects) so callers can await ordering a settings write after the opt-in event.
export function setOptIn(optedIn: boolean): Promise<void> {
try {
return (
@@ -81,10 +51,7 @@ export function setOptIn(optedIn: boolean): Promise<void> {
}
}
// Read the effective consent state for Privacy-pane rendering. Fails
// closed to `pending_banner` if the bridge is missing (tests, sandbox),
// which the UI treats like a non-actionable/disabled toggle — safer than
// pretending the toggle is live when we cannot confirm consent.
// Fails closed to `pending_banner` when the bridge is missing, so the UI never shows a live toggle we can't confirm.
export async function getConsentState(): Promise<TelemetryConsentState> {
try {
const result = await window.api?.telemetryGetConsentState?.()
@@ -95,20 +62,8 @@ export async function getConsentState(): Promise<TelemetryConsentState> {
}
}
// Banner ✕ — silent persisted opt-IN (acknowledge without eventing).
// Separate channel from `setOptIn(true)` because the event contract for
// the ✕ path is "persist optedIn=true, fire nothing." Routing this through
// `setOptIn(true)` would derive `via='first_launch_banner'` and emit
// `telemetry_opted_in`, which the ✕-as-silent-acknowledge semantics
// forbid — the user did not explicitly opt in, they declined to intervene.
// The only renderer surface that calls this bridge is the FirstLaunchBanner
// ✕ button; the banner's "Turn off" and every other opt-{in,out} path
// uses `setOptIn(…)` so the corresponding event still fires.
//
// Returns a Promise so callers that need to order a subsequent settings
// fetch after main has persisted the acknowledge can `await` it. Most
// call sites ignore the return value; the fire-and-forget contract is
// preserved by resolving (not rejecting) on any bridge error.
// Banner ✕ = silent persisted opt-in: unlike setOptIn(true) it must NOT emit telemetry_opted_in (user declined to intervene, didn't opt in).
// Returns a Promise (resolves, never rejects) so callers can await ordering a settings fetch after the acknowledge persists.
export function acknowledgeBanner(): Promise<void> {
try {
return (
+28 -94
View File
@@ -15,8 +15,7 @@ import { resolveCompatibleAgentTypeForOwner } from '../../../shared/agent-title-
import { resolvePaneAgentOwner } from '../../../shared/pane-agent-owner'
import type { TerminalTab, TuiAgent } from '../../../shared/types'
// A shell name, or the tab's neutral default title — where Orca's
// inferred-interrupt reset parks it. Blank titles are no evidence either way.
// A shell name or the tab's neutral default title (where inferred-interrupt reset parks it); blank titles are no evidence.
function titleShowsNoAgent(title: string, defaultTitle?: string): boolean {
const trimmed = title.trim()
return trimmed.length > 0 && (isShellProcess(trimmed) || trimmed === defaultTitle?.trim())
@@ -36,11 +35,9 @@ function resolveSignalAgentForLaunchOwner(
}
/**
* Probe-free evidence that a launched agent exited: the title shows no agent,
* no live hook row remains in the tab, and either the hook completed or
* previously observed activity vanished. The vanished-activity disjunct is
* local-only: remote rows also drop on transport blips that say nothing about
* the process.
* Probe-free evidence a launched agent exited: title shows no agent, no live
* hook remains, and either the hook completed or observed activity vanished.
* Vanished-activity is local-only — remote rows also drop on transport blips.
*/
export function resolveLaunchedAgentExitEvidence(args: {
title: string
@@ -56,10 +53,7 @@ export function resolveLaunchedAgentExitEvidence(args: {
if (args.hookAgent || args.siblingHookAgent || args.processAgent) {
return false
}
// Why: OSC 133;D proved the foreground returned to the shell — process-grade
// exit evidence that doesn't depend on the agent leaving a clean title.
// Local-only by construction (remote panes have no shell-foreground producer);
// the gate keeps the invariant even for out-of-pipeline callers.
// Why: OSC 133;D (foreground back at shell) is title-independent exit evidence; local-only — remote panes have no shell-foreground producer.
if (!args.isRemote && args.processShellForeground && args.hasObservedAgentSignal) {
return true
}
@@ -84,15 +78,7 @@ export function resolveTabAgentFromSignals(args: {
launchAgent?: TuiAgent
}): TuiAgent | null {
const launchAgent = args.launchAgent ?? null
// The focused pane's durable agent owner: launch intent first, then this
// pane's own host-stamped hook identity (live or completed), then its
// hibernated session record. It anchors every identity decision for THIS pane
// — it re-owns ambiguous Pi-compatible wrapper titles (OMP emits Pi's frames)
// and keeps a mirrored or restored pane, which dropped its host-owned
// launchAgent, resolving through the durable record instead of the title.
// Why: strictly focused-pane-scoped — a sibling split-pane's identity says
// nothing about which Pi-variant this pane runs, so it must not re-own the
// focused title (it would mislabel a genuine Pi pane as its sibling's OMP).
// Durable focused-pane owner (launch intent → hook → session); focused-pane-scoped so a sibling can't re-own the focused title (would mislabel a Pi pane as OMP).
const owner = resolvePaneAgentOwner({
launchAgent,
hookAgent: args.hookAgent,
@@ -100,18 +86,10 @@ export function resolveTabAgentFromSignals(args: {
sleepingSessionAgent: args.sleepingSessionAgent
}) as TuiAgent | null
// A pane's identity comes from its hook record regardless of activity state —
// being idle between turns must not erase which agent is here. We keep the
// live/idle split only because it governs how a title may override identity: a
// LIVE hook is ground truth (a title never overrides it), while an IDLE record
// is durable but a cross-group title can reclaim a pane reused for a different
// agent. Sibling identities normalize against launchAgent only (the tab's
// shared launch intent), never the focused pane's own hook identity.
// The live/idle split governs title override: a LIVE hook is never title-overridden; an IDLE record can be reclaimed by a cross-group title. Siblings normalize vs launchAgent only.
const liveFocusedIdentity = resolveSignalAgentForLaunchOwner(args.hookAgent, owner)
const liveSiblingIdentity = resolveSignalAgentForLaunchOwner(args.siblingHookAgent, launchAgent)
// Why: OSC 133;D proved this local pane's foreground is back at the shell, so
// the finished agent's idle identity is stale and must stop painting the tab.
// Remote titles lag their runtime, so keep the idle identity there.
// Why: OSC 133;D proves this local pane returned to shell, so the idle identity is stale; remote titles lag runtime, so keep it there.
const processProvesShell = !args.isRemote && args.processShellForeground === true
const hasCompletedHook = (args.focusedCompletedHookAgent ?? null) !== null
const noAgentTitle = titleShowsNoAgent(args.title, args.defaultTitle)
@@ -120,29 +98,19 @@ export function resolveTabAgentFromSignals(args: {
const idleFocusedIdentity = idleIdentitySuppressed
? null
: resolveSignalAgentForLaunchOwner(args.focusedCompletedHookAgent, owner)
// Why: `idleIdentitySuppressed` is the FOCUSED pane's own exit evidence, so it
// must not clear a sibling split-pane's idle identity — a focused pane back at
// its shell says nothing about whether the sibling's agent has exited.
// Why: idleIdentitySuppressed is the FOCUSED pane's exit evidence, so it must not clear a sibling's idle identity.
const idleSiblingIdentity = resolveSignalAgentForLaunchOwner(
args.siblingCompletedHookAgent,
launchAgent
)
// The title carries identity in only two roles: (a) a reuse override — it
// names a DIFFERENT-group agent than the pane's known identity, proving the
// pane was reused for a new agent — or (b) a legacy standalone identity when
// the pane has no hook at all. Within the same title-identity group it says
// nothing (OMP wraps Pi and emits identical frames), so the durable record
// wins; re-owning explicitTitleAgent through `owner` enforces that.
// Title carries identity only as a reuse override (names a DIFFERENT-group agent) or a legacy standalone id when no hook — same-group titles say nothing (OMP wraps Pi), so the record wins.
const explicitTitleAgent = resolveSignalAgentForLaunchOwner(
resolveExplicitTerminalTitleAgentType(args.title),
owner
)
const priorIdentity = idleFocusedIdentity ?? launchAgent
// Why: a completed hook is itself proof the pane has shown activity, so it
// arms the reuse override without waiting for `hasObservedAgentSignal` — which
// starts false for one mount commit and would otherwise flash the exited
// agent's idle identity before the new (hookless) agent's title reclaims.
// Why: a completed hook already proves activity, so it arms the reuse override without waiting for hasObservedAgentSignal (false for one mount commit).
const titleReclaimsReusedPane =
priorIdentity !== null &&
explicitTitleAgent !== null &&
@@ -168,19 +136,10 @@ export function resolveTabAgentFromSignals(args: {
processShellForeground: args.processShellForeground
})
const activeLaunchAgent = launchedAgentExited ? null : launchAgent
// Why: the foreground process, like the hook and title signals, must be
// re-owned within its title-identity group. OMP wraps Pi as `shell → omp → pi`,
// so the foreground reader oscillates between reporting `omp` and `pi` across
// command boundaries; taken raw it outranks launchAgent and flips an OMP-owned
// tab's icon between the two glyphs. Re-owning collapses the same-group read
// onto the durable owner while a genuine cross-group process still stands.
// Why: re-own the foreground process within its title-identity group so OMP's nested pi (shell → omp → pi) can't flip an OMP-owned tab's icon.
const processAgent = resolveSignalAgentForLaunchOwner(args.processAgent, owner)
const sleepingSessionAgent = args.sleepingSessionAgent ?? null
// Identity-first precedence. The live focused hook is ground truth while the
// agent works; process identity covers agents with neither hook nor title; the
// title then acts only in its reuse-override / legacy roles; and the pane's
// durable idle identity — the record for an agent that ran here and went idle —
// ranks above the hibernated session, the launch bootstrap, and sibling panes.
// Identity-first precedence (see JSDoc): live hook > process > title > idle > sleeping > launch > sibling.
return (
liveFocusedIdentity ??
processAgent ??
@@ -195,29 +154,16 @@ export function resolveTabAgentFromSignals(args: {
/**
* Resolve which coding-harness agent a terminal tab is running, for its tab-bar
* icon. Identity flows through the same already-computed state as the sidebar
* agent rows — no foreground probing. It is a pane's IDENTITY, kept separate
* from its activity state: a hook record identifies the pane whether the agent
* is working or idle. Identity-first precedence:
* icon. A pane's IDENTITY (separate from activity state), from the same
* already-computed state as the sidebar rows — no foreground probing.
* Identity-first precedence:
*
* 1. Live focused hook — provider identity from native integrations while the
* agent is actively working; ground truth, never overridden by a title.
* 2. Process identity — the recognized foreground process, read at OSC 133
* command boundaries (local panes only); covers agents that emit neither
* hooks nor titles, and its shell-foreground mark is title-independent exit
* evidence. Re-owned within its title-identity group, so OMP's nested `pi`
* child (the `shell → omp → pi` tree) cannot flip the icon back to Pi.
* 3. Title — only as a reuse override (it names a DIFFERENT-group agent than the
* pane's known identity, proving reuse) or as a legacy standalone identity
* when the pane has no hook. Within the same title-identity group it carries
* no identity (OMP wraps Pi with identical frames), so the record wins.
* 4. Idle focused identity — the pane's own hook record after the agent went
* idle between turns; the durable answer to "which agent is this" once the
* live hook, process, and any reuse-title are absent. Suppressed on a local
* pane once OSC 133;D proves the agent exited.
* 1. Live focused hook — ground truth while the agent works; never title-overridden.
* 2. Process identity — recognized foreground process (local only); re-owned within its title-identity group so OMP's nested `pi` (shell → omp → pi) can't flip the icon.
* 3. Title — only a reuse override (names a DIFFERENT-group agent) or a legacy standalone identity when the pane has no hook.
* 4. Idle focused identity — the pane's own hook record after it went idle; suppressed locally once OSC 133;D proves exit.
* 5. Sleeping session identity — a hibernated pane's captured session record.
* 6. launchAgent — what Orca launched here; the bootstrap before any hook, hook
* record, or process signal exists, cleared once exit evidence shows it left.
* 6. launchAgent — bootstrap before any hook/process signal; cleared once exit evidence shows it left.
* 7. Sibling-pane identity (live, then idle) — split-tab fallback.
*/
export function useTabAgent(tab: TerminalTab): TuiAgent | null {
@@ -255,15 +201,12 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
? Boolean(s.paneForegroundAgentByPaneKey[focusedPaneKey]?.shellForeground)
: false
)
// Why: a hibernated pane's persisted session record is pane-scoped evidence of
// which agent actually ran here — the freshest identity once the PTY, hook,
// and process signals are all gone, and proof a stale launchAgent was reused.
// Why: a hibernated pane's session record is the freshest identity once PTY, hook, and process signals are all gone.
const sleepingSessionAgent = useAppStore((s) =>
focusedPaneKey ? (s.sleepingAgentSessionsByPaneKey[focusedPaneKey]?.agent ?? null) : null
)
// The focused pane's PTY (single-pane tabs have exactly one leaf). Only used
// to reset per-process-generation signals when the pane is respawned.
// Focused pane's PTY; only used to reset per-process-generation signals on respawn.
const ptyId = useAppStore((s) => {
const layout = s.terminalLayoutsByTabId[tab.id]
const activeLeafId = layout?.activeLeafId
@@ -274,9 +217,7 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
const ptyIds = s.ptyIdsByTabId[tab.id] ?? []
return ptyIds.length === 1 ? ptyIds[0]! : null
})
// Why: with no layout to prove which pane a completed row belongs to, only a
// single-pane tab may treat it as focused-pane exit evidence — a sibling's
// done row must not clear another pane's launch identity.
// Why: with no layout to place a completed row, only a single-pane tab may treat it as focused-pane exit evidence.
const completedHookScopeKnown = useAppStore((s) => {
const layout = s.terminalLayoutsByTabId[tab.id]
if (layout?.activeLeafId && isTerminalLeafId(layout.activeLeafId)) {
@@ -301,9 +242,7 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
const completedHookEvidence = hasCompletedHook && completedHookScopeKnown
useEffect(() => {
// Why: reset and re-seed in one effect so a pane respawn both invalidates
// the previous generation's signal and immediately re-observes a still-live
// hook row instead of leaving the signal stuck false.
// Why: reset+re-seed in one effect so a respawn drops the stale-generation signal yet re-observes a still-live hook, not left stuck false.
const generation = `${ptyId ?? ''}|${String(isRemoteLike)}`
if (signalGenerationRef.current !== generation) {
signalGenerationRef.current = generation
@@ -311,14 +250,11 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
setHasObservedAgentSignal(false)
}
const explicitTitleAgent = resolveExplicitTerminalTitleAgentType(tab.title)
// Why: for launched panes, only a title naming the launched agent counts as
// its activity — other-agent or sibling evidence must not arm exit clearing
// for an agent that never produced evidence of its own.
// Why: only a title naming the launched agent arms its exit clearing — sibling/other-agent evidence must not.
const fallbackAgentSignal = tab.launchAgent
? explicitTitleAgent === tab.launchAgent
: Boolean(explicitTitleAgent || siblingHookAgent)
// Why: a recognized foreground process is focused-pane ground truth, so it
// arms exit clearing even for agents with no hook or title integration.
// Why: a recognized foreground process arms exit clearing even for agents with no hook or title integration.
if (focusedHookAgent || completedHookEvidence || processAgent || fallbackAgentSignal) {
hasObservedAgentSignalRef.current = true
setHasObservedAgentSignal(true)
@@ -338,9 +274,7 @@ export function useTabAgent(tab: TerminalTab): TuiAgent | null {
if (!tab.launchAgent) {
return
}
// Why: AND the state with the ref — the ref is generation-safe within this
// commit (the observe effect above already reset it), while the state can
// lag one render behind a pane focus/respawn switch.
// Why: AND ref with state — the ref is generation-safe this commit while state can lag one render behind a respawn.
const launchedAgentExited = resolveLaunchedAgentExitEvidence({
title: tab.title,
defaultTitle: tab.defaultTitle,
+17 -71
View File
@@ -16,17 +16,7 @@ import { buildActiveConnectionIdsAtShutdown } from './workspace-session-reconnec
export { buildActiveConnectionIdsAtShutdown }
/** Why (issue #1158): the debounced + shutdown session writers share this
* gate so a hydration failure cannot overwrite orca-data.json with the
* empty in-memory state the error path leaves behind.
*
* - workspaceSessionReady gates the UI mount; it flips true even in the
* error path so users aren't locked out of a crashed session.
* - hydrationSucceeded only flips true after a clean load; it stays false
* forever if hydration ever threw, which is what keeps the writer a
* no-op for the rest of that process lifetime.
*
* Both must be true to persist. */
/** Why (issue #1158): require both flags so a hydration failure can't overwrite orca-data.json with empty error-path state. */
export function shouldPersistWorkspaceSession(
state: Pick<AppState, 'workspaceSessionReady' | 'hydrationSucceeded'>
): boolean {
@@ -66,12 +56,7 @@ export type WorkspaceSessionSnapshot = Pick<
sleepingAgentSessionsByPaneKey?: AppState['sleepingAgentSessionsByPaneKey']
}
// Why: the App-level Zustand subscriber that debounces session writes uses
// this list as a shallow-equality gate so it only resets the timer when a
// field that actually feeds buildWorkspaceSessionPayload changes. Keeping
// the list co-located with WorkspaceSessionSnapshot means a future field
// added to the snapshot type fails the _exhaustive check below at compile
// time, preventing the gate from silently going stale.
// Why: shallow-equality gate for the debounced session writer; _exhaustive below keeps it in sync with the snapshot type.
export const SESSION_RELEVANT_FIELDS = [
'activeRepoId',
'activeWorkspaceKey',
@@ -130,9 +115,7 @@ export function buildEditorSessionData(
const editFileIdsByWorktree: Record<string, Set<string>> = {}
for (const f of editFiles) {
const arr = byWorktree[f.worktreeId] ?? (byWorktree[f.worktreeId] = [])
// Why: read-only tabs never persist a dirty draft even if isDirty is
// somehow set — restoring a draft would reintroduce writable/hot-exit state
// for an agent-owned transcript.
// Why: never persist a dirty draft for a read-only tab — restoring one would reintroduce writable/hot-exit state for an agent transcript.
const dirtyDraftContent = f.isDirty && f.readOnly !== true ? editorDrafts[f.id] : undefined
arr.push({
filePath: f.filePath,
@@ -141,14 +124,11 @@ export function buildEditorSessionData(
language: f.language,
isPreview: f.isPreview || undefined,
runtimeEnvironmentId: f.runtimeEnvironmentId,
// Why: persist read-only only when true so pre-existing writable sessions
// stay writable on restore (absence is the writable default).
// Why: persist readOnly only when true; absence is the writable default on restore.
...(f.readOnly === true ? { readOnly: true } : {}),
...(f.readOnly === true && f.liveTail === true ? { liveTail: true } : {}),
...(dirtyDraftContent !== undefined ? { dirtyDraftContent } : {}),
// Why: the edit baseline travels with the dirty draft so a restore can
// re-derive a changed-on-disk conflict before autosave may overwrite an
// agent write that landed while the app was closed.
// Why: baseline travels with the draft so restore can detect a changed-on-disk conflict before autosave clobbers an offline agent write.
...(dirtyDraftContent !== undefined && f.lastKnownDiskSignature
? { lastKnownDiskSignature: f.lastKnownDiskSignature }
: {})
@@ -178,10 +158,7 @@ export function buildEditorSessionData(
activeTabTypeEntries.push([worktreeId, tabType])
continue
}
// Why: restart only restores edit-mode files. Persisting "editor" with a
// transient diff/conflict file ID creates a session payload that cannot be
// satisfied on startup and leaves the UI with no real editor tab to select.
// Only keep the editor marker when it points at a restored file.
// Why: only keep the "editor" marker when it points at a restored file, else startup has no real editor tab to select.
if (persistedActiveFileIdByWorktree[worktreeId]) {
activeTabTypeEntries.push([worktreeId, tabType])
}
@@ -191,8 +168,7 @@ export function buildEditorSessionData(
WorkspaceVisibleTabType
>
const allEditFileIds = new Set(Object.values(editFileIdsByWorktree).flatMap((ids) => [...ids]))
// Why: preserve the actual value so per-file hide overrides survive restart;
// the map only ever carries `false` entries (visible is the default).
// Why: preserve the value so per-file hide overrides survive restart (map only carries `false`; visible is the default).
const persistedMarkdownFrontmatterVisible = Object.fromEntries(
Object.entries(markdownFrontmatterVisible ?? {}).filter(([fileId]) =>
allEditFileIds.has(fileId)
@@ -216,9 +192,7 @@ export function buildBrowserSessionData(
'browserTabsByWorktree' | 'browserPagesByWorkspace' | 'activeBrowserTabIdByWorktree'
> {
return {
// Why: browser tabs persist only lightweight chrome state. Live guest
// webContents are recreated on restore, so loading is reset to false and
// transient errors are preserved only as last-known tab metadata.
// Why: guest webContents are recreated on restore, so persist only lightweight chrome state (loading reset to false).
browserTabsByWorktree: buildPersistedBrowserTabsByWorktree(browserTabsByWorktree),
browserPagesByWorkspace: buildPersistedBrowserPagesByWorkspace(browserPagesByWorkspace),
activeBrowserTabIdByWorktree
@@ -250,15 +224,7 @@ export function buildPersistedBrowserPagesByWorkspace(
export function buildSanitizedTabsByWorktree(
tabsByWorktree: WorkspaceSessionSnapshot['tabsByWorktree']
): WorkspaceSessionState['tabsByWorktree'] {
// Why: pendingActivationSpawn is documented on TerminalTab as a transient
// renderer-only handoff between setActiveWorktree and the next updateTabPtyId
// — it must never be persisted. The main-process session:set handler writes
// the payload to disk without re-parsing it against the Zod schema, so if
// the flag were ever set and not consumed before a save (e.g. app quits
// mid-handoff), it would round-trip to disk and the next session would
// start with a stale suppression flag that drops the first legitimate PTY
// spawn from the sidebar's recency sort. Strip it here to enforce the
// type-level invariant at the persistence boundary.
// Why: strip transient pendingActivationSpawn — session:set persists without Zod re-parse, so a stale flag would drop the first PTY spawn on restart.
return Object.fromEntries(
Object.entries(tabsByWorktree).map(([worktreeId, tabs]) => [
worktreeId,
@@ -276,17 +242,11 @@ export function buildTerminalSessionData(
): Pick<WorkspaceSessionState, 'activeWorktreeIdsOnShutdown' | 'remoteSessionIdsByTabId'> {
const tabsByWorktree = snapshot.tabsByWorktree
// Why: ptyIdsByTabId is the live-PTY map. tab.ptyId is only a wake hint that
// sleep intentionally preserves, so using it as liveness would revive slept
// worktrees as active after restart.
// Why: use ptyIdsByTabId (live PTYs), not tab.ptyId, which sleep preserves as a wake hint and would revive slept worktrees as active.
const ptyIdsByTabId = snapshot.ptyIdsByTabId
const hasLivePty = (tabId: string): boolean => (ptyIdsByTabId[tabId]?.length ?? 0) > 0
// Why: lastKnownRelayPtyIdByTabId preserves remote session IDs across relay
// disconnect/reconnect cycles, where clearTabPtyId(null) clears tab.ptyId
// but keeps the relay PTY alive. Sleep is different: it preserves tab.ptyId
// as a wake hint after clearing ptyIdsByTabId, so that shape must not count
// as active on restart.
// Why: relay reconnect keeps lastKnown but clears tab.ptyId; the !tab.ptyId guard excludes slept tabs (which keep ptyId as a wake hint).
const lastKnown = snapshot.lastKnownRelayPtyIdByTabId
const hasReconnectableSession = (tab: { id: string; ptyId: string | null }): boolean =>
hasLivePty(tab.id) || (!tab.ptyId && Boolean(lastKnown[tab.id]))
@@ -302,13 +262,8 @@ export function buildTerminalSessionData(
)
const repoById = new Map(snapshot.repos.map((repo) => [repo.id, repo]))
// Why: the renderer already has tab.ptyId for every terminal tab and knows
// which worktrees are SSH-backed via repo.connectionId. Deriving the map
// here avoids a sync IPC round-trip during beforeunload, which is fragile
// (can be dropped by Chromium under shutdown time pressure).
// Why: this builder runs from the session-write debounce and beforeunload.
// Pre-index repo/worktree identity once so large workspaces don't rescan all
// repos/worktrees for every terminal tab while the renderer is trying to quit.
// Why: derive here to avoid a fragile sync IPC round-trip during beforeunload (Chromium can drop it under shutdown pressure).
// Why: pre-indexed above so large workspaces don't rescan every repo/worktree per terminal tab while the renderer is quitting.
const remoteSessionIdsByTabId: Record<string, string> = {}
for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) {
const worktree = worktreeById.get(worktreeId)
@@ -346,9 +301,7 @@ export function buildWorkspaceSessionPayload(
activeTabId: snapshot.activeTabId,
tabsByWorktree: buildSanitizedTabsByWorktree(snapshot.tabsByWorktree),
terminalLayoutsByTabId: snapshot.terminalLayoutsByTabId,
// Why: session:set fully replaces the persisted object, so every write path
// must carry forward which worktrees still had live PTYs. Dropping this
// field silently disables eager terminal reconnect on the next restart.
// Why: session:set fully replaces the persisted object, so dropping this silently disables eager terminal reconnect on restart.
activeWorktreeIdsOnShutdown: terminalSessionData.activeWorktreeIdsOnShutdown,
activeTabIdByWorktree: snapshot.activeTabIdByWorktree,
...buildEditorSessionData(
@@ -363,23 +316,16 @@ export function buildWorkspaceSessionPayload(
snapshot.browserPagesByWorkspace,
snapshot.activeBrowserTabIdByWorktree
),
// Why: browser history is user-lifetime state. Enforce the storage cap at
// the payload boundary so stale renderer state cannot make every session
// write stringify an oversized legacy history array.
// Why: enforce the history storage cap here so stale renderer state can't make every write stringify an oversized legacy array.
browserUrlHistory: normalizeBrowserHistoryEntries(snapshot.browserUrlHistory),
// Why: split creation and tab creation are separate renderer updates.
// Persist only layouts backed by real tabs so a reload cannot restore a
// blank split pane from that transient midpoint.
// Why: persist only layouts backed by real tabs so a reload can't restore a blank split pane from the split-before-tab midpoint.
...buildPersistedUnifiedTabSessionData(snapshot),
activeConnectionIdsAtShutdown: buildActiveConnectionIdsAtShutdown(
snapshot,
terminalSessionData.remoteSessionIdsByTabId ?? null
),
remoteSessionIdsByTabId: terminalSessionData.remoteSessionIdsByTabId,
// Why: per-worktree focus-recency for Cmd+J's empty-query ordering.
// Omit when empty so sessions written by builds that never stamped
// anything don't bloat the payload. See
// docs/cmd-j-empty-query-ordering.md.
// Why: omit when empty so builds that never stamped focus-recency don't bloat the payload. See docs/cmd-j-empty-query-ordering.md.
lastVisitedAtByWorktreeId: buildLastVisitedAtByWorktreeId(snapshot),
defaultTerminalTabsAppliedByWorktreeId:
snapshot.defaultTerminalTabsAppliedByWorktreeId &&
+31 -101
View File
@@ -69,9 +69,8 @@ import { seedNativeChatAppliedSessionOptions } from '@/components/native-chat/na
import { resolveNativeChatSessionOptionDefaults } from '../../../shared/native-chat-session-option-defaults'
import type { SessionOptionValue } from '../../../shared/native-chat-session-options'
/** Telemetry payload threaded from the launch site to `pty:spawn`. Main
* fires `agent_started` only after the spawn succeeds — see
* telemetry-plan.md§Agent launch semantics. */
/** Telemetry threaded from the launch site to `pty:spawn`; main fires `agent_started`
* only after the spawn succeeds. See telemetry-plan.md§Agent launch semantics. */
export type AgentStartedTelemetry = EventProps<'agent_started'>
/** Startup command threaded onto a worktree's first terminal at activation. */
@@ -89,11 +88,7 @@ export type WorktreeStartupPayload = {
telemetry?: AgentStartedTelemetry
}
// Why: issue commands can originate from two sources with different shapes —
// (1) a repo-level runner script generated by main (WorktreeSetupLaunch), or
// (2) a user-typed command template substituted in the TaskPage flow.
// We accept either so callers don't need to synthesize a runner script file
// just to queue a direct command string.
// Why: accept either a main-generated runner script or a plain TaskPage command string, so callers needn't synthesize a runner file.
export type IssueCommandLaunch =
| WorktreeSetupLaunch
| { command: string; env?: Record<string, string> }
@@ -150,22 +145,13 @@ type WorktreeActivationStore = Partial<WorktreeRuntimeOwnerState> & {
}
/**
* Shared activation sequence used by the worktree palette, AddRepoDialog,
* and AddWorktreeDialog. Covers: cross-repo `activeRepoId` switch,
* `activeView` back to terminal, `setActiveWorktree`, initial terminal
* creation, sidebar filter clearing, and sidebar reveal.
*
* The caller only passes `worktreeId`; the helper derives `repoId`
* internally via `findWorktreeById`. Returns early without side effects
* if the worktree is not found (e.g. deleted between palette open and select).
* Shared activation sequence used by the worktree palette and add-repo/worktree dialogs.
* The caller passes only `worktreeId`; the helper derives `repoId` and returns early
* without side effects if the worktree is not found (deleted between palette open and select).
*/
export type ActivateAndRevealResult = {
/** Id of the primary terminal tab seeded with `opts.startup`, when one was
* created during this activation call. Callers that want to target the
* exact pane the startup command ran in (e.g. to await agent readiness
* and paste follow-up text) should use this rather than peeking at
* `activeTabIdByWorktree`, which may point at another tab if setup or
* issue-command scripts opened their own. */
/** Id of the primary terminal tab seeded with `opts.startup`, or null. Prefer this over
* `activeTabIdByWorktree`, which may point at another tab if setup/issue scripts opened their own. */
primaryTabId: string | null
}
@@ -313,8 +299,7 @@ export function activateAndRevealWorktree(
const hasActivationWork = Boolean(
opts?.startup || opts?.setup || opts?.defaultTabs || opts?.issueCommand
)
// Why: a plain reselect of the already-visible workspace should still reveal
// the sidebar row, but it must not restamp focus recency and wake persistence.
// Why: a plain reselect should still reveal the sidebar row but must not restamp focus recency or wake persistence.
const isPlainAlreadyActiveTerminal =
!hasActivationWork &&
state.activeRepoId === wt.repoId &&
@@ -331,15 +316,12 @@ export function activateAndRevealWorktree(
state.setActiveView('terminal')
}
// 3. Core activation: sets activeWorktreeId, restores per-worktree state,
// clears unread, bumps dead PTY generations, triggers GitHub refresh
// 3. Core activation: setActiveWorktree also restores per-worktree state, clears unread, bumps dead PTY generations, refreshes GitHub
state.setActiveWorktree(worktreeId)
const postActivationState = useAppStore.getState()
const ownerRuntimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(postActivationState, wt.id)
if (opts?.notifyHostRuntime !== false && isWebRuntimeSessionActive(ownerRuntimeEnvironmentId)) {
// Why: paired web clients own only local selection state. The desktop host
// should publish session surfaces for the phone without treating that as a
// desktop navigation command.
// Why: paired web clients own only local selection, so the desktop host publishes session surfaces without treating it as a nav command.
void activateWebRuntimeSessionWorktree({
worktreeId,
environmentId: ownerRuntimeEnvironmentId,
@@ -347,28 +329,17 @@ export function activateAndRevealWorktree(
})
}
// Why: record focus recency for Cmd+J's empty-query ordering BEFORE any
// later async step (initial terminal / reveal) could throw — the user
// already perceives the switch as successful the instant activeWorktreeId
// flips, so the recency stamp must land with the same guarantee. Separate
// from recordWorktreeVisit (nav-history) and from worktree.lastActivityAt
// (background signal) on purpose — see docs/cmd-j-empty-query-ordering.md.
// Why: focus recency for Cmd+J ordering, distinct from recordWorktreeVisit/lastActivityAt; stamp before any later async step could throw. See docs/cmd-j-empty-query-ordering.md.
if (!isPlainAlreadyActiveTerminal) {
state.markWorktreeVisited(worktreeId)
}
// Why: activateAndRevealWorktree always ends in 'terminal' view (step 2),
// and Settings/Tasks transitions do not pass through this function, so no
// view-guard is needed here. The guard skips re-recording when the caller
// is goBackWorktree/goForwardWorktree, which mutate the history index
// directly instead of treating the target as a new visit.
// Why: skip re-recording for goBack/goForward history navigation — it moves the index instead of visiting anew (isNavigatingHistory).
if (!isPlainAlreadyActiveTerminal && !state.isNavigatingHistory) {
state.recordWorktreeVisit(worktreeId)
}
// Why: sleeping an agent destroys the local PTY but preserves the provider
// session id. Waking the workspace should restore those CLI sessions without
// making the user click a separate sidebar row.
// Why: sleeping destroys the local PTY but preserves the provider session id, so waking should restore those CLI sessions automatically.
resumeSleepingAgentSessionsForWorktree(worktreeId)
// 4. Ensure a focusable surface exists for externally-created worktrees
@@ -384,10 +355,7 @@ export function activateAndRevealWorktree(
useAppStore.getState().queueTabInitialCwd(primaryTabId, opts.initialCwd)
}
// 5. Clear sidebar filters that would hide the target worktree
// Why: revealWorktreeInSidebar relies on the worktree card being rendered
// in the sidebar. If sidebar filters exclude the target, the card is never
// rendered and the reveal silently no-ops.
// 5. Clear sidebar filters hiding the target — reveal needs the card rendered, else it silently no-ops.
if (state.filterRepoIds.length > 0 && !state.filterRepoIds.includes(wt.repoId)) {
state.setFilterRepoIds([])
}
@@ -433,8 +401,7 @@ export function ensureWebRuntimeWorktreeTerminalAfterWake(worktreeId: string): v
const hasMirroredHostTabs = tabs.some((tab) => isWebTerminalSurfaceTabId(tab.id))
if (hasMirroredHostTabs) {
// Why: the host session still owns these tabs — wait for the mirror to
// repopulate PTY handles instead of creating a duplicate terminal.
// Why: the host session still owns these tabs — wait for the mirror to repopulate PTY handles instead of duplicating a terminal.
return
}
@@ -451,8 +418,7 @@ export function ensureWebRuntimeWorktreeTerminalAfterWake(worktreeId: string): v
return
}
// Why: sleep keeps local tab rows but terminal.stop clears host PTYs, so
// activation alone can leave a woke workspace with tab chrome but no surface.
// Why: sleep keeps tab rows but terminal.stop clears host PTYs, so a woke workspace can have tab chrome but no surface.
void createWebRuntimeSessionTerminal({
worktreeId,
environmentId: runtimeEnvironmentId,
@@ -473,9 +439,7 @@ export function ensureWorktreeHasInitialTerminal(
opts?: { activateCreatedTabs?: boolean }
): string | null {
const { renderableTabCount } = store.reconcileWorktreeTabModel(worktreeId)
// Why: activation can now restore editor- or browser-only worktrees from the
// reconciled tab-group model. Creating a terminal just because the legacy
// terminal slice is empty would reopen worktrees with an unexpected extra tab.
// Why: creating a terminal just because the legacy terminal slice is empty gives editor/browser-only worktrees an unexpected extra tab.
const ownerState =
store.settings !== undefined || store.repos !== undefined || store.worktreesByRepo !== undefined
? store
@@ -501,9 +465,7 @@ export function ensureWorktreeHasInitialTerminal(
wrappedSetupCommandStr = sequenced.setupCommand
}
// Why: remote web clients mirror the runtime server's session tabs. A local
// activation fallback can spawn a second host terminal before the mirror lands,
// but returned setup fallbacks still need to run on an already mirrored tab.
// Why: web clients mirror the server's session tabs, so avoid spawning a duplicate host terminal before the mirror lands.
if (isWebRuntimeSessionActive(getRuntimeEnvironmentIdForWorktree(ownerState, worktreeId))) {
const existingTerminalTabId = store.tabsByWorktree[worktreeId]?.[0]?.id
if (existingTerminalTabId && (setup || issueCommand)) {
@@ -519,9 +481,7 @@ export function ensureWorktreeHasInitialTerminal(
return existingTerminalTabId
}
if (setup || issueCommand) {
// Why: runtime-owned worktrees mirror their session tabs asynchronously,
// so right after create there is usually no tab yet. Hold the commands
// for the first mirrored tab instead of silently dropping them.
// Why: runtime-owned worktrees mirror session tabs async, so hold commands for the first mirrored tab instead of dropping them.
queueHookCommandsForFirstWorktreeTab({
worktreeId,
deliver: (state, firstTerminalTabId) =>
@@ -542,8 +502,7 @@ export function ensureWorktreeHasInitialTerminal(
if (!shouldAutoCreateInitialTerminal(renderableTabCount)) {
const existingTerminalTabId = store.tabsByWorktree[worktreeId]?.[0]?.id
if (existingTerminalTabId && (setup || issueCommand)) {
// Why: main may have already adopted the startup tab but failed to spawn
// setup; renderer activation must still launch the returned fallback setup.
// Why: main may have adopted the startup tab but failed to spawn setup; renderer must still launch the returned fallback setup.
queueSetupAndIssueCommands(
store,
worktreeId,
@@ -572,15 +531,8 @@ export function ensureWorktreeHasInitialTerminal(
return templatedTabId
}
// Why: this tab only exists because the user clicked/activated a worktree
// that had no focusable surface yet. Tag it so the resulting PTY spawn
// does not count as activity and reshuffle the Recent sort. Explicit
// "New Tab" actions (handleNewTab in Terminal.tsx) do not set the flag.
//
// Why: the initial terminal can be seeded with a coding agent (new-workspace
// flow, or reopening an empty worktree created with an agent). Stamp that on
// the tab before hooks arrive so native chat and provider chrome can resolve
// the agent immediately; sequenced setup keeps the same launch metadata.
// Why: tag this activation-created tab so its PTY spawn doesn't count as activity and reshuffle the Recent sort.
// Why: stamp the seeded agent before hooks arrive so native chat and provider chrome can resolve it immediately.
const launchAgent =
sequencedStartup?.launchAgent ??
(sequencedStartup?.telemetry
@@ -606,10 +558,7 @@ export function ensureWorktreeHasInitialTerminal(
store.setActiveTab(terminalTab.id)
}
// Why: the new-workspace flow can seed the first terminal with a selected
// coding agent and user prompt. Queue that startup command on the initial
// pane so the main terminal begins in the requested agent session instead of
// opening to an idle shell and forcing the user to repeat the same prompt.
// Why: queue the seeded startup on the initial pane so the terminal begins in the requested agent session instead of an idle shell.
if (sequencedStartup) {
if (launchAgent) {
seedNativeChatAppliedSessionOptions(
@@ -730,11 +679,7 @@ function queueSetupAndIssueCommands(
wrappedSetupCommandStr: string | undefined,
opts: { activateCreatedTabs?: boolean } | undefined
): void {
// Why: the setup script launch location is user-configurable. The default
// 'new-tab' creates a separate background tab titled "Setup" without
// stealing focus from the main terminal, so setup output never crowds the
// primary pane; 'split-vertical' and 'split-horizontal' keep the setup
// output adjacent to the main terminal via a split.
// Why: setup launch location is user-configurable — 'new-tab' keeps setup output off the primary pane; splits keep it adjacent.
if (setup) {
const mode = useAppStore.getState().settings?.setupScriptLaunchMode ?? 'new-tab'
const setupCommand = {
@@ -747,15 +692,11 @@ function queueSetupAndIssueCommands(
recordInteraction: false,
...(opts?.activateCreatedTabs === false ? { activate: false } : {})
})
// Why: createTab auto-activates the new tab. Revert activation so the
// user's focus stays on the primary terminal — per the design, the
// Setup tab runs unattended in the background.
// Why: createTab auto-activates the new tab; revert so focus stays on the primary terminal while Setup runs in the background.
if (opts?.activateCreatedTabs !== false) {
store.setActiveTab(terminalTabId)
}
// Why: customTitle wins over the auto-generated "Terminal N" label
// everywhere the tab is rendered (tab bar, switcher, session snapshots),
// so labeling via customTitle is the single authoritative source.
// Why: customTitle overrides the auto "Terminal N" label everywhere the tab renders, so it's the authoritative label source.
store.setTabCustomTitle(setupTab.id, 'Setup', { recordInteraction: false })
store.queueTabStartupCommand(setupTab.id, setupCommand)
} else {
@@ -766,15 +707,9 @@ function queueSetupAndIssueCommands(
}
}
// Why: when the user links a GitHub issue and opts into that repo's
// per-user issue automation, spawn a separate split pane to run the
// agent command. Queued independently from setup so both can start in
// parallel; repo bootstrap and personal issue workflows are separate
// concerns, so Orca should not invent a dependency between them.
// Why: issue automation runs in its own split, queued independently from setup so both can start in parallel (separate concerns).
if (issueCommand) {
// Why: WorktreeSetupLaunch carries a runner-script file (from main) and we
// shell out to bash; the TaskPage variant is already an expanded command
// string, so pass it through directly.
// Why: WorktreeSetupLaunch carries a runner-script file to shell out to; the TaskPage variant is already an expanded command string.
const queuedIssueCommand =
'runnerScriptPath' in issueCommand
? {
@@ -786,10 +721,7 @@ function queueSetupAndIssueCommands(
}
}
// Why: break the import cycle — the nav-history slice must activate workspace
// entries from goBack/goForward, but it lives under @/store, which activation
// already imports from. Registering here keeps folder workspace replay on the
// same path as direct folder activation.
// Why: break the import cycle — nav-history slice (under @/store) can't import activation directly, so register the activator here.
setWorktreeNavActivator((workspaceId) => {
const workspaceScope = parseWorkspaceKey(workspaceId)
if (workspaceScope?.type === 'folder') {
@@ -798,9 +730,7 @@ setWorktreeNavActivator((workspaceId) => {
return activateAndRevealWorktree(workspaceId)
})
// Why: page entries in nav history replay through setActiveView(...)
// (not open*Page) so back/forward does not mutate previousViewBefore* or
// append duplicate history. See navigateToIndex for the replay branch.
// Why: page entries replay via setActiveView (not open*Page) so back/forward doesn't mutate previousViewBefore* or duplicate history (see navigateToIndex).
setWorktreeNavViewActivator((entry) => {
if (entry === 'automations') {
useAppStore.getState().setActiveView(entry)
+13 -56
View File
@@ -33,22 +33,10 @@ export function getWorktreeStatus(
runtimePaneTitlesByTabId: Record<string, Record<number, string>> = {},
options: WorktreeStatusHeuristicOptions = {}
): WorktreeStatus {
// Why: liveness gates every promotion. tab.ptyId is the wake-hint sessionId
// preserved across sleep (so wake can reattach to the same daemon history
// dir / relay session) — it is *not* a liveness signal. ptyIdsByTabId is the
// source of truth: sleep clears it to []; pty.spawn writes it; pty.kill
// clears it. Reading the live-pty map keeps the dot honest after sleep,
// crash, or any path where the wake-hint outlives the actual PTY.
// Why: tab.ptyId is a wake-hint that survives sleep, not a liveness signal; gate on ptyIdsByTabId, which sleep/kill clear when the PTY dies.
const liveTabs = tabs.filter((tab) => tabHasLivePty(ptyIdsByTabId, tab.id))
// Why: a split-pane tab can host multiple concurrent agents, but `tab.title`
// only reflects the most-recently-focused pane (see onActivePaneChange in
// use-terminal-pane-lifecycle.ts). Reading just `tab.title` causes the
// sidebar spinner to follow the focused pane instead of the aggregate tab
// state — e.g. clicking an idle Claude pane while Codex is still working in
// another pane would collapse the spinner to solid green. Consult per-pane
// titles first (same pattern as countWorkingAgentsForTab) and only fall back
// to `tab.title` for tabs that have no mounted panes yet.
// Why: tab.title tracks only the most-recently-focused pane (onActivePaneChange in use-terminal-pane-lifecycle.ts); consult per-pane titles so the spinner reflects aggregate tab state.
const hasStatus = (status: 'permission' | 'working'): boolean =>
liveTabs.some((tab) => tabHasStatus(tab, runtimePaneTitlesByTabId, status, options))
@@ -59,8 +47,7 @@ export function getWorktreeStatus(
return 'working'
}
if (liveTabs.length > 0 || browserTabs.length > 0) {
// Why: browser-only worktrees are still active from the user's point of
// view even when they have no PTY-backed terminal.
// Why: browser-only worktrees (no PTY) are still active from the user's point of view.
return 'active'
}
return 'inactive'
@@ -80,9 +67,7 @@ function tabHasStatus(
const paneTitleEntries = Object.entries(paneTitles)
for (const [runtimePaneId, title] of paneTitleEntries) {
const leafId = resolveRuntimePaneTitleLeafIdFromRoot(tabLayoutRoot, runtimePaneId)
// Why: runtime titles can arrive before layout hydration in SSH/replay
// paths. With exactly one title and one authoritative agent row, the tab
// is unambiguous enough to prefer that row over a stale spinner.
// Why: runtime titles can precede layout hydration (SSH/replay); with one title and one agent row, prefer that row over a stale spinner.
const hasSingleUnmappedAgentStatusPane =
leafId === null && agentStatusPaneIds?.size === 1 && paneTitleEntries.length === 1
if (
@@ -98,21 +83,14 @@ function tabHasStatus(
}
return false
}
// Why: a tab-level title does not identify which split pane it came from.
// Once any visible agent row owns a pane in that tab, prefer the row state
// to avoid resurrecting stale "working" titles for a completed pane.
// Why: a tab title can't identify its pane; once an agent row owns one, prefer the row over a completed pane's stale "working" title.
if (agentStatusPaneIds && agentStatusPaneIds.size > 0) {
return false
}
return classifyTitleActivity(tab.title) === status && titleStatusIsAgentAttributable(tab.title)
}
// Why: the title heuristic is only a fallback — hook-managed agents promote the
// worktree via hasLiveWorking/hasPermission in resolveWorktreeStatus, not here.
// A bare braille-spinner title (e.g. an exited agent's never-cleared "⠐ task"
// frame) classifies as working yet produces no sidebar agent row, spinning the
// worktree forever with "0 agents". Require the same agent attribution the row
// builder uses, so a title only spins the dot when it would also show a row.
// Why: require agent attribution so a bare never-cleared spinner title can't spin the dot "0 agents" forever with no matching sidebar row.
function titleStatusIsAgentAttributable(title: string): boolean {
return resolveAgentTypeFromTerminalTitle(title) !== null
}
@@ -123,27 +101,12 @@ export function getWorktreeStatusLabel(status: WorktreeStatus): string {
/**
* Apply the WorktreeCard priority overlay (permission > working > done >
* heuristic) on top of the title-heuristic base. Live PTY liveness still gates
* title-derived working/permission, but explicit agent rows are allowed to
* promote the dot: if the sidebar shows a running/completed/blocking inline
* agent row, the worktree status must agree with that visible row. Sleep
* cleanup owns removing stale retained rows; once they are gone, no promotion
* occurs.
* heuristic) on top of the title-heuristic base. Explicit agent rows may
* promote the dot; sleep cleanup owns removing stale retained rows.
*
* Argument semantics (sourced by the WorktreeCard caller from the store):
* - `tabs`, `browserTabs`: the worktree's terminal and browser tabs.
* - `ptyIdsByTabId`: live-PTY map narrowed to this worktree (the liveness
* gate; see tabHasLivePty).
* - `runtimePaneTitlesByTabId`: per-tab pane title map narrowed to this
* worktree (used by the title-heuristic for split-pane spinners).
* - `hasPermission`: any fresh hook entry in {blocked, waiting} for a tab in
* this worktree.
* - `hasLiveWorking`: any fresh hook entry in {working} for a tab in this
* worktree.
* - `hasLiveDone`: any fresh hook entry in {done} for a tab in this worktree.
* - `hasRetainedDone`: any retained-agent snapshot scoped to this worktreeId.
* - `agentStatusPaneIdsByTabId`: stable leaf ids and legacy runtime pane ids
* whose visible agent rows should override title-derived heuristics.
* Map args are narrowed to this worktree. `hasPermission`/`hasLiveWorking`/
* `hasLiveDone` are fresh hook entries ({blocked,waiting} / {working} / {done});
* `hasRetainedDone` is a retained-agent snapshot scoped to this worktreeId.
*/
export function resolveWorktreeStatus(args: {
tabs: readonly Pick<TerminalTab, 'id' | 'title'>[]
@@ -172,17 +135,11 @@ export function resolveWorktreeStatus(args: {
if (args.hasPermission) {
return 'permission'
}
// Why: heuristic 'permission' must outrank heuristic 'working' (a tab can
// be "working" while another pane in the same tab is blocked on permission;
// the user-actionable signal wins). Both this branch and the args.hasPermission
// branch above return 'permission' — they're separated only because
// args.hasPermission must also outrank heuristic 'working' below.
// Why: heuristic 'permission' outranks heuristic 'working' — the user-actionable signal wins when panes in one tab disagree.
if (heuristic === 'permission') {
return 'permission'
}
// Why: restored-but-unfocused cards may have the startup hook snapshot before
// their terminal pane mounts and repopulates runtimePaneTitlesByTabId.
// Trust the fresh explicit working row so those cards stay yellow on restart.
// Why: restored cards get the hook snapshot before panes mount; trust the explicit working row so they stay yellow on restart.
if (args.hasLiveWorking || heuristic === 'working') {
return 'working'
}
+22 -71
View File
@@ -70,11 +70,7 @@ type TabsProjectionCache = {
}
const registeredTabs = new Map<string, RegisteredTerminalTab>()
// Why: track when each tab was registered so we can suppress the "no live
// transport" warning during the initial PTY connection window. The warning
// is noise when it fires on mount (PTY spawn/attach is async and hasn't
// finished yet), but valuable if the transport is still missing after the
// grace period — that indicates a real stuck state.
// Why: registration time suppresses the "no live transport" warning during the async PTY-connect window; after the grace period it's a real stuck state.
const tabRegisteredAt = new Map<string, number>()
const NO_TRANSPORT_GRACE_MS = 10_000
const EMPTY_ACTIVE_BROWSER_TAB_ID_BY_WORKTREE: AppState['activeBrowserTabIdByWorktree'] = {}
@@ -112,8 +108,7 @@ export function registerRuntimeTerminalTab(tab: RegisteredTerminalTab): () => vo
tabRegisteredAt.set(tab.tabId, Date.now())
scheduleRuntimeGraphSync()
return () => {
// Why: React can mount a replacement surface before the prior effect
// cleans up. Stale cleanup must not erase the successor's live registry.
// Why: React can mount a replacement surface before the prior effect cleans up; stale cleanup must not erase the successor's registry.
if (registeredTabs.get(tab.tabId) !== tab) {
return
}
@@ -169,9 +164,7 @@ export function scheduleRuntimeGraphSync(): void {
return
}
syncScheduled = true
// Why: terminal title/status updates often arrive as separate IPC tasks.
// A frame-sized timer collapses that churn into one graph publish without
// tying runtime state publication to paint frames or visible-window status.
// Why: a frame-sized timer collapses separate title/status IPC tasks into one graph publish without tying publication to paint frames.
syncTimer = setTimeout(() => {
syncTimer = null
syncScheduled = false
@@ -191,22 +184,14 @@ async function runRuntimeGraphSync(): Promise<void> {
syncInFlight = false
if (syncPendingAfterFlight) {
syncPendingAfterFlight = false
// Why: syncWindowGraph crosses IPC and can be slower than title/layout
// churn. Collapse all updates that arrived during one in-flight sync
// into a single trailing graph instead of stacking concurrent IPC calls.
// Why: coalesce updates that arrived during one in-flight sync into a single trailing graph instead of stacking concurrent IPC calls.
scheduleRuntimeGraphSync()
}
}
}
export type RuntimeMobileSessionSyncKey = {
// Why: large maps the renderer never reshapes are compared by reference.
// Reallocating `terminalLayoutsByTabId` / `runtimePaneTitlesByTabId` is the
// signal that some pane layout or pane title actually changed; nothing else
// in the store rewrites those references. Comparing references avoids
// stringifying potentially thousands of accumulated tab entries on every
// `setActivePane` / `updateTabTitle` mutation. See
// docs/agent-working-pane-typing-lag.md.
// Why: compared by reference; reallocation signals a real layout/title change, avoiding stringifying thousands of tabs. See docs/agent-working-pane-typing-lag.md.
terminalLayoutsByTabId: AppState['terminalLayoutsByTabId']
runtimePaneTitlesByTabId: AppState['runtimePaneTitlesByTabId']
groupsByWorktree: AppState['groupsByWorktree']
@@ -225,10 +210,7 @@ export type RuntimeMobileSessionSyncKey = {
generatedTabTitlesEnabled: boolean
systemPrefersDark: boolean | null
terminalThemeProjection: string
// Why: these projections still need value-level inspection because the
// underlying references churn even when the mobile-relevant shape is
// unchanged (`tabsByWorktree` reallocates on every OSC title frame).
// Pre-serialize them once.
// Why: underlying refs churn even when the mobile shape is unchanged (tabsByWorktree reallocates per OSC title frame); pre-serialize.
tabsProjection: string
openFilesProjection: string
browserProjection: string
@@ -315,9 +297,7 @@ export function getRuntimeMobileSessionSyncKey(
activeTabId: state.activeTabId,
activeBrowserTabIdByWorktree:
state.activeBrowserTabIdByWorktree ?? EMPTY_ACTIVE_BROWSER_TAB_ID_BY_WORKTREE,
// Why: paired web/mobile snapshots include full agentStatus details. The
// epoch covers sort/retention/freshness transitions; the projection covers
// prompt/tool details without publishing every timestamp-only heartbeat.
// Why: epoch covers sort/retention/freshness changes; projection covers prompt/tool details, skipping timestamp-only heartbeats.
agentStatusEpoch: state.agentStatusEpoch ?? 0,
agentStatusProjection:
canReusePrevious && agentStatusByPaneKey === previousAgentStatusByPaneKey
@@ -331,9 +311,7 @@ export function getRuntimeMobileSessionSyncKey(
previousKey.systemPrefersDark === terminalThemeSystemPrefersDark
? previousKey.terminalThemeProjection
: JSON.stringify(resolveMobileTerminalTheme(state, systemPrefersDark) ?? null),
// Why: background agent title ticks can change runtimePaneTitlesByTabId
// many times per second while the user types elsewhere. Reuse unchanged
// projections so those ticks do not rescan all tabs, files, and drafts.
// Why: background title ticks churn many times/sec; reuse unchanged projections so they don't rescan all tabs, files, and drafts.
tabsProjection:
canReusePrevious && state.tabsByWorktree === previousState.tabsByWorktree
? previousKey.tabsProjection
@@ -356,8 +334,7 @@ export function getRuntimeMobileSessionSyncKey(
}
function getBrowserTabsByWorktree(state: AppState): AppState['browserTabsByWorktree'] {
// Why: some runtime-sync callers and tests construct partial pre-browser
// renderer states; treat missing browser slices as no browser tabs.
// Why: some callers/tests build partial pre-browser states; treat missing browser slices as no tabs.
return state.browserTabsByWorktree ?? EMPTY_BROWSER_TABS_BY_WORKTREE
}
@@ -496,8 +473,7 @@ function buildRuntimeMobileAgentStatusProjection(
})),
toolName: entry.toolName ?? null,
toolInput: entry.toolInput ?? null,
// Why: include so a newly-captured AskUserQuestion prompt re-fires the
// mobile session republish even when no other field changed.
// Why: include so a newly-captured AskUserQuestion prompt re-fires the mobile republish even when no other field changed.
interactivePrompt: entry.interactivePrompt ?? null,
lastAssistantMessage: entry.lastAssistantMessage ?? null,
interrupted: entry.interrupted ?? null
@@ -539,15 +515,10 @@ async function syncRuntimeGraph(): Promise<void> {
if (!syncEnabled || !getStoreState) {
return
}
// Why: the runtime graph helper cannot import the Zustand store directly
// because the terminal slice also imports this module to schedule syncs.
// Injecting the getter from App keeps the runtime graph path out of the
// store construction cycle and avoids test-time partial initialization.
// Why: can't import the store directly (terminal slice imports this module); inject the getter to break the construction cycle.
const state = getStoreState()
const systemPrefersDark = getSystemPrefersDark()
// Why: sync can run after high-churn terminal/title mutations. Build lookup
// maps once per sync instead of flattening every worktree's tabs for each
// registered terminal.
// Why: build lookup maps once per sync instead of re-flattening every worktree's tabs for each registered terminal.
const terminalTabById = new Map(
Object.values(state.tabsByWorktree)
.flat()
@@ -615,13 +586,7 @@ async function syncRuntimeGraph(): Promise<void> {
}
}
// Why: background automation tabs spawn their agent PTY eagerly and are created
// inactive, so they never mount a TerminalPane and never enter `registeredTabs`.
// Without this pass their leaf+ptyId is never published, so the runtime treats
// the live agent PTY as orphaned (surfaced as a synthetic `pty:<id>` terminal)
// and `orca terminal list` / session-reuse can't see the real tab. Publish them
// from the persisted layout, gated on a live eager buffer so we only adopt a
// still-running unmounted PTY (never a stale saved ptyId).
// Why: inactive automation tabs never mount a TerminalPane; publish their leaf+ptyId from persisted layout (gated on a live buffer) or the live PTY looks orphaned.
for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) {
for (const tab of tabs) {
if (registeredTabs.has(tab.id) || isWebOnlyMirroredTerminalTab(state, tab)) {
@@ -685,9 +650,7 @@ export function buildMobileSessionTabSnapshots(
state: AppState,
systemPrefersDark = getSystemPrefersDark()
): RuntimeMobileSessionTabsSnapshot[] {
// Why: mobile publication can run on high-frequency background agent title
// ticks. Cache open-file indexes and draft hashes by immutable store-slice
// reference so title-only syncs do not rescan or rehash editor state.
// Why: high-frequency title ticks fire mobile sync; cache indexes/hashes by store-slice ref to skip rescanning editor state.
const openFileIndexes = getOpenFileIndexes(state.openFiles)
const editorDraftVersionByFileId = getEditorDraftVersionByFileId(state.editorDrafts)
const worktreeIds = new Set<string>([
@@ -788,8 +751,7 @@ export function buildMobileSessionTabSnapshots(
}
}
// Why: split-group projection can miss plain editor files during hydration.
// Publish the missing file so paired mobile/web clients still mirror it.
// Why: split-group projection can miss plain editor files during hydration; publish them so mobile/web still mirror.
const fallbackEditorTabs: FallbackEditorTabTarget[] = []
if (openFilesForWorktree) {
const unifiedEditorTabs = getEditorUnifiedTabsForWorktree(state, worktreeId)
@@ -876,8 +838,7 @@ export function buildMobileSessionTabSnapshots(
}
function isEditorSurfaceTab(tab: Pick<Tab, 'contentType'>): boolean {
// Why: mobile file snapshots can faithfully mirror ordinary edit/diff files;
// conflict review and check-details tabs require metadata this contract lacks.
// Why: mobile can mirror ordinary edit/diff files; conflict-review and check-details tabs need metadata this contract lacks.
return tab.contentType === 'editor' || tab.contentType === 'diff'
}
@@ -1009,10 +970,7 @@ function isWebOnlyMirroredTerminalTab(
const ptyIds = [tab.ptyId, ...layoutPtyIds].filter(
(ptyId): ptyId is string => typeof ptyId === 'string' && ptyId.length > 0
)
// Why: web mirror ids are a web-renderer implementation detail. If such an
// id has only remote/no PTYs, it is a mirror and must not be published back
// as host state. Legacy leaked host tabs with local PTYs still publish so
// existing sessions keep desktop/web parity.
// Why: only-remote/no-PTY tabs are web mirrors, not host state; legacy local-PTY tabs still publish for desktop/web parity.
return ptyIds.every(isRemoteRuntimePtyId)
}
@@ -1151,8 +1109,7 @@ function buildMobileSessionGroupProjection(
}
const tabOrder = visibleOrder.map((item) => item.tabId ?? item.id)
const tabOrderSet = new Set(tabOrder)
// Why: persisted split groups can contain very large tab orders; append
// iteratively so mobile sync does not hit V8's argument-list limit.
// Why: persisted split groups can have very large tab orders; append iteratively to avoid V8's argument-list limit.
for (const item of visibleOrder) {
order.push(item)
}
@@ -1259,9 +1216,7 @@ function getRuntimeLeafIdsForTerminal(tabId: string, state: AppState): string[]
return persistedLeafIds
}
// Why: a newly-created terminal tab can be in the store before TerminalPane
// mounts. Without a live or persisted UUID leaf, there is no stable mobile
// surface to publish yet; fabricating pane:1 would become stale after mount.
// Why: a new tab can predate TerminalPane mount; fabricating pane:1 with no live/persisted leaf would go stale after mount.
return []
}
@@ -1301,9 +1256,7 @@ function buildMobileTerminalSurfaceTabs(
typeof HTMLElement !== 'undefined' && firstChild instanceof HTMLElement ? firstChild : null
)
const parentLayout = normalizeTerminalLayoutSnapshot({
// Why: the live DOM tree (when mounted) is authoritative; otherwise the
// saved tree. Both carry the real direction — only synthesize as a last
// resort, never re-guess. Shared with the client-ingest path.
// Why: live DOM tree is authoritative when mounted, else the saved tree; synthesize only as a last resort, never re-guess.
root: resolveTerminalLayoutRoot({
authoritativeRoot: liveLayoutRoot,
existingRoot: sanitizedSavedLayout?.root,
@@ -1466,8 +1419,7 @@ function isMobileUnsupportedCombinedDiffSource(
}
function isMobilePublishableOpenFile(file: AppState['openFiles'][number]): boolean {
// Why: combined diff tabs use display labels as relative paths and require
// the desktop combined renderer; mobile would otherwise try files.read.
// Why: combined diff tabs use display labels as paths and need the desktop renderer; mobile would mis-call files.read.
return !isMobileUnsupportedCombinedDiffSource(file.diffSource)
}
@@ -1492,8 +1444,7 @@ function buildMobileBrowserTab(
loading: activePage?.loading ?? workspace.loading,
canGoBack: activePage?.canGoBack ?? workspace.canGoBack,
canGoForward: activePage?.canGoForward ?? workspace.canGoForward,
// Why: null means the active page successfully cleared its failure. Falling
// back through ?? would resurrect a stale workspace-level error.
// Why: null means the active page cleared its failure; ?? would resurrect a stale workspace-level error.
loadError: activePage ? activePage.loadError : workspace.loadError,
certificateFailure: activePage
? (state.browserCertificateFailuresByPageId?.[activePage.id] ?? null)
+19 -56
View File
@@ -35,8 +35,7 @@ export {
export function isWebRuntimeSessionActive(
activeRuntimeEnvironmentId: string | null | undefined
): boolean {
// Why: headless serve sessions are owned by the remote runtime, regardless
// of whether the attaching client is web or desktop Electron.
// Why: headless serve sessions are owned by the remote runtime, whether the client is web or desktop Electron.
return Boolean(activeRuntimeEnvironmentId?.trim())
}
@@ -95,8 +94,7 @@ export async function createWebRuntimeSessionTerminal(args: {
response as RuntimeRpcResponse<RuntimeMobileSessionCreateTerminalResult>
)
if (args.activate !== false) {
// Why: record focus intent so the reconcile follows the snapshot's active
// tab to THIS new terminal, instead of sticky-keeping the prior tab.
// Why: record focus intent so the reconcile follows to this new terminal instead of sticky-keeping the prior tab.
recordWebSessionFocusIntent(args.worktreeId, createdTerminal.tab.id)
}
await refreshWebRuntimeSessionTabsSnapshot(environmentId, args.worktreeId)
@@ -139,24 +137,17 @@ export async function createWebRuntimeSessionBrowserTab(args: {
worktree: toRuntimeWorktreeSelector(args.worktreeId),
url: args.url,
profileId: args.profileId ?? undefined,
// Why: this is the user clicking "New Browser Tab", so focus it. On a
// headless host this marks the tab active in the session snapshot so the
// reconcile keeps focus on it instead of snapping back to a terminal.
// Why: user clicked "New Browser Tab", so mark it active in the snapshot, else the reconcile snaps back to a terminal.
activate: true,
// Why: place the new browser in the split group whose "+" was clicked,
// so the host snapshot is authoritative for its group (no left-snap).
// Why: place the new browser in the clicked split group so the host snapshot is authoritative for it (no left-snap).
...(args.targetGroupId ? { targetGroupId: args.targetGroupId } : {}),
// Why: paired web clients need the local tab immediately. The remote
// pane will stream once the host webview registers; waiting here makes
// the workspace appear to close while the host finishes mounting.
// Why: web clients need the local tab now; waiting for host webview registration makes the workspace appear to close.
waitForRegistration: false
},
timeoutMs: 15_000
})
const created = unwrapRuntimeRpcResult(response as RuntimeRpcResponse<BrowserTabCreateResult>)
// Why: record focus intent (browser session tab id === browserPageId on a
// headless host) so the reconcile follows the snapshot's active tab to this
// new browser tab rather than sticky-keeping the prior one.
// Why: record focus intent (tab id === browserPageId on a headless host) so the reconcile follows to the new browser tab.
recordWebSessionFocusIntent(args.worktreeId, created.browserPageId)
stageWebRuntimeBrowserTab({
environmentId,
@@ -212,9 +203,7 @@ function stageWebRuntimeBrowserTab(args: {
}
const url = args.url?.trim() || 'about:blank'
// Why: paired web browser tabs are host-owned, but the session snapshot can
// arrive after React has already rendered a fallback workspace. Stage the
// remote handle immediately so the current worktree stays selected.
// Why: the snapshot can arrive after React renders a fallback; stage the handle now so the worktree stays selected.
const browserTab = useAppStore.getState().createBrowserTab(args.worktreeId, url, {
title: url === 'about:blank' ? 'New Browser Tab' : url,
focusAddressBar: true,
@@ -270,14 +259,12 @@ async function refreshWebRuntimeSessionTabsSnapshot(
const { applyFreshWebSessionTabsSnapshot, applyWebSessionTabsStorePatch } =
await import('./web-session-tabs-sync')
applyWebSessionTabsStorePatch((state) => {
// Why: eager refreshes can resolve after the user has selected another
// worktree; session parity should update tabs without stealing focus.
// Why: eager refreshes can resolve after the user switched worktrees; update tabs without stealing focus.
const patch = applyFreshWebSessionTabsSnapshot(state, snapshot, environmentId)
return patch === state ? state : patch
})
} catch (error) {
// Why: browser creation already succeeded on the host. If the eager parity
// refresh fails, the long-lived session.tabs subscription can still catch up.
// Why: host creation already succeeded; the long-lived session.tabs subscription catches up if this eager refresh fails.
console.warn(
'[web-runtime-session] failed to refresh browser tab snapshot:',
error instanceof Error ? error.message : String(error)
@@ -350,10 +337,7 @@ export async function moveWebRuntimeSessionTab(
}
if (args.kind === 'reorder') {
// Why: record the intended LOCAL order synchronously, before the async host
// resolution below, so an in-flight pre-move snapshot carrying the old order
// can't snap the tab back. The reconcile applies this until the host echoes
// the new order. (tabOrder here is already local unified tab ids.)
// Why: record local order synchronously before async host resolution, so a pre-move snapshot can't snap the tab back.
recordWebSessionReorderIntent(args.worktreeId, args.targetGroupId, args.tabOrder, Date.now())
}
@@ -401,9 +385,7 @@ export async function moveWebRuntimeSessionTab(
? {
...base,
kind: 'reorder' as const,
// Why: paired web groups can contain local-only tabs alongside
// host-mirrored tabs. The host reorder API only accepts host tab
// ids, so local ids must be omitted from the mirrored order.
// Why: the host reorder API only accepts host tab ids, so local-only tabs must be omitted from the mirrored order.
tabOrder: reorderedHostTabOrder
}
: args.kind === 'split'
@@ -415,8 +397,7 @@ export async function moveWebRuntimeSessionTab(
: {
...base,
kind: 'move-to-group' as const,
// Why: web groups can contain local-only tabs. Host insertion
// indexes must be counted in the filtered host-backed order.
// Why: web groups can contain local-only tabs, so host insertion indexes count only the filtered host-backed order.
index: targetHostIndex
}
const response = await window.api.runtimeEnvironments.call({
@@ -453,12 +434,7 @@ async function callWebRuntimeSessionTabMethod(
}
if (method === 'session.tabs.close') {
// Why: the caller prunes the local mirror synchronously, but the precise
// host id resolution below sits behind an async import. A host snapshot
// published in that gap would re-materialize the just-closed tab before any
// intent exists to suppress it (the immediate "flash back"). Record a
// best-effort intent synchronously now — the resolved-id record below then
// covers any id the static decode couldn't recover.
// Why: sync best-effort intent before the async id resolution, so a snapshot in that gap can't flash the closed tab back.
recordWebSessionCloseIntent(args.worktreeId, toHostSessionTabId(args.tabId), Date.now())
}
@@ -472,9 +448,7 @@ async function callWebRuntimeSessionTabMethod(
tabId: args.tabId
}) ?? toHostSessionTabId(args.tabId)
if (method === 'session.tabs.close') {
// Why: the local mirror is pruned before this resolves, so suppress this
// host tab in the reconcile until the host snapshot confirms removal —
// otherwise an in-flight pre-close snapshot makes the tab flash back.
// Why: suppress until the host confirms removal, else an in-flight pre-close snapshot flashes the tab back.
recordWebSessionCloseIntent(args.worktreeId, hostTabId, Date.now())
}
const response = await window.api.runtimeEnvironments.call({
@@ -514,9 +488,7 @@ export function splitWebRuntimeTerminal(
return false
}
// Why: split requests from the paired web client must run on the host pane.
// A local split would mint a web-only pane and the host would mirror it back
// as a separate tab instead of preserving the terminal split layout.
// Why: split must run on the host pane; a local split mints a web-only pane the host mirrors back as a tab, not a split.
const pendingMirrorSuppressionId = reservePendingWebRuntimeSplitMirrorTelemetry(ptyId, direction)
const releasePendingMirrorSuppression = schedulePendingWebRuntimeSplitMirrorTelemetryRelease(
ptyId,
@@ -632,9 +604,7 @@ export function closeWebRuntimeTerminal(ptyId: string | null | undefined): boole
return false
}
// Why: host-session mirror panes are detached locally in the browser, but
// the host owns the real pane graph. Close the host terminal first so later
// session snapshots cannot resurrect the locally removed pane.
// Why: host owns the real pane graph; close the host terminal first so later snapshots can't resurrect the removed pane.
void window.api.runtimeEnvironments
.call({
selector: environmentId,
@@ -656,10 +626,7 @@ export function closeWebRuntimeTerminal(ptyId: string | null | undefined): boole
return true
}
// Why: pane geometry inside a tab (split ratios, expanded pane, pane titles) is
// host-authoritative for remote-server tabs, so a local-only divider drag /
// expand / pane-rename reverts on the next snapshot. Push the structure to the
// host so it persists. tabId is the local web tab id; we resolve the host id.
// Why: pane geometry is host-authoritative for remote tabs; local-only changes revert on next snapshot, so push to host.
export async function updateWebRuntimePaneLayout(args: {
worktreeId: string
tabId: string
@@ -699,9 +666,7 @@ export async function updateWebRuntimePaneLayout(args: {
}
}
// Why: tab color/pin are host-authoritative for remote-server tabs; mirror the
// change to the host so it persists and survives the next snapshot. Pass only
// the fields that changed (undefined = leave as-is on the host).
// Why: tab color/pin are host-authoritative; mirror the change so it persists (undefined field = leave as-is on host).
export function setWebRuntimeTabProps(args: {
worktreeId: string
tabId: string
@@ -748,9 +713,7 @@ export function setWebRuntimeTabProps(args: {
return true
}
// Why: clearing scrollback locally (pane.terminal.clear()) is undone by the next
// host snapshot/re-subscribe, which replays the host buffer. Clear the host
// buffer too so the clear actually sticks on a remote-server pane.
// Why: local pane.terminal.clear() is undone by the next host snapshot replay; clear the host buffer so it sticks.
export function clearWebRuntimeTerminalBuffer(ptyId: string | null | undefined): boolean {
if (!ptyId) {
return false
+39 -125
View File
@@ -1,6 +1,4 @@
/* eslint-disable max-lines -- Why: web session-tab sync reconciles terminal,
* unified-tab, group, and PTY maps atomically so host-published surfaces don't
* leave the web client in a split-brain tab state. */
/* eslint-disable max-lines -- web session-tab sync reconciles terminal, unified-tab, group, and PTY maps atomically to avoid split-brain tab state */
import { useEffect } from 'react'
import type { AppState } from '../store'
import { useAppStore } from '../store'
@@ -178,11 +176,7 @@ export function getLastKnownHostTerminalTabCount(
)
}
// Why: a post-reconnect subscription replay re-emits the current snapshot with
// an unchanged epoch/version; dropping the freshness entry lets the monotonic
// gate accept that replay as authoritative instead of freezing the mirror
// (#7718). Normal-operation ordering protection is untouched — this only runs
// for responses the connection tagged as reconnect replays.
// Why: a post-reconnect replay re-emits the snapshot with unchanged epoch/version; dropping the freshness entry lets the monotonic gate accept it instead of freezing the mirror (#7718).
export function acceptReplayedWebSessionTabsSnapshot(
environmentId: string,
worktreeId: string
@@ -196,31 +190,18 @@ export function shouldApplyWebSessionTabsSnapshot(
): boolean {
const key = sessionTabsFreshnessKey(environmentId, snapshot.worktree)
if ((snapshot as { removed?: unknown }).removed === true) {
// Why: removed worktrees can stop publishing snapshots, so their
// freshness/mapping entries need explicit cleanup instead of waiting for
// a later replacement snapshot that may never arrive.
// Why: removed worktrees can stop publishing, so clean up their tracking now instead of waiting for a replacement snapshot that may never arrive.
clearWebSessionTabsTrackingForWorktree(environmentId, snapshot.worktree)
queueAcceptedWebSessionTerminalSnapshot(snapshot, environmentId)
return true
}
if (snapshot.worktree === FLOATING_TERMINAL_WORKTREE_ID) {
// Why: the floating workspace is a local synthetic terminal. A focused
// remote runtime can publish an empty same-id snapshot while the user has a
// local ssh/tmux tab open; treating that as authoritative deletes the local
// floating tabs.
// Why: the floating workspace is a local synthetic terminal; a remote empty same-id snapshot would delete the user's local floating tabs.
return false
}
rememberHostTerminalTabCount(environmentId, snapshot)
const current = latestSessionTabsSnapshotByWorktree.get(key)
// Why: snapshotVersion is monotonic only WITHIN one host generation; it resets
// when the host restarts, and each restart produces a different publicationEpoch.
// So only treat a frame as stale when it shares the current epoch and isn't
// newer — a different epoch is a new generation (or a restart) and must apply,
// even if its version is lower. (A cross-stream out-of-order frame with a
// different epoch may briefly apply, but the next snapshot's higher version
// self-heals it; rejecting on version alone would instead permanently drop a
// post-restart snapshot, since the client's tracking survives transparent
// transport reconnects.)
// Why: snapshotVersion is monotonic only within one publicationEpoch (resets on host restart); reject as stale only within the same epoch, since a different epoch is a new generation and must apply.
if (
current &&
current.publicationEpoch === snapshot.publicationEpoch &&
@@ -232,8 +213,7 @@ export function shouldApplyWebSessionTabsSnapshot(
publicationEpoch: snapshot.publicationEpoch,
snapshotVersion: snapshot.snapshotVersion
})
// Why: a mounted mirror that exhausted bounded polling needs fresh host
// evidence without subscribing to every application-store write.
// Why: a mounted mirror that exhausted bounded polling needs fresh host evidence without subscribing to every store write.
queueAcceptedWebSessionTerminalSnapshot(snapshot, environmentId)
return true
}
@@ -437,8 +417,7 @@ function chooseRemoteTerminalLayout(
])
: undefined
const activeLeafId =
// Why: host title/status snapshots may still mark an agent pane active
// after this client selected a different split pane.
// Why: host title/status snapshots may still mark an agent pane active after this client selected a different split pane.
(existingLayout?.activeLeafId && knownLeafIds.has(existingLayout.activeLeafId)
? existingLayout.activeLeafId
: null) ??
@@ -453,9 +432,7 @@ function chooseRemoteTerminalLayout(
? parentLayout.expandedLeafId
: null
return {
// Why: the host's parentLayout is authoritative (carries the real split
// direction); only if it doesn't cover the current leaves do we keep the
// prior client tree, then degenerate — never re-guess a direction.
// Why: host parentLayout is authoritative for split direction; else keep the prior client tree, then degenerate — never re-guess a direction.
root: resolveTerminalLayoutRoot({
authoritativeRoot: parentLayout?.root,
existingRoot: existingLayout?.root,
@@ -468,9 +445,7 @@ function chooseRemoteTerminalLayout(
activeLeafId,
expandedLeafId,
ptyIdsByLeafId,
// Why: surface.title is the tab/PTY label ("Terminal 2", agent title,
// etc.). Restoring it as a pane title makes the web client render a fake
// title bar above xterm. Only host layout titles are real user pane titles.
// Why: surface.title is the tab/PTY label, not a pane title; restoring it as one renders a fake title bar. Only host layout titles are real pane titles.
...(parentLayout?.titlesByLeafId ? { titlesByLeafId: parentLayout.titlesByLeafId } : {})
}
}
@@ -487,14 +462,11 @@ function shouldReplaceTerminalTab(
!isMirroredTerminalSurfaceId(tab.id) &&
nextMirroredLaunchAgents.has(tab.launchAgent)
) {
// Why: paired web agent quick-launch used to create local-only tabs before
// the host snapshot landed. Retire only the matching agent's stale row.
// Why: agent quick-launch created a local-only tab before the host snapshot landed; retire only the matching agent's stale row.
return true
}
if (isMirroredTerminalSurfaceId(tab.id)) {
// Why: host session snapshots are authoritative for host-mirrored tabs.
// Replace old mirrors even when the next surface is still waiting on a
// stream handle, otherwise paired web keeps stale handles or drops parity.
// Why: host snapshots are authoritative for mirrored tabs; replace old mirrors even when the next surface still awaits a stream handle, else parity drifts.
return true
}
if (tab.pendingActivationSpawn && tab.ptyId === null && nextRemotePtyIds.size > 0) {
@@ -503,9 +475,7 @@ function shouldReplaceTerminalTab(
if (!isRuntimeTerminalTabForEnvironment(tab, environmentId)) {
return false
}
// Why: web-created remote tabs use local UUIDs until the host publishes the
// corresponding session surface. Only retire them once their PTY is present
// in the host snapshot, while always pruning prior mirrored surface IDs.
// Why: web-created remote tabs use local UUIDs until the host publishes their surface; only retire them once their PTY appears in the snapshot.
return (
tab.ptyId !== null &&
(nextRemotePtyIds.has(tab.ptyId) ||
@@ -513,10 +483,7 @@ function shouldReplaceTerminalTab(
)
}
/**
* Constructs mirrored terminal tabs from the mobile session status payload,
* normalising Pi-compatible agent titles under launch ownership.
*/
/** Constructs mirrored terminal tabs from the mobile session status payload, normalising Pi-compatible agent titles under launch ownership. */
function buildMirroredTerminalTabs(
snapshot: RuntimeMobileSessionTabsResult,
environmentId: string,
@@ -571,23 +538,16 @@ function buildMirroredTerminalTabs(
activeSurface.quickCommandLabel?.trim() ||
surfaces.find((surface) => surface.quickCommandLabel?.trim())?.quickCommandLabel?.trim() ||
existing?.quickCommandLabel?.trim()
// Why: startup cwd is host-owned launch metadata; once the host omits it,
// mirrored clients must not resurrect stale subdirectory intent.
// Why: startupCwd is host-owned launch metadata; once the host omits it, don't resurrect stale subdirectory intent.
const startupCwd =
activeSurface.startupCwd || surfaces.find((surface) => surface.startupCwd)?.startupCwd
// Why: tab color/pin echo back through host snapshots, so prefer the client's
// own record (kept authoritative in tabsByWorktree by the pin/color setters)
// and fall back to the host value only when this client has no prior tab —
// e.g. first reconcile or a change made on another client. Mirrors how
// customTitle always prefers the client value to avoid echo-window reverts.
// Why: color/pin echo back through host snapshots, so prefer the client's own record and fall back to host only without a prior tab (avoids echo-window reverts).
const hostColorSurface = surfaces.find((surface) => surface.color != null)
const color = existing ? (existing.color ?? null) : (hostColorSurface?.color ?? null)
const isPinned = existing
? existing.isPinned === true
: surfaces.some((surface) => surface.isPinned)
// Why: viewMode echoes back through host snapshots like color/pin, so prefer
// the client's own record during the optimistic echo window and adopt the host
// value only when this client has no prior tab (first reconcile / other client).
// Why: viewMode echoes back through host snapshots, so prefer the client's record during the echo window and adopt the host value only without a prior tab.
const hostViewModeSurface = surfaces.find((surface) => surface.viewMode)
const viewMode = existing ? existing.viewMode : hostViewModeSurface?.viewMode
return {
@@ -605,8 +565,7 @@ function buildMirroredTerminalTabs(
...(viewMode ? { viewMode } : {}),
sortOrder: sortOffset + index,
createdAt: existing?.createdAt ?? now + index,
// Why: launchAgent is host-owned lifecycle metadata. If the host stops
// publishing it, mirrored clients must not resurrect stale startup intent.
// Why: launchAgent is host-owned lifecycle metadata; once the host omits it, don't resurrect stale startup intent.
...(launchAgent ? { launchAgent } : {})
},
hostTabId: parentTabId,
@@ -623,10 +582,7 @@ function toMirroredPaneKey(surface: TerminalSurface): string | null {
return makePaneKey(toWebTerminalSurfaceTabId(surface.parentTabId), surface.leafId)
}
/**
* Normalises and mirrors agent status updates from the host payload,
* preserving authoritative ownership metadata.
*/
/** Normalises and mirrors agent status updates from the host payload, preserving ownership metadata. */
function remapHostAgentStatus(surface: TerminalSurface): AgentStatusEntry | null {
if (!surface.agentStatus) {
return null
@@ -650,10 +606,7 @@ function isMirroredAgentPaneKeyForTabs(paneKey: string, tabIds: ReadonlySet<stri
return parsed !== null && tabIds.has(parsed.tabId)
}
/**
* Generates a state patch for mirrored agent statuses, merging host
* status entries with client overrides defensively.
*/
/** Generates a state patch for mirrored agent statuses, merging host entries with client overrides. */
function buildMirroredAgentStatusPatch(
state: WebSessionTabsSyncState,
currentTerminalTabs: readonly TerminalTab[],
@@ -681,9 +634,7 @@ function buildMirroredAgentStatusPatch(
continue
}
const existing = state.agentStatusByPaneKey[entry.paneKey]
// Why: active web streams can report a fresher OSC 9999 status for the same
// mirrored pane before the next host snapshot arrives. Do not rewind that
// row with an older host publication.
// Why: an active web stream can report a fresher OSC 9999 status before the next host snapshot, so don't rewind it with an older host publication.
const nextEntry =
existing && existing.updatedAt > entry.updatedAt
? normalizeCompatibleAgentStatusEntryForOwner(existing, entry.agentType)
@@ -748,10 +699,7 @@ function buildMirroredAgentStatusPatch(
function buildTerminalUnifiedTab(
tab: TerminalTab,
groupId: string,
// Why: viewMode (terminal vs native chat) is host-tracked, but the client's
// optimistic toggle must win during the echo window. Callers pass the reconciled
// value (host value falling back to the captured client value) so toggling to
// chat doesn't revert when the next session-graph sync rebuilds tabs.
// Why: viewMode is host-tracked but the client's optimistic toggle must win during the echo window; callers pass the reconciled value.
viewMode?: Tab['viewMode']
): Tab {
return {
@@ -871,8 +819,7 @@ function buildMirroredEditorTabs(
runtimeEnvironmentId: environmentId,
mode: tab.type === 'markdown' ? tab.mode : 'edit',
markdownPreviewSourceFileId: sourceFileId,
// Why: marks this tab as host-owned so a later snapshot that omits it can
// cull it. Locally opened web tabs lack this flag and survive syncs.
// Why: marks this tab host-owned so a later snapshot that omits it can cull it; locally opened tabs lack this flag and survive.
mirroredFromRuntimeSession: true
}
return {
@@ -1006,8 +953,7 @@ function chooseTargetGroupId(
group.id === state.activeGroupIdByWorktree[snapshot.worktree] && inRenderedLayout(group.id)
) ??
groups.find((group) => inRenderedLayout(group.id))
// Why: host snapshots can reference desktop-only group ids. The web layout's
// rendered group is the only safe CSS anchor target for mirrored panes.
// Why: host snapshots can reference desktop-only group ids; the rendered group is the only safe CSS anchor for mirrored panes.
const firstRenderedLayoutGroupId = layoutGroupIds.values().next().value as string | undefined
return (
preferred?.id ??
@@ -1233,8 +1179,7 @@ function buildMirroredHostGroups({
...(existing?.tabOrder.filter((tabId) => !localHostOrder.includes(tabId)) ?? []),
...localHostOrder
]
// Why: a pending client reorder for this group wins over a stale pre-move
// host order until the host echoes the move (or membership changes).
// Why: a pending client reorder wins over a stale pre-move host order until the host echoes the move (or membership changes).
const tabOrder = resolveWebSessionReorderedOrder(worktreeId, hostGroup.id, hostTabOrder, now)
if (tabOrder.length === 0) {
continue
@@ -1680,15 +1625,8 @@ export function applyWebSessionTabsSnapshot(
if (worktreeId === FLOATING_TERMINAL_WORKTREE_ID) {
return state
}
// Why: a remote close prunes the local mirror immediately, but an in-flight
// pre-close snapshot can still list the tab and flash it back. Drop any tab
// the client is closing until the host confirms removal; reconcile the intents
// against the full snapshot first so confirmed (absent) closes clear.
// Why: must match the id the close path records as the intent. The close RPC
// resolves to the host session tab id (terminal parentTabId; otherwise tab.id)
// — keying browser on browserPageId instead never matched, so browser closes
// were never suppressed and reconcile cleared the intent on the still-present
// snapshot. The host also addresses tabs by session id, not page id.
// Why: an in-flight pre-close snapshot can flash a closing tab back, so drop tabs the client is closing until the host confirms removal.
// Why: key close intents by host session tab id (terminal parentTabId else tab.id), not browserPageId, or browser closes never get suppressed.
const snapshotHostTabId = (tab: RuntimeMobileSessionTabsResult['tabs'][number]): string =>
tab.type === 'terminal' ? tab.parentTabId : tab.id
reconcileWebSessionCloseIntents(
@@ -1705,11 +1643,7 @@ export function applyWebSessionTabsSnapshot(
)
}
: rawSnapshot
// Why: only follow the snapshot's active tab over the user's current focus when
// the client itself initiated this activation (a create/activate it recorded).
// An unsolicited server-active (e.g. an agent "thinking" echo) must not steal
// focus — that's the #5435 contract. Intent matches by the host active tab id
// (terminal session id, or browserPageId for browser tabs); consume it once.
// Why: follow the snapshot's active tab over the user's focus only when this client initiated the activation; unsolicited server-active must not steal focus (#5435).
const focusIntentHostTabId = peekWebSessionFocusIntent(worktreeId)
const honorSnapshotActiveFocus =
focusIntentHostTabId !== null &&
@@ -1830,9 +1764,7 @@ export function applyWebSessionTabsSnapshot(
file.worktreeId === worktreeId &&
file.runtimeEnvironmentId === environmentId &&
(file.mode === 'edit' || file.mode === 'markdown-preview') &&
// Why: only cull tabs that came from the host mirror. Files the web
// user opened locally have no host counterpart, so a snapshot that
// omits them is not a signal to close them.
// Why: only cull host-mirrored tabs; locally opened files have no host counterpart, so their omission isn't a close signal.
file.mirroredFromRuntimeSession === true &&
!mirroredEditorFileIds.has(file.id)
)
@@ -1882,8 +1814,6 @@ export function applyWebSessionTabsSnapshot(
buildTerminalUnifiedTab(
entry.tab,
hostGroupIdByTabId.get(entry.hostTabId) ?? targetGroupId,
// Prefer the reconciled mirrored value (already client-wins during the echo
// window); fall back to the captured client value when the entry omits it.
entry.tab.viewMode ?? existingViewModeByTabId.get(entry.tab.id)
)
)
@@ -1935,8 +1865,7 @@ export function applyWebSessionTabsSnapshot(
(nextTerminalTabs ?? []).some((tab) => tab.id === state.activeTabIdByWorktree[worktreeId])
? state.activeTabIdByWorktree[worktreeId]
: null
// Why: when the client initiated this activation (honorSnapshotActiveFocus),
// the snapshot's active terminal wins over the sticky current focus.
// Why: on a client-initiated activation (honorSnapshotActiveFocus), the snapshot's active terminal wins over sticky current focus.
const intentTerminalId =
honorSnapshotActiveFocus && snapshot.activeTabType === 'terminal'
? activeMirroredTerminalId
@@ -1983,8 +1912,7 @@ export function applyWebSessionTabsSnapshot(
worktreeId,
nextUnifiedTabs
})
// Why: a client-initiated activation also drives the visible unified tab,
// overriding the sticky current-visible tab.
// Why: a client-initiated activation also drives the visible unified tab, overriding the sticky current-visible tab.
const intentUnifiedTabId = honorSnapshotActiveFocus
? snapshot.activeTabType === 'browser'
? activeMirroredBrowserTabId
@@ -2103,9 +2031,7 @@ export function applyWebSessionTabsSnapshot(
next.push(tabId)
}
}
// Why: remote snapshots can arrive after the client staged local browser
// tabs. Preserve the user's visible mixed order and only append new host
// tabs; otherwise terminal-browser-terminal can collapse to browser-terminal-terminal.
// Why: snapshots can arrive after the client staged local browser tabs, so preserve visible order and only append new host tabs.
for (const tabId of current) {
push(tabId)
}
@@ -2260,8 +2186,7 @@ export function applyWebSessionTabsSnapshot(
sameGroups
)
const nextActiveGroupId =
// Why: remote status/title snapshots carry the host's last active tab; a
// client that already switched panes must keep its local group focus.
// Why: status/title snapshots carry the host's last active tab; a client that already switched panes keeps its local group focus.
nextGroups?.find((group) => group.activeTabId === nextActiveUnifiedTabId)?.id ??
nextGroups?.find((group) => group.id === snapshot.activeGroupId)?.id ??
nextGroups?.[0]?.id ??
@@ -2363,10 +2288,7 @@ export function applyWebSessionTabsSnapshot(
: nextActiveEditorFileId
? ('editor' as const)
: ('terminal' as const)
// Why: an empty/closed host snapshot has no active host tab, but the web
// client must not keep pointing global shortcuts at a removed browser/editor.
// A client-initiated activation (honorSnapshotActiveFocus) makes the snapshot's
// type win, so a create can switch the visible pane (e.g. terminal -> browser).
// Why: don't keep pointing shortcuts at a removed browser/editor; a client-initiated activation lets the snapshot's type switch the visible pane.
const nextVisibleTabType = honorSnapshotActiveFocus
? (snapshotVisibleTabType ?? currentVisibleTabTypeStillValid ?? fallbackVisibleTabType)
: (currentVisibleTabTypeStillValid ?? snapshotVisibleTabType ?? fallbackVisibleTabType)
@@ -2520,8 +2442,7 @@ export function applyWebSessionTabsStorePatch(
patch !== state && Object.prototype.hasOwnProperty.call(patch, 'agentStatusByPaneKey')
return patch
})
// Why: paired-web snapshots bypass setAgentStatus, so they must explicitly
// arm the same stale-boundary timer as local hook events.
// Why: paired-web snapshots bypass setAgentStatus, so arm the stale-boundary timer explicitly like local hook events do.
if (mirroredAgentStatusChanged) {
useAppStore.getState().scheduleAgentStatusFreshness()
}
@@ -2541,20 +2462,15 @@ export function useWebSessionTabsSync(): void {
const environmentIds = runtimeSessionMirrorEnvironmentKey
? runtimeSessionMirrorEnvironmentKey.split('\u0000').filter((id) => id.trim())
: []
// Why: startup hydration writes browser-local session state; applying the
// host snapshot before that point gets clobbered and leaves the sidebar stale.
// Selectedness is not liveness: desktop and web clients both mirror the
// runtime's session bindings so background worktrees do not look asleep.
// Why: mirror all paired runtimes' sessions, not just the selected worktree, so background worktrees don't look asleep (selectedness isn't liveness).
// Why: applying the host snapshot before startup hydration writes browser-local session state clobbers it and leaves the sidebar stale.
if (!workspaceSessionReady || environmentIds.length === 0) {
return
}
let disposed = false
const unsubscribes: (() => void)[] = []
// Why: the streaming RPC emits an initial snapshots event, but startup can
// render a paired web session before that event is applied. A one-shot
// fetch makes initial parity deterministic; the stream remains the live
// update path afterward.
// Why: the stream's initial snapshot can land after first render, so a one-shot fetch makes initial parity deterministic.
for (const environmentId of environmentIds) {
if (
!shouldSyncAllRuntimeSessionTabs({
@@ -2667,8 +2583,7 @@ export function useWebSessionTabsSync(): void {
for (const unsubscribe of unsubscribes) {
unsubscribe()
}
// Why: environment ids can churn as paired runtimes reconnect or switch;
// stale freshness/mapping entries should not live for the renderer lifetime.
// Why: environment ids churn as paired runtimes reconnect; don't leak stale tracking for the renderer lifetime.
for (const environmentId of environmentIds) {
clearWebSessionTabsTrackingForEnvironment(environmentId)
}
@@ -2758,8 +2673,7 @@ export function useWebSessionTabsSync(): void {
beginWebRuntimeWakeTerminalRespawn(activeWorktreeId)
) {
requestedRespawnAfterWake = true
// Why: wake recovery must recreate the terminal without changing
// selected worktree to avoid re-triggering activation churn.
// Why: recreate the terminal without changing selected worktree to avoid re-triggering activation churn.
void createWebRuntimeSessionTerminal({
worktreeId: activeWorktreeId,
environmentId,
+106 -370
View File
@@ -42,17 +42,13 @@ import {
} from './agent-pane-authority'
import { createFreshnessScheduler } from './agent-status-freshness-scheduler'
/** Snapshot of a finished (or vanished) agent status entry, kept around so
* the dashboard + sidebar hover can continue showing the completion until the
* user acknowledges it by clicking the worktree. The `worktreeId` is stamped
* at retention time so we know where the row belongs even after the tab/pty
* it came from has gone away. */
/** Snapshot of a finished/vanished agent status entry, kept so the dashboard and sidebar hover
* keep showing the completion until the user clicks the worktree. `worktreeId` is stamped at
* retention time so the row's home is known even after its tab/pty is gone. */
export type RetainedAgentEntry = {
entry: AgentStatusEntry
worktreeId: string
/** Snapshot of the tab the agent lived in at retention time. We keep the
* full record (not just an id) because the tab may be gone from
* `tabsByWorktree` by the time the retained row is rendered. */
/** Snapshot of the tab at retention time; kept full (not just an id) because the tab may be gone from `tabsByWorktree` by render time. */
tab: TerminalTab
agentType: AgentType
startedAt: number
@@ -106,14 +102,11 @@ type AgentLaunchConfigRegistryEntry = {
}
export type AgentStatusSlice = {
/** Explicit agent status entries keyed by `${tabId}:${leafId}` composite.
* Real-time only — lives in renderer memory, not persisted to disk. */
/** Explicit agent status entries keyed by `${tabId}:${leafId}`; real-time only, not persisted. */
agentStatusByPaneKey: Record<string, AgentStatusEntry>
/** Main-synced dispatch metadata for live terminal panes that may only have
* title-derived status in the renderer. */
/** Main-synced dispatch metadata for live panes that may only have title-derived status in the renderer. */
runtimeAgentOrchestrationByPaneKey: Record<string, AgentStatusOrchestrationContext>
/** PTYs that still report legacy numeric pane keys but have registry-backed
* UUID pane proof. Stored separately from normal hook-reported status. */
/** PTYs still reporting legacy numeric pane keys but with registry-backed UUID proof; stored separately from normal hook-reported status. */
migrationUnsupportedByPtyId: Record<string, MigrationUnsupportedPtyEntry>
/** Monotonic tick that advances when agent-status freshness boundaries pass. */
agentStatusEpoch: number
@@ -123,27 +116,19 @@ export type AgentStatusSlice = {
/** Arm the shared freshness timer after an external mirror writes live rows. */
scheduleAgentStatusFreshness: () => void
/** Retained "done" entries — snapshots of agents that have disappeared from
* `agentStatusByPaneKey`. Keyed by paneKey so re-appearance of the same pane
* overwrites the snapshot. Shared between the dashboard and the sidebar
* agent-status hover so the two surfaces display identical rows. */
/** Retained "done" snapshots of agents gone from `agentStatusByPaneKey`, keyed by paneKey so pane re-appearance overwrites; shared by dashboard and sidebar hover. */
retainedAgentsByPaneKey: Record<string, RetainedAgentEntry>
/** Durable agent sessions captured when a workspace sleeps. These are not
* live status rows; they power the one-click CLI resume action on wake. */
/** Durable agent sessions captured on sleep (not live rows); power the one-click CLI resume on wake. */
sleepingAgentSessionsByPaneKey: Record<string, SleepingAgentSessionRecord>
/** Ephemeral launch snapshots keyed by concrete pane. Hook payloads do not
* carry Orca launch settings, so the renderer supplies them from startup. */
/** Ephemeral launch snapshots keyed by pane; hook payloads lack Orca launch settings, so the renderer supplies them from startup. */
agentLaunchConfigByPaneKey: Record<string, AgentLaunchConfigRegistryEntry>
/** Pane keys explicitly torn down (pane close, tab close, PTY exit, manual
* dismissal) and therefore forbidden from being re-retained on their next
* disappearance. Consumed by the retention sync as a one-shot suppressor. */
/** Pane keys explicitly torn down, forbidden from re-retention on next disappearance; a one-shot suppressor consumed by the retention sync. */
retentionSuppressedPaneKeys: Record<string, true>
/** Terminal tabs explicitly closed in this renderer session. Used only to
* drop late in-flight IPC statuses and stale main-cache replays. */
/** Terminal tabs explicitly closed this session; used to drop late in-flight IPC statuses and stale main-cache replays. */
recentlyClosedAgentStatusTabIds: Record<string, true>
/** Exact pane authorities retired while sibling panes in the tab stay live. */
@@ -211,56 +196,41 @@ export type AgentStatusSlice = {
/** Remove a single entry (e.g., when a pane's terminal exits). */
removeAgentStatus: (paneKey: string) => void
/** Remove all entries whose paneKey starts with the given prefix.
* Used when a tab is closed — same prefix-sweep as cacheTimerByKey cleanup. */
/** Remove all entries whose paneKey starts with the given prefix (tab close prefix-sweep). */
removeAgentStatusByTabPrefix: (tabIdPrefix: string) => void
/** Remove stale live rows while preserving pane launch and resume identity. */
clearTransientAgentStatuses: (connectionId: string, clearedAt: number) => void
/** Remove a single entry AND suppress re-retention on its next disappearance.
* Used for USER-INITIATED teardown — the dashboard/hover X button, and
* pane close — where the user is telling us "I'm done with this row". */
/** Remove a single entry AND suppress re-retention on its next disappearance (user-initiated teardown: X button, pane close). */
dropAgentStatus: (paneKey: string) => void
/** Remove all entries under a tab AND suppress re-retention for each.
* Used on tab close — the user is tearing down the whole tab, so any
* remaining agent rows (live or retained) must not reappear. */
/** Remove all entries under a tab AND suppress re-retention for each (tab close — no rows may reappear). */
dropAgentStatusByTabPrefix: (
tabIdPrefix: string,
opts?: DropAgentStatusByTabPrefixOptions
) => void
/** Remove one automatically hibernated completed-agent pane while preserving
* sibling live/retained rows in the same worktree. */
/** Remove one auto-hibernated completed-agent pane while preserving sibling live/retained rows in the same worktree. */
dropHibernatedAgentStatusPane: (
worktreeId: string,
paneKey: string,
opts?: DropHibernatedAgentPaneOptions
) => void
/** Remove all entries for a worktree AND suppress re-retention for live rows.
* Used on worktree sleep/remove — the whole worktree surface is folding, so
* retained rows must drop even if their original tab is no longer present.
*
* Live entries are swept by tab prefix and by main-stamped worktree
* attribution so worker rows that arrive before their tab exists do not
* survive sleep/remove. */
/** Remove all entries for a worktree AND suppress re-retention for live rows (worktree sleep/remove).
* Sweeps live rows by tab prefix and by main-stamped worktree attribution so worker rows that arrive before their tab don't survive. */
dropAgentStatusByWorktree: (worktreeId: string, opts?: DropAgentStatusByWorktreeOptions) => void
captureSleepingAgentSessionsByWorktree: (worktreeId: string, paneKeys?: string[]) => void
/** Capture resumable agent sessions across every worktree for crash recovery
* or a confirmed quit. The mode keeps live and quit precedence explicit. */
/** Capture resumable agent sessions across every worktree for crash recovery or quit; mode sets live/quit precedence. */
captureAllSleepingAgentSessions: (mode: AllAgentSessionCaptureMode) => void
clearSleepingAgentSession: (paneKey: string) => void
clearSleepingAgentSessionsByPaneKey: (paneKeys: readonly string[]) => void
clearSleepingAgentSessionsByWorktree: (worktreeId: string) => void
pruneSleepingAgentSessions: (validWorktreeIds: Set<string>) => void
/** Retain agent snapshots (called by the top-level retention sync effect).
* Accepts an array so multiple agents disappearing in the same frame
* produce a single set(...) — avoids intermediate states visible
* mid-loop to consumers. */
/** Retain agent snapshots. Accepts an array so simultaneous disappearances produce a single set() with no mid-loop intermediate states. */
retainAgents: (entries: RetainedAgentEntry[]) => void
/** Dismiss a retained entry by its paneKey. */
@@ -272,20 +242,11 @@ export type AgentStatusSlice = {
/** Prune retained entries whose worktreeId is not in the given set. */
pruneRetainedAgents: (validWorktreeIds: Set<string>) => void
/** Clear one-shot teardown suppressors after the retention sync observes
* that disappearance and decides not to retain the row. */
/** Clear one-shot teardown suppressors after the retention sync declines to retain the row. */
clearRetentionSuppressedPaneKeys: (paneKeys: string[]) => void
}
// Why: retainedAgentsByPaneKey snapshots a completed agent (a full
// AgentStatusEntry — up to ~24KB of prompt/message text — plus a TerminalTab)
// per ephemeral paneKey. paneKeys never recur, and the map is pruned only on
// worktree removal or manual dismissal, so a long-lived worktree in a busy
// multi-agent session grows it without bound — the dominant driver of the
// renderer JS-heap OOM. Cap by insertion order (== retention order), evicting
// the oldest completions first so the newest — the ones a user is most likely
// to still care about — always survive. Evicted rows just stop showing in the
// recently-completed overlay.
// Why: retained entries are heavy (~24KB) and grow unbounded on busy worktrees (dominant renderer OOM); cap, evicting oldest completions first.
const MAX_RETAINED_AGENTS = 500
function capRetainedAgents(
@@ -603,8 +564,8 @@ export function collectSleepingAgentSessionRecordsForWorktree(
const isManualWorktreeSleep = collectOptions.captureMode === 'manual-worktree-sleep'
const isCompletedAgentHibernation = collectOptions.captureMode === 'completed-agent-hibernation'
const isWorktreeOwnedCapture = isManualWorktreeSleep || isCompletedAgentHibernation
// Why: hibernated completions are intentional worktree-owned records; wake
// treats originless completed records as ambiguous legacy captures.
// Why: hibernated completions are intentional worktree-owned records; wake treats
// originless completed records as ambiguous legacy captures.
const origin: SleepingAgentSessionRecord['origin'] | undefined = isWorktreeOwnedCapture
? 'worktree-sleep'
: undefined
@@ -623,8 +584,8 @@ export function collectSleepingAgentSessionRecordsForWorktree(
) {
continue
}
// Why: Pi identity is resumable with no turn row and while idle after
// done; manual sleep must promote both instead of deleting the checkpoint.
// Why: Pi identity is resumable with no turn row and while idle after done, so manual
// sleep must promote both instead of deleting the checkpoint.
records[existing.paneKey] = {
...existing,
state: 'working',
@@ -721,9 +682,8 @@ export function collectHibernatedCompletionEvidenceForWorktree(
return retained
}
// Why: the periodic resume-record capture re-runs on an interval; comparing
// everything except capturedAt lets an unchanged agent skip the store write
// entirely, so idle ticks never dirty the session persistence pipeline.
// Why: comparing all fields except capturedAt lets an unchanged agent skip the store write,
// so periodic idle re-captures never dirty session persistence.
function sleepingRecordsEquivalentIgnoringCaptureTime(
existing: SleepingAgentSessionRecord | undefined,
next: SleepingAgentSessionRecord
@@ -872,8 +832,7 @@ function registryEntryMatchesStatus(args: {
identity.launchToken !== undefined &&
(args.launchToken === undefined || identity.launchToken !== args.launchToken)
) {
// Why: missing or mismatched launch tokens are stale launch proof even if a
// provider session id was reused by a later manual/mixed Codex run.
// Why: a missing/mismatched launch token is stale proof even if a later manual/mixed Codex run reused the provider session id.
return false
}
if (identity.providerSession !== undefined) {
@@ -933,16 +892,13 @@ function getLaunchConfigForEntry(
: undefined
}
// Why: the renderer twin of the main-process closedAgentStatusTabIds set that
// #7561 FIFO-capped. It suppresses late hook/status events for a just-closed tab,
// so it must outlive the tab briefly — but tabId is ephemeral and it was only
// ever added to, growing one entry per tab-close for the renderer's whole life.
// Why: renderer twin of main's #7561 FIFO-capped closedAgentStatusTabIds — suppresses late
// events for a just-closed tab, but was add-only and grew unbounded, hence this cap.
export const RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX = 1024
export const RECENTLY_RETIRED_AGENT_STATUS_PANE_KEYS_MAX = 1024
// delete-then-set for LRU recency, then evict the oldest keys past the cap (Record
// key order is insertion order for non-integer string keys). A status event for a
// tab closed >MAX tabs ago cannot still arrive, so eviction is safe.
// delete-then-set for LRU recency, then evict oldest keys past the cap (Record iterates
// insertion order); safe because a status for a tab closed >MAX tabs ago cannot still arrive.
function boundRecentlyClosedAgentStatusTabIds(
existing: Record<string, true>,
tabId: string
@@ -1099,19 +1055,13 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
set,
get
) => {
// Why: the freshness scheduler is intentionally process-lifetime-scoped —
// no dispose path — because it matches the store's own lifetime model
// (the zustand store is a module-level singleton that lives until process
// exit). Adding a teardown hook would require a store-dispose lifecycle
// that does not exist anywhere else in the codebase.
// Why: scheduler is process-lifetime-scoped (no dispose) because the store is a
// module-level singleton with no teardown lifecycle anywhere in the codebase.
const freshness = createFreshnessScheduler({
getEntries: () => Object.values(get().agentStatusByPaneKey),
bumpEpochs: () => {
// Why: freshness is time-based, not event-based. Advancing these epochs
// at the exact stale boundary forces all freshness-aware selectors to
// recompute — and re-sorts WorktreeList — even when no new PTY output
// arrives. sortEpoch must bump in lockstep with agentStatusEpoch because
// a stale transition can legitimately change worktree ordering.
// Why: freshness is time-based — bump both epochs at the stale boundary to force selector
// recompute and re-sort even with no new output, since staleness can change worktree ordering.
set((s) => ({
agentStatusEpoch: s.agentStatusEpoch + 1,
sortEpoch: s.sortEpoch + 1
@@ -1327,8 +1277,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
}
const nextEntry = { ...liveEntry, orchestration: merged }
nextLive[paneKey] = nextEntry
// Why: only replace titles when labels match the live dispatch
// taskId; sticky completed context must not rename a later turn.
// Why: only replace titles when labels match the live dispatch taskId; sticky completed context must not rename a later turn.
if (
(merged.displayName?.trim() || merged.taskTitle?.trim()) &&
orchestrationLabelsMatchLiveDispatch({
@@ -1524,8 +1473,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
agent,
providerSession,
prompt: '',
// Why: this is durable process/session identity, not visible turn
// state; a non-done value keeps cold restore eligible.
// Why: durable process/session identity, not visible turn state; a non-done value keeps cold restore eligible.
state: 'working',
capturedAt: updatedAt,
updatedAt,
@@ -1554,9 +1502,8 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
if (nextRetained !== s.retainedAgentsByPaneKey) {
delete nextRetained[paneKey]
}
// Why: on identity mismatch the sleeping record drops its launch config,
// so a stale registry entry must be cleared too or a later return to the
// old provider identity could reuse stale args/env. Mirror setAgentStatus.
// Why: on identity mismatch the sleeping record drops its launch config, so clear the stale
// registry entry too, else a later return to the old identity reuses stale args/env.
let nextLaunchConfigs = s.agentLaunchConfigByPaneKey
if (registryMatches && registryEntry) {
nextLaunchConfigs = {
@@ -1600,8 +1547,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
const updatedAt = timing?.updatedAt ?? Date.now()
if (
paneKey in get().recentlyRetiredAgentStatusPaneKeys ||
// Why: a closed terminal tab is no longer a valid destination for hook
// replays or late status events, even if main still receives them.
// Why: a closed tab is no longer a valid destination for hook replays or late status events.
isRecentlyClosedAgentStatusTab(
get().recentlyClosedAgentStatusTabIds,
getTabIdFromPaneKey(paneKey)
@@ -1614,24 +1560,17 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
const generatedTitleEntry: { current: AgentStatusEntry | null } = { current: null }
set((s) => {
const existing = s.agentStatusByPaneKey[paneKey]
// Why: snapshots and live pushes share receivedAt from the same main-side
// lastStatusByPaneKey.set, so equal timestamps carry identical data. Strict <
// preserves live-after-live updates that land in the same millisecond.
// Why: snapshots and live pushes share one timestamp source, so equal timestamps carry
// identical data; strict < preserves same-millisecond live-after-live updates.
if (existing && updatedAt < existing.updatedAt) {
return s
}
// Why: terminalTitle is identity-like — it labels the pane itself, not
// the current turn's activity. Preserve the prior value when a ping
// omits it so the pane label does not flicker out between hook events.
// Unlike the tool/prompt/assistant fields below (which legitimately
// clear on a fresh turn), a missing title means "no update", not "the
// pane has no title any more".
// Why: terminalTitle labels the pane itself, not the turn, so a missing title means "no update" —
// preserve the prior value to avoid flicker (unlike tool/prompt fields, which clear on a fresh turn).
const effectiveTitle = terminalTitle ?? existing?.terminalTitle
// Why: build up a rolling log of state transitions so the dashboard can
// render activity blocks showing what the agent has been doing. Only push
// when the state actually changes to avoid duplicate entries from prompt-
// only updates within the same state.
// Rolling log of state transitions for the dashboard's activity blocks; push only on
// real state changes to avoid dupes from prompt-only pings within the same state.
let history: AgentStateHistoryEntry[] = existing?.stateHistory ?? []
if (existing && existing.state !== payload.state) {
history = [
@@ -1639,13 +1578,9 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
{
state: existing.state,
prompt: existing.prompt,
// Why: use stateStartedAt (not updatedAt) so the history row
// reflects when the state was first reported, not the most
// recent within-state ping (tool/prompt updates refresh
// updatedAt but not stateStartedAt).
// Why: use stateStartedAt (not updatedAt) so the row reflects when the state was first reported, not the latest within-state ping.
startedAt: existing.stateStartedAt,
// Why: preserve the interrupt flag on the historical `done` entry
// so activity-block views can render past cancellations as such.
// Why: preserve the interrupt flag on the historical `done` entry so activity-block views can render past cancellations.
interrupted: existing.interrupted
}
]
@@ -1665,8 +1600,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
incoming: payload.agentType,
now: updatedAt
})
// Why: Command Code has no UserPromptSubmit; a fresh transcript prompt while
// still `working` is the smart-sort turn boundary.
// Why: Command Code has no UserPromptSubmit; a fresh transcript prompt while still `working` is the smart-sort turn boundary.
const commandCodeNewTurn =
existing !== undefined &&
isCommandCodeNewTurnWhileWorking({
@@ -1681,11 +1615,8 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
const promptInteractionKey =
payload.promptInteractionKey ??
(payload.prompt === existing?.prompt ? existing?.promptInteractionKey : undefined)
// Why: prefer main's authoritative stateStartedAt when provided — main's
// attachStatusTiming preserves it across same-state pings (server.ts) and
// persists it across restart. Fall back to existing.stateStartedAt only when
// main did not send timing (legacy callers / OSC fallback path), and to
// updatedAt for a brand-new pane.
// Why: prefer main's authoritative stateStartedAt (attachStatusTiming persists it across
// same-state pings and restart); fall back to existing only when main sent no timing, updatedAt for a new pane.
const stateStartedAt =
timing?.stateStartedAt ??
(commandCodeNewTurn
@@ -1704,11 +1635,8 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
return s
}
// Why: tool/assistant fields come pre-merged from the main-process
// cache (see `resolveToolState` in server.ts), so the payload always
// carries the authoritative current snapshot — including clears on a
// fresh turn. Writing through directly (no existing fallback) is what
// lets a `UserPromptSubmit` reset clear stale tool lines in the UI.
// Why: tool/assistant fields arrive pre-merged and authoritative from main (resolveToolState
// in server.ts), so write them through directly — no fallback — so UserPromptSubmit clears stale tool lines.
const runtimeOrchestration = s.runtimeAgentOrchestrationByPaneKey[paneKey]
const runtimeMergedOrchestration = runtimeOrchestration
? mergeCurrentOrchestrationContext(existing?.orchestration, runtimeOrchestration)
@@ -1775,9 +1703,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
)
? existingSleepingRecord.launchConfig
: undefined
// Why: pane keys can be reused after a manually-started agent replaces
// an Orca-launched one. Once the provider session changes, the old
// pane-key launch registry must not bleed options into the new session.
// Why: on a reused pane key, once the provider session changes the old launch registry must not bleed options into the new session.
const launchConfigSource =
(payload.state !== 'done' && !providerSessionChanged && metadata?.launchToken
? metadata?.launchConfig
@@ -1807,27 +1733,20 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
stateHistory: history,
toolName: payload.toolName,
toolInput: payload.toolInput,
// Why: full untruncated AskUserQuestion JSON; carried so mobile/web
// clients can render the live prompt card. parseAgentStatusPayload
// already clears it when the agent moves to a different tool/state.
// Why: full untruncated AskUserQuestion JSON so mobile/web can render the live prompt
// card; parseAgentStatusPayload clears it on tool/state change.
interactivePrompt: payload.interactivePrompt,
lastAssistantMessage: payload.lastAssistantMessage,
// Why: reused panes may start non-orchestrated work after runtime
// metadata expires. Only final done rows keep the previous lineage
// fallback so completed children stay grouped.
// Why: reused panes can start non-orchestrated work; only final done rows keep the
// previous lineage fallback so completed children stay grouped.
orchestration,
// Why: reuse the previous array reference when the roster is
// unchanged so subscribers comparing by identity skip re-renders on
// high-frequency same-roster pings.
// Why: reuse the prior array ref when the roster is unchanged so identity-comparing subscribers skip re-renders.
subagents: agentSubagentsEqual(existing?.subagents, payload.subagents)
? existing?.subagents
: payload.subagents,
...(providerSession ? { providerSession } : {}),
...(promptInteractionKey ? { promptInteractionKey } : {}),
// Why: interrupted lives on `done` only. parseAgentStatusPayload
// already clamps it to `undefined` for non-done states, so writing
// the field through directly preserves truth for done and resets
// it when a new turn starts (working → Stop reprices it).
// Why: `interrupted` is done-only; parseAgentStatusPayload already clamps it for non-done states, so write it through directly.
interrupted: payload.interrupted
}
generatedTitleEntry.current = entry
@@ -1838,37 +1757,16 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
) {
completionRefreshWorktreeId = entry.worktreeId ?? findAgentPaneWorktreeId(s, paneKey)
}
// Why: broad freshness-aware subscribers only need a global tick when
// an entry appears, changes state, crosses stale->fresh, or receives
// a same-state `done` update that may carry the final assistant
// message for retained rows. Same-state working prompt/tool pings
// still update agentStatusByPaneKey for the owning row, but they must
// not fan out through dashboard/sidebar aggregate work across every
// card. Sort-relevant inputs are:
// 1. `state` transitions — smart-sort class is a function of state.
// 2. Freshness transitions (stale → fresh) — `resolveAttention` in
// smart-attention.ts filters entries through
// `isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)`
// (30-min TTL). A stale entry that refreshes with the SAME state
// goes from "not contributing" (Class 4) to driving a higher
// class — order must update. Snapshot hydration can pass an older
// updatedAt; in that case the entry is still stored with its true
// age, and selectors will immediately decay it if it is already
// stale.
// Why: emit a global tick only when an entry appears, changes state, crosses stale→fresh,
// or is a same-state `done` update — same-state working pings must not fan out to aggregates.
const wasFresh =
!!existing && isExplicitAgentStatusFresh(existing, updatedAt, AGENT_STATUS_STALE_AFTER_MS)
// Why attribution is aggregate state: a late main-process stamp can
// change which workspace remains visible without changing agent state.
// Why: a late main-process attribution stamp can change which workspace stays visible without changing agent state.
const attributionChanged =
existing?.worktreeId !== entry.worktreeId || existing?.tabId !== entry.tabId
// Why: main is authoritative on stateStartedAt and only advances it on a
// real turn boundary (state transition or a Command Code new turn). If the
// renderer-local `commandCodeNewTurn` misses it — e.g. a transcript-read
// failure left `existing.promptInteractionKey` undefined so the key-change
// is invisible here — main's reset still arrives via `timing.stateStartedAt`.
// Treat a same-state stateStartedAt advance as sort-relevant so smart sort
// never goes stale. Non-Command-Code agents never advance stateStartedAt
// while the state is unchanged, so this stays effectively CC-scoped.
// Why: main can advance stateStartedAt on a same-state turn boundary the renderer
// missed; treat that as sort-relevant so smart sort never goes stale.
// Non-Command-Code agents never advance stateStartedAt at a fixed state, so this stays CC-scoped.
const sameStateStateStartedAtChanged =
!!existing &&
existing.state === payload.state &&
@@ -1897,22 +1795,15 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
entry.interrupted !== existing.interrupted)
const retentionRelevantChange =
sortRelevantChange || attributionChanged || doneRetentionFieldsChanged
// Why: a new status event means the agent is live again — lift any
// one-shot retention suppressor so the row can be retained normally
// on its next disappearance. setAgentStatus fires on every PTY status
// update (high frequency), so only clone retentionSuppressedPaneKeys
// when there is actually a suppressor to remove — otherwise every
// status ping would churn that map reference and force spurious
// re-renders in any subscriber selecting on it.
// Why: a fresh status means the agent is live again — lift its one-shot retention suppressor.
// Clone the map only when a suppressor exists, else every high-frequency ping churns the ref.
const hasSuppressor = paneKey in s.retentionSuppressedPaneKeys
let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys
if (hasSuppressor) {
nextRetentionSuppressedPaneKeys = { ...s.retentionSuppressedPaneKeys }
delete nextRetentionSuppressedPaneKeys[paneKey]
}
// Why: pane keys are reused by the same terminal pane across turns.
// Once a fresh live hook row arrives, any retained snapshot for that
// pane is stale and must not render beside the live row in the sidebar.
// Why: pane keys are reused across turns, so a fresh live row makes any retained snapshot stale — drop it so it doesn't render beside the live row.
const hasRetainedSnapshot = paneKey in s.retainedAgentsByPaneKey
const nextRetainedAgents = hasRetainedSnapshot
? { ...s.retainedAgentsByPaneKey }
@@ -1931,8 +1822,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
const liveRecoveryRecord = liveRecoveryWorktreeId
? sleepingRecordFromEntry({
state: s,
// Why: a completed Pi turn leaves the TUI session alive. Keep
// resume identity active without representing done as pending work.
// Why: a completed Pi turn leaves the TUI session alive — keep resume identity active without representing done as pending work.
entry: retainsPiRecoveryIdentity
? { ...entry, state: 'working', prompt: '', lastAssistantMessage: undefined }
: entry,
@@ -1965,8 +1855,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
}
}
}
// Why: launch tokens can remain in a shell after an Orca-started TUI exits;
// once the original session is done they must no longer authorize config reuse.
// Why: launch tokens can outlive an Orca-started TUI in the shell; once the session is done they must no longer authorize config reuse.
if (
(providerSessionChanged || entry.state === 'done') &&
paneKey in s.agentLaunchConfigByPaneKey
@@ -2005,10 +1894,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
}
const entryForGeneratedTitle = generatedTitleEntry.current
if (entryForGeneratedTitle) {
// Why: sticky orchestration (~30m) can outlive the dispatch turn.
// - Matching labels: replace so displayName upgrades the task preview.
// - Mismatched sticky taskId on a new dispatch preamble: replace so the
// prior task's title does not stick across re-dispatch on the same pane.
// Why: sticky orchestration (~30m) can outlive the dispatch turn, so replace the title on matching labels or a re-dispatch's mismatched taskId.
const hasMatchingOrchestrationLabels = Boolean(
(entryForGeneratedTitle.orchestration?.displayName?.trim() ||
entryForGeneratedTitle.orchestration?.taskTitle?.trim()) &&
@@ -2027,8 +1913,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
)
const shouldReplaceGeneratedTitle =
hasMatchingOrchestrationLabels || isNewDispatchAgainstStickyOrchestration
// Why: setAgentStatus is high-frequency. Only parse dispatch preambles when
// a title write is still possible (feature on + replace or first-write).
// Why: setAgentStatus is high-frequency, so only parse dispatch preambles when a title write is actually possible.
const mayWriteGeneratedTitle =
get().settings?.tabAutoGenerateTitle === true &&
(shouldReplaceGeneratedTitle ||
@@ -2049,13 +1934,11 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
get().setGeneratedTabTitleFromAgentPrompt(paneKey, generatedTitlePrompt)
}
}
// Why: schedule after set completes so the timer reads the updated map.
// queueMicrotask avoids re-entry into the zustand store during set.
// Why: schedule via queueMicrotask after set so the timer reads the updated map without re-entering the store during set.
queueMicrotask(() => freshness.schedule())
if (completionRefreshWorktreeId) {
const worktreeId = completionRefreshWorktreeId
// Why: agents can create a PR via `gh pr create`, bypassing Orca's
// create-PR flow and leaving a fresh "no PR" cache entry in place.
// Why: agents can create a PR via `gh pr create`, bypassing Orca's flow and leaving a stale "no PR" cache entry in place.
queueMicrotask(() => get().refreshGitHubForWorktreeIfStale(worktreeId))
}
},
@@ -2117,19 +2000,13 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
s.migrationUnsupportedByPtyId,
(entry) => entry.paneKey === paneKey
)
// Why: acknowledgedAgentsByPaneKey is written per user-ack but owned
// lifecycle-wise by the pane — drop the ack entry in lockstep with the
// live-map entry so closed panes don't leave stale ack timestamps that
// could silently suppress "unvisited" signals on future paneKey
// collisions.
// Why: drop the ack entry with the pane so a future paneKey collision can't inherit a stale ack that suppresses "unvisited" signals.
let nextAck = s.acknowledgedAgentsByPaneKey
if (paneKey in nextAck) {
nextAck = { ...nextAck }
delete nextAck[paneKey]
}
// Why: bump sortEpoch in lockstep with agentStatusEpoch — removing an
// agent can legitimately change worktree sort order, same rationale
// as setAgentStatus.
// Why: bump sortEpoch with agentStatusEpoch — removing an agent can change worktree sort order (same as setAgentStatus).
return {
agentStatusByPaneKey: next,
agentLaunchConfigByPaneKey: nextLaunchConfigs,
@@ -2179,10 +2056,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
delete nextAck[k]
}
}
// Why: bump sortEpoch in lockstep with agentStatusEpoch — removing
// agents can legitimately change worktree sort order, same rationale
// as setAgentStatus. The pre-check guards against spurious bumps when
// no keys matched the prefix.
// Why: bump sortEpoch with agentStatusEpoch — removing agents can change worktree sort order (same as setAgentStatus).
return {
agentStatusByPaneKey: next,
agentLaunchConfigByPaneKey: nextLaunchConfigs,
@@ -2205,8 +2079,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
set((s) => {
let next: Record<string, AgentStatusEntry> | null = null
for (const [paneKey, existing] of Object.entries(s.agentStatusByPaneKey)) {
// Why: undefined is an unstamped legacy/renderer-owned row. Its host
// cannot be proven, so normal pane teardown remains its safe cleanup.
// Why: undefined connectionId is an unstamped legacy/renderer-owned row whose host can't be proven, so leave it to normal pane teardown.
if (existing.connectionId !== connectionId || existing.updatedAt > clearedAt) {
continue
}
@@ -2239,10 +2112,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
},
dropAgentStatus: (paneKey) => {
// Why: single sync read — zustand set is synchronous, so the value we
// observe inside the set callback is the same one we would re-read via
// get() immediately after. Capture it once from inside the callback
// rather than double-reading the store before and during set.
// Why: zustand set is synchronous, so capture liveExisted once inside the callback instead of double-reading the store.
let liveExisted = false
set((s) => {
const hasLive = paneKey in s.agentStatusByPaneKey
@@ -2252,9 +2122,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
s.migrationUnsupportedByPtyId,
(entry) => entry.paneKey === paneKey
)
// See removeAgentStatus for rationale on ack cleanup. Apply this
// regardless of live/retained presence — the ack entry is owned by
// the pane lifecycle independently of live/retained state.
// See removeAgentStatus for ack-cleanup rationale; the ack entry is owned by the pane lifecycle regardless of live/retained state.
let nextAck = s.acknowledgedAgentsByPaneKey
if (paneKey in nextAck) {
nextAck = { ...nextAck }
@@ -2267,13 +2135,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
if (hasLaunchConfig) {
delete nextLaunchConfigs[paneKey]
}
// Why: bail when there is genuinely nothing to do. The old guard
// `!hasLive && !hasRetained && alreadySuppressed` leaked a phantom
// suppressor write in the `!hasLive && !hasRetained && !alreadySuppressed`
// case. With the hasLive-gated suppressor below, a no-op drop on a
// paneKey with no live and no retained entry truly has nothing to
// change, so short-circuit here — but still flush a pending ack
// cleanup or launch-config cleanup if one is present.
// Why: short-circuit when there's nothing to change, but still flush a pending ack or launch-config cleanup if one is present.
if (!hasLive && !hasRetained && !migrationUnsupported.changed) {
if (hasLaunchConfig) {
return {
@@ -2300,34 +2162,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
delete nextRetained[paneKey]
}
// Why: explicit teardown means "the user is done with this row", so
// the next retention sync must not resurrect it from the previous frame.
//
// Why same-frame race is acceptable: if dropAgentStatus fires in the
// same React frame as setAgentStatus, before useRetainedAgentsSync's
// prevAgentsRef has captured the live entry, the planted suppressor
// may never be consumed by a live→gone transition and would persist.
// In practice suppressors are bounded by user-dismissed paneKeys (a
// small set), so the leak is pragmatically inert — accepting it is
// cheaper than threading frame-level ordering guarantees through the
// retention sync.
//
// Why gate on hasLive: the suppressor is a one-shot flag consumed by
// `collectRetainedAgentsOnDisappear` (useRetainedAgents.ts), which
// iterates the PREVIOUS render's LIVE agents to decide what to
// retain. If we dismiss a retained-only row (no live entry at drop
// time), no live→gone transition will ever fire for this paneKey, so
// the suppressor would never be consumed and would leak indefinitely
// — only clearing if the same paneKey later became live again via
// setAgentStatus. A retained-only dismissal just needs the retained
// entry removed; there is no live-agent resurrection risk to guard
// against. Only spread retentionSuppressedPaneKeys when hasLive.
//
// Why the `!(paneKey in s.retentionSuppressedPaneKeys)` check: if a
// suppressor is already present, re-spreading produces a new object
// reference with identical contents and spuriously re-renders any
// subscriber selecting on retentionSuppressedPaneKeys. Mirror the
// guard used in setAgentStatus.
// Why: explicit teardown must not let retention sync resurrect this row — plant a one-shot suppressor, but only when hasLive (a retained-only key has no live→gone transition to consume it, so it leaks) and not already present (re-spreading spuriously re-renders subscribers).
const needsSuppressorWrite = hasLive && !(paneKey in s.retentionSuppressedPaneKeys)
return {
@@ -2348,28 +2183,16 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
: {}),
agentStatusEpoch:
hasLive || migrationUnsupported.changed ? s.agentStatusEpoch + 1 : s.agentStatusEpoch,
// Why: mirrors removeAgentStatus — dropping a live working/blocked
// agent changes its contribution to the worktree sort score, so the
// sidebar smart-sort must recompute. Without this bump, a user-
// initiated dismissal from the inline agents list would leave the
// sidebar ordering stale until some unrelated event repaired it.
// Why: mirrors removeAgentStatus — dropping a live agent changes its worktree sort score, so bump sortEpoch to recompute the sidebar smart-sort.
sortEpoch: hasLive || migrationUnsupported.changed ? s.sortEpoch + 1 : s.sortEpoch
}
})
// Why: freshness.schedule only matters when the live map changed —
// retained-only and no-op drops don't touch it. Gate on the live
// presence observed inside set() so a noop drop on a paneKey with no
// live and no retained entry (or a retained-only dismissal) skips the
// microtask.
// Why: freshness.schedule only matters when the live map changed, so gate on the live presence observed inside set() — no-op/retained-only drops skip it.
if (liveExisted) {
queueMicrotask(() => freshness.schedule())
}
// Why: propagate the dismissal to the main-process hook cache so the
// on-disk last-status file evicts this paneKey on the next debounced
// write. Without this, the main process would re-hydrate the dismissed
// entry on the next launch and the row would re-appear. Fire-and-forget.
// Why: the typeof window guard keeps the slice usable from the
// node test environment, where window is undefined.
// Why: propagate the dismissal to the main-process hook cache so the on-disk cache doesn't re-hydrate this row on next launch. Fire-and-forget.
// Why: the typeof window guard keeps the slice usable from the node test env, where window is undefined.
if (typeof window !== 'undefined') {
window.api?.agentStatus?.drop?.(paneKey)
}
@@ -2400,9 +2223,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
s.migrationUnsupportedByPtyId,
(entry) => entry.paneKey?.startsWith(prefix) ?? false
)
// See removeAgentStatus for rationale on ack cleanup. Apply this
// regardless of live/retained presence — ack entries are owned by
// the pane lifecycle independently of live/retained state.
// See removeAgentStatus for ack-cleanup rationale; ack entries are owned by the pane lifecycle regardless of live/retained state.
let nextAck = s.acknowledgedAgentsByPaneKey
const ackKeys = Object.keys(nextAck).filter(
(k) => k.startsWith(prefix) || completedOrphanKeySet.has(k)
@@ -2461,24 +2282,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
delete nextRetained[key]
}
// Why: plant suppressors only for paneKeys that had a live entry,
// mirroring the hasLive gate in dropAgentStatus — suppressors are
// one-shot flags consumed by collectRetainedAgentsOnDisappear on a
// live→gone transition, so a suppressor on a retained-only paneKey
// would leak because no such transition will ever fire. Also skip
// keys that are already suppressed so we don't spuriously reallocate
// the suppressor map for subscribers that select on its identity.
//
// Same-frame race: if a hook ping promotes working→done in the same
// render frame as teardown, the next retention-sync run sees the entry
// as `done` in prevAgents and surfaces it in retained — even though
// the user just tore it down. Planting suppressors is the cheap guard
// for the common ordering; the rare inverse ordering has the same
// bounded suppressor-leak tradeoff described in dropAgentStatus.
//
// Skip completed-orphan keys: their tab is already gone, so retention
// sync never snapshots them and no live→gone transition ever fires to
// consume the suppressor — planting one would leak permanently.
// Why: a suppressor is only consumed on a live→gone transition, so plant one only for live paneKeys and skip already-suppressed and completed-orphan keys — otherwise it leaks (mirrors dropAgentStatus).
const suppressorAdds = liveKeys.filter(
(k) => !completedOrphanKeySet.has(k) && !(k in s.retentionSuppressedPaneKeys)
)
@@ -2501,9 +2305,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
...(nextAck !== s.acknowledgedAgentsByPaneKey
? { acknowledgedAgentsByPaneKey: nextAck }
: {}),
// Why: mirrors removeAgentStatusByTabPrefix — only bump the live-map
// epoch / sortEpoch when the live map actually changed. Retained-only
// sweeps do not participate in smart-sort or freshness calculations.
// Why: mirrors removeAgentStatusByTabPrefix — only bump epochs when the live map changed; retained-only sweeps don't affect sort/freshness.
agentStatusEpoch:
hadLive || migrationUnsupported.changed ? s.agentStatusEpoch + 1 : s.agentStatusEpoch,
sortEpoch: hadLive || migrationUnsupported.changed ? s.sortEpoch + 1 : s.sortEpoch
@@ -2680,10 +2482,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
}
}
const retainedEvidenceKeys = new Set(retainedEvidence.keys())
// See removeAgentStatus for rationale on ack cleanup. Current tabs are
// swept by prefix; attributed live rows and orphan retained rows are
// swept by their retained/lifecycle key. Auto-hibernated completion
// evidence keeps its read state so a slept card does not turn bold again.
// See removeAgentStatus for ack-cleanup rationale; auto-hibernated completion evidence keeps its read state so a slept card doesn't turn bold again.
let nextAck = s.acknowledgedAgentsByPaneKey
const ackKeys = Object.keys(nextAck).filter(
(k) =>
@@ -2698,10 +2497,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
delete nextAck[key]
}
}
// Mirror dropAgentStatusByTabPrefix: when nothing live or retained
// changed, narrow the return to just the ack delta (or s) so we don't
// emit a new top-level state object that re-renders full-state
// subscribers for nothing.
// Mirror dropAgentStatusByTabPrefix: when nothing live/retained changed, return just the ack delta (or s) to avoid full-state re-renders.
if (
liveKeys.length === 0 &&
launchConfigKeys.length === 0 &&
@@ -2744,10 +2540,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
}
}
// Why: normal worktree teardown folds the surface, so live rows need
// suppressors. Auto-hibernated `done` rows become retained evidence
// immediately, so suppressing those same pane keys would erase them on
// the next retention sync.
// Why: suppress live rows on teardown, but skip auto-hibernated `done` rows — they become retained evidence a suppressor would erase next sync.
const suppressorAdds = liveKeys.filter(
(k) => !retainedEvidenceKeys.has(k) && !(k in s.retentionSuppressedPaneKeys)
)
@@ -2804,8 +2597,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
},
captureAllSleepingAgentSessions: (mode) => {
// Why: both periodic crash checkpoints and quit flushes persist live
// provider ids, but only a confirmed quit may claim quit precedence.
// Why: periodic checkpoints and quit flushes both persist provider ids, but only a confirmed quit may claim quit precedence.
set((s) => {
const capturedAt = Date.now()
const origin = mode === 'quit' ? ('quit' as const) : ('live' as const)
@@ -2842,8 +2634,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
origin
})
const existing = next[entry.paneKey]
// Why: a timer racing confirmed window close must not downgrade its
// shutdown snapshot; a new live hook event supersedes it elsewhere.
// Why: a periodic timer must not downgrade a confirmed-quit shutdown snapshot; a live hook event supersedes it elsewhere.
if (
mode === 'periodic' &&
existing?.origin === 'quit' &&
@@ -2923,20 +2714,12 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
},
retainAgents: (entries) => {
// Why: retained entries are a pure read-overlay — consumers read
// retainedAgentsByPaneKey directly each render, so no sort/status epoch
// bump is needed. Retention does not participate in sort ordering.
// Batching into a single set(...) keeps multi-agent disappearance atomic.
// Why: retained entries are a pure read-overlay (no epoch bump needed); batch into one set so multi-agent disappearance is atomic.
if (entries.length === 0) {
return
}
set((s) => {
// Why: skip the allocation + set(...) entirely when every input entry
// is already present by reference. Consumers of retainedAgentsByPaneKey
// select on its identity (the inline agents list), so a spurious map
// reallocation forces re-renders even when nothing changed. Mirrors
// the identity-preservation pattern used by pruneRetainedAgents and
// clearRetentionSuppressedPaneKeys.
// Why: skip reallocation when every entry is already present by reference — consumers select on map identity, so a spurious realloc forces re-renders.
let changed = false
for (const retained of entries) {
if (s.retainedAgentsByPaneKey[retained.entry.paneKey] !== retained) {
@@ -2957,51 +2740,24 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
mergedOrchestration !== retained.entry.orchestration
? { ...retained.entry, orchestration: mergedOrchestration }
: retained.entry
// Why: INVARIANT — the map key equals retained.entry.paneKey. This
// lets callers look up a retained row by the same paneKey they use
// for agentStatusByPaneKey and keeps dismissal (dismissRetainedAgent)
// keyed on a single identifier. collectRetainedAgentsOnDisappear
// relies on this invariant too: it checks
// `retainedAgentsByPaneKey[paneKey]` to decide whether a vanished
// agent is already retained.
// INVARIANT: map key equals retained.entry.paneKey, so callers look up retained rows by the same paneKey as agentStatusByPaneKey.
next[retained.entry.paneKey] =
entry === retained.entry ? retained : { ...retained, entry }
}
// Why: bound the map so a long multi-agent session cannot leak the
// renderer heap. retainAgents is the only path that grows it, so
// capping here is sufficient; evicts oldest-retained first.
// Why: cap the map so a long multi-agent session can't leak the renderer heap (retainAgents is the only growth path); evicts oldest-retained first.
return { retainedAgentsByPaneKey: capRetainedAgents(next) }
})
},
dismissRetainedAgent: (paneKey) => {
// Why: no agentStatusEpoch / sortEpoch bump here (mirrors retainAgents).
// Retained rows are a pure read-overlay on top of agentStatusByPaneKey —
// they do not contribute to smart-sort class resolution (see
// resolveAttention in smart-attention.ts, which reads
// agentStatusByPaneKey only) and dashboard
// selectors re-render on retainedAgentsByPaneKey identity changes
// directly. Bumping epochs would force sidebar re-sorts and selector
// recomputations for a change that cannot affect either result.
// Why: no epoch bump (mirrors retainAgents) — retained rows are a pure read-overlay that don't affect smart-sort; selectors re-render on map identity.
set((s) => {
if (!(paneKey in s.retainedAgentsByPaneKey)) {
return s
}
const next = { ...s.retainedAgentsByPaneKey }
delete next[paneKey]
// Why: mirror dropAgentStatus's hasLive-gated suppressor. If the same
// paneKey has BOTH a retained entry AND a concurrent live entry, simply
// removing the retained row leaves the live entry free to vanish
// cleanly on its next disappearance — and because
// collectRetainedAgentsOnDisappear (useRetainedAgents.ts) only skips
// paneKeys that are currently in retainedAgentsByPaneKey, the
// just-dismissed row would be resurrected by a new retention snapshot.
// Plant a one-shot suppressor so the next live→gone transition for
// this paneKey is ignored by the retention sync.
//
// Gate on `paneKey in agentStatusByPaneKey`: with no live entry there
// is no live→gone transition to guard against, and a stray suppressor
// would leak indefinitely (same rationale as dropAgentStatus).
// Why: mirror dropAgentStatus — plant a one-shot suppressor only when a live entry coexists, so the retention sync doesn't resurrect this dismissed row (gate on hasLive, else it leaks).
const hasLive = paneKey in s.agentStatusByPaneKey
if (!hasLive || paneKey in s.retentionSuppressedPaneKeys) {
return { retainedAgentsByPaneKey: next }
@@ -3017,27 +2773,12 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
},
dismissRetainedAgentsByWorktree: (worktreeId) => {
// Why: collect inside set so we capture the exact paneKeys removed
// (worktree filter is applied here). After the synchronous set()
// returns, fan out a window.api.agentStatus.drop per removed key so
// the main-process hook cache (and on-disk last-status file) eviction
// matches the renderer's removal. Without this, the on-disk cache
// would resurrect the dismissed rows on the next launch.
// Why: collect removed paneKeys inside set, then fan out window.api drop so the on-disk cache doesn't resurrect the dismissed rows on next launch.
const dismissedPaneKeys: string[] = []
set((s) => {
let changed = false
const next: Record<string, RetainedAgentEntry> = {}
// Why: mirror dismissRetainedAgent's hasLive-gated suppressor logic.
// When a dismissed paneKey ALSO has a concurrent live entry in
// agentStatusByPaneKey, removing the retained row alone lets the next
// live→gone transition for that paneKey re-retain the row via the
// retention sync (collectRetainedAgentsOnDisappear only skips paneKeys
// currently present in retainedAgentsByPaneKey). Without planting a
// suppressor here, "Dismiss all" for a worktree would silently
// resurrect the just-dismissed rows as soon as the live agents
// disappeared. Only plant suppressors for the hasLive subset — a stray
// suppressor on a retained-only paneKey would leak indefinitely
// because no live→gone transition would ever consume it.
// Why: mirror dismissRetainedAgent — plant a suppressor only for dismissed paneKeys that also have a live entry, else the next live→gone transition re-retains the row (a retained-only suppressor leaks).
const toSuppress: string[] = []
for (const [key, ra] of Object.entries(s.retainedAgentsByPaneKey)) {
if (ra.worktreeId === worktreeId) {
@@ -3073,12 +2814,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
},
pruneRetainedAgents: (validWorktreeIds) => {
// Why: deliberately does NOT sweep retentionSuppressedPaneKeys for
// pruned worktrees. PaneKeys are minted fresh when a worktree is
// re-created (worktrees keep unique tab IDs), so stale suppressors
// keyed on pruned paneKeys can never be matched by a future live entry
// — they are inert and harmless. Sweeping them would add churn for no
// observable benefit.
// Why: intentionally leaves retentionSuppressedPaneKeys — paneKeys are minted fresh on worktree re-create, so stale suppressors can never match a future live entry.
set((s) => {
let changed = false
const next: Record<string, RetainedAgentEntry> = {}
+28 -96
View File
@@ -61,15 +61,9 @@ type CreateBrowserTabOptions = {
title?: string
sessionProfileId?: string | null
sessionPartition?: string | null
// Why: callers like "Open Preview to the Side" need to place the new browser
// tab in a specific (sibling or newly-split) group rather than the ambient
// active group. Defaults to the worktree's current active group.
// Place the new tab in a specific group (e.g. "Open Preview to the Side"); defaults to the worktree's active group.
targetGroupId?: string
// Why: the explicit "New Tab" action (keyboard shortcut, + button) should
// land the user in the address bar even when their configured home page is a
// real URL, so they can type a destination immediately. Link-opened tabs
// (context menu, window.open, http link routing) leave this unset so focus
// stays on the webview. When omitted, we fall back to the blank-URL check.
// Explicit "New Tab" focuses the address bar even with a real home URL; link-opened tabs leave it unset.
focusAddressBar?: boolean
browserRuntimeEnvironmentId?: string | null
}
@@ -103,8 +97,7 @@ function sanitizeBrowserPageAnnotation(annotation: BrowserPageAnnotation): Brows
: annotation.comment,
payload: {
...annotation.payload,
// Why: annotations live in persisted renderer state; screenshots are
// transient copy payloads and can retain megabytes per note.
// Why: annotations persist to disk; null the transient screenshot to avoid retaining megabytes per note.
screenshot: null
}
}
@@ -145,14 +138,7 @@ export type BrowserSlice = {
closeBrowserPage: (pageId: string) => void
reopenClosedBrowserPage: (workspaceId: string) => BrowserPage | null
setActiveBrowserPage: (workspaceId: string, pageId: string) => void
// Why: scoped sibling of setActiveBrowserTab+setActiveBrowserPage that
// never yanks the user across worktrees. Multiple agents can drive
// browsers in parallel worktrees; a global focus call from agent X would
// steal the screen from the user reading agent Y. Updates per-worktree
// active tab/page unconditionally; updates the GLOBAL active tab and (if
// surfacePane) global activeTabType only when worktreeId === active
// worktree. Cross-worktree calls pre-stage the targeted worktree's view
// for whenever the user next switches to it.
// Focus that never yanks the user across worktrees: per-worktree slots always update, globals only when targeting the active worktree.
focusBrowserTabInWorktree: (
worktreeId: string,
browserPageId: string,
@@ -231,10 +217,7 @@ function normalizeUrl(url: string): string {
if (trimmed.length === 0) {
return 'about:blank'
}
// Why: setBrowserPageUrl is the single sink for URL updates from did-navigate,
// CDP navigation-update IPC, and direct address-bar submits. Redact at this
// boundary so the Kagi bearer token cannot reach BrowserPage.url, which is
// persisted to disk via the workspace session writer.
// Why: redact at this single URL sink so the Kagi bearer token can't reach BrowserPage.url, which is persisted to disk.
return redactKagiSessionToken(trimmed)
}
@@ -246,10 +229,7 @@ function normalizeBrowserTitle(title: string | null | undefined, url: string): s
title === ORCA_BROWSER_BLANK_URL ||
!title
) {
// Why: blank pages render through Orca's inert data: URL guest. Persisting
// that internal bootstrap URL as the page/workspace title leaks an
// implementation detail into the tab strip and makes every blank page look
// broken. Keep the user-facing label stable as "New Tab" instead.
// Why: don't surface the internal blank-guest URL as a title (leaks an impl detail, looks broken); show "New Tab" instead.
return 'New Tab'
}
return title
@@ -324,9 +304,7 @@ function buildBrowserPage(
worktreeId,
url: normalizedUrl,
title: normalizeBrowserTitle(title, normalizedUrl),
// Why: blank pages mount an inert guest first. Treating them as loading
// would make an empty workspace flash the global loading affordance even
// though no real navigation happened yet.
// Why: blank pages mount an inert guest (no real navigation); marking them loading would flash the loading affordance.
loading: normalizedUrl !== 'about:blank' && normalizedUrl !== ORCA_BROWSER_BLANK_URL,
faviconUrl: null,
canGoBack: false,
@@ -514,9 +492,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
options?.title,
options?.browserRuntimeEnvironmentId
)
// Why: when no explicit profile is passed, inherit the user's chosen default
// profile. This lets users set a preferred profile in Settings that all new
// browser tabs use automatically.
// Why: with no explicit profile, inherit the user's default so a Settings preference applies to new tabs.
const sessionProfileId =
options?.sessionProfileId !== undefined
? options.sessionProfileId
@@ -639,10 +615,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
return
}
} catch (error) {
// Why: a remote-owned workspace must NOT silently fall back to a local
// desktop browser tab — that creates confusing split ownership. Headless
// remotes that support browser panes advertise browser.headless.v1 and
// succeed above; if creation fails, surface it instead of going local.
// Why: browser.headless.v1 remotes succeed above, so a failure here is real; surface it instead of a confusing local-tab fallback (split ownership).
console.warn(
'[browser] remote browser tab creation failed:',
error instanceof Error ? error.message : String(error)
@@ -798,10 +771,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
shutdownWorktreeBrowsers: async (worktreeId) => {
const workspaces = get().browserTabsByWorktree[worktreeId] ?? []
// Why: snapshot pre-loop so the post-loop set() can reproduce the original
// `hadBrowserTabs` semantics. Reading `s.browserTabsByWorktree[worktreeId]`
// inside set() would always be empty here because each closeBrowserTab call
// above has already removed the workspace from that array.
// Why: snapshot before the loop — closeBrowserTab empties the array, so set() below couldn't recompute hadBrowserTabs.
const hadBrowserTabs = workspaces.length > 0
for (const workspace of workspaces) {
destroyWorkspaceWebviews(get().browserPagesByWorkspace, workspace.id)
@@ -812,10 +782,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
delete nextBrowserTabsByWorktree[worktreeId]
const nextActiveBrowserTabIdByWorktree = { ...s.activeBrowserTabIdByWorktree }
delete nextActiveBrowserTabIdByWorktree[worktreeId]
// Why: mirror shutdownWorktreeTerminals' `hadBrowserTabs && isActive`
// guard. Only reset the globally-visible active browser surface when the
// worktree being shut down is the one the user is looking at AND it
// actually had browser tabs to tear down.
// Why: reset the global browser surface only when the shut-down worktree is the active one AND had tabs.
const shouldResetGlobalBrowser = s.activeWorktreeId === worktreeId && hadBrowserTabs
return {
browserTabsByWorktree: nextBrowserTabsByWorktree,
@@ -828,8 +795,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
},
reopenClosedBrowserTab: (worktreeId) => {
// Why: read and pop atomically inside set() to prevent a TOCTOU race
// where two rapid Cmd+Shift+T presses both restore the same entry.
// Why: read and pop atomically inside set() so two rapid Cmd+Shift+T presses can't both restore the same entry (TOCTOU).
let entryToRestore: ClosedBrowserWorkspaceSnapshot | undefined
set((s) => {
@@ -865,8 +831,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
return get().browserTabsByWorktree[worktreeId]?.find((tab) => tab.id === restored.id) ?? null
}
// Why: create the tab with the first page, then append the rest in
// original order so multi-page workspaces preserve their page sequence.
// Why: append remaining pages in original order so multi-page workspaces preserve their page sequence.
const [firstPage, ...restPages] = pages
const restored = get().createBrowserTab(worktreeId, firstPage.url, {
title: firstPage.title,
@@ -884,8 +849,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
})
}
// Why: duplicate URLs are valid browser pages; restoring by URL can select
// the wrong copy. The restore path preserves page order, so map by index.
// Why: duplicate URLs are valid, so matching by URL can pick the wrong copy; restore preserves order, so map by index.
const activePageId = snap.activePageId
if (activePageId) {
const restoredPages = get().browserPagesByWorkspace[restored.id] ?? []
@@ -919,10 +883,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
}
})
// Why: notify the CDP bridge which guest webContents is now active so
// subsequent agent commands (snapshot, click, etc.) target the correct tab.
// registerGuest uses page IDs (not workspace IDs), so we resolve the active
// page within the workspace to find the correct browserPageId.
// Why: notify the CDP bridge of the active guest; it keys on page IDs not workspace IDs, so resolve the workspace's active page.
const workspace = findWorkspace(get().browserTabsByWorktree, tabId)
if (
workspace?.activePageId &&
@@ -1111,8 +1072,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
},
reopenClosedBrowserPage: (workspaceId) => {
// Why: read and pop atomically inside set() to prevent a TOCTOU race
// where two rapid Cmd+Shift+T presses both restore the same page.
// Why: read and pop atomically inside set() so two rapid Cmd+Shift+T presses can't both restore the same page (TOCTOU).
let pageToRestore: BrowserPage | undefined
set((s) => {
@@ -1167,8 +1127,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
}
})
// Why: switching the active page within a workspace changes which guest
// webContents the CDP bridge should target for agent commands.
// Why: switching the active page changes which guest webContents the CDP bridge targets for agent commands.
if (
!isRuntimeEnvironmentActive(get()) &&
typeof window !== 'undefined' &&
@@ -1190,37 +1149,24 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
},
focusBrowserTabInWorktree: (worktreeId, browserPageId, options) => {
// Why: bridge identifies the target by browserPageId (CDP page id stored
// on BrowserPage.id), but the renderer's tab strip activates a workspace
// (BrowserWorkspace.id, a local UUID). They diverge whenever a workspace
// owns more than one page. Walk pageIds in the targeted worktree's tab
// list to find the owning workspace.
// Why: bridge targets a browserPageId but tabs activate a workspace; find the owning workspace (they differ for multi-page tabs).
const tabsForWorktree = get().browserTabsByWorktree[worktreeId] ?? []
const workspace = tabsForWorktree.find((tab) => (tab.pageIds ?? []).includes(browserPageId))
if (!workspace) {
// Best-effort: state for this worktree may not be hydrated yet, or the
// page closed between the bridge switching and this IPC arriving.
// Best-effort: worktree state may not be hydrated yet, or the page closed between bridge switch and this IPC arriving.
return
}
// Default to true: the only caller (`tab switch --focus` IPC listener)
// wants the pane surfaced when targeting the active worktree. `false` is
// an opt-out for hypothetical pure-pre-staging callers.
// Default true: the only caller (tab switch --focus) wants the pane surfaced; false is an opt-out for pre-staging callers.
const surfacePane = options?.surfacePane ?? true
const pages = get().browserPagesByWorkspace[workspace.id] ?? []
const nextWorkspace = mirrorWorkspaceFromActivePage(
{ ...workspace, activePageId: browserPageId },
pages
)
// TODO: per-worktree writes below duplicate setActiveBrowserTab /
// setActiveBrowserPage. We can't reuse those because they touch globals
// unconditionally (the very behavior --focus is avoiding). If they ever
// grow side-effects (analytics, persistence) those will silently diverge
// here. Consider extracting a private per-worktree-only helper that
// both call paths share.
// TODO: duplicates setActiveBrowserTab/Page; can't reuse (they touch globals unconditionally). Extract a per-worktree-only helper.
set((s) => {
const isActiveWorktree = s.activeWorktreeId === worktreeId
// Per-worktree slots: always update (safe pre-staging; only visible
// when user navigates to this worktree).
// Per-worktree slots: always update — safe pre-staging, only visible when user navigates here.
const nextTabsByWorktree = {
...s.browserTabsByWorktree,
[worktreeId]: tabsForWorktree.map((tab) => (tab.id === workspace.id ? nextWorkspace : tab))
@@ -1232,8 +1178,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
const nextActiveTabTypeByWorktree = surfacePane
? { ...s.activeTabTypeByWorktree, [worktreeId]: 'browser' as const }
: s.activeTabTypeByWorktree
// Globals: only mutate when the targeted worktree is currently active.
// This is the line that keeps cross-worktree --focus calls silent.
// Globals: mutate only when the targeted worktree is active — keeps cross-worktree --focus silent.
return {
browserTabsByWorktree: nextTabsByWorktree,
activeBrowserTabIdByWorktree: nextActiveTabIdByWorktree,
@@ -1243,9 +1188,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
}
})
// Why: notify the CDP bridge which guest webContents is now active so
// subsequent agent commands target the correct page. Mirrors the
// notifyActiveTabChanged calls in setActiveBrowserTab/setActiveBrowserPage.
// Why: notify the CDP bridge which guest webContents is active so agent commands target the correct page.
if (
!isRuntimeEnvironmentActive(get()) &&
typeof window !== 'undefined' &&
@@ -1254,9 +1197,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
window.api.browser.notifyActiveTabChanged({ browserPageId }).catch(() => {})
}
// Why: keep the unified-tab strip's active entry in sync within the
// targeted worktree. activateTab only mutates per-worktree slices, so
// it's safe to call cross-worktree without yanking the user.
// Why: sync the unified-tab strip's active entry; activateTab only mutates per-worktree slices, so it's cross-worktree-safe.
const item = (get().unifiedTabsByWorktree[worktreeId] ?? []).find(
(entry) => entry.contentType === 'browser' && entry.entityId === workspace.id
)
@@ -1431,8 +1372,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
if (!workspace) {
return s
}
// Why: annotations point at DOM coordinates from one loaded document.
// A real URL change invalidates those markers and copied context.
// Why: annotations point at DOM coords of the loaded document; a real URL change invalidates those markers.
const shouldClearAnnotations = normalizeUrl(page.url) !== nextUrl
const nextPages = (s.browserPagesByWorkspace[workspace.id] ?? []).map((entry) =>
entry.id === pageId
@@ -1497,10 +1437,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
return removedHandle
},
// viewportPresetId is a per-page setting on BrowserPage and is intentionally not
// mirrored onto BrowserWorkspace: the outer tab strip doesn't surface the preset,
// so there's no UI consumer at the workspace layer. Keeping it page-local avoids
// cross-layer plumbing; do NOT add mirrorWorkspaceFromActivePage here.
// viewportPresetId is intentionally page-local (no workspace-layer UI consumer); do NOT add mirrorWorkspaceFromActivePage here.
setBrowserPageViewportPreset: (pageId, viewportPresetId) =>
set((s) => {
const page = findPage(s.browserPagesByWorkspace, pageId)
@@ -1576,12 +1513,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
}
addAdditionalValidWorkspaceKeys(validWorktreeIdsForCleanup, options)
// Why: mirror closeBrowserTab's contract — reducers are pure, imperative
// side effects bracket them. Compute dropped workspaces first, destroy
// their webviews, then run the state reducer unchanged. hydrate is called
// once at boot (App.tsx) when the webview registry is empty, so this loop
// is a no-op today; it's defense-in-depth for any future caller that
// re-hydrates after webviews are live.
// Why: destroy dropped workspaces' webviews before the pure reducer; no-op today (boot registry empty), defends future re-hydration callers.
const droppedWorkspaceIds: string[] = []
for (const [worktreeId, tabs] of Object.entries(persistedTabsByWorktree)) {
if (!validWorktreeIdsForCleanup.has(worktreeId)) {
+21 -89
View File
@@ -1,6 +1,4 @@
/* eslint-disable max-lines -- Why: this slice keeps optimistic note
mutation, rollback, persistence ordering, and sent-state transitions together
so every write follows the same queue and rollback invariants. */
/* eslint-disable max-lines -- Why: keeps note mutation, rollback, persistence ordering, and sent-state transitions under shared queue/rollback invariants. */
import type { StateCreator } from 'zustand'
import type { AppState } from '../types'
import type { DiffComment, Worktree } from '../../../../shared/types'
@@ -87,12 +85,7 @@ function deliverySnapshotMatches(
)
}
// Why: return a stable reference when no comments exist so selectors don't
// produce a fresh `[]` on every store update. A new array identity would
// trigger re-renders in any consumer using referential equality.
// Frozen + typed `readonly` so an accidental `list.push(...)` on the returned
// value is both a runtime TypeError and a TypeScript compile error, preventing
// the sentinel from being corrupted globally.
// Why: one shared frozen sentinel so selectors don't return a fresh [] (avoids re-renders); freezing stops a stray push corrupting the shared instance for every consumer.
const EMPTY_COMMENTS: readonly DiffComment[] = Object.freeze([])
async function persist(
@@ -123,25 +116,11 @@ function settingsForWorktreeOwner(state: AppState, worktreeId: string): AppState
: ({ activeRuntimeEnvironmentId: runtimeEnvironmentId } as AppState['settings'])
}
// Why: IPC writes from `persist` are not ordered with respect to each other.
// If two mutations (e.g. rapid add then delete, or two adds) are in flight
// concurrently, their `updateMeta` resolutions can arrive out of call order,
// letting an older snapshot overwrite a newer one on disk. We serialize per
// worktree so only one write runs at a time. We also defer reading the
// snapshot until the queued work actually starts — at dequeue time we pull
// the LATEST `diffComments` from the store — which collapses a burst of N
// mutations into at most 2 in-flight writes per worktree (1 running + 1
// queued) and guarantees the last disk write reflects the newest state.
// Why: IPC writes aren't ordered, so serialize per worktree to stop an older snapshot from overwriting a newer one on disk.
const persistQueueByWorktree: Map<string, Promise<void>> = new Map()
// Why: chain each new write onto the prior promise for this worktree so
// writes land in call order. We use `.then(..., ..)` with both handlers so a
// failing previous write doesn't break the chain — we still proceed with the
// next write. The queued work reads the latest list from the store via
// `get()` at dequeue time (not via a captured parameter) so it writes the
// most recent snapshot rather than a stale one from when it was enqueued.
// The returned promise resolves/rejects when THIS specific write commits so
// callers can preserve their optimistic-update + rollback flow.
// Why: chain each write onto the prior promise so writes land in call order; both then handlers keep the chain alive past a failure.
// Why: queued work reads the latest list at dequeue time, and the returned promise settles for THIS write so callers can roll back.
function enqueuePersist(worktreeId: string, get: () => AppState): Promise<void> {
const prior = persistQueueByWorktree.get(worktreeId) ?? Promise.resolve()
const run = async (): Promise<void> => {
@@ -153,14 +132,8 @@ function enqueuePersist(worktreeId: string, get: () => AppState): Promise<void>
}
const next = prior.then(run, run)
persistQueueByWorktree.set(worktreeId, next)
// Why: once this write settles, clear the queue entry only if no later
// write has been chained on top. Otherwise the map should keep pointing at
// the latest tail so subsequent enqueues chain onto the real in-flight
// tail, not a stale resolved promise. Use `then(cleanup, cleanup)` (not
// `finally`) so a rejection on `next` is fully consumed by this branch —
// otherwise the `.finally()` chain propagates the rejection as an
// unhandledRejection even though the caller `await`s `next` in its own
// try/catch.
// Why: clear the queue entry only if still the tail, so later enqueues chain onto the real in-flight promise.
// Why: then(cleanup, cleanup) not finally, so a rejection is consumed here rather than re-thrown as unhandledRejection.
const cleanup = (): void => {
if (persistQueueByWorktree.get(worktreeId) === next) {
persistQueueByWorktree.delete(worktreeId)
@@ -170,9 +143,7 @@ function enqueuePersist(worktreeId: string, get: () => AppState): Promise<void>
return next
}
// Why: derive the next comment list from the latest store snapshot inside
// the `set` updater so two concurrent writes (rapid add+delete, or a
// delete-while-add-in-flight) can't clobber each other via a stale closure.
// Why: derive the next list inside the `set` updater so concurrent writes can't clobber each other via a stale closure.
function mutateComments(
set: Parameters<StateCreator<AppState, [], [], DiffCommentsSlice>>[0],
worktreeId: string,
@@ -207,16 +178,7 @@ function mutateComments(
return { previous, next }
}
// Why: if the IPC write fails, the optimistic renderer state drifts from
// disk. Roll back so what the user sees always matches what will survive a
// reload.
//
// Identity guard: we only revert when the current diffComments array is
// strictly identical (===) to the `next` array this mutation produced. If
// another mutation has already landed (e.g. Add B succeeded while Add A was
// still in flight), it will have replaced the array with a different
// identity. In that case we must leave the newer state alone — rolling back
// to our stale `previous` would erase B along with the failed A.
// Why: on IPC-write failure, roll back optimistic state so the renderer matches disk (identity-guarded below).
function rollback(
set: Parameters<StateCreator<AppState, [], [], DiffCommentsSlice>>[0],
worktreeId: string,
@@ -230,16 +192,11 @@ function rollback(
return {}
}
const target = repoList.find((w) => w.id === worktreeId)
// Why: if the worktree was removed between the optimistic mutation and
// this rollback, there is nothing to restore. Bail out before remapping
// `repoList` so we don't allocate a new outer-array identity and trigger
// spurious subscriber notifications.
// Why: worktree gone since the mutation; bail before remapping so we don't allocate a new array identity and fire spurious notifications.
if (!target) {
return {}
}
// Why: only roll back if no other mutation landed since this one. If a
// later write already replaced the comments array with a different
// identity, our stale `previous` would erase that newer state.
// Why: only roll back if no later mutation replaced the array, else our stale `previous` would erase newer state.
if (target.diffComments !== expectedCurrent) {
return {}
}
@@ -255,19 +212,13 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
get
) => ({
getDiffComments: (worktreeId) => {
// Why: accept null/undefined so callers with an optional active worktree
// can pass it through without allocating a fresh `[]` fallback each
// render, which would defeat the `EMPTY_COMMENTS` sentinel's referential
// stability and trigger spurious re-renders in useAppStore selectors.
// Why: return the stable sentinel for a missing worktree so optional-worktree callers don't allocate a fresh [] and trigger re-renders.
if (!worktreeId) {
return EMPTY_COMMENTS as DiffComment[]
}
const worktree = findWorktreeById(get().worktreesByRepo, worktreeId)
if (!worktree?.diffComments) {
// Why: cast the frozen sentinel to the mutable `DiffComment[]` return
// type. The array is frozen at runtime so accidental mutation throws;
// the cast only hides the `readonly` marker from consumers that never
// mutate the list in practice.
// Why: cast the frozen sentinel to the mutable return type; runtime freeze makes accidental mutation throw.
return EMPTY_COMMENTS as DiffComment[]
}
return worktree.diffComments
@@ -284,38 +235,26 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
return null
}
try {
// Why: enqueue through the per-worktree queue so concurrent mutations
// cannot land on disk out of call order. The queued write reads the
// latest store snapshot at dequeue time, so it will reflect any newer
// mutation that landed after this one was enqueued.
// Why: serialize through the per-worktree queue so concurrent writes can't land on disk out of call order.
await enqueuePersist(input.worktreeId, get)
get().recordFeatureInteraction?.('review-notes')
return comment
} catch (err) {
console.error('Failed to persist diff comments:', err)
// Why: rollback's identity guard will no-op if a later mutation has
// already replaced the in-memory list, so losing a successful newer
// write is not possible here even though we queued in order.
// Why: rollback's identity guard no-ops if a later mutation already replaced the list, so a newer write can't be lost.
rollback(set, input.worktreeId, result.previous, result.next)
return null
}
},
updateDiffComment: async (worktreeId, commentId, body) => {
// Why: trim trailing whitespace but reject an entirely-empty edit so we
// don't end up with a saved note that renders as a blank card. Callers
// should treat `false` as "edit not committed" and keep the editor open
// so the user can either type more or cancel explicitly.
// Why: reject an empty edit so we never save a note that renders as a blank card; false means "not committed", keep the editor open.
const trimmed = body.trim()
if (!trimmed) {
return false
}
// Why: look up the current state OUTSIDE mutateComments so we can
// distinguish "comment missing" (return false — likely an edit-while-
// deleted race; the card should keep its draft and not silently close)
// from "body unchanged" (return true — benign no-op; the card can close
// the editor without surfacing an error).
// Why: distinguish "comment missing" (false; keep draft, likely edit-while-deleted) from "body unchanged" (true; close editor) before mutating.
const repoId = getRepoIdFromWorktreeId(worktreeId)
const repoList = get().worktreesByRepo[repoId]
const target = repoList?.find((w) => w.id === worktreeId)
@@ -337,15 +276,12 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
return null
}
const next = current.slice()
// Why: editing a previously-sent note makes the agent's copy stale, so
// the note should become eligible for the next Send notes action.
// Why: editing a sent note makes the agent's copy stale, so reset sentAt to re-queue it for the next Send.
next[idx] = { ...current[idx], body: trimmed, sentAt: undefined }
return next
})
if (!result) {
// Why: between the pre-check and the set updater, the comment vanished
// or another mutation already wrote the same body. Treat as success so
// the caller closes its editor.
// Why: comment vanished or the same body was already written between pre-check and set; treat as success so the editor closes.
return true
}
try {
@@ -366,9 +302,7 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
const result = mutateComments(set, worktreeId, (existing) => {
const next = existing.filter((comment) => {
const snapshot = snapshotsById.get(comment.id)
// Why: delivery is async. If the user edits a note before the prompt
// is accepted by the agent, the old snapshot was sent but the current
// note is a fresh pending note and must stay visible.
// Why: delivery is async; a note edited after its snapshot was sent is a fresh pending note that must stay visible.
return !snapshot || !deliverySnapshotMatches(comment, snapshot)
})
return next.length === existing.length ? null : next
@@ -426,9 +360,7 @@ export const createDiffCommentsSlice: StateCreator<AppState, [], [], DiffComment
return
}
try {
// Why: enqueue through the per-worktree queue so concurrent mutations
// cannot land on disk out of call order. See enqueuePersist for the
// ordering invariant.
// Why: serialize through the per-worktree queue so concurrent writes can't land out of call order.
await enqueuePersist(worktreeId, get)
} catch (err) {
console.error('Failed to persist diff comments:', err)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+49 -141
View File
@@ -1,7 +1,4 @@
/* eslint-disable max-lines -- Why: repo slice owns local/runtime routing,
add/remove/reorder side effects, and cross-slice teardown. Splitting it during
the client-server refactor would obscure the invariants this file is currently
auditing and preserving. */
/* eslint-disable max-lines -- Why: repo slice owns local/runtime routing, add/remove/reorder side effects, and cross-slice teardown; splitting mid-refactor would obscure its invariants. */
import type { StateCreator } from 'zustand'
import { toast } from 'sonner'
import type { AppState } from '../types'
@@ -289,8 +286,7 @@ async function warnIfProjectKnownInAnotherProfile(
activeOrcaProfileId: string | null
): Promise<void> {
const findProjectProfiles = window.api.orcaProfiles?.findProjectProfiles
// Why: without a loaded active profile ID the scan cannot exclude the
// current profile and would false-positive on the project just added.
// Why: without an active profile ID the scan can't exclude the current profile and would false-positive on the just-added project.
if (!findProjectProfiles || !activeOrcaProfileId) {
return
}
@@ -342,9 +338,7 @@ function scheduleSafeAutoForkSync(get: () => AppState, repos: readonly Repo[]):
)
.then(() => undefined)
.catch((error) => {
// Why: safe-auto is opportunistic. Auth/protection/divergence failures
// should not create startup noise; the settings row exposes Sync Now
// for explicit, toast-backed diagnosis.
// Why: safe-auto is opportunistic; auth/protection/divergence failures shouldn't add startup noise (Sync Now handles explicit diagnosis).
console.info('Safe fork auto-sync skipped', error)
})
.finally(() => {
@@ -431,8 +425,7 @@ async function fetchProjectHostSetupCompatibility(
setups: setupResponse.setups.map((setup) => setupWithFetchedOwner(setup, target))
}
} catch {
// Why: newer clients must still hydrate against older runtimes/preloads
// that only know `repo.list`; derive the transitional model locally.
// Why: newer clients must hydrate against older runtimes that only know repo.list; derive the transitional model locally.
return projectHostSetupProjectionFromRepos(repos)
}
}
@@ -484,8 +477,7 @@ function mergeProjectCompatibilityProject(base: Project, overlay: Project): Proj
const project: Project = {
...base,
...overlay,
// Why: all-host startup fetches hosts separately; one host's project record
// must not erase repo ownership learned from another host with the same id.
// Why: all-host startup fetches hosts separately; one host's record must not erase repo ownership learned from another host with the same id.
sourceRepoIds: [...new Set([...base.sourceRepoIds, ...overlay.sourceRepoIds])],
createdAt: Math.min(base.createdAt, overlay.createdAt),
updatedAt: Math.max(base.updatedAt, overlay.updatedAt)
@@ -527,8 +519,7 @@ function mergeUpdatedProjectCompatibilityProject(
'localWindowsRuntimePreference' in updated
? updated.localWindowsRuntimePreference
: updates.localWindowsRuntimePreference
// Why: project.update returns one host's project record, but preference
// clears must still override the cross-host metadata preservation merge.
// Why: project.update returns one host's record, but preference clears must override the cross-host metadata-preservation merge.
if (localWindowsRuntimePreference === undefined) {
delete project.localWindowsRuntimePreference
} else {
@@ -598,8 +589,7 @@ function mergePreviousProjectMetadata(
): Project {
const project = mergeProjectCompatibilityProject(previous, current)
if (hostId === LOCAL_EXECUTION_HOST_ID) {
// Why: `localWindowsRuntimePreference` belongs to the local host; a local
// refresh that omits it is authoritative and should clear stale renderer state.
// Why: localWindowsRuntimePreference belongs to the local host; a local refresh that omits it is authoritative and clears stale renderer state.
if ('localWindowsRuntimePreference' in current) {
if (current.localWindowsRuntimePreference === undefined) {
delete project.localWindowsRuntimePreference
@@ -610,14 +600,12 @@ function mergePreviousProjectMetadata(
delete project.localWindowsRuntimePreference
}
} else if (previous.localWindowsRuntimePreference !== undefined) {
// Why: remote runtimes can have their own local Windows preference; they must
// not overwrite the client-local project runtime setting.
// Why: a remote runtime's local Windows preference must not overwrite the client-local project runtime setting.
project.localWindowsRuntimePreference = previous.localWindowsRuntimePreference
}
return {
...project,
// Why: fetched project metadata can lag behind repo.list; repo ownership
// must track the freshly reconciled repos so removed host repos do not linger.
// Why: fetched project metadata can lag repo.list; track ownership to the reconciled repos so removed-host repos don't linger.
sourceRepoIds: getMergedSourceRepoIdsForHostRefresh(previous, current, reposById, hostId)
}
}
@@ -713,8 +701,7 @@ function mergeFetchedProjectCompatibilityForHost({
return setup.hostId === hostId
}
const owner = parseExecutionHostId(setup.hostId)
// Why: desktop persistence owns local and direct-SSH setups; runtime setups
// remain authoritative on their remote Orca server.
// Why: desktop persistence owns local and direct-SSH setups; runtime setups stay authoritative on their remote Orca server.
return setup.hostId === LOCAL_EXECUTION_HOST_ID || owner?.kind === 'ssh'
}
const fetchedSetupsForHost = fetched.projectHostSetups.filter(setupBelongsToFetchedCatalog)
@@ -734,8 +721,7 @@ function mergeFetchedProjectCompatibilityForHost({
const fetchedProjects = fetched.projects
.filter((project) => {
const previousProject = previousProjectById.get(project.id)
// Why: repo-derived compatibility projects include every known host.
// A one-host refresh should only reconcile that host or prune its stale ownership.
// Why: repo-derived compatibility projects include every host; a one-host refresh should only reconcile or prune that host's ownership.
return (
projectHasHost(project, fetched.projectHostSetups) ||
(previousProject ? projectHasHost(previousProject, previous.projectHostSetups) : false)
@@ -836,8 +822,7 @@ function applyInheritedProjectGroups(previous: readonly Repo[], fetched: readonl
if (inheritedProjectGroupId === undefined) {
return repo
}
// Why: project groups are a local organization affordance. Runtime copies
// of the same canonical project should appear in the user's existing group.
// Why: project groups are a local affordance; runtime copies of the same canonical project should appear in the user's existing group.
return { ...repo, projectGroupId: inheritedProjectGroupId }
})
}
@@ -1042,9 +1027,7 @@ function clearRestoredFolderWorkspaceSessionOwners(
}
const workspace = state.folderWorkspaces.find((entry) => entry.id === scope.folderWorkspaceId)
if (workspace && !state.projectGroups.some((group) => group.id === workspace.projectGroupId)) {
// Why: folder workspace ownership is resolved through its project group.
// If that catalog is still missing, keep the restored host owner so a
// session write before the next retry does not move runtime tabs local.
// Why: ownership resolves via the project group; if that catalog is still missing, keep the restored host owner so a session write doesn't move runtime tabs local.
next[key] = hostId
}
}
@@ -1495,12 +1478,10 @@ export type RepoSlice = {
groupId: string | null,
order?: number
) => Promise<boolean>
// options.hostId disambiguates which host's row to remove when the same repo
// id exists on multiple hosts; without it the focused host is assumed.
// options.hostId disambiguates which host's row to remove when the id exists on multiple hosts; else the focused host is assumed.
removeProject: (projectId: string, options?: { hostId?: ExecutionHostId }) => Promise<void>
updateProject: (projectId: string, updates: ProjectUpdate) => Promise<boolean>
// options.hostId targets a specific host's repo row + RPC target when the same
// repo id exists on multiple hosts; without it the focused host is assumed.
// options.hostId targets a specific host's row + RPC target when the id exists on multiple hosts; else the focused host is assumed.
updateRepo: (
projectId: string,
updates: RepoUpdate,
@@ -1547,8 +1528,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}),
fetchRepos: async () => {
// Why: overlapping repos:changed fetches can resolve out of order; an earlier
// one must not overwrite a newer result and resurrect deleted projects (#7020).
// Why: overlapping repos:changed fetches can resolve out of order; a stale one must not overwrite a newer result and resurrect deleted projects (#7020).
let generation = 0
set((s) => {
generation = s.reposFetchGeneration + 1
@@ -1563,17 +1543,11 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
let finalizedHostRepos: Repo[] = []
set((s) => {
// Why: an in-flight fetch for a just-removed runtime env would otherwise
// re-add purged repos/rows and stick — nothing re-triggers the purge. Skip
// only when the catalog's env was actually removed (tombstoned), not merely
// absent from the not-yet-hydrated saved list (#8881).
// Why: an in-flight fetch for a just-removed env would re-add purged repos and stick; skip only when the env was tombstoned, not merely unhydrated (#8881).
if (isRemovedRuntimeHostId(catalog.hostId, s.removedRuntimeEnvironmentIds)) {
return s
}
// Why: after re-adoption re-points a repo onto a re-added SSH target, the
// per-host merge leaves the stale row on the old (removed) target id — a
// ghost a terminal pane can bind to and fail with "SSH target not found".
// Drop rows on unknown SSH targets that a live-host sibling supersedes.
// Why: re-adoption leaves a stale row on the old SSH target id (a ghost that fails "SSH target not found"); drop rows a live-host sibling supersedes.
const result = mergeFetchedRepoCatalog(catalog, s.repos)
const reconciliation = reconcileSupersededSshRepos(result.repos, s)
const prunedRepos = applyManualRepoOrder(reconciliation.repos, s.manualRepoOrder)
@@ -1624,8 +1598,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
const catalog = await fetchRepoCatalogForTarget(target)
let finalizedHostRepos: Repo[] = []
set((s) => {
// Why: skip a merge for a runtime env removed while this Connect-flow fetch
// was in flight, so purged repos/rows are not re-added (#8881).
// Why: skip merging a runtime env removed while this Connect-flow fetch was in flight, so purged repos aren't re-added (#8881).
if (isRemovedRuntimeHostId(catalog.hostId, s.removedRuntimeEnvironmentIds)) {
return s
}
@@ -1680,24 +1653,15 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
generation = s.reposFetchGeneration + 1
return { reposFetchGeneration: generation }
})
// Why: a cold start that restores a remote workspace re-activates that
// remote runtime environment, and fetching only the active host hides every
// other host's repos (notably all local repos), which reads as "my projects
// vanished". Load local + every configured runtime environment so the
// sidebar "All hosts" scope shows them together regardless of which
// environment is active. Each host fails soft: an unreachable/disconnected
// host is skipped without blocking the others.
// Why: fetching only the active host hides every other host's repos ("my projects vanished"); load local + all runtime envs, each failing soft.
const applyCatalog = (catalog: FetchedRepoCatalog): void => {
// Why: repos:changed can start another all-host refresh while this one is
// in flight. Never let the older catalog resurrect a migrated SSH owner.
// Why: a concurrent all-host refresh must not let the older catalog resurrect a migrated SSH owner.
if (get().reposFetchGeneration !== generation) {
return
}
let hostRepos: Repo[] = []
set((s) => {
// Why: an all-host refresh can still be merging a host removed mid-load;
// skip a catalog whose env was tombstoned by a removal, not one merely
// absent from the not-yet-hydrated saved list (#8881).
// Why: skip a catalog whose env was tombstoned mid-load (removed), not one merely absent from the not-yet-hydrated saved list (#8881).
if (isRemovedRuntimeHostId(catalog.hostId, s.removedRuntimeEnvironmentIds)) {
return s
}
@@ -1733,9 +1697,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
setupScriptPromptDismissedRepoIds: s.setupScriptPromptDismissedRepoIds
}
})
// Why: preserve the safe-auto fork sync that fetchRepos /
// fetchRuntimeEnvironmentRepos schedule after merging each host, so
// cold-start (which now routes through here) keeps updating safe-auto forks.
// Why: keep the safe-auto fork sync (as fetchRepos does) so cold-start, which now routes here, still updates safe-auto forks.
scheduleSafeAutoForkSync(get, hostRepos)
}
const validateRepoScopedUi = (): void => {
@@ -1769,8 +1731,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
const environments = await listRuntimeEnvironmentsForAllHostLoad()
// Why: unreachable remotes can spend the full connect timeout; merge each
// resolved host through the state updater so parallel loads do not clobber.
// Why: unreachable remotes can spend the full connect timeout; merge each resolved host via the state updater so parallel loads don't clobber.
await Promise.all(
environments.map(async (environment) => {
try {
@@ -1786,9 +1747,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
})
)
// Why: first-paint startup intentionally loads only local repos before
// remotes answer. Validate repo-scoped UI only once every configured host has
// answered; otherwise an offline runtime would erase its saved filters.
// Why: validate repo-scoped UI only after every host answers; first-paint loads only local repos, so an offline runtime would erase its saved filters.
if (!failed && get().reposFetchGeneration === generation) {
validateRepoScopedUi()
}
@@ -1808,8 +1767,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
},
fetchProjectGroupsForAllHosts: async (options) => {
// Why: startup renders an all-host sidebar; replacing groups with only the
// active host would leave repos from other hosts visible but ungrouped.
// Why: startup renders an all-host sidebar; replacing groups with only the active host leaves other hosts' repos visible but ungrouped.
const applyCatalog = (catalog: FetchedProjectGroupCatalog): void => {
set((s) => ({
projectGroups: mergeFetchedProjectGroupCatalog(catalog, s.projectGroups).projectGroups,
@@ -1858,8 +1816,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
},
fetchFolderWorkspacesForAllHosts: async (options) => {
// Why: folder workspaces are owned through their project groups, so startup
// must fetch groups first and then merge each host's folder slice.
// Why: folder workspaces are owned through their project groups; fetch groups first, then merge each host's folder slice.
const applyCatalog = (catalog: FetchedFolderWorkspaceCatalog): void => {
set((s) => ({
folderWorkspaces: mergeFetchedFolderWorkspaceCatalog(
@@ -1993,8 +1950,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
target,
'projectGroup.scanNested',
{ path },
// Why: older runtime servers cannot stream or cancel scans, so the
// renderer must retain a bounded failure path for large folders.
// Why: older runtime servers can't stream or cancel scans; keep a bounded failure path for large folders.
{ timeoutMs: 20_000 }
)
)
@@ -2173,8 +2129,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
updateProjectGroup: async (groupId, updates) => {
try {
// Why: project groups are focused-host-scoped by design — fetch/create/update/
// delete all route by the focused host, and the list is replaced (not merged).
// Why: project groups are focused-host-scoped by design; all CRUD routes by the focused host and the list is replaced, not merged.
const target = getActiveRuntimeTarget(get().settings)
const updated =
target.kind === 'local'
@@ -2401,10 +2356,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
return null
}
}
// Why: folder mode is a capability downgrade, not a silent fallback.
// Show an in-app confirmation dialog so users understand that worktrees,
// SCM, PRs, and checks will be unavailable for this root. The dialog's
// OK handler calls addNonGitFolder to complete the flow.
// Why: folder mode is a capability downgrade (no worktrees/SCM/PRs/checks), so confirm via dialog rather than silently falling back.
const { openModal } = get()
openModal('confirm-non-git-folder', {
folderPath: path,
@@ -2447,8 +2399,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
description: repo.displayName
}
)
// Why: the design requires the cross-profile advisory for SSH-added
// projects too — the presence lookup already keys on connection/host.
// Why: the cross-profile advisory applies to SSH-added projects too; the presence lookup already keys on connection/host.
await warnIfProjectKnownInAnotherProfile(repo, get().activeOrcaProfileId)
}
return repo
@@ -2706,8 +2657,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
addRepo: async () => {
const target = getActiveRuntimeTarget(get().settings)
if (target.kind !== 'local') {
// Why: OS folder pickers return client-local paths. Remote environments
// need an explicit host path, which the Add Project dialog handles.
// Why: OS folder pickers return client-local paths; remote environments need an explicit host path (Add Project dialog).
toast.error(
translate(
'auto.store.slices.repos.e649269645',
@@ -2731,20 +2681,13 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
return null
}
await markOnboardingProjectAdded('addedFolder')
// Why: without focusing the new folder, the UI looks unchanged after
// the dialog closes and users think nothing happened. Fetch the
// synthetic folder worktree and route through the standard activation
// sequence so the sidebar reveals and opens the folder the same way
// clicking a worktree card does. Lazy-imported to avoid a circular
// module load (worktree-activation imports the store root).
// Why: focus the new folder so the add is visible; lazy-import worktree-activation to avoid a circular module load (it imports the store root).
await get().fetchWorktrees(repo.id)
const folderWorktree = get().worktreesByRepo[repo.id]?.[0]
if (folderWorktree) {
const { activateAndRevealWorktree } = await import('../../lib/worktree-activation')
const onboarding = await window.api.onboarding.get().catch(() => null)
// Why: a new user can dismiss the wizard, then immediately add their
// first folder from Landing. That path skips onboarding's completeRepo
// hook, so carry the selected default agent into the first terminal here.
// Why: adding the first folder from Landing skips onboarding's completeRepo hook; carry the default agent into the first terminal here.
const startup = buildDismissedOnboardingFolderAgentStartup(
get().settings,
onboarding,
@@ -2769,9 +2712,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
removeProject: async (projectId, options) => {
try {
// Why: pass an explicit hostId (e.g. when removing an SSH host's root repo)
// so a duplicate id across hosts resolves to the intended row instead of
// falling back to the focused host.
// Why: pass an explicit hostId so a duplicate id across hosts resolves to the intended row, not the focused-host fallback.
const ownerRepo = findRepoForHost(get().repos, projectId, {
settings: get().settings,
hostId: options?.hostId
@@ -2780,26 +2721,16 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
return
}
const ownerHostId = getRepoExecutionHostId(ownerRepo)
// Why: an SSH-mode per-workspace-env's workspace is the repo's main worktree, so deleting it
// routes here (project removal) rather than through removeWorktree. Tear down the backing
// ephemeral runtime (Docker/VM + hidden SSH target) first so it doesn't leak when the project
// is removed. Matches on the repo's runtime-owned connectionId and its known worktree ids.
// Why: an SSH per-workspace-env's workspace is the repo's main worktree, so removal routes here; tear down its ephemeral runtime first so it doesn't leak.
if (isRuntimeOwnedSshTargetId(ownerRepo.connectionId)) {
await cleanupEphemeralVmRuntimesForDeleted({
workspaceIds: getKnownRepoWorktreeIds(get(), projectId, ownerHostId),
runtimeOwnedSshTargetIds: [ownerRepo.connectionId as string]
})
}
// Why: derive the runtime target from the owner's own settings, passing the
// explicit options.hostId so a duplicate repo id across hosts resolves to the
// intended row. settingsForRepoOwner clears the focused runtime for SSH/local
// owners (routing local) and pins runtime owners to their environment, so an
// SSH host removal never routes repo.rm to the focused runtime.
// Why: derive the target from the owner's settings (via options.hostId) so an SSH host removal never routes repo.rm to the focused runtime.
const target = getActiveRuntimeTarget(settingsForRepoOwner(get(), projectId, options?.hostId))
// Why: the same repo id can exist on multiple hosts (local + an SSH target,
// or a re-added SSH target). Main's repos:remove is repo-id-only and would
// delete every host's row. Scope the local-side removal to the owning host
// so a cross-host duplicate id keeps its other rows.
// Why: repos:remove is id-only and would delete every host's row; scope local removal to the owning host so cross-host duplicates keep other rows.
const idExistsOnOtherHost = get().repos.some(
(repo) => repo.id === projectId && getRepoExecutionHostId(repo) !== ownerHostId
)
@@ -2844,11 +2775,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
}
// Why: route project removal through the canonical per-worktree purge so all
// ~30 worktree-scoped maps are evicted. removeProject previously hand-deleted
// only a handful (tabs/layouts/ptys), leaking the rest (unified tabs, groups,
// git status, browser, everActivated, …) per worktree of every removed repo.
// Runs before the repo-scoped set() below so the purge still sees tabsByWorktree.
// Why: use the canonical per-worktree purge to evict all worktree-scoped maps (hand-deletion leaked most); runs before the set() below so it still sees tabsByWorktree.
get().purgeWorktreeTerminalState(worktreeIds)
set((s) => {
@@ -2885,10 +2812,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
delete nextPtyIdsByTabId[tabId]
delete nextRuntimePaneTitlesByTabId[tabId]
}
// Why: editor state is worktree-scoped. Removing a repo must also
// remove open editor files and per-worktree active-file tracking for
// all worktrees that belonged to the repo, otherwise orphaned entries
// would persist in the session save and pollute state.
// Why: editor state is worktree-scoped; clear the repo's open files + active-file tracking so orphans don't linger in the session save.
const worktreeIdSet = new Set(worktreeIds)
const nextOpenFiles = s.openFiles.filter((f) => !worktreeIdSet.has(f.worktreeId))
const nextActiveFileIdByWorktree = { ...s.activeFileIdByWorktree }
@@ -2901,11 +2825,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
? s.openFiles.some((f) => f.id === s.activeFileId && worktreeIdSet.has(f.worktreeId))
: false
const nextRepos = s.repos.filter((r) => !repoMatchesHostIdentity(r, projectId, ownerHostId))
// Why: when no sibling host still owns this repo id, drop every persisted
// timestamp for the repo's worktrees — including unhydrated SSH/remote ones
// absent from worktreeIdSet, which pruneLastVisitedTimestamps would otherwise
// defer forever as "not yet hydrated" after the repo is gone. When a duplicate
// id remains on another host, stay host-scoped via worktreeIdSet.
// Why: when no sibling host owns this id, drop every worktree timestamp (unhydrated SSH ones would otherwise never prune); else stay host-scoped.
const repoIdFullyRemoved = !nextRepos.some((r) => r.id === projectId)
let nextLastVisitedAtByWorktreeId = s.lastVisitedAtByWorktreeId
for (const id of Object.keys(s.lastVisitedAtByWorktreeId)) {
@@ -2923,8 +2843,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
const removedRepoIds = s.repos.filter((r) => !survivingRepoIds.has(r.id)).map((r) => r.id)
return {
repos: nextRepos,
// Why: drop the removed repos' sparse-preset maps so they don't outlive
// the repo for the renderer's whole session.
// Why: drop removed repos' sparse-preset maps so they don't outlive the repo for the whole session.
...omitSparsePresetsForRepos(s, removedRepoIds),
...mergeProjectCompatibilityForHostRepoChange({
previous: { projects: s.projects, projectHostSetups: s.projectHostSetups },
@@ -2948,10 +2867,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
lastVisitedAtByWorktreeId: nextLastVisitedAtByWorktreeId,
folderWorkspacePathStatuses: {},
sortEpoch: s.sortEpoch + 1,
// Why: removing the last repo while in settings leaves activeView as
// 'settings', which renders an empty settings pane instead of Landing.
// Also clear activeWorktreeId so App renders Landing (it checks
// !activeWorktreeId). Without this, the terminal surface shows instead.
// Why: removing the last repo must reset activeView + clear activeWorktreeId so App renders Landing, not an empty settings/terminal pane.
...(nextRepos.length === 0
? {
activeView: 'terminal' as const,
@@ -3006,8 +2922,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
updateRepo: async (projectId, updates, options) => {
const updateRepoChains = getRepoUpdateChains(get)
// Why: pass options.hostId so a duplicate repo id across hosts resolves to the
// intended row instead of findRepoForHost's settings-focused fallback.
// Why: pass options.hostId so a duplicate repo id across hosts resolves to the intended row, not the settings-focused fallback.
const ownerRepo = findRepoForHost(get().repos, projectId, {
settings: get().settings,
hostId: options?.hostId
@@ -3015,9 +2930,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
if (!ownerRepo) {
return false
}
// Why: an explicit hostId is authoritative — treat it as an explicit host so
// routing goes to that host's target (local IPC or its runtime RPC) rather
// than the currently-focused runtime, which is the same-id/self-pair case.
// Why: an explicit hostId is authoritative; route to that host's target rather than the currently-focused runtime.
const ownerHasExplicitHost = Boolean(
options?.hostId || ownerRepo.executionHostId?.trim() || ownerRepo.connectionId?.trim()
)
@@ -3097,8 +3010,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
}
}
const previous = updateRepoChains.get(updateChainKey)
// Why: repo settings are persisted as full nested values. Preserve call
// order per repo so a slower IPC/RPC response cannot overwrite newer state.
// Why: settings persist as full nested values, so preserve per-repo call order — a slower response mustn't overwrite newer state.
const next = previous
? previous.catch(() => undefined).then(applyRepoUpdate)
: applyRepoUpdate()
@@ -3115,8 +3027,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
setActiveRepo: (projectId) => set({ activeRepoId: projectId }),
reorderRepos: async (orderedIds) => {
// Optimistically apply the new order so the sidebar updates instantly;
// resync only if main rejects (stale permutation due to a racing add/remove).
// Optimistically apply the new order for instant sidebar update; resync only if main rejects (racing add/remove).
const previous = get().repos
const remainingById = new Map<string, { repos: Repo[]; nextIndex: number }>()
for (const repo of previous) {
@@ -3149,9 +3060,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
folderWorkspacePathStatuses: {}
})
try {
// Why: each host persists only its own repos and rejects non-permutations,
// so split the cross-host order into per-host permutations and dispatch one
// reorder per owner host.
// Why: each host persists only its own repos and rejects non-permutations; dispatch one per-host permutation per owner.
const groups = splitRepoReorderByHost(orderedIds, next, get().settings)
const [results] = await Promise.all([
Promise.all(
@@ -3174,8 +3083,7 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
)
})
),
// Why: servers can only persist their local permutations. The desktop
// profile owns the cross-host relationships needed after a cold load.
// Why: servers only persist local permutations; the desktop profile owns cross-host order after a cold load.
window.api.ui.set({ manualRepoOrder })
])
if (results.some((result) => result.status === 'rejected')) {
@@ -805,8 +805,7 @@ describe('setActiveWorktree', () => {
const worktree = store.getState().worktreesByRepo.repo1[0]
expect(worktree.sortOrder).toBe(123)
expect(worktree.lastActivityAt).toBe(lastActivityAt)
// Why: selecting a worktree should not manufacture smart-sort activity.
// Persisted ordering signals come from real background work or edits, not focus.
// Why: selecting a worktree must not manufacture smart-sort activity; ordering comes from real work, not focus.
expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled()
})
@@ -1708,9 +1707,7 @@ describe('setActiveWorktree', () => {
store.getState().createTab(wt)
unsubscribe()
// Why: task-page launches queue startup/setup commands before React mounts.
// A terminal-only intermediate state can mount the legacy host and race
// the split-group host, duplicating setup panes and PTYs.
// Why: a terminal-only intermediate state mounts the legacy host and races the split-group host, duplicating setup panes and PTYs.
expect(snapshots).toEqual([{ terminalCount: 1, unifiedCount: 1, groupCount: 1 }])
})
@@ -2423,10 +2420,7 @@ describe('setActiveWorktree', () => {
})
})
// Why: unread flags are ephemeral UI state — they must not linger past the
// lifetime of the tab/pane they point at. A stale flag on a closed tab
// would render a bell the user can never dismiss because the tab (and
// therefore every focus path that clears it) is gone.
// Why: a stale unread flag on a closed tab renders a bell the user can never dismiss, since the tab is gone.
it('drops unreadTerminalTabs for a closed tab', () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
@@ -2440,9 +2434,7 @@ describe('setActiveWorktree', () => {
const closing = store.getState().createTab(wt)
const surviving = store.getState().createTab(wt)
// Seed flags directly — the self-guarded mark actions intentionally
// refuse the currently-active tab, but this test's subject is closeTab's
// cleanup behavior, not the guards.
// Seed directly: mark actions refuse the active tab, but this test targets closeTab's cleanup, not the guards.
store.setState({
unreadTerminalTabs: {
[closing.id]: true as const,
@@ -2458,10 +2450,7 @@ describe('setActiveWorktree', () => {
expect(s.unreadTerminalTabs[surviving.id]).toBe(true)
})
// Why: shutdownWorktreeTerminals tears down every PTY in the worktree. The
// focus events that would normally clear unread (bell-in-focused-pane,
// activate-tab) never arrive for dead PTYs, so the flags have to be
// dropped by the shutdown path itself.
// Why: focus events that normally clear unread never arrive for dead PTYs, so the shutdown path must drop the flags itself.
it('drops unread flags for every tab in a shutdown worktree', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
@@ -2490,11 +2479,7 @@ describe('setActiveWorktree', () => {
expect(s.unreadTerminalTabs[tabB.id]).toBeUndefined()
})
// Why: ownership regression (design §1.3). shutdownWorktreeTerminals used to
// delete browserTabsByWorktree[worktreeId] and reset
// activeBrowserTabId/activeTabType as a side effect — now those mutations
// belong exclusively to shutdownWorktreeBrowsers. If a refactor reintroduces
// the side effect, both thunks will write the same keys and race.
// Why: browser-state mutations belong to shutdownWorktreeBrowsers only (design §1.3); reintroducing them here races both thunks.
it('leaves browser state untouched when shutting down terminals', async () => {
const store = createTestStore()
const wt = 'repo1::/path/wt1'
@@ -2925,14 +2910,7 @@ describe('setActiveWorktree', () => {
})
})
// Why: sleep (`shutdownWorktreeTerminals(wt, { keepIdentifiers: true })`)
// kills the PTYs but preserves wake hints (tab.ptyId, ptyIdsByLeafId, the
// runtime pane titles) so wake can reattach to the same daemon-history dir
// or relay session. Before the sleep-statuses fix, the live agent-status
// rows were also preserved — so a Claude that was mid-turn at sleep time
// kept its row in the inline agents list as "working" until the 30-min
// stale TTL decayed it. Sleep now drops live entries and retained `done`
// snapshots for the whole worktree, so the card folds to a single grey signal.
// Why: sleep must drop live + retained agent-status rows, else a mid-turn agent stays "working" until the 30-min stale TTL.
describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -3047,11 +3025,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
})
it('aborts pane hibernation without side effects when no resume record can be captured', async () => {
// The prod ghost pane was killed with NO sleeping record captured, so
// nothing could ever wake it. Planner eligibility can go stale between
// ticks, so the shutdown must throw before any suppression or kill when the
// capture comes back empty (a done agent with no resumable provider
// session), leaving the pane fully intact for a later retry.
// No capturable resume record means the pane could never wake, so shutdown throws before any suppression or kill.
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
@@ -3110,10 +3084,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
})
it('rolls back the sleeping record and suppression when the hibernation kill fails', async () => {
// The sleeping record must be visible to the pane's exit handler BEFORE the
// kill (pty:exit can beat the kill promise back to the renderer), so it is
// written alongside the suppression — and both must roll back if the kill
// fails, or a live pane would carry a stale wake record.
// Record written before the kill (pty:exit can beat it back); both it and the suppression must roll back if the kill fails.
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
@@ -3164,11 +3135,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
})
it('persists the sleeping record and suppression before issuing the hibernation kill', async () => {
// pty:exit can beat the kill promise back to the renderer, and the pane's
// exit handler arms the hibernation wake only if the sleeping record is
// already in the store. A record written after the kill resolves passes
// every end-state assertion while still losing that race, so this test
// observes the store at the moment the kill is issued.
// pty:exit can beat the kill promise back; the record must be in the store before the kill or the wake never arms.
const store = createTestStore()
const wt = 'repo1::/path/wt1'
const targetLeaf = '11111111-1111-4111-8111-111111111111'
@@ -3222,8 +3189,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
providerSession: { key: 'session_id', id: 'sess-ordering-1' }
})
expect(suppressionAtKillTime).toBe(true)
// The record must survive the successful kill so the reveal-time wake can
// consume it.
// The record must survive the successful kill so the reveal-time wake can consume it.
const state = store.getState()
expect(state.sleepingAgentSessionsByPaneKey[targetPaneKey]).toBeDefined()
})
@@ -4838,8 +4804,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
})
// Plant one current-tab row and one orphan row. Retained rows render by
// worktreeId, so sleep must sweep both instead of only tab prefixes.
// Retained rows render by worktreeId, so sleep must sweep the orphan row too, not just tab prefixes.
store.getState().retainAgents([
{
entry: {
@@ -4959,8 +4924,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
// Why: sleep folds retained rows too, so the next retention sync must not
// recreate a `done` row from the previous render after the user slept it.
// Why: sleep folds retained rows too, so the next retention sync must not recreate a slept `done` row.
expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBe(true)
})
@@ -4983,8 +4947,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
// Why: an existing suppressor was planted by a prior dismissal flow; sleep
// must not erase it (would resurface a row the user already dismissed).
// Why: a suppressor planted by a prior dismissal must survive sleep, else the dismissed row resurfaces.
expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBe(true)
})
@@ -5038,9 +5001,7 @@ describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
})
})
// Why: CLI-spawned background terminals stamp ORCA_PANE_KEY into the PTY env
// at spawn time. The renderer must adopt the tab under the same id so hook
// events route to the correct slot.
// Why: CLI-spawned terminals stamp ORCA_PANE_KEY at spawn; renderer must adopt the tab under that id so hook events route correctly.
describe('createTab tabId hint', () => {
it('uses the supplied id when no collision exists', () => {
const store = createTestStore()
@@ -214,8 +214,7 @@ describe('removeProject cascade', () => {
expect(mockApi.pty.kill).toHaveBeenCalledWith('pty1')
expect(mockApi.pty.kill).toHaveBeenCalledWith('pty2')
// The tabs are gone before async exit events can close them, so retaining
// their one-shot guards would leak ephemeral PTY ids for the renderer session.
// Tabs are gone before async exit events fire, so retaining one-shot guards would leak ephemeral PTY ids.
expect(s.suppressedPtyExitIds['pty1']).toBeUndefined()
expect(s.suppressedPtyExitIds['pty2']).toBeUndefined()
expect(s.pendingCodexPaneRestartIds['pty1']).toBeUndefined()
@@ -224,8 +223,7 @@ describe('removeProject cascade', () => {
store.getState().clearTabPtyId('tab1', 'pty1')
store.getState().clearTabPtyId('tab2', 'pty2')
// Why: exit IPC can arrive after repo purge but before the mounted pane
// unmounts. A late exit must not recreate an index for a tab with no owner.
// Why: exit IPC can arrive after repo purge but before the pane unmounts; a late exit must not recreate an index for an ownerless tab.
expect(store.getState().ptyIdsByTabId['tab1']).toBeUndefined()
expect(store.getState().ptyIdsByTabId['tab2']).toBeUndefined()
})
@@ -318,9 +316,7 @@ describe('hydrateWorkspaceSession', () => {
expect(s.terminalLayoutsByTabId['tab-valid']).toBeDefined()
expect(s.terminalLayoutsByTabId['tab-invalid']).toBeUndefined()
// Why: with two-phase hydration, workspaceSessionReady stays false after
// hydrateWorkspaceSession. It flips to true in reconnectPersistedTerminals()
// after all eager PTY spawns complete.
// Why: two-phase hydration keeps workspaceSessionReady false until reconnectPersistedTerminals() flips it after eager spawns.
expect(s.workspaceSessionReady).toBe(false)
})
@@ -373,8 +369,7 @@ describe('hydrateWorkspaceSession', () => {
})
it('preserves tabs for a known repo whose worktrees have not loaded yet', () => {
// Why (#1158): empty per-repo worktrees can mean a degraded local fetch or
// SSH reconnect race, not that every persisted tab for the repo is stale.
// Why (#1158): empty per-repo worktrees can mean a degraded fetch or reconnect race, not that persisted tabs are stale.
const store = createTestStore()
const stalledWt = 'repo1::/path/wt1'
@@ -440,8 +435,7 @@ describe('hydrateWorkspaceSession', () => {
})
it('drops tabs when an authoritative scan reports no matching worktrees', () => {
// Why: once git has answered authoritatively, an empty repo list means
// deleted local worktrees, not a startup race.
// Why: once git answers authoritatively, an empty repo list means deleted local worktrees, not a startup race.
const store = createTestStore()
const staleWt = 'repo1::/path/deleted'
@@ -475,9 +469,7 @@ describe('hydrateWorkspaceSession', () => {
})
it('drops tabs for an unknown repo', () => {
// Why: the carve-out only forgives missing worktrees for repos that still
// exist in the repos list. If the user removed the whole repo, its tabs
// are genuinely stale and must be dropped.
// Why: the carve-out only forgives missing worktrees for repos still in the repos list; a removed repo's tabs are genuinely stale.
const store = createTestStore()
const orphanWt = 'repoGone::/path/wt1'
@@ -537,13 +529,10 @@ describe('hydrateWorkspaceSession', () => {
expect(s.activeTabId).toBe('tab1')
expect(s.activeRepoId).toBe('repo1')
// Why: restored tabs receive pendingActivationSpawn so the pane mount's
// reattach (or fresh spawn if the daemon session died) does not count as
// activity and bounce the worktree to the top of Recent.
// Why: pendingActivationSpawn keeps the mount's reattach/respawn from counting as activity and bouncing the worktree up Recent.
expect(s.tabsByWorktree[validWt][0].pendingActivationSpawn).toBe(true)
// The restored-active worktree is marked ever-activated so a later click
// doesn't retag (which would suppress a real codex-restart / new-pane bump).
// Marked ever-activated so a later click doesn't retag and suppress a real codex-restart/new-pane bump.
expect(s.everActivatedWorktreeIds.has(validWt)).toBe(true)
})
})
@@ -773,8 +762,7 @@ describe('hydrateBrowserSession', () => {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
activeWorktreeId: wt,
// Simulate hydrateEditorSession returning {} (no editor files) —
// activeTabTypeByWorktree stays at the initial empty object
// Simulate hydrateEditorSession returning {} (no editor files) — activeTabTypeByWorktree stays empty.
activeTabTypeByWorktree: {}
})
@@ -792,8 +780,7 @@ describe('hydrateBrowserSession', () => {
})
const s = store.getState()
// hydrateBrowserSession must merge 'browser' entries into activeTabTypeByWorktree
// so setActiveWorktree doesn't default to 'terminal' and cause a blank screen
// hydrateBrowserSession must merge 'browser' into activeTabTypeByWorktree, else setActiveWorktree defaults to 'terminal' → blank screen.
expect(s.activeTabTypeByWorktree[wt]).toBe('browser')
expect(s.activeTabType).toBe('browser')
expect(s.activeBrowserTabId).toBe('browser-1')
@@ -1156,20 +1143,13 @@ describe('terminal slice behaviors', () => {
expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalled()
})
// Why: clicking a worktree in the sidebar triggers a generation bump on
// dead-PTY tabs which remounts TerminalPane and fresh-spawns a PTY. That
// fresh spawn calls updateTabPtyId → bumpWorktreeActivity. Without the
// pendingActivationSpawn tag, the just-clicked worktree would be stamped
// with Date.now() and float to the top of Recent on every click. isReattach
// is not set on fresh spawns, so this bug slips past PR 310e9daf.
// Why: a click's fresh spawn on dead-PTY tabs would bump activity and float the worktree up Recent; pendingActivationSpawn prevents it (PR 310e9daf).
it('does not bump lastActivityAt when a click-driven fresh spawn follows setActiveWorktree', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
const originalLastActivityAt = 1000
// Why: a tab with a null ptyId triggers the allDead branch in
// setActiveWorktree, which bumps generation and sets
// pendingActivationSpawn so the subsequent fresh spawn is suppressed.
// Why: a null-ptyId tab hits setActiveWorktree's allDead branch, which tags pendingActivationSpawn to suppress the fresh spawn.
store.setState({
repos: [
{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }
@@ -1224,8 +1204,7 @@ describe('terminal slice behaviors', () => {
updates: expect.objectContaining({ lastActivityAt: expect.any(Number) })
})
)
// The flag is consumed so a later legitimate respawn (codex restart etc.)
// is not silently suppressed as well.
// The flag is consumed so a later legit respawn (codex restart etc.) isn't silently suppressed too.
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined()
})
@@ -1280,13 +1259,7 @@ describe('terminal slice behaviors', () => {
expect(tab.pendingActivationSpawn).toBe(true)
})
// Why: the FIRST activation of a worktree tags every tab — even if tab.ptyId
// already looks live, because reconnectPersistedTerminals can re-populate
// tab.ptyId with a restored daemon session ID before the pane mounts, making
// the upcoming updateTabPtyId look like new activity when it is really just
// the click-driven reattach. Subsequent activations of the SAME worktree
// must NOT re-tag — otherwise a later split-pane spawn or codex restart
// would be silently suppressed.
// Why: first activation tags every tab (even live-looking ptyIds, since reconnect may repopulate before mount); re-activation must not re-tag or it drops later spawns.
it('tags on first activation but not on re-activation', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
@@ -1332,20 +1305,13 @@ describe('terminal slice behaviors', () => {
store.getState().updateTabPtyId('tab-1', 'pty-live')
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined()
// Switch away, then re-activate. The re-activation must NOT tag again,
// or a later legitimate spawn (codex restart, new pane) would be dropped.
// Switch away, then re-activate: re-activation must NOT tag again, or a later legit spawn (codex restart, new pane) is dropped.
store.getState().setActiveWorktree(null)
store.getState().setActiveWorktree(worktreeId)
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined()
})
// Why: re-activating a worktree whose PTYs died while the user was away (e.g.
// relay disconnect, sleep) hits the allDead generation bump, which remounts
// TerminalPane and fresh-spawns a PTY. That respawn is a side-effect of the
// click, not real activity. First-activation tagging doesn't cover it
// (everActivatedWorktreeIds already has the worktree), so without tagging the
// allDead bump the worktree would stamp lastActivityAt and jump to the top of
// Recent on every re-click — the reported "click bounces it to the top" bug.
// Why: re-activating dead-PTY worktrees triggers the allDead respawn (a click side-effect, not activity) that first-activation tagging misses, so tag it too.
it('does not bump lastActivityAt when a re-activation respawns dead PTYs', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
@@ -1365,9 +1331,7 @@ describe('terminal slice behaviors', () => {
})
]
},
// Tab retains a wake-hint ptyId but has no live PTY, and the worktree was
// already activated this session — so this is a re-activation, not a
// first activation.
// Wake-hint ptyId but no live PTY, and worktree already activated this session — a re-activation, not a first activation.
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'wake-hint-session' })]
},
@@ -1396,15 +1360,12 @@ describe('terminal slice behaviors', () => {
})
store.getState().setActiveWorktree(worktreeId)
// The allDead generation bump must tag the tab so the click-driven respawn
// is suppressed, even though this is not the first activation.
// The allDead generation bump must tag the tab so the click-driven respawn is suppressed, even on a non-first activation.
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBe(true)
const sortEpochBeforeSpawn = store.getState().sortEpoch
// Simulate the stale wake-hint reattach failing before TerminalPane falls
// back to a fresh spawn. The clear suppresses its own activity bump without
// consuming the spawn suppression.
// Stale wake-hint reattach fails before a fresh spawn; the clear suppresses its own bump without consuming the spawn suppression.
store.getState().clearTabPtyId('tab-1', 'wake-hint-session')
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBe(true)
@@ -1499,11 +1460,7 @@ describe('terminal slice behaviors', () => {
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined()
})
// Why: first-visit worktrees (no tabs yet) trigger Terminal.tsx's activation
// fallback which calls createTab(). That auto-created tab passes
// pendingActivationSpawn: true so its PTY spawn is suppressed — otherwise
// clicking a never-visited worktree in the sidebar would stamp lastActivityAt
// and reshuffle Recent/Smart (the user-reported bounce ~5s after click).
// Why: first-visit worktrees auto-create a pendingActivationSpawn tab so the spawn doesn't stamp lastActivityAt and bounce Recent.
it('does not bump lastActivityAt when createTab auto-creates for a first-visit worktree', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
@@ -1523,8 +1480,7 @@ describe('terminal slice behaviors', () => {
})
]
},
// No tabs yet — this is a fresh worktree the user is visiting for the
// first time in this session.
// No tabs yet — a fresh worktree visited for the first time this session.
tabsByWorktree: {},
ptyIdsByTabId: {},
activeWorktreeId: worktreeId
@@ -1551,8 +1507,7 @@ describe('terminal slice behaviors', () => {
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined()
})
// Why: real background events (agent output, OSC titles) must still bump
// activity. Only the specific activation-driven spawn is suppressed.
// Why: real background events (agent output, OSC titles) must still bump activity; only activation-driven spawns are suppressed.
it('bumps lastActivityAt for a fresh spawn with no activation tag', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
@@ -1600,11 +1555,7 @@ vi.mock('@/components/terminal-pane/pty-transport', () => ({
describe('reconnectPersistedTerminals', () => {
let ptyIdCounter: number
// Why: reconnect-by-daemon-session-ID is an opt-in path (the experimental
// daemon toggle). These tests exercise that path, so each store created here
// must have the toggle set to true before hydrateWorkspaceSession runs —
// otherwise hydration clears pendingReconnectPtyIdByTabId and tab.ptyId
// never gets rehydrated.
// Why: the daemon toggle must be on before hydration, else hydration clears reconnect state and tab.ptyId never rehydrates.
function createDaemonEnabledStore(): ReturnType<typeof createTestStore> {
return createTestStore()
}
@@ -1658,9 +1609,7 @@ describe('reconnectPersistedTerminals', () => {
const s = store.getState()
expect(s.workspaceSessionReady).toBe(true)
// Why: Option 2 defers actual pty.spawn to connectPanePty. The store
// records daemon session IDs as tab-level ptyIds so connectPanePty
// can pass them as sessionId to the daemon's createOrAttach.
// Why: spawn is deferred to connectPanePty; the store records daemon session IDs as tab-level ptyIds for it to reattach.
expect(s.tabsByWorktree[wt1][0].ptyId).toBe('old-pty-1')
expect(s.tabsByWorktree[wt2][0].ptyId).toBeNull()
expect(s.ptyIdsByTabId.tab1).toEqual(['old-pty-1'])
@@ -1760,8 +1709,7 @@ describe('reconnectPersistedTerminals', () => {
}
})
// No activeWorktreeIdsOnShutdown — simulates session from older build
// The tab still has a ptyId from the raw session data
// No activeWorktreeIdsOnShutdown — simulates a session from an older build.
store.getState().hydrateWorkspaceSession({
activeRepoId: 'repo1',
activeWorktreeId: wt1,
@@ -1956,12 +1904,9 @@ describe('reconnectPersistedTerminals', () => {
const s = store.getState()
// Why: deferred reattach doesn't call spawn — connectPanePty handles it
expect((mockApi.pty as Record<string, unknown>).spawn).not.toHaveBeenCalled()
// Why: reconnect restores the tab-level ptyId so getWorktreeStatus()
// sees the tab as active (green dot) even before the terminal mounts.
// connectPanePty reads ptyIdsByLeafId for per-leaf daemon sessions.
// Why: reconnect restores the tab-level ptyId so getWorktreeStatus() shows active (green dot) before the terminal mounts.
expect(s.tabsByWorktree[wt1][0].ptyId).toBe('daemon-session-B')
// ptyIdsByLeafId preserved from hydration for connectPanePty to consume,
// but legacy pane:* leaves are reminted to durable UUID leaves at hydration.
// ptyIdsByLeafId preserved for connectPanePty; legacy pane:* leaves reminted to durable UUID leaves at hydration.
const layout = s.terminalLayoutsByTabId['tab1']
const bindings = layout.ptyIdsByLeafId ?? {}
expect(Object.keys(bindings)).toHaveLength(2)
@@ -2049,8 +1994,7 @@ describe('hydrateEditorSession', () => {
worktreesByRepo: {
repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
},
// Why: hydrateEditorSession reads activeWorktreeId from the store
// (set by hydrateWorkspaceSession), not from the raw session.
// Why: hydrateEditorSession reads activeWorktreeId from the store (set by hydrateWorkspaceSession), not the raw session.
activeWorktreeId: wt
})
+28 -97
View File
@@ -429,9 +429,7 @@ describe('TabsSlice', () => {
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
// Visit order: ...→t3 (last created)→t1→t3. Closing t3 should jump
// back to t1 (previous), not t2 (the visual right-neighbor after t3's
// removal fallback or left-neighbor).
// Visit order ...→t3→t1→t3; closing t3 should jump to t1 (MRU previous), not the visual neighbor t2.
store.getState().activateTab(t1.id)
store.getState().activateTab(t3.id)
store.getState().closeUnifiedTab(t3.id)
@@ -447,8 +445,7 @@ describe('TabsSlice', () => {
})
it('falls back to neighbor selection when the MRU stack has no prior tab', () => {
// Build state manually so no prior activations have been recorded. This
// mirrors a freshly-hydrated session with only an active tab known.
// Build state manually (no prior activations) — mirrors a freshly-hydrated session with only an active tab known.
const groupId = 'mru-fallback-group'
store.setState({
unifiedTabsByWorktree: {
@@ -526,13 +523,10 @@ describe('TabsSlice', () => {
})
// Second group's MRU tail should be t3.
// Switch focus to the source group so subsequent activations in the
// source group don't pollute the second group's MRU.
// Focus the source group so its activations don't pollute the second group's MRU.
store.getState().activateTab(t1.id)
// Re-focus second group by activating t2, then close t2 — we expect the
// previous tab within the same group (t3), not a neighbor from the
// source group.
// Re-focus the second group via t2, then close it: expect the same-group previous tab (t3), not a source-group neighbor.
store.getState().activateTab(t3.id)
store.getState().activateTab(t2.id)
store.getState().closeUnifiedTab(t2.id)
@@ -586,24 +580,17 @@ describe('TabsSlice', () => {
expect(store.getState().unifiedTabsByWorktree[WT][0].isPreview).toBe(false)
})
// Why: regression guard for "click the tab with a bell and it doesn't go
// away". The tab-strip bell reads from unreadTerminalTabs, keyed by the
// terminal tab's entityId. activateTab receives a *unified* tabId, so the
// clear step must resolve entityId from the unified tab or the flag sticks.
// Why (regression): activateTab gets a *unified* tabId but the bell is keyed by entityId, so it must resolve entityId or the bell won't clear on click.
it('clears unreadTerminalTabs for a terminal tab when its unified tab activates', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
// t2 is active after creation; move focus to t1 so we can mark t2 unread.
store.getState().activateTab(t1.id)
// Mark WT as the active worktree. activateTab's unread-clear is guarded
// on activeWorktreeId so the signal isn't swallowed when activating a
// tab in a hidden worktree. Real-world callers only hit activateTab
// for visible tabs, so this mirrors production conditions.
// Mark WT active: activateTab's unread-clear is guarded on activeWorktreeId so hidden-worktree activations don't swallow the signal.
store.setState({ activeWorktreeId: WT })
// t1.entityId and t2.entityId are the terminal tabIds that
// markTerminalTabUnread / TabBar read from.
// entityId is the terminal tabId that markTerminalTabUnread / TabBar read from.
const t2TerminalId = t2.entityId
store.setState({
unreadTerminalTabs: {
@@ -619,22 +606,14 @@ describe('TabsSlice', () => {
})
})
// ─── markTerminalTabUnread ───────────────────────────────────────
//
// Ghostty "show until interact" model: BEL always marks the tab unread,
// including the currently-focused tab and the active tab of every visible
// split group. The indicator is cleared by user interaction (keystroke,
// click, focus-gain) via clearTerminalTabUnread — NOT by the mark path
// trying to guess whether the user already "sees" the tab.
// Ghostty "show until interact": BEL always marks unread (even focused/visible tabs); only user interaction via clearTerminalTabUnread dismisses it.
describe('markTerminalTabUnread', () => {
it('marks the tab even when it is active in a visible split group of the active worktree', () => {
// Group A: the current worktree's root group, created implicitly by
// createUnifiedTab. Populate it with a terminal tab (tabA).
// Group A: the worktree's root group (implicit from createUnifiedTab), populated with tabA.
const tabA = store.getState().createUnifiedTab(WT, 'terminal')
const groupAId = store.getState().groupsByWorktree[WT][0].id
// Group B: split to the right of Group A, then populate with its own
// terminal tab and focus Group B so tabA is visible-but-not-focused.
// Group B: split right of A, populate + focus it so tabA is visible-but-not-focused.
const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right')
if (!groupBId) {
throw new Error('createEmptySplitGroup returned null')
@@ -643,8 +622,7 @@ describe('TabsSlice', () => {
store.getState().focusGroup(WT, groupBId)
store.setState({ activeWorktreeId: WT })
// Seed the backing legacy terminal tab so markTerminalTabUnread's
// owner-missing guard doesn't short-circuit.
// Seed the backing legacy terminal tab so the owner-missing guard doesn't short-circuit.
store.setState({
tabsByWorktree: {
[WT]: [
@@ -662,9 +640,7 @@ describe('TabsSlice', () => {
}
})
// Fire a bell on Group A's terminal tab. Under ghostty semantics the
// indicator must appear even though that tab is visible — only
// clearTerminalTabUnread (called from onData / pointerdown) dismisses it.
// Fire a bell on Group A's visible tab: under ghostty semantics the indicator still appears — only clearTerminalTabUnread dismisses it.
store.getState().markTerminalTabUnread(tabA.entityId)
expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBe(true)
@@ -677,8 +653,7 @@ describe('TabsSlice', () => {
const groupAId = store.getState().groupsByWorktree[WT][0].id
store.getState().activateTab(tabA1.id)
// Group B split to the right with its own tab (so there are two visible
// groups, matching the split-group condition). Focus Group B.
// Split Group B to the right with its own tab (two visible groups, matching the split-group condition); focus it.
const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right')
if (!groupBId) {
throw new Error('createEmptySplitGroup returned null')
@@ -686,10 +661,7 @@ describe('TabsSlice', () => {
store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId })
store.getState().focusGroup(WT, groupBId)
store.setState({ activeWorktreeId: WT })
// Why: markTerminalTabUnread guards against writing unread for a tab
// that no longer exists in tabsByWorktree. In production, every
// terminal unified tab has a backing legacy terminal tab (createTab
// calls createUnifiedTab with matching ids); seed that invariant here.
// Why: markTerminalTabUnread skips tabs missing from tabsByWorktree, so seed the backing legacy tab that every terminal unified tab has in production.
store.setState({
tabsByWorktree: {
[WT]: [
@@ -713,19 +685,11 @@ describe('TabsSlice', () => {
expect(store.getState().unreadTerminalTabs[tabA2.entityId]).toBe(true)
})
// Why: under the show-until-interact model, BEL fires unconditionally
// even when the user is looking at a non-terminal surface or the tab
// is globally active. This test pins that behavior for the "editor is
// on screen, terminal is offscreen" case — clearly a legitimate unread.
// Why: under show-until-interact, BEL fires unconditionally even on a non-terminal/offscreen surface — a legitimate unread.
it('still marks the tab when the active surface is not terminal', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
// Point global active* at this tab (matches post-activate state) but
// mark a *different* worktree as active so the visible-groups check
// does not apply. The only remaining guard is activeTabType, which
// we set to 'editor' — the user is NOT looking at this terminal.
// Why: seed tabsByWorktree to match the production invariant that
// every terminal unified tab has a backing legacy terminal tab —
// markTerminalTabUnread now guards against a missing owner tab.
// Point active* at this tab but mark a different worktree active (skips the visible-groups check); only activeTabType='editor' remains as a guard.
// Why: seed tabsByWorktree — markTerminalTabUnread guards against a missing owner tab.
store.setState({
activeWorktreeId: 'other-wt::/path/x',
activeTabId: tab.entityId,
@@ -753,9 +717,7 @@ describe('TabsSlice', () => {
it('is a no-op when the tab is already flagged', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
// Why: seed tabsByWorktree so markTerminalTabUnread's owner-missing guard
// (terminals.ts:641-643) doesn't short-circuit — we need to exercise the
// "already flagged" branch further down (terminals.ts:673-676).
// Why: seed tabsByWorktree so the owner-missing guard doesn't short-circuit before we reach the "already flagged" branch.
store.setState({
unreadTerminalTabs: { [tab.entityId]: true as const },
activeTabId: 'something-else',
@@ -784,10 +746,7 @@ describe('TabsSlice', () => {
expect(store.getState().unreadTerminalTabs).toBe(before)
})
// Why: markTerminalTabUnread is agent-agnostic — the working→idle
// transition in onAgentBecameIdle fires once per Claude task and MUST
// raise the dot; blocking it at the store layer would swallow the
// completion signal.
// Why: markTerminalTabUnread is agent-agnostic — blocking the working→idle dot here would swallow the agent's completion signal.
it('marks unread for an agent tab when it is not focused', () => {
const agentTabId = 'agent-tab-1'
store.setState({
@@ -816,11 +775,7 @@ describe('TabsSlice', () => {
})
})
// ─── clearTerminalTabUnread ──────────────────────────────────────────
//
// Called on actual user interaction with a terminal pane (keystroke via
// xterm onData, or pointerdown on the container). Pins the dismissal half
// of the show-until-interact contract.
// Called on real user interaction (xterm onData keystroke or pointerdown) — the dismissal half of show-until-interact.
describe('clearTerminalTabUnread', () => {
it('removes the tab from unreadTerminalTabs', () => {
const tabId = 'bell-tab-1'
@@ -844,12 +799,7 @@ describe('TabsSlice', () => {
})
})
// ─── focusGroup clears unread on focused group's terminal tab ─────────
//
// Regression guard: users clicking a group that already had its tab
// "active" (so activateTab doesn't run) must still dismiss the indicator
// on that group's active terminal tab. Without this, the bell lingers
// until the tab is clicked a second time.
// Regression guard: clicking a group whose tab is already active (no activateTab) must still dismiss the bell, else it lingers until a second click.
describe('focusGroup', () => {
it('does not broadcast active-surface writes when the focused group is already current', () => {
const editorFileId = '/tmp/feature/src/main.ts'
@@ -893,9 +843,7 @@ describe('TabsSlice', () => {
expect(store.getState().activeTabTypeByWorktree).toBe(before.activeTabTypeByWorktree)
})
// Why: focusGroup is fired on every pointerdown within a split group's
// chrome (onPointerDown + onFocusCapture in TabGroupPanel). Clearing the
// tab-level bell here is fine — the user is now looking at this group.
// Why: focusGroup fires on every pointerdown in the group chrome, so clearing the tab-level bell here is safe — the user is now viewing it.
it("clears the tab-level bell on the focused group's active tab", () => {
const tabA = store.getState().createUnifiedTab(WT, 'terminal')
const groupAId = store.getState().groupsByWorktree[WT][0].id
@@ -907,16 +855,13 @@ describe('TabsSlice', () => {
// Focus Group B first so the active group is not A.
store.getState().focusGroup(WT, groupBId)
// Seed tab-level unread on Group A's terminal tab. Also mark WT as the
// active worktree — focusGroup's unread-clear is guarded on
// activeWorktreeId to avoid swallowing bells in hidden worktrees.
// Mark WT active: focusGroup's unread-clear is guarded on activeWorktreeId to avoid swallowing bells in hidden worktrees.
store.setState({
unreadTerminalTabs: { [tabA.entityId]: true as const },
activeWorktreeId: WT
})
// Clicking Group A's chrome re-focuses the group without necessarily
// calling activateTab (its active tab hasn't changed).
// Clicking Group A's chrome re-focuses it without calling activateTab (active tab unchanged).
store.getState().focusGroup(WT, groupAId)
// Tab-level bell cleared — the user is now viewing this tab.
@@ -940,9 +885,7 @@ describe('TabsSlice', () => {
activeWorktreeId: WT
})
// Why: both groups' active tabs are simultaneously visible in a split
// layout, so neither should keep a stale unread bell once the user is
// looking at the workspace.
// Why: both groups' active tabs are visible in a split, so neither keeps a stale unread bell once focused.
store.getState().focusGroup(WT, groupAId)
expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBeUndefined()
@@ -1366,9 +1309,7 @@ describe('TabsSlice', () => {
})
it('syncs isPinned to the TerminalTab in tabsByWorktree (reconcile echo guard)', () => {
// Why: reconcile derives a remote tab's pin from tabsByWorktree[*].isPinned;
// if pin/unpin only touched unifiedTabsByWorktree, an unrelated host
// snapshot would recompute isPinned:false and un-pin during the echo window.
// Why: reconcile derives pin from tabsByWorktree[*].isPinned; without syncing, a host snapshot re-computes isPinned:false and un-pins during the echo window.
const tab = store.getState().createUnifiedTab(WT, 'terminal')
store.setState((state) => ({
tabsByWorktree: {
@@ -2126,11 +2067,7 @@ describe('TabsSlice', () => {
})
it('promotes legacy terminals to the worktree remembered tab, not always the first one', () => {
// Why (regression): selecting a non-first terminal, switching to another
// worktree, then returning must land on the remembered tab. Reconcile
// used to seed a freshly-ensured group with restoredLegacyTabs[0], so the
// remembered selection in activeTabIdByWorktree was silently dropped and
// the worktree always reopened on Terminal 1.
// Why (regression): reconcile seeded the group with restoredLegacyTabs[0], dropping the remembered selection so it always reopened Terminal 1.
const firstTerminalId = 'runtime-terminal-1'
const secondTerminalId = 'runtime-terminal-2'
@@ -2179,13 +2116,7 @@ describe('TabsSlice', () => {
})
it('keeps a sole terminal renderable after its PTY exits so a failed direnv does not strand the worktree', () => {
// Why (regression): a PR worktree's only terminal can die on startup (a
// failing .envrc/direnv). pty-connection keeps that dead pane mounted
// instead of bouncing to Landing; this asserts the supporting invariant —
// once a terminal is promoted to a unified tab, clearing its PTY does NOT
// make it an orphan, so reconcile still reports it renderable (count 1).
// If this regressed to 0, the worktree would auto-respawn or get torn
// down (setActiveWorktree(null)), reintroducing the Landing bounce.
// Why (regression): a promoted terminal whose PTY dies must stay renderable, not orphan and bounce to Landing.
const tab = store
.getState()
.createTab(WT, undefined, undefined, { pendingActivationSpawn: true })
+41 -139
View File
@@ -1,7 +1,4 @@
/* eslint-disable max-lines -- Why: split-tab group state has to update layout,
* per-group focus, and tab membership atomically. Keeping those transitions in
* one slice avoids split-brain behavior between the unified tab model and the
* legacy terminal/editor/browser content slices. */
/* eslint-disable max-lines -- Why: split-tab group state updates layout, focus, and tab membership atomically in one slice to avoid split-brain. */
import type { StateCreator } from 'zustand'
import type { AppState } from '../types'
import type {
@@ -44,8 +41,7 @@ export type TabSplitDirection = 'left' | 'right' | 'up' | 'down'
export type TabsSlice = {
unifiedTabsByWorktree: Record<string, Tab[]>
// Why: signals the matching tab's inline title editor to open. A global
// keyboard shortcut (tab.rename) sets this; the tab clears it on consume.
// Why: id of the tab whose inline title editor should open; shortcut (tab.rename) sets it, the tab clears it on consume.
renamingTabId: string | null
groupsByWorktree: Record<string, TabGroup[]>
activeGroupIdByWorktree: Record<string, string>
@@ -118,8 +114,7 @@ export type TabsSlice = {
setTabLabel: (tabId: string, label: string) => void
/** Set a tab's view mode (terminal vs native chat). Patches only that tab. */
setTabViewMode: (tabId: string, mode: 'terminal' | 'chat') => void
/** Flip a tab between the terminal and native chat renderings. The live
* TerminalPane stays mounted — this only changes which surface is shown. */
/** Flip a tab between terminal and native-chat renderings; the live TerminalPane stays mounted. */
toggleTabViewMode: (tabId: string) => void
setTabCustomLabel: (
tabId: string,
@@ -182,9 +177,7 @@ export type TabsSlice = {
) => void
}
// Why: keep the TerminalTab (tabsByWorktree) pin in sync with the unified-tab
// pin so reconcile's `existing.isPinned` fallback stays authoritative locally.
// Returns an empty patch when the tab isn't a persisted TerminalTab.
// Why: keep the TerminalTab pin in sync with the unified pin so reconcile's existing.isPinned fallback stays authoritative locally.
function patchTerminalTabPinned(
tabsByWorktree: Record<string, TerminalTab[]>,
worktreeId: string,
@@ -203,14 +196,11 @@ function patchTerminalTabPinned(
}
}
// Why: pin is host-authoritative for remote-server tabs, so mirror it to the
// host (like setTabColor) or it's lost on reconnect/restart/other clients.
// Why: pin is host-authoritative for remote-server tabs, so mirror it (like setTabColor) or it's lost on reconnect/other clients.
// Dynamic import keeps this store slice off the runtime layer.
function mirrorTabPinnedToHost(state: AppState, tabId: string, isPinned: boolean): void {
const found = findTabAndWorktree(state.unifiedTabsByWorktree, tabId)
// Why: only terminal tab pins are persisted host-side today (browser/editor
// tracked in #5729), so skip the RPC for other types instead of a no-op round
// trip.
// Why: only terminal tab pins are persisted host-side today (browser/editor in #5729); skip the RPC for other types.
if (
!found ||
found.tab.contentType !== 'terminal' ||
@@ -224,18 +214,15 @@ function mirrorTabPinnedToHost(state: AppState, tabId: string, isPinned: boolean
)
}
// Why: viewMode is host-tracked like color/pin, so mirror the local toggle/set to
// the host or it's lost on reconnect/restart and never reaches paired clients.
// Only the user/RPC-set action path mirrors — never the reconcile that applies a
// host value — so the echoed snapshot can't re-trigger an outbound RPC (no loop).
// Why: viewMode is host-tracked like color/pin, so mirror local sets or they're lost on reconnect and to paired clients.
// Only the action path mirrors (never reconcile applying a host value), so the echoed snapshot can't re-trigger an outbound RPC.
function mirrorTabViewModeToHost(
state: AppState,
tabId: string,
viewMode: 'terminal' | 'chat'
): void {
const found = findTabAndWorktree(state.unifiedTabsByWorktree, tabId)
// Why: only terminal tab viewMode is persisted host-side; skip the RPC for other
// types instead of a no-op round trip.
// Why: only terminal tab viewMode is persisted host-side; skip the RPC for other types instead of a no-op round trip.
if (
!found ||
found.tab.contentType !== 'terminal' ||
@@ -487,9 +474,7 @@ function deriveActiveSurfaceForWorktree(
} else if (hasGroupOwnedSurface) {
activeFileId = fileStillOpen ? restoredFileId : null
activeBrowserTabId = browserTabStillOpen ? restoredBrowserTabId : (browserTabs[0]?.id ?? null)
// Why: when the user focuses an empty split, global shortcuts should
// target that group's default terminal area instead of the previously
// active browser/editor in another group.
// Why: focusing an empty split should target its default terminal area, not the previously active browser/editor in another group.
activeTabType = 'terminal'
} else if (browserTabStillOpen) {
activeFileId = fileStillOpen ? restoredFileId : null
@@ -669,8 +654,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const shouldActivate = init?.activate ?? true
const nextActiveTabId = shouldActivate ? created.id : (group.activeTabId ?? created.id)
const sanitizedRecent = sanitizeRecentTabIds(group.recentTabIds, nextOrder)
// Why: automation-created browser tabs need to exist and paint without
// stealing the visible group selection from the user's current tab.
// Why: automation-created browser tabs must paint without stealing the visible group selection from the user's current tab.
const nextRecent = shouldActivate
? pushRecentTabId(sanitizedRecent, created.id)
: sanitizedRecent
@@ -827,13 +811,8 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
return {}
}
const { tab, worktreeId } = found
// Why: activating a terminal tab dismisses the tab-level bell — the user
// has now moved their eyes to this tab.
//
// Why (activeWorktree guard below): only dismiss the tab-level bell when
// the tab is in the active worktree — otherwise the tab is not visible
// yet and the signal would be lost before the user saw it. Mirrors the
// guard in focusGroup.
// Why: activating a terminal tab dismisses its tab-level bell — the user has moved their eyes here.
// Why (activeWorktree guard below): only when the tab is in the active worktree, else the unseen signal is lost (mirrors focusGroup).
const terminalEntityId = tab.contentType === 'terminal' ? tab.entityId : null
const nextUnreadTerminalTabs =
state.activeWorktreeId === worktreeId &&
@@ -861,10 +840,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
? {
...group,
activeTabId: tabId,
// Why: MRU tracks every activation within the group so
// closeUnifiedTab can jump back to the previous tab instead
// of the visual neighbor. Sanitize first to prune ids from
// removed tabs that may have lingered in persisted state.
// Why: track every activation in the group's MRU so closeUnifiedTab returns to the previous tab; sanitize to prune removed ids.
recentTabIds: pushRecentTabId(
sanitizeRecentTabIds(group.recentTabIds, group.tabOrder),
tabId
@@ -877,9 +853,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
...state.activeGroupIdByWorktree,
[worktreeId]: tab.groupId
},
// Why: skip writing unreadTerminalTabs when the reference is unchanged —
// avoids a no-op top-level state allocation that would force re-evaluation
// of full-state selectors. Mirrors focusGroup / reconcileWorktreeTabModel.
// Why: skip writing unreadTerminalTabs when the reference is unchanged, avoiding a no-op alloc that re-runs full-state selectors.
...(nextUnreadTerminalTabs !== state.unreadTerminalTabs
? { unreadTerminalTabs: nextUnreadTerminalTabs }
: {})
@@ -902,8 +876,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
if (tab.contentType === 'terminal' && !opts?.terminalRetirementHandled) {
const dedupedGroupOrder = dedupeTabOrder(group.tabOrder)
const wasLastTab = dedupeTabOrder(dedupedGroupOrder.filter((id) => id !== tabId)).length === 0
// Why: unified-only hydrated tabs still own provider sessions even when
// their legacy terminal row is missing, so every terminal close retires by entity id.
// Why: unified-only hydrated tabs still own provider sessions without a legacy row, so retire every terminal close by entity id.
get().closeTab(tab.entityId, { recordInteraction: opts?.recordInteraction })
return { closedTabId: tabId, wasLastTab, worktreeId }
}
@@ -911,10 +884,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const dedupedGroupOrder = dedupeTabOrder(group.tabOrder)
const remainingOrder = dedupeTabOrder(dedupedGroupOrder.filter((id) => id !== tabId))
const wasLastTab = remainingOrder.length === 0
// Why: when closing the active tab, walk the group's MRU stack back to the
// previously-active tab instead of the visual neighbor. `pickNextActiveTab`
// falls back to pickNeighbor when the MRU is empty (hydrated sessions,
// never-visited siblings) so behavior degrades gracefully.
// Why: on closing the active tab, walk the MRU stack to the previously-active tab; pickNextActiveTab falls back to the neighbor.
const nextActiveTabId =
group.activeTabId === tabId
? wasLastTab
@@ -931,10 +901,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const nextTabs = (current.unifiedTabsByWorktree[worktreeId] ?? []).filter(
(item) => item.id !== tabId
)
// Why: closeUnifiedTab can be invoked without going through terminals.closeTab
// (e.g., close-to-right / close-others gestures via closeOtherTabs and
// closeTabsToRight). The unread-flag map is keyed by terminal entityId and
// would otherwise leak a stale dot for a tab that no longer renders.
// Why: close-to-right/others bypass terminals.closeTab, so clear the entityId-keyed unread flag here or a stale dot leaks.
let nextUnreadTerminalTabs = current.unreadTerminalTabs
if (terminalEntityId && current.unreadTerminalTabs[terminalEntityId]) {
nextUnreadTerminalTabs = { ...current.unreadTerminalTabs }
@@ -978,18 +945,11 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
},
layoutByWorktree: nextLayoutByWorktree,
activeGroupIdByWorktree: nextActiveGroupIdByWorktree,
// Why: skip writing unreadTerminalTabs when the reference is unchanged —
// avoids a no-op top-level state allocation that would force re-evaluation
// of full-state selectors. Mirrors focusGroup / reconcileWorktreeTabModel.
// Why: skip writing unreadTerminalTabs when the reference is unchanged, avoiding a no-op alloc that re-runs full-state selectors.
...(nextUnreadTerminalTabs !== current.unreadTerminalTabs
? { unreadTerminalTabs: nextUnreadTerminalTabs }
: {}),
// Why: the split-group model can legally derive "terminal with no
// active tab" after the final unified tab closes. That leaves the
// worktree selected but render-empty, so the workspace shows a blank
// pane instead of Orca's landing screen. When that happens, write the
// landing-state fallback directly instead of recomputing active-surface
// fields from a worktree that is no longer active.
// Why: closing the last tab can leave the worktree selected but render-empty, so write the landing-state fallback directly.
...(shouldDeactivateWorktree
? {
activeWorktreeId: null,
@@ -1052,9 +1012,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
if (!group) {
continue
}
// Why: drag-and-drop should preserve a single canonical position for
// each tab. Sanitizing here restores the invariant at the store
// boundary so later group operations do not branch on duplicate ids.
// Why: dedupe at the store boundary so each tab keeps one canonical position and later group ops don't branch on duplicate ids.
const nextTabOrder = dedupeTabOrder(tabIds)
reordered = true
const orderMap = new Map(nextTabOrder.map((id, index) => [id, index]))
@@ -1099,13 +1057,10 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
if (!found) {
return {}
}
// Why: default is 'terminal' for legacy/missing, so the first toggle flips
// to 'chat'. patchTab mutates only this tab, leaving split siblings intact.
// Why: viewMode defaults to 'terminal' for legacy/missing, so the first toggle flips to 'chat'.
const fromMode: 'terminal' | 'chat' = found.tab.viewMode === 'chat' ? 'chat' : 'terminal'
const nextMode = fromMode === 'chat' ? 'terminal' : 'chat'
// Why: `launchAgent` lives on the legacy terminal tab keyed by the unified
// tab's entityId — resolve it here so the toggle telemetry can attribute
// adoption by agent without threading it through every caller.
// Why: launchAgent lives on the legacy terminal tab (keyed by entityId); resolve it here so toggle telemetry can attribute by agent.
const agent =
(state.tabsByWorktree[found.worktreeId] ?? []).find(
(terminal) => terminal.id === found.tab.entityId
@@ -1169,9 +1124,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
...state.unifiedTabsByWorktree,
[worktreeId]: applyTabOrderSortValues(tabs, tabOrder)
},
// Why: reconcile derives a tab's pin from the TerminalTab (tabsByWorktree),
// so mirror the pin there too — otherwise an unrelated host snapshot
// recomputes isPinned:false and visually un-pins during the echo window.
// Why: reconcile derives pin from the TerminalTab, so mirror it there too or a host snapshot recomputes isPinned:false and un-pins during the echo window.
...patchTerminalTabPinned(state.tabsByWorktree, worktreeId, tabId, true),
groupsByWorktree: {
...state.groupsByWorktree,
@@ -1278,9 +1231,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const groupId = createBrowserUuid()
set((state) => ({
// Why: a freshly selected worktree can legitimately have zero tabs, but
// split-group affordances still need a canonical root group so new tabs
// and splits land in a deterministic place like VS Code's editor area.
// Why: a zero-tab worktree still needs a canonical root group so new tabs and splits land in a deterministic place.
groupsByWorktree: {
...state.groupsByWorktree,
[worktreeId]: [{ id: groupId, worktreeId, activeTabId: null, tabOrder: [] }]
@@ -1306,15 +1257,8 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
...state.activeGroupIdByWorktree,
[worktreeId]: groupId
}
// Why: focusing a split group surfaces whichever terminal tab is already
// active in that group, so the tab-level bell is no longer needed.
//
// Why (activeWorktree guard below): only clear unreadTerminalTabs when
// focusing a group within the *active* worktree. If the caller is
// focusing a group in a background worktree, that tab is not visible
// yet — dismissing its bell here would silently swallow the signal
// before the user ever sees the tab. All current callers only fire for
// the active worktree, but this guard prevents future misuse.
// Why: focusing a group surfaces its active terminal tab, so dismiss the tab-level bell.
// Why (activeWorktree guard below): only when the group is in the active worktree, else the unseen tab's bell is swallowed.
if (state.activeWorktreeId !== worktreeId) {
if (groupAlreadyFocused) {
return state
@@ -1365,11 +1309,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
}
return {
...(groupAlreadyFocused ? {} : { activeGroupIdByWorktree: nextActiveGroupIdByWorktree }),
// Why: only write unreadTerminalTabs back into state when it actually
// changed. The IIFE above returns state.unreadTerminalTabs by reference
// on no-op; preserving that reference via conditional spread keeps
// downstream selectors/subscribers from firing spuriously. This matches
// the pattern used by activateTab and closeUnifiedTab.
// Why: only write unreadTerminalTabs when it changed — preserving the reference keeps selectors/subscribers from firing spuriously.
...(nextUnreadTerminalTabs !== state.unreadTerminalTabs
? { unreadTerminalTabs: nextUnreadTerminalTabs }
: {}),
@@ -1396,8 +1336,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
groupId,
remainingGroups[0]?.id ?? null
)
// Why: drop the dead group's recent-quick-command entry so the in-memory
// map can't grow unbounded as users open/close groups.
// Why: drop the dead group's recent-quick-command entry so the map can't grow unbounded as groups open/close.
const { [groupId]: _droppedRecent, ...remainingRecent } = current.recentQuickCommandIdByGroup
return {
groupsByWorktree: { ...current.groupsByWorktree, [worktreeId]: remainingGroups },
@@ -1476,9 +1415,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const dedupedSourceGroupOrder = dedupeTabOrder(sourceGroup.tabOrder)
const sourceOrder = dedupeTabOrder(dedupedSourceGroupOrder.filter((id) => id !== tabId))
// Why: defensive filter so target order can't grow a duplicate if the
// tab id somehow already exists there (stale state, prior bug). See
// dropUnifiedTab for the same guard.
// Why: defensive dedupe so target order can't grow a duplicate id (stale state); see dropUnifiedTab for the same guard.
const targetOrder = dedupeTabOrder(targetGroup.tabOrder.filter((id) => id !== tabId))
const targetIndex = Math.max(
0,
@@ -1499,9 +1436,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
...group,
activeTabId:
group.activeTabId === tabId
? // Why: when the moved tab was active in the source, keep
// MRU-aware selection so the user lands on their previously
// focused tab rather than a visual neighbor.
? // Why: keep MRU-aware selection so the user lands on their previously-focused tab, not a visual neighbor.
pickNextActiveTab(dedupedSourceGroupOrder, sourceGroup.recentTabIds, tabId)
: group.activeTabId,
tabOrder: sourceOrder,
@@ -1603,9 +1538,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
layout
})
) {
// Why: dragging the final tab in a group onto that same group's edge,
// or onto the adjacent sibling's matching edge, creates a transient
// column only to collapse the emptied source immediately.
// Why: dropping a group's last tab on its own/sibling matching edge only makes a transient column that immediately collapses.
return {}
}
@@ -1651,11 +1584,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const sourceOrder = dedupeTabOrder(dedupedSourceGroupOrder.filter((id) => id !== tabId))
const destinationGroup =
nextGroups.find((group) => group.id === resolvedTargetGroupId) ?? targetGroup
// Why: the target group's stored order can already contain this tab id
// from a prior racey write or a same-group split where the source and
// destination transiently share it. Splicing without filtering first
// would leave the same id in the order twice, which React surfaces as
// a duplicate-key warning in TabBar and can mis-reconcile xterm panes.
// Why: target order may already hold this tab id (racey write / same-group split); dedupe first or React hits a duplicate key.
const targetOrder = dedupeTabOrder(destinationGroup.tabOrder.filter((id) => id !== tabId))
const targetIndex = Math.max(
0,
@@ -1673,9 +1602,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
...group,
activeTabId:
group.activeTabId === tabId
? // Why: same MRU-aware fallback as moveUnifiedTabToGroup so
// the pane left behind by a drag keeps the user on their
// previously-active tab.
? // Why: same MRU-aware fallback as moveUnifiedTabToGroup — the drag keeps the user on their previously-active tab.
pickNextActiveTab(dedupedSourceGroupOrder, sourceGroup.recentTabIds, tabId)
: group.activeTabId,
tabOrder: sourceOrder,
@@ -1809,9 +1736,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
return {
layoutByWorktree: {
...state.layoutByWorktree,
// Why: split sizing is part of the tab-group model, not transient UI
// state. Persisting ratios here keeps restores and multi-step group
// operations in sync with what the user actually resized.
// Why: split ratios belong to the tab-group model (not transient UI), so persist them for restores and multi-step group ops.
[worktreeId]: updateSplitRatio(
currentLayout,
nodePath.length > 0 ? nodePath.split('.') : [],
@@ -1834,15 +1759,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
if (unifiedTerminalEntityIds.has(tab.id)) {
return false
}
// Why: this is a one-shot migration filter for tabs not yet promoted
// to unifiedTabs — keeping the wake-hint `tab.ptyId` clause is
// intentional. tab.ptyId is the preserved sessionId (so wake can
// reattach to the same daemon-history dir / relay session); a slept
// tab will have `livePtyIds` empty *and* `tab.ptyId` populated, and
// we want it included in the migration sweep so reconcile picks it
// up. Reconcile fires again post-reattach, so the eventual live PTY
// also routes through this branch. Do *not* repurpose this as an
// "is this tab alive?" check — those reads must use ptyIdsByTabId.
// Why: migration filter — tab.ptyId (preserved sessionId) keeps slept tabs in the sweep for wake reattach; NOT a liveness check (use ptyIdsByTabId).
const livePtyIds = state.ptyIdsByTabId[tab.id] ?? []
return livePtyIds.length > 0 || tab.ptyId != null
})
@@ -1880,10 +1797,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
}))
const reconciledUnifiedTabs =
restoredLegacyTabs.length > 0 ? [...unifiedTabs, ...restoredLegacyTabs] : unifiedTabs
// Why: when a freshly-ensured group has no active tab yet, seed it from the
// worktree's remembered selection before the first restored tab. Otherwise
// returning to a worktree whose terminals only exist in the runtime slice
// always reopens on Terminal 1 and drops the tab the user left on.
// Why: seed a freshly-ensured group's active tab from the remembered selection, else the worktree always reopens on Terminal 1.
const rememberedLegacyActiveTabId = state.activeTabIdByWorktree[worktreeId]
const restoredLegacyTabIds = new Set(restoredLegacyTabs.map((tab) => tab.id))
const legacyFallbackActiveTabId =
@@ -1894,10 +1808,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
restoredLegacyTabs.length > 0 && reconciliationGroup
? updateGroup(ensuredGroupState!.groupsByWorktree[worktreeId] ?? [], {
...reconciliationGroup,
// Why: legacy terminal tabs can still exist in the runtime slice
// after split groups became the source of truth. Restoring them
// into the active/root group keeps existing live PTYs reachable
// instead of making activation spawn a duplicate "Terminal 2".
// Why: restore runtime-slice legacy tabs into the active/root group so live PTYs stay reachable instead of spawning a duplicate.
activeTabId: reconciliationGroup.activeTabId ?? legacyFallbackActiveTabId,
tabOrder: dedupeTabOrder([
...reconciliationGroup.tabOrder,
@@ -1940,9 +1851,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
const tabOrderUnchanged =
tabOrder.length === group.tabOrder.length &&
tabOrder.every((tabId, index) => tabId === group.tabOrder[index])
// Why: reconciliation can drop backing tabs (stale persisted ids, dead
// PTYs, closed editor files). Keep the MRU stack in sync so the next
// close doesn't try to activate a tab the renderer no longer owns.
// Why: keep the MRU stack in sync with dropped tabs so the next close doesn't activate one the renderer no longer owns.
const recentTabIds = sanitizeRecentTabIds(group.recentTabIds, tabOrder)
const recentUnchanged =
recentTabIds.length === (group.recentTabIds ?? []).length &&
@@ -1993,11 +1902,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
layoutChanged ||
orphanTerminalIds.size > 0
) {
// Why: when reconcile drops a unified terminal tab (stale persisted id,
// dead PTY, closed editor), its entry in unreadTerminalTabs (keyed by the
// terminal tab's entityId) would otherwise linger forever and bleed into
// downstream persistence/selectors. Mirrors the cleanup in closeUnifiedTab
// which removes the unread flag when a terminal tab is torn down.
// Why: drop unreadTerminalTabs entries (keyed by entityId) for terminal tabs reconcile removed, or the stale flag lingers forever.
const droppedTerminalEntityIds: string[] = []
for (const tab of unifiedTabs) {
if (tab.contentType !== 'terminal') {
@@ -2036,10 +1941,7 @@ export const createTabsSlice: StateCreator<AppState, [], [], TabsSlice> = (set,
? {
layoutByWorktree: {
...current.layoutByWorktree,
// Why: a restored live runtime terminal needs a concrete leaf
// in the split-group model before activation runs again.
// Without this, the worktree still looks render-empty and the
// activation fallback spawns a duplicate "Terminal 2".
// Why: restored runtime terminal needs a concrete leaf before activation, else the fallback spawns a duplicate "Terminal 2".
[worktreeId]: nextLayout!
}
}
@@ -139,9 +139,7 @@ describe('hydrateWorkspaceSession', () => {
store.getState().hydrateWorkspaceSession(session)
// Why: ptyIdsByLeafId contains daemon session IDs that survive restart.
// reconnectPersistedTerminals uses them to reattach each split-pane
// leaf to its specific daemon session.
// Why: ptyIdsByLeafId holds daemon session IDs that survive restart, letting each split-pane leaf reattach to its own session.
expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({
...makeLayout(),
ptyIdsByLeafId: { 'pane:1': 'daemon-session-1' },
@@ -218,9 +216,7 @@ describe('hydrateWorkspaceSession', () => {
}
})
// Why: `id` keeps the `::workspace:<uuid>` identity suffix, but `path` and
// `displayName` must resolve to the real folder so Git and other filesystem
// callers never spawn against a nonexistent cwd.
// Why: id keeps the ::workspace:<uuid> suffix, but path/displayName must resolve to the real folder so callers don't spawn against a missing cwd.
expect(store.getState().worktreesByRepo['folder-repo']).toEqual([
expect.objectContaining({ id: worktreeId, path: '/home/user', displayName: 'user' })
])
@@ -367,8 +363,7 @@ describe('hydrateWorkspaceSession', () => {
store.getState().hydrateWorkspaceSession(session)
// Why: restart can preserve scrollback for an exited pane while live siblings
// reattach. Keyboard focus must land on a PTY-backed pane, not the dead leaf.
// Why: restart can preserve scrollback for an exited pane, so focus must land on a live PTY-backed pane, not the dead leaf.
expect(store.getState().terminalLayoutsByTabId['tab-1']?.activeLeafId).toBe(liveLeftLeafId)
})
@@ -441,8 +436,7 @@ describe('hydrateWorkspaceSession', () => {
await store.getState().reconnectPersistedTerminals()
unsubscribe()
// Why: startup restores every daemon wake hint, but subscribers should see
// one ready-state transition instead of one update per restored tab.
// Why: startup restores every daemon wake hint, but subscribers should see one ready-state transition, not one update per restored tab.
expect(updateCount).toBe(1)
expect(store.getState().workspaceSessionReady).toBe(true)
expect(store.getState().ptyIdsByTabId).toMatchObject({
@@ -458,11 +452,7 @@ describe('hydrateWorkspaceSession', () => {
})
it('stashes deferred SSH session ids for worktrees not yet in worktreesByRepo', async () => {
// Why: at cold start SSH worktrees are absent from worktreesByRepo (relay
// discovery needs the connection). The deferred stash must fall back to
// the repo id embedded in the composite worktree id — otherwise restored
// SSH panes fresh-spawn into a missing PTY provider and strand an
// "SSH connection is not active" toast.
// Why: at cold start SSH worktrees aren't in worktreesByRepo, so the stash must fall back to the repo id embedded in the composite worktree id — else restored panes strand an "SSH connection is not active" toast.
const store = createTestStore()
const worktreeId = 'repo1::/home/user/remote-project'
const sshSessionId = 'ssh:ssh-target-1@@pty-7'
@@ -547,11 +537,7 @@ describe('hydrateWorkspaceSession', () => {
})
it('seeds worktree nav history with the restored active worktree', () => {
// Why: without seeding, the first sidebar click after startup becomes the
// only history entry, so Back stays disabled until the user clicks a
// second worktree. Seeding here ensures the restored worktree is already
// at index 0 so the very first user-driven switch has a prior entry to
// go Back to.
// Why: seeding the restored worktree at index 0 gives the first user switch a prior entry, so Back isn't disabled until a second click.
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
@@ -607,10 +593,7 @@ describe('hydrateWorkspaceSession', () => {
const store = createTestStore()
seedStore(store, { worktreesByRepo: {} })
// Why: pre-seed non-default stale values so the assertions below can only
// pass if hydration actively overwrites the fields. Without this, the
// slice's default `[]` / `-1` would satisfy the expectations even if
// hydrateWorkspaceSession never touched nav history in this branch.
// Why: pre-seed stale values so the assertions can only pass if hydration actively overwrites nav history in this branch.
store.setState({ worktreeNavHistory: ['stale-a', 'stale-b'], worktreeNavHistoryIndex: 1 })
const session: WorkspaceSessionState = {
@@ -628,17 +611,11 @@ describe('hydrateWorkspaceSession', () => {
})
it('drops invalid restored worktree from nav history seed', () => {
// Why: hydrateWorkspaceSession validates activeWorktreeId against the
// current worktreesByRepo and sets it to null when stale. The history
// seed must follow that validation, not the raw session field — otherwise
// a deleted worktree would sit at history[0] and fail activation on Back.
// Why: the history seed must follow the validated activeWorktreeId (nulled when stale), or a deleted worktree sits at history[0] and fails Back.
const store = createTestStore()
seedStore(store, { worktreesByRepo: { repo1: [] } })
// Why: pre-seed non-default stale values so the assertions below can only
// pass if hydration actively overwrites the fields. Without this, the
// slice's default `[]` / `-1` would satisfy the expectations even if
// hydrateWorkspaceSession never cleared nav history for an invalid worktree.
// Why: pre-seed stale values so the assertions can only pass if hydration actively clears nav history for the invalid worktree.
store.setState({ worktreeNavHistory: ['stale-a', 'stale-b'], worktreeNavHistoryIndex: 1 })
const session: WorkspaceSessionState = {
@@ -657,11 +634,7 @@ describe('hydrateWorkspaceSession', () => {
})
it('records a subsequent visit on top of the hydration seed so Back is enabled after the first click', () => {
// Why: pins down the PR's user-visible contract — after hydration seeds
// the restored worktree at index 0, the very first sidebar click appends
// a new entry at index 1, which is what makes Back enabled immediately.
// Without the seed, the first click would produce a single-entry history
// and Back would stay disabled until a second click.
// Why: the hydration seed at index 0 lets the first sidebar click enable Back immediately (without it, Back needs a second click).
const store = createTestStore()
const wt1 = 'repo1::/wt-1'
const wt2 = 'repo1::/wt-2'
@@ -693,10 +666,7 @@ describe('hydrateWorkspaceSession', () => {
describe('hydrationSucceeded flag (issue #1158)', () => {
it('defaults to false so the session writer is gated off at startup', () => {
// Why: App.tsx only flips hydrationSucceeded=true after a clean load from
// orca-data.json. If a startup error prevents that call, the flag stays
// false and the debounced writer never fires — protecting the user's good
// on-disk state from being overwritten with an empty in-memory snapshot.
// Why: default false so a startup error keeps the debounced writer gated off, protecting good on-disk state from an empty snapshot.
const store = createTestStore()
expect(store.getState().hydrationSucceeded).toBe(false)
})
@@ -710,10 +680,7 @@ describe('hydrationSucceeded flag (issue #1158)', () => {
})
it('hydrateWorkspaceSession does not flip hydrationSucceeded on its own', () => {
// Why: the hydration call can populate state partially and still throw
// downstream (e.g. reconnect fails). Leaving the flip to App.tsx — after
// hydrateWorkspaceSession has returned without throwing — keeps the gate
// honest in those mid-flight failures.
// Why: hydration can populate state then throw downstream, so App.tsx flips the flag only after a clean return.
const store = createTestStore()
const wt = 'repo1::/wt'
seedStore(store, {
File diff suppressed because it is too large Load Diff
+66 -214
View File
@@ -237,9 +237,7 @@ function clampPetSize(size: number): number {
return Math.max(PET_SIZE_MIN, Math.min(PET_SIZE_MAX, Math.round(size)))
}
// Why: mirrors the preset→query mapping used by TaskPage's preset buttons.
// Keeping a local copy here avoids a store ↔ lib circular import while letting
// openTaskPage warm exactly the cache key the page will read on mount.
// Why: local copy of TaskPage's preset→query mapping avoids a store ↔ lib circular import while warming the exact cache key.
function presetToQuery(presetId: TaskViewPresetId | null): string {
switch (presetId) {
case 'all':
@@ -258,10 +256,7 @@ function presetToQuery(presetId: TaskViewPresetId | null): string {
}
}
// Why: persisted UI state pre-dated the consolidation of `memory` + `sessions`
// into a single `resource-usage` entry. Rewrite legacy ids in place and
// de-duplicate. We leave unknown ids alone so a downgrade→upgrade cycle
// doesn't strip a newer build's ids out of the user's settings.
// Why: migrate legacy memory+sessions ids → resource-usage; keep unknown ids so downgrade→upgrade can't strip a newer build's ids.
function migrateStatusBarItems(items: readonly string[] | undefined): StatusBarItem[] {
const source = items ?? DEFAULT_STATUS_BAR_ITEMS
const out: string[] = []
@@ -291,17 +286,10 @@ function normalizeHydratedVisibleWorkspaceHostIds(ui: PersistedUIState): Visible
const MIN_SIDEBAR_WIDTH = 220
const MAX_LEFT_SIDEBAR_WIDTH = 500
// Why: the right sidebar drag-resize is window-relative (see right-sidebar
// component), so persisted widths can legitimately be well above the old 500px
// cap on wide displays. Use a large hard ceiling purely as a safety net for
// corrupted/manually-edited values rather than as a product limit.
// Why: right-sidebar resize is window-relative, so widths can far exceed 500px on wide displays; this ceiling is only a corruption safety net.
const MAX_RIGHT_SIDEBAR_WIDTH = 4000
const LINEAR_TASK_PREFETCH_LIMIT = 36
// Why: bound disk growth for acknowledgedAgentsByPaneKey across hard quits —
// in-session cleanup (agent-status.ts) prunes on pane lifecycle, but crash/
// forced-kill paths leave entries pinned. Mirrors HYDRATE_MAX_AGE_MS in
// src/main/agent-hooks/server.ts for parallel reasoning with the sibling
// hook-status entries these acks pair with.
// Why: bound disk growth across hard quits (crash paths leave acks pinned); mirrors HYDRATE_MAX_AGE_MS in agent-hooks/server.ts.
const HYDRATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
const VALID_TASK_PRESETS = new Set<TaskViewPresetId>([
'all',
@@ -439,10 +427,7 @@ function sanitizePersistedSidebarWidth(width: unknown, fallback: number, maxWidt
return Math.min(maxWidth, Math.max(MIN_SIDEBAR_WIDTH, width))
}
// Why: persisted JSON can be tampered with or carry legacy/corrupt shapes.
// Reject arrays (typeof [] === 'object'), prototype-pollution keys, and
// non-positive-finite values; drop entries past the TTL so hard-quit leaks
// don't accumulate forever.
// Why: persisted JSON may be tampered/corrupt — reject arrays, prototype-pollution keys, and non-finite values; drop past-TTL entries.
function sanitizeAcknowledgedAgentsByPaneKey(value: unknown): Record<string, number> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return {}
@@ -513,9 +498,7 @@ function sanitizeHydratedActiveView(
if (!isTopLevelView(value)) {
return 'terminal'
}
// Why: activity is hidden when its setting is off, so restoring it lands on a
// hidden page (same guard as closeSettingsPage). mobile/automations stay
// functional when hidden, so only activity is gated here.
// Why: activity is hidden when its setting is off, so gate only it (mobile/automations stay functional when hidden).
if (value === 'activity' && !experimentalActivityEnabled) {
return 'terminal'
}
@@ -605,13 +588,7 @@ export type UISlice = {
openAgentSendPopoverTargetMode: (args: OpenAgentSendPopoverTargetModeArgs) => void
closeAgentSendPopoverTargetMode: (id?: string, instanceId?: string) => void
sendPromptToSidebarAgentTarget: (paneKey: string) => Promise<boolean>
/** Per-agent "I've looked at this" timestamps, keyed by paneKey. Set when
* the user clicks an agent row or its parent workspace card from the
* dashboard. A row is considered unvisited when no ack exists OR the
* agent's current stateStartedAt is newer than the last ack (i.e. the
* agent has transitioned state since the user last saw it). Persisted
* via PersistedUIState because agent rows themselves now survive restart —
* without this, rows you'd already visited come back bold on relaunch. */
/** Per-agent "I've looked at this" timestamps (paneKey → ts). A row is unvisited when no ack exists or stateStartedAt is newer than the last ack. Persisted so visited rows don't return bold on relaunch. */
acknowledgedAgentsByPaneKey: Record<string, number>
acknowledgeAgents: (paneKeys: string[]) => void
unacknowledgeAgents: (paneKeys: string[]) => void
@@ -693,8 +670,7 @@ export type UISlice = {
setGithubTaskDrawerWorkItem: (item: GitHubWorkItem | null) => void
newWorkspaceDraft: {
repoId: string | null
// Why: project-first workspace creation resolves through these when present,
// while old drafts can keep using only repoId during the additive migration.
// Why: project-first creation uses these when present; old drafts keep using only repoId during the additive migration.
projectId?: string | null
projectGroupId?: string | null
hostId?: ExecutionHostId | null
@@ -711,21 +687,17 @@ export type UISlice = {
linearIdentifier?: string
linearBranchName?: string
} | null
/** Why: starting from a task must preserve where provider data came from
* separately from the host selected to run the workspace. */
/** Preserve where provider data came from, separately from the host chosen to run the workspace. */
taskSourceContext?: TaskSourceContext | null
agent: TuiAgent
linkedIssue: string
linkedPR: number | null
/** GitLab parallels — number for an issue, iid for an MR. Optional so
* drafts saved before GitLab support keep loading without migration. */
/** GitLab parallels — number for an issue, iid for an MR. Optional so pre-GitLab drafts still load without migration. */
linkedGitLabIssue?: number | null
linkedGitLabMR?: number | null
// Why: repo-scoped start ref selected via the "Start from" picker.
// Absent means "use the repo's effective base ref".
// Why: repo-scoped start ref from the "Start from" picker; absent means "use the repo's effective base ref".
baseBranch?: string
// Why: review-created worktrees can start from a head ref/SHA while Source
// Control must compare against the provider target branch.
// Why: review worktrees start from a head ref/SHA while Source Control compares against the provider target branch.
compareBaseRef?: string
} | null
openTaskPage: (
@@ -765,19 +737,10 @@ export type UISlice = {
} | null
openSettingsTarget: (target: NonNullable<UISlice['settingsNavigationTarget']>) => void
clearSettingsTarget: () => void
/**
* Which host the Projects Settings pane shows for each project, keyed by
* projectId. Set by the pane's "Available Hosts" switcher. Ephemeral on
* purpose — never persisted, so a reload reopens on the project's effective
* host rather than a possibly-dangling selection.
*/
/** Which host the Projects Settings pane shows per project (keyed by projectId). Ephemeral on purpose — never persisted, so reload reopens on the effective host. */
settingsProjectHostSelection: Record<string, ExecutionHostId>
setSettingsProjectHostSelection: (projectId: string, hostId: ExecutionHostId) => void
/**
* One-shot Appearance accordion to expand for nested Settings deep links
* (e.g. Usage percentages lives under Window & Sidebar). Cleared when
* Appearance consumes it.
*/
/** One-shot Appearance accordion to expand for nested Settings deep links (e.g. Usage percentages under Window & Sidebar). Cleared when Appearance consumes it. */
appearanceAccordionDeepLink: 'interface' | 'terminal' | 'window' | null
setAppearanceAccordionDeepLink: (
section: NonNullable<UISlice['appearanceAccordionDeepLink']>
@@ -928,23 +891,17 @@ export type UISlice = {
) => void
setWorkspacePortScanForKey: (key: string, result: WorkspacePortScanResult | null) => void
setWorkspacePortScanRefreshing: (refreshing: boolean) => void
/** Whether the experimental pet overlay is currently visible. Persisted
* so "Hide pet" from the status-bar menu survives reload. Independent
* of the experimentalPet settings flag — the feature flag gates
* whether the overlay can ever render; this controls whether it does now. */
/** Whether the pet overlay is currently visible. Persisted so "Hide pet" survives reload. Independent of the experimentalPet flag (which gates whether it can render at all). */
petVisible: boolean
setPetVisible: (v: boolean) => void
/** Which pet is active — either a bundled id or a custom UUID.
* Persisted alongside petVisible via the PersistedUIState pipeline. */
/** Which pet is active — a bundled id or a custom UUID. Persisted via PersistedUIState. */
petId: string
setPetId: (id: string) => void
/** User-uploaded pet images. Metadata only — bytes live in main's userData. */
customPets: CustomPet[]
addCustomPet: (model: CustomPet) => void
removeCustomPet: (id: string) => void
/** Pet overlay size in CSS pixels (square). User-adjustable from the
* status-bar menu so a too-big imported sprite isn't a stuck-on-screen
* problem. */
/** Pet overlay size in CSS pixels (square). User-adjustable so an oversized imported sprite isn't stuck on screen. */
petSize: number
setPetSize: (size: number) => void
pendingRevealWorktree: PendingSidebarWorktreeReveal | null
@@ -966,10 +923,7 @@ export type UISlice = {
) => void
clearPendingRevealWorktreeId: () => void
clearPendingRevealSidebarRow: () => void
// Why: lets the SourceControl sidebar request that the diff editor scroll
// to a specific note. Cleared by the diff decorator after it reveals the
// line, so the same id can be requested again later without the surface
// seeing a stale value.
// Why: cleared by the diff decorator after it reveals the line, so the same id can be requested again without a stale value.
scrollToDiffCommentId: string | null
setScrollToDiffCommentId: (id: string | null) => void
persistedUIReady: boolean
@@ -980,19 +934,14 @@ export type UISlice = {
hydratePersistedUI: (ui: PersistedUIState, source?: 'startup' | 'sync') => void
updateStatus: UpdateStatus
setUpdateStatus: (status: UpdateStatus) => void
// Why: cached changelog from the last 'available' status so the card still has
// rich content (title/media/description) during downloading, error, and downloaded
// states. Cleared on idle/checking/not-available to prevent stale leakage.
// Why: cache last-'available' changelog so the card keeps rich content while downloading; cleared on idle/checking to avoid staleness.
updateChangelog: ChangelogData | null
// Why: UpdateCard is lazy-loaded, so it may miss the transient
// checking/userInitiated status. Keep manual-check intent in the store until
// the resulting available/error/not-available state can consume it.
// Why: UpdateCard is lazy-loaded and may miss the transient checking status; hold manual-check intent until a terminal state consumes it.
updateUserInitiatedCycle: boolean
dismissedUpdateVersion: string | null
dismissUpdate: (versionOverride?: string) => void
clearDismissedUpdateVersion: () => void
// Why: ephemeral and renderer-only — never persisted and never crosses IPC.
// Resets every session and on every phase transition (see setUpdateStatus).
// Why: ephemeral, renderer-only — never persisted; resets each session and on every phase transition (see setUpdateStatus).
updateCardCollapsed: boolean
setUpdateCardCollapsed: (collapsed: boolean) => void
updateReassuranceSeen: boolean
@@ -1068,9 +1017,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
const target = resolveRunningAgentSendTarget(get(), mode.worktreeId, paneKey)
if (!target || target.status !== 'eligible' || !target.ptyId) {
// Why: live revalidation can lose eligibility after the user opened the
// menu. Treat that like an ineligible row click: keep the picker open and
// let the row title explain the current reason without adding toast noise.
// Why: eligibility can drop after the menu opened; keep the picker open (row title explains) rather than adding toast noise.
return false
}
@@ -1162,13 +1109,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
return s
}
const now = Date.now()
// Why: only allocate a new map (and emit a store update) if at least
// one ack is actually moving forward. Comparing `prev < now` instead
// of `prev !== now` matters because stored values are historical
// timestamps and `Date.now()` advances every millisecond — a strict-
// inequality guard would fire on every call and rewrite the map on
// every dashboard click or auto-ack tick, forcing every subscriber
// (all agent rows, the SidebarHeader count, etc.) to re-render.
// Why: only reallocate if an ack advances; compare prev<now not !== — Date.now() ticks every ms and !== would rewrite the map every call.
let next: Record<string, number> | null = null
for (const key of paneKeys) {
const prev = s.acknowledgedAgentsByPaneKey[key] ?? 0
@@ -1259,12 +1200,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
if (data.openJiraIssue) {
get().recordFeatureInteraction?.('jira-tasks')
}
// Why: record a Tasks visit in the shared back/forward history so the
// titlebar Back/Forward buttons can return to Tasks. All task-source
// variants (github/linear presets) collapse to a single 'tasks' entry;
// the slice's adjacent-entry dedupe drops re-opens. No isNavigatingHistory
// guard needed — back-to-Tasks routes through setActiveView('tasks') and
// never re-enters openTaskPage.
// Why: record a Tasks visit in shared back/forward history; all task-source variants collapse to one deduped 'tasks' entry.
const detailEntry = data.openGitHubWorkItem
? ({
kind: 'task-detail',
@@ -1311,11 +1247,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
state.activeView === 'tasks' ? state.previousViewBeforeTasks : state.activeView,
taskPageData: data
}))
// Why: prefetch the GitHub work-item list in parallel with React's first
// render of the TaskPage — by the time the page's own effect runs, the SWR
// cache is either already populated or the request is in-flight and will
// be deduped. This removes ~300–800ms of perceived latency on initial
// page load.
// Why: prefetch the work-item list during first render so the page's effect hits a warm/in-flight SWR cache (~300–800ms win).
const state = get()
const preferredVisibleTaskProviders = normalizeVisibleTaskProviders(
state.settings?.visibleTaskProviders
@@ -1353,11 +1285,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
const resume = state.taskResumeState
const defaultPreset = state.settings?.defaultTaskViewPreset ?? 'all'
// Why: must match the exact query TaskPage's resume effect mounts with,
// otherwise the warm cache key (e.g. 'is:issue is:open') misses the
// page's actual fetch key and the prefetch is wasted. When the user has
// an explicit custom search (preset === null), preserve it so both sides
// agree.
// Why: must match the query TaskPage's resume effect mounts with, else the warm cache key misses and prefetch is wasted.
const query =
resume?.githubItemsPreset === null
? (resume.githubItemsQuery ?? '').trim()
@@ -1383,8 +1311,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
{ sourceContext }
)
} else {
// Why: TaskPage no longer exposes Linear preset filters; keep warm
// prefetch aligned with the default unsearched issue list.
// Why: TaskPage no longer exposes Linear preset filters; keep prefetch aligned with the default unsearched issue list.
state.prefetchLinearIssues(
{
kind: 'list',
@@ -1405,15 +1332,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
setGithubTaskDrawerWorkItem: (item) => set({ githubTaskDrawerWorkItem: item }),
closeTaskPage: () =>
set((state) => {
// Why: Esc-close from Tasks must rewind the history index if we're
// currently parked on a 'tasks' entry. Without this, A → Tasks → Esc
// leaves the index at the 'tasks' entry, making Back a visual no-op
// (activator re-activates A) and Forward re-opens Tasks. If there is no
// earlier live entry (e.g. history is just ['tasks']), leave the index
// at 0 — setting it to -1 would lose the only forward target, while the
// resulting Back visual no-op self-heals as soon as a real visit records
// a new entry. closeTaskPage never runs from the history-nav path, so no
// isNavigatingHistory guard is needed.
// Why: if parked on a 'tasks' entry, rewind the history index so Back/Forward aren't no-ops; keep 0 if it's the only entry.
const currentEntry = state.worktreeNavHistory[state.worktreeNavHistoryIndex]
let nextHistoryIndex = state.worktreeNavHistoryIndex
if (
@@ -1511,15 +1430,11 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
setNewWorkspaceDraft: (draft) => set({ newWorkspaceDraft: draft }),
clearNewWorkspaceDraft: () => set({ newWorkspaceDraft: null }),
openSettingsPage: () => {
// Why: settings search is a transient page filter; opening Settings
// should never inherit hidden sections from the previous visit.
// Why: settings search is a transient filter; opening Settings shouldn't inherit hidden sections from last visit.
get().setSettingsSearchQuery('')
set((state) => ({
activeView: 'settings',
// Why: Settings is a temporary detour from either terminal or the
// full-page tasks view. Preserve the originating view so the Settings
// back action restores an in-progress workspace draft instead of always
// dumping the user into terminal.
// Why: preserve the originating view so Settings back returns there (e.g. in-progress draft), not always terminal.
previousViewBeforeSettings:
state.activeView === 'settings' ? state.previousViewBeforeSettings : state.activeView
}))
@@ -1537,8 +1452,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
openSettingsTarget: (target) => set({ settingsNavigationTarget: target }),
clearSettingsTarget: () => set({ settingsNavigationTarget: null }),
settingsProjectHostSelection: {},
// Why: renderer-only, never persisted — no window.api.ui.set here and this
// field is intentionally absent from the debounced UI writer in App.tsx.
// Why: renderer-only, never persisted — no window.api.ui.set, and absent from the debounced UI writer in App.tsx.
setSettingsProjectHostSelection: (projectId, hostId) =>
set((s) =>
s.settingsProjectHostSelection[projectId] === hostId
@@ -1623,8 +1537,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
persistPromise = persist.catch(console.error)
}
if (tourProgression === 'reveal-sidebar-and-advance') {
// Why: the split can be triggered by keyboard/menu paths while the
// sidebar is closed, but the next tour target lives in the sidebar.
// Why: split can fire from keyboard/menu with the sidebar closed, but the next tour target lives in the sidebar.
return {
featureInteractions: next,
sidebarOpen: true,
@@ -1978,8 +1891,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
window.api.ui.set({ projectOrderManualDefaultNoticeDismissed: true }).catch(console.error)
return { projectOrderManualDefaultNoticeDismissed: true }
}),
// Why: defaults true so pre-hydration / brand-new sessions never flash the
// change notice before persistence resolves eligibility.
// Why: default true so pre-hydration / new sessions never flash the change notice before persistence resolves.
usagePercentageDisplayChangeNoticeDismissed: true,
dismissUsagePercentageDisplayChangeNotice: () =>
set((s) => {
@@ -2000,9 +1912,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
}),
groupBy: 'repo',
// Why: group keys are mode-specific (e.g. repo id vs PR status), so
// collapsed state from one mode is meaningless in another. Clearing
// also prevents unbounded accumulation of stale keys across mode switches.
// Why: group keys are mode-specific, so clear collapsed state on mode switch — stale keys are meaningless and accumulate.
setGroupBy: (g) => {
window.api.ui.set({ groupBy: g, collapsedGroups: [] }).catch(console.error)
set({ groupBy: g, collapsedGroups: new Set<string>() })
@@ -2011,8 +1921,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
sortBy: 'recent',
setSortBy: (s) => set({ sortBy: s }),
// Why: like setSortBy, this is a bare set — it persists only via the
// debounced window.api.ui.set writer in App.tsx, not on its own.
// Why: bare set — persists only via the debounced window.api.ui.set writer in App.tsx, not on its own.
projectOrderBy: 'manual',
setProjectOrderBy: (p) => set({ projectOrderBy: p }),
@@ -2023,8 +1932,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
setShowSleepingWorkspaces: (v) => set({ showSleepingWorkspaces: v }),
workspaceHostScope: 'all',
// Why (multi-host design): host scope is presentation/filtering only — it must
// never trigger resource teardown (terminals, browser pages, etc.).
// Why: host scope is presentation/filtering only — must never trigger resource teardown (terminals, browser pages).
setWorkspaceHostScope: (scope) => {
const normalized = normalizeExecutionHostScope(scope)
const visibleWorkspaceHostIds = normalized === 'all' ? null : [normalized]
@@ -2036,8 +1944,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
visibleWorkspaceHostIds: null,
setVisibleWorkspaceHostIds: (ids) => {
const normalized = normalizeVisibleExecutionHostIds(ids)
// Why: workspaceHostScope remains the compatibility/default-host signal
// for creation flows while visibility can now be multi-select.
// Why: workspaceHostScope stays the compat/default-host signal for creation flows; visibility can now be multi-select.
let workspaceHostScope: WorkspaceHostScope = get().workspaceHostScope
if (normalized === null) {
workspaceHostScope = 'all'
@@ -2190,8 +2097,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
usagePercentageDisplay: DEFAULT_USAGE_PERCENTAGE_DISPLAY,
setUsagePercentageDisplay: (display) => {
const normalized = normalizeUsagePercentageDisplay(display)
// Why: changing the control is the discovery path; permanently dismiss the
// one-time change notice so it does not reappear after the user adapted.
// Why: changing the control is the discovery path, so permanently dismiss the one-time change notice.
window.api.ui
.set({
usagePercentageDisplay: normalized,
@@ -2237,8 +2143,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
}
return { workspacePortScan: scan }
}),
// Why: host-set changes must remove stale per-host scans in one store update so a
// large disconnected host set cannot fan out map notifications to every subscriber.
// Why: drop stale per-host scans in one store update so a large host set can't fan out notifications to every subscriber.
replaceWorkspacePortScans: (scansByKey, projection) =>
set((state) => {
if (
@@ -2274,9 +2179,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
}),
setWorkspacePortScanRefreshing: (refreshing) => set({ workspacePortScanRefreshing: refreshing }),
// Why: default true so a user who enables experimentalPet sees the
// pet immediately. Hide pet from the status-bar menu flips this
// to false; the value is persisted via the standard PersistedUIState pipeline.
// Why: default true so enabling experimentalPet shows the pet immediately (persisted; "Hide pet" flips it false).
petVisible: true,
setPetVisible: (v) => {
window.api.ui.set({ petVisible: v }).catch(console.error)
@@ -2310,11 +2213,9 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
return s
}
const next = s.customPets.filter((m) => m.id !== id)
// Why: if the user removes the currently-active custom pet, fall
// back to the bundled default so the overlay doesn't render nothing.
// Why: removing the active custom pet falls back to bundled default so the overlay isn't empty.
const fallback = s.petId === id ? DEFAULT_PET_ID : s.petId
// Why: send a single combined IPC update so customPets and
// petId persist atomically when both change.
// Why: single combined IPC update so customPets and petId persist atomically.
const ipcPayload: { customPets: CustomPet[]; petId?: string } = {
customPets: next
}
@@ -2322,13 +2223,9 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
ipcPayload.petId = fallback
}
window.api.ui.set(ipcPayload).catch(console.error)
// Why: revoke the cached blob: URL so the underlying Blob is released;
// otherwise it stays in memory for the rest of the session.
// Why: revoke the cached blob: URL so the Blob is released, not leaked for the session.
revokeCustomPetBlobUrl(id)
// Why: best-effort — the bytes are owned by main. If the disk delete
// fails, the orphaned image stays in userData; each import uses a fresh
// UUID so the file won't be hit again, and the renderer's metadata
// index no longer references it.
// Why: best-effort delete — bytes owned by main; fresh-UUID imports mean an orphaned file is never re-referenced.
window.api.pet.delete(id, target.fileName, target.kind).catch(console.error)
const partial: Partial<UISlice> = { customPets: next }
if (fallback !== s.petId) {
@@ -2372,23 +2269,14 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
const orderedRepos = applyManualRepoOrder(s.repos, manualRepoOrder)
const validRepoIds = new Set(s.repos.map((repo) => repo.id))
const persistedFilterRepoIds = sanitizePersistedRepoIds(ui.filterRepoIds)
// Why: persisted UI from pre-rename builds used sidekick* keys. Read
// those only as fallbacks so new pet* writes win immediately after upgrade.
// Why: pre-rename builds used sidekick* keys; read as fallback only so new pet* writes win after upgrade.
const customPets = Array.isArray(ui.customPets)
? ui.customPets
: Array.isArray(ui.customSidekicks)
? ui.customSidekicks
: []
const petId = ui.petId ?? ui.sidekickId
// Migration history:
// v1: sort was called 'smart' internally
// v2: renamed 'smart' → 'recent' (same weighted-score behavior)
// v3: 'smart' reintroduced as the weighted-score sort, 'recent' becomes
// a last-activity sort (worktree.lastActivityAt descending). The
// one-shot migration from old 'recent' to 'smart' happens in the
// main process (persistence.ts load()) using the _sortBySmartMigrated
// flag — not here — so that users who intentionally select the new
// 'recent' sort keep it across restarts.
// Migration: one-shot old-'recent'→'smart' runs in main (_sortBySmartMigrated), not here, so a deliberate 'recent' choice survives restart.
const sortBy = ui.sortBy
const migratedStatusBarItems = migrateStatusBarItems(ui.statusBarItems)
const statusBarItemsWithPorts =
@@ -2435,10 +2323,7 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
ui.rightSidebarExplorerView
)
const hydrated = {
// Why: persisted UI data comes from disk and may be stale, corrupted,
// or manually edited. Clamp widths during hydration so invalid values
// cannot push the renderer into broken layouts before the user drags a
// sidebar again.
// Why: persisted widths may be stale/corrupt/hand-edited; clamp during hydration so invalid values can't break layout.
sidebarWidth: sanitizePersistedSidebarWidth(
ui.sidebarWidth,
s.sidebarWidth,
@@ -2459,28 +2344,22 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
rightSidebarExplorerView: rightSidebarRoute.rightSidebarExplorerView,
groupBy: (ui.groupBy as UISlice['groupBy'] | 'parent') === 'parent' ? 'repo' : ui.groupBy,
sortBy,
// Why: main-process getUI() already normalized this to a valid value
// (defaulting to 'manual'); read it through without migrating sortBy.
// Why: main-process getUI() already normalized this (defaulting to 'manual'); read it through without migrating.
projectOrderBy: ui.projectOrderBy,
// Why: Active-only was retired. Force the old persisted flag off so an
// old profile cannot invisibly keep narrowing the workspace list.
// Why: Active-only was retired; force the old flag off so an old profile can't invisibly narrow the workspace list.
showActiveOnly: false,
// Why: `hideSleepingWorkspaces` is the canonical negative-form filter.
// Older positive-form keys are intentionally ignored so old profiles
// start from the new default: sleeping workspaces visible.
// Why: ignore older positive-form keys so old profiles start from the new default (sleeping workspaces visible).
showSleepingWorkspaces: !(ui.hideSleepingWorkspaces ?? DEFAULT_HIDE_SLEEPING_WORKSPACES),
workspaceHostScope: normalizeExecutionHostScope(ui.workspaceHostScope),
visibleWorkspaceHostIds: normalizeHydratedVisibleWorkspaceHostIds(ui),
workspaceHostOrder: normalizeExecutionHostOrder(ui.workspaceHostOrder),
manualRepoOrder,
// Why: UI state can arrive after a catalog or from another client; apply
// the desktop-owned overlay immediately instead of waiting for a refetch.
// Why: apply the desktop-owned overlay immediately since UI state can arrive after a catalog or from another client.
repos: orderedRepos,
hideDefaultBranchWorkspace: ui.hideDefaultBranchWorkspace ?? false,
hideAutomationGeneratedWorkspaces: ui.hideAutomationGeneratedWorkspaces === true,
showDotfilesByWorktree: sanitizeShowDotfilesByWorktree(ui.showDotfilesByWorktree),
// Why: startup hydrates UI before repo catalogs now. With no catalog
// loaded yet, defer repo-filter validation to the all-host repo refresh.
// Why: startup hydrates UI before repo catalogs, so defer repo-filter validation to the all-host refresh.
filterRepoIds:
validRepoIds.size === 0
? persistedFilterRepoIds
@@ -2498,15 +2377,11 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
statusBarItems: statusBarItemsWithGrok,
statusBarVisible: ui.statusBarVisible ?? true,
usagePercentageDisplay: normalizeUsagePercentageDisplay(ui.usagePercentageDisplay),
// Why: absent → true so existing users see the pet the first time
// they enable the experimental flag. Only an explicit Hide pet
// dismissal persists a `false` value.
// Why: default true so existing users see the pet on first enabling the flag; only an explicit Hide persists false.
petVisible: ui.petVisible ?? ui.sidekickVisible ?? true,
petSize: clampPetSize(ui.petSize ?? ui.sidekickSize ?? PET_SIZE_DEFAULT),
customPets,
// Why: accept the persisted id if it matches a bundled pet or a
// known custom one; otherwise fall back so the overlay never renders
// nothing (e.g. custom pet was removed by another session).
// Why: fall back to default when the persisted id is unknown (e.g. custom pet removed elsewhere) so the overlay renders.
petId: ((): string => {
const id = petId
if (typeof id !== 'string') {
@@ -2551,38 +2426,26 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
mobileEmulatorAgentSetupDismissed: ui.mobileEmulatorAgentSetupDismissed === true,
projectOrderManualDefaultNoticeDismissed:
ui.projectOrderManualDefaultNoticeDismissed === true,
// Why: load() resolves this for existing vs new profiles; treat only
// explicit true as dismissed so a false from migration still surfaces.
// Why: treat only explicit true as dismissed so a false from migration still surfaces.
usagePercentageDisplayChangeNoticeDismissed:
ui.usagePercentageDisplayChangeNoticeDismissed === true,
// Why: default false when undefined so existing users still see the CTA;
// only an explicit dismissal persists true.
// Why: default false so existing users still see the CTA; only explicit dismissal persists true.
usageEmptyStateDismissed: ui.usageEmptyStateDismissed === true,
// Why: restore visited-row acks alongside the persisted hook entries
// they pair with. Stale acks for paneKeys whose tab/PTY no longer
// exists are inert (no row references them); a paneKey reuse stamps a
// fresh stateStartedAt that beats the old ack via the ackAt <
// stateStartedAt comparison in WorktreeCardAgents. Sanitizer drops
// entries past HYDRATE_MAX_AGE_MS so hard-quit/crash paths that miss
// the in-session cleanup in agent-status.ts can't accumulate forever.
// Why: stale acks are inert (paneKey reuse beats them via stateStartedAt); sanitizer bounds growth past HYDRATE_MAX_AGE_MS.
acknowledgedAgentsByPaneKey: sanitizeAcknowledgedAgentsByPaneKey(
ui.acknowledgedAgentsByPaneKey
),
workspaceCleanupDismissals: sanitizeWorkspaceCleanupDismissals(
ui.workspaceCleanup?.dismissals
),
// Why: restore the view only from the startup hydration. The same action also
// runs on every cross-window ui:stateChanged broadcast (source 'sync', the
// default); re-applying activeView there would yank the user's current
// per-window view (navigation state, not a synced preference).
// Why: restore only on startup; on 'sync' broadcasts it would clobber the window's current per-window view.
activeView:
source === 'startup'
? sanitizeHydratedActiveView(ui.activeView, s.settings?.experimentalActivity === true)
: s.activeView,
persistedUIReady: true
}
// Why: main rebroadcasts UI written by any client. Identical hydration must
// not create fresh references that App's debounced writer echoes to main.
// Why: return the same ref on identical hydration so App's debounced writer doesn't echo it back to main.
return hydratedUIPartialMatchesState(s, hydrated) ? s : hydrated
}),
@@ -2603,25 +2466,19 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
update.updateUserInitiatedCycle = false
}
if (status.state === 'available') {
// Why: cache changelog from each 'available' payload so the card retains
// rich content across downloading/error/downloaded transitions. Always
// overwrite (even with null) to prevent a previous rich changelog from
// leaking into a later simple-mode update for a different version.
// Why: always overwrite (even with null) so a prior version's changelog can't leak into a later simple-mode update.
update.updateChangelog = status.changelog ?? null
} else if (
status.state === 'idle' ||
status.state === 'checking' ||
status.state === 'not-available'
) {
// Why: reset on cycle-boundary states so stale rich content from a
// previous update cycle cannot resurface.
// Why: reset on cycle-boundary states so stale rich content from a previous cycle can't resurface.
update.updateChangelog = null
}
// For 'downloading', 'downloaded', 'error': leave updateChangelog untouched
// so the card can keep showing rich content from the original 'available'.
// 'downloading'/'downloaded'/'error': leave updateChangelog untouched to keep the original 'available' content.
if (status.state !== prevState) {
// Why: re-surface the card on every phase transition so a prior collapse
// of `downloading` doesn't bury the `downloaded`/`error` that follows.
// Why: re-surface the card on each phase transition so a collapsed `downloading` doesn't bury `downloaded`/`error`.
update.updateCardCollapsed = false
}
set(update)
@@ -2634,19 +2491,14 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
},
dismissUpdate: (versionOverride?: string) =>
set((s) => {
// Why: the 'error' variant has no version field, so the card passes
// the cached version explicitly via versionOverride.
// Why: the 'error' variant has no version field, so the card passes it via versionOverride.
const dismissedUpdateVersion =
versionOverride ?? ('version' in s.updateStatus ? (s.updateStatus.version ?? null) : null)
const activeNudgeId =
'activeNudgeId' in s.updateStatus ? (s.updateStatus.activeNudgeId ?? null) : null
// Why: dismissing an update is user intent, not transient view state. Persist
// the dismissed version so relaunching the app does not immediately re-show
// the same reminder card until a newer release appears.
// Why: persist dismissal so relaunch doesn't immediately re-show the same card until a newer release.
void window.api.ui.set({ dismissedUpdateVersion }).catch(console.error)
// Why: only dismiss the main-process nudge campaign when the visible card
// actually came from a nudge-driven update cycle. Ordinary update dismissals
// must not consume the active campaign state.
// Why: only consume the nudge campaign for cards from a nudge cycle, not ordinary dismissals.
if (activeNudgeId) {
void window.api.updater.dismissNudge().catch(console.error)
}
@@ -9,17 +9,10 @@ import {
} from '../../../../shared/task-source-context'
import { parseWorkspaceKey } from '../../../../shared/workspace-scope'
// Why: cap the per-session history so a long-lived workspace with many
// worktree jumps cannot grow the array unbounded. 50 is generous enough
// that the cap is never visible in normal use but small enough that the
// linear skip-deleted scan in goBack/goForward stays trivially cheap.
// Why: bound per-session history growth; 50 keeps goBack/goForward's linear scans cheap yet is never hit in normal use.
const MAX_HISTORY = 50
// Why: entries are worktree IDs OR page sentinels for full-page visits.
// The slice, selector, and action names retain the
// "worktree"/"WorktreeHistory" prefix for call-site stability — renaming
// across ~20 sites would churn for no behavior win. View entries are
// always live (never skipped by findPrev/NextLiveWorktreeHistoryIndex).
// Why: entries may be page sentinels, not just worktree IDs; names keep the "worktree" prefix for call-site stability.
export type WorktreeNavHistorySimpleViewEntry = 'tasks' | 'automations'
export type WorktreeNavHistoryTaskDetailEntry =
| {
@@ -55,13 +48,9 @@ export type WorktreeNavHistoryEntry = string | WorktreeNavHistoryViewEntry
export type WorktreeNavHistorySlice = {
// Linear history, oldest -> newest.
worktreeNavHistory: WorktreeNavHistoryEntry[]
// Index into worktreeNavHistory; points at the currently-active entry.
// -1 means empty (no worktree ever activated this session).
// Index into worktreeNavHistory pointing at the active entry; -1 means empty.
worktreeNavHistoryIndex: number
// Why: set while goBack/goForward are calling activateAndRevealWorktree so
// the activation path's recordWorktreeVisit step can skip re-recording a
// history-driven navigation. Kept in-store (rather than as a module-level
// mutable) so tests can drive the slice in isolation.
// Why: true during goBack/goForward so recordWorktreeVisit skips re-recording a history-driven navigation.
isNavigatingHistory: boolean
recordWorktreeVisit: (worktreeId: string) => void
@@ -73,10 +62,7 @@ export type WorktreeNavHistorySlice = {
type ActivateFn = (worktreeId: string) => unknown
type ViewActivateFn = (entry: WorktreeNavHistoryViewEntry) => void
// Why: the slice must call activateAndRevealWorktree from goBack/goForward, but
// importing it directly would create a cycle (activation imports the store).
// Install the reference at module init via setWorktreeNavActivator and keep
// the slice itself unaware of the activation module.
// Why: injected via setWorktreeNavActivator to avoid an import cycle (activation imports the store).
let activator: ActivateFn | null = null
let viewActivator: ViewActivateFn | null = null
@@ -84,15 +70,12 @@ export function setWorktreeNavActivator(fn: ActivateFn | null): void {
activator = fn
}
// Why: installed by App-level init so the slice can dispatch page entries
// to setActiveView(...) without importing the UI slice directly (the UI
// slice already transitively depends on this module via the store creator).
// Why: injected to avoid an import cycle — the UI slice already depends on this module.
export function setWorktreeNavViewActivator(fn: ViewActivateFn | null): void {
viewActivator = fn
}
// Why: view entries short-circuit as live unconditionally — findWorktreeById
// takes a worktree id and would always return undefined for page sentinels.
// Why: view entries count as live unconditionally — findWorktreeById can't resolve page sentinels.
function isViewEntry(entry: WorktreeNavHistoryEntry): entry is WorktreeNavHistoryViewEntry {
return entry === 'tasks' || entry === 'automations' || typeof entry === 'object'
}
@@ -150,22 +133,18 @@ function appendHistoryEntry(
s: { worktreeNavHistory: WorktreeNavHistoryEntry[]; worktreeNavHistoryIndex: number },
entry: WorktreeNavHistoryEntry
): { worktreeNavHistory: WorktreeNavHistoryEntry[]; worktreeNavHistoryIndex: number } {
// Why: re-visiting the same entry must not pollute history. The de-dup
// applies only to the current entry so that A -> B -> A remains a valid
// stack (user left B, returned to A). Same rule covers page re-opens:
// Tasks data changes and repeated Automations opens collapse to one entry.
// Why: de-dup only against the current entry so A -> B -> A stays a valid stack.
const current = s.worktreeNavHistory[s.worktreeNavHistoryIndex]
if (current !== undefined && getHistoryEntryKey(current) === getHistoryEntryKey(entry)) {
return s
}
// Truncate any forward entries, then append and advance the index.
// Truncate forward entries so appending starts a new branch.
const truncated = s.worktreeNavHistory.slice(0, s.worktreeNavHistoryIndex + 1)
truncated.push(entry)
let nextIndex = s.worktreeNavHistoryIndex + 1
// Why: cap eviction drops the oldest entries. The index must shift left
// by the same count so it still points at the just-appended current entry.
// Why: shift index left by the eviction count so it still points at the just-appended entry.
if (truncated.length > MAX_HISTORY) {
const evict = truncated.length - MAX_HISTORY
truncated.splice(0, evict)
@@ -265,44 +244,30 @@ function navigateToIndex(
}
const targetEntry = state.worktreeNavHistory[targetIndex]
// Why: capture-and-restore (not force false) so re-entrant navigation
// (e.g. a store subscriber synchronously triggers another goBack) does
// not race on the boolean — the outer call's `finally` restores its own
// prior value rather than clobbering state set by an inner call.
// Why: capture-and-restore (not force false) so re-entrant navigation doesn't clobber the flag.
const prevNavigating = get().isNavigatingHistory
set({ isNavigatingHistory: true } as Partial<AppState>)
try {
if (isViewEntry(targetEntry)) {
if (!viewActivator) {
// Why: a silent no-op would mean the back/forward chord lands on a
// page history entry and appears broken. See setWorktreeNavActivator
// rationale above.
// Why: warn (not a silent no-op) so a page-entry chord isn't a broken-looking no-op.
console.warn(
`go${direction === 'back' ? 'Back' : 'Forward'}Worktree: view activator not registered`
)
return
}
// Why: dispatch via setActiveView (installed as viewActivator) rather
// than open*Page so we don't mutate previousViewBefore* or fire
// page-open side effects during replay. activateAndRevealWorktree on the
// other branch already switches activeView back to 'terminal'.
// Why: use setActiveView (not open*Page) so replay doesn't mutate previousViewBefore* or fire page-open side effects.
viewActivator(targetEntry)
set({ worktreeNavHistoryIndex: targetIndex } as Partial<AppState>)
} else {
if (!activator) {
// Why: a silent no-op here would mean the back/forward chord simply
// does nothing with no diagnostic. The activator is registered at
// module init by worktree-activation.ts, so a missing activator means
// either test setup forgot to install one or the production import
// graph regressed.
// Why: warn (not a silent no-op) so a missing activator is diagnosable.
console.warn(
`go${direction === 'back' ? 'Back' : 'Forward'}Worktree called before worktree activator was registered`
)
return
}
// Why: activateAndRevealWorktree returns `ActivateAndRevealResult | false`;
// `false` is the only observable failure signal. Advance the index only on
// success so the slice stays consistent with what the user actually sees.
// Why: `false` is the activator's only failure signal — advance the index only on success.
const result = activator(targetEntry)
if (result !== false) {
set({ worktreeNavHistoryIndex: targetIndex } as Partial<AppState>)
+21 -63
View File
@@ -1,7 +1,4 @@
/* eslint-disable max-lines --
* Why: this slice test keeps the worktree store scenarios in one file so the
* shared mock store setup stays consistent across closely related behaviors.
*/
/* eslint-disable max-lines -- keeps all worktree-slice test scenarios in one file for a consistent shared mock store setup. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { create } from 'zustand'
import type { AppState } from '../types'
@@ -127,8 +124,7 @@ function createTestStore() {
return create<AppState>()(
(...a) =>
({
// Why: this test isolates the worktree slice, so it only provides the
// state surface that `createWorktreeSlice` reads and writes.
// Why: this test isolates the worktree slice, so it provides only the state surface createWorktreeSlice touches.
...createWorktreeSlice(...a),
trustedOrcaHooks: {},
repos: [],
@@ -419,8 +415,7 @@ describe('fetchWorktrees', () => {
linkedPR: 101,
pushTarget: { remoteName: 'origin', branchName: 'feature-one' }
})
// Persisted metadata still carries the stale link when the listing refresh
// is the first path to observe the terminal branch switch.
// Persisted metadata still carries the stale link when the listing refresh first observes the terminal branch switch.
const refreshed = makeWorktree({
id: 'repo1::/path/wt1',
repoId: 'repo1',
@@ -1256,8 +1251,7 @@ describe('fetchWorktrees', () => {
expect(mockApi.worktrees.listDetected).toHaveBeenCalledWith({ repoId: 'repo-ssh' })
expect(runtimeEnvironmentCall).not.toHaveBeenCalled()
// Why: SSH worktrees are fetched via local IPC but belong to the SSH host;
// they must carry the repo's ssh host id, not the local default.
// Why: SSH worktrees are fetched via local IPC but belong to the SSH host, so they carry the repo's ssh host id.
expect(store.getState().worktreesByRepo['repo-ssh']).toEqual([
{ ...sshWorktree, hostId: 'ssh:ssh-1' }
])
@@ -1265,8 +1259,7 @@ describe('fetchWorktrees', () => {
it('stamps remote runtime worktrees with the owning repo runtime host', async () => {
const store = createTestStore()
// Why: a remote runtime returns its worktrees from its own perspective, so
// their hostId arrives as the default "local" even though they live remotely.
// Why: a remote runtime returns worktrees from its own perspective, so their hostId arrives as the default "local".
const remote = makeWorktree({
id: 'repo-remote::/remote/wt1',
repoId: 'repo-remote',
@@ -1816,8 +1809,7 @@ describe('worktree lineage state', () => {
repoId: 'repo-remote',
path: '/remote/child'
})
// Why: the remote returns the updated worktree from its own perspective, so
// it arrives with the default local host even though the repo is remote.
// Why: the remote returns the updated worktree from its own perspective, so it arrives with the default local host.
const updatedChild = { ...child, hostId: 'local' as const, lineage }
store.setState({
repos: [
@@ -2965,8 +2957,7 @@ describe('createWorktree base status merge', () => {
id: 'repo-remote::/remote/feature',
repoId: 'repo-remote',
path: '/remote/feature',
// Why: the remote creates the worktree and reports it from its own
// perspective, so it comes back with the default local host.
// Why: the remote reports the worktree from its own perspective, so it comes back with the default local host.
hostId: 'local'
})
store.setState({
@@ -3139,8 +3130,7 @@ describe('createWorktree base status merge', () => {
await store.getState().createWorktree('repo1', 'feature', 'origin/main')
// The button workflow (Keep main up to date / Settings link) lives in the
// toast component's own test; here we just assert the sticky nudge is raised.
// Button workflow is tested in the toast component; here we just assert the sticky nudge is raised.
expect(toast.info).toHaveBeenCalledWith(
'Local main is behind origin/main',
expect.objectContaining({
@@ -3194,8 +3184,7 @@ describe('createWorktree base status merge', () => {
const options = vi.mocked(toast.info).mock.calls.at(-1)?.[1] as unknown as {
onDismiss: () => void
}
// The Turn On success path dismisses the toast, which fires onDismiss; that
// must not be recorded as a decline now that the feature is enabled.
// Turn On dismisses the toast (firing onDismiss); that must not be recorded as a decline.
options.onDismiss()
await Promise.resolve()
@@ -3436,8 +3425,7 @@ describe('removeWorktree state cleanup', () => {
[removed.id]: [makeTerminalTab({ id: 'removed-tab', worktreeId: removed.id })],
[surviving.id]: [makeTerminalTab({ id: 'surviving-tab', worktreeId: surviving.id })]
},
// Split panes write these even when false; only closeTab deleted them
// before, so removeWorktree used to strand them for the whole session.
// Split panes write these even when false; removeWorktree used to strand them (only closeTab deleted them).
expandedPaneByTabId: { 'removed-tab': true, 'surviving-tab': false },
canExpandPaneByTabId: { 'removed-tab': false, 'surviving-tab': true }
} as unknown as Partial<AppState>)
@@ -3721,8 +3709,7 @@ describe('removeWorktree state cleanup', () => {
globalWithDocument.document = originalDocument
}
// The anchor must be captured while the row still exists so the post-delete
// restore pins the pre-removal position instead of the already-shifted list.
// The anchor must be captured while the row still exists so restore pins the pre-removal position.
expect(worktreePresentWhenRecorded).toBe(true)
expect(store.getState().worktreesByRepo.repo1).toEqual([])
})
@@ -3930,12 +3917,7 @@ describe('removeWorktree state cleanup', () => {
})
it('clears recentlyClosedBrowserTabsByWorktree for the removed worktree', async () => {
// Why: closeBrowserTab (which shutdownWorktreeBrowsers delegates to) pushes
// each closed workspace into recentlyClosedBrowserTabsByWorktree for the
// Cmd+Shift+T undo path. When the owning worktree is deleted those
// snapshots reference entities that can never be restored — removeWorktree
// must clear the worktree key symmetrically with browserTabsByWorktree
// (design §1.1).
// Why: undo snapshots for a deleted worktree can never be restored, so removeWorktree clears the key (design §1.1).
const store = createTestStore()
const wt = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' })
@@ -5562,10 +5544,7 @@ describe('worktree remote runtime mutations', () => {
})
})
// Why: ghostty "show until interact" model — BEL must raise the sidebar dot
// even on the active worktree, and only clearWorktreeUnread (called from the
// terminal pane on keystroke / pointerdown) dismisses it. Pins both halves
// of that contract.
// Why: ghostty "show until interact" — BEL raises the dot even on the active worktree; only clearWorktreeUnread clears it.
describe('worktree unread (show-until-interact)', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -5679,12 +5658,7 @@ describe('worktree unread (show-until-interact)', () => {
})
})
// Why: design §4.4 — the hydration-time purge must be gated behind a
// per-repo success check (F1 regression) so a transient git error on one
// repo cannot silently wipe every persisted tabsByWorktree entry for that
// repo. An empty-but-successful fetch from a newly-cloned sibling repo is
// also unsafe to treat as authoritative on its own. Pins both halves of
// that contract plus the happy-path purge.
// Why: design §4.4 — hydration purge gated on per-repo success (F1 regression) so a git error can't wipe tabsByWorktree.
describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -5711,8 +5685,7 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' })
const wtB = makeWorktree({ id: 'repoB::/b/wt1', repoId: 'repoB', path: '/b/wt1' })
// Stub: repoA succeeds; repoB throws. Stale tabsByWorktree entry for
// repoA::/a/stale must NOT be purged while any repo fetch is degraded.
// repoA succeeds, repoB throws; a stale tabsByWorktree entry must NOT be purged while any repo fetch is degraded.
mockApi.worktrees.list.mockImplementation(async ({ repoId }: { repoId: string }) => {
if (repoId === 'repoA') {
return [wtA]
@@ -5756,9 +5729,7 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
it('defers the purge when every repo succeeds but none returns worktrees (empty-sibling safety)', async () => {
const store = createTestStore()
// Both repos succeed but legitimately return empty (newly-cloned). The
// union of valid ids would be empty — declaring that authoritative
// would wipe every persisted tabsByWorktree entry. Must defer instead.
// Empty valid-id union (both repos newly-cloned, empty) isn't authoritative — defer instead of wiping tabsByWorktree.
mockApi.worktrees.list.mockResolvedValue([])
store.setState({
@@ -5906,10 +5877,7 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
})
})
// Why: multi-host regression — once hydration has fired, a mid-session
// fetchAllWorktrees (e.g. triggered by switching focus) must NEVER purge
// terminal state, even if a host transiently reports zero worktrees. The
// hydration-time purge is the only purge path here; it is gated to boot.
// Why: multi-host regression — after hydration a mid-session fetch must never purge, even if a host reports zero worktrees.
it('does not purge another host tab state when hasHydratedWorktreePurge is already true and a host reports zero worktrees', async () => {
const store = createTestStore()
const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' })
@@ -6141,10 +6109,7 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
})
it('does not coalesce a foreground re-probe onto a background reuse:true scan for a remote repo', async () => {
// Why: the reuse flag is part of the coalescing key for remote targets, so a
// foreground fetchWorktrees (reuse:false) must run its own compat-preflighted
// scan instead of sharing a background reuse:true scan that may have reused a
// stale failure — the foreground caller must always re-probe.
// Why: reuse is part of the coalescing key, so a foreground reuse:false scan must re-probe, not reuse a stale background failure.
const store = createTestStore()
const remote = makeWorktree({ id: 'repo1::/remote/wt', repoId: 'repo1', path: '/remote/wt' })
store.setState({
@@ -6307,12 +6272,7 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => {
})
})
// Why: design §4.4 — purgeWorktreeTerminalState wipes every worktree-scoped
// map symmetrically so a single removed-worktree event cannot leave
// per-worktree entries stranded. The full cascade is already covered by
// removeWorktree tests above; this block exercises the action directly to
// confirm cross-map coverage (worktree key, tab id, file id, and top-level
// actives).
// Why: design §4.4 — purgeWorktreeTerminalState wipes every worktree-scoped map symmetrically so no entry is stranded.
describe('purgeWorktreeTerminalState direct (design §4.4)', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -6818,8 +6778,7 @@ describe('setWorktreesPinnedAndReveal', () => {
// Only the focused row is revealed, not the first-changed one.
expect(reveal).toHaveBeenCalledTimes(1)
expect(reveal).toHaveBeenCalledWith(focused.id, { behavior: 'smooth', highlight: true })
// Every targeted row is pinned, not just the revealed one, and the
// already-pinned row is left untouched.
// Every targeted row is pinned, not just the revealed one; the already-pinned row is untouched.
expect(store.getState().worktreesByRepo.repo1[0].isPinned).toBe(true)
expect(store.getState().worktreesByRepo.repo1[1].isPinned).toBe(true)
expect(store.getState().worktreesByRepo.repo1[2].isPinned).toBe(true)
@@ -6957,8 +6916,7 @@ describe('migrateWorktreeIdentity', () => {
expect(s.defaultTerminalTabsAppliedByWorktreeId[NEW]).toBe(true)
// The two maps absent from the purge list are still re-keyed.
expect(s.recentlyClosedEditorTabsByWorktree[NEW]).toEqual([{ id: 'f1', worktreeId: NEW }])
// Terminal reopen snapshots re-key AND remap startupCwd under the old
// worktree path; paths outside the renamed folder stay as-is.
// Terminal reopen snapshots re-key and remap startupCwd under the old path; outside paths stay as-is.
expect(s.recentlyClosedTerminalTabsByWorktree[OLD]).toBeUndefined()
expect(s.recentlyClosedTerminalTabsByWorktree[NEW]).toEqual([
{ startupCwd: '/ws/worktree-creation-spinner/packages/app' },
File diff suppressed because it is too large Load Diff
+42 -99
View File
@@ -1,6 +1,4 @@
/* eslint-disable max-lines -- Why: the web preload adapter is the browser-side
replacement for Electron preload, so the compatibility surface is necessarily
centralized at this boundary. */
/* eslint-disable max-lines -- Why: browser-side Electron-preload replacement; compatibility surface centralizes here. */
import type {
PreloadApi,
PreflightStatus,
@@ -137,8 +135,7 @@ const SESSION_STORAGE_KEY = 'orca.web.workspaceSession.v1'
const ONBOARDING_STORAGE_KEY = 'orca.web.onboarding.v1'
const GITHUB_CACHE_STORAGE_KEY = 'orca.web.githubCache.v1'
const KEYBINDINGS_STORAGE_KEY = 'orca.web.keybindings.v1'
// Why: browser-paired clients need desktop parity for large dev sessions; the
// runtime's no-limit default remains capped for lower-level RPC callers.
// Why: paired clients need parity for large dev sessions; the runtime default stays capped for lower-level RPC callers.
const WEB_RUNTIME_WORKTREE_LIST_LIMIT = 10_000
const MAX_CLIPBOARD_IMAGE_BASE64_CHARS = CLIPBOARD_IMAGE_MAX_BASE64_CHARS
export const MAX_CLIPBOARD_IMAGE_SOURCE_BYTES = CLIPBOARD_IMAGE_MAX_SOURCE_BYTES
@@ -511,8 +508,7 @@ function createWebPreloadApi(): Partial<PreloadApi> {
getFloatingMarkdownDirectory: () => Promise.resolve(''),
pickFloatingMarkdownDocument: () => Promise.resolve(null),
pickFloatingWorkspaceDirectory: () => Promise.resolve(null),
// Browser fallback has no app-owned userData directory; rejecting keeps
// the sentinel from claiming that sensitive evidence was persisted.
// Browser fallback has no app-owned userData dir; reject so the sentinel can't claim sensitive evidence was persisted.
writeTerminalRenderDesyncEvidence: () =>
Promise.reject(
new Error('Terminal render evidence is unavailable in the browser fallback.')
@@ -596,8 +592,7 @@ function createWebPreloadApi(): Partial<PreloadApi> {
},
settings: {
get: async () => getRuntimeBackedStoredSettings(),
// Why: localStorage-backed settings are synchronous in the web client,
// so the pre-hydration kill-switch read works the same as desktop.
// Why: localStorage-backed settings are synchronous, so the pre-hydration kill-switch read works the same as desktop.
getSync: () => getStoredSettings(),
set: async (updates) => {
if (updates.activeRuntimeEnvironmentId === null) {
@@ -652,9 +647,7 @@ function createWebPreloadApi(): Partial<PreloadApi> {
deleteBundle: () => Promise.reject(new Error('Sent diagnostics are unavailable on web.'))
},
session: {
// hostId mirrors the desktop bridge: omitted/'local' targets the existing
// storage key; non-local hosts persist under a host-suffixed key so their
// sessions stay isolated from the local one.
// Mirrors desktop bridge: non-local hosts persist under a host-suffixed key so their sessions stay isolated from local.
get: (hostId) => Promise.resolve(getStoredWorkspaceSession(hostId)),
set: async (session, hostId) => {
writeJson(sessionStorageKeyForHost(hostId), sanitizeWebRuntimeWorkspaceSession(session))
@@ -1096,10 +1089,7 @@ function createWebKeybindingsApi(): WebKeybindingsApi {
}
}
// Why: the desktop reads native-chat transcripts over IPC; the web client has
// no IPC, so route readSession/subscribe through the runtime RPC (the same
// methods the mobile app uses). Without this, window.api.nativeChat was
// undefined on web and the chat view showed no messages.
// Why: web has no IPC for native-chat transcripts, so route readSession/subscribe through runtime RPC (as mobile does).
function createNativeChatApi(): NativeChatApi {
return {
readSession: async (agent, sessionId, limit, transcriptPath) =>
@@ -1112,10 +1102,7 @@ function createNativeChatApi(): NativeChatApi {
})
),
subscribe: (args, onFrame) => {
// No paired runtime yet: nothing to subscribe to, and
// requireActiveEnvironment() would throw. Return a no-op teardown so the
// chat view mounts cleanly until a runtime is paired (only the not-paired
// case is swallowed — real subscribe errors still surface via .catch).
// No paired runtime yet: return a no-op teardown so the chat view mounts cleanly; only the not-paired case is swallowed.
const environment = requireActiveEnvironmentOrNull()
if (!environment) {
onFrame({
@@ -1207,10 +1194,7 @@ function createNativeChatApi(): NativeChatApi {
)
}
} else if (!receivedInitial) {
// Why: an ok response whose payload shape we don't recognize would
// otherwise never flip receivedInitial, stranding the view on
// 'loading'. Settle it with an empty snapshot (carrying any error
// the runtime sent) so the UI resolves.
// Why: an unrecognized ok payload never flips receivedInitial, stranding the view on 'loading'; settle it empty instead.
receivedInitial = true
onFrame({
type: 'snapshot',
@@ -1222,10 +1206,7 @@ function createNativeChatApi(): NativeChatApi {
}
},
{
// Why: send nativeChat.unsubscribe on teardown so the server reaps
// the transcript fs-watcher on view-toggle, not just on socket close
// (the watcher-leak fix). Echo the pane-specific token so two panes
// watching one session cannot tear down each other's watcher.
// Why: unsubscribe reaps the fs-watcher on view-toggle (leak fix); echo the pane token so two panes don't tear down each other's watcher.
buildUnsubscribe: () =>
buildNativeChatUnsubscribe(args.agent, args.sessionId, args.subscriptionId)
}
@@ -1327,8 +1308,7 @@ function createAiVaultApi(): NonNullable<Partial<PreloadApi>['aiVault']> {
if (requestedScope !== 'all' && requestedScope !== executionHostId) {
return Promise.resolve(webAiVaultUnavailableResult(requestedScope))
}
// Why: the browser client has no local filesystem; every history scan
// runs on the paired server and must be stamped as that runtime host.
// Why: no local filesystem in the browser, so every history scan runs on and is stamped as the paired runtime host.
return callRuntimeResult<AiVaultListResult>('aiVault.listSessions', {
limit: args?.limit,
force: args?.force,
@@ -1336,9 +1316,7 @@ function createAiVaultApi(): NonNullable<Partial<PreloadApi>['aiVault']> {
executionHostId
})
},
// Why: the runtime RPC surface only exposes aiVault.listSessions; subagent
// transcript listing has no server-side method yet, so the browser client
// reports an empty (not erroring) result.
// Why: no server-side RPC for subagent transcript listing yet, so report an empty (not erroring) result.
listSubagentSessions: () => Promise.resolve({ sessions: [], issues: [] }),
onWindowFocused: () => noopUnsubscribe
}
@@ -1373,15 +1351,12 @@ function createReposApi(): NonNullable<Partial<PreloadApi>['repos']> {
await callRuntimeResult('repo.rm', { repo: repoId })
invalidateRuntimeWorktreeCaches()
},
// Why: host-scoped forget targets a disconnected/removed SSH host owned by
// the desktop app. A paired web client talks to a single Orca runtime and
// has no ghost-host state to reconcile.
// Why: host-scoped forget targets a desktop-owned SSH host; a paired web client has one runtime and no ghost-host state.
removeForHost: () => {
throw new Error('Forgetting a host is unavailable in paired web clients.')
},
reorder: async ({ orderedIds }) => callRuntimeResult('repo.reorder', { orderedIds }),
// Why: this path persists desktop-owned local or SSH rows. Paired web
// clients own only their single runtime, which uses repo.reorder directly.
// Why: this persists desktop-owned local/SSH rows; paired web clients own one runtime and use repo.reorder directly.
reorderForHost: async () => {
throw new Error('Host-scoped project reordering is unavailable in paired web clients.')
},
@@ -1397,13 +1372,11 @@ function createReposApi(): NonNullable<Partial<PreloadApi>['repos']> {
).repo
},
cloneRemote: async () => {
// Why: SSH relay cloning is owned by the desktop main process; paired web
// clients must not pretend they can run that local IPC path directly.
// Why: SSH relay cloning is owned by the desktop main process; paired web clients can't run that local IPC path.
throw new Error('SSH clone is unavailable in paired web clients.')
},
createRemote: async () => {
// Why: SSH relay project creation is owned by the desktop main process;
// paired web clients cannot create folders through local SSH IPC.
// Why: SSH relay project creation is owned by the desktop main process; paired web clients can't use local SSH IPC.
throw new Error('Creating projects on SSH hosts is unavailable in paired web clients.')
},
cloneAbort: () => Promise.resolve(),
@@ -1515,8 +1488,7 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
automationProvenanceRequest: args.automationProvenanceRequest
})
},
// Why: the runtime create path emits no two-phase progress, so the web
// client's creation panel simply falls back to an indeterminate spinner.
// Why: the runtime create path emits no two-phase progress, so the panel falls back to an indeterminate spinner.
onCreateProgress: () => noopUnsubscribe,
prefetchCreateBase: async ({ repoId, baseBranch }) => {
await callRuntimeResult('worktree.prefetchCreateBase', {
@@ -1548,8 +1520,7 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
runHooks: skipArchive !== true
})
},
// Why: forget-locally clears a workspace pinned to a disconnected/removed
// SSH host on the desktop app; a paired web client has no such ghost state.
// Why: forget-locally clears a desktop workspace pinned to a dead SSH host; a paired web client has no such ghost state.
forgetLocal: () => {
throw new Error('Forgetting a workspace is unavailable in paired web clients.')
},
@@ -1591,8 +1562,7 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
persistSortOrder: async ({ orderedIds }) => {
await callRuntimeResult('worktree.persistSortOrder', { orderedIds })
},
// Why: the capture lives in desktop main memory and is not exposed over
// pairing; the dialog falls back to the persisted excerpt on web clients.
// Why: the capture lives in desktop main memory, unexposed over pairing; the dialog falls back to the persisted excerpt.
getBranchRenameFailureOutput: async () => null,
onChanged: () => noopUnsubscribe,
onGitStatusMetadataChanged: () => noopUnsubscribe,
@@ -1736,8 +1706,7 @@ function createFileApi(): NonNullable<Partial<PreloadApi>['fs']> {
return result.files.map((entry) => entry.relativePath)
},
cancelListFiles: async () => {
// Why: the paired-web path lists files over runtime RPC with its own
// request timeout; there is no host-side scan to abort from here.
// Why: paired-web lists files over runtime RPC with its own timeout; there's no host-side scan to abort here.
},
search: async (args) => {
const file = await resolveRuntimeFilePath(args.rootPath)
@@ -1761,8 +1730,7 @@ function createFileApi(): NonNullable<Partial<PreloadApi>['fs']> {
}
}
// Why: track the in-flight abortable status request per token so cancelStatus
// can abort the matching subscription and close its remote request context.
// Why: track the in-flight abortable status request per token so cancelStatus can abort it and close its remote context.
const webGitStatusAbortControllers = new Map<string, AbortController>()
async function callAbortableRuntimeStatus<TResult>(
@@ -1809,9 +1777,7 @@ function createGitApi(): NonNullable<Partial<PreloadApi>['git']> {
bypassEffectiveUpstreamNegativeCache,
reuseLineStats
}
// Why: without a token there's nothing to cancel, so stay on the pooled
// call transport. With one, route through the subscription bridge so
// cancelStatus can close the request context and abort the remote scan.
// Why: no token = nothing to cancel (pooled); a token routes via the subscription bridge so cancelStatus can abort.
if (!requestToken) {
return callRuntimeResult('git.status', params)
}
@@ -1835,8 +1801,7 @@ function createGitApi(): NonNullable<Partial<PreloadApi>['git']> {
paths
})
},
// Why: the "add huge folder to .gitignore" flow is a local-desktop helper;
// in the web runtime there's no offer, so return no candidates / no-op.
// Why: the "add huge folder to .gitignore" flow is desktop-only; the web runtime makes no offer, so return no candidates.
findHugeFoldersToIgnore: async () => [],
appendGitignore: async () => false,
history: async ({ worktreePath, limit, baseRef }) => {
@@ -2496,14 +2461,12 @@ function createWebUiApi(): NonNullable<Partial<PreloadApi>['ui']> {
},
isMaximized: () => Promise.resolve(false),
onOpenSettings: () => noopUnsubscribe,
// Why: the web client has no native tray/menu bar, so there is never a
// queued open-settings intent to consume.
// Why: the web client has no native tray/menu bar, so there's never a queued open-settings intent to consume.
consumePendingOpenSettings: () => Promise.resolve(false),
onOpenSetupGuide: () => noopUnsubscribe,
onOpenFeatureTour: () => noopUnsubscribe,
onOpenCrashReport: () => noopUnsubscribe,
// No desktop main process to push state changes; the web client re-reads
// via ui.get on interaction instead.
// No desktop main process to push state changes; the web client re-reads via ui.get on interaction.
onStateChanged: () => noopUnsubscribe,
onToggleLeftSidebar: () => noopUnsubscribe,
onToggleRightSidebar: () => noopUnsubscribe,
@@ -2563,12 +2526,10 @@ function createWebUiApi(): NonNullable<Partial<PreloadApi>['ui']> {
onTerminalTabCloseRequest: () => noopUnsubscribe,
respondTerminalTabClose: () => {},
onSleepWorktree: () => noopUnsubscribe,
// Why: paired web is a full renderer that wakes on activation; mobile wake is
// desktop-host-scoped, so the web client never receives this signal.
// Why: paired web is a full renderer that wakes on activation; mobile wake is desktop-host-scoped and never reaches web.
onResumeSleepingAgents: () => noopUnsubscribe,
onTerminalZoom: () => noopUnsubscribe,
// Why: a paired web client has no OS sleep signal; occlusion-driven
// visibilitychange already covers its wake recovery.
// Why: a paired web client has no OS sleep signal; occlusion-driven visibilitychange already covers wake recovery.
onSystemResumed: () => noopUnsubscribe,
onFileDrop: () => noopUnsubscribe,
syncTrafficLights: () => {},
@@ -2775,8 +2736,7 @@ function createSkillsApi(): NonNullable<Partial<PreloadApi>['skills']> {
return {
discover: (target) =>
callRuntimeResult<SkillDiscoveryResult>('skills.discover', target, 15_000),
// Why: browser clients have no local skill homes, and remote-host
// freshness stays disabled until its update rail has equivalent coverage.
// Why: browser clients have no local skill homes; remote-host freshness stays off until its update rail covers it.
freshnessInventory: (): Promise<SkillFreshnessInventory> =>
Promise.resolve({
schemaVersion: 1,
@@ -2820,8 +2780,7 @@ function createRateLimitsApi(): NonNullable<Partial<PreloadApi>['rateLimits']> {
get: () => Promise.resolve(empty),
refresh: () => Promise.resolve(empty),
refreshCodexForTarget: () => Promise.resolve(empty),
// Why: web clients do not own local Codex auth, so reset-credit
// redemption remains desktop-only and reports the safe no-credit outcome.
// Why: web clients don't own local Codex auth; report the safe no-credit outcome since redemption is desktop-only.
consumeCodexResetCredit: () => Promise.resolve({ outcome: 'noCredit', state: empty }),
refreshClaudeForTarget: () => Promise.resolve(empty),
setPollingInterval: () => Promise.resolve(),
@@ -2929,8 +2888,7 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
ackData: () => {},
onDeliveryResyncRequest: () => noopUnsubscribe,
respondDeliveryResync: () => {},
// Why healthy stub: web terminals ride the remote-runtime transport, not
// main's delivery gate — a zero-in-flight reply keeps the watchdog idle.
// Why: web terminals bypass main's delivery gate; a zero-in-flight reply keeps the watchdog idle.
reportRendererDeliveryState: () =>
Promise.resolve({ inFlightTotalChars: 0, inFlightPtyCount: 0, msSinceLastAck: null }),
getPtyDataListenerCount: () => 0,
@@ -2939,8 +2897,7 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
setRendererPtyVisible: () => {},
setHiddenRendererPty: () => {},
setPtyDeliveryInterest: () => {},
// Why no-op: remote-runtime PTYs are never hidden-gate markable, so the
// web client has no main-side responder to feed.
// Why: remote-runtime PTYs are never hidden-gate markable, so there's no main-side responder to feed.
publishTerminalViewAttributes: () => {},
hasChildProcesses: () => Promise.resolve(false),
getForegroundProcess: () => Promise.resolve(null),
@@ -2953,8 +2910,7 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
ids.map((id) => ({ id, authoritative: false })),
hasPty: () => Promise.resolve(null),
getMainBufferSnapshot: () => Promise.resolve(null),
// Why: remote-runtime PTYs never transit local main, so the web client has
// no side-effect facts source; renderer byte parsing stays authoritative.
// Why: remote-runtime PTYs skip local main (no side-effect source); renderer byte parsing stays authoritative.
onSideEffect: () => noopUnsubscribe,
getSideEffectSnapshot: () => Promise.resolve(null),
getRendererDeliveryDebugSnapshot: () =>
@@ -3008,9 +2964,7 @@ function createPtyApi(): NonNullable<Partial<PreloadApi>['pty']> {
function createSshApi(): NonNullable<Partial<PreloadApi>['ssh']> {
return {
// Why: SSH connections are owned by the paired host. Read/connect route to
// its runtime RPC so remote worktrees can show real connection state and
// reconnect (STA-1468); target management stays desktop-only.
// Why: SSH is owned by the paired host; route read/connect to runtime RPC for state/reconnect (STA-1468). Target mgmt is desktop-only.
listTargets: async () => {
if (!requireActiveEnvironmentOrNull()) {
return []
@@ -3168,8 +3122,7 @@ async function saveClipboardImageAsTempFileInRuntime(
CLIPBOARD_IMAGE_SAVE_TIMEOUT_MS
)
} catch (error) {
// Why: once chunked paste has created server-side state, failed append or
// commit must not wait for TTL cleanup before releasing the bounded slot.
// Why: after chunked paste holds server-side state, release the bounded slot on failure rather than wait for TTL cleanup.
await callRuntimeResult(
'clipboard.abortImageUpload',
{ uploadId },
@@ -3211,8 +3164,7 @@ function resolveEnvironment(selector: string): StoredWebRuntimeEnvironment {
return environment
}
if (selector.startsWith('web-') && environment.id.startsWith('web-')) {
// Why: persisted terminal ids can outlive a web-client re-pair, which creates
// a fresh web-* environment id even when it points at the same active server.
// Why: persisted terminal ids can outlive a re-pair, which mints a fresh web-* id for the same active server.
return environment
}
throw new Error(`Unknown Orca runtime environment: ${selector}`)
@@ -3370,8 +3322,7 @@ async function updateRuntimePRBotAuthorOverride(args: {
}): Promise<GlobalSettings> {
const local = getStoredSettings()
if (requireActiveEnvironmentOrNull()) {
// Why: a paired client must not report a successful mark that the
// authoritative runtime failed to persist and will later overwrite.
// Why: don't report a successful mark the authoritative runtime failed to persist and will later overwrite.
const result = await callRuntimeResult<{ settings: Partial<GlobalSettings> }>(
'settings.updatePRBotAuthorOverride',
args,
@@ -3406,14 +3357,12 @@ function getStoredOnboarding(): OnboardingState {
return closed
}
const closed = closeWebOnboarding(getDefaultOnboardingState())
// Why: pairing already means the user has an Orca server. Desktop first-run
// onboarding would incorrectly probe browser-local tools and block the client.
// Why: paired clients already have an Orca server; skip desktop first-run onboarding that would probe browser-local tools.
writeJson(ONBOARDING_STORAGE_KEY, closed)
return closed
}
/** Resolve the localStorage key for a session partition. Non-'local' hosts get
* a host-suffixed key so their sessions never clobber the local one. */
/** Resolve the localStorage key for a session partition; non-'local' hosts get a host-suffixed key so they never clobber the local one. */
function sessionStorageKeyForHost(hostId?: string | null): string {
const resolved = normalizeExecutionHostId(hostId) ?? LOCAL_EXECUTION_HOST_ID
return resolved === LOCAL_EXECUTION_HOST_ID
@@ -3435,8 +3384,7 @@ function getStoredWorkspaceSession(hostId?: string | null): WorkspaceSessionStat
return localSession
}
const ui = readLocalWebUIState()
// Why: paired web clients mirror host session-tabs after startup. Replaying
// browser-local terminal handles first creates stale remote PTYs and errors.
// Why: replaying browser-local terminal handles first creates stale remote PTYs; mirror host session-tabs instead.
return sanitizeWebRuntimeWorkspaceSession({
...getDefaultWorkspaceSession(),
activeRepoId: ui.lastActiveRepoId,
@@ -3464,8 +3412,7 @@ function readLocalWebUIState(): PersistedUIState {
const storedSettings = getStoredSettings()
const base = {
...defaults,
// Why: when runtime ui.get is unavailable, web fallback must mirror the
// main-process missing-property seed from the legacy card layout mode.
// Why: mirror the main-process missing-property seed from legacy card layout mode when runtime ui.get is unavailable.
worktreeCardProperties: getWorktreeCardModeProperties(
storedSettings.compactWorktreeCards ? 'Compact' : 'Default'
)
@@ -3475,8 +3422,7 @@ function readLocalWebUIState(): PersistedUIState {
}
return mergeWebUIState(base, {
...stored,
// Why: web fallback lacks main-process normalization, so migrate the
// retired setting only when the local UI preference is still absent.
// Why: web fallback lacks main-process normalization; migrate the retired setting only when local UI preference is absent.
rightSidebarOpen: storedSettings.rightSidebarOpenByDefault
})
}
@@ -3657,8 +3603,7 @@ function isMissingPathError(error: unknown): boolean {
}
async function resolveRuntimeWorktreeByPath(worktreePath: string): Promise<Worktree> {
// Why: hidden-but-open worktrees must still resolve for git/file operations.
// `worktree.list` is sidebar-visible only, so path resolution uses detected rows.
// Why: hidden-but-open worktrees must still resolve, but `worktree.list` is sidebar-visible only — resolve via detected rows.
const worktrees = await listAllRuntimeDetectedWorktrees()
const match = worktrees
.map((worktree) => ({
@@ -3716,9 +3661,7 @@ function mapRepoPathArg(args: unknown): unknown {
const repoId = typeof record.repoId === 'string' && record.repoId.trim() ? record.repoId : null
return {
...record,
// Why: runtime repo selectors accept loose path/name forms, but duplicate
// checked-out repos can make those ambiguous. The renderer already passes
// Orca's repo id on task calls, so prefer the explicit selector.
// Why: duplicate checked-out repos make path/name selectors ambiguous; prefer the explicit repo id the renderer passes.
repo: repoId ? `id:${repoId}` : record.repoPath
}
}
+22 -65
View File
@@ -1,6 +1,4 @@
/* eslint-disable max-lines -- Why: this browser runtime client owns the E2EE
WebSocket state machine, JSON-RPC request routing, streaming callbacks, and
binary frame forwarding as one transport boundary. */
/* eslint-disable max-lines -- Why: one transport boundary — E2EE WebSocket state machine, JSON-RPC routing, streaming, binary frame forwarding. */
import type { RuntimeRpcResponse, RuntimeRpcSuccess } from '../../../shared/runtime-rpc-envelope'
import { isKeepaliveFrame } from '../../../shared/runtime-rpc-envelope'
import type { WebPairingOffer } from './web-pairing'
@@ -54,11 +52,7 @@ export type WebRuntimeSubscriptionHandle = {
export type SubscribeOptions = {
timeoutMs?: number
// Why: streaming subscriptions whose server-side cleanup is keyed by a
// client-supplied token (native chat keys its fs-watcher by agent:sessionId)
// must send an explicit unsubscribe RPC on teardown so the watcher is reaped
// on view-toggle, not just on socket close. Returns the RPC frame to emit, or
// null when the method needs no explicit teardown.
// Why: token-keyed server cleanup needs an explicit unsubscribe to be reaped on view-toggle, not just socket close.
buildUnsubscribe?: (params: unknown) => { method: string; params: unknown } | null
}
@@ -67,15 +61,7 @@ const CONNECT_TIMEOUT_MS = 12_000
const HANDSHAKE_TIMEOUT_MS = 10_000
const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15_000]
const SHARED_CONNECTION_SUBSCRIPTION_METHODS = new Set(['files.watch'])
// Why: the browser WebSocket API hides protocol pings/pongs, so a half-open
// connection (mobile NAT idle timeout, server crash, wifi→cellular handoff)
// leaves readyState===OPEN with no onclose/onerror — the UI silently freezes on
// stale data and never reconnects. Poll connection liveness while the tab is
// visible: after HEARTBEAT_IDLE_MS of silence send a cheap status.get probe
// (any inbound frame proves liveness), and only if that probe stays unanswered
// for HEARTBEAT_PROBE_GRACE_MS close the socket to drive the reconnect path.
// Closing is gated on an unanswered PROBE, never on raw accumulated silence, so
// a backgrounded/frozen tab can never be mistaken for a dead socket on resume.
// Why: browser WebSockets hide pings/pongs, so a half-open socket stays OPEN with no onclose/onerror — poll liveness in-app.
const HEARTBEAT_INTERVAL_MS = 10_000
const HEARTBEAT_IDLE_MS = 25_000
const HEARTBEAT_PROBE_GRACE_MS = 20_000
@@ -92,13 +78,9 @@ export class WebRuntimeClient {
private reconnectTimer: number | null = null
private heartbeatTimer: number | null = null
private lastInboundFrameAt = 0
// Why: timestamp of an outstanding liveness probe (null = none in flight).
// The dead-close fires only when a SENT probe goes unanswered, never on raw
// silence, so a hidden/frozen tab resuming after a long gap re-probes first.
// Timestamp of an outstanding liveness probe (null = none); dead-close fires only on an unanswered sent probe.
private heartbeatProbeSentAt: number | null = null
// Why: detect a suspended tick loop (backgrounded/frozen tab). If a tick lands
// far later than scheduled, treat the gap as "no evidence", reset the clocks,
// and re-probe instead of closing.
// Why: tracks last tick time to detect a suspended loop (frozen tab) so a long gap re-probes instead of closing.
private lastHeartbeatTickAt = 0
private readonly pending = new Map<string, PendingRequest>()
private readonly subscriptions = new Map<string, RuntimeSubscription>()
@@ -141,9 +123,7 @@ export class WebRuntimeClient {
options?: SubscribeOptions
): Promise<WebRuntimeSubscriptionHandle> {
if (SHARED_CONNECTION_SUBSCRIPTION_METHODS.has(method)) {
// Why: file watches are text-only and already have an explicit
// files.unwatch RPC, so sharing the main socket avoids exhausting the
// server's WebSocket connection cap in large browser sessions.
// Why: sharing the main socket for file watches avoids exhausting the server's WebSocket connection cap.
return this.subscribeSharedFileWatch(params, callbacks, options)
}
const client = new WebRuntimeClient(this.pairing)
@@ -172,9 +152,7 @@ export class WebRuntimeClient {
)
return {
unsubscribe: () => {
// Why: emit the explicit teardown RPC (e.g. nativeChat.unsubscribe)
// on the child socket BEFORE closing it, so the server reaps the
// fs-watcher on view-toggle instead of leaking it until socket close.
// Why: emit the teardown RPC before closing the child socket so the server reaps the fs-watcher on view-toggle.
handle.unsubscribe()
closeChild()
},
@@ -245,8 +223,7 @@ export class WebRuntimeClient {
dropLocalSubscription()
return
}
// Why: retain the shared-socket callback and retry ownership until the
// server acknowledges physical teardown; a new watch joins this barrier.
// Why: retain the callback and retry until the server acks physical teardown; a new watch joins this barrier.
const retries = this.fileWatchTeardownRetries.get(teardownKey) ?? new Set()
retries.add(retryRemoteUnwatch)
this.fileWatchTeardownRetries.set(teardownKey, retries)
@@ -264,8 +241,7 @@ export class WebRuntimeClient {
return
}
}
// Why: the server publishes cancellation ownership before native setup;
// callers should still become ready only after the watcher is live.
// Why: server publishes cancellation ownership before native setup; callers become ready only once the watcher is live.
if (isFileWatchStartingResponse(response)) {
return
}
@@ -273,9 +249,7 @@ export class WebRuntimeClient {
callbacks.onResponse(response)
if (pendingReplayResync && nextSubscriptionId && response.ok) {
pendingReplayResync = false
// Why: a replayed watch reports changes only from its own native
// setup; the reconnect gap produced no events, so consumers must
// conservatively re-scan once the replacement is ready.
// Why: a replayed watch only reports events after its own setup, so consumers must re-scan the reconnect gap.
callbacks.onResponse(createFileWatchReplayOverflowResponse(response, params))
}
} else if (response.ok === false) {
@@ -303,8 +277,7 @@ export class WebRuntimeClient {
if (retries?.size === 0) {
this.fileWatchTeardownRetries.delete(teardownKey)
}
// Why: socket close physically releases the old server subscription;
// a locally stopped watch must not be replayed on the replacement.
// Why: socket close physically releases the server subscription — a stopped watch must not replay on the replacement.
dropLocalSubscription()
},
onTransportReplayed: () => {
@@ -328,12 +301,10 @@ export class WebRuntimeClient {
if (remoteSubscriptionId) {
unwatchAndDropLocalSubscription()
} else if (transportInterrupted) {
// Why: socket close already released the old server subscription;
// remove its replay record instead of reviving a locally stopped watch.
// Why: socket close already released the server subscription — drop its replay record, don't revive a stopped watch.
dropLocalSubscription()
}
// Why: an older server may not publish its id until ready. Retain the
// callback so a late response can still physically unwatch the root.
// Why: an older server may not publish its id until ready — retain the callback so a late response can still unwatch.
},
sendBinary: (bytes) => handle?.sendBinary(bytes)
}
@@ -356,8 +327,7 @@ export class WebRuntimeClient {
return {
unsubscribe: () => {
this.subscriptions.delete(subscription.id)
// Tell the server to reap its keyed cleanup (e.g. native-chat fs-watcher)
// before the socket goes away. Best-effort: a closed socket already reaps.
// Tell the server to reap its keyed cleanup before the socket closes; best-effort (a closed socket already reaps).
const teardown = options?.buildUnsubscribe?.(params)
if (teardown) {
this.sendEncrypted({
@@ -445,14 +415,11 @@ export class WebRuntimeClient {
}
ws.onmessage = (event) => {
// Why: stale socket callbacks can arrive after reconnect swaps this.ws;
// they must not drive auth or subscription state on the replacement.
// Why: stale callbacks from a pre-reconnect socket must not drive state on the replacement this.ws.
if (this.ws !== ws) {
return
}
// Why: any inbound frame (RPC reply, subscription push, keepalive, probe
// echo) proves the socket is alive — reset the liveness watchdog and clear
// any outstanding probe.
// Why: any inbound frame proves the socket is alive — reset the liveness watchdog and clear any outstanding probe.
this.lastInboundFrameAt = this.now()
this.heartbeatProbeSentAt = null
void this.handleSocketMessage(event.data, ws)
@@ -787,8 +754,7 @@ export class WebRuntimeClient {
}
}
// Why: overridable seams so a test can drive deterministic time + visibility
// without faking globals across the whole crypto/transport fixture.
// Why: overridable seams so tests can drive deterministic time + visibility without faking globals.
protected now(): number {
return Date.now()
}
@@ -816,17 +782,14 @@ export class WebRuntimeClient {
private runHeartbeatTick(): void {
const now = this.now()
// Why: if this tick lands far later than scheduled, the loop was suspended
// (backgrounded/frozen tab) — that gap is NOT evidence the socket died, so
// re-baseline the liveness clocks and drop any stale probe before judging.
// Why: a much-later-than-scheduled tick means the loop was suspended (frozen tab), not a dead socket — re-baseline.
const sinceLastTick = now - this.lastHeartbeatTickAt
this.lastHeartbeatTickAt = now
if (sinceLastTick >= HEARTBEAT_INTERVAL_MS * 2) {
this.lastInboundFrameAt = now
this.heartbeatProbeSentAt = null
}
// Why: a backgrounded tab shows no live data and the user can't see
// staleness, so don't spend battery probing; the next visible tick re-checks.
// Why: don't probe while hidden — no visible staleness to detect and it wastes battery; next visible tick re-checks.
if (!this.isDocumentVisible()) {
return
}
@@ -834,9 +797,7 @@ export class WebRuntimeClient {
if (!ws || ws.readyState !== WebSocket.OPEN || this.state !== 'connected') {
return
}
// Why: close ONLY when a probe we actually sent has gone unanswered past the
// grace window — never on raw accumulated silence. This guarantees at least
// one real round-trip attempt before declaring the socket half-open.
// Why: close only when a probe we actually sent goes unanswered past grace — never on raw accumulated silence.
if (
this.heartbeatProbeSentAt !== null &&
now - this.heartbeatProbeSentAt >= HEARTBEAT_PROBE_GRACE_MS
@@ -846,10 +807,7 @@ export class WebRuntimeClient {
return
}
if (this.heartbeatProbeSentAt === null && now - this.lastInboundFrameAt >= HEARTBEAT_IDLE_MS) {
// Why: a fire-and-forget liveness probe. The reply (or any other frame)
// resets lastInboundFrameAt and clears heartbeatProbeSentAt; the id is
// intentionally unmatched in handleSocketMessage so it adds no pending
// request or timeout. If sending fails the socket isn't OPEN — skip.
// Why: fire-and-forget liveness probe; its id is intentionally unmatched so it registers no pending request/timeout.
if (
this.sendEncrypted({
id: `web-heartbeat-${this.nextId()}`,
@@ -903,8 +861,7 @@ function createFileWatchReplayOverflowResponse(
result: {
type: 'changed',
worktree: typeof worktree === 'string' ? worktree : '',
// Why: overflow consumers re-scan the whole root and never read the
// path; the client does not know the server-side root path here.
// Why: overflow consumers re-scan the whole root and ignore the path (client lacks the server-side root here).
events: [{ kind: 'overflow', absolutePath: '' }]
},
_meta: readyResponse._meta