mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Scope terminal parking inputs and registries to workspace ownership
This commit is contained in:
+17
-188
@@ -1,208 +1,37 @@
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import type {
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalTab
|
||||
} from '../../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { useAppStore } from '../../../../store/index'
|
||||
import type { AppState } from '../../../../store/types'
|
||||
import { useCallback, useEffect, useSyncExternalStore } from 'react'
|
||||
import type { TerminalTab } from '../../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { syncParkedTerminalTabWatchers } from '../output-watchers/terminal-parked-tab-watchers'
|
||||
import { disposeParkedTerminalWatchersForWorktree } from '../output-watchers/terminal-parked-watcher-registry'
|
||||
import {
|
||||
disposeParkedTerminalWatchersForWorktree,
|
||||
capturedPanesByTabId
|
||||
} from '../output-watchers/terminal-parked-watcher-registry'
|
||||
subscribeTerminalParkingInputs,
|
||||
terminalParkingInputRevision
|
||||
} from '../terminal-parking-input-events'
|
||||
|
||||
type TerminalParkingAssignment = {
|
||||
groupId: string
|
||||
isActiveInGroup: boolean
|
||||
}
|
||||
|
||||
const EMPTY_PTY_IDS: readonly string[] = []
|
||||
|
||||
type WatcherReconciliationStoreInputs = readonly (
|
||||
| readonly string[]
|
||||
| TerminalLayoutSnapshot
|
||||
| string
|
||||
| null
|
||||
)[]
|
||||
|
||||
const EMPTY_WATCHER_RECONCILIATION_INPUTS: WatcherReconciliationStoreInputs = Object.freeze([])
|
||||
|
||||
/** Length-prefix fragments for injective concatenation without JSON escaping rescans. */
|
||||
function joinKeyFragments(fragments: readonly string[]): string {
|
||||
let key = ''
|
||||
for (const fragment of fragments) {
|
||||
key += `${fragment.length}:${fragment}`
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
export function getTerminalParkingInputsKey(terminalTabs: readonly TerminalTab[]): string {
|
||||
return JSON.stringify(terminalTabs.map((tab) => [tab.id, tab.ptyId, tab.pendingActivationSpawn]))
|
||||
}
|
||||
|
||||
export function getTerminalParkingAssignmentsKey(
|
||||
assignments: ReadonlyMap<string, TerminalParkingAssignment>
|
||||
): string {
|
||||
return JSON.stringify(
|
||||
Array.from(assignments, ([tabId, assignment]) => [
|
||||
tabId,
|
||||
assignment.groupId,
|
||||
assignment.isActiveInGroup
|
||||
])
|
||||
export function useTerminalParkingWorkspaceRevision(worktreeId: string): number {
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => subscribeTerminalParkingInputs(worktreeId, listener),
|
||||
[worktreeId]
|
||||
)
|
||||
}
|
||||
|
||||
function getWatcherSynchronizationKey(args: {
|
||||
worktreeId: string
|
||||
inputsKey: string
|
||||
assignmentsKey: string
|
||||
parkedTabIds: ReadonlySet<string>
|
||||
activationDeferredMountTabIds?: ReadonlySet<string> | null
|
||||
reconciliationKey: string
|
||||
}): string {
|
||||
return joinKeyFragments([
|
||||
args.worktreeId,
|
||||
args.inputsKey,
|
||||
args.assignmentsKey,
|
||||
joinKeyFragments(Array.from(args.parkedTabIds)),
|
||||
joinKeyFragments(Array.from(args.activationDeferredMountTabIds ?? []).sort()),
|
||||
args.reconciliationKey
|
||||
])
|
||||
}
|
||||
|
||||
function getCapturedPaneKey(terminalTabs: readonly TerminalTab[]): string {
|
||||
return JSON.stringify(
|
||||
terminalTabs.map((tab) => {
|
||||
const capture = capturedPanesByTabId.get(tab.id)
|
||||
return [
|
||||
tab.id,
|
||||
capture?.worktreeId ?? null,
|
||||
capture?.panes.map((pane) => [pane.ptyId, pane.paneId, pane.leafId, pane.drivesTabTitle]) ??
|
||||
[]
|
||||
]
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/** Memoize store-derived shallow-stable inputs; registry-derived captures mutate outside React and must be read separately. */
|
||||
function getWatcherReconciliationStoreInputsKey(
|
||||
terminalTabs: readonly TerminalTab[],
|
||||
inputs: WatcherReconciliationStoreInputs
|
||||
): string {
|
||||
if (inputs.length === 0) {
|
||||
return ''
|
||||
}
|
||||
return JSON.stringify(
|
||||
terminalTabs.map((tab, index) => {
|
||||
const offset = index * 3
|
||||
const layout = inputs[offset + 1] as TerminalLayoutSnapshot | null
|
||||
return [
|
||||
tab.id,
|
||||
inputs[offset] as readonly string[],
|
||||
layout?.root ?? null,
|
||||
layout?.activeLeafId ?? null,
|
||||
layout?.ptyIdsByLeafId ?? null,
|
||||
inputs[offset + 2] as string
|
||||
]
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function getWatcherReconciliationKey(
|
||||
terminalTabs: readonly TerminalTab[],
|
||||
storeInputsKey: string
|
||||
): string {
|
||||
if (storeInputsKey === '') {
|
||||
return ''
|
||||
}
|
||||
return joinKeyFragments([storeInputsKey, getCapturedPaneKey(terminalTabs)])
|
||||
}
|
||||
|
||||
function selectWatcherReconciliationStoreInputs(
|
||||
state: AppState,
|
||||
terminalTabs: readonly TerminalTab[]
|
||||
): WatcherReconciliationStoreInputs {
|
||||
return terminalTabs.flatMap((tab) => {
|
||||
// Missing titles already serialize empty; do not allocate a throwaway fallback object per tab/write.
|
||||
const paneTitles = state.runtimePaneTitlesByTabId[tab.id]
|
||||
return [
|
||||
state.ptyIdsByTabId[tab.id] ?? EMPTY_PTY_IDS,
|
||||
state.terminalLayoutsByTabId[tab.id] ?? null,
|
||||
paneTitles ? Object.keys(paneTitles).join(',') : ''
|
||||
]
|
||||
})
|
||||
const snapshot = useCallback(() => terminalParkingInputRevision(worktreeId), [worktreeId])
|
||||
return useSyncExternalStore(subscribe, snapshot)
|
||||
}
|
||||
|
||||
export function useParkedTerminalWatcherSynchronization(args: {
|
||||
worktreeId: string
|
||||
terminalTabs: readonly TerminalTab[]
|
||||
inputsKey: string
|
||||
assignmentsKey: string
|
||||
parkedTabIds: ReadonlySet<string>
|
||||
activationDeferredMountTabIds?: ReadonlySet<string> | null
|
||||
}): void {
|
||||
const {
|
||||
worktreeId,
|
||||
terminalTabs,
|
||||
inputsKey,
|
||||
assignmentsKey,
|
||||
parkedTabIds,
|
||||
activationDeferredMountTabIds
|
||||
} = args
|
||||
const reconciliationStoreInputs = useAppStore(
|
||||
useShallow((state: AppState) =>
|
||||
// Why: an empty committed park set has no live watcher state for store writes to reconcile.
|
||||
parkedTabIds.size === 0
|
||||
? EMPTY_WATCHER_RECONCILIATION_INPUTS
|
||||
: selectWatcherReconciliationStoreInputs(state, terminalTabs)
|
||||
)
|
||||
)
|
||||
// Memoize dominant per-tab tree serialization by shallow selector identity.
|
||||
const reconciliationStoreInputsKey = useMemo(
|
||||
() => getWatcherReconciliationStoreInputsKey(terminalTabs, reconciliationStoreInputs),
|
||||
[reconciliationStoreInputs, terminalTabs]
|
||||
)
|
||||
const reconciliationKey = getWatcherReconciliationKey(terminalTabs, reconciliationStoreInputsKey)
|
||||
const synchronizationKey = getWatcherSynchronizationKey({ ...args, reconciliationKey })
|
||||
const synchronizationKeyRef = useRef<string | null>(null)
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
synchronizationKeyRef.current = null
|
||||
disposeParkedTerminalWatchersForWorktree(worktreeId)
|
||||
},
|
||||
[worktreeId]
|
||||
)
|
||||
|
||||
const { worktreeId, terminalTabs, parkedTabIds, activationDeferredMountTabIds } = args
|
||||
const revision = useTerminalParkingWorkspaceRevision(worktreeId)
|
||||
useEffect(() => () => disposeParkedTerminalWatchersForWorktree(worktreeId), [worktreeId])
|
||||
useEffect(() => {
|
||||
if (synchronizationKeyRef.current === synchronizationKey) {
|
||||
return
|
||||
}
|
||||
syncParkedTerminalTabWatchers({
|
||||
worktreeId,
|
||||
tabs: terminalTabs,
|
||||
parkedTabIds,
|
||||
// Why: activation-deferred tabs have no prior pane-owned title slot.
|
||||
restoreTitleOnStartTabIds: activationDeferredMountTabIds ?? undefined
|
||||
})
|
||||
// Why: capture cleanup mutates the registry during commit; store its post-commit key.
|
||||
synchronizationKeyRef.current = getWatcherSynchronizationKey({
|
||||
worktreeId,
|
||||
inputsKey,
|
||||
assignmentsKey,
|
||||
parkedTabIds,
|
||||
activationDeferredMountTabIds,
|
||||
reconciliationKey: getWatcherReconciliationKey(terminalTabs, reconciliationStoreInputsKey)
|
||||
})
|
||||
}, [
|
||||
activationDeferredMountTabIds,
|
||||
assignmentsKey,
|
||||
inputsKey,
|
||||
parkedTabIds,
|
||||
reconciliationStoreInputsKey,
|
||||
synchronizationKey,
|
||||
terminalTabs,
|
||||
worktreeId
|
||||
])
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- the workspace revision owns semantic tab inputs; title-only replacements carry no watcher change.
|
||||
}, [activationDeferredMountTabIds, parkedTabIds, revision, worktreeId])
|
||||
}
|
||||
|
||||
+25
-23
@@ -25,10 +25,7 @@ import {
|
||||
} from '../verdict/use-terminal-park-verdict-pin'
|
||||
import { withholdUnparkableTerminalTabs } from '../retention/terminal-cold-park-withheld-tabs'
|
||||
import { getTerminalParkingPolicyOverrides } from '../instrumentation/terminal-parking-e2e-overrides'
|
||||
import {
|
||||
selectEvictionExemptTerminalTabIds,
|
||||
selectEvictionExemptTerminalTabLayoutKey
|
||||
} from '../retention/terminal-eviction-exempt-tabs'
|
||||
import { selectEvictionExemptTerminalTabIds } from '../retention/terminal-eviction-exempt-tabs'
|
||||
import { selectSleepingRecordParkExemptTabIds } from '../retention/sleeping-record-park-exemption'
|
||||
import { usePendingStartupParkPresence } from '../retention/terminal-pending-startup-park-presence'
|
||||
import { canWatcherCoverParkedTerminalTab } from '../output-watchers/terminal-parked-tab-watchers'
|
||||
@@ -36,8 +33,7 @@ import { captureNewlyParkedTerminalTabs } from '../capture/parked-terminal-tab-c
|
||||
import { createTerminalTabActivationOrder } from '../retention/terminal-tab-activation-order'
|
||||
import { buildTerminalTabColdParkCandidates } from '../retention/terminal-tab-park-candidates'
|
||||
import {
|
||||
getTerminalParkingAssignmentsKey,
|
||||
getTerminalParkingInputsKey,
|
||||
useTerminalParkingWorkspaceRevision,
|
||||
useParkedTerminalWatcherSynchronization
|
||||
} from './use-parked-terminal-watcher-synchronization'
|
||||
import {
|
||||
@@ -80,19 +76,26 @@ export function useTerminalTabColdParking(args: {
|
||||
activityTerminalPortals,
|
||||
activationDeferredMountTabIds
|
||||
} = args
|
||||
const terminalParkingInputsKey = useMemo(
|
||||
() => getTerminalParkingInputsKey(terminalTabs),
|
||||
[terminalTabs]
|
||||
)
|
||||
const terminalParkingAssignmentsKey = useMemo(
|
||||
() => getTerminalParkingAssignmentsKey(assignments),
|
||||
[assignments]
|
||||
)
|
||||
const terminalParkingTabsDependency = coldParkTerminalPanes
|
||||
? terminalParkingInputsKey
|
||||
: terminalTabs
|
||||
const parkingInputRevision = useTerminalParkingWorkspaceRevision(worktreeId)
|
||||
const assignmentProjection = useRef(assignments)
|
||||
if (assignmentProjection.current !== assignments) {
|
||||
const previous = assignmentProjection.current
|
||||
if (
|
||||
previous.size !== assignments.size ||
|
||||
[...assignments].some(([id, assignment]) => {
|
||||
const before = previous.get(id)
|
||||
return (
|
||||
before?.groupId !== assignment.groupId ||
|
||||
before.isActiveInGroup !== assignment.isActiveInGroup
|
||||
)
|
||||
})
|
||||
) {
|
||||
assignmentProjection.current = assignments
|
||||
}
|
||||
}
|
||||
const terminalParkingTabsDependency = coldParkTerminalPanes ? parkingInputRevision : terminalTabs
|
||||
const terminalParkingAssignmentsDependency = coldParkTerminalPanes
|
||||
? terminalParkingAssignmentsKey
|
||||
? assignmentProjection.current
|
||||
: assignments
|
||||
const pendingStartupByTabId = usePendingStartupParkPresence(terminalTabs)
|
||||
const terminalParkingEnabled = useAppStore(
|
||||
@@ -250,15 +253,14 @@ export function useTerminalTabColdParking(args: {
|
||||
terminalParkingEnabled,
|
||||
terminalSshParkingEnabled,
|
||||
terminalTabParkingRevision,
|
||||
parkingInputRevision,
|
||||
terminalParkingAssignmentsDependency,
|
||||
terminalParkingTabsDependency,
|
||||
worktreeId
|
||||
])
|
||||
|
||||
// Force-park exemptions depend on layout leaf PTYs even when terminalTabs is unchanged.
|
||||
const evictionExemptLayoutKey = useAppStore((state) =>
|
||||
isForceParked ? selectEvictionExemptTerminalTabLayoutKey(state, terminalTabs) : ''
|
||||
)
|
||||
const evictionExemptLayoutKey = parkingInputRevision
|
||||
// Cache exemption layout walks until force-park, tabs, or layout PTYs change.
|
||||
const evictionExemptTerminalTabIds = useMemo(
|
||||
() =>
|
||||
@@ -304,6 +306,7 @@ export function useTerminalTabColdParking(args: {
|
||||
}
|
||||
}
|
||||
return parked
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- coverage rereads external workspace facts owned by this revision.
|
||||
}, [
|
||||
activityTerminalPortals,
|
||||
assignments,
|
||||
@@ -316,6 +319,7 @@ export function useTerminalTabColdParking(args: {
|
||||
sleepingRecordOwnedTabIds,
|
||||
terminalTabs,
|
||||
terminalPaneSplitMountLeaseTabIds,
|
||||
parkingInputRevision,
|
||||
worktreeId
|
||||
])
|
||||
|
||||
@@ -331,8 +335,6 @@ export function useTerminalTabColdParking(args: {
|
||||
useParkedTerminalWatcherSynchronization({
|
||||
worktreeId,
|
||||
terminalTabs,
|
||||
assignmentsKey: terminalParkingAssignmentsKey,
|
||||
inputsKey: terminalParkingInputsKey,
|
||||
parkedTabIds: parkedTerminalTabIds,
|
||||
activationDeferredMountTabIds
|
||||
})
|
||||
|
||||
-27
@@ -1,6 +1,5 @@
|
||||
/** Agent-owner tab sets for gone-session parking, built once per source identity so a pass over every tab stays linear. */
|
||||
import type { TerminalTab } from '../../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
|
||||
const launchAgentTabIdsByTabs = new WeakMap<readonly TerminalTab[], ReadonlySet<string>>()
|
||||
const NO_TAB_IDS: ReadonlySet<string> = new Set()
|
||||
@@ -16,29 +15,3 @@ export function launchAgentTabIds(tabs: readonly TerminalTab[] | undefined): Rea
|
||||
}
|
||||
return tabIds
|
||||
}
|
||||
|
||||
let sleepingRecordTabIdsCache: {
|
||||
records: Record<string, SleepingAgentSessionRecord>
|
||||
tabIds: ReadonlySet<string>
|
||||
} | null = null
|
||||
|
||||
/** Tabs a sleeping record names by tabId or by a `${tabId}:` pane-key prefix. */
|
||||
export function sleepingRecordTabIds(
|
||||
records: Record<string, SleepingAgentSessionRecord>
|
||||
): ReadonlySet<string> {
|
||||
if (sleepingRecordTabIdsCache?.records === records) {
|
||||
return sleepingRecordTabIdsCache.tabIds
|
||||
}
|
||||
const tabIds = new Set<string>()
|
||||
for (const paneKey in records) {
|
||||
const recordTabId = records[paneKey]?.tabId
|
||||
if (recordTabId !== undefined) {
|
||||
tabIds.add(recordTabId)
|
||||
}
|
||||
for (let colon = paneKey.indexOf(':'); colon !== -1; colon = paneKey.indexOf(':', colon + 1)) {
|
||||
tabIds.add(paneKey.slice(0, colon))
|
||||
}
|
||||
}
|
||||
sleepingRecordTabIdsCache = { records, tabIds }
|
||||
return tabIds
|
||||
}
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import { isTerminalLeafId } from '../../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import { isRemoteExecutionHostPtyId } from '../../../../../../shared/execution-host/remote-execution-host-pty-id'
|
||||
import { terminalProviderAllowsParking } from '../../../terminal/terminal-provider-snapshot-capability'
|
||||
import { terminalProviderSessionIsGone } from '../../../terminal/terminal-provider-gone-sessions'
|
||||
import { isParkRestorableTerminalPty } from '../retention/terminal-hidden-view-parking'
|
||||
import { selectPairedRuntimeParkingEnvironmentIds } from '../retention/paired-runtime-parking-capabilities'
|
||||
import {
|
||||
capturedPanesByTabId,
|
||||
parkedTerminalCaptureRevision
|
||||
} from './terminal-parked-watcher-registry'
|
||||
import type { ParkableTerminalTabModel } from './terminal-parked-watcher-reconciliation'
|
||||
import { collectLeafIdsInOrder } from '../../layout/terminal-layout-leaf-traversal'
|
||||
import { resolveRootlessTerminalLayoutLeafId } from '../../../../../../shared/workspace-layout/terminal-pane-tree'
|
||||
import type { ParkedTerminalPaneCapture } from './terminal-parked-watcher-registry'
|
||||
import { launchAgentTabIds } from './parked-tab-agent-owner-index'
|
||||
|
||||
export type ParkedTerminalPtyEligibility = (ptyId: string) => boolean
|
||||
const allowOrdinaryParkRestore = (ptyId: string): boolean =>
|
||||
isRemoteExecutionHostPtyId(ptyId) || terminalProviderAllowsParking(ptyId)
|
||||
|
||||
type State = ReturnType<typeof useAppStore.getState>
|
||||
|
||||
export function parkRestorePolicyFromState(
|
||||
state: Pick<State, 'settings' | 'runtimeStatusByEnvironmentId'>
|
||||
) {
|
||||
return {
|
||||
sshParkingEnabled: state.settings?.terminalSshViewParking !== false,
|
||||
pairedRuntimeParkingEnvironmentIds: selectPairedRuntimeParkingEnvironmentIds(
|
||||
state.runtimeStatusByEnvironmentId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
type Coverage = {
|
||||
inputs: readonly unknown[]
|
||||
panes: ReturnType<typeof resolveParkedTerminalPaneCandidates>
|
||||
}
|
||||
const coverageByTab = new WeakMap<ParkableTerminalTabModel, Coverage>()
|
||||
|
||||
/** Share pane facts, never a policy-independent boolean: activation and ordinary parking admit different routes. */
|
||||
export function parkedTerminalTabCoverage(
|
||||
worktreeId: string,
|
||||
tab: ParkableTerminalTabModel,
|
||||
state: State = useAppStore.getState()
|
||||
) {
|
||||
const inputs = [
|
||||
worktreeId,
|
||||
tab.ptyId,
|
||||
state.terminalLayoutsByTabId[tab.id],
|
||||
state.ptyIdsByTabId?.[tab.id],
|
||||
state.lastKnownRelayPtyIdByTabId?.[tab.id],
|
||||
state.runtimePaneTitlesByTabId[tab.id],
|
||||
capturedPanesByTabId.get(tab.id),
|
||||
parkedTerminalCaptureRevision(tab.id)
|
||||
]
|
||||
const previous = coverageByTab.get(tab)
|
||||
const facts =
|
||||
previous && inputs.every((input, index) => input === previous.inputs[index])
|
||||
? previous
|
||||
: { inputs, panes: resolveParkedTerminalPaneCandidates(tab, state) }
|
||||
if (facts !== previous) {
|
||||
coverageByTab.set(tab, facts)
|
||||
}
|
||||
return { panes: facts.panes, restorePolicy: parkRestorePolicyFromState(state) }
|
||||
}
|
||||
|
||||
function goneSessionsKeepTabMounted(
|
||||
worktreeId: string,
|
||||
tab: ParkableTerminalTabModel,
|
||||
facts: ReturnType<typeof parkedTerminalTabCoverage>
|
||||
): boolean {
|
||||
const goneCount = facts.panes.filter(
|
||||
(pane) => pane.ptyId !== null && terminalProviderSessionIsGone(pane.ptyId)
|
||||
).length
|
||||
if (goneCount === 0) {
|
||||
return false
|
||||
}
|
||||
const state = useAppStore.getState()
|
||||
return (
|
||||
goneCount < facts.panes.length ||
|
||||
launchAgentTabIds(state.tabsByWorktree[worktreeId]).has(tab.id) ||
|
||||
sleepingAgentRecordIndex.hasTabPrefix(state.sleepingAgentSessionsByPaneKey, tab.id)
|
||||
)
|
||||
}
|
||||
|
||||
export function canWatcherCoverParkedTerminalTab(
|
||||
worktreeId: string,
|
||||
tab: ParkableTerminalTabModel,
|
||||
isPtyEligible: ParkedTerminalPtyEligibility = allowOrdinaryParkRestore
|
||||
): boolean {
|
||||
const facts = parkedTerminalTabCoverage(worktreeId, tab)
|
||||
return (
|
||||
facts.panes.length > 0 &&
|
||||
facts.panes.every(
|
||||
(pane) =>
|
||||
pane.ptyId !== null &&
|
||||
isTerminalLeafId(pane.leafId) &&
|
||||
isParkRestorableTerminalPty(pane.ptyId, worktreeId, facts.restorePolicy) &&
|
||||
isPtyEligible(pane.ptyId)
|
||||
) &&
|
||||
!goneSessionsKeepTabMounted(worktreeId, tab, facts)
|
||||
)
|
||||
}
|
||||
|
||||
type ParkedPaneFallbackState = {
|
||||
terminalLayoutsByTabId: ReturnType<typeof useAppStore.getState>['terminalLayoutsByTabId']
|
||||
runtimePaneTitlesByTabId: ReturnType<typeof useAppStore.getState>['runtimePaneTitlesByTabId']
|
||||
}
|
||||
|
||||
function fallbackParkedPaneCandidates(
|
||||
tab: ParkableTerminalTabModel,
|
||||
state: ParkedPaneFallbackState
|
||||
): ParkedTerminalPaneCapture[] {
|
||||
const layout = state.terminalLayoutsByTabId[tab.id]
|
||||
const rootLeafIds = collectLeafIdsInOrder(layout?.root)
|
||||
const rootlessLeafId = layout ? resolveRootlessTerminalLayoutLeafId(layout) : null
|
||||
const leafIds =
|
||||
rootLeafIds.length > 0 ? rootLeafIds : rootlessLeafId !== null ? [rootlessLeafId] : []
|
||||
if (leafIds.length === 0) {
|
||||
return []
|
||||
}
|
||||
const ptyIdsByLeafId = layout?.ptyIdsByLeafId ?? {}
|
||||
const titleSlots = Object.keys(state.runtimePaneTitlesByTabId[tab.id] ?? {})
|
||||
const reusableSlot =
|
||||
leafIds.length === 1 && titleSlots.length === 1 ? Number(titleSlots[0]) : null
|
||||
return leafIds.map((leafId, index) => ({
|
||||
ptyId: ptyIdsByLeafId[leafId] ?? (leafIds.length === 1 ? tab.ptyId : null),
|
||||
paneId: reusableSlot ?? -(index + 1),
|
||||
leafId,
|
||||
drivesTabTitle: layout?.activeLeafId ? leafId === layout.activeLeafId : index === 0
|
||||
}))
|
||||
}
|
||||
|
||||
function leafPtyKey(leafId: string, ptyId: string | null): string {
|
||||
return `${leafId}\u0000${ptyId ?? ''}\u0000${ptyId === null ? 0 : 1}`
|
||||
}
|
||||
|
||||
// Index captured panes so a many-split tab stays linear in its pane count.
|
||||
function capturedCoversFallback(
|
||||
captured: readonly ParkedTerminalPaneCapture[],
|
||||
fallback: readonly ParkedTerminalPaneCapture[]
|
||||
): boolean {
|
||||
const capturedLeafPtyKeys = new Set(
|
||||
captured.map((candidate) => leafPtyKey(candidate.leafId, candidate.ptyId))
|
||||
)
|
||||
return fallback.every((pane) => capturedLeafPtyKeys.has(leafPtyKey(pane.leafId, pane.ptyId)))
|
||||
}
|
||||
|
||||
function resolveParkedTerminalPaneCandidates(
|
||||
tab: ParkableTerminalTabModel,
|
||||
state: ParkedPaneFallbackState
|
||||
): ParkedTerminalPaneCapture[] {
|
||||
const captured = capturedPanesByTabId.get(tab.id)
|
||||
const fallback = fallbackParkedPaneCandidates(tab, state)
|
||||
if (!captured) {
|
||||
return fallback
|
||||
}
|
||||
const capturedIsCurrent =
|
||||
captured.panes.length > 0 &&
|
||||
(tab.ptyId === null || captured.panes.some((pane) => pane.ptyId === tab.ptyId)) &&
|
||||
(fallback.length === 0 ||
|
||||
(captured.panes.length === fallback.length &&
|
||||
capturedCoversFallback(captured.panes, fallback)))
|
||||
if (capturedIsCurrent) {
|
||||
return captured.panes
|
||||
}
|
||||
if (fallback.length === 0) {
|
||||
return fallback
|
||||
}
|
||||
const priorByLeafId = new Map<string, ParkedTerminalPaneCapture>()
|
||||
for (const candidate of captured.panes) {
|
||||
if (!priorByLeafId.has(candidate.leafId)) {
|
||||
priorByLeafId.set(candidate.leafId, candidate)
|
||||
}
|
||||
}
|
||||
return fallback.map((pane) => {
|
||||
const prior = priorByLeafId.get(pane.leafId)
|
||||
return prior
|
||||
? {
|
||||
...pane,
|
||||
paneId: prior.paneId,
|
||||
...(prior.ptyId === pane.ptyId && prior.workspaceOwner
|
||||
? { workspaceOwner: prior.workspaceOwner }
|
||||
: {}),
|
||||
drivesTabTitle: prior.drivesTabTitle,
|
||||
// Why: the fact belongs to the captured PTY; a re-minted id on this leaf is a different shell.
|
||||
...(prior.ptyId === pane.ptyId && prior.untouchedFreshSpawn
|
||||
? { untouchedFreshSpawn: true }
|
||||
: {})
|
||||
}
|
||||
: pane
|
||||
})
|
||||
}
|
||||
+8
-3
@@ -2,6 +2,7 @@ import { isTerminalLeafId } from '../../../../../../shared/workspace-layout/stab
|
||||
import { isProvenProcessExit } from '../../../../../../shared/terminal/pty/lifecycle/terminal-exit-cause'
|
||||
import { isRemoteRuntimePtyId } from '../../../../../../shared/remote-runtime/remote-runtime-pty-id'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { getTerminalTabOwnerWorktreeId } from '@/store/terminals/terminal-tab-owner-index'
|
||||
import { terminalProviderSessionIsGone } from '../../../terminal/terminal-provider-gone-sessions'
|
||||
import { closeTerminalTab } from '../../../terminal/terminal-tab-actions'
|
||||
import { startParkedTerminalByteWatcher } from './parked-terminal-byte-watcher'
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
} from '../../layout/close/terminal-pane-close-identity'
|
||||
import {
|
||||
capturedPanesByTabId,
|
||||
retainParkedWatcherPty,
|
||||
parkedWatchersByTabId,
|
||||
type ParkedTabWatcherEntry,
|
||||
type ParkedTerminalPaneCapture
|
||||
@@ -140,7 +142,9 @@ export function startParkedPtyWatcher(args: {
|
||||
? () => {}
|
||||
: subscribeToPtyExit(ptyId, handlePtyExit)
|
||||
entry.paneIdByPtyId.set(ptyId, pane.paneId)
|
||||
const releaseOwnership = retainParkedWatcherPty(tab.id, ptyId)
|
||||
entry.disposersByPtyId.set(ptyId, () => {
|
||||
releaseOwnership()
|
||||
unsubscribeExit()
|
||||
disposeWatcher()
|
||||
})
|
||||
@@ -174,9 +178,10 @@ export function collapseParkedTerminalLeaf(tabId: string, leafId: string, ptyId?
|
||||
if (!detached) {
|
||||
return
|
||||
}
|
||||
const terminalTab = Object.values(state.tabsByWorktree)
|
||||
.flat()
|
||||
.find((candidate) => candidate.id === tabId)
|
||||
const worktreeId = getTerminalTabOwnerWorktreeId(state.tabsByWorktree, tabId)
|
||||
const terminalTab = worktreeId
|
||||
? state.tabsByWorktree[worktreeId]?.find((candidate) => candidate.id === tabId)
|
||||
: undefined
|
||||
if (shouldClearLaunchAgentForClosedPane(terminalTab, ptyId ?? layout?.ptyIdsByLeafId?.[leafId])) {
|
||||
state.clearTabLaunchAgent(tabId)
|
||||
}
|
||||
|
||||
+33
-116
@@ -1,94 +1,29 @@
|
||||
/** Parking removes pane byte parsers; run pane-less watchers until reveal, exit or teardown. */
|
||||
import { isTerminalLeafId } from '../../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { isRemoteExecutionHostPtyId } from '../../../../../../shared/execution-host/remote-execution-host-pty-id'
|
||||
import { discardPreHandlerPtyState } from '../../pty-transport/delivery/pty-pre-handler-buffer'
|
||||
import { terminalProviderAllowsParking } from '../../../terminal/terminal-provider-snapshot-capability'
|
||||
import { terminalProviderSessionIsGone } from '../../../terminal/terminal-provider-gone-sessions'
|
||||
import {
|
||||
isParkRestorableTerminalPty,
|
||||
type TerminalParkRestorePolicy
|
||||
} from '../retention/terminal-hidden-view-parking'
|
||||
import { selectPairedRuntimeParkingEnvironmentIds } from '../retention/paired-runtime-parking-capabilities'
|
||||
import { isParkRestorableTerminalPty } from '../retention/terminal-hidden-view-parking'
|
||||
|
||||
import {
|
||||
reconcileParkedWatcherPtyIds,
|
||||
resolveParkedTerminalPaneCandidates,
|
||||
type ParkableTerminalTabModel
|
||||
} from './terminal-parked-watcher-reconciliation'
|
||||
import { launchAgentTabIds, sleepingRecordTabIds } from './parked-tab-agent-owner-index'
|
||||
import { collapseParkedExitedLeaf, startParkedPtyWatcher } from './terminal-parked-pty-watcher'
|
||||
import {
|
||||
capturedPanesByTabId,
|
||||
disposeParkedTabWatchers,
|
||||
retireParkedTerminalTab,
|
||||
parkedWatchersByTabId,
|
||||
type ParkedTabWatcherEntry,
|
||||
type ParkedTerminalPaneCapture
|
||||
} from './terminal-parked-watcher-registry'
|
||||
|
||||
export type ParkedTerminalPtyEligibility = (ptyId: string) => boolean
|
||||
|
||||
const allowOrdinaryParkRestore = (ptyId: string): boolean =>
|
||||
isRemoteExecutionHostPtyId(ptyId) || terminalProviderAllowsParking(ptyId)
|
||||
|
||||
// SSH fact watchers use local main too; coverage follows restore policy, not daemon-only snapshots.
|
||||
function parkRestorePolicyFromState(state: {
|
||||
settings: { terminalSshViewParking?: boolean } | null
|
||||
runtimeStatusByEnvironmentId: ReadonlyMap<
|
||||
string,
|
||||
{ status: { capabilities?: readonly string[] } | null | undefined }
|
||||
>
|
||||
}): TerminalParkRestorePolicy {
|
||||
return {
|
||||
sshParkingEnabled: state.settings?.terminalSshViewParking !== false,
|
||||
pairedRuntimeParkingEnvironmentIds: selectPairedRuntimeParkingEnvironmentIds(
|
||||
state.runtimeStatusByEnvironmentId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Refuse parking unless every valid-leaf PTY is restorable and watcher-covered, or bell/title/completion effects disappear. */
|
||||
export function canWatcherCoverParkedTerminalTab(
|
||||
worktreeId: string,
|
||||
tab: ParkableTerminalTabModel,
|
||||
// Local parking requires authoritative daemon snapshots; paired/SSH use their own restore policy.
|
||||
isPtyEligible: ParkedTerminalPtyEligibility = allowOrdinaryParkRestore
|
||||
): boolean {
|
||||
const state = useAppStore.getState()
|
||||
const panes = resolveParkedTerminalPaneCandidates(tab, state)
|
||||
const restorePolicy = parkRestorePolicyFromState(state)
|
||||
return (
|
||||
panes.length > 0 &&
|
||||
panes.every(
|
||||
(pane) =>
|
||||
pane.ptyId !== null &&
|
||||
isTerminalLeafId(pane.leafId) &&
|
||||
isParkRestorableTerminalPty(pane.ptyId, worktreeId, restorePolicy) &&
|
||||
isPtyEligible(pane.ptyId)
|
||||
) &&
|
||||
!goneSessionsKeepTabMounted(worktreeId, tab, panes, state)
|
||||
)
|
||||
}
|
||||
|
||||
/** A live sibling's exit would close a parked tab whose gone panes carry no watcher; an agent tab keeps its mounted restore path. */
|
||||
function goneSessionsKeepTabMounted(
|
||||
worktreeId: string,
|
||||
tab: ParkableTerminalTabModel,
|
||||
panes: readonly ParkedTerminalPaneCapture[],
|
||||
state: ReturnType<typeof useAppStore.getState>
|
||||
): boolean {
|
||||
const goneCount = panes.filter(
|
||||
(pane) => pane.ptyId !== null && terminalProviderSessionIsGone(pane.ptyId)
|
||||
).length
|
||||
if (goneCount === 0) {
|
||||
return false
|
||||
}
|
||||
return (
|
||||
goneCount < panes.length ||
|
||||
launchAgentTabIds(state.tabsByWorktree[worktreeId]).has(tab.id) ||
|
||||
sleepingRecordTabIds(state.sleepingAgentSessionsByPaneKey).has(tab.id)
|
||||
)
|
||||
}
|
||||
export { canWatcherCoverParkedTerminalTab } from './parked-terminal-tab-coverage'
|
||||
export type { ParkedTerminalPtyEligibility } from './parked-terminal-tab-coverage'
|
||||
import {
|
||||
parkedTerminalTabCoverage,
|
||||
parkRestorePolicyFromState
|
||||
} from './parked-terminal-tab-coverage'
|
||||
|
||||
function startParkedTabWatchers(
|
||||
worktreeId: string,
|
||||
@@ -103,7 +38,7 @@ function startParkedTabWatchers(
|
||||
}
|
||||
parkedWatchersByTabId.set(tab.id, entry)
|
||||
const restorePolicy = parkRestorePolicyFromState(useAppStore.getState())
|
||||
for (const pane of resolveParkedTerminalPaneCandidates(tab, useAppStore.getState())) {
|
||||
for (const pane of parkedTerminalTabCoverage(worktreeId, tab).panes) {
|
||||
startParkedPtyWatcher({
|
||||
worktreeId,
|
||||
tab,
|
||||
@@ -180,7 +115,7 @@ function watchablePanes(
|
||||
const state = useAppStore.getState()
|
||||
const restorePolicy = parkRestorePolicyFromState(state)
|
||||
return new Map(
|
||||
resolveParkedTerminalPaneCandidates(tab, state).flatMap((pane) =>
|
||||
parkedTerminalTabCoverage(worktreeId, tab).panes.flatMap((pane) =>
|
||||
pane.ptyId &&
|
||||
isTerminalLeafId(pane.leafId) &&
|
||||
isParkRestorableTerminalPty(pane.ptyId, worktreeId, restorePolicy)
|
||||
@@ -247,7 +182,11 @@ function startOrReconcileParkedTabWatchers(
|
||||
if (!entry.parkedTabIds.has(tab.id)) {
|
||||
continue
|
||||
}
|
||||
const watcherEntry = parkedWatchersByTabId.get(tab.id)
|
||||
let watcherEntry = parkedWatchersByTabId.get(tab.id)
|
||||
if (watcherEntry && watcherEntry.worktreeId !== worktreeId) {
|
||||
disposeParkedTabWatchers(tab.id)
|
||||
watcherEntry = undefined
|
||||
}
|
||||
const restoreTitleOnRegister = entry.restoreTitleOnStartTabIds?.has(tab.id) === true
|
||||
if (watcherEntry) {
|
||||
reconcileParkedTabWatchers(worktreeId, tab, watcherEntry, restoreTitleOnRegister)
|
||||
@@ -257,50 +196,28 @@ function startOrReconcileParkedTabWatchers(
|
||||
}
|
||||
}
|
||||
|
||||
/** Batch registry sweeps once per rendered workspace set for O(registry + tabs) work. Hoisting disposal/start crosses only disjoint tab sets because each tab has one workspace owner. */
|
||||
/** Reconcile only addressed workspace buckets; unrelated watchers and captures retain their owners. */
|
||||
export function syncParkedTerminalTabWatchersForWorkspaces(
|
||||
entriesByWorktreeId: ReadonlyMap<string, ParkedTerminalTabWatcherSyncEntry>
|
||||
): void {
|
||||
if (entriesByWorktreeId.size === 0) {
|
||||
return
|
||||
}
|
||||
// Allocate live-tab sets only for worktrees with registry rows.
|
||||
const liveTabIdsByWorktreeId = new Map<string, ReadonlySet<string>>()
|
||||
const liveTabIdsFor = (worktreeId: string): ReadonlySet<string> | null => {
|
||||
const cached = liveTabIdsByWorktreeId.get(worktreeId)
|
||||
if (cached) {
|
||||
return cached
|
||||
}
|
||||
const entry = entriesByWorktreeId.get(worktreeId)
|
||||
if (!entry) {
|
||||
return null
|
||||
}
|
||||
const liveTabIds = new Set(entry.tabs.map((tab) => tab.id))
|
||||
liveTabIdsByWorktreeId.set(worktreeId, liveTabIds)
|
||||
return liveTabIds
|
||||
}
|
||||
for (const [tabId, watcherEntry] of parkedWatchersByTabId) {
|
||||
const entry = entriesByWorktreeId.get(watcherEntry.worktreeId)
|
||||
if (!entry) {
|
||||
continue
|
||||
}
|
||||
const liveTabIds = liveTabIdsFor(watcherEntry.worktreeId)
|
||||
if (!liveTabIds?.has(tabId)) {
|
||||
disposeClosedParkedTabWatchers(tabId, watcherEntry)
|
||||
continue
|
||||
}
|
||||
if (!entry.parkedTabIds.has(tabId) && watcherEntry.disposersByPtyId.size > 0) {
|
||||
disposeParkedTabWatchers(tabId)
|
||||
}
|
||||
}
|
||||
// Why: closed tabs never park/reveal again; drop captures to keep the registry bounded.
|
||||
for (const [tabId, capture] of capturedPanesByTabId) {
|
||||
const liveTabIds = liveTabIdsFor(capture.worktreeId)
|
||||
if (liveTabIds && !liveTabIds.has(tabId)) {
|
||||
capturedPanesByTabId.delete(tabId)
|
||||
}
|
||||
}
|
||||
for (const [worktreeId, entry] of entriesByWorktreeId) {
|
||||
const liveTabIds = new Set(entry.tabs.map((tab) => tab.id))
|
||||
for (const tabId of Array.from(parkedWatchersByTabId.workspaceTabIds(worktreeId))) {
|
||||
const watcherEntry = parkedWatchersByTabId.get(tabId)
|
||||
if (!watcherEntry) {
|
||||
continue
|
||||
}
|
||||
if (!liveTabIds.has(tabId)) {
|
||||
disposeClosedParkedTabWatchers(tabId, watcherEntry)
|
||||
} else if (!entry.parkedTabIds.has(tabId) && watcherEntry.disposersByPtyId.size > 0) {
|
||||
disposeParkedTabWatchers(tabId)
|
||||
}
|
||||
}
|
||||
for (const tabId of Array.from(capturedPanesByTabId.workspaceTabIds(worktreeId))) {
|
||||
if (!liveTabIds.has(tabId)) {
|
||||
retireParkedTerminalTab(tabId)
|
||||
}
|
||||
}
|
||||
startOrReconcileParkedTabWatchers(worktreeId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
-97
@@ -1,104 +1,7 @@
|
||||
import type { TerminalTab } from '../../../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { useAppStore } from '@/store/index'
|
||||
import { collectLeafIdsInOrder } from '../../layout/terminal-layout-leaf-traversal'
|
||||
import { resolveRootlessTerminalLayoutLeafId } from '../../../../../../shared/workspace-layout/terminal-pane-tree'
|
||||
import {
|
||||
capturedPanesByTabId,
|
||||
type ParkedTerminalPaneCapture
|
||||
} from './terminal-parked-watcher-registry'
|
||||
|
||||
export type ParkableTerminalTabModel = Pick<TerminalTab, 'id' | 'ptyId'>
|
||||
|
||||
type ParkedPaneFallbackState = {
|
||||
terminalLayoutsByTabId: ReturnType<typeof useAppStore.getState>['terminalLayoutsByTabId']
|
||||
runtimePaneTitlesByTabId: ReturnType<typeof useAppStore.getState>['runtimePaneTitlesByTabId']
|
||||
}
|
||||
|
||||
export function fallbackParkedPaneCandidates(
|
||||
tab: ParkableTerminalTabModel,
|
||||
state: ParkedPaneFallbackState
|
||||
): ParkedTerminalPaneCapture[] {
|
||||
const layout = state.terminalLayoutsByTabId[tab.id]
|
||||
const rootLeafIds = collectLeafIdsInOrder(layout?.root)
|
||||
const rootlessLeafId = layout ? resolveRootlessTerminalLayoutLeafId(layout) : null
|
||||
const leafIds =
|
||||
rootLeafIds.length > 0 ? rootLeafIds : rootlessLeafId !== null ? [rootlessLeafId] : []
|
||||
if (leafIds.length === 0) {
|
||||
return []
|
||||
}
|
||||
const ptyIdsByLeafId = layout?.ptyIdsByLeafId ?? {}
|
||||
const titleSlots = Object.keys(state.runtimePaneTitlesByTabId[tab.id] ?? {})
|
||||
const reusableSlot =
|
||||
leafIds.length === 1 && titleSlots.length === 1 ? Number(titleSlots[0]) : null
|
||||
return leafIds.map((leafId, index) => ({
|
||||
ptyId: ptyIdsByLeafId[leafId] ?? (leafIds.length === 1 ? tab.ptyId : null),
|
||||
paneId: reusableSlot ?? -(index + 1),
|
||||
leafId,
|
||||
drivesTabTitle: layout?.activeLeafId ? leafId === layout.activeLeafId : index === 0
|
||||
}))
|
||||
}
|
||||
|
||||
function leafPtyKey(leafId: string, ptyId: string | null): string {
|
||||
return `${leafId}\u0000${ptyId ?? ''}\u0000${ptyId === null ? 0 : 1}`
|
||||
}
|
||||
|
||||
// Index captured panes so a many-split tab stays linear in its pane count.
|
||||
function capturedCoversFallback(
|
||||
captured: readonly ParkedTerminalPaneCapture[],
|
||||
fallback: readonly ParkedTerminalPaneCapture[]
|
||||
): boolean {
|
||||
const capturedLeafPtyKeys = new Set(
|
||||
captured.map((candidate) => leafPtyKey(candidate.leafId, candidate.ptyId))
|
||||
)
|
||||
return fallback.every((pane) => capturedLeafPtyKeys.has(leafPtyKey(pane.leafId, pane.ptyId)))
|
||||
}
|
||||
|
||||
export function resolveParkedTerminalPaneCandidates(
|
||||
tab: ParkableTerminalTabModel,
|
||||
state: ParkedPaneFallbackState
|
||||
): ParkedTerminalPaneCapture[] {
|
||||
const captured = capturedPanesByTabId.get(tab.id)
|
||||
const fallback = fallbackParkedPaneCandidates(tab, state)
|
||||
if (!captured) {
|
||||
return fallback
|
||||
}
|
||||
const capturedIsCurrent =
|
||||
captured.panes.length > 0 &&
|
||||
(tab.ptyId === null || captured.panes.some((pane) => pane.ptyId === tab.ptyId)) &&
|
||||
(fallback.length === 0 ||
|
||||
(captured.panes.length === fallback.length &&
|
||||
capturedCoversFallback(captured.panes, fallback)))
|
||||
if (capturedIsCurrent) {
|
||||
return captured.panes
|
||||
}
|
||||
if (fallback.length === 0) {
|
||||
return fallback
|
||||
}
|
||||
const priorByLeafId = new Map<string, ParkedTerminalPaneCapture>()
|
||||
for (const candidate of captured.panes) {
|
||||
if (!priorByLeafId.has(candidate.leafId)) {
|
||||
priorByLeafId.set(candidate.leafId, candidate)
|
||||
}
|
||||
}
|
||||
return fallback.map((pane) => {
|
||||
const prior = priorByLeafId.get(pane.leafId)
|
||||
return prior
|
||||
? {
|
||||
...pane,
|
||||
paneId: prior.paneId,
|
||||
...(prior.ptyId === pane.ptyId && prior.workspaceOwner
|
||||
? { workspaceOwner: prior.workspaceOwner }
|
||||
: {}),
|
||||
drivesTabTitle: prior.drivesTabTitle,
|
||||
// Why: the fact belongs to the captured PTY; a re-minted id on this leaf is a different shell.
|
||||
...(prior.ptyId === pane.ptyId && prior.untouchedFreshSpawn
|
||||
? { untouchedFreshSpawn: true }
|
||||
: {})
|
||||
}
|
||||
: pane
|
||||
})
|
||||
}
|
||||
|
||||
export function reconcileParkedWatcherPtyIds(args: {
|
||||
currentTabPtyId: string | null
|
||||
entryTabPtyId: string | null
|
||||
|
||||
+126
-29
@@ -1,4 +1,6 @@
|
||||
/** Store-free registry/disposal lets shutdown slices stop watchers synchronously without re-entering store initialization through the watcher lifecycle import. */
|
||||
import { WorkspaceParkedTerminalRegistry } from './workspace-parked-terminal-registry'
|
||||
import { invalidateTerminalParkingInputs } from '../terminal-parking-input-events'
|
||||
import type { NotificationWorkspaceOwner } from '../../../../../../shared/notification-source'
|
||||
import {
|
||||
discardPreHandlerPtyState,
|
||||
@@ -22,7 +24,83 @@ export type ParkedTerminalPaneCapture = {
|
||||
|
||||
export type CapturedTabPanes = { worktreeId: string; panes: ParkedTerminalPaneCapture[] }
|
||||
|
||||
export const capturedPanesByTabId = new Map<string, CapturedTabPanes>()
|
||||
const captureRevisions = new Map<string, number>()
|
||||
const captureTabIdsByPtyId = new Map<string, Set<string>>()
|
||||
const captureTabIdsByEnvironmentId = new Map<string, Set<string>>()
|
||||
|
||||
function updateCaptureMembership(tabId: string, capture: CapturedTabPanes, add: boolean): void {
|
||||
for (const pane of capture.panes) {
|
||||
if (!pane.ptyId) {
|
||||
continue
|
||||
}
|
||||
const environmentId = parseRemoteRuntimePtyId(pane.ptyId)?.environmentId
|
||||
for (const [index, key] of [
|
||||
[captureTabIdsByPtyId, pane.ptyId],
|
||||
[captureTabIdsByEnvironmentId, environmentId]
|
||||
] as const) {
|
||||
if (!key) {
|
||||
continue
|
||||
}
|
||||
if (add) {
|
||||
let ids = index.get(key)
|
||||
if (!ids) {
|
||||
index.set(key, (ids = new Set()))
|
||||
}
|
||||
ids.add(tabId)
|
||||
} else {
|
||||
const ids = index.get(key)
|
||||
ids?.delete(tabId)
|
||||
if (ids?.size === 0) {
|
||||
index.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function capturedTerminalWorkspacesForPtyIds(ptyIds: Iterable<string>): Set<string> {
|
||||
return capturedWorkspaceIds(captureTabIdsByPtyId, ptyIds)
|
||||
}
|
||||
|
||||
export function capturedTerminalWorkspacesForEnvironmentIds(ids: Iterable<string>): Set<string> {
|
||||
return capturedWorkspaceIds(captureTabIdsByEnvironmentId, ids)
|
||||
}
|
||||
|
||||
function capturedWorkspaceIds(
|
||||
index: ReadonlyMap<string, ReadonlySet<string>>,
|
||||
keys: Iterable<string>
|
||||
) {
|
||||
const worktreeIds = new Set<string>()
|
||||
for (const key of keys) {
|
||||
for (const tabId of index.get(key) ?? []) {
|
||||
const capture = capturedPanesByTabId.get(tabId)
|
||||
if (capture) {
|
||||
worktreeIds.add(capture.worktreeId)
|
||||
}
|
||||
}
|
||||
}
|
||||
return worktreeIds
|
||||
}
|
||||
export const capturedPanesByTabId = new WorkspaceParkedTerminalRegistry<CapturedTabPanes>(
|
||||
(tabId, worktreeId, previous, next) => {
|
||||
if (previous) {
|
||||
updateCaptureMembership(tabId, previous, false)
|
||||
}
|
||||
if (next) {
|
||||
updateCaptureMembership(tabId, next, true)
|
||||
}
|
||||
if (capturedPanesByTabId.has(tabId)) {
|
||||
captureRevisions.set(tabId, (captureRevisions.get(tabId) ?? 0) + 1)
|
||||
} else {
|
||||
captureRevisions.delete(tabId)
|
||||
}
|
||||
invalidateTerminalParkingInputs(worktreeId)
|
||||
}
|
||||
)
|
||||
|
||||
export function parkedTerminalCaptureRevision(tabId: string): number {
|
||||
return captureRevisions.get(tabId) ?? 0
|
||||
}
|
||||
|
||||
// Capture original runtime-title slots before numeric IDs disappear on unmount, or stale working titles can pin status.
|
||||
export function captureParkedTerminalPaneCandidates(
|
||||
@@ -42,7 +120,22 @@ export type ParkedTabWatcherEntry = {
|
||||
disposersByPtyId: Map<string, () => void>
|
||||
}
|
||||
|
||||
export const parkedWatchersByTabId = new Map<string, ParkedTabWatcherEntry>()
|
||||
export const parkedWatchersByTabId = new WorkspaceParkedTerminalRegistry<ParkedTabWatcherEntry>()
|
||||
const watcherTabIdsByPtyId = new Map<string, Set<string>>()
|
||||
|
||||
export function retainParkedWatcherPty(tabId: string, ptyId: string): () => void {
|
||||
let tabIds = watcherTabIdsByPtyId.get(ptyId)
|
||||
if (!tabIds) {
|
||||
watcherTabIdsByPtyId.set(ptyId, (tabIds = new Set()))
|
||||
}
|
||||
tabIds.add(tabId)
|
||||
return () => {
|
||||
tabIds.delete(tabId)
|
||||
if (tabIds.size === 0) {
|
||||
watcherTabIdsByPtyId.delete(ptyId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getParkedTerminalWatcherTabIds(): string[] {
|
||||
return Array.from(parkedWatchersByTabId.keys())
|
||||
@@ -99,17 +192,17 @@ export function retireParkedTerminalTab(tabId: string): void {
|
||||
}
|
||||
capturedPanesByTabId.delete(tabId)
|
||||
}
|
||||
captureRevisions.delete(tabId)
|
||||
}
|
||||
|
||||
/** Dispose sidecars only after shutdown commits; retain tab entries against stale-ID restarts until wake remints IDs. */
|
||||
export function disposeParkedTerminalWatchersForPtyIds(ptyIds: readonly string[]): void {
|
||||
for (const entry of parkedWatchersByTabId.values()) {
|
||||
for (const ptyId of ptyIds) {
|
||||
const dispose = entry.disposersByPtyId.get(ptyId)
|
||||
if (dispose) {
|
||||
entry.disposersByPtyId.delete(ptyId)
|
||||
dispose()
|
||||
}
|
||||
for (const ptyId of ptyIds) {
|
||||
for (const tabId of Array.from(watcherTabIdsByPtyId.get(ptyId) ?? [])) {
|
||||
const entry = parkedWatchersByTabId.get(tabId)
|
||||
const dispose = entry?.disposersByPtyId.get(ptyId)
|
||||
entry?.disposersByPtyId.delete(ptyId)
|
||||
dispose?.()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,13 +211,15 @@ export function disposeParkedTerminalWatchersForWorktree(
|
||||
worktreeId: string,
|
||||
options?: { consumePreHandlerState?: boolean }
|
||||
): void {
|
||||
for (const [tabId, entry] of parkedWatchersByTabId) {
|
||||
if (entry.worktreeId === worktreeId) {
|
||||
if (options?.consumePreHandlerState) {
|
||||
disposeRemovedWorktreeParkedTabWatchers(tabId, entry)
|
||||
} else {
|
||||
disposeParkedTabWatchers(tabId)
|
||||
}
|
||||
for (const tabId of Array.from(parkedWatchersByTabId.workspaceTabIds(worktreeId))) {
|
||||
const entry = parkedWatchersByTabId.get(tabId)
|
||||
if (!entry) {
|
||||
continue
|
||||
}
|
||||
if (options?.consumePreHandlerState) {
|
||||
disposeRemovedWorktreeParkedTabWatchers(tabId, entry)
|
||||
} else {
|
||||
disposeParkedTabWatchers(tabId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,20 +251,22 @@ function disposeRemovedWorktreeParkedTabWatchers(
|
||||
disposeParkedTabWatchers(tabId)
|
||||
}
|
||||
|
||||
/** Drops watchers and captures for worktrees that no longer exist. */
|
||||
export function pruneParkedTerminalWatchers(liveWorktreeIds: ReadonlySet<string>): void {
|
||||
for (const [tabId, entry] of parkedWatchersByTabId) {
|
||||
if (!liveWorktreeIds.has(entry.worktreeId)) {
|
||||
disposeRemovedWorktreeParkedTabWatchers(tabId, entry)
|
||||
}
|
||||
export function retireParkedTerminalWorktree(worktreeId: string): void {
|
||||
disposeRemovedWorktreeParkedTerminalWatchers(worktreeId)
|
||||
for (const tabId of Array.from(capturedPanesByTabId.workspaceTabIds(worktreeId))) {
|
||||
retireParkedTerminalTab(tabId)
|
||||
}
|
||||
for (const [tabId, capture] of capturedPanesByTabId) {
|
||||
if (!liveWorktreeIds.has(capture.worktreeId)) {
|
||||
for (const pane of capture.panes) {
|
||||
// Workspace removal can bypass parked closeTab; release its strong scroll-intent keys too.
|
||||
releaseTerminalScrollIntentKey(pane.leafId)
|
||||
}
|
||||
capturedPanesByTabId.delete(tabId)
|
||||
}
|
||||
|
||||
/** Cold workspace-catalog replacement only; normal removals retire their addressed workspace. */
|
||||
export function pruneParkedTerminalWatchers(liveWorktreeIds: ReadonlySet<string>): void {
|
||||
const registeredIds = new Set([
|
||||
...parkedWatchersByTabId.workspaceIds(),
|
||||
...capturedPanesByTabId.workspaceIds()
|
||||
])
|
||||
for (const worktreeId of registeredIds) {
|
||||
if (!liveWorktreeIds.has(worktreeId)) {
|
||||
retireParkedTerminalWorktree(worktreeId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/** Keep reverse ownership in the mutation API, including exit tombstones and captures written during unmount. */
|
||||
export class WorkspaceParkedTerminalRegistry<T extends { worktreeId: string }> extends Map<
|
||||
string,
|
||||
T
|
||||
> {
|
||||
private readonly tabIdsByWorktreeId = new Map<string, Set<string>>()
|
||||
|
||||
constructor(
|
||||
private readonly changed?: (
|
||||
tabId: string,
|
||||
worktreeId: string,
|
||||
previous: T | undefined,
|
||||
next: T | undefined
|
||||
) => void
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
override set(tabId: string, entry: T): this {
|
||||
const previous = this.get(tabId)
|
||||
if (previous === entry) {
|
||||
return this
|
||||
}
|
||||
if (previous && previous.worktreeId !== entry.worktreeId) {
|
||||
this.delete(tabId)
|
||||
}
|
||||
let bucket = this.tabIdsByWorktreeId.get(entry.worktreeId)
|
||||
if (!bucket) {
|
||||
this.tabIdsByWorktreeId.set(entry.worktreeId, (bucket = new Set()))
|
||||
}
|
||||
bucket.add(tabId)
|
||||
super.set(tabId, entry)
|
||||
this.changed?.(tabId, entry.worktreeId, previous, entry)
|
||||
return this
|
||||
}
|
||||
|
||||
override delete(tabId: string): boolean {
|
||||
const previous = this.get(tabId)
|
||||
if (!previous) {
|
||||
return false
|
||||
}
|
||||
super.delete(tabId)
|
||||
const bucket = this.tabIdsByWorktreeId.get(previous.worktreeId)
|
||||
bucket?.delete(tabId)
|
||||
if (bucket?.size === 0) {
|
||||
this.tabIdsByWorktreeId.delete(previous.worktreeId)
|
||||
}
|
||||
this.changed?.(tabId, previous.worktreeId, previous, undefined)
|
||||
return true
|
||||
}
|
||||
|
||||
override clear(): void {
|
||||
for (const tabId of this.keys()) {
|
||||
this.delete(tabId)
|
||||
}
|
||||
}
|
||||
|
||||
workspaceTabIds(worktreeId: string): Iterable<string> {
|
||||
return this.tabIdsByWorktreeId.get(worktreeId) ?? []
|
||||
}
|
||||
|
||||
workspaceIds(): Iterable<string> {
|
||||
return this.tabIdsByWorktreeId.keys()
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -1,4 +1,5 @@
|
||||
import '../../../../../../shared/protocol-version'
|
||||
import { terminalInputRecordChangedKeys } from '@/store/terminals/terminal-input-record-transition'
|
||||
import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../../../../shared/terminal/runtime-policy/terminal-runtime-capabilities'
|
||||
import {
|
||||
isRuntimeHostContactRevoked,
|
||||
@@ -46,8 +47,15 @@ export function createPairedRuntimeParkingEnvironmentIdsSelector() {
|
||||
return cached.environmentIds
|
||||
}
|
||||
|
||||
const capable = new Set<string>()
|
||||
for (const [environmentId, entry] of statuses) {
|
||||
const changedIds = cached ? terminalInputRecordChangedKeys(cached.statuses, statuses) : null
|
||||
const capable = changedIds ? new Set(cached?.environmentIds) : new Set<string>()
|
||||
const environmentIdsToInspect = changedIds ?? statuses.keys()
|
||||
for (const environmentId of environmentIdsToInspect) {
|
||||
capable.delete(environmentId)
|
||||
const entry = statuses.get(environmentId)
|
||||
if (!entry) {
|
||||
continue
|
||||
}
|
||||
// Keep last-verified build capabilities across unverifiable probes; a revoked host cannot promise restoration (docs/reference/ssh-execution-boundary.md).
|
||||
if (isRuntimeHostContactRevoked(entry)) {
|
||||
continue
|
||||
|
||||
+26
-43
@@ -4,7 +4,7 @@ import {
|
||||
parsePaneKey
|
||||
} from '../../../../../../shared/workspace-layout/stable-pane-id'
|
||||
import { activationTreatsNoteAsFinished } from '../../../../lib/agent-session/resume/sleeping-agent-pane-ownership'
|
||||
import { createWorktreeRecordSelector } from '@/store/terminals/worktree-terminal-record-selector'
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
|
||||
const EMPTY_TAB_IDS: ReadonlySet<string> = new Set()
|
||||
|
||||
@@ -12,51 +12,34 @@ type SleepingRecordParkExemptionState = {
|
||||
sleepingAgentSessionsByPaneKey?: Record<string, SleepingAgentSessionRecord>
|
||||
}
|
||||
|
||||
let exemptTabIdsByWorktreeCache: {
|
||||
records: Record<string, SleepingAgentSessionRecord>
|
||||
byWorktreeId: ReadonlyMap<string, ReadonlySet<string>>
|
||||
} | null = null
|
||||
const exemptionsByEntries = new WeakMap<object, ReadonlySet<string>>()
|
||||
|
||||
/** Group consumable records by worktree once per record map; each mounted worktree then reads its bucket instead of rescanning every record. */
|
||||
function exemptTabIdsByWorktree(
|
||||
records: Record<string, SleepingAgentSessionRecord>
|
||||
): ReadonlyMap<string, ReadonlySet<string>> {
|
||||
if (exemptTabIdsByWorktreeCache?.records === records) {
|
||||
return exemptTabIdsByWorktreeCache.byWorktreeId
|
||||
/** Only consumable parsed records pin panes; raw prefix ownership is a separate coverage fact. */
|
||||
export function selectSleepingRecordParkExemptTabIds(
|
||||
state: SleepingRecordParkExemptionState,
|
||||
worktreeId: string
|
||||
): ReadonlySet<string> {
|
||||
if (!state.sleepingAgentSessionsByPaneKey) {
|
||||
return EMPTY_TAB_IDS
|
||||
}
|
||||
const byWorktreeId = new Map<string, Set<string>>()
|
||||
for (const paneKey in records) {
|
||||
const record = records[paneKey]
|
||||
if (!record || activationTreatsNoteAsFinished(record)) {
|
||||
continue
|
||||
}
|
||||
// Why: malformed pane keys must yield no owner instead of a truncated tab id.
|
||||
const tabId =
|
||||
record.tabId ??
|
||||
parsePaneKey(record.paneKey)?.tabId ??
|
||||
parseLegacyNumericPaneKey(record.paneKey)?.tabId
|
||||
if (tabId) {
|
||||
let owned = byWorktreeId.get(record.worktreeId)
|
||||
if (!owned) {
|
||||
owned = new Set()
|
||||
byWorktreeId.set(record.worktreeId, owned)
|
||||
const entries = sleepingAgentRecordIndex.entries(state.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
let tabIds = exemptionsByEntries.get(entries)
|
||||
if (!tabIds) {
|
||||
const ids = new Set<string>()
|
||||
for (const [, record] of entries) {
|
||||
if (activationTreatsNoteAsFinished(record)) {
|
||||
continue
|
||||
}
|
||||
const tabId =
|
||||
record.tabId ??
|
||||
parsePaneKey(record.paneKey)?.tabId ??
|
||||
parseLegacyNumericPaneKey(record.paneKey)?.tabId
|
||||
if (tabId) {
|
||||
ids.add(tabId)
|
||||
}
|
||||
owned.add(tabId)
|
||||
}
|
||||
tabIds = ids
|
||||
exemptionsByEntries.set(entries, tabIds)
|
||||
}
|
||||
exemptTabIdsByWorktreeCache = { records, byWorktreeId }
|
||||
return byWorktreeId
|
||||
return tabIds
|
||||
}
|
||||
|
||||
/** Exempt only consumable sleeping records: parked panes cannot cold-restore, but finished notes would pin panes forever. Memoize by record-map identity to avoid rescanning every worktree on unrelated writes. */
|
||||
export const selectSleepingRecordParkExemptTabIds = createWorktreeRecordSelector<
|
||||
SleepingRecordParkExemptionState,
|
||||
ReadonlySet<string>
|
||||
>({
|
||||
readSources: (state) => [state.sleepingAgentSessionsByPaneKey],
|
||||
empty: EMPTY_TAB_IDS,
|
||||
build: ({ sleepingAgentSessionsByPaneKey }, worktreeId) =>
|
||||
sleepingAgentSessionsByPaneKey
|
||||
? (exemptTabIdsByWorktree(sleepingAgentSessionsByPaneKey).get(worktreeId) ?? EMPTY_TAB_IDS)
|
||||
: EMPTY_TAB_IDS
|
||||
})
|
||||
|
||||
+3
-6
@@ -1,11 +1,8 @@
|
||||
import { parkedTerminalTabCoverage } from '../output-watchers/parked-terminal-tab-coverage'
|
||||
/** Keep unrestorable live PTYs mounted through force-park so remount cannot orphan their shells. */
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { isEvictionExemptTerminalPty } from './terminal-hidden-worktree-retention'
|
||||
import '../output-watchers/terminal-parked-tab-watchers'
|
||||
import {
|
||||
resolveParkedTerminalPaneCandidates,
|
||||
type ParkableTerminalTabModel
|
||||
} from '../output-watchers/terminal-parked-watcher-reconciliation'
|
||||
import type { ParkableTerminalTabModel } from '../output-watchers/terminal-parked-watcher-reconciliation'
|
||||
|
||||
/** Check every split PTY plus tab.ptyId fallback; the first leaf alone misses unrestorable siblings. Retention is per tab, so one exempt pane pins its split siblings beyond the budget; sibling tabs remain evictable. */
|
||||
export function isEvictionExemptTerminalTab(
|
||||
@@ -15,7 +12,7 @@ export function isEvictionExemptTerminalTab(
|
||||
if (isEvictionExemptTerminalPty(tab.ptyId, worktreeId)) {
|
||||
return true
|
||||
}
|
||||
return resolveParkedTerminalPaneCandidates(tab, useAppStore.getState()).some((pane) =>
|
||||
return parkedTerminalTabCoverage(worktreeId, tab).panes.some((pane) =>
|
||||
isEvictionExemptTerminalPty(pane.ptyId, worktreeId)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
const revisions = new Map<string, number>()
|
||||
const listeners = new Map<string, Set<() => void>>()
|
||||
const addressedListeners = new Set<(worktreeId: string) => void>()
|
||||
let epoch = 0
|
||||
|
||||
export function terminalParkingInputEpoch(): number {
|
||||
return epoch
|
||||
}
|
||||
|
||||
export function terminalParkingInputRevision(worktreeId: string): number {
|
||||
return revisions.get(worktreeId) ?? 0
|
||||
}
|
||||
|
||||
export function invalidateTerminalParkingInputs(worktreeId: string): void {
|
||||
epoch += 1
|
||||
revisions.set(worktreeId, epoch)
|
||||
for (const listener of listeners.get(worktreeId) ?? []) {
|
||||
listener()
|
||||
}
|
||||
for (const listener of addressedListeners) {
|
||||
listener(worktreeId)
|
||||
}
|
||||
}
|
||||
|
||||
export function retireTerminalParkingInputs(worktreeId: string): void {
|
||||
if (!revisions.delete(worktreeId)) {
|
||||
return
|
||||
}
|
||||
epoch += 1
|
||||
for (const listener of listeners.get(worktreeId) ?? []) {
|
||||
listener()
|
||||
}
|
||||
for (const listener of addressedListeners) {
|
||||
listener(worktreeId)
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeTerminalParkingInputs(worktreeId: string, listener: () => void) {
|
||||
let bucket = listeners.get(worktreeId)
|
||||
if (!bucket) {
|
||||
listeners.set(worktreeId, (bucket = new Set()))
|
||||
}
|
||||
bucket.add(listener)
|
||||
return () => {
|
||||
bucket.delete(listener)
|
||||
if (bucket.size === 0) {
|
||||
listeners.delete(worktreeId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeAddressedTerminalParkingInputs(
|
||||
listener: (worktreeId: string) => void
|
||||
): () => void {
|
||||
addressedListeners.add(listener)
|
||||
return () => addressedListeners.delete(listener)
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { useCallback, useRef, useSyncExternalStore } from 'react'
|
||||
import {
|
||||
subscribeAddressedTerminalParkingInputs,
|
||||
terminalParkingInputEpoch
|
||||
} from './terminal-parking-input-events'
|
||||
|
||||
/** A missed pre-subscription transition is an unknown snapshot, never an assumed complete dirty list. */
|
||||
export function useTerminalParkingWorkspaceChanges(workspaceIds: readonly string[]) {
|
||||
const pending = useRef(new Set(workspaceIds))
|
||||
const observedEpoch = useRef(terminalParkingInputEpoch())
|
||||
const subscribe = useCallback((changed: () => void) => {
|
||||
return subscribeAddressedTerminalParkingInputs((worktreeId) => {
|
||||
pending.current.add(worktreeId)
|
||||
observedEpoch.current = terminalParkingInputEpoch()
|
||||
changed()
|
||||
})
|
||||
}, [])
|
||||
const revision = useSyncExternalStore(subscribe, terminalParkingInputEpoch)
|
||||
const takeChangedWorkspaces = useCallback((): Set<string> => {
|
||||
const dirty = pending.current
|
||||
pending.current = new Set()
|
||||
if (observedEpoch.current !== terminalParkingInputEpoch()) {
|
||||
for (const id of workspaceIds) {
|
||||
dirty.add(id)
|
||||
}
|
||||
observedEpoch.current = terminalParkingInputEpoch()
|
||||
}
|
||||
return dirty
|
||||
}, [workspaceIds])
|
||||
return { revision, takeChangedWorkspaces }
|
||||
}
|
||||
+11
-2
@@ -1,6 +1,7 @@
|
||||
import { installSavedResumeStartupCancellation } from './saved-resume-startup-cancellation'
|
||||
import { launchConfigsEqual } from '../../../../../../shared/agent-session/lifecycle/agent-resume-record-equivalence'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import type { PtyConnectResult } from '../../pty-transport/pty-transport-types'
|
||||
import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../../shared/non-secure-context-uuid'
|
||||
import { findLegacyNumericSleepingRecord } from '../../../../../../shared/sleeping-record-legacy-pane-key'
|
||||
@@ -30,7 +31,12 @@ export function installSleepingRecordAccess(session: ConnectPanePtySession): voi
|
||||
return { paneKey: session.cacheKey, record: stableRecord }
|
||||
}
|
||||
const legacy = findLegacyNumericSleepingRecord(
|
||||
state.sleepingAgentSessionsByPaneKey,
|
||||
Object.fromEntries(
|
||||
sleepingAgentRecordIndex.entries(
|
||||
state.sleepingAgentSessionsByPaneKey,
|
||||
session.deps.worktreeId
|
||||
)
|
||||
),
|
||||
{ tabId: session.deps.tabId, numericPaneId: String(session.pane.id) },
|
||||
(record) => record.worktreeId === session.deps.worktreeId
|
||||
)
|
||||
@@ -44,7 +50,10 @@ export function installSleepingRecordAccess(session: ConnectPanePtySession): voi
|
||||
if (consumed.paneKey !== keepPaneKey) {
|
||||
state.clearSleepingAgentSession(consumed.paneKey)
|
||||
}
|
||||
for (const [paneKey, record] of Object.entries(state.sleepingAgentSessionsByPaneKey)) {
|
||||
for (const [paneKey, record] of sleepingAgentRecordIndex.entries(
|
||||
state.sleepingAgentSessionsByPaneKey,
|
||||
consumed.record.worktreeId
|
||||
)) {
|
||||
if (
|
||||
paneKey !== consumed.paneKey &&
|
||||
paneKey !== keepPaneKey &&
|
||||
|
||||
@@ -1,18 +1,40 @@
|
||||
import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types'
|
||||
import {
|
||||
TERMINAL_WORKTREE_COLD_PARK_DELAY_MS,
|
||||
TERMINAL_WORKTREE_HOT_RETAIN_MS,
|
||||
TERMINAL_WORKTREE_HOT_RETAIN_LIMIT,
|
||||
canParkTerminalWorktreeRenderers,
|
||||
selectColdParkedTerminalWorktrees,
|
||||
selectIdsBeyondHotRetain,
|
||||
type TerminalWorktreeColdParkCandidate
|
||||
} from './terminal-pane/parking/retention/terminal-hidden-view-parking'
|
||||
import {
|
||||
hasPendingRetentionSpawnWork,
|
||||
TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS,
|
||||
type TerminalWorktreeRetentionCandidate
|
||||
} from './terminal-pane/parking/retention/terminal-hidden-worktree-retention'
|
||||
import { getTerminalParkingPolicyOverrides } from './terminal-pane/parking/instrumentation/terminal-parking-e2e-overrides'
|
||||
import { canWatcherCoverParkedTerminalTab } from './terminal-pane/parking/output-watchers/terminal-parked-tab-watchers'
|
||||
import { getHeldTerminalPrewarmWorktrees } from './terminal/terminal-worktree-prewarm'
|
||||
import type { TerminalParkingFoundation } from './use-terminal-parking-foundation'
|
||||
|
||||
export type TerminalParkingPassCandidates = ReturnType<typeof collectTerminalParkingPassCandidates>
|
||||
type CandidateOwner = {
|
||||
candidates: Map<string, TerminalWorktreeColdParkCandidate>
|
||||
ordinarilyEligible: Map<
|
||||
string,
|
||||
{ id: string; hiddenSinceMs: number; covered: boolean; keepWarm: boolean }
|
||||
>
|
||||
budget: Map<string, TerminalWorktreeRetentionCandidate>
|
||||
phases: Map<string, string>
|
||||
ordinaryParked: ReadonlySet<string>
|
||||
budgetSnapshot: TerminalWorktreeRetentionCandidate[]
|
||||
}
|
||||
const owners = new WeakMap<object, CandidateOwner>()
|
||||
|
||||
export function collectTerminalParkingPassCandidates(controller: TerminalParkingFoundation) {
|
||||
/** Keep eligibility local; the real cross-workspace budget ranks cached metadata, never rechecks unrelated PTYs. */
|
||||
export function collectTerminalParkingPassCandidates(
|
||||
controller: TerminalParkingFoundation,
|
||||
dirty: ReadonlySet<string>
|
||||
) {
|
||||
const {
|
||||
activeView,
|
||||
activityTerminalPortals,
|
||||
@@ -28,38 +50,52 @@ export function collectTerminalParkingPassCandidates(controller: TerminalParking
|
||||
terminalWorktreeHiddenSinceRef,
|
||||
terminalWorktreeParkCooldownUntilRef,
|
||||
terminalWorktreeParkingTimersRef,
|
||||
workspaceSurfaceIds,
|
||||
workspaceSurfaceIdSet
|
||||
} = controller
|
||||
const parkingTimers = terminalWorktreeParkingTimersRef.current
|
||||
for (const timer of parkingTimers.values()) {
|
||||
window.clearTimeout(timer)
|
||||
let owner = owners.get(terminalWorktreeHiddenSinceRef)
|
||||
if (!owner) {
|
||||
owner = {
|
||||
candidates: new Map(),
|
||||
ordinarilyEligible: new Map(),
|
||||
budget: new Map(),
|
||||
phases: new Map(),
|
||||
ordinaryParked: new Set(),
|
||||
budgetSnapshot: []
|
||||
}
|
||||
owners.set(terminalWorktreeHiddenSinceRef, owner)
|
||||
}
|
||||
parkingTimers.clear()
|
||||
|
||||
let rankingChanged = false
|
||||
const nowMs = Date.now()
|
||||
const overrides = getTerminalParkingPolicyOverrides()
|
||||
const portalWorktreeIds = new Set(activityTerminalPortals.map((portal) => portal.worktreeId))
|
||||
for (const worktreeId of Array.from(terminalWorktreeHiddenSinceRef.current.keys())) {
|
||||
const restorePolicy = {
|
||||
sshParkingEnabled: terminalSshParkingEnabled,
|
||||
pairedRuntimeParkingEnvironmentIds
|
||||
}
|
||||
const parkingTimers = terminalWorktreeParkingTimersRef.current
|
||||
const keepWarmWorktreeIds = getHeldTerminalPrewarmWorktrees()
|
||||
for (const worktreeId of dirty) {
|
||||
const timer = parkingTimers.get(worktreeId)
|
||||
if (timer !== undefined) {
|
||||
window.clearTimeout(timer)
|
||||
parkingTimers.delete(worktreeId)
|
||||
}
|
||||
if (!workspaceSurfaceIdSet.has(worktreeId) || !mountedWorktreeIdsRef.current.has(worktreeId)) {
|
||||
terminalWorktreeHiddenSinceRef.current.delete(worktreeId)
|
||||
measuringTerminalWorktreeIdsRef.current.delete(worktreeId)
|
||||
terminalWorktreeParkCooldownUntilRef.current.delete(worktreeId)
|
||||
}
|
||||
}
|
||||
|
||||
const retentionCandidates: TerminalWorktreeColdParkCandidate[] = []
|
||||
for (const worktreeId of workspaceSurfaceIds) {
|
||||
if (!mountedWorktreeIdsRef.current.has(worktreeId)) {
|
||||
terminalWorktreeHiddenSinceRef.current.delete(worktreeId)
|
||||
measuringTerminalWorktreeIdsRef.current.delete(worktreeId)
|
||||
terminalWorktreeParkCooldownUntilRef.current.delete(worktreeId)
|
||||
rankingChanged ||= owner.candidates.has(worktreeId)
|
||||
owner.candidates.delete(worktreeId)
|
||||
owner.phases.delete(worktreeId)
|
||||
owner.ordinarilyEligible.delete(worktreeId)
|
||||
owner.budget.delete(worktreeId)
|
||||
continue
|
||||
}
|
||||
const isVisible = activeView === 'terminal' && renderedActiveWorktreeId === worktreeId
|
||||
const shouldMeasureHiddenWorktree =
|
||||
!isVisible && measurableBackgroundWorktreeIdsRef.current.has(worktreeId)
|
||||
const hasActivityTerminalPortal = portalWorktreeIds.has(worktreeId)
|
||||
const hasActivityTerminalPortal = activityTerminalPortals.some(
|
||||
(portal) => portal.worktreeId === worktreeId
|
||||
)
|
||||
if (shouldMeasureHiddenWorktree) {
|
||||
measuringTerminalWorktreeIdsRef.current.add(worktreeId)
|
||||
} else {
|
||||
@@ -74,84 +110,121 @@ export function collectTerminalParkingPassCandidates(controller: TerminalParking
|
||||
if (isVisible || hasActivityTerminalPortal) {
|
||||
terminalWorktreeHiddenSinceRef.current.delete(worktreeId)
|
||||
terminalWorktreeParkCooldownUntilRef.current.delete(worktreeId)
|
||||
} else if (!shouldMeasureHiddenWorktree) {
|
||||
if (!terminalWorktreeHiddenSinceRef.current.has(worktreeId)) {
|
||||
terminalWorktreeHiddenSinceRef.current.set(worktreeId, nowMs)
|
||||
}
|
||||
} else if (
|
||||
!shouldMeasureHiddenWorktree &&
|
||||
!terminalWorktreeHiddenSinceRef.current.has(worktreeId)
|
||||
) {
|
||||
terminalWorktreeHiddenSinceRef.current.set(worktreeId, nowMs)
|
||||
}
|
||||
|
||||
retentionCandidates.push({
|
||||
const terminalTabs = tabsByWorktree[worktreeId] ?? []
|
||||
const candidate = {
|
||||
worktreeId,
|
||||
terminalTabs: tabsByWorktree[worktreeId] ?? [],
|
||||
terminalTabs,
|
||||
isVisible,
|
||||
shouldMeasureHiddenWorktree,
|
||||
hasActivityTerminalPortal,
|
||||
hiddenSinceMs: terminalWorktreeHiddenSinceRef.current.get(worktreeId) ?? null,
|
||||
parkCooldownUntilMs: terminalWorktreeParkCooldownUntilRef.current.get(worktreeId) ?? null
|
||||
})
|
||||
}
|
||||
|
||||
const restorePolicy = {
|
||||
sshParkingEnabled: terminalSshParkingEnabled,
|
||||
pairedRuntimeParkingEnvironmentIds
|
||||
}
|
||||
const nextParkedTerminalWorktreeIds = selectColdParkedTerminalWorktrees({
|
||||
worktrees: retentionCandidates,
|
||||
pendingStartupByTabId,
|
||||
parkingEnabled: terminalParkingEnabled,
|
||||
nowMs,
|
||||
restorePolicy,
|
||||
...overrides
|
||||
})
|
||||
const watcherCoverageByTabId = new Map<string, boolean>()
|
||||
const worktreeTabsAreWatcherCovered = (worktreeId: string, tabs: TerminalTab[]): boolean =>
|
||||
tabs.every((tab) => {
|
||||
const cached = watcherCoverageByTabId.get(tab.id)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
const covered = canWatcherCoverParkedTerminalTab(worktreeId, tab)
|
||||
watcherCoverageByTabId.set(tab.id, covered)
|
||||
return covered
|
||||
})
|
||||
// Leased prewarm worktrees (hover, keyboard neighbors) stay mounted; the retention budget still applies.
|
||||
const keepWarmWorktreeIds = getHeldTerminalPrewarmWorktrees()
|
||||
for (const worktreeId of Array.from(nextParkedTerminalWorktreeIds)) {
|
||||
}
|
||||
owner.candidates.set(worktreeId, candidate)
|
||||
const covered = terminalTabs.every((tab) => canWatcherCoverParkedTerminalTab(worktreeId, tab))
|
||||
const canPark = (parkCooldownUntilMs: number | null) =>
|
||||
canParkTerminalWorktreeRenderers({
|
||||
...candidate,
|
||||
parkCooldownUntilMs,
|
||||
pendingStartupByTabId,
|
||||
parkingEnabled: terminalParkingEnabled,
|
||||
nowMs,
|
||||
restorePolicy,
|
||||
...(overrides.coldParkDelayMs !== undefined
|
||||
? { coldParkDelayMs: overrides.coldParkDelayMs }
|
||||
: {})
|
||||
})
|
||||
const budgetRow = {
|
||||
worktreeId,
|
||||
isVisible,
|
||||
shouldMeasureHiddenWorktree,
|
||||
hasActivityTerminalPortal,
|
||||
hiddenSinceMs: candidate.hiddenSinceMs,
|
||||
parkCooldownUntilMs: candidate.parkCooldownUntilMs,
|
||||
ordinaryParkingCovers: covered && canPark(null),
|
||||
hasPendingSpawnWork: terminalTabs.some((tab) =>
|
||||
hasPendingRetentionSpawnWork(tab, pendingStartupByTabId)
|
||||
)
|
||||
}
|
||||
const previousBudget = owner.budget.get(worktreeId)
|
||||
const phase = [
|
||||
candidate.hiddenSinceMs !== null &&
|
||||
nowMs >=
|
||||
candidate.hiddenSinceMs +
|
||||
(overrides.coldParkDelayMs ?? TERMINAL_WORKTREE_COLD_PARK_DELAY_MS),
|
||||
candidate.hiddenSinceMs !== null &&
|
||||
nowMs >=
|
||||
candidate.hiddenSinceMs + (overrides.hotRetainMs ?? TERMINAL_WORKTREE_HOT_RETAIN_MS),
|
||||
candidate.hiddenSinceMs !== null &&
|
||||
nowMs >=
|
||||
candidate.hiddenSinceMs +
|
||||
(overrides.retentionTtlMs ?? TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS),
|
||||
candidate.parkCooldownUntilMs !== null && nowMs >= candidate.parkCooldownUntilMs
|
||||
].join(',')
|
||||
if (
|
||||
keepWarmWorktreeIds.has(worktreeId) ||
|
||||
!worktreeTabsAreWatcherCovered(worktreeId, tabsByWorktree[worktreeId] ?? [])
|
||||
!previousBudget ||
|
||||
previousBudget.hiddenSinceMs !== budgetRow.hiddenSinceMs ||
|
||||
previousBudget.isVisible !== budgetRow.isVisible ||
|
||||
previousBudget.shouldMeasureHiddenWorktree !== budgetRow.shouldMeasureHiddenWorktree ||
|
||||
previousBudget.hasActivityTerminalPortal !== budgetRow.hasActivityTerminalPortal ||
|
||||
previousBudget.parkCooldownUntilMs !== budgetRow.parkCooldownUntilMs ||
|
||||
previousBudget.ordinaryParkingCovers !== budgetRow.ordinaryParkingCovers ||
|
||||
previousBudget.hasPendingSpawnWork !== budgetRow.hasPendingSpawnWork ||
|
||||
owner.phases.get(worktreeId) !== phase
|
||||
) {
|
||||
nextParkedTerminalWorktreeIds.delete(worktreeId)
|
||||
rankingChanged = true
|
||||
}
|
||||
owner.budget.set(worktreeId, budgetRow)
|
||||
owner.phases.set(worktreeId, phase)
|
||||
if (candidate.hiddenSinceMs !== null && canPark(candidate.parkCooldownUntilMs)) {
|
||||
const previousOrdinary = owner.ordinarilyEligible.get(worktreeId)
|
||||
const keepWarm = keepWarmWorktreeIds.has(worktreeId)
|
||||
if (
|
||||
previousOrdinary?.hiddenSinceMs !== candidate.hiddenSinceMs ||
|
||||
previousOrdinary.covered !== covered ||
|
||||
previousOrdinary.keepWarm !== keepWarm
|
||||
) {
|
||||
rankingChanged = true
|
||||
}
|
||||
owner.ordinarilyEligible.set(worktreeId, {
|
||||
id: worktreeId,
|
||||
hiddenSinceMs: candidate.hiddenSinceMs,
|
||||
covered,
|
||||
keepWarm
|
||||
})
|
||||
} else if (owner.ordinarilyEligible.delete(worktreeId)) {
|
||||
rankingChanged = true
|
||||
}
|
||||
}
|
||||
|
||||
if (rankingChanged) {
|
||||
const ranked = selectIdsBeyondHotRetain([...owner.ordinarilyEligible.values()], {
|
||||
nowMs,
|
||||
hotRetainMs: overrides.hotRetainMs ?? TERMINAL_WORKTREE_HOT_RETAIN_MS,
|
||||
hotRetainLimit: overrides.hotRetainLimit ?? TERMINAL_WORKTREE_HOT_RETAIN_LIMIT
|
||||
})
|
||||
for (const id of ranked) {
|
||||
const row = owner.ordinarilyEligible.get(id)
|
||||
if (!row?.covered || row.keepWarm) {
|
||||
ranked.delete(id)
|
||||
}
|
||||
}
|
||||
owner.ordinaryParked = ranked
|
||||
owner.budgetSnapshot = [...owner.budget.values()]
|
||||
}
|
||||
return {
|
||||
parkingTimers,
|
||||
nowMs,
|
||||
overrides,
|
||||
retentionCandidates,
|
||||
restorePolicy,
|
||||
nextParkedTerminalWorktreeIds,
|
||||
worktreeTabsAreWatcherCovered
|
||||
rankingChanged,
|
||||
nextParkedTerminalWorktreeIds: new Set(owner.ordinaryParked),
|
||||
candidateForWorktree: (id: string) => owner.candidates.get(id),
|
||||
retentionBudgetCandidates: owner.budgetSnapshot
|
||||
}
|
||||
}
|
||||
|
||||
export function canOrdinarilyParkRetentionCandidate(
|
||||
controller: TerminalParkingFoundation,
|
||||
pass: TerminalParkingPassCandidates,
|
||||
candidate: TerminalWorktreeColdParkCandidate
|
||||
): boolean {
|
||||
const tabs = controller.tabsByWorktree[candidate.worktreeId] ?? []
|
||||
const parkEligible = canParkTerminalWorktreeRenderers({
|
||||
...candidate,
|
||||
parkCooldownUntilMs: null,
|
||||
pendingStartupByTabId: controller.pendingStartupByTabId,
|
||||
parkingEnabled: controller.terminalParkingEnabled,
|
||||
nowMs: pass.nowMs,
|
||||
restorePolicy: pass.restorePolicy,
|
||||
...(pass.overrides.coldParkDelayMs !== undefined
|
||||
? { coldParkDelayMs: pass.overrides.coldParkDelayMs }
|
||||
: {})
|
||||
})
|
||||
return parkEligible && pass.worktreeTabsAreWatcherCovered(candidate.worktreeId, tabs)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { invalidateTerminalParkingInputs } from '../terminal-pane/parking/terminal-parking-input-events'
|
||||
import { addBackgroundMountedTerminalWorktree } from './background-terminal-worktree-mount'
|
||||
|
||||
export const BACKGROUND_WORKTREE_MEASURE_WINDOW_MS = 3000
|
||||
@@ -36,10 +37,12 @@ export function scheduleBackgroundTerminalWorktreeMeasure({
|
||||
const timer = setTimeoutFn(() => {
|
||||
measurableBackgroundWorktreeIds.delete(worktreeId)
|
||||
timers.delete(worktreeId)
|
||||
invalidateTerminalParkingInputs(worktreeId)
|
||||
onRevision()
|
||||
}, BACKGROUND_WORKTREE_MEASURE_WINDOW_MS)
|
||||
|
||||
timers.set(worktreeId, timer)
|
||||
invalidateTerminalParkingInputs(worktreeId)
|
||||
onRevision()
|
||||
return added
|
||||
}
|
||||
|
||||
@@ -1,4 +1,66 @@
|
||||
import type { TabGroup, TabGroupLayoutNode } from '../../../../shared/tab-types'
|
||||
import { terminalInputRecordChangedKeys } from '@/store/terminals/terminal-input-record-transition'
|
||||
|
||||
export class MountedTerminalWorktrees extends Set<string> {
|
||||
private readonly changedIds = new Set<string>()
|
||||
private readonly committedChanges = {
|
||||
watcher: new Set<string>(),
|
||||
retention: new Set<string>()
|
||||
}
|
||||
|
||||
private markChanged(id: string): void {
|
||||
this.changedIds.add(id)
|
||||
this.committedChanges.watcher.add(id)
|
||||
this.committedChanges.retention.add(id)
|
||||
}
|
||||
|
||||
takeCommittedChanges(consumer: 'watcher' | 'retention'): ReadonlySet<string> {
|
||||
const changed = this.committedChanges[consumer]
|
||||
this.committedChanges[consumer] = new Set()
|
||||
return changed
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
}
|
||||
|
||||
override add(id: string): this {
|
||||
if (!this.has(id)) {
|
||||
this.markChanged(id)
|
||||
}
|
||||
return super.add(id)
|
||||
}
|
||||
|
||||
override delete(id: string): boolean {
|
||||
if (!super.delete(id)) {
|
||||
return false
|
||||
}
|
||||
this.markChanged(id)
|
||||
return true
|
||||
}
|
||||
|
||||
override clear(): void {
|
||||
for (const id of this) {
|
||||
this.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
takeChangedIds(): ReadonlySet<string> {
|
||||
const changed = new Set(this.changedIds)
|
||||
this.changedIds.clear()
|
||||
return changed
|
||||
}
|
||||
}
|
||||
|
||||
type LayoutPresence = {
|
||||
catalog: string[]
|
||||
catalogIds: ReadonlySet<string>
|
||||
layouts: Record<string, TabGroupLayoutNode | undefined>
|
||||
groups: Record<string, TabGroup[]>
|
||||
activeGroups: Record<string, string | undefined>
|
||||
present: Set<string>
|
||||
}
|
||||
const layoutPresenceByMounts = new WeakMap<ReadonlySet<string>, LayoutPresence>()
|
||||
|
||||
export function getEffectiveLayoutForWorktree(
|
||||
worktreeId: string,
|
||||
@@ -26,9 +88,52 @@ export function anyMountedWorktreeHasLayout(
|
||||
groupsByWorktree: Record<string, TabGroup[]>,
|
||||
activeGroupIdByWorktree: Record<string, string | undefined>
|
||||
): boolean {
|
||||
return allWorktreeIds.some(
|
||||
(id) =>
|
||||
const previous = layoutPresenceByMounts.get(mountedWorktreeIds)
|
||||
const catalogIds =
|
||||
previous?.catalog === allWorktreeIds ? previous.catalogIds : new Set(allWorktreeIds)
|
||||
let dirty =
|
||||
mountedWorktreeIds instanceof MountedTerminalWorktrees
|
||||
? new Set(mountedWorktreeIds.takeChangedIds())
|
||||
: null
|
||||
if (previous && dirty) {
|
||||
for (const [before, after] of [
|
||||
[previous.layouts, layoutByWorktree],
|
||||
[previous.groups, groupsByWorktree],
|
||||
[previous.activeGroups, activeGroupIdByWorktree]
|
||||
]) {
|
||||
const changed = terminalInputRecordChangedKeys(before, after)
|
||||
if (changed === null) {
|
||||
dirty = null
|
||||
break
|
||||
}
|
||||
for (const id of changed) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Bootstrap, catalog replacement and unknown source replacements cannot assume an addressed mount history.
|
||||
if (!previous || previous.catalog !== allWorktreeIds || dirty === null) {
|
||||
dirty = new Set([...mountedWorktreeIds, ...(previous?.present ?? [])])
|
||||
}
|
||||
const present = previous?.present ?? new Set<string>()
|
||||
for (const id of dirty) {
|
||||
if (
|
||||
catalogIds.has(id) &&
|
||||
mountedWorktreeIds.has(id) &&
|
||||
getEffectiveLayoutForWorktree(id, layoutByWorktree, groupsByWorktree, activeGroupIdByWorktree)
|
||||
)
|
||||
) {
|
||||
present.add(id)
|
||||
} else {
|
||||
present.delete(id)
|
||||
}
|
||||
}
|
||||
layoutPresenceByMounts.set(mountedWorktreeIds, {
|
||||
catalog: allWorktreeIds,
|
||||
catalogIds,
|
||||
layouts: layoutByWorktree,
|
||||
groups: groupsByWorktree,
|
||||
activeGroups: activeGroupIdByWorktree,
|
||||
present
|
||||
})
|
||||
return present.size > 0
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { invalidateTerminalParkingPtyInputs } from '@/store/terminals/terminal-parking-input-owner'
|
||||
let capabilityRevision = 0
|
||||
const capabilityRevisionListeners = new Set<() => void>()
|
||||
|
||||
export function publishTerminalProviderCapabilityChange(): void {
|
||||
export function publishTerminalProviderCapabilityChange(ptyIds?: Iterable<string>): void {
|
||||
invalidateTerminalParkingPtyInputs(ptyIds)
|
||||
capabilityRevision += 1
|
||||
for (const listener of capabilityRevisionListeners) {
|
||||
listener()
|
||||
|
||||
@@ -16,17 +16,21 @@ export async function probeTerminalProviderGoneSessions(
|
||||
return
|
||||
}
|
||||
const sizeBefore = goneSessionPtyIds.size
|
||||
const changedPtyIds = new Set<string>()
|
||||
for (let offset = 0; offset < candidates.length; offset += 512) {
|
||||
const gone = await resolveGone(candidates.slice(offset, offset + 512)).catch(() => [])
|
||||
if (generation !== goneProbeGeneration) {
|
||||
return
|
||||
}
|
||||
for (const id of gone.filter((goneId) => !boundSessionPtyIds.has(goneId))) {
|
||||
if (!goneSessionPtyIds.has(id)) {
|
||||
changedPtyIds.add(id)
|
||||
}
|
||||
goneSessionPtyIds.add(id)
|
||||
}
|
||||
}
|
||||
if (goneSessionPtyIds.size !== sizeBefore) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange(changedPtyIds)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +38,7 @@ export async function probeTerminalProviderGoneSessions(
|
||||
export function markTerminalProviderSessionBound(ptyId: string): void {
|
||||
boundSessionPtyIds.add(ptyId)
|
||||
if (goneSessionPtyIds.delete(ptyId)) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange([ptyId])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,77 +1,150 @@
|
||||
import { reuseArrayIfEqual } from '@/components/sidebar/workspace-card/activity/worktree-agent-row-selectors'
|
||||
import { sameBucketRecords } from '@/lib/bucket-record-equality'
|
||||
import { sameStringRecord } from '../../../../shared/workspace-layout/terminal-layout-equality'
|
||||
import {
|
||||
type SnapshotCapabilityBindingState,
|
||||
type SnapshotCapabilityTab,
|
||||
collectTerminalProviderSnapshotPtyIds
|
||||
} from './terminal-provider-snapshot-capability'
|
||||
import { terminalInputRecordChangedKeys } from '@/store/terminals/terminal-input-record-transition'
|
||||
import { createTerminalTabOwnerIndex } from '@/store/terminals/terminal-tab-owner-index'
|
||||
import type { SnapshotCapabilityBindingState } from './terminal-provider-snapshot-capability'
|
||||
|
||||
type TabsByWorktree = SnapshotCapabilityBindingState['tabsByWorktree']
|
||||
type LayoutsByTabId = NonNullable<SnapshotCapabilityBindingState['terminalLayoutsByTabId']>
|
||||
|
||||
const EMPTY_TABS: TabsByWorktree = Object.freeze({})
|
||||
const EMPTY_LAYOUTS: LayoutsByTabId = Object.freeze({})
|
||||
|
||||
function sameBoundTab(previous: SnapshotCapabilityTab, next: SnapshotCapabilityTab): boolean {
|
||||
return previous.id === next.id && previous.ptyId === next.ptyId
|
||||
type State = SnapshotCapabilityBindingState
|
||||
type Source = {
|
||||
tabs: State['tabsByWorktree']
|
||||
bindings: State['ptyIdsByTabId']
|
||||
layouts: NonNullable<State['terminalLayoutsByTabId']>
|
||||
reconnect: NonNullable<State['pendingReconnectPtyIdByTabId']>
|
||||
}
|
||||
const EMPTY_LAYOUTS: Source['layouts'] = Object.freeze({})
|
||||
const EMPTY_RECONNECT: Source['reconnect'] = Object.freeze({})
|
||||
|
||||
/** Only leaf PTY bindings matter; titles, focus and buffers replace layout objects without changing them. */
|
||||
function sameLayoutLeafPtyIds(previous: LayoutsByTabId, next: LayoutsByTabId): boolean {
|
||||
if (previous === next) {
|
||||
return true
|
||||
}
|
||||
const tabIds = Object.keys(next)
|
||||
if (tabIds.length !== Object.keys(previous).length) {
|
||||
return false
|
||||
}
|
||||
for (const tabId of tabIds) {
|
||||
const nextLayout = next[tabId]
|
||||
const previousLayout = previous[tabId]
|
||||
if (previousLayout === nextLayout) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
!previousLayout ||
|
||||
!sameStringRecord(previousLayout.ptyIdsByLeafId, nextLayout?.ptyIdsByLeafId)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** Gate scans on tab/PTY-binding fields, then reuse equal output arrays to avoid synchronization restarts. Adjacent-state equality is transitive across unchanged writes. */
|
||||
export function createTerminalProviderSnapshotBoundPtyIdsSelector(): (
|
||||
state: SnapshotCapabilityBindingState
|
||||
) => string[] {
|
||||
let previousTabsByWorktree: TabsByWorktree = EMPTY_TABS
|
||||
let previousLayoutsByTabId: LayoutsByTabId = EMPTY_LAYOUTS
|
||||
let previousPtyIdsByTabId: SnapshotCapabilityBindingState['ptyIdsByTabId'] | undefined
|
||||
let previousPendingReconnectPtyIdByTabId: SnapshotCapabilityBindingState['pendingReconnectPtyIdByTabId']
|
||||
/** PTYs may belong to several sources; removing one binding must not prune another source's answer. */
|
||||
export function createTerminalProviderSnapshotBoundPtyIdsSelector(): (state: State) => string[] {
|
||||
let previous: Source | null = null
|
||||
const tabOwners = createTerminalTabOwnerIndex()
|
||||
const workspacePtys = new Map<string, ReadonlySet<string>>()
|
||||
const layoutPtys = new Map<string, ReadonlySet<string>>()
|
||||
const reconnectPtys = new Map<string, ReadonlySet<string>>()
|
||||
const references = new Map<string, number>()
|
||||
let boundPtyIds: string[] = []
|
||||
let collected = false
|
||||
let membershipChanged = false
|
||||
|
||||
function replace(
|
||||
contributions: Map<string, ReadonlySet<string>>,
|
||||
key: string,
|
||||
next: ReadonlySet<string>
|
||||
): void {
|
||||
const before = contributions.get(key)
|
||||
for (const id of before ?? []) {
|
||||
if (next.has(id)) {
|
||||
continue
|
||||
}
|
||||
const count = (references.get(id) ?? 0) - 1
|
||||
if (count > 0) {
|
||||
references.set(id, count)
|
||||
} else {
|
||||
references.delete(id)
|
||||
membershipChanged = true
|
||||
}
|
||||
}
|
||||
for (const id of next) {
|
||||
if (before?.has(id)) {
|
||||
continue
|
||||
}
|
||||
const count = references.get(id) ?? 0
|
||||
references.set(id, count + 1)
|
||||
membershipChanged ||= count === 0
|
||||
}
|
||||
if (next.size > 0) {
|
||||
contributions.set(key, next)
|
||||
} else {
|
||||
contributions.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
function replaceWorkspace(source: Source, worktreeId: string): void {
|
||||
const ids = new Set<string>()
|
||||
for (const tab of source.tabs[worktreeId] ?? []) {
|
||||
if (tab.ptyId) {
|
||||
ids.add(tab.ptyId)
|
||||
}
|
||||
for (const id of source.bindings[tab.id] ?? []) {
|
||||
ids.add(id)
|
||||
}
|
||||
}
|
||||
replace(workspacePtys, worktreeId, ids)
|
||||
}
|
||||
|
||||
function replaceLayout(source: Source, tabId: string): void {
|
||||
replace(layoutPtys, tabId, new Set(Object.values(source.layouts[tabId]?.ptyIdsByLeafId ?? {})))
|
||||
}
|
||||
|
||||
function replaceReconnect(source: Source, tabId: string): void {
|
||||
const id = source.reconnect[tabId]
|
||||
replace(reconnectPtys, tabId, new Set(id !== undefined ? [id] : []))
|
||||
}
|
||||
|
||||
function resyncUnknownSnapshot(source: Source): void {
|
||||
workspacePtys.clear()
|
||||
layoutPtys.clear()
|
||||
reconnectPtys.clear()
|
||||
references.clear()
|
||||
membershipChanged = true
|
||||
for (const id of Object.keys(source.tabs)) {
|
||||
replaceWorkspace(source, id)
|
||||
}
|
||||
for (const id of Object.keys(source.layouts)) {
|
||||
replaceLayout(source, id)
|
||||
}
|
||||
for (const id of Object.keys(source.reconnect)) {
|
||||
replaceReconnect(source, id)
|
||||
}
|
||||
}
|
||||
|
||||
return (state) => {
|
||||
const layoutsByTabId = state.terminalLayoutsByTabId ?? EMPTY_LAYOUTS
|
||||
const unchanged =
|
||||
collected &&
|
||||
previousPtyIdsByTabId === state.ptyIdsByTabId &&
|
||||
previousPendingReconnectPtyIdByTabId === state.pendingReconnectPtyIdByTabId &&
|
||||
sameBucketRecords(previousTabsByWorktree, state.tabsByWorktree, sameBoundTab) &&
|
||||
sameLayoutLeafPtyIds(previousLayoutsByTabId, layoutsByTabId)
|
||||
if (!unchanged) {
|
||||
boundPtyIds = reuseArrayIfEqual(
|
||||
boundPtyIds,
|
||||
collectTerminalProviderSnapshotPtyIds(state).sort()
|
||||
)
|
||||
previousPtyIdsByTabId = state.ptyIdsByTabId
|
||||
previousPendingReconnectPtyIdByTabId = state.pendingReconnectPtyIdByTabId
|
||||
collected = true
|
||||
const source: Source = {
|
||||
tabs: state.tabsByWorktree,
|
||||
bindings: state.ptyIdsByTabId,
|
||||
layouts: state.terminalLayoutsByTabId ?? EMPTY_LAYOUTS,
|
||||
reconnect: state.pendingReconnectPtyIdByTabId ?? EMPTY_RECONNECT
|
||||
}
|
||||
previousTabsByWorktree = state.tabsByWorktree
|
||||
previousLayoutsByTabId = layoutsByTabId
|
||||
const changedWorkspaces = previous
|
||||
? terminalInputRecordChangedKeys(previous.tabs, source.tabs)
|
||||
: null
|
||||
const changedBindings = previous
|
||||
? terminalInputRecordChangedKeys(previous.bindings, source.bindings)
|
||||
: null
|
||||
const changedLayouts = previous
|
||||
? terminalInputRecordChangedKeys(previous.layouts, source.layouts)
|
||||
: null
|
||||
const changedReconnect = previous
|
||||
? terminalInputRecordChangedKeys(previous.reconnect, source.reconnect)
|
||||
: null
|
||||
tabOwners.getOwners(source.tabs)
|
||||
if (!changedWorkspaces || !changedBindings || !changedLayouts || !changedReconnect) {
|
||||
resyncUnknownSnapshot(source)
|
||||
} else {
|
||||
const worktreeIds = new Set(changedWorkspaces)
|
||||
for (const tabId of changedBindings) {
|
||||
for (const id of tabOwners.getOwnerIds(source.tabs, tabId)) {
|
||||
worktreeIds.add(id)
|
||||
}
|
||||
}
|
||||
for (const id of worktreeIds) {
|
||||
replaceWorkspace(source, id)
|
||||
}
|
||||
for (const id of changedLayouts) {
|
||||
replaceLayout(source, id)
|
||||
}
|
||||
for (const id of changedReconnect) {
|
||||
replaceReconnect(source, id)
|
||||
}
|
||||
}
|
||||
if (membershipChanged) {
|
||||
const next = [...references.keys()].sort()
|
||||
if (
|
||||
next.length !== boundPtyIds.length ||
|
||||
next.some((id, index) => id !== boundPtyIds[index])
|
||||
) {
|
||||
boundPtyIds = next
|
||||
}
|
||||
membershipChanged = false
|
||||
}
|
||||
previous = source
|
||||
return boundPtyIds
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,8 +124,12 @@ export async function synchronizeTerminalProviderSnapshotCapabilities(
|
||||
lastSynchronizedLivePtyIds = livePtyIds
|
||||
const live = new Set(livePtyIds.filter((id) => id.length > 0))
|
||||
let capabilityChanged = false
|
||||
const changedPtyIds = new Set<string>()
|
||||
for (const cachedId of authoritativeSnapshotByPtyId.keys()) {
|
||||
if (!live.has(cachedId)) {
|
||||
if (authoritativeSnapshotByPtyId.get(cachedId) === true) {
|
||||
changedPtyIds.add(cachedId)
|
||||
}
|
||||
capabilityChanged ||= authoritativeSnapshotByPtyId.get(cachedId) === true
|
||||
authoritativeSnapshotByPtyId.delete(cachedId)
|
||||
}
|
||||
@@ -150,7 +154,7 @@ export async function synchronizeTerminalProviderSnapshotCapabilities(
|
||||
}
|
||||
refreshEarliestUnknownCapabilityRetry()
|
||||
if (capabilityChanged) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange(changedPtyIds)
|
||||
}
|
||||
return unknownCapabilityRetryDelayMs(nowMs)
|
||||
}
|
||||
@@ -163,7 +167,7 @@ export async function synchronizeTerminalProviderSnapshotCapabilities(
|
||||
if (generation !== synchronizationGeneration) {
|
||||
// Return zero to preserve a superseded caller’s retry chain; the winning startup pass ignores its return value.
|
||||
if (capabilityChanged) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange(changedPtyIds)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -176,7 +180,7 @@ export async function synchronizeTerminalProviderSnapshotCapabilities(
|
||||
if (generation !== synchronizationGeneration) {
|
||||
// Supersession must preserve the caller’s timer chain for later slow re-asks.
|
||||
if (capabilityChanged) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange(changedPtyIds)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -190,6 +194,9 @@ export async function synchronizeTerminalProviderSnapshotCapabilities(
|
||||
for (const id of batch) {
|
||||
const authoritative = resolvedById.get(id)
|
||||
if (typeof authoritative === 'boolean') {
|
||||
if ((authoritativeSnapshotByPtyId.get(id) === true) !== (authoritative === true)) {
|
||||
changedPtyIds.add(id)
|
||||
}
|
||||
capabilityChanged ||=
|
||||
(authoritativeSnapshotByPtyId.get(id) === true) !== (authoritative === true)
|
||||
authoritativeSnapshotByPtyId.set(id, authoritative)
|
||||
@@ -202,7 +209,7 @@ export async function synchronizeTerminalProviderSnapshotCapabilities(
|
||||
}
|
||||
refreshEarliestUnknownCapabilityRetry()
|
||||
if (capabilityChanged) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange(changedPtyIds)
|
||||
}
|
||||
return unknownCapabilityRetryDelayMs(observedAtMs === undefined ? Date.now() : nowMs)
|
||||
}
|
||||
@@ -213,7 +220,11 @@ export async function refreshTerminalProviderSnapshotCapabilities(
|
||||
): Promise<number | null> {
|
||||
lastSynchronizedLivePtyIds = null
|
||||
let capabilityChanged = false
|
||||
const changedPtyIds = new Set<string>()
|
||||
for (const id of livePtyIds) {
|
||||
if (authoritativeSnapshotByPtyId.get(id) === true) {
|
||||
changedPtyIds.add(id)
|
||||
}
|
||||
capabilityChanged ||= authoritativeSnapshotByPtyId.get(id) === true
|
||||
authoritativeSnapshotByPtyId.delete(id)
|
||||
unknownCapabilityRetryAtByPtyId.delete(id)
|
||||
@@ -221,7 +232,7 @@ export async function refreshTerminalProviderSnapshotCapabilities(
|
||||
}
|
||||
refreshEarliestUnknownCapabilityRetry()
|
||||
if (capabilityChanged) {
|
||||
publishTerminalProviderCapabilityChange()
|
||||
publishTerminalProviderCapabilityChange(changedPtyIds)
|
||||
}
|
||||
return synchronizeTerminalProviderSnapshotCapabilities(livePtyIds, resolveCapabilities)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import type { AppState } from '@/store/types'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { getSleepingRecordTabId } from '@/lib/sleeping-agent-wake-requests'
|
||||
import '../terminal-pane/parking/output-watchers/terminal-parked-tab-watchers'
|
||||
import { resolveParkedTerminalPaneCandidates } from '../terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation'
|
||||
import { parkedTerminalTabCoverage } from '../terminal-pane/parking/output-watchers/parked-terminal-tab-coverage'
|
||||
|
||||
export function selectRevealTerminalTabIds(state: AppState, worktreeId: string): Set<string> {
|
||||
const revealTabIds = new Set<string>()
|
||||
@@ -24,7 +25,9 @@ export function selectRevealTerminalTabIds(state: AppState, worktreeId: string):
|
||||
|
||||
export function selectSleepingTabIds(state: AppState, worktreeId: string): Set<string> {
|
||||
const tabIds = new Set<string>()
|
||||
for (const record of Object.values(state.sleepingAgentSessionsByPaneKey)) {
|
||||
for (const record of sleepingAgentRecordIndex
|
||||
.entries(state.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)) {
|
||||
const tabId = record.worktreeId === worktreeId ? getSleepingRecordTabId(record) : null
|
||||
if (tabId) {
|
||||
tabIds.add(tabId)
|
||||
@@ -44,7 +47,7 @@ export function scheduleTerminalPrewarmStage(callback: () => void): () => void {
|
||||
}
|
||||
|
||||
export function resolveReattachPtyIds(tab: TerminalTab, state: AppState): string[] {
|
||||
return resolveParkedTerminalPaneCandidates(tab, state).flatMap((pane) =>
|
||||
return parkedTerminalTabCoverage(tab.worktreeId, tab, state).panes.flatMap((pane) =>
|
||||
pane.ptyId ? [pane.ptyId] : []
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { invalidateTerminalParkingInputs } from '../terminal-pane/parking/terminal-parking-input-events'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
|
||||
/** Each stage is its own task so a slow pointer sweep never stacks mount, style/layout and WebGL into one long frame. */
|
||||
@@ -22,6 +23,9 @@ export function setTerminalPrewarmWorktrees(
|
||||
return
|
||||
}
|
||||
worktreeIdsByClient.set(client, [...worktreeIds])
|
||||
for (const id of new Set([...current, ...worktreeIds])) {
|
||||
invalidateTerminalParkingInputs(id)
|
||||
}
|
||||
for (const listener of listeners) {
|
||||
listener()
|
||||
}
|
||||
@@ -47,7 +51,18 @@ export function getTerminalPrewarmWorktrees(): ReadonlyMap<
|
||||
let heldWorktreeIds: ReadonlySet<string> = new Set()
|
||||
|
||||
export function setHeldTerminalPrewarmWorktrees(worktreeIds: Iterable<string>): void {
|
||||
const previous = heldWorktreeIds
|
||||
heldWorktreeIds = new Set(worktreeIds)
|
||||
for (const id of previous) {
|
||||
if (!heldWorktreeIds.has(id)) {
|
||||
invalidateTerminalParkingInputs(id)
|
||||
}
|
||||
}
|
||||
for (const id of heldWorktreeIds) {
|
||||
if (!previous.has(id)) {
|
||||
invalidateTerminalParkingInputs(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getHeldTerminalPrewarmWorktrees(): ReadonlySet<string> {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { shouldSeedDefaultSurface } from '@/lib/workspace/activation/initial-surface/automatic-default-surface'
|
||||
import { findPendingWorktreeCreationId } from '@/lib/workspace/creation/pending-worktree-creation'
|
||||
import { isTerminalWorkspaceEmptiedOnPurpose } from '../../../../shared/workspace-layout/closed-terminal-tab-tombstones'
|
||||
import { gateWorktreeAgentActivation } from '@/lib/workspace/activation/worktree-agent-activation-gate'
|
||||
import { createWorkspaceTerminalHostAuthoritySelector } from '@/lib/workspace-terminal-host-authority'
|
||||
import { hasStructuredAgentLaunchInWorktree } from '@/lib/agent-session/launch/structured-agent-session-launch-status'
|
||||
import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/workspace/activation/initial-surface/empty-workspace-default-surface-claims'
|
||||
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
|
||||
import { createInitialTerminalThroughLayoutOwner } from '@/store/terminals/terminal-tab-create-through-layout-owner'
|
||||
import type { TerminalColdActivationController } from '../terminal-cold-activation'
|
||||
|
||||
type TerminalStartupController = Pick<
|
||||
TerminalColdActivationController,
|
||||
| 'activeWorktreeId'
|
||||
| 'workspaceSessionReady'
|
||||
| 'terminalStartupRestorationReady'
|
||||
| 'hydrationSucceeded'
|
||||
| 'reconcileWorktreeTabModel'
|
||||
| 'createTab'
|
||||
>
|
||||
|
||||
export function useTerminalStartupActivation(controller: TerminalStartupController): void {
|
||||
const {
|
||||
activeWorktreeId,
|
||||
workspaceSessionReady,
|
||||
terminalStartupRestorationReady,
|
||||
hydrationSucceeded,
|
||||
reconcileWorktreeTabModel,
|
||||
createTab
|
||||
} = controller
|
||||
const startupActivationGateWorktreeIdsRef = useRef(new Set<string>())
|
||||
// Subscribe so host answers rerun the passes; retain owner resolution to avoid repeating catalog walks on every store write (STA-3363).
|
||||
const hostAuthoritySelector = useMemo(
|
||||
() => createWorkspaceTerminalHostAuthoritySelector(activeWorktreeId),
|
||||
[activeWorktreeId]
|
||||
)
|
||||
const activeWorktreeHostAuthority = useAppStore(hostAuthoritySelector)
|
||||
const activeWorktreeCreationPending = useAppStore(
|
||||
(state) =>
|
||||
findPendingWorktreeCreationId(state.pendingWorktreeCreations, activeWorktreeId) !== null
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!workspaceSessionReady ||
|
||||
!terminalStartupRestorationReady ||
|
||||
!activeWorktreeId ||
|
||||
activeWorktreeCreationPending
|
||||
) {
|
||||
return
|
||||
}
|
||||
// An unanswered owner is not an empty host; seeding before its census duplicates tabs (STA-4658).
|
||||
if (activeWorktreeHostAuthority !== 'none') {
|
||||
return
|
||||
}
|
||||
if (startupActivationGateWorktreeIdsRef.current.has(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
void gateWorktreeAgentActivation(activeWorktreeId).then((outcome) => {
|
||||
if (
|
||||
cancelled ||
|
||||
outcome === 'blocked' ||
|
||||
useAppStore.getState().activeWorktreeId !== activeWorktreeId
|
||||
) {
|
||||
return
|
||||
}
|
||||
// An in-flight reseed owns the surface but remains unmarked so leaving mid-wait allows retry on return.
|
||||
if (outcome === 'empty' && isEmptyWorkspaceDefaultSurfacePending(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
// Only applied decisions consume the gate; canceled/blocked checks stay retryable and reruns share the in-flight promise.
|
||||
startupActivationGateWorktreeIdsRef.current.add(activeWorktreeId)
|
||||
if (outcome !== 'empty') {
|
||||
return
|
||||
}
|
||||
// A pending or unanswered chat create owns the surface even before its tab is published.
|
||||
if (hasStructuredAgentLaunchInWorktree(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
// Why: the activation gate reconciles durable/live agent state first; only an actually empty, never-visited workspace receives a default shell.
|
||||
const { renderableTabCount } = reconcileWorktreeTabModel(activeWorktreeId)
|
||||
// Only recorded closes preserve emptiness; reread at decision time because rows can change while waiting.
|
||||
const emptiedOnPurpose = isTerminalWorkspaceEmptiedOnPurpose(
|
||||
useAppStore.getState(),
|
||||
activeWorktreeId
|
||||
)
|
||||
if (shouldSeedDefaultSurface(activeWorktreeId, renderableTabCount, emptiedOnPurpose)) {
|
||||
if (
|
||||
ORCA_LAYOUT_OWNER_IS_MAIN &&
|
||||
createInitialTerminalThroughLayoutOwner(useAppStore.getState, activeWorktreeId, () =>
|
||||
createTab(activeWorktreeId, undefined, undefined, { pendingActivationSpawn: true })
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Initial default tabs must not count as user activity and reorder the sidebar; explicit New Tab still does.
|
||||
createTab(activeWorktreeId, undefined, undefined, { pendingActivationSpawn: true })
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [
|
||||
activeWorktreeId,
|
||||
activeWorktreeHostAuthority,
|
||||
activeWorktreeCreationPending,
|
||||
createTab,
|
||||
reconcileWorktreeTabModel,
|
||||
terminalStartupRestorationReady,
|
||||
workspaceSessionReady
|
||||
])
|
||||
|
||||
const startupResumeWorktreeIdsRef = useRef(new Set<string>())
|
||||
useEffect(() => {
|
||||
if (
|
||||
!workspaceSessionReady ||
|
||||
!terminalStartupRestorationReady ||
|
||||
!hydrationSucceeded ||
|
||||
!activeWorktreeId
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (startupResumeWorktreeIdsRef.current.has(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
// Do not consume recovery while the host is unanswered or sleeping agents remain stranded for this session.
|
||||
if (activeWorktreeHostAuthority === 'unverifiable') {
|
||||
return
|
||||
}
|
||||
startupResumeWorktreeIdsRef.current.add(activeWorktreeId)
|
||||
// Startup recovery needs the same host census and in-flight gate as explicit activation.
|
||||
void gateWorktreeAgentActivation(activeWorktreeId).then(
|
||||
(outcome) => {
|
||||
if (outcome === 'blocked') {
|
||||
startupResumeWorktreeIdsRef.current.delete(activeWorktreeId)
|
||||
}
|
||||
},
|
||||
() => startupResumeWorktreeIdsRef.current.delete(activeWorktreeId)
|
||||
)
|
||||
}, [
|
||||
activeWorktreeId,
|
||||
activeWorktreeHostAuthority,
|
||||
hydrationSucceeded,
|
||||
terminalStartupRestorationReady,
|
||||
workspaceSessionReady
|
||||
])
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useLayoutEffect, useRef } from 'react'
|
||||
import { invalidateTerminalParkingInputs } from '../terminal-pane/parking/terminal-parking-input-events'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { hasRegisteredRuntimeTerminalTab } from '../../runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry'
|
||||
@@ -62,7 +63,7 @@ export function useTerminalWorktreePrewarm(controller: TerminalColdActivationCon
|
||||
c.renderedActiveWorktreeId === worktreeId ||
|
||||
c.lastActivationWorktreeIdRef.current === worktreeId
|
||||
})
|
||||
bumpRevision()
|
||||
bumpRevision(worktreeId)
|
||||
},
|
||||
remainingHoldMs: (worktreeId) => {
|
||||
const c = controllerRef.current
|
||||
@@ -79,8 +80,10 @@ export function useTerminalWorktreePrewarm(controller: TerminalColdActivationCon
|
||||
: cooldownUntilMs + NARROWING_UNDO_MARGIN_MS - Date.now()
|
||||
}
|
||||
})
|
||||
const bumpRevision = (): void =>
|
||||
const bumpRevision = (worktreeId: string): void => {
|
||||
invalidateTerminalParkingInputs(worktreeId)
|
||||
controllerRef.current.setBackgroundMountRevision((revision) => revision + 1)
|
||||
}
|
||||
|
||||
const stopMeasuring = (worktreeId: string): void => {
|
||||
const c = controllerRef.current
|
||||
@@ -90,7 +93,7 @@ export function useTerminalWorktreePrewarm(controller: TerminalColdActivationCon
|
||||
// Skip the post-measure cool-down: ordinary parking (or the neighbor exemption) decides from here.
|
||||
c.measuringTerminalWorktreeIdsRef.current.delete(worktreeId)
|
||||
}
|
||||
bumpRevision()
|
||||
bumpRevision(worktreeId)
|
||||
}
|
||||
|
||||
const advance = (
|
||||
@@ -99,7 +102,7 @@ export function useTerminalWorktreePrewarm(controller: TerminalColdActivationCon
|
||||
stage: TerminalPrewarmStage
|
||||
): void => {
|
||||
controllerRef.current.prewarmLeasesRef.current.set(worktreeId, stage)
|
||||
bumpRevision()
|
||||
bumpRevision(worktreeId)
|
||||
const next = stage === 'mount' ? 'layout' : stage === 'layout' ? 'warm' : null
|
||||
if (next === null && lease.hovered) {
|
||||
return
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { MountedTerminalWorktrees } from './terminal/split-group-mount'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useTerminalParkingWorkspaceChanges } from './terminal-pane/parking/use-terminal-parking-workspace-changes'
|
||||
import { invalidateTerminalParkingInputs } from './terminal-pane/parking/terminal-parking-input-events'
|
||||
import { useAppStore } from '../store'
|
||||
import {
|
||||
TERMINAL_HIDDEN_WORKTREE_RETENTION_TTL_MS,
|
||||
countEvictionExemptTabRoutes,
|
||||
formatEvictionExemptRouteCounts,
|
||||
hasPendingRetentionSpawnWork,
|
||||
selectForceParkEvictableTabIds,
|
||||
selectRetentionForceParkedTerminalWorktrees,
|
||||
type TerminalWorktreeRetentionCandidate
|
||||
selectRetentionForceParkedTerminalWorktrees
|
||||
} from './terminal-pane/parking/retention/terminal-hidden-worktree-retention'
|
||||
import { recordRendererCrashBreadcrumb } from '@/lib/crash-breadcrumb-recorder'
|
||||
import { selectEvictionExemptTerminalTabIds } from './terminal-pane/parking/retention/terminal-eviction-exempt-tabs'
|
||||
@@ -16,10 +17,7 @@ import { warnTerminalLifecycleAnomaly } from './terminal-pane/layout/reconciliat
|
||||
import { recordTerminalWorktreeParkingDebugVerdicts } from './terminal-pane/parking/instrumentation/terminal-parking-e2e-overrides'
|
||||
import { getTerminalWorktreeColdParkRecheckDelayMs } from './terminal-pane/parking/retention/terminal-cold-park-recheck-deadlines'
|
||||
import { haveSameIdSet } from './terminal-workspace-model'
|
||||
import {
|
||||
canOrdinarilyParkRetentionCandidate,
|
||||
collectTerminalParkingPassCandidates
|
||||
} from './terminal-parking-pass-candidates'
|
||||
import { collectTerminalParkingPassCandidates } from './terminal-parking-pass-candidates'
|
||||
import type { TerminalParkingFoundation } from './use-terminal-parking-foundation'
|
||||
|
||||
export function useTerminalParkingPass(controller: TerminalParkingFoundation): void {
|
||||
@@ -34,7 +32,6 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
setEvictionExemptTerminalTabIds,
|
||||
setForceParkedTerminalWorktreeIds,
|
||||
setParkedTerminalWorktreeIds,
|
||||
setTerminalParkingRevision,
|
||||
tabsByWorktree,
|
||||
terminalParkingEnabled,
|
||||
terminalParkingRevision,
|
||||
@@ -50,40 +47,107 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
evictionExempt: ReadonlySet<string>
|
||||
} | null>(null)
|
||||
|
||||
const { revision, takeChangedWorkspaces } =
|
||||
useTerminalParkingWorkspaceChanges(workspaceSurfaceIds)
|
||||
const previousController = useRef<TerminalParkingFoundation | null>(null)
|
||||
const forcedParking = useRef<ReadonlySet<string>>(new Set())
|
||||
const exemptionByWorktree = useRef(new Map<string, ReadonlySet<string>>())
|
||||
useEffect(() => {
|
||||
const pass = collectTerminalParkingPassCandidates(controller)
|
||||
const retentionBudgetCandidates: TerminalWorktreeRetentionCandidate[] =
|
||||
pass.retentionCandidates.map((candidate) => {
|
||||
const tabs = tabsByWorktree[candidate.worktreeId] ?? []
|
||||
return {
|
||||
worktreeId: candidate.worktreeId,
|
||||
hiddenSinceMs: candidate.hiddenSinceMs,
|
||||
isVisible: candidate.isVisible,
|
||||
shouldMeasureHiddenWorktree: candidate.shouldMeasureHiddenWorktree,
|
||||
hasActivityTerminalPortal: candidate.hasActivityTerminalPortal,
|
||||
parkCooldownUntilMs: candidate.parkCooldownUntilMs ?? null,
|
||||
ordinaryParkingCovers: canOrdinarilyParkRetentionCandidate(controller, pass, candidate),
|
||||
hasPendingSpawnWork: tabs.some((tab) =>
|
||||
hasPendingRetentionSpawnWork(tab, pendingStartupByTabId)
|
||||
)
|
||||
const previous = previousController.current
|
||||
previousController.current = controller
|
||||
const dirty = takeChangedWorkspaces()
|
||||
if (controller.mountedWorktreeIdsRef.current instanceof MountedTerminalWorktrees) {
|
||||
for (const id of controller.mountedWorktreeIdsRef.current.takeCommittedChanges('retention')) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
if (previous) {
|
||||
if (
|
||||
previous.activeView !== activeView ||
|
||||
previous.renderedActiveWorktreeId !== renderedActiveWorktreeId
|
||||
) {
|
||||
if (previous.renderedActiveWorktreeId) {
|
||||
dirty.add(previous.renderedActiveWorktreeId)
|
||||
}
|
||||
})
|
||||
const forceParkedWorktreeIds = selectRetentionForceParkedTerminalWorktrees({
|
||||
worktrees: retentionBudgetCandidates,
|
||||
parkingEnabled: terminalParkingEnabled,
|
||||
retentionBudgetEnabled: terminalRetentionBudgetEnabled,
|
||||
nowMs: pass.nowMs,
|
||||
...pass.overrides
|
||||
})
|
||||
recordTerminalWorktreeParkingDebugVerdicts(
|
||||
retentionBudgetCandidates.map((candidate) => ({
|
||||
...candidate,
|
||||
parkCooldownUntilMs: candidate.parkCooldownUntilMs ?? null,
|
||||
forceParked: forceParkedWorktreeIds.has(candidate.worktreeId)
|
||||
}))
|
||||
)
|
||||
if (renderedActiveWorktreeId) {
|
||||
dirty.add(renderedActiveWorktreeId)
|
||||
}
|
||||
}
|
||||
if (previous.activityTerminalPortals !== activityTerminalPortals) {
|
||||
for (const portal of [...previous.activityTerminalPortals, ...activityTerminalPortals]) {
|
||||
dirty.add(portal.worktreeId)
|
||||
}
|
||||
}
|
||||
if (previous.workspaceSurfaceIds !== workspaceSurfaceIds) {
|
||||
const currentIds = controller.workspaceSurfaceIdSet
|
||||
const previousIds = previous.workspaceSurfaceIdSet
|
||||
for (const id of previous.workspaceSurfaceIds) {
|
||||
if (!currentIds.has(id)) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
for (const id of workspaceSurfaceIds) {
|
||||
if (!previousIds.has(id)) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
previous.terminalParkingEnabled !== terminalParkingEnabled ||
|
||||
previous.terminalRetentionBudgetEnabled !== terminalRetentionBudgetEnabled ||
|
||||
previous.terminalParkingRevision !== terminalParkingRevision
|
||||
) {
|
||||
for (const id of controller.mountedWorktreeIdsRef.current) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dirty.size === 0) {
|
||||
return
|
||||
}
|
||||
const pass = collectTerminalParkingPassCandidates(controller, dirty)
|
||||
const retentionBudgetCandidates = pass.retentionBudgetCandidates
|
||||
const forceParkedWorktreeIds =
|
||||
pass.rankingChanged ||
|
||||
previous?.terminalRetentionBudgetEnabled !== terminalRetentionBudgetEnabled ||
|
||||
previous?.terminalParkingEnabled !== terminalParkingEnabled
|
||||
? selectRetentionForceParkedTerminalWorktrees({
|
||||
worktrees: retentionBudgetCandidates,
|
||||
parkingEnabled: terminalParkingEnabled,
|
||||
retentionBudgetEnabled: terminalRetentionBudgetEnabled,
|
||||
nowMs: pass.nowMs,
|
||||
...pass.overrides
|
||||
})
|
||||
: forcedParking.current
|
||||
forcedParking.current = forceParkedWorktreeIds
|
||||
if (pass.rankingChanged) {
|
||||
recordTerminalWorktreeParkingDebugVerdicts(
|
||||
retentionBudgetCandidates.map((candidate) => ({
|
||||
...candidate,
|
||||
parkCooldownUntilMs: candidate.parkCooldownUntilMs ?? null,
|
||||
forceParked: forceParkedWorktreeIds.has(candidate.worktreeId)
|
||||
}))
|
||||
)
|
||||
}
|
||||
const capturedParked = parkedCaptureDoneRef.current
|
||||
for (const id of Array.from(capturedParked)) {
|
||||
const changedParkedIds = new Set(dirty)
|
||||
const previousParked = dispatchedIdSetsRef.current?.parked ?? new Set<string>()
|
||||
for (const id of previousParked) {
|
||||
if (!forceParkedWorktreeIds.has(id) && !pass.nextParkedTerminalWorktreeIds.has(id)) {
|
||||
changedParkedIds.add(id)
|
||||
}
|
||||
}
|
||||
for (const id of pass.nextParkedTerminalWorktreeIds) {
|
||||
if (!previousParked.has(id)) {
|
||||
changedParkedIds.add(id)
|
||||
}
|
||||
}
|
||||
for (const id of forceParkedWorktreeIds) {
|
||||
if (!previousParked.has(id)) {
|
||||
changedParkedIds.add(id)
|
||||
}
|
||||
}
|
||||
for (const id of changedParkedIds) {
|
||||
if (!forceParkedWorktreeIds.has(id) && !pass.nextParkedTerminalWorktreeIds.has(id)) {
|
||||
capturedParked.delete(id)
|
||||
}
|
||||
@@ -92,8 +156,8 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
// Capture before unmount while xterm still owns client scrollback; paired-parking capability
|
||||
// does not guarantee host buffer retention. Force-parks capture below under their eviction exemption.
|
||||
// Why localOnly: the ordinary park is the every-hide cadence; its bytes stay off the upload.
|
||||
for (const worktreeId of pass.nextParkedTerminalWorktreeIds) {
|
||||
if (capturedParked.has(worktreeId)) {
|
||||
for (const worktreeId of changedParkedIds) {
|
||||
if (!pass.nextParkedTerminalWorktreeIds.has(worktreeId) || capturedParked.has(worktreeId)) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
@@ -107,10 +171,19 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
capturedParked.add(worktreeId)
|
||||
}
|
||||
}
|
||||
for (const id of exemptionByWorktree.current.keys()) {
|
||||
if (!forceParkedWorktreeIds.has(id)) {
|
||||
exemptionByWorktree.current.delete(id)
|
||||
}
|
||||
}
|
||||
const nextEvictionExemptTabIds = new Set<string>()
|
||||
for (const worktreeId of forceParkedWorktreeIds) {
|
||||
const forceParkedTabs = tabsByWorktree[worktreeId] ?? []
|
||||
const exemptTabIds = selectEvictionExemptTerminalTabIds(worktreeId, forceParkedTabs)
|
||||
let exemptTabIds = exemptionByWorktree.current.get(worktreeId)
|
||||
if (!exemptTabIds || dirty.has(worktreeId)) {
|
||||
exemptTabIds = selectEvictionExemptTerminalTabIds(worktreeId, forceParkedTabs)
|
||||
exemptionByWorktree.current.set(worktreeId, exemptTabIds)
|
||||
}
|
||||
for (const tabId of exemptTabIds) {
|
||||
nextEvictionExemptTabIds.add(tabId)
|
||||
}
|
||||
@@ -168,7 +241,16 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
.map((candidate) => candidate.worktreeId)
|
||||
)
|
||||
|
||||
for (const candidate of pass.retentionCandidates) {
|
||||
for (const worktreeId of changedParkedIds) {
|
||||
const previousTimer = pass.parkingTimers.get(worktreeId)
|
||||
if (previousTimer !== undefined) {
|
||||
window.clearTimeout(previousTimer)
|
||||
pass.parkingTimers.delete(worktreeId)
|
||||
}
|
||||
const candidate = pass.candidateForWorktree(worktreeId)
|
||||
if (!candidate) {
|
||||
continue
|
||||
}
|
||||
if (
|
||||
candidate.isVisible ||
|
||||
candidate.shouldMeasureHiddenWorktree ||
|
||||
@@ -194,13 +276,15 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
const worktreeId = candidate.worktreeId
|
||||
const timer = window.setTimeout(() => {
|
||||
pass.parkingTimers.delete(worktreeId)
|
||||
setTerminalParkingRevision((revision) => revision + 1)
|
||||
invalidateTerminalParkingInputs(worktreeId)
|
||||
}, delayMs)
|
||||
pass.parkingTimers.set(worktreeId, timer)
|
||||
}
|
||||
}
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- `controller` is rebuilt every render; the pass reads only the listed values and stable refs.
|
||||
}, [
|
||||
revision,
|
||||
takeChangedWorkspaces,
|
||||
activeView,
|
||||
activityTerminalPortals,
|
||||
backgroundMountRevision,
|
||||
@@ -211,7 +295,6 @@ export function useTerminalParkingPass(controller: TerminalParkingFoundation): v
|
||||
setEvictionExemptTerminalTabIds,
|
||||
setForceParkedTerminalWorktreeIds,
|
||||
setParkedTerminalWorktreeIds,
|
||||
setTerminalParkingRevision,
|
||||
tabsByWorktree,
|
||||
terminalParkingEnabled,
|
||||
terminalParkingRevision,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { MountedTerminalWorktrees } from './terminal/split-group-mount'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useTerminalStartupActivation } from './terminal/use-terminal-startup-activation'
|
||||
import { useTerminalParkingWorkspaceChanges } from './terminal-pane/parking/use-terminal-parking-workspace-changes'
|
||||
import { getTerminalTabOwnerWorktreeId } from '@/store/terminals/terminal-tab-owner-index'
|
||||
import { findActivityTerminalPortal } from './activity/activity-terminal-portal'
|
||||
import { shouldSeedDefaultSurface } from '@/lib/workspace/activation/initial-surface/automatic-default-surface'
|
||||
import { findPendingWorktreeCreationId } from '@/lib/workspace/creation/pending-worktree-creation'
|
||||
import {
|
||||
canWatcherCoverParkedTerminalTab,
|
||||
syncParkedTerminalTabWatchersForWorkspaces,
|
||||
@@ -14,15 +16,8 @@ import {
|
||||
} from './terminal-pane/parking/output-watchers/terminal-parked-watcher-registry'
|
||||
|
||||
import { useAppStore } from '@/store'
|
||||
import { isTerminalWorkspaceEmptiedOnPurpose } from '../../../shared/workspace-layout/closed-terminal-tab-tombstones'
|
||||
import { gateWorktreeAgentActivation } from '@/lib/workspace/activation/worktree-agent-activation-gate'
|
||||
import { createWorkspaceTerminalHostAuthoritySelector } from '@/lib/workspace-terminal-host-authority'
|
||||
import { hasStructuredAgentLaunchInWorktree } from '@/lib/agent-session/launch/structured-agent-session-launch-status'
|
||||
import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/workspace/activation/initial-surface/empty-workspace-default-surface-claims'
|
||||
import type { TerminalColdActivationController } from './terminal-cold-activation'
|
||||
import { selectParkedEquivalentMountTabIds } from './terminal/startup-terminal-tab-hold'
|
||||
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch'
|
||||
import { createInitialTerminalThroughLayoutOwner } from '@/store/terminals/terminal-tab-create-through-layout-owner'
|
||||
|
||||
// Why shared: surfaces without watchable live tabs need no per-pass allocation.
|
||||
const NO_PARKED_TAB_IDS: ReadonlySet<string> = new Set()
|
||||
@@ -66,37 +61,123 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController)
|
||||
activeTabId,
|
||||
activeTabIdByWorktree,
|
||||
activeView,
|
||||
activeWorktreeId,
|
||||
activityTerminalPortals,
|
||||
anyMountedWorktreeHasLayout,
|
||||
backgroundMountRevision,
|
||||
createTab,
|
||||
effectiveParkedTerminalWorktreeIds,
|
||||
evictionExemptTerminalTabIds,
|
||||
getEffectiveLayoutForWorktree,
|
||||
groupsByWorktree,
|
||||
hydrationSucceeded,
|
||||
measurableBackgroundWorktreeIdsRef,
|
||||
mountedWorktreeIdsRef,
|
||||
pairedRuntimeParkingEnvironmentIds,
|
||||
pendingStartupByTabId,
|
||||
reconcileWorktreeTabModel,
|
||||
renderedActiveWorktreeId,
|
||||
startupTerminalTabHold,
|
||||
tabsByWorktree,
|
||||
terminalParkingEnabled,
|
||||
terminalProviderSnapshotCapabilityRevision,
|
||||
terminalSshParkingEnabled,
|
||||
terminalStartupRestorationReady,
|
||||
terminalTitleSnapshotAuthorityEnabled,
|
||||
workspaceSessionReady,
|
||||
workspaceSurfaceIds
|
||||
} = controller
|
||||
|
||||
const { revision, takeChangedWorkspaces } =
|
||||
useTerminalParkingWorkspaceChanges(workspaceSurfaceIds)
|
||||
const previousWatcherInputs = useRef<TerminalWatcherController | null>(null)
|
||||
useEffect(() => {
|
||||
pruneParkedTerminalWatchers(terminalWatcherLiveWorkspaceIds(workspaceSurfaceIds))
|
||||
const previous = previousWatcherInputs.current
|
||||
previousWatcherInputs.current = controller
|
||||
const dirty = takeChangedWorkspaces()
|
||||
if (mountedWorktreeIdsRef.current instanceof MountedTerminalWorktrees) {
|
||||
for (const id of mountedWorktreeIdsRef.current.takeCommittedChanges('watcher')) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
if (!previous || previous.workspaceSurfaceIds !== workspaceSurfaceIds) {
|
||||
const previousIds = new Set(previous?.workspaceSurfaceIds)
|
||||
for (const id of workspaceSurfaceIds) {
|
||||
if (!previousIds.has(id)) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
pruneParkedTerminalWatchers(terminalWatcherLiveWorkspaceIds(workspaceSurfaceIds))
|
||||
}
|
||||
if (previous) {
|
||||
if (
|
||||
previous.activeTabId !== activeTabId ||
|
||||
previous.backgroundMountRevision !== backgroundMountRevision
|
||||
) {
|
||||
if (renderedActiveWorktreeId) {
|
||||
dirty.add(renderedActiveWorktreeId)
|
||||
}
|
||||
}
|
||||
if (
|
||||
previous.activeView !== activeView ||
|
||||
previous.renderedActiveWorktreeId !== renderedActiveWorktreeId
|
||||
) {
|
||||
if (previous.renderedActiveWorktreeId) {
|
||||
dirty.add(previous.renderedActiveWorktreeId)
|
||||
}
|
||||
if (renderedActiveWorktreeId) {
|
||||
dirty.add(renderedActiveWorktreeId)
|
||||
}
|
||||
}
|
||||
if (previous.startupTerminalTabHold !== startupTerminalTabHold) {
|
||||
if (previous.startupTerminalTabHold) {
|
||||
dirty.add(previous.startupTerminalTabHold.worktreeId)
|
||||
}
|
||||
if (startupTerminalTabHold) {
|
||||
dirty.add(startupTerminalTabHold.worktreeId)
|
||||
}
|
||||
}
|
||||
if (previous.activityTerminalPortals !== activityTerminalPortals) {
|
||||
for (const portal of [...previous.activityTerminalPortals, ...activityTerminalPortals]) {
|
||||
dirty.add(portal.worktreeId)
|
||||
}
|
||||
}
|
||||
if (previous.effectiveParkedTerminalWorktreeIds !== effectiveParkedTerminalWorktreeIds) {
|
||||
for (const id of previous.effectiveParkedTerminalWorktreeIds) {
|
||||
if (!effectiveParkedTerminalWorktreeIds.has(id)) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
for (const id of effectiveParkedTerminalWorktreeIds) {
|
||||
if (!previous.effectiveParkedTerminalWorktreeIds.has(id)) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (previous.evictionExemptTerminalTabIds !== evictionExemptTerminalTabIds) {
|
||||
const state = useAppStore.getState()
|
||||
for (const tabId of new Set([
|
||||
...previous.evictionExemptTerminalTabIds,
|
||||
...evictionExemptTerminalTabIds
|
||||
])) {
|
||||
if (
|
||||
previous.evictionExemptTerminalTabIds.has(tabId) ===
|
||||
evictionExemptTerminalTabIds.has(tabId)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
const id = getTerminalTabOwnerWorktreeId(state.tabsByWorktree, tabId)
|
||||
if (id) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (previous.anyMountedWorktreeHasLayout !== anyMountedWorktreeHasLayout) {
|
||||
for (const id of mountedWorktreeIdsRef.current) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dirty.size === 0) {
|
||||
return
|
||||
}
|
||||
const syncEntriesByWorktreeId = new Map<string, ParkedTerminalTabWatcherSyncEntry>()
|
||||
for (const workspaceId of workspaceSurfaceIds) {
|
||||
for (const workspaceId of dirty) {
|
||||
if (
|
||||
anyMountedWorktreeHasLayout &&
|
||||
mountedWorktreeIdsRef.current.has(workspaceId) &&
|
||||
@@ -172,6 +253,9 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController)
|
||||
}
|
||||
syncParkedTerminalTabWatchersForWorkspaces(syncEntriesByWorktreeId)
|
||||
}, [
|
||||
controller,
|
||||
revision,
|
||||
takeChangedWorkspaces,
|
||||
activationDeferredMountTabIdsByWorktreeRef,
|
||||
activeTabId,
|
||||
activeView,
|
||||
@@ -199,121 +283,5 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController)
|
||||
])
|
||||
useEffect(() => () => disposeAllParkedTerminalWatchers(), [])
|
||||
|
||||
const startupActivationGateWorktreeIdsRef = useRef(new Set<string>())
|
||||
// Subscribe so host answers rerun the passes; retain owner resolution to avoid repeating catalog walks on every store write (STA-3363).
|
||||
const hostAuthoritySelector = useMemo(
|
||||
() => createWorkspaceTerminalHostAuthoritySelector(activeWorktreeId),
|
||||
[activeWorktreeId]
|
||||
)
|
||||
const activeWorktreeHostAuthority = useAppStore(hostAuthoritySelector)
|
||||
const activeWorktreeCreationPending = useAppStore(
|
||||
(state) =>
|
||||
findPendingWorktreeCreationId(state.pendingWorktreeCreations, activeWorktreeId) !== null
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!workspaceSessionReady ||
|
||||
!terminalStartupRestorationReady ||
|
||||
!activeWorktreeId ||
|
||||
activeWorktreeCreationPending
|
||||
) {
|
||||
return
|
||||
}
|
||||
// An unanswered owner is not an empty host; seeding before its census duplicates tabs (STA-4658).
|
||||
if (activeWorktreeHostAuthority !== 'none') {
|
||||
return
|
||||
}
|
||||
if (startupActivationGateWorktreeIdsRef.current.has(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
void gateWorktreeAgentActivation(activeWorktreeId).then((outcome) => {
|
||||
if (
|
||||
cancelled ||
|
||||
outcome === 'blocked' ||
|
||||
useAppStore.getState().activeWorktreeId !== activeWorktreeId
|
||||
) {
|
||||
return
|
||||
}
|
||||
// An in-flight reseed owns the surface but remains unmarked so leaving mid-wait allows retry on return.
|
||||
if (outcome === 'empty' && isEmptyWorkspaceDefaultSurfacePending(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
// Only applied decisions consume the gate; canceled/blocked checks stay retryable and reruns share the in-flight promise.
|
||||
startupActivationGateWorktreeIdsRef.current.add(activeWorktreeId)
|
||||
if (outcome !== 'empty') {
|
||||
return
|
||||
}
|
||||
// A pending or unanswered chat create owns the surface even before its tab is published.
|
||||
if (hasStructuredAgentLaunchInWorktree(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
// Why: the activation gate reconciles durable/live agent state first; only an actually empty, never-visited workspace receives a default shell.
|
||||
const { renderableTabCount } = reconcileWorktreeTabModel(activeWorktreeId)
|
||||
// Only recorded closes preserve emptiness; reread at decision time because rows can change while waiting.
|
||||
const emptiedOnPurpose = isTerminalWorkspaceEmptiedOnPurpose(
|
||||
useAppStore.getState(),
|
||||
activeWorktreeId
|
||||
)
|
||||
if (shouldSeedDefaultSurface(activeWorktreeId, renderableTabCount, emptiedOnPurpose)) {
|
||||
if (
|
||||
ORCA_LAYOUT_OWNER_IS_MAIN &&
|
||||
createInitialTerminalThroughLayoutOwner(useAppStore.getState, activeWorktreeId, () =>
|
||||
createTab(activeWorktreeId, undefined, undefined, { pendingActivationSpawn: true })
|
||||
)
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Initial default tabs must not count as user activity and reorder the sidebar; explicit New Tab still does.
|
||||
createTab(activeWorktreeId, undefined, undefined, { pendingActivationSpawn: true })
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [
|
||||
activeWorktreeId,
|
||||
activeWorktreeHostAuthority,
|
||||
activeWorktreeCreationPending,
|
||||
createTab,
|
||||
reconcileWorktreeTabModel,
|
||||
terminalStartupRestorationReady,
|
||||
workspaceSessionReady
|
||||
])
|
||||
|
||||
const startupResumeWorktreeIdsRef = useRef(new Set<string>())
|
||||
useEffect(() => {
|
||||
if (
|
||||
!workspaceSessionReady ||
|
||||
!terminalStartupRestorationReady ||
|
||||
!hydrationSucceeded ||
|
||||
!activeWorktreeId
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (startupResumeWorktreeIdsRef.current.has(activeWorktreeId)) {
|
||||
return
|
||||
}
|
||||
// Do not consume recovery while the host is unanswered or sleeping agents remain stranded for this session.
|
||||
if (activeWorktreeHostAuthority === 'unverifiable') {
|
||||
return
|
||||
}
|
||||
startupResumeWorktreeIdsRef.current.add(activeWorktreeId)
|
||||
// Startup recovery needs the same host census and in-flight gate as explicit activation.
|
||||
void gateWorktreeAgentActivation(activeWorktreeId).then(
|
||||
(outcome) => {
|
||||
if (outcome === 'blocked') {
|
||||
startupResumeWorktreeIdsRef.current.delete(activeWorktreeId)
|
||||
}
|
||||
},
|
||||
() => startupResumeWorktreeIdsRef.current.delete(activeWorktreeId)
|
||||
)
|
||||
}, [
|
||||
activeWorktreeId,
|
||||
activeWorktreeHostAuthority,
|
||||
hydrationSucceeded,
|
||||
terminalStartupRestorationReady,
|
||||
workspaceSessionReady
|
||||
])
|
||||
useTerminalStartupActivation(controller)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo, useRef } from 'react'
|
||||
import { MountedTerminalWorktrees } from './terminal/split-group-mount'
|
||||
import { parseWorkspaceKey } from '../../../shared/workspace-scope'
|
||||
import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { useAppStore } from '../store'
|
||||
@@ -22,7 +23,7 @@ export function useTerminalWorkspaceFoundation() {
|
||||
TerminalTab
|
||||
> | null>(null)
|
||||
terminalTopologyProjectionRef.current ??= createTerminalWorktreeTopologyProjection()
|
||||
const mountedWorktreeIdsRef = useRef(new Set<string>())
|
||||
const mountedWorktreeIdsRef = useRef<Set<string>>(new MountedTerminalWorktrees())
|
||||
const browserGuestWorktreeRecencyRef = useRef<string[]>([])
|
||||
const measurableBackgroundWorktreeIdsRef = useRef(new Set<string>())
|
||||
const terminalWorktreeHiddenSinceRef = useRef(new Map<string, number>())
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import { isWorkspaceSleepRecord } from '../../../../../shared/workspace-sleep'
|
||||
import {
|
||||
@@ -154,7 +155,9 @@ function providerSessionOwnedElsewhere(
|
||||
state: ReturnType<typeof useAppStore.getState>
|
||||
): boolean {
|
||||
// Claim keys handle same-workspace duplicates; finished notes, moved hosts and foreign-machine records cannot claim sessions.
|
||||
return Object.values(state.sleepingAgentSessionsByPaneKey).some(
|
||||
return Array.from(
|
||||
sleepingAgentRecordIndex.providerSessionCandidates(state.sleepingAgentSessionsByPaneKey, record)
|
||||
).some(
|
||||
(other) =>
|
||||
other.worktreeId !== record.worktreeId &&
|
||||
other.agent === record.agent &&
|
||||
@@ -221,7 +224,9 @@ export function resumeSleepingAgentSessionsForWorktree(
|
||||
return 0
|
||||
}
|
||||
// Main resumes workspace sleep records in their own panes; only stranded ones get a fresh tab here.
|
||||
const worktreeRecords = Object.values(state.sleepingAgentSessionsByPaneKey)
|
||||
const worktreeRecords = sleepingAgentRecordIndex
|
||||
.entries(state.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)
|
||||
.filter(
|
||||
(record) =>
|
||||
record.worktreeId === worktreeId &&
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import { getFirstTerminalTabOwnerWorktreeId } from '@/store/terminals/terminal-tab-owner-index'
|
||||
import type { useAppStore } from '@/store/index'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import { agentTurnEndedUncleanly } from '../../../../../shared/agent-status/lifecycle/agent-main-agent-verdict'
|
||||
@@ -43,7 +45,9 @@ function getLegacyProviderSessionKeysForTab(
|
||||
tabId: string
|
||||
): Set<string> {
|
||||
const keys = new Set<string>()
|
||||
for (const record of Object.values(state.sleepingAgentSessionsByPaneKey)) {
|
||||
for (const record of sleepingAgentRecordIndex
|
||||
.entries(state.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)) {
|
||||
if (record.worktreeId === worktreeId && getLegacyPaneTabId(record) === tabId) {
|
||||
keys.add(getProviderSessionClaimKey(record))
|
||||
}
|
||||
@@ -131,13 +135,11 @@ function findPreservedTabOwner(
|
||||
if (hinted) {
|
||||
return { tab: hinted, worktreeId: worktreeIdHint }
|
||||
}
|
||||
for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) {
|
||||
const tab = tabs.find((candidate) => candidate.id === tabId)
|
||||
if (tab) {
|
||||
return { tab, worktreeId }
|
||||
}
|
||||
}
|
||||
return null
|
||||
const worktreeId = getFirstTerminalTabOwnerWorktreeId(state.tabsByWorktree, tabId)
|
||||
const tab = worktreeId
|
||||
? state.tabsByWorktree[worktreeId]?.find((candidate) => candidate.id === tabId)
|
||||
: undefined
|
||||
return tab && worktreeId ? { tab, worktreeId } : null
|
||||
}
|
||||
|
||||
/** A workspace sleep's record whose tab is gone: main has no pane to resume it in, so the window reopens it in a fresh tab (#22657). */
|
||||
|
||||
@@ -132,9 +132,9 @@ function getCanonicalPassiveWakeRecords(
|
||||
|
||||
/** Wake mobile-visible sleepers without desktop navigation: wake mounted hibernated panes and collect claims; target-mount unmounted passive hibernation tabs; resume other records without navigation, skipping claims; mount those activate:false resume tabs so startup reaches PTYs. Skip restoreOnTabOpenOnly records to preserve explicit sleep. PTYs republish automatically, so await no spawn. */
|
||||
export function wakeSleepingAgentsForWorktreeInBackground(worktreeId: string): void {
|
||||
const sleptRecords = Object.values(useAppStore.getState().sleepingAgentSessionsByPaneKey).filter(
|
||||
(record) => record.worktreeId === worktreeId
|
||||
)
|
||||
const sleptRecords = sleepingAgentRecordIndex
|
||||
.entries(useAppStore.getState().sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)
|
||||
// No sleepers means no mounting: phone browsing must not accumulate desktop workspaces/PTYS.
|
||||
if (sleptRecords.length === 0) {
|
||||
return
|
||||
@@ -190,3 +190,4 @@ export function wakeSleepingAgentsForWorktreeInBackground(worktreeId: string): v
|
||||
}
|
||||
resumeSleepingAgentSessionsForWorktree(worktreeId, resumeOptions)
|
||||
}
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAppStore } from '@/store'
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import {
|
||||
parseLegacyNumericPaneKey,
|
||||
@@ -23,7 +24,10 @@ export function requestSleepingAgentWakeOnMount(
|
||||
tabIds: readonly string[]
|
||||
): void {
|
||||
const wanted = new Set(tabIds)
|
||||
for (const record of Object.values(useAppStore.getState().sleepingAgentSessionsByPaneKey)) {
|
||||
for (const [, record] of sleepingAgentRecordIndex.entries(
|
||||
useAppStore.getState().sleepingAgentSessionsByPaneKey,
|
||||
worktreeId
|
||||
)) {
|
||||
const tabId = getSleepingRecordTabId(record)
|
||||
if (record.worktreeId === worktreeId && tabId !== null && wanted.has(tabId)) {
|
||||
requestedRecords.add(record)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { sleepingAgentRecordIndex } from '@/store/terminals/sleeping-agent-record-index'
|
||||
import { useAppStore } from '@/store/index'
|
||||
import type { PtyListedSession } from '../../../../../shared/terminal/pty/lifecycle/pty-listed-session'
|
||||
import {
|
||||
@@ -84,9 +85,10 @@ export function workspaceHasSleepingAgentSessions(
|
||||
state: Pick<ReturnType<typeof useAppStore.getState>, 'sleepingAgentSessionsByPaneKey'>,
|
||||
worktreeId: string
|
||||
): boolean {
|
||||
return Object.values(state.sleepingAgentSessionsByPaneKey).some(
|
||||
(record) => record.worktreeId === worktreeId
|
||||
)
|
||||
return sleepingAgentRecordIndex
|
||||
.entries(state.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)
|
||||
.some((record) => record.worktreeId === worktreeId)
|
||||
}
|
||||
|
||||
function hasStructuredSession(store: ActivationStore, worktreeId: string): boolean {
|
||||
@@ -122,7 +124,9 @@ function liveSleepingAgentClaims(
|
||||
session.paneKey ? [[session.paneKey, session.id] as const] : []
|
||||
)
|
||||
)
|
||||
for (const record of Object.values(store.sleepingAgentSessionsByPaneKey)) {
|
||||
for (const record of sleepingAgentRecordIndex
|
||||
.entries(store.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)) {
|
||||
if (record.worktreeId !== worktreeId) {
|
||||
continue
|
||||
}
|
||||
@@ -247,10 +251,13 @@ export async function runWorktreeAgentActivationGate(
|
||||
liveWorkspaceSessions,
|
||||
structuredInventory
|
||||
)
|
||||
const hasUnclaimedRecovery = Object.values(store.sleepingAgentSessionsByPaneKey).some(
|
||||
(record) =>
|
||||
record.worktreeId === worktreeId && !claims.keys.has(getProviderSessionClaimKey(record))
|
||||
)
|
||||
const hasUnclaimedRecovery = sleepingAgentRecordIndex
|
||||
.entries(store.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([, record]) => record)
|
||||
.some(
|
||||
(record) =>
|
||||
record.worktreeId === worktreeId && !claims.keys.has(getProviderSessionClaimKey(record))
|
||||
)
|
||||
// A surfaced PTY without a conversation claim may still own the sleeping session.
|
||||
if (
|
||||
hasUnclaimedRecovery &&
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordChangedKeys } from '@/store/terminals/terminal-input-record-transition'
|
||||
|
||||
export type WorktreeTabBucketProjection<T, P> = {
|
||||
project: (source: Readonly<Record<string, readonly T[]>>) => Record<string, P[]>
|
||||
}
|
||||
@@ -17,12 +19,23 @@ export function createWorktreeTabBucketProjection<T, P>(args: {
|
||||
return previousProjection
|
||||
}
|
||||
|
||||
const sourceKeys = Object.keys(source)
|
||||
const knownKeys = previousSource
|
||||
? terminalInputRecordChangedKeys(previousSource, source)
|
||||
: null
|
||||
const sourceKeys = knownKeys ? [...knownKeys] : Object.keys(source)
|
||||
let changed =
|
||||
previousProjection === null || sourceKeys.length !== Object.keys(previousProjection).length
|
||||
const nextProjection: Record<string, P[]> = {}
|
||||
previousProjection === null ||
|
||||
(!knownKeys && sourceKeys.length !== Object.keys(previousProjection).length)
|
||||
const nextProjection: Record<string, P[]> = knownKeys ? { ...previousProjection } : {}
|
||||
|
||||
for (const worktreeId of sourceKeys) {
|
||||
if (!(worktreeId in source)) {
|
||||
if (worktreeId in nextProjection) {
|
||||
changed = true
|
||||
}
|
||||
delete nextProjection[worktreeId]
|
||||
continue
|
||||
}
|
||||
const sourceTabs = source[worktreeId] ?? []
|
||||
const previousTabs = previousProjection?.[worktreeId]
|
||||
let projectedTabs: P[]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
import type { AgentStatusSlice } from './agent-status-slice-contract'
|
||||
import type { AgentStatusRuntime } from './agent-status-runtime'
|
||||
import type { AgentLaunchConfigRegistryEntry } from './agent-status-contract'
|
||||
@@ -84,7 +85,13 @@ export function createAgentStatusLaunchActions(
|
||||
}
|
||||
: {}),
|
||||
...(nextSleepingAgentSessions !== s.sleepingAgentSessionsByPaneKey
|
||||
? { sleepingAgentSessionsByPaneKey: nextSleepingAgentSessions }
|
||||
? {
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
nextSleepingAgentSessions,
|
||||
[paneKey]
|
||||
)
|
||||
}
|
||||
: {})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
import { projectAgentPaneConversation } from './agent-pane-conversation'
|
||||
import type { AppState } from '../../types'
|
||||
import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types'
|
||||
@@ -116,7 +117,11 @@ export function reduceAgentStatusLiveUpdate(
|
||||
? { agentConversationsByPaneKey: nextConversations }
|
||||
: {}),
|
||||
retainedAgentsByPaneKey: nextRetainedAgents,
|
||||
sleepingAgentSessionsByPaneKey: nextSleepingAgentSessions,
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
state.sleepingAgentSessionsByPaneKey,
|
||||
nextSleepingAgentSessions,
|
||||
[paneKey, ...evictedPaneKeys]
|
||||
),
|
||||
agentLaunchConfigByPaneKey: nextLaunchConfigs,
|
||||
migrationUnsupportedByPtyId: migrationUnsupported.next,
|
||||
retentionSuppressedPaneKeys: nextRetentionSuppressedPaneKeys,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
export const RECENTLY_CLOSED_AGENT_STATUS_TAB_IDS_MAX = 1024
|
||||
export const RECENTLY_RETIRED_AGENT_STATUS_PANE_KEYS_MAX = 1024
|
||||
|
||||
@@ -86,7 +87,7 @@ export function movePaneKeyedRecord<T>(
|
||||
const next = { ...record }
|
||||
delete next[fromPaneKey]
|
||||
next[toPaneKey] = transform(value)
|
||||
return next
|
||||
return terminalInputRecordTransition(record, next, [fromPaneKey, toPaneKey])
|
||||
}
|
||||
|
||||
export function removePaneKeys<T>(
|
||||
@@ -102,7 +103,7 @@ export function removePaneKeys<T>(
|
||||
next ??= { ...record }
|
||||
delete next[key]
|
||||
}
|
||||
return next ?? record
|
||||
return next ? terminalInputRecordTransition(record, next, paneKeys) : record
|
||||
}
|
||||
|
||||
export function removePaneKeysByTabPrefix<T>(
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
import type { AgentStatusSlice } from './agent-status-slice-contract'
|
||||
import type { AgentStatusRuntime } from './agent-status-runtime'
|
||||
import type {
|
||||
@@ -155,10 +156,14 @@ export function createAgentStatusProviderSessionActions(
|
||||
? { agentConversationsByPaneKey: nextConversations }
|
||||
: {}),
|
||||
retainedAgentsByPaneKey: nextRetained,
|
||||
sleepingAgentSessionsByPaneKey: {
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
[paneKey]: record
|
||||
},
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
{
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
[paneKey]: record
|
||||
},
|
||||
[paneKey]
|
||||
),
|
||||
agentLaunchConfigByPaneKey: nextLaunchConfigs,
|
||||
acknowledgedAgentsByPaneKey: removePaneKeys(
|
||||
s.acknowledgedAgentsByPaneKey,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sleepingAgentRecordIndex } from '../../terminals/sleeping-agent-record-index'
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import type { AgentStatusSlice } from './agent-status-slice-contract'
|
||||
import type { AgentStatusRuntime } from './agent-status-runtime'
|
||||
@@ -41,7 +43,20 @@ export function createAgentStatusRecoveryActions(
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? { sleepingAgentSessionsByPaneKey: next } : s
|
||||
return changed
|
||||
? {
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
next,
|
||||
[
|
||||
...sleepingAgentRecordIndex
|
||||
.entries(s.sleepingAgentSessionsByPaneKey, worktreeId)
|
||||
.map(([key]) => key),
|
||||
...Object.keys(records)
|
||||
]
|
||||
)
|
||||
}
|
||||
: s
|
||||
})
|
||||
},
|
||||
|
||||
@@ -67,7 +82,15 @@ export function createAgentStatusRecoveryActions(
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? { sleepingAgentSessionsByPaneKey: next } : s
|
||||
return changed
|
||||
? {
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
next,
|
||||
Object.keys(s.agentStatusByPaneKey)
|
||||
)
|
||||
}
|
||||
: s
|
||||
})
|
||||
},
|
||||
|
||||
@@ -78,10 +101,14 @@ export function createAgentStatusRecoveryActions(
|
||||
s.sleepingAgentSessionsByPaneKey[record.paneKey] !== replaces
|
||||
? s
|
||||
: {
|
||||
sleepingAgentSessionsByPaneKey: {
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
[record.paneKey]: record
|
||||
}
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
{
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
[record.paneKey]: record
|
||||
},
|
||||
[record.paneKey]
|
||||
)
|
||||
}
|
||||
)
|
||||
},
|
||||
@@ -90,14 +117,16 @@ export function createAgentStatusRecoveryActions(
|
||||
clearSleepingAgentSessionsByWorktree: (worktreeId) => {
|
||||
set((s) => {
|
||||
let changed = false
|
||||
const next: Record<string, SleepingAgentSessionRecord> = {}
|
||||
const next = { ...s.sleepingAgentSessionsByPaneKey }
|
||||
const removed: string[] = []
|
||||
for (const [paneKey, record] of Object.entries(s.sleepingAgentSessionsByPaneKey)) {
|
||||
for (const [paneKey, record] of sleepingAgentRecordIndex.entries(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
worktreeId
|
||||
)) {
|
||||
if (record.worktreeId === worktreeId) {
|
||||
changed = true
|
||||
removed.push(paneKey)
|
||||
} else {
|
||||
next[paneKey] = record
|
||||
delete next[paneKey]
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
@@ -109,7 +138,11 @@ export function createAgentStatusRecoveryActions(
|
||||
delete nextLaunch[paneKey]
|
||||
}
|
||||
return {
|
||||
sleepingAgentSessionsByPaneKey: next,
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
next,
|
||||
removed
|
||||
),
|
||||
...(nextLaunch !== s.agentLaunchConfigByPaneKey
|
||||
? { agentLaunchConfigByPaneKey: nextLaunch }
|
||||
: {})
|
||||
@@ -139,7 +172,11 @@ export function createAgentStatusRecoveryActions(
|
||||
delete nextLaunch[paneKey]
|
||||
}
|
||||
return {
|
||||
sleepingAgentSessionsByPaneKey: next,
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
next,
|
||||
removed
|
||||
),
|
||||
...(nextLaunch !== s.agentLaunchConfigByPaneKey
|
||||
? { agentLaunchConfigByPaneKey: nextLaunch }
|
||||
: {})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AppState } from '../../types'
|
||||
import { sleepingAgentRecordIndex } from '../../terminals/sleeping-agent-record-index'
|
||||
import '../../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
@@ -40,7 +41,10 @@ export function collectSleepingAgentSessionRecordsForWorktree(
|
||||
const promotedLiveRecoveryPaneKeys = new Set<string>()
|
||||
|
||||
if (isManualWorktreeSleep) {
|
||||
for (const existing of Object.values(state.sleepingAgentSessionsByPaneKey)) {
|
||||
for (const [, existing] of sleepingAgentRecordIndex.entries(
|
||||
state.sleepingAgentSessionsByPaneKey,
|
||||
worktreeId
|
||||
)) {
|
||||
const liveEntry = state.agentStatusByPaneKey[existing.paneKey]
|
||||
if (
|
||||
existing.worktreeId !== worktreeId ||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { removePaneKeys } from './agent-status-pane-keyed-records'
|
||||
import { applyAgentStatusBatchUpdate } from './agent-status-batch-update'
|
||||
import { projectAgentPaneConversation } from './agent-pane-conversation'
|
||||
import { structuralValuesEqualIgnoringUndefined } from '../../../../../shared/structural-value-equality'
|
||||
@@ -273,19 +274,13 @@ export function createAgentStatusRuntime(
|
||||
}
|
||||
const uniquePaneKeys = new Set(paneKeys)
|
||||
set((s) => {
|
||||
let nextSleeping = s.sleepingAgentSessionsByPaneKey
|
||||
for (const paneKey of uniquePaneKeys) {
|
||||
if (paneKey in nextSleeping) {
|
||||
if (nextSleeping === s.sleepingAgentSessionsByPaneKey) {
|
||||
nextSleeping = { ...nextSleeping }
|
||||
}
|
||||
delete nextSleeping[paneKey]
|
||||
}
|
||||
}
|
||||
const nextSleeping = removePaneKeys(s.sleepingAgentSessionsByPaneKey, uniquePaneKeys)
|
||||
if (nextSleeping === s.sleepingAgentSessionsByPaneKey) {
|
||||
return s
|
||||
}
|
||||
return { sleepingAgentSessionsByPaneKey: nextSleeping }
|
||||
return {
|
||||
sleepingAgentSessionsByPaneKey: nextSleeping
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
import { sleepingAgentRecordIndex } from '../../terminals/sleeping-agent-record-index'
|
||||
import type { AppState } from '../../types'
|
||||
import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types'
|
||||
import { agentTurnEndedUncleanly } from '../../../../../shared/agent-status/lifecycle/agent-main-agent-verdict'
|
||||
@@ -78,7 +80,8 @@ export function removeSleepingRecordsReplacedByManualWorktreeSleep(
|
||||
const allowedPaneKeys = paneKeys ? new Set(paneKeys) : null
|
||||
let next = records
|
||||
let changed = false
|
||||
for (const [paneKey, record] of Object.entries(records)) {
|
||||
const removed = new Set<string>()
|
||||
for (const [paneKey, record] of sleepingAgentRecordIndex.entries(records, worktreeId)) {
|
||||
if (record.worktreeId !== worktreeId || (allowedPaneKeys && !allowedPaneKeys.has(paneKey))) {
|
||||
continue
|
||||
}
|
||||
@@ -90,7 +93,8 @@ export function removeSleepingRecordsReplacedByManualWorktreeSleep(
|
||||
next = { ...records }
|
||||
}
|
||||
delete next[paneKey]
|
||||
removed.add(paneKey)
|
||||
changed = true
|
||||
}
|
||||
return { records: next, changed }
|
||||
return { records: terminalInputRecordTransition(records, next, removed), changed }
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { createRuntimeEnvironmentStatusRetention } from './runtime-environment-status-retention'
|
||||
import type {
|
||||
RuntimeStatusSlice,
|
||||
RuntimeStatusStoreSetState,
|
||||
RuntimeStatusStoreState
|
||||
} from './runtime-status-types'
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
|
||||
import { lastVerifiedRuntimeStatus } from '../../../../../shared/remote-runtime/host-status/runtime-host-status'
|
||||
import { runtimeEnvironmentStatusesEqual } from './runtime-environment-status-equality'
|
||||
@@ -75,16 +77,19 @@ export const createRuntimeStatusSlice: (
|
||||
set((s) => {
|
||||
const keep = new Set(environments.map((environment) => environment.id))
|
||||
const nextStatuses = new Map(s.runtimeStatusByEnvironmentId)
|
||||
const removedStatusIds = new Set<string>()
|
||||
let statusesChanged = false
|
||||
for (const id of nextStatuses.keys()) {
|
||||
if (!keep.has(id)) {
|
||||
nextStatuses.delete(id)
|
||||
removedStatusIds.add(id)
|
||||
runtimeStatusConnectionGeneration.advanceRuntimeEnvironmentConnectionGeneration(id)
|
||||
statusesChanged = true
|
||||
}
|
||||
}
|
||||
for (const id of replacedEnvironmentIds) {
|
||||
if (nextStatuses.delete(id)) {
|
||||
removedStatusIds.add(id)
|
||||
statusesChanged = true
|
||||
}
|
||||
runtimeStatusConnectionGeneration.advanceRuntimeEnvironmentConnectionGeneration(id)
|
||||
@@ -123,7 +128,15 @@ export const createRuntimeStatusSlice: (
|
||||
runtimeEnvironments: catalogUnchanged ? s.runtimeEnvironments : reconciled,
|
||||
runtimeEnvironmentCatalogHydrated: true,
|
||||
runtimeEnvironmentCatalogSettled: true,
|
||||
...(statusesChanged ? { runtimeStatusByEnvironmentId: nextStatuses } : {}),
|
||||
...(statusesChanged
|
||||
? {
|
||||
runtimeStatusByEnvironmentId: terminalInputRecordTransition(
|
||||
s.runtimeStatusByEnvironmentId,
|
||||
nextStatuses,
|
||||
removedStatusIds
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
...(removedChanged ? { removedRuntimeEnvironmentIds: nextRemoved } : {})
|
||||
}
|
||||
})
|
||||
@@ -155,9 +168,10 @@ export const createRuntimeStatusSlice: (
|
||||
const apply = (): void =>
|
||||
applyRuntimeHostStatusSnapshot(snapshot, get(), (entry) => {
|
||||
set((s) => ({
|
||||
runtimeStatusByEnvironmentId: new Map(s.runtimeStatusByEnvironmentId).set(
|
||||
snapshot.environmentId,
|
||||
entry
|
||||
runtimeStatusByEnvironmentId: terminalInputRecordTransition(
|
||||
s.runtimeStatusByEnvironmentId,
|
||||
new Map(s.runtimeStatusByEnvironmentId).set(snapshot.environmentId, entry),
|
||||
[snapshot.environmentId]
|
||||
)
|
||||
}))
|
||||
})
|
||||
@@ -239,7 +253,11 @@ export const createRuntimeStatusSlice: (
|
||||
return {
|
||||
runtimeStatusByEnvironmentId: statusUnchanged
|
||||
? s.runtimeStatusByEnvironmentId
|
||||
: new Map(s.runtimeStatusByEnvironmentId).set(environmentId, nextEntry),
|
||||
: terminalInputRecordTransition(
|
||||
s.runtimeStatusByEnvironmentId,
|
||||
new Map(s.runtimeStatusByEnvironmentId).set(environmentId, nextEntry),
|
||||
[environmentId]
|
||||
),
|
||||
...(environmentsChanged ? { runtimeEnvironments } : {})
|
||||
}
|
||||
})
|
||||
@@ -255,38 +273,7 @@ export const createRuntimeStatusSlice: (
|
||||
}
|
||||
},
|
||||
|
||||
clearRuntimeEnvironmentStatus: (environmentId) => {
|
||||
dismissRuntimeDisconnectedToast(environmentId)
|
||||
set((s) => {
|
||||
runtimeStatusConnectionGeneration.advanceRuntimeEnvironmentConnectionGeneration(environmentId)
|
||||
if (!s.runtimeStatusByEnvironmentId.has(environmentId)) {
|
||||
return s
|
||||
}
|
||||
const next = new Map(s.runtimeStatusByEnvironmentId)
|
||||
next.delete(environmentId)
|
||||
return { runtimeStatusByEnvironmentId: next }
|
||||
})
|
||||
},
|
||||
|
||||
retainRuntimeEnvironmentStatuses: (environmentIds) => {
|
||||
const keep = new Set(environmentIds)
|
||||
for (const id of get().runtimeStatusByEnvironmentId.keys()) {
|
||||
if (!keep.has(id)) {
|
||||
dismissRuntimeDisconnectedToast(id)
|
||||
}
|
||||
}
|
||||
set((s) => {
|
||||
let changed = false
|
||||
const next = new Map(s.runtimeStatusByEnvironmentId)
|
||||
for (const id of next.keys()) {
|
||||
if (!keep.has(id)) {
|
||||
next.delete(id)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed ? { runtimeStatusByEnvironmentId: next } : s
|
||||
})
|
||||
},
|
||||
...createRuntimeEnvironmentStatusRetention(set, get),
|
||||
|
||||
refreshRuntimeEnvironmentStatus: (environmentId, timeoutMs = 10_000) =>
|
||||
refreshRuntimeEnvironmentStatus(
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type {
|
||||
RuntimeStatusSlice,
|
||||
RuntimeStatusStoreSetState,
|
||||
RuntimeStatusStoreState
|
||||
} from './runtime-status-types'
|
||||
import { terminalInputRecordTransition } from '../../terminals/terminal-input-record-transition'
|
||||
import { dismissRuntimeDisconnectedToast } from './runtime-environment-disconnect-toast'
|
||||
import * as runtimeStatusConnectionGeneration from './runtime-status-connection-generation'
|
||||
|
||||
export function createRuntimeEnvironmentStatusRetention(
|
||||
set: RuntimeStatusStoreSetState,
|
||||
get: () => RuntimeStatusStoreState
|
||||
): Pick<RuntimeStatusSlice, 'clearRuntimeEnvironmentStatus' | 'retainRuntimeEnvironmentStatuses'> {
|
||||
return {
|
||||
clearRuntimeEnvironmentStatus: (environmentId) => {
|
||||
dismissRuntimeDisconnectedToast(environmentId)
|
||||
set((s) => {
|
||||
runtimeStatusConnectionGeneration.advanceRuntimeEnvironmentConnectionGeneration(
|
||||
environmentId
|
||||
)
|
||||
if (!s.runtimeStatusByEnvironmentId.has(environmentId)) {
|
||||
return s
|
||||
}
|
||||
const next = new Map(s.runtimeStatusByEnvironmentId)
|
||||
next.delete(environmentId)
|
||||
return {
|
||||
runtimeStatusByEnvironmentId: terminalInputRecordTransition(
|
||||
s.runtimeStatusByEnvironmentId,
|
||||
next,
|
||||
[environmentId]
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
retainRuntimeEnvironmentStatuses: (environmentIds) => {
|
||||
const keep = new Set(environmentIds)
|
||||
for (const id of get().runtimeStatusByEnvironmentId.keys()) {
|
||||
if (!keep.has(id)) {
|
||||
dismissRuntimeDisconnectedToast(id)
|
||||
}
|
||||
}
|
||||
set((s) => {
|
||||
let changed = false
|
||||
const removed: string[] = []
|
||||
const next = new Map(s.runtimeStatusByEnvironmentId)
|
||||
for (const id of next.keys()) {
|
||||
if (!keep.has(id)) {
|
||||
next.delete(id)
|
||||
removed.push(id)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
? {
|
||||
runtimeStatusByEnvironmentId: terminalInputRecordTransition(
|
||||
s.runtimeStatusByEnvironmentId,
|
||||
next,
|
||||
removed
|
||||
)
|
||||
}
|
||||
: s
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import { terminalInputRecordChangedKeys } from './terminal-input-record-transition'
|
||||
|
||||
type Records = Readonly<Record<string, SleepingAgentSessionRecord | undefined>>
|
||||
type RecordEntry = readonly [string, SleepingAgentSessionRecord]
|
||||
const EMPTY_ENTRIES: readonly RecordEntry[] = []
|
||||
|
||||
function providerSessionKey(record: SleepingAgentSessionRecord): string | null {
|
||||
return record.providerSession
|
||||
? JSON.stringify([record.agent, record.providerSession.key, record.providerSession.id])
|
||||
: null
|
||||
}
|
||||
|
||||
function tabPrefixes(key: string, record: SleepingAgentSessionRecord | undefined): Set<string> {
|
||||
const ids = new Set(record?.tabId === undefined ? [] : [record.tabId])
|
||||
for (let colon = key.indexOf(':'); colon !== -1; colon = key.indexOf(':', colon + 1)) {
|
||||
ids.add(key.slice(0, colon))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
export function createSleepingAgentRecordIndex() {
|
||||
let source: Records | null = null
|
||||
const orderByKey = new Map<string, number>()
|
||||
let nextOrder = 0
|
||||
const entriesByWorktree = new Map<string, Map<string, SleepingAgentSessionRecord>>()
|
||||
const snapshotsByWorktree = new Map<string, readonly RecordEntry[]>()
|
||||
const keysByTabPrefix = new Map<string, Set<string>>()
|
||||
const recordsByProviderSession = new Map<string, Map<string, SleepingAgentSessionRecord>>()
|
||||
|
||||
function update(records: Records): void {
|
||||
if (records === source) {
|
||||
return
|
||||
}
|
||||
const previous = source
|
||||
const dirty = new Set<string>()
|
||||
const keys = previous ? terminalInputRecordChangedKeys(previous, records) : null
|
||||
// Bootstrap, hydration or an unknown replacement has no trusted partial change list.
|
||||
if (keys === null) {
|
||||
for (const id of entriesByWorktree.keys()) {
|
||||
dirty.add(id)
|
||||
}
|
||||
orderByKey.clear()
|
||||
nextOrder = 0
|
||||
entriesByWorktree.clear()
|
||||
snapshotsByWorktree.clear()
|
||||
keysByTabPrefix.clear()
|
||||
recordsByProviderSession.clear()
|
||||
}
|
||||
const changedKeys = keys ?? Object.keys(records)
|
||||
for (const key of changedKeys) {
|
||||
const before = keys ? previous?.[key] : undefined
|
||||
const after = records[key]
|
||||
const beforePresent = keys !== null && previous !== null && Object.hasOwn(previous, key)
|
||||
const afterPresent = Object.hasOwn(records, key)
|
||||
if (before === after && beforePresent === afterPresent) {
|
||||
continue
|
||||
}
|
||||
if (!afterPresent) {
|
||||
orderByKey.delete(key)
|
||||
} else if (!orderByKey.has(key)) {
|
||||
orderByKey.set(key, nextOrder++)
|
||||
}
|
||||
if (beforePresent) {
|
||||
for (const tabId of tabPrefixes(key, before)) {
|
||||
const owned = keysByTabPrefix.get(tabId)
|
||||
owned?.delete(key)
|
||||
if (owned?.size === 0) {
|
||||
keysByTabPrefix.delete(tabId)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (afterPresent) {
|
||||
for (const tabId of tabPrefixes(key, after)) {
|
||||
let owned = keysByTabPrefix.get(tabId)
|
||||
if (!owned) {
|
||||
keysByTabPrefix.set(tabId, (owned = new Set()))
|
||||
}
|
||||
owned.add(key)
|
||||
}
|
||||
}
|
||||
if (before) {
|
||||
const sessionKey = providerSessionKey(before)
|
||||
if (sessionKey && (!after || providerSessionKey(after) !== sessionKey)) {
|
||||
const bucket = recordsByProviderSession.get(sessionKey)
|
||||
bucket?.delete(key)
|
||||
if (bucket?.size === 0) {
|
||||
recordsByProviderSession.delete(sessionKey)
|
||||
}
|
||||
}
|
||||
if (after?.worktreeId !== before.worktreeId) {
|
||||
entriesByWorktree.get(before.worktreeId)?.delete(key)
|
||||
}
|
||||
dirty.add(before.worktreeId)
|
||||
}
|
||||
if (after) {
|
||||
const sessionKey = providerSessionKey(after)
|
||||
if (sessionKey) {
|
||||
let bucket = recordsByProviderSession.get(sessionKey)
|
||||
if (!bucket) {
|
||||
recordsByProviderSession.set(sessionKey, (bucket = new Map()))
|
||||
}
|
||||
bucket.set(key, after)
|
||||
}
|
||||
let bucket = entriesByWorktree.get(after.worktreeId)
|
||||
if (!bucket) {
|
||||
entriesByWorktree.set(after.worktreeId, (bucket = new Map()))
|
||||
}
|
||||
bucket.set(key, after)
|
||||
dirty.add(after.worktreeId)
|
||||
}
|
||||
}
|
||||
for (const worktreeId of dirty) {
|
||||
const bucket = entriesByWorktree.get(worktreeId)
|
||||
if (bucket?.size) {
|
||||
snapshotsByWorktree.set(
|
||||
worktreeId,
|
||||
[...bucket].sort(([a], [b]) => {
|
||||
const indexA = Number(a)
|
||||
const indexB = Number(b)
|
||||
const numericA =
|
||||
Number.isInteger(indexA) && indexA >= 0 && indexA < 4294967295 && String(indexA) === a
|
||||
const numericB =
|
||||
Number.isInteger(indexB) && indexB >= 0 && indexB < 4294967295 && String(indexB) === b
|
||||
if (numericA || numericB) {
|
||||
return numericA && numericB ? indexA - indexB : numericA ? -1 : 1
|
||||
}
|
||||
return orderByKey.get(a)! - orderByKey.get(b)!
|
||||
})
|
||||
)
|
||||
} else {
|
||||
entriesByWorktree.delete(worktreeId)
|
||||
snapshotsByWorktree.delete(worktreeId)
|
||||
}
|
||||
}
|
||||
source = records
|
||||
}
|
||||
|
||||
return {
|
||||
update,
|
||||
acceptTransition(previous: Records | null, next: Records) {
|
||||
const worktreeIds = new Set<string>()
|
||||
const tabIds = new Set<string>()
|
||||
const keys = previous ? terminalInputRecordChangedKeys(previous, next) : null
|
||||
const changedKeys = keys ?? new Set([...Object.keys(previous ?? {}), ...Object.keys(next)])
|
||||
for (const key of changedKeys) {
|
||||
const before = previous?.[key]
|
||||
const after = next[key]
|
||||
const beforePresent = previous !== null && Object.hasOwn(previous, key)
|
||||
const afterPresent = Object.hasOwn(next, key)
|
||||
if (before === after && beforePresent === afterPresent) {
|
||||
continue
|
||||
}
|
||||
if (beforePresent || afterPresent) {
|
||||
for (const tabId of tabPrefixes(key, undefined)) {
|
||||
tabIds.add(tabId)
|
||||
}
|
||||
}
|
||||
for (const record of [before, after]) {
|
||||
if (!record) {
|
||||
continue
|
||||
}
|
||||
worktreeIds.add(record.worktreeId)
|
||||
for (const tabId of tabPrefixes(key, record)) {
|
||||
tabIds.add(tabId)
|
||||
}
|
||||
}
|
||||
}
|
||||
update(next)
|
||||
return { worktreeIds, tabIds }
|
||||
},
|
||||
entries(records: Records, worktreeId: string): readonly RecordEntry[] {
|
||||
update(records)
|
||||
return snapshotsByWorktree.get(worktreeId) ?? EMPTY_ENTRIES
|
||||
},
|
||||
hasTabPrefix(records: Records, tabId: string): boolean {
|
||||
update(records)
|
||||
return keysByTabPrefix.has(tabId)
|
||||
},
|
||||
providerSessionCandidates(
|
||||
records: Records,
|
||||
record: SleepingAgentSessionRecord
|
||||
): Iterable<SleepingAgentSessionRecord> {
|
||||
update(records)
|
||||
const key = providerSessionKey(record)
|
||||
return (key ? recordsByProviderSession.get(key)?.values() : undefined) ?? []
|
||||
},
|
||||
worktreeIds(records: Records): Iterable<string> {
|
||||
update(records)
|
||||
return entriesByWorktree.keys()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const sleepingAgentRecordIndex = createSleepingAgentRecordIndex()
|
||||
@@ -0,0 +1,38 @@
|
||||
type RecordTransition = { previous: WeakRef<object>; keys: ReadonlySet<string> }
|
||||
const transitions = new WeakMap<object, RecordTransition>()
|
||||
|
||||
/** Exact writer provenance is transient; weak previous identities cannot retain a history of store snapshots. */
|
||||
export function terminalInputRecordTransition<T extends object>(
|
||||
previous: T,
|
||||
next: T,
|
||||
keys: Iterable<string>
|
||||
): T {
|
||||
if (next !== previous) {
|
||||
transitions.set(next, { previous: new WeakRef(previous), keys: new Set(keys) })
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
export function terminalInputRecordChangedKeys(
|
||||
previous: object,
|
||||
next: object
|
||||
): ReadonlySet<string> | null {
|
||||
if (previous === next) {
|
||||
return new Set()
|
||||
}
|
||||
const keys = new Set<string>()
|
||||
const visited = new Set<object>()
|
||||
let cursor: object | undefined = next
|
||||
while (cursor !== previous && cursor !== undefined && !visited.has(cursor)) {
|
||||
visited.add(cursor)
|
||||
const transition = transitions.get(cursor)
|
||||
if (!transition) {
|
||||
return null
|
||||
}
|
||||
for (const key of transition.keys) {
|
||||
keys.add(key)
|
||||
}
|
||||
cursor = transition.previous.deref()
|
||||
}
|
||||
return cursor === previous ? keys : null
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch'
|
||||
import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
|
||||
import { terminalLayoutEqual } from '../../../../shared/workspace-layout/terminal-layout-equality'
|
||||
@@ -9,7 +10,7 @@ import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './termin
|
||||
import {
|
||||
resolvePrimaryLayoutPtyId,
|
||||
uniquePtyIds,
|
||||
withTerminalTabPtyId
|
||||
withTerminalTabPtyIds
|
||||
} from './terminal-pty-identities'
|
||||
import { transferNormalizedTerminalLayoutPtyOwnership } from './workspace-terminal-hydration-patch'
|
||||
import { recordChatPaneInLayoutOwner } from './terminal-chat-pane-layout-owner'
|
||||
@@ -49,13 +50,17 @@ export function createTerminalLayoutActions(
|
||||
return s
|
||||
}
|
||||
return {
|
||||
terminalLayoutsByTabId: {
|
||||
...s.terminalLayoutsByTabId,
|
||||
[tabId]: {
|
||||
...layout,
|
||||
ptyIdsByLeafId: { ...layout.ptyIdsByLeafId, [leafId]: ptyId }
|
||||
}
|
||||
}
|
||||
terminalLayoutsByTabId: terminalInputRecordTransition(
|
||||
s.terminalLayoutsByTabId,
|
||||
{
|
||||
...s.terminalLayoutsByTabId,
|
||||
[tabId]: {
|
||||
...layout,
|
||||
ptyIdsByLeafId: { ...layout.ptyIdsByLeafId, [leafId]: ptyId }
|
||||
}
|
||||
},
|
||||
[tabId]
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -84,7 +89,11 @@ export function createTerminalLayoutActions(
|
||||
}
|
||||
const next = { ...s.terminalLayoutsByTabId }
|
||||
delete next[tabId]
|
||||
return { terminalLayoutsByTabId: next }
|
||||
return {
|
||||
terminalLayoutsByTabId: terminalInputRecordTransition(s.terminalLayoutsByTabId, next, [
|
||||
tabId
|
||||
])
|
||||
}
|
||||
}
|
||||
const normalized = normalizeTerminalLayoutPtyOwnership(layout)
|
||||
// Resolved before the bailout: normalization can transfer pane ownership even when the stored snapshot is untouched.
|
||||
@@ -100,7 +109,11 @@ export function createTerminalLayoutActions(
|
||||
return s
|
||||
}
|
||||
return {
|
||||
terminalLayoutsByTabId: { ...s.terminalLayoutsByTabId, [tabId]: normalized.snapshot }
|
||||
terminalLayoutsByTabId: terminalInputRecordTransition(
|
||||
s.terminalLayoutsByTabId,
|
||||
{ ...s.terminalLayoutsByTabId, [tabId]: normalized.snapshot },
|
||||
[tabId]
|
||||
)
|
||||
}
|
||||
})
|
||||
transferNormalizedTerminalLayoutPtyOwnership(get(), tabId, ownershipTransfers)
|
||||
@@ -147,17 +160,20 @@ export function createTerminalLayoutActions(
|
||||
nextLastKnownRelayPtyIdByTabId[targetTabId] = detachedPtyId
|
||||
}
|
||||
// Why: pane-to-tab detach moves a live PTY without spawning or exiting, so transfer identity without activity bumps.
|
||||
const sourceTabsByWorktree = withTerminalTabPtyId(
|
||||
s.tabsByWorktree,
|
||||
sourceTabId,
|
||||
sourcePrimaryPtyId
|
||||
)
|
||||
const nextTabsByWorktree = detachedPtyId
|
||||
? withTerminalTabPtyId(sourceTabsByWorktree, targetTabId, detachedPtyId)
|
||||
: sourceTabsByWorktree
|
||||
const nextTabsByWorktree = withTerminalTabPtyIds(s.tabsByWorktree, [
|
||||
{ tabId: sourceTabId, ptyId: sourcePrimaryPtyId },
|
||||
...(detachedPtyId ? [{ tabId: targetTabId, ptyId: detachedPtyId }] : [])
|
||||
])
|
||||
return {
|
||||
ptyIdsByTabId: nextPtyIdsByTabId,
|
||||
lastKnownRelayPtyIdByTabId: nextLastKnownRelayPtyIdByTabId,
|
||||
ptyIdsByTabId: terminalInputRecordTransition(s.ptyIdsByTabId, nextPtyIdsByTabId, [
|
||||
sourceTabId,
|
||||
targetTabId
|
||||
]),
|
||||
lastKnownRelayPtyIdByTabId: terminalInputRecordTransition(
|
||||
s.lastKnownRelayPtyIdByTabId,
|
||||
nextLastKnownRelayPtyIdByTabId,
|
||||
[sourceTabId, targetTabId]
|
||||
),
|
||||
...(nextTabsByWorktree !== s.tabsByWorktree ? { tabsByWorktree: nextTabsByWorktree } : {})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { replaceTabBuckets, replaceRecordEntries } from '@/store/keyed-record-transitions'
|
||||
import type { AppState } from '../types'
|
||||
|
||||
type TerminalTabReconnectState = Pick<
|
||||
@@ -200,25 +201,22 @@ export function buildOrphanTerminalCleanupPatch(
|
||||
orphanTerminalIds,
|
||||
keptTabs
|
||||
)
|
||||
const nextPtyIdsByTabId = { ...state.ptyIdsByTabId }
|
||||
const nextRuntimePaneTitlesByTabId = { ...state.runtimePaneTitlesByTabId }
|
||||
const nextTerminalLayoutsByTabId = { ...state.terminalLayoutsByTabId }
|
||||
const nextPendingStartupByTabId = { ...state.pendingStartupByTabId }
|
||||
for (const orphanTabId of orphanTerminalIds) {
|
||||
delete nextPtyIdsByTabId[orphanTabId]
|
||||
delete nextRuntimePaneTitlesByTabId[orphanTabId]
|
||||
delete nextTerminalLayoutsByTabId[orphanTabId]
|
||||
delete nextPendingStartupByTabId[orphanTabId]
|
||||
}
|
||||
const deletions = [...orphanTerminalIds].map((id) => [id, null] as const)
|
||||
return {
|
||||
...companions,
|
||||
tabsByWorktree: {
|
||||
...state.tabsByWorktree,
|
||||
[worktreeId]: keptTabs
|
||||
},
|
||||
ptyIdsByTabId: nextPtyIdsByTabId,
|
||||
runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId,
|
||||
terminalLayoutsByTabId: nextTerminalLayoutsByTabId,
|
||||
pendingStartupByTabId: nextPendingStartupByTabId
|
||||
tabsByWorktree: replaceTabBuckets(state.tabsByWorktree, [[worktreeId, keptTabs]]),
|
||||
ptyIdsByTabId: replaceRecordEntries<string[]>(state.ptyIdsByTabId, deletions),
|
||||
runtimePaneTitlesByTabId: replaceRecordEntries<Record<number, string>>(
|
||||
state.runtimePaneTitlesByTabId,
|
||||
deletions
|
||||
),
|
||||
terminalLayoutsByTabId: replaceRecordEntries<AppState['terminalLayoutsByTabId'][string]>(
|
||||
state.terminalLayoutsByTabId,
|
||||
deletions
|
||||
),
|
||||
pendingStartupByTabId: replaceRecordEntries<AppState['pendingStartupByTabId'][string]>(
|
||||
state.pendingStartupByTabId,
|
||||
deletions
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
|
||||
import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
|
||||
import '@/components/terminal-pane/pty-transport/delivery/pty-dispatcher'
|
||||
@@ -118,7 +119,14 @@ export function createTerminalPaneHibernationActions(
|
||||
delete nextSleeping[key]
|
||||
}
|
||||
}
|
||||
return { suppressedPtyExitIds: next, sleepingAgentSessionsByPaneKey: nextSleeping }
|
||||
return {
|
||||
suppressedPtyExitIds: next,
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
nextSleeping,
|
||||
sleepingRecordKeys
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
set((s) => ({
|
||||
@@ -126,10 +134,14 @@ export function createTerminalPaneHibernationActions(
|
||||
...s.suppressedPtyExitIds,
|
||||
...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
},
|
||||
sleepingAgentSessionsByPaneKey: {
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
...sleepingAgentSessionRecords
|
||||
}
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
{
|
||||
...s.sleepingAgentSessionsByPaneKey,
|
||||
...sleepingAgentSessionRecords
|
||||
},
|
||||
sleepingRecordKeys
|
||||
)
|
||||
}))
|
||||
if (expectedRuntimePtyIds.length > 0) {
|
||||
if (!runtimeEnvironmentId) {
|
||||
@@ -240,19 +252,35 @@ export function createTerminalPaneHibernationActions(
|
||||
const nextLastTerminalInputAtByPaneKey = { ...s.lastTerminalInputAtByPaneKey }
|
||||
delete nextLastTerminalInputAtByPaneKey[opts.paneKey]
|
||||
return {
|
||||
tabsByWorktree: nextTabsByWorktree,
|
||||
ptyIdsByTabId: {
|
||||
...s.ptyIdsByTabId,
|
||||
[opts.tabId]: remainingPtyIds
|
||||
},
|
||||
lastKnownRelayPtyIdByTabId: nextLastKnownRelay,
|
||||
tabsByWorktree: terminalInputRecordTransition(s.tabsByWorktree, nextTabsByWorktree, [
|
||||
worktreeId
|
||||
]),
|
||||
ptyIdsByTabId: terminalInputRecordTransition(
|
||||
s.ptyIdsByTabId,
|
||||
{
|
||||
...s.ptyIdsByTabId,
|
||||
[opts.tabId]: remainingPtyIds
|
||||
},
|
||||
[opts.tabId]
|
||||
),
|
||||
lastKnownRelayPtyIdByTabId: terminalInputRecordTransition(
|
||||
s.lastKnownRelayPtyIdByTabId,
|
||||
nextLastKnownRelay,
|
||||
[opts.tabId]
|
||||
),
|
||||
suppressedPtyExitIds: {
|
||||
...s.suppressedPtyExitIds,
|
||||
...Object.fromEntries(exitGuardPtyIds.map((ptyId) => [ptyId, true] as const))
|
||||
},
|
||||
codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId,
|
||||
...(nextRuntimePaneTitlesByTabId !== s.runtimePaneTitlesByTabId
|
||||
? { runtimePaneTitlesByTabId: nextRuntimePaneTitlesByTabId }
|
||||
? {
|
||||
runtimePaneTitlesByTabId: terminalInputRecordTransition(
|
||||
s.runtimePaneTitlesByTabId,
|
||||
nextRuntimePaneTitlesByTabId,
|
||||
[opts.tabId]
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
...removePanesAttention(s, new Set([opts.paneKey])),
|
||||
lastTerminalInputAtByPaneKey: nextLastTerminalInputAtByPaneKey
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
import {
|
||||
capturedTerminalWorkspacesForPtyIds,
|
||||
capturedTerminalWorkspacesForEnvironmentIds,
|
||||
capturedPanesByTabId,
|
||||
parkedWatchersByTabId,
|
||||
retireParkedTerminalTab
|
||||
} from '@/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-registry'
|
||||
import type { AppState } from '../types'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import { terminalInputRecordChangedKeys } from './terminal-input-record-transition'
|
||||
import { sleepingAgentRecordIndex } from './sleeping-agent-record-index'
|
||||
import { getTerminalTabOwnerWorktreeId, getTerminalTabOwners } from './terminal-tab-owner-index'
|
||||
import {
|
||||
invalidateTerminalParkingInputs,
|
||||
retireTerminalParkingInputs
|
||||
} from '@/components/terminal-pane/parking/terminal-parking-input-events'
|
||||
import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
|
||||
|
||||
const TAB_RECORDS = [
|
||||
'terminalLayoutsByTabId',
|
||||
'ptyIdsByTabId',
|
||||
'lastKnownRelayPtyIdByTabId',
|
||||
'runtimePaneTitlesByTabId',
|
||||
'pendingStartupByTabId'
|
||||
] as const
|
||||
const tabIdsByPtyId = new Map<string, Set<string>>()
|
||||
const ptyIdsByTabId = new Map<string, Set<string>>()
|
||||
const tabIdsByEnvironmentId = new Map<string, Set<string>>()
|
||||
let accepted: AppState | null = null
|
||||
|
||||
function sameParkingTab(previous: TerminalTab | undefined, next: TerminalTab): boolean {
|
||||
return (
|
||||
previous !== undefined &&
|
||||
previous.id === next.id &&
|
||||
previous.worktreeId === next.worktreeId &&
|
||||
previous.ptyId === next.ptyId &&
|
||||
previous.pendingActivationSpawn === next.pendingActivationSpawn &&
|
||||
previous.generation === next.generation &&
|
||||
previous.startupCwd === next.startupCwd &&
|
||||
previous.launchAgent === next.launchAgent
|
||||
)
|
||||
}
|
||||
|
||||
function sameTitleSlots(previous: object | undefined, next: object | undefined): boolean {
|
||||
const before = Object.keys(previous ?? {})
|
||||
const after = Object.keys(next ?? {})
|
||||
return before.length === after.length && before.every((key) => key in (next ?? {}))
|
||||
}
|
||||
|
||||
function changedKeys(previous: object, next: object): Iterable<string> {
|
||||
return (
|
||||
terminalInputRecordChangedKeys(previous, next) ??
|
||||
new Set([...Object.keys(previous), ...Object.keys(next)])
|
||||
)
|
||||
}
|
||||
|
||||
function replacePtyMembership(state: AppState, tabId: string): void {
|
||||
for (const ptyId of ptyIdsByTabId.get(tabId) ?? []) {
|
||||
const tabs = tabIdsByPtyId.get(ptyId)
|
||||
tabs?.delete(tabId)
|
||||
if (tabs?.size === 0) {
|
||||
tabIdsByPtyId.delete(ptyId)
|
||||
}
|
||||
const environmentId = parseRemoteRuntimePtyId(ptyId)?.environmentId
|
||||
if (environmentId) {
|
||||
const environmentTabs = tabIdsByEnvironmentId.get(environmentId)
|
||||
environmentTabs?.delete(tabId)
|
||||
if (environmentTabs?.size === 0) {
|
||||
tabIdsByEnvironmentId.delete(environmentId)
|
||||
}
|
||||
}
|
||||
}
|
||||
const worktreeId = getTerminalTabOwnerWorktreeId(state.tabsByWorktree, tabId)
|
||||
const tab = worktreeId
|
||||
? state.tabsByWorktree[worktreeId]?.find((candidate) => candidate.id === tabId)
|
||||
: undefined
|
||||
if (!tab) {
|
||||
ptyIdsByTabId.delete(tabId)
|
||||
return
|
||||
}
|
||||
const ptyIds = new Set([
|
||||
...(tab.ptyId ? [tab.ptyId] : []),
|
||||
...(state.ptyIdsByTabId[tabId] ?? []),
|
||||
...Object.values(state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId ?? {}),
|
||||
...(state.lastKnownRelayPtyIdByTabId[tabId] ? [state.lastKnownRelayPtyIdByTabId[tabId]] : [])
|
||||
])
|
||||
ptyIdsByTabId.set(tabId, ptyIds)
|
||||
for (const ptyId of ptyIds) {
|
||||
let tabs = tabIdsByPtyId.get(ptyId)
|
||||
if (!tabs) {
|
||||
tabIdsByPtyId.set(ptyId, (tabs = new Set()))
|
||||
}
|
||||
tabs.add(tabId)
|
||||
const environmentId = parseRemoteRuntimePtyId(ptyId)?.environmentId
|
||||
if (environmentId) {
|
||||
let environmentTabs = tabIdsByEnvironmentId.get(environmentId)
|
||||
if (!environmentTabs) {
|
||||
tabIdsByEnvironmentId.set(environmentId, (environmentTabs = new Set()))
|
||||
}
|
||||
environmentTabs.add(tabId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Install pure source ownership before Zustand dispatch; the caller publishes after the accepted write. */
|
||||
export function acceptTerminalParkingInputs(state: AppState): ReadonlySet<string> {
|
||||
if (accepted === state) {
|
||||
return new Set()
|
||||
}
|
||||
const previous = accepted
|
||||
const dirty = new Set<string>()
|
||||
const changedTabs = new Set<string>()
|
||||
const previousOwners = previous ? getTerminalTabOwners(previous.tabsByWorktree) : null
|
||||
const oldOwners = new Map<string, string>()
|
||||
if (!previous || previous.tabsByWorktree !== state.tabsByWorktree) {
|
||||
const worktreeIds = previous
|
||||
? changedKeys(previous.tabsByWorktree, state.tabsByWorktree)
|
||||
: Object.keys(state.tabsByWorktree)
|
||||
for (const id of worktreeIds) {
|
||||
if (previous?.tabsByWorktree[id] === state.tabsByWorktree[id]) {
|
||||
continue
|
||||
}
|
||||
const before = previous?.tabsByWorktree[id] ?? []
|
||||
const after = state.tabsByWorktree[id] ?? []
|
||||
if (
|
||||
before.length === after.length &&
|
||||
after.every((tab, index) => sameParkingTab(before[index], tab))
|
||||
) {
|
||||
continue
|
||||
}
|
||||
dirty.add(id)
|
||||
for (const tab of previous?.tabsByWorktree[id] ?? []) {
|
||||
changedTabs.add(tab.id)
|
||||
const owner = previousOwners?.get(tab.id)
|
||||
if (owner) {
|
||||
oldOwners.set(tab.id, owner)
|
||||
}
|
||||
}
|
||||
for (const tab of state.tabsByWorktree[id] ?? []) {
|
||||
changedTabs.add(tab.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
const owners = getTerminalTabOwners(state.tabsByWorktree)
|
||||
for (const field of [
|
||||
'layoutByWorktree',
|
||||
'groupsByWorktree',
|
||||
'activeGroupIdByWorktree'
|
||||
] as const) {
|
||||
const before = previous?.[field]
|
||||
const after = state[field]
|
||||
if (before === after) {
|
||||
continue
|
||||
}
|
||||
for (const id of before ? changedKeys(before, after) : Object.keys(after)) {
|
||||
if (before?.[id] !== after[id]) {
|
||||
dirty.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const field of TAB_RECORDS) {
|
||||
const before = previous?.[field]
|
||||
const after = state[field]
|
||||
if (before === after) {
|
||||
continue
|
||||
}
|
||||
for (const tabId of before ? changedKeys(before, after) : Object.keys(after)) {
|
||||
if (
|
||||
field === 'runtimePaneTitlesByTabId' &&
|
||||
sameTitleSlots(
|
||||
previous?.runtimePaneTitlesByTabId[tabId],
|
||||
state.runtimePaneTitlesByTabId[tabId]
|
||||
)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
if (before?.[tabId] !== after[tabId]) {
|
||||
changedTabs.add(tabId)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (previous?.sleepingAgentSessionsByPaneKey !== state.sleepingAgentSessionsByPaneKey) {
|
||||
const changed = sleepingAgentRecordIndex.acceptTransition(
|
||||
previous?.sleepingAgentSessionsByPaneKey ?? null,
|
||||
state.sleepingAgentSessionsByPaneKey
|
||||
)
|
||||
for (const id of changed.worktreeIds) {
|
||||
dirty.add(id)
|
||||
}
|
||||
for (const tabId of changed.tabIds) {
|
||||
changedTabs.add(tabId)
|
||||
}
|
||||
}
|
||||
for (const tabId of changedTabs) {
|
||||
const owner = owners.get(tabId)
|
||||
const oldOwner = oldOwners.get(tabId)
|
||||
if (owner) {
|
||||
dirty.add(owner)
|
||||
}
|
||||
if (oldOwner) {
|
||||
dirty.add(oldOwner)
|
||||
}
|
||||
replacePtyMembership(state, tabId)
|
||||
}
|
||||
if (previous?.runtimeStatusByEnvironmentId !== state.runtimeStatusByEnvironmentId) {
|
||||
const environmentIds = previous
|
||||
? (terminalInputRecordChangedKeys(
|
||||
previous.runtimeStatusByEnvironmentId,
|
||||
state.runtimeStatusByEnvironmentId
|
||||
) ??
|
||||
new Set([
|
||||
...previous.runtimeStatusByEnvironmentId.keys(),
|
||||
...state.runtimeStatusByEnvironmentId.keys()
|
||||
]))
|
||||
: state.runtimeStatusByEnvironmentId.keys()
|
||||
for (const environmentId of environmentIds) {
|
||||
if (
|
||||
previous?.runtimeStatusByEnvironmentId.get(environmentId) ===
|
||||
state.runtimeStatusByEnvironmentId.get(environmentId)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
for (const id of capturedTerminalWorkspacesForEnvironmentIds([environmentId])) {
|
||||
dirty.add(id)
|
||||
}
|
||||
for (const tabId of tabIdsByEnvironmentId.get(environmentId) ?? []) {
|
||||
const owner = owners.get(tabId)
|
||||
if (owner) {
|
||||
dirty.add(owner)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
previous &&
|
||||
previous.settings?.terminalSshViewParking !== state.settings?.terminalSshViewParking
|
||||
) {
|
||||
for (const worktreeId of Object.keys(state.tabsByWorktree)) {
|
||||
dirty.add(worktreeId)
|
||||
}
|
||||
}
|
||||
accepted = state
|
||||
return dirty
|
||||
}
|
||||
|
||||
export function publishAcceptedTerminalParkingInputs(worktreeIds: ReadonlySet<string>): void {
|
||||
for (const worktreeId of worktreeIds) {
|
||||
for (const tabId of new Set([
|
||||
...capturedPanesByTabId.workspaceTabIds(worktreeId),
|
||||
...parkedWatchersByTabId.workspaceTabIds(worktreeId)
|
||||
])) {
|
||||
if (
|
||||
accepted &&
|
||||
getTerminalTabOwnerWorktreeId(accepted.tabsByWorktree, tabId) !== worktreeId
|
||||
) {
|
||||
retireParkedTerminalTab(tabId)
|
||||
}
|
||||
}
|
||||
if (accepted && !(worktreeId in accepted.tabsByWorktree)) {
|
||||
retireTerminalParkingInputs(worktreeId)
|
||||
} else {
|
||||
invalidateTerminalParkingInputs(worktreeId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function invalidateTerminalParkingPtyInputs(ptyIds?: Iterable<string>): void {
|
||||
if (!accepted) {
|
||||
return
|
||||
}
|
||||
const dirty = new Set<string>()
|
||||
if (ptyIds === undefined) {
|
||||
for (const worktreeId of Object.keys(accepted.tabsByWorktree)) {
|
||||
dirty.add(worktreeId)
|
||||
}
|
||||
} else {
|
||||
const changedPtyIds = [...ptyIds]
|
||||
for (const id of capturedTerminalWorkspacesForPtyIds(changedPtyIds)) {
|
||||
dirty.add(id)
|
||||
}
|
||||
for (const ptyId of changedPtyIds) {
|
||||
for (const tabId of tabIdsByPtyId.get(ptyId) ?? []) {
|
||||
const worktreeId = getTerminalTabOwnerWorktreeId(accepted.tabsByWorktree, tabId)
|
||||
if (worktreeId) {
|
||||
dirty.add(worktreeId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
publishAcceptedTerminalParkingInputs(dirty)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { StoreApi } from 'zustand'
|
||||
import type { AppState } from '../types'
|
||||
import {
|
||||
acceptTerminalParkingInputs,
|
||||
publishAcceptedTerminalParkingInputs
|
||||
} from './terminal-parking-input-owner'
|
||||
|
||||
type ParkingInputStore = Pick<StoreApi<AppState>, 'getState' | 'subscribe'>
|
||||
|
||||
/** Read the current accepted state so reentrant notifications cannot restore an older owner. */
|
||||
export function installTerminalParkingInputs(store: ParkingInputStore): () => void {
|
||||
acceptTerminalParkingInputs(store.getState())
|
||||
return store.subscribe(() => {
|
||||
publishAcceptedTerminalParkingInputs(acceptTerminalParkingInputs(store.getState()))
|
||||
})
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { getFirstTerminalTabOwnerWorktreeId } from './terminal-tab-owner-index'
|
||||
import {
|
||||
isRemoteRuntimePtyId,
|
||||
parseRemoteRuntimePtyId,
|
||||
@@ -70,7 +72,9 @@ export function createTerminalPtyBindingActions(
|
||||
}
|
||||
}
|
||||
let nextTabsByWorktree = s.tabsByWorktree
|
||||
for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) {
|
||||
const ownerId = getFirstTerminalTabOwnerWorktreeId(s.tabsByWorktree, tabId)
|
||||
for (const wId of ownerId ? [ownerId] : []) {
|
||||
const tabs = s.tabsByWorktree[wId] ?? []
|
||||
const index = tabs.findIndex((t) => t.id === tabId)
|
||||
if (index === -1) {
|
||||
continue
|
||||
@@ -176,17 +180,30 @@ export function createTerminalPtyBindingActions(
|
||||
}
|
||||
return {
|
||||
...(nextTabsByWorktree !== s.tabsByWorktree
|
||||
? { tabsByWorktree: nextTabsByWorktree }
|
||||
? {
|
||||
tabsByWorktree: terminalInputRecordTransition(
|
||||
s.tabsByWorktree,
|
||||
nextTabsByWorktree,
|
||||
worktreeId ? [worktreeId] : []
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
...(nextPtyIds !== existingPtyIds || !(tabId in s.ptyIdsByTabId)
|
||||
? { ptyIdsByTabId: { ...s.ptyIdsByTabId, [tabId]: nextPtyIds } }
|
||||
? {
|
||||
ptyIdsByTabId: terminalInputRecordTransition(
|
||||
s.ptyIdsByTabId,
|
||||
{ ...s.ptyIdsByTabId, [tabId]: nextPtyIds },
|
||||
[tabId]
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
...(s.lastKnownRelayPtyIdByTabId[tabId] !== ptyId
|
||||
? {
|
||||
lastKnownRelayPtyIdByTabId: {
|
||||
...s.lastKnownRelayPtyIdByTabId,
|
||||
[tabId]: ptyId
|
||||
}
|
||||
lastKnownRelayPtyIdByTabId: terminalInputRecordTransition(
|
||||
s.lastKnownRelayPtyIdByTabId,
|
||||
{ ...s.lastKnownRelayPtyIdByTabId, [tabId]: ptyId },
|
||||
[tabId]
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
...(nextUnverifiedPtyLossTabIds !== s.unverifiedPtyLossTabIds
|
||||
@@ -200,7 +217,13 @@ export function createTerminalPtyBindingActions(
|
||||
codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId,
|
||||
migrationUnsupportedByPtyId: nextMigrationUnsupportedByPtyId,
|
||||
...(nextTerminalLayoutsByTabId !== s.terminalLayoutsByTabId
|
||||
? { terminalLayoutsByTabId: nextTerminalLayoutsByTabId }
|
||||
? {
|
||||
terminalLayoutsByTabId: terminalInputRecordTransition(
|
||||
s.terminalLayoutsByTabId,
|
||||
nextTerminalLayoutsByTabId,
|
||||
[tabId]
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
...(shouldBumpSortEpoch ? { sortEpoch: s.sortEpoch + 1 } : {})
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { getFirstTerminalTabOwnerWorktreeId } from './terminal-tab-owner-index'
|
||||
import type {
|
||||
TerminalLayoutSnapshot,
|
||||
TerminalTab
|
||||
@@ -50,22 +52,29 @@ export function resolvePrimaryLayoutPtyId(layout: TerminalLayoutSnapshot): strin
|
||||
return activePtyId ?? Object.values(ptyIdsByLeafId)[0] ?? null
|
||||
}
|
||||
|
||||
export function withTerminalTabPtyId(
|
||||
export function withTerminalTabPtyIds(
|
||||
tabsByWorktree: Record<string, TerminalTab[]>,
|
||||
tabId: string,
|
||||
ptyId: string | null
|
||||
changes: readonly { tabId: string; ptyId: string | null }[]
|
||||
): Record<string, TerminalTab[]> {
|
||||
for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) {
|
||||
const index = tabs.findIndex((tab) => tab.id === tabId)
|
||||
if (index === -1) {
|
||||
let next = tabsByWorktree
|
||||
const changedWorktreeIds = new Set<string>()
|
||||
for (const { tabId, ptyId } of changes) {
|
||||
const worktreeId = getFirstTerminalTabOwnerWorktreeId(tabsByWorktree, tabId)
|
||||
if (!worktreeId) {
|
||||
continue
|
||||
}
|
||||
if (tabs[index]?.ptyId === ptyId) {
|
||||
return tabsByWorktree
|
||||
const tabs = next[worktreeId] ?? []
|
||||
const index = tabs.findIndex((tab) => tab.id === tabId)
|
||||
if (index === -1 || tabs[index]?.ptyId === ptyId) {
|
||||
continue
|
||||
}
|
||||
if (next === tabsByWorktree) {
|
||||
next = { ...tabsByWorktree }
|
||||
}
|
||||
const nextTabs = [...tabs]
|
||||
nextTabs[index] = { ...nextTabs[index]!, ptyId }
|
||||
return { ...tabsByWorktree, [worktreeId]: nextTabs }
|
||||
next[worktreeId] = nextTabs
|
||||
changedWorktreeIds.add(worktreeId)
|
||||
}
|
||||
return tabsByWorktree
|
||||
return terminalInputRecordTransition(tabsByWorktree, next, changedWorktreeIds)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { getFirstTerminalTabOwnerWorktreeId } from './terminal-tab-owner-index'
|
||||
import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id'
|
||||
import { hasWorktreeSleepIntent } from '@/lib/worktree-sleep-intent'
|
||||
import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state'
|
||||
@@ -23,7 +25,9 @@ export function createTerminalPtyReleaseActions(
|
||||
const existingPtyIds = s.ptyIdsByTabId[tabId] ?? []
|
||||
const remainingPtyIds = ptyId ? existingPtyIds.filter((id) => id !== ptyId) : []
|
||||
let nextTabsByWorktree = s.tabsByWorktree
|
||||
for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) {
|
||||
const ownerId = getFirstTerminalTabOwnerWorktreeId(s.tabsByWorktree, tabId)
|
||||
for (const wId of ownerId ? [ownerId] : []) {
|
||||
const tabs = s.tabsByWorktree[wId] ?? []
|
||||
const index = tabs.findIndex((t) => t.id === tabId)
|
||||
if (index === -1) {
|
||||
continue
|
||||
@@ -90,10 +94,20 @@ export function createTerminalPtyReleaseActions(
|
||||
}
|
||||
return {
|
||||
...(nextTabsByWorktree !== s.tabsByWorktree
|
||||
? { tabsByWorktree: nextTabsByWorktree }
|
||||
? {
|
||||
tabsByWorktree: terminalInputRecordTransition(
|
||||
s.tabsByWorktree,
|
||||
nextTabsByWorktree,
|
||||
worktreeId ? [worktreeId] : []
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
ptyIdsByTabId: nextPtyIdsByTabId,
|
||||
lastKnownRelayPtyIdByTabId: nextLastKnownRelay,
|
||||
ptyIdsByTabId: terminalInputRecordTransition(s.ptyIdsByTabId, nextPtyIdsByTabId, [tabId]),
|
||||
lastKnownRelayPtyIdByTabId: terminalInputRecordTransition(
|
||||
s.lastKnownRelayPtyIdByTabId,
|
||||
nextLastKnownRelay,
|
||||
[tabId]
|
||||
),
|
||||
pendingPaneAccountRestarts: nextPendingPaneAccountRestarts,
|
||||
codexRestartNoticeByPtyId: nextCodexRestartNoticeByPtyId
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
|
||||
import { clearTransientTerminalState } from './terminal-transient-state'
|
||||
@@ -113,16 +114,34 @@ export function commitTerminalShutdownState({
|
||||
}
|
||||
|
||||
return {
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId: ptyIdsByTabId.read(),
|
||||
lastKnownRelayPtyIdByTabId: lastKnownRelayPtyIdByTabId.read(),
|
||||
runtimePaneTitlesByTabId: runtimePaneTitlesByTabId.read(),
|
||||
tabsByWorktree: terminalInputRecordTransition(state.tabsByWorktree, tabsByWorktree, [
|
||||
worktreeId
|
||||
]),
|
||||
ptyIdsByTabId: terminalInputRecordTransition(
|
||||
state.ptyIdsByTabId,
|
||||
ptyIdsByTabId.read(),
|
||||
tabs.map((tab) => tab.id)
|
||||
),
|
||||
lastKnownRelayPtyIdByTabId: terminalInputRecordTransition(
|
||||
state.lastKnownRelayPtyIdByTabId,
|
||||
lastKnownRelayPtyIdByTabId.read(),
|
||||
tabs.map((tab) => tab.id)
|
||||
),
|
||||
runtimePaneTitlesByTabId: terminalInputRecordTransition(
|
||||
state.runtimePaneTitlesByTabId,
|
||||
runtimePaneTitlesByTabId.read(),
|
||||
tabs.map((tab) => tab.id)
|
||||
),
|
||||
suppressedPtyExitIds: suppressedPtyExitIds.read(),
|
||||
pendingPtyShutdownIds: pendingPtyShutdownIds.read(),
|
||||
pendingPaneAccountRestarts: pendingPaneAccountRestarts.read(),
|
||||
codexRestartNoticeByPtyId: codexRestartNoticeByPtyId.read(),
|
||||
pendingIssueCommandSplitByTabId: pendingIssueCommandSplitByTabId.read(),
|
||||
terminalLayoutsByTabId: terminalLayoutsByTabId.read(),
|
||||
terminalLayoutsByTabId: terminalInputRecordTransition(
|
||||
state.terminalLayoutsByTabId,
|
||||
terminalLayoutsByTabId.read(),
|
||||
tabs.map((tab) => tab.id)
|
||||
),
|
||||
...removeTabsAttention(
|
||||
state,
|
||||
tabs.map((tab) => tab.id)
|
||||
@@ -144,10 +163,11 @@ export function commitTerminalShutdownState({
|
||||
).records
|
||||
: state.sleepingAgentSessionsByPaneKey
|
||||
return {
|
||||
sleepingAgentSessionsByPaneKey: {
|
||||
...base,
|
||||
...sleepingAgentSessionRecords
|
||||
}
|
||||
sleepingAgentSessionsByPaneKey: terminalInputRecordTransition(
|
||||
base,
|
||||
{ ...base, ...sleepingAgentSessionRecords },
|
||||
Object.keys(sleepingAgentSessionRecords)
|
||||
)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createNonSecureContextUuid as createBrowserUuid } from '../../../../shared/non-secure-context-uuid'
|
||||
import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state'
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
|
||||
type TabStartupCommand = TerminalSlice['pendingStartupByTabId'][string]
|
||||
|
||||
@@ -32,10 +33,14 @@ export function createTerminalStartupQueueActions(
|
||||
queueTabStartupCommand: (tabId, startup) => {
|
||||
const normalized = normalizeTabStartupCommand(startup)
|
||||
set((s) => ({
|
||||
pendingStartupByTabId: {
|
||||
...s.pendingStartupByTabId,
|
||||
[tabId]: normalized
|
||||
}
|
||||
pendingStartupByTabId: terminalInputRecordTransition(
|
||||
s.pendingStartupByTabId,
|
||||
{
|
||||
...s.pendingStartupByTabId,
|
||||
[tabId]: normalized
|
||||
},
|
||||
[tabId]
|
||||
)
|
||||
}))
|
||||
},
|
||||
queueTabInitialCwd: (tabId, cwd) => {
|
||||
@@ -71,7 +76,11 @@ export function createTerminalStartupQueueActions(
|
||||
}
|
||||
const next = { ...s.pendingStartupByTabId }
|
||||
delete next[tabId]
|
||||
return { pendingStartupByTabId: next }
|
||||
return {
|
||||
pendingStartupByTabId: terminalInputRecordTransition(s.pendingStartupByTabId, next, [
|
||||
tabId
|
||||
])
|
||||
}
|
||||
})
|
||||
return pending
|
||||
},
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { getTerminalTabOwnerWorktreeIds } from './terminal-tab-owner-index'
|
||||
import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-tab-types'
|
||||
import type { TerminalSlice, TerminalStoreSet } from './terminal-state'
|
||||
|
||||
@@ -7,8 +9,12 @@ export function createTerminalTabAgentLaunchPaneActions(
|
||||
return {
|
||||
setTabAgentLaunchPane: (tabId, launchPane, options) => {
|
||||
set((s) => {
|
||||
const owners = [...getTerminalTabOwnerWorktreeIds(s.tabsByWorktree, tabId)]
|
||||
if (owners.length === 0) {
|
||||
return s
|
||||
}
|
||||
const next = { ...s.tabsByWorktree }
|
||||
for (const wId of Object.keys(next)) {
|
||||
for (const wId of owners) {
|
||||
if (!next[wId].some((t) => t.id === tabId)) {
|
||||
continue
|
||||
}
|
||||
@@ -25,7 +31,7 @@ export function createTerminalTabAgentLaunchPaneActions(
|
||||
return launchPane ? { ...remounted, agentLaunchPane: launchPane } : remounted
|
||||
})
|
||||
}
|
||||
return { tabsByWorktree: next }
|
||||
return { tabsByWorktree: terminalInputRecordTransition(s.tabsByWorktree, next, owners) }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { getTerminalTabOwnerWorktreeIds } from './terminal-tab-owner-index'
|
||||
import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph/graph-sync-scheduler'
|
||||
import { resolveTerminalWorktreeRoute } from '@/lib/terminal-worktree-route'
|
||||
import type { TerminalSlice, TerminalStoreGet, TerminalStoreSet } from './terminal-state'
|
||||
@@ -16,12 +18,16 @@ export function createTerminalTabAppearanceActions(
|
||||
({ renameHostTerminalTab }) => renameHostTerminalTab(state, tabId, title)
|
||||
)
|
||||
set((s) => {
|
||||
const owners = [...getTerminalTabOwnerWorktreeIds(s.tabsByWorktree, tabId)]
|
||||
if (owners.length === 0) {
|
||||
return s
|
||||
}
|
||||
const next = { ...s.tabsByWorktree }
|
||||
for (const wId of Object.keys(next)) {
|
||||
for (const wId of owners) {
|
||||
next[wId] = next[wId].map((t) => (t.id === tabId ? { ...t, customTitle: title } : t))
|
||||
}
|
||||
scheduleRuntimeGraphSync()
|
||||
return { tabsByWorktree: next }
|
||||
return { tabsByWorktree: terminalInputRecordTransition(s.tabsByWorktree, next, owners) }
|
||||
})
|
||||
const item = findRenamableUnifiedTab(get().unifiedTabsByWorktree, tabId)
|
||||
if (item?.contentType === 'agent-session') {
|
||||
@@ -44,11 +50,15 @@ export function createTerminalTabAppearanceActions(
|
||||
},
|
||||
setTabColor: (tabId, color, opts) => {
|
||||
set((s) => {
|
||||
const owners = [...getTerminalTabOwnerWorktreeIds(s.tabsByWorktree, tabId)]
|
||||
if (owners.length === 0) {
|
||||
return s
|
||||
}
|
||||
const next = { ...s.tabsByWorktree }
|
||||
for (const wId of Object.keys(next)) {
|
||||
for (const wId of owners) {
|
||||
next[wId] = next[wId].map((t) => (t.id === tabId ? { ...t, color } : t))
|
||||
}
|
||||
return { tabsByWorktree: next }
|
||||
return { tabsByWorktree: terminalInputRecordTransition(s.tabsByWorktree, next, owners) }
|
||||
})
|
||||
const item = findRenamableUnifiedTab(get().unifiedTabsByWorktree, tabId)
|
||||
if (item) {
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
terminalInputRecordChangedKeys,
|
||||
terminalInputRecordTransition
|
||||
} from './terminal-input-record-transition'
|
||||
|
||||
type TerminalTabOwnerBuckets = Readonly<Record<string, readonly { id: string }[]>>
|
||||
|
||||
type IndexedBucket = {
|
||||
@@ -8,6 +13,8 @@ type IndexedBucket = {
|
||||
export type TerminalTabOwnerIndex = {
|
||||
getOwners(tabsByWorktree: TerminalTabOwnerBuckets): ReadonlyMap<string, string>
|
||||
getOwner(tabsByWorktree: TerminalTabOwnerBuckets, tabId: string): string | null
|
||||
getFirstOwner(tabsByWorktree: TerminalTabOwnerBuckets, tabId: string): string | null
|
||||
getOwnerIds(tabsByWorktree: TerminalTabOwnerBuckets, tabId: string): Iterable<string>
|
||||
adoptMetadataOnlyBucketReplacements(
|
||||
previousTabsByWorktree: TerminalTabOwnerBuckets,
|
||||
nextTabsByWorktree: TerminalTabOwnerBuckets,
|
||||
@@ -18,6 +25,8 @@ export type TerminalTabOwnerIndex = {
|
||||
export function createTerminalTabOwnerIndex(): TerminalTabOwnerIndex {
|
||||
let source: TerminalTabOwnerBuckets | null = null
|
||||
let orderedKeys: string[] = []
|
||||
const bucketOrder = new Map<string, number>()
|
||||
let nextBucketOrder = 0
|
||||
const bucketByWorktreeId = new Map<string, IndexedBucket>()
|
||||
const worktreeIdsByTabId = new Map<string, Set<string>>()
|
||||
const ownerByTabId = new Map<string, string>()
|
||||
@@ -51,6 +60,62 @@ export function createTerminalTabOwnerIndex(): TerminalTabOwnerIndex {
|
||||
return ownerByTabId
|
||||
}
|
||||
|
||||
const knownKeys = source ? terminalInputRecordChangedKeys(source, tabsByWorktree) : null
|
||||
if (knownKeys && source) {
|
||||
const affectedTabIds = new Set<string>()
|
||||
for (const worktreeId of knownKeys) {
|
||||
const indexed = bucketByWorktreeId.get(worktreeId)
|
||||
const tabs = tabsByWorktree[worktreeId]
|
||||
if (indexed?.source === tabs) {
|
||||
continue
|
||||
}
|
||||
if (indexed) {
|
||||
for (const tabId of indexed.tabIds) {
|
||||
affectedTabIds.add(tabId)
|
||||
}
|
||||
removeBucketMembership(worktreeId, indexed.tabIds)
|
||||
}
|
||||
if (!tabs) {
|
||||
bucketByWorktreeId.delete(worktreeId)
|
||||
bucketOrder.delete(worktreeId)
|
||||
continue
|
||||
}
|
||||
if (!indexed) {
|
||||
bucketOrder.set(worktreeId, nextBucketOrder++)
|
||||
}
|
||||
const tabIds = new Set(tabs.map((tab) => tab.id))
|
||||
bucketByWorktreeId.set(worktreeId, { source: tabs, tabIds })
|
||||
addBucketMembership(worktreeId, tabIds)
|
||||
for (const tabId of tabIds) {
|
||||
affectedTabIds.add(tabId)
|
||||
}
|
||||
}
|
||||
for (const tabId of affectedTabIds) {
|
||||
const ids = worktreeIdsByTabId.get(tabId)
|
||||
if (!ids?.size) {
|
||||
ownerByTabId.delete(tabId)
|
||||
} else if (ids.size === 1) {
|
||||
ownerByTabId.set(tabId, ids.values().next().value!)
|
||||
} else {
|
||||
let owner: string | undefined
|
||||
let rank = -1
|
||||
for (const id of ids) {
|
||||
const order = bucketOrder.get(id) ?? -1
|
||||
if (order > rank) {
|
||||
owner = id
|
||||
rank = order
|
||||
}
|
||||
}
|
||||
if (owner) {
|
||||
ownerByTabId.set(tabId, owner)
|
||||
}
|
||||
}
|
||||
}
|
||||
source = tabsByWorktree
|
||||
return ownerByTabId
|
||||
}
|
||||
|
||||
// Unknown snapshots can change key order and duplicate ownership; rebuild that order once.
|
||||
const nextOrderedKeys = Object.keys(tabsByWorktree)
|
||||
const orderChanged =
|
||||
orderedKeys.length !== nextOrderedKeys.length ||
|
||||
@@ -121,6 +186,11 @@ export function createTerminalTabOwnerIndex(): TerminalTabOwnerIndex {
|
||||
|
||||
source = tabsByWorktree
|
||||
orderedKeys = nextOrderedKeys
|
||||
bucketOrder.clear()
|
||||
for (const [id, order] of orderByWorktreeId) {
|
||||
bucketOrder.set(id, order)
|
||||
}
|
||||
nextBucketOrder = nextOrderedKeys.length
|
||||
return ownerByTabId
|
||||
}
|
||||
|
||||
@@ -150,12 +220,43 @@ export function createTerminalTabOwnerIndex(): TerminalTabOwnerIndex {
|
||||
return {
|
||||
getOwners: update,
|
||||
getOwner: (tabsByWorktree, tabId) => update(tabsByWorktree).get(tabId) ?? null,
|
||||
getOwnerIds: (tabsByWorktree, tabId) => {
|
||||
update(tabsByWorktree)
|
||||
return worktreeIdsByTabId.get(tabId) ?? []
|
||||
},
|
||||
getFirstOwner: (tabsByWorktree, tabId) => {
|
||||
update(tabsByWorktree)
|
||||
let owner: string | null = null
|
||||
let rank = Number.POSITIVE_INFINITY
|
||||
for (const id of worktreeIdsByTabId.get(tabId) ?? []) {
|
||||
const order = bucketOrder.get(id) ?? Number.POSITIVE_INFINITY
|
||||
if (order < rank) {
|
||||
owner = id
|
||||
rank = order
|
||||
}
|
||||
}
|
||||
return owner
|
||||
},
|
||||
adoptMetadataOnlyBucketReplacements
|
||||
}
|
||||
}
|
||||
|
||||
const sharedTerminalTabOwnerIndex = createTerminalTabOwnerIndex()
|
||||
|
||||
export function getTerminalTabOwnerWorktreeIds(
|
||||
tabsByWorktree: TerminalTabOwnerBuckets,
|
||||
tabId: string
|
||||
): Iterable<string> {
|
||||
return sharedTerminalTabOwnerIndex.getOwnerIds(tabsByWorktree, tabId)
|
||||
}
|
||||
|
||||
export function getFirstTerminalTabOwnerWorktreeId(
|
||||
tabsByWorktree: TerminalTabOwnerBuckets,
|
||||
tabId: string
|
||||
): string | null {
|
||||
return sharedTerminalTabOwnerIndex.getFirstOwner(tabsByWorktree, tabId)
|
||||
}
|
||||
|
||||
export function getTerminalTabOwners(
|
||||
tabsByWorktree: TerminalTabOwnerBuckets
|
||||
): ReadonlyMap<string, string> {
|
||||
@@ -174,9 +275,5 @@ export function adoptTerminalTabOwnerMetadataOnlyBuckets(
|
||||
nextTabsByWorktree: TerminalTabOwnerBuckets,
|
||||
replacedWorktreeIds: Iterable<string>
|
||||
): void {
|
||||
sharedTerminalTabOwnerIndex.adoptMetadataOnlyBucketReplacements(
|
||||
previousTabsByWorktree,
|
||||
nextTabsByWorktree,
|
||||
replacedWorktreeIds
|
||||
)
|
||||
terminalInputRecordTransition(previousTabsByWorktree, nextTabsByWorktree, replacedWorktreeIds)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
import { isDecorativeAgentTitleFrameChange } from '../../../../shared/agent-status/title/agent-decorative-title-signature'
|
||||
import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph/graph-sync-scheduler'
|
||||
import { classifyTitleActivity } from '@/lib/pane-agent-evidence'
|
||||
@@ -72,10 +73,11 @@ export function createTerminalTabPresentationActions(
|
||||
scheduleRuntimeGraphSync()
|
||||
return {
|
||||
tabsByWorktree: nextTabsByWorktree,
|
||||
unifiedTabsByWorktree: {
|
||||
...s.unifiedTabsByWorktree,
|
||||
[ownerWorktreeId]: nextUnifiedTabs
|
||||
}
|
||||
unifiedTabsByWorktree: terminalInputRecordTransition(
|
||||
s.unifiedTabsByWorktree,
|
||||
{ ...s.unifiedTabsByWorktree, [ownerWorktreeId]: nextUnifiedTabs },
|
||||
[ownerWorktreeId]
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
@@ -136,7 +138,13 @@ export function createTerminalTabPresentationActions(
|
||||
const nextTabs = [...tabs]
|
||||
nextTabs[tabIndex] = tabWithoutLaunchAgent
|
||||
scheduleRuntimeGraphSync()
|
||||
return { tabsByWorktree: { ...s.tabsByWorktree, [ownerWorktreeId]: nextTabs } }
|
||||
return {
|
||||
tabsByWorktree: terminalInputRecordTransition(
|
||||
s.tabsByWorktree,
|
||||
{ ...s.tabsByWorktree, [ownerWorktreeId]: nextTabs },
|
||||
[ownerWorktreeId]
|
||||
)
|
||||
}
|
||||
})
|
||||
},
|
||||
setRuntimePaneTitle: (tabId, paneId, title) => {
|
||||
@@ -159,10 +167,11 @@ export function createTerminalTabPresentationActions(
|
||||
const isActive = ownerWorktreeId !== null && ownerWorktreeId === s.activeWorktreeId
|
||||
const shouldBump = classificationChanged && ownerWorktreeId !== null && !isActive
|
||||
return {
|
||||
runtimePaneTitlesByTabId: {
|
||||
...s.runtimePaneTitlesByTabId,
|
||||
[tabId]: { ...currentByPane, [paneId]: title }
|
||||
},
|
||||
runtimePaneTitlesByTabId: terminalInputRecordTransition(
|
||||
s.runtimePaneTitlesByTabId,
|
||||
{ ...s.runtimePaneTitlesByTabId, [tabId]: { ...currentByPane, [paneId]: title } },
|
||||
[tabId]
|
||||
),
|
||||
...(shouldBump ? { sortEpoch: s.sortEpoch + 1 } : {})
|
||||
}
|
||||
})
|
||||
@@ -191,7 +200,11 @@ export function createTerminalTabPresentationActions(
|
||||
const isActive = ownerWorktreeId !== null && ownerWorktreeId === s.activeWorktreeId
|
||||
const shouldBump = hadClassification && ownerWorktreeId !== null && !isActive
|
||||
return {
|
||||
runtimePaneTitlesByTabId: next,
|
||||
runtimePaneTitlesByTabId: terminalInputRecordTransition(
|
||||
s.runtimePaneTitlesByTabId,
|
||||
next,
|
||||
[tabId]
|
||||
),
|
||||
...(shouldBump ? { sortEpoch: s.sortEpoch + 1 } : {})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { isSupportedWindowsShellOverride } from '../../../../shared/windows-term
|
||||
import type { AppState } from '../types'
|
||||
import type { TerminalPaneStart } from './terminal-state'
|
||||
import { getRemoteConnectionIdForWorktree, worktreeUsesWslPath } from './terminal-workspace-routing'
|
||||
import { terminalInputRecordTransition } from './terminal-input-record-transition'
|
||||
|
||||
type TabStartup = AppState['pendingStartupByTabId'][string]
|
||||
|
||||
@@ -94,7 +95,13 @@ export function startWindowTabInMain(
|
||||
if (startup) {
|
||||
// Main runs it; a later mount of the pane must not run it again.
|
||||
const { [tab.id]: _started, ...pendingStartupByTabId } = state.pendingStartupByTabId
|
||||
store.setState({ pendingStartupByTabId })
|
||||
store.setState({
|
||||
pendingStartupByTabId: terminalInputRecordTransition(
|
||||
state.pendingStartupByTabId,
|
||||
pendingStartupByTabId,
|
||||
[tab.id]
|
||||
)
|
||||
})
|
||||
}
|
||||
void callRuntimeRpc<{ terminal: { ptyId: string } }>({ kind: 'local' }, 'terminal.create', {
|
||||
worktree: `id:${tab.worktreeId}`,
|
||||
@@ -123,8 +130,13 @@ export function startWindowTabInMain(
|
||||
if (message === 'host_not_owned') {
|
||||
// Restore startup only if main started nothing and the tab remains open; closed tabs cannot consume it.
|
||||
if (startup && store.getState().terminalLayoutsByTabId[tab.id]) {
|
||||
const pending = store.getState().pendingStartupByTabId
|
||||
store.setState({
|
||||
pendingStartupByTabId: { ...store.getState().pendingStartupByTabId, [tab.id]: startup }
|
||||
pendingStartupByTabId: terminalInputRecordTransition(
|
||||
pending,
|
||||
{ ...pending, [tab.id]: startup },
|
||||
[tab.id]
|
||||
)
|
||||
})
|
||||
}
|
||||
clearWindowTabMark(store, paneKey, mark)
|
||||
|
||||
Reference in New Issue
Block a user