Prevent restored inactive terminal tabs from being flagged as orphans (#6179)
Consolidate session binding resolution into a dedicated helper that scans active PTY states, restored tab PTY IDs, and split-pane layout wake hints. This ensures that deferred-reattach terminal sessions are not falsely classified as orphaned before their UI panes mount.
This commit is contained in:
@@ -68,6 +68,11 @@ import {
|
||||
getResourceManagerAriaLabel,
|
||||
getResourceManagerTooltipLines
|
||||
} from './resource-manager-terminal-copy'
|
||||
import {
|
||||
buildResourceSessionBindingIndex,
|
||||
countUnboundDaemonSessions,
|
||||
type ResourceSessionBindingInputs
|
||||
} from './resource-session-bindings'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
const POLL_MS = 2_000
|
||||
@@ -732,6 +737,8 @@ export function ResourceUsageStatusSegment({
|
||||
const fetchSnapshot = useAppStore((s) => s.fetchMemorySnapshot)
|
||||
const workspaceSessionReady = useAppStore((s) => s.workspaceSessionReady)
|
||||
const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId)
|
||||
const tabsByWorktreeForPtyBindings = useAppStore((s) => s.tabsByWorktree)
|
||||
const terminalLayoutsByTabId = useAppStore((s) => s.terminalLayoutsByTabId)
|
||||
const setActiveView = useAppStore((s) => s.setActiveView)
|
||||
const openModal = useAppStore((s) => s.openModal)
|
||||
const openSpacePage = useAppStore((s) => s.openSpacePage)
|
||||
@@ -778,6 +785,17 @@ export function ResourceUsageStatusSegment({
|
||||
// While a runtime server is active, hiding local samples avoids showing or
|
||||
// killing sessions from the wrong machine.
|
||||
const resourceSnapshot = runtimeEnvironmentActive ? null : snapshot
|
||||
// Why: ptyIdsByTabId intentionally tracks mounted/live panes only. Resource
|
||||
// Manager also reads restored wake hints, but only for classification.
|
||||
const resourceSessionBindings = useMemo<ResourceSessionBindingInputs>(
|
||||
() => ({
|
||||
ptyIdsByTabId,
|
||||
tabsByWorktree: tabsByWorktreeForPtyBindings,
|
||||
terminalLayoutsByTabId,
|
||||
workspaceSessionReady
|
||||
}),
|
||||
[ptyIdsByTabId, tabsByWorktreeForPtyBindings, terminalLayoutsByTabId, workspaceSessionReady]
|
||||
)
|
||||
|
||||
// Why: after a kill confirms and the session unmounts, focus would otherwise
|
||||
// fall to <body>. We park a ref on the popover body so we can restore focus
|
||||
@@ -947,6 +965,7 @@ export function ResourceUsageStatusSegment({
|
||||
? mergeSnapshotAndSessions(resourceSnapshot, sessions, {
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
terminalLayoutsByTabId,
|
||||
runtimePaneTitlesByTabId,
|
||||
workspaceSessionReady,
|
||||
repoDisplayNameById,
|
||||
@@ -960,6 +979,7 @@ export function ResourceUsageStatusSegment({
|
||||
sessions,
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
terminalLayoutsByTabId,
|
||||
runtimePaneTitlesByTabId,
|
||||
workspaceSessionReady,
|
||||
repoDisplayNameById,
|
||||
@@ -969,28 +989,12 @@ export function ResourceUsageStatusSegment({
|
||||
|
||||
// Why: orphanCount drives the trigger badge (always visible in the status
|
||||
// bar, popover open or not) so it must compute outside the open-gate.
|
||||
// Build the bound set with a single flat walk instead of nested Object
|
||||
// iterations to keep this light on every store update.
|
||||
const orphanCount = useMemo(() => {
|
||||
if (!workspaceSessionReady || runtimeEnvironmentActive) {
|
||||
return 0
|
||||
}
|
||||
const bound = new Set<string>()
|
||||
for (const ids of Object.values(ptyIdsByTabId)) {
|
||||
for (const id of ids) {
|
||||
if (id) {
|
||||
bound.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = 0
|
||||
for (const s of sessions) {
|
||||
if (!bound.has(s.id)) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}, [sessions, ptyIdsByTabId, workspaceSessionReady, runtimeEnvironmentActive])
|
||||
return countUnboundDaemonSessions(sessions, resourceSessionBindings)
|
||||
}, [sessions, resourceSessionBindings, workspaceSessionReady, runtimeEnvironmentActive])
|
||||
|
||||
const { totalMemory, totalCpu, hostShare, memBadgeLabel } = useMemo(() => {
|
||||
const memory = resourceSnapshot?.totalMemory ?? 0
|
||||
@@ -1123,14 +1127,7 @@ export function ResourceUsageStatusSegment({
|
||||
if (!workspaceSessionReady) {
|
||||
return
|
||||
}
|
||||
const bound = new Set<string>()
|
||||
for (const ids of Object.values(ptyIdsByTabId)) {
|
||||
for (const id of ids) {
|
||||
if (id) {
|
||||
bound.add(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
const bound = buildResourceSessionBindingIndex(resourceSessionBindings).boundPtyIds
|
||||
const orphans = sessions.filter((s) => !bound.has(s.id))
|
||||
if (orphans.length === 0) {
|
||||
return
|
||||
@@ -1141,7 +1138,7 @@ export function ResourceUsageStatusSegment({
|
||||
setSessions((prev) => prev.filter((s) => !orphanIds.has(s.id)))
|
||||
await Promise.allSettled(orphans.map((s) => window.api.pty.kill(s.id)))
|
||||
void refreshSessions()
|
||||
}, [sessions, ptyIdsByTabId, workspaceSessionReady, refreshSessions])
|
||||
}, [sessions, resourceSessionBindings, workspaceSessionReady, refreshSessions])
|
||||
|
||||
const runKillConfirmed = useCallback(async () => {
|
||||
if (!killConfirm) {
|
||||
|
||||
@@ -186,6 +186,27 @@ describe('mergeSnapshotAndSessions', () => {
|
||||
expect(out[0].worktrees[0].sessions[0].bound).toBe(true)
|
||||
})
|
||||
|
||||
it('treats startup deferred reattach tab ptyId wake hints as bound sessions', () => {
|
||||
const tabId = 'tab-restored'
|
||||
const sessionId = 'orca::/Users/me/Triton@@deferred'
|
||||
const ds: DaemonSession[] = [{ id: sessionId, cwd: '/Users/me/Triton', title: 'orca/Triton' }]
|
||||
const restoredTab = { ...makeTab(tabId, 'Restored'), ptyId: sessionId }
|
||||
const ctx = baseCtx({
|
||||
tabsByWorktree: {
|
||||
'orca::/Users/me/Triton': [restoredTab]
|
||||
},
|
||||
ptyIdsByTabId: { [tabId]: [] }
|
||||
})
|
||||
|
||||
const out = mergeSnapshotAndSessions(null, ds, ctx)
|
||||
|
||||
expect(out[0].worktrees[0].sessions[0]).toMatchObject({
|
||||
sessionId,
|
||||
bound: true,
|
||||
tabId
|
||||
})
|
||||
})
|
||||
|
||||
it('repo aggregate sums only worktrees with numeric metrics; remote-by-connectionId flags chip', () => {
|
||||
// Why: a single repo can be both reflected as a snapshot worktree
|
||||
// (covered by the local collector) and a daemon-only session
|
||||
|
||||
@@ -31,6 +31,7 @@ import type {
|
||||
UnifiedSessionRow,
|
||||
UnifiedWorktreeRow
|
||||
} from './resource-usage-merge-types'
|
||||
import { buildResourceSessionBindingIndex } from './resource-session-bindings'
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -124,34 +125,6 @@ function resolveDaemonSessionLabel(
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
// Why: the previous implementation did O(N) linear scans over
|
||||
// ptyIdsByTabId / tabsByWorktree for *every* session it processed. With a
|
||||
// large workspace that's S * (T + W) work per merge — and the merge runs on
|
||||
// every snapshot poll plus every store mutation. Pre-build O(1) lookup
|
||||
// indices once per merge instead.
|
||||
type MergeIndex = {
|
||||
ptyIdToTabId: Map<string, string>
|
||||
tabIdToWorktreeId: Map<string, string>
|
||||
}
|
||||
|
||||
function buildMergeIndex(ctx: MergeContext): MergeIndex {
|
||||
const ptyIdToTabId = new Map<string, string>()
|
||||
for (const [tabId, ptyIds] of Object.entries(ctx.ptyIdsByTabId)) {
|
||||
for (const ptyId of ptyIds) {
|
||||
if (ptyId) {
|
||||
ptyIdToTabId.set(ptyId, tabId)
|
||||
}
|
||||
}
|
||||
}
|
||||
const tabIdToWorktreeId = new Map<string, string>()
|
||||
for (const [worktreeId, tabs] of Object.entries(ctx.tabsByWorktree)) {
|
||||
for (const tab of tabs) {
|
||||
tabIdToWorktreeId.set(tab.id, worktreeId)
|
||||
}
|
||||
}
|
||||
return { ptyIdToTabId, tabIdToWorktreeId }
|
||||
}
|
||||
|
||||
// ─── Public merge function ─────────────────────────────────────────
|
||||
|
||||
export const UNATTRIBUTED_REPO_ID = '__unattributed__'
|
||||
@@ -164,13 +137,11 @@ export function mergeSnapshotAndSessions(
|
||||
): UnifiedProjectGroup[] {
|
||||
const repos = new Map<string, UnifiedProjectGroup>()
|
||||
const seenSessionIds = new Set<string>()
|
||||
const index = buildMergeIndex(ctx)
|
||||
// Why: bound = the daemon session id appears as a pty id under some tab.
|
||||
// ptyIdToTabId already encodes that membership in O(1), so the bound set
|
||||
// is just its keys.
|
||||
const boundPtyIds = ctx.workspaceSessionReady
|
||||
? new Set(index.ptyIdToTabId.keys())
|
||||
: new Set<string>()
|
||||
// Why: pre-build O(1) lookup indices once per merge. This includes live
|
||||
// ptyIdsByTabId plus deferred-reattach wake hints, so restored inactive
|
||||
// sessions do not appear as Resource Manager orphans before their pane mounts.
|
||||
const index = buildResourceSessionBindingIndex(ctx)
|
||||
const boundPtyIds = index.boundPtyIds
|
||||
|
||||
function isRepoRemote(repoId: string): boolean {
|
||||
// Why: missing entry === we don't know about this repo (typically the
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/types'
|
||||
import {
|
||||
buildResourceSessionBindingIndex,
|
||||
countUnboundDaemonSessions
|
||||
} from './resource-session-bindings'
|
||||
|
||||
function makeTab(id: string, ptyId: string | null = null): TerminalTab {
|
||||
return {
|
||||
id,
|
||||
ptyId,
|
||||
worktreeId: 'repo::/workspace',
|
||||
title: 'Terminal',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 0,
|
||||
type: 'terminal',
|
||||
paneCount: 1
|
||||
} as unknown as TerminalTab
|
||||
}
|
||||
|
||||
function makeLayout(ptyIdsByLeafId: Record<string, string>): TerminalLayoutSnapshot {
|
||||
return {
|
||||
root: { type: 'leaf', leafId: 'leaf-1' },
|
||||
activeLeafId: 'leaf-1',
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId
|
||||
}
|
||||
}
|
||||
|
||||
describe('resource session bindings', () => {
|
||||
it('combines live PTYs with restored tab and split-pane wake hints', () => {
|
||||
const index = buildResourceSessionBindingIndex({
|
||||
ptyIdsByTabId: {
|
||||
'tab-active': ['pty-live', 'pty-live']
|
||||
},
|
||||
tabsByWorktree: {
|
||||
'repo::/workspace': [makeTab('tab-active'), makeTab('tab-restored', 'pty-restored')]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-restored': makeLayout({
|
||||
'leaf-1': 'pty-leaf-a',
|
||||
'leaf-2': 'pty-leaf-b'
|
||||
})
|
||||
},
|
||||
workspaceSessionReady: true
|
||||
})
|
||||
|
||||
expect(index.ptyIdToTabId).toEqual(
|
||||
new Map([
|
||||
['pty-live', 'tab-active'],
|
||||
['pty-restored', 'tab-restored'],
|
||||
['pty-leaf-a', 'tab-restored'],
|
||||
['pty-leaf-b', 'tab-restored']
|
||||
])
|
||||
)
|
||||
expect([...index.boundPtyIds].sort()).toEqual([
|
||||
'pty-leaf-a',
|
||||
'pty-leaf-b',
|
||||
'pty-live',
|
||||
'pty-restored'
|
||||
])
|
||||
})
|
||||
|
||||
it('ignores stale layout-only PTYs after their tab is gone', () => {
|
||||
const index = buildResourceSessionBindingIndex({
|
||||
ptyIdsByTabId: {},
|
||||
tabsByWorktree: {
|
||||
'repo::/workspace': [makeTab('tab-live', null)]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-closed': makeLayout({ 'leaf-1': 'pty-closed' })
|
||||
},
|
||||
workspaceSessionReady: true
|
||||
})
|
||||
|
||||
expect(index.ptyIdToTabId.has('pty-closed')).toBe(false)
|
||||
expect(index.boundPtyIds.has('pty-closed')).toBe(false)
|
||||
})
|
||||
|
||||
it('counts only daemon sessions without live or restorable tab bindings', () => {
|
||||
const count = countUnboundDaemonSessions(
|
||||
[
|
||||
{ id: 'pty-live', cwd: '/workspace', title: 'live' },
|
||||
{ id: 'pty-restored', cwd: '/workspace', title: 'restored' },
|
||||
{ id: 'pty-orphan', cwd: '/tmp', title: 'orphan' }
|
||||
],
|
||||
{
|
||||
ptyIdsByTabId: { 'tab-live': ['pty-live'] },
|
||||
tabsByWorktree: {
|
||||
'repo::/workspace': [makeTab('tab-live'), makeTab('tab-restored', 'pty-restored')]
|
||||
},
|
||||
terminalLayoutsByTabId: {},
|
||||
workspaceSessionReady: true
|
||||
}
|
||||
)
|
||||
|
||||
expect(count).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/types'
|
||||
import type { DaemonSession } from './resource-usage-merge-types'
|
||||
|
||||
export type ResourceSessionBindingInputs = {
|
||||
tabsByWorktree: Record<string, TerminalTab[]>
|
||||
ptyIdsByTabId: Record<string, string[]>
|
||||
terminalLayoutsByTabId?: Record<string, TerminalLayoutSnapshot>
|
||||
workspaceSessionReady: boolean
|
||||
}
|
||||
|
||||
export type ResourceSessionBindingIndex = {
|
||||
ptyIdToTabId: Map<string, string>
|
||||
tabIdToWorktreeId: Map<string, string>
|
||||
boundPtyIds: Set<string>
|
||||
}
|
||||
|
||||
function addBinding(
|
||||
ptyIdToTabId: Map<string, string>,
|
||||
tabId: string,
|
||||
ptyId: string | null | undefined
|
||||
): void {
|
||||
if (!ptyId || ptyIdToTabId.has(ptyId)) {
|
||||
return
|
||||
}
|
||||
ptyIdToTabId.set(ptyId, tabId)
|
||||
}
|
||||
|
||||
export function buildResourceSessionBindingIndex(
|
||||
inputs: ResourceSessionBindingInputs
|
||||
): ResourceSessionBindingIndex {
|
||||
const ptyIdToTabId = new Map<string, string>()
|
||||
const tabIdToWorktreeId = new Map<string, string>()
|
||||
|
||||
for (const [worktreeId, tabs] of Object.entries(inputs.tabsByWorktree)) {
|
||||
for (const tab of tabs) {
|
||||
tabIdToWorktreeId.set(tab.id, worktreeId)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [tabId, ptyIds] of Object.entries(inputs.ptyIdsByTabId)) {
|
||||
for (const ptyId of ptyIds) {
|
||||
addBinding(ptyIdToTabId, tabId, ptyId)
|
||||
}
|
||||
}
|
||||
|
||||
// Why: startup-deferred reattach intentionally leaves inactive tabs out of
|
||||
// ptyIdsByTabId, but their daemon sessions are still owned by tab/layout
|
||||
// wake hints. Resource Manager should not classify those as orphans.
|
||||
for (const tabs of Object.values(inputs.tabsByWorktree)) {
|
||||
for (const tab of tabs) {
|
||||
addBinding(ptyIdToTabId, tab.id, tab.ptyId)
|
||||
}
|
||||
}
|
||||
|
||||
for (const [tabId, layout] of Object.entries(inputs.terminalLayoutsByTabId ?? {})) {
|
||||
if (!tabIdToWorktreeId.has(tabId)) {
|
||||
continue
|
||||
}
|
||||
for (const ptyId of Object.values(layout.ptyIdsByLeafId ?? {})) {
|
||||
addBinding(ptyIdToTabId, tabId, ptyId)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ptyIdToTabId,
|
||||
tabIdToWorktreeId,
|
||||
boundPtyIds: inputs.workspaceSessionReady ? new Set(ptyIdToTabId.keys()) : new Set()
|
||||
}
|
||||
}
|
||||
|
||||
export function countUnboundDaemonSessions(
|
||||
sessions: readonly DaemonSession[],
|
||||
inputs: ResourceSessionBindingInputs
|
||||
): number {
|
||||
if (!inputs.workspaceSessionReady) {
|
||||
return 0
|
||||
}
|
||||
const { boundPtyIds } = buildResourceSessionBindingIndex(inputs)
|
||||
let count = 0
|
||||
for (const session of sessions) {
|
||||
if (!boundPtyIds.has(session.id)) {
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TerminalTab } from '../../../../shared/types'
|
||||
import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/types'
|
||||
|
||||
/** `null` === "no local sample" (e.g. SSH PTY); UI renders as em-dash. */
|
||||
export type Metric = number | null
|
||||
@@ -50,6 +50,8 @@ export type MergeContext = {
|
||||
tabsByWorktree: Record<string, TerminalTab[]>
|
||||
/** From useAppStore: maps tabId -> ptyIds[] for the bound check. */
|
||||
ptyIdsByTabId: Record<string, string[]>
|
||||
/** From useAppStore: persisted per-leaf PTY wake hints for deferred reattach. */
|
||||
terminalLayoutsByTabId?: Record<string, TerminalLayoutSnapshot>
|
||||
/** From useAppStore: per-tab live pane titles (for label resolution). */
|
||||
runtimePaneTitlesByTabId: Record<string, Record<number, string>>
|
||||
/** From useAppStore: false until renderer state can distinguish bound/orphan. */
|
||||
|
||||
Reference in New Issue
Block a user