Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions src/main/ipc/remote-workspace-snapshot-normalization.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest'
import type {
RemoteWorkspaceSession,
RemoteWorkspaceSnapshot
} from '../../shared/remote-workspace-types'
import {
normalizeSnapshot,
remoteWorkspaceSessionMatchesSnapshot
} from './remote-workspace-snapshot-normalization'

function emptyRemoteWorkspaceSession(): RemoteWorkspaceSession {
return {
activeWorktreePath: null,
activeTabId: null,
tabsByWorktreePath: {},
terminalLayoutsByTabId: {}
}
}

function snapshot(session: RemoteWorkspaceSession, revision = 7): RemoteWorkspaceSnapshot {
return {
namespace: 'target',
revision,
updatedAt: 123,
schemaVersion: 1,
session
}
}

describe('remote workspace snapshot normalization: close tombstones', () => {
it('closedTabTombstonesByTabId survives normalizeSnapshot', () => {
const raw = snapshot({
...emptyRemoteWorkspaceSession(),
closedTabTombstonesByTabId: {
'tab-ghost': { closedAt: 111, worktreePath: '/home/user/bug-cats' }
}
})

const normalized = normalizeSnapshot(raw, 'target')

expect(normalized.session.closedTabTombstonesByTabId).toEqual({
'tab-ghost': { closedAt: 111, worktreePath: '/home/user/bug-cats' }
})
})

it('remoteWorkspaceSessionMatchesSnapshot reports NOT-matching when only tombstones differ', () => {
const base = snapshot(emptyRemoteWorkspaceSession())
const sessionWithTombstone: RemoteWorkspaceSession = {
...emptyRemoteWorkspaceSession(),
closedTabTombstonesByTabId: {
'tab-ghost': { closedAt: 111, worktreePath: '/home/user/bug-cats' }
}
}

expect(remoteWorkspaceSessionMatchesSnapshot(base, sessionWithTombstone)).toBe(false)
})

it('drops invalid tombstone entries while keeping the valid one', () => {
const raw = snapshot({
...emptyRemoteWorkspaceSession(),
closedTabTombstonesByTabId: {
'tab-valid': { closedAt: 111, worktreePath: '/home/user/bug-cats' },
'tab-null': null,
'tab-missing-worktree-path': { closedAt: 222 },
'tab-bad-closed-at': { closedAt: 'x', worktreePath: '/home/user/bug-cats' }
} as never
})

const normalized = normalizeSnapshot(raw, 'target')

expect(normalized.session.closedTabTombstonesByTabId).toEqual({
'tab-valid': { closedAt: 111, worktreePath: '/home/user/bug-cats' }
})
})

it('normalizes an all-invalid tombstone map to undefined', () => {
const raw = snapshot({
...emptyRemoteWorkspaceSession(),
closedTabTombstonesByTabId: {
'tab-null': null,
'tab-missing-worktree-path': { closedAt: 222 }
} as never
})

const normalized = normalizeSnapshot(raw, 'target')

expect(normalized.session.closedTabTombstonesByTabId).toBeUndefined()
})
})
33 changes: 33 additions & 0 deletions src/main/ipc/remote-workspace-snapshot-normalization.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isDeepStrictEqual } from 'node:util'
import type {
RemoteClosedTabTombstone,
RemoteWorkspaceSession,
RemoteWorkspaceSnapshot
} from '../../shared/remote-workspace-types'
Expand Down Expand Up @@ -30,6 +31,35 @@ function normalizeOptionalRecord<T extends Record<string, unknown>>(value: unkno
return Object.keys(value).length > 0 ? (value as T) : undefined
}

function isValidRemoteClosedTabTombstone(value: unknown): value is RemoteClosedTabTombstone {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return false
}
const candidate = value as Partial<RemoteClosedTabTombstone>
return (
typeof candidate.closedAt === 'number' &&
Number.isFinite(candidate.closedAt) &&
typeof candidate.worktreePath === 'string' &&
candidate.worktreePath.length > 0
)
}

// Why: a corrupt inbound snapshot (e.g. `{"tab-1": null}`) later crashes
// importRemoteWorkspaceSession, which reads tombstone.worktreePath without
// re-checking its shape. Dropping invalid entries here keeps that read safe.
function normalizeClosedTabTombstonesByTabId(
value: unknown
): Record<string, RemoteClosedTabTombstone> | undefined {
const record = normalizeOptionalRecord<Record<string, unknown>>(value)
if (!record) {
return undefined
}
const entries = Object.entries(record).filter(([, tombstone]) =>
isValidRemoteClosedTabTombstone(tombstone)
) as [string, RemoteClosedTabTombstone][]
return entries.length > 0 ? Object.fromEntries(entries) : undefined
}

function normalizeRemoteSession(raw: unknown): RemoteWorkspaceSession {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
return emptyRemoteSession()
Expand Down Expand Up @@ -62,6 +92,9 @@ function normalizeRemoteSession(raw: unknown): RemoteWorkspaceSession {
),
lastVisitedAtByWorktreePath: normalizeOptionalRecord<Record<string, number>>(
input.lastVisitedAtByWorktreePath
),
closedTabTombstonesByTabId: normalizeClosedTabTombstonesByTabId(
input.closedTabTombstonesByTabId
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,12 @@ export const WORKSPACE_SESSION_FIELD_DISPOSITION = {
terminalSurfaceTombstonesByPaneKey: {
onRepoRemoval: 'prunedByBespokeRule',
onTransfer: 'copiedByBespokeRule'
},
// Residue: keyed by tab id and pruned by neither path, like remoteSessionIdsByTabId. Bounded
// regardless: the tombstone helpers TTL- and cap-prune the map on every write and merge.
closedTerminalTabTombstonesByTabId: {
onRepoRemoval: 'notRepoScoped',
onTransfer: 'notTransferred'
}
} as const satisfies Record<keyof WorkspaceSessionState, SessionFieldDisposition>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { describe, expect, it } from 'vitest'

import { mergeDirectSshRemoteWorkspaceSession } from './remote-workspace-session-merge'
import { worktreeWorkspaceKey } from '../../../shared/workspace-scope'
import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types'
import type { TerminalTab } from '../../../shared/terminal-tab-types'
import type { AppState } from '../store/types'

const WORKTREE = 'repo-1::/home/user/bug-cats'

function terminalTab(id: string, overrides: Partial<TerminalTab> = {}): TerminalTab {
return {
id,
title: id,
type: 'terminal',
worktreeId: WORKTREE,
...overrides
} as TerminalTab
}

function sessionState(overrides: Partial<WorkspaceSessionState> = {}): WorkspaceSessionState {
return {
activeRepoId: 'repo-1',
activeWorktreeId: WORKTREE,
activeWorkspaceKey: worktreeWorkspaceKey(WORKTREE),
activeTabId: 'agent',
tabsByWorktree: {},
terminalLayoutsByTabId: {},
activeTabIdByWorktree: {},
...overrides
} as WorkspaceSessionState
}

function merge(
current: WorkspaceSessionState,
remote: WorkspaceSessionState,
liveTabs: AppState['tabsByWorktree'] = {}
): WorkspaceSessionState {
return mergeDirectSshRemoteWorkspaceSession(
current,
remote,
new Set([WORKTREE]),
liveTabs,
new Set()
)
}

describe('direct-SSH pull merge: closed-tab tombstones', () => {
it('a remote tab with a local tombstone is not re-inserted', () => {
const ghost = terminalTab('tab-ghost')
const current = sessionState({
tabsByWorktree: { [WORKTREE]: [] },
closedTerminalTabTombstonesByTabId: {
'tab-ghost': { closedAt: Date.now(), worktreeId: WORKTREE }
}
})
const remote = sessionState({
tabsByWorktree: { [WORKTREE]: [ghost] },
terminalLayoutsByTabId: { 'tab-ghost': { type: 'single', tabId: 'tab-ghost' } as never }
})

const merged = merge(current, remote, { [WORKTREE]: [] })

expect(merged.tabsByWorktree[WORKTREE] ?? []).toEqual([])
expect(merged.terminalLayoutsByTabId['tab-ghost']).toBeUndefined()
expect(merged.closedTerminalTabTombstonesByTabId?.['tab-ghost']).toBeDefined()
})

it('a remote tombstone kills the matching local tab-list entry too', () => {
const tabX = terminalTab('tab-x')
const current = sessionState({
tabsByWorktree: { [WORKTREE]: [tabX] }
})
const remote = sessionState({
tabsByWorktree: {},
closedTerminalTabTombstonesByTabId: {
'tab-x': { closedAt: Date.now(), worktreeId: WORKTREE }
}
})

const merged = merge(current, remote, {})

expect((merged.tabsByWorktree[WORKTREE] ?? []).map((t) => t.id)).not.toContain('tab-x')
})

it('a live local tab invalidates a stale tombstone for its id', () => {
const tabLive = terminalTab('tab-live')
const current = sessionState({
tabsByWorktree: { [WORKTREE]: [tabLive] },
closedTerminalTabTombstonesByTabId: {
'tab-live': { closedAt: Date.now(), worktreeId: WORKTREE }
}
})
const remote = sessionState({
tabsByWorktree: { [WORKTREE]: [tabLive] }
})

const merged = merge(current, remote, { [WORKTREE]: [tabLive] })

expect((merged.tabsByWorktree[WORKTREE] ?? []).map((t) => t.id)).toContain('tab-live')
expect(merged.closedTerminalTabTombstonesByTabId?.['tab-live']).toBeUndefined()
})

it('a tombstone wins over preserveLocalTerminalTabIds when the tab is not live locally', () => {
// preserveLocalTerminalTabIds (recovery tabs) only matters for a REMOTE tab that also exists
// locally with a newer generation — it never revives a tab the tombstone filter already dropped.
const ghost = terminalTab('tab-recovery-ghost')
const current = sessionState({
tabsByWorktree: { [WORKTREE]: [] },
closedTerminalTabTombstonesByTabId: {
'tab-recovery-ghost': { closedAt: Date.now(), worktreeId: WORKTREE }
}
})
const remote = sessionState({
tabsByWorktree: { [WORKTREE]: [ghost] }
})

const merged = mergeDirectSshRemoteWorkspaceSession(
current,
remote,
new Set([WORKTREE]),
{},
new Set(['tab-recovery-ghost'])
)

expect((merged.tabsByWorktree[WORKTREE] ?? []).map((t) => t.id)).not.toContain(
'tab-recovery-ghost'
)
})

it('clears activeTabId and activeTabIdByWorktree entries that name a tombstoned tab', () => {
const ghost = terminalTab('tab-ghost')
const survivor = terminalTab('tab-survivor')
const current = sessionState({
tabsByWorktree: { [WORKTREE]: [] }
})
const remote = sessionState({
tabsByWorktree: { [WORKTREE]: [ghost, survivor] },
activeTabId: 'tab-ghost',
activeTabIdByWorktree: { [WORKTREE]: 'tab-ghost' },
closedTerminalTabTombstonesByTabId: {
'tab-ghost': { closedAt: Date.now(), worktreeId: WORKTREE }
}
})

const merged = merge(current, remote, { [WORKTREE]: [] })

expect(merged.activeTabId).toBeNull()
expect(merged.activeTabIdByWorktree?.[WORKTREE]).toBeNull()
})

it('a non-tombstoned active tab id passes through unchanged', () => {
const survivor = terminalTab('tab-survivor')
const current = sessionState({
tabsByWorktree: { [WORKTREE]: [] }
})
const remote = sessionState({
tabsByWorktree: { [WORKTREE]: [survivor] },
activeTabId: 'tab-survivor',
activeTabIdByWorktree: { [WORKTREE]: 'tab-survivor' }
})

const merged = merge(current, remote, { [WORKTREE]: [] })

expect(merged.activeTabId).toBe('tab-survivor')
expect(merged.activeTabIdByWorktree?.[WORKTREE]).toBe('tab-survivor')
})

it('without any tombstone the local-survival trade is unchanged', () => {
// Copied from remote-workspace-session-merge-local-survival.test.ts: the host still lists a tab
// closed elsewhere, and absence alone must keep letting it survive.
const agent = terminalTab('agent')
const closedElsewhere = terminalTab('closed-elsewhere')
const current = sessionState({ tabsByWorktree: { [WORKTREE]: [agent, closedElsewhere] } })
const remote = sessionState({ tabsByWorktree: { [WORKTREE]: [agent] } })

const merged = merge(current, remote, { [WORKTREE]: [agent, closedElsewhere] })

expect(merged.tabsByWorktree[WORKTREE].map((tab) => tab.id)).toContain('closed-elsewhere')
})
})
Loading