test: remove 427 low-value renderer store tests (#37623)

* test: remove 427 low-value renderer store tests

* test: mark retirement plan import as type-only

* test: format reconciled reliability gate metadata
This commit is contained in:
OrcaWin
2026-11-02 19:00:07 -08:00
committed by GitHub
parent 0094f6e9e3
commit fd62da8acb
46 changed files with 64 additions and 9955 deletions
-3
View File
@@ -1078,9 +1078,6 @@
7 test-no-wall-clock:src/renderer/src/store/slices/linear-source-context-cache-scope.test.ts
1 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-agent-status-retention.test.ts
2 test-no-wall-clock:src/renderer/src/store/slices/store-sleep-exact-runtime-stop.test.ts
7 test-no-wall-clock:src/renderer/src/store/slices/tabs-unread-and-focus.test.ts
1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-view-layout.test.ts
1 test-no-wall-clock:src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts
2 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-agent-stop-preflight.test.ts
4 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-local-evidence-invariants.test.ts
2 test-no-wall-clock:src/renderer/src/store/slices/workspace-cleanup-removal-preflight.test.ts
File diff suppressed because one or more lines are too long
-16
View File
@@ -11392,46 +11392,30 @@
"src/renderer/src/store/slices/tabs-model-reconciliation.test.ts": 1800,
"src/renderer/src/store/slices/tabs-open-close-lifecycle.test.ts": 2140,
"src/renderer/src/store/slices/tabs-pane-layout-operations.test.ts": 1652,
"src/renderer/src/store/slices/tabs-session-hydration.test.ts": 1772,
"src/renderer/src/store/slices/tabs-split-create.test.ts": 1733,
"src/renderer/src/store/slices/tabs-unread-and-focus.test.ts": 1801,
"src/renderer/src/store/slices/tabs/hydrated-workspace-reconciliation-batch.test.ts": 1988,
"src/renderer/src/store/slices/tabs/layout-owner-shared-path-gates.test.ts": 1707,
"src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts": 1866,
"src/renderer/src/store/slices/tabs/tab-selection-contract.test.ts": 270,
"src/renderer/src/store/slices/tabs/tabs-layout-owner-groups-order.test.ts": 1731,
"src/renderer/src/store/slices/tabs/tabs-reconciliation-batch-identity.test.ts": 1901,
"src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703,
"src/renderer/src/store/slices/tabs/tabs-root-group.test.ts": 1796,
"src/renderer/src/store/slices/terminal-input-activity-store-write.test.ts": 1726,
"src/renderer/src/store/slices/terminal-layout-pty-ownership.test.ts": 1734,
"src/renderer/src/store/slices/terminal-orphan-helpers.test.ts": 308,
"src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts": 1627,
"src/renderer/src/store/slices/terminal-pane-detach-agent-retention.test.ts": 2846,
"src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts": 1751,
"src/renderer/src/store/slices/terminal-quick-command-hosts.test.ts": 1759,
"src/renderer/src/store/slices/terminal-tab-id-hydration.test.ts": 1738,
"src/renderer/src/store/slices/terminal-tab-owner-index.test.ts": 50,
"src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts": 1791,
"src/renderer/src/store/slices/terminal-tab-retirement-store.test.ts": 1955,
"src/renderer/src/store/slices/terminal-tab-retirement.test.ts": 338,
"src/renderer/src/store/slices/terminal-tab-title-batch.test.ts": 1749,
"src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts": 1673,
"src/renderer/src/store/slices/terminals-hydration-canonical-pty-overlap.test.ts": 1946,
"src/renderer/src/store/slices/terminals-hydration-canonical-rows.test.ts": 1680,
"src/renderer/src/store/slices/terminals-hydration.test.ts": 1768,
"src/renderer/src/store/slices/ui-acknowledge-agents-clock-skew.test.ts": 631,
"src/renderer/src/store/slices/ui-agent-send-target.test.ts": 760,
"src/renderer/src/store/slices/ui-contextual-tours.test.ts": 659,
"src/renderer/src/store/slices/ui-feature-interactions.test.ts": 648,
"src/renderer/src/store/slices/ui-host-filter-sync.test.ts": 597,
"src/renderer/src/store/slices/ui-host-workspace-statuses.test.ts": 1695,
"src/renderer/src/store/slices/ui-hydration-view-layout.test.ts": 659,
"src/renderer/src/store/slices/ui-hydration-workspace-cleanup-browse.test.ts": 659,
"src/renderer/src/store/slices/ui-hydration-workspace-preferences.test.ts": 723,
"src/renderer/src/store/slices/ui-modal-slot-dismissal.test.ts": 662,
"src/renderer/src/store/slices/ui-notice-dismissals.test.ts": 544,
"src/renderer/src/store/slices/ui-page-navigation.test.ts": 629,
"src/renderer/src/store/slices/ui/ui-slice-surface-actions.test.ts": 1760,
"src/renderer/src/store/slices/workspace-activation-preparation.test.ts": 1932,
"src/renderer/src/store/slices/workspace-attention/workspace-unread-characterization.test.ts": 1974,
@@ -44,14 +44,4 @@ describe('closeUnifiedTab with a missing group record (#11308)', () => {
expect(result).toEqual({ closedTabId: closing.id, wasLastTab: false, worktreeId: WT })
expect(store.getState().unifiedTabsByWorktree[WT]?.map((tab) => tab.id)).toEqual([kept.id])
})
it('reports the last tab when the worktree has no other tab', async () => {
const only = store.getState().createUnifiedTab(WT, 'editor', { id: 'editor-only' })
main = await drawTabsFromMain(store)
store.setState({ groupsByWorktree: { [WT]: [] } })
expect(store.getState().closeUnifiedTab(only.id)?.wasLastTab).toBe(true)
await main.settle()
expect(store.getState().unifiedTabsByWorktree[WT] ?? []).toEqual([])
})
})
@@ -12,91 +12,6 @@ function makeBaseSession(): WorkspaceSessionState {
}
}
describe('buildHydratedTabState group validation', () => {
it('filters out invalid worktree IDs', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
unifiedTabs: {
w1: [
{
id: 't1',
entityId: 't1',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'terminal',
label: 'Term',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
],
w_gone: [
{
id: 't2',
entityId: 't2',
groupId: 'g2',
worktreeId: 'w_gone',
contentType: 'terminal',
label: 'Gone',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
tabGroups: {
w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }],
w_gone: [{ id: 'g2', worktreeId: 'w_gone', activeTabId: 't2', tabOrder: ['t2'] }]
}
}
const result = buildHydratedTabState(session, new Set(['w1']))
expect(result.unifiedTabsByWorktree.w1).toHaveLength(1)
expect(result.unifiedTabsByWorktree.w_gone).toBeUndefined()
})
it('validates group references against hydrated tabs', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
unifiedTabs: {
w1: [
{
id: 't1',
entityId: 't1',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'terminal',
label: 'Term',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
tabGroups: {
w1: [
{
id: 'g1',
worktreeId: 'w1',
activeTabId: 'deleted-tab',
tabOrder: ['deleted-tab', 't1']
}
]
}
}
const result = buildHydratedTabState(session, new Set(['w1']))
const group = result.groupsByWorktree.w1[0]
expect(group.activeTabId).toBeNull()
expect(group.tabOrder).toEqual(['t1'])
})
})
describe('buildHydratedTabState referential repair', () => {
const tab = (id: string, groupId: string, sortOrder: number) => ({
id,
@@ -143,73 +58,6 @@ describe('buildHydratedTabState referential repair', () => {
])
})
it('adopts tabs stranded by one dropped group into a surviving group', () => {
const result = buildHydratedTabState(
{
...makeBaseSession(),
unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g2', 1)] },
tabGroups: { w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }] }
},
new Set(['w1'])
)
expect(result.groupsByWorktree.w1.map((group) => group.id)).toEqual(['g1'])
expect(result.groupsByWorktree.w1[0].tabOrder).toEqual(['t1', 't2'])
expect(result.unifiedTabsByWorktree.w1.map((t) => t.groupId)).toEqual(['g1', 'g1'])
})
it('repairs a tab groupId when a surviving group already owns the tab', () => {
const result = buildHydratedTabState(
{
...makeBaseSession(),
unifiedTabs: { w1: [tab('t1', 'g-dropped', 0)] },
tabGroups: { w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] }] }
},
new Set(['w1'])
)
expect(result.groupsByWorktree.w1[0].tabOrder).toEqual(['t1'])
expect(result.unifiedTabsByWorktree.w1[0].groupId).toBe('g1')
})
it('spans every surviving group when the persisted layout is gone', () => {
// Salvaged layouts must span every surviving group or tabs in omitted groups remain silently hidden.
const result = buildHydratedTabState(
{
...makeBaseSession(),
unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g2', 1)] },
tabGroups: {
w1: [
{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] },
{ id: 'g2', worktreeId: 'w1', activeTabId: 't2', tabOrder: ['t2'] }
]
}
},
new Set(['w1'])
)
expect(leafGroupIds(result.layoutByWorktree.w1)).toEqual(['g1', 'g2'])
})
it('adds surviving groups omitted by a partial persisted layout', () => {
const result = buildHydratedTabState(
{
...makeBaseSession(),
unifiedTabs: { w1: [tab('t1', 'g1', 0), tab('t2', 'g2', 1)] },
tabGroups: {
w1: [
{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1'] },
{ id: 'g2', worktreeId: 'w1', activeTabId: 't2', tabOrder: ['t2'] }
]
},
tabGroupLayouts: { w1: { type: 'leaf', groupId: 'g1' } }
},
new Set(['w1'])
)
expect(leafGroupIds(result.layoutByWorktree.w1)).toEqual(['g1', 'g2'])
})
it('collapses a persisted layout that repeats one group across leaves', () => {
const result = buildHydratedTabState(
{
@@ -15,273 +15,6 @@ function makeBaseSession(): WorkspaceSessionState {
}
describe('buildHydratedTabState – unified format', () => {
it('hydrates tabs and groups from unified format', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
unifiedTabs: {
w1: [
{
id: 't1',
entityId: 't1',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'terminal',
label: 'Term',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'f1',
entityId: 'f1',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'editor',
label: 'File',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
tabGroups: {
w1: [{ id: 'g1', worktreeId: 'w1', activeTabId: 't1', tabOrder: ['t1', 'f1'] }]
}
}
const result = buildHydratedTabState(session, new Set(['w1']))
expect(result.unifiedTabsByWorktree.w1).toHaveLength(2)
expect(result.groupsByWorktree.w1).toHaveLength(1)
expect(result.activeGroupIdByWorktree.w1).toBe('g1')
})
// Legacy previews persisted editor chrome without documents; drop unrestorable preview tabs while retaining normal editors.
it('drops the chrome of a preview tab from before previews were browser tabs', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
openFilesByWorktree: {
w1: [
{
filePath: '/repo/docs/report.html',
relativePath: 'docs/report.html',
worktreeId: 'w1',
language: 'html'
}
]
},
unifiedTabs: {
w1: [
{
id: 'preview-1',
entityId: 'html-preview::w1::/repo/docs/report.html',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'editor',
label: 'docs/report.html (preview)',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'editor-1',
entityId: '/repo/docs/report.html',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'editor',
label: 'report.html',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
tabGroups: {
w1: [
{
id: 'g1',
worktreeId: 'w1',
activeTabId: 'preview-1',
tabOrder: ['preview-1', 'editor-1']
}
]
}
}
const result = buildHydratedTabState(session, new Set(['w1']))
// Same-document normal editor must survive; dropping all editor chrome would pass an empty-strip check.
expect(result.unifiedTabsByWorktree.w1?.map((tab) => tab.id)).toEqual(['editor-1'])
})
it('collapses groups and layout when transient tabs are dropped during hydration', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
openFilesByWorktree: {
w1: [
{
filePath: '/editor.ts',
relativePath: 'editor.ts',
worktreeId: 'w1',
language: 'typescript'
}
]
},
unifiedTabs: {
w1: [
{
id: 'diff-1',
entityId: '/diff.ts',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'diff',
label: 'diff.ts',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'editor-1',
entityId: '/editor.ts',
groupId: 'g2',
worktreeId: 'w1',
contentType: 'editor',
label: 'editor.ts',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
tabGroups: {
w1: [
{ id: 'g1', worktreeId: 'w1', activeTabId: 'diff-1', tabOrder: ['diff-1'] },
{ id: 'g2', worktreeId: 'w1', activeTabId: 'editor-1', tabOrder: ['editor-1'] }
]
},
tabGroupLayouts: {
w1: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId: 'g1' },
second: { type: 'leaf', groupId: 'g2' },
ratio: 0.5
}
},
activeGroupIdByWorktree: { w1: 'g1' }
}
const result = buildHydratedTabState(session, new Set(['w1']))
expect(result.unifiedTabsByWorktree.w1).toEqual([
expect.objectContaining({ id: 'editor-1', groupId: 'g2', contentType: 'editor' })
])
expect(result.groupsByWorktree.w1).toEqual([
{
id: 'g2',
worktreeId: 'w1',
activeTabId: 'editor-1',
tabOrder: ['editor-1'],
recentTabIds: ['editor-1']
}
])
expect(result.activeGroupIdByWorktree.w1).toBe('g2')
expect(result.layoutByWorktree.w1).toEqual({ type: 'leaf', groupId: 'g2' })
})
it('keeps restored simulator tabs while pruning unrelated empty split groups', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
unifiedTabs: {
w1: [
{
id: 'terminal-1',
entityId: 'terminal-1',
groupId: 'g1',
worktreeId: 'w1',
contentType: 'terminal',
label: 'Terminal',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'simulator-1',
entityId: 'simulator-1',
groupId: 'g2',
worktreeId: 'w1',
contentType: 'simulator',
label: 'iPhone 17 Pro',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
tabGroups: {
w1: [
{ id: 'g1', worktreeId: 'w1', activeTabId: 'terminal-1', tabOrder: ['terminal-1'] },
{ id: 'g2', worktreeId: 'w1', activeTabId: 'simulator-1', tabOrder: ['simulator-1'] },
{ id: 'g3', worktreeId: 'w1', activeTabId: null, tabOrder: [] }
]
},
tabGroupLayouts: {
w1: {
type: 'split',
direction: 'horizontal',
first: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId: 'g1' },
second: { type: 'leaf', groupId: 'g2' },
ratio: 0.5
},
second: { type: 'leaf', groupId: 'g3' },
ratio: 0.5
}
},
activeGroupIdByWorktree: { w1: 'g2' }
}
const result = buildHydratedTabState(session, new Set(['w1']))
expect(result.unifiedTabsByWorktree.w1).toEqual([
expect.objectContaining({ id: 'terminal-1', contentType: 'terminal', groupId: 'g1' }),
expect.objectContaining({ id: 'simulator-1', contentType: 'simulator', groupId: 'g2' })
])
expect(result.groupsByWorktree.w1).toEqual([
{
id: 'g1',
worktreeId: 'w1',
activeTabId: 'terminal-1',
tabOrder: ['terminal-1'],
recentTabIds: ['terminal-1']
},
{
id: 'g2',
worktreeId: 'w1',
activeTabId: 'simulator-1',
tabOrder: ['simulator-1'],
recentTabIds: ['simulator-1']
}
])
expect(result.activeGroupIdByWorktree.w1).toBe('g2')
expect(result.layoutByWorktree.w1).toEqual({
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId: 'g1' },
second: { type: 'leaf', groupId: 'g2' },
ratio: 0.5
})
})
it('collapses tab records that a corrupt session persisted under one id', () => {
// Editor migration could re-stamp a sibling’s tab ID; duplicate React keys strand ghost rows.
const duplicateId = 'editor:wt%3A%3Alungfish:env-a:FINAL-REPORT.md'
@@ -45,18 +45,6 @@ vi.mock('@/runtime/runtime-layout-client', async (importOriginal) =>
store = createTestStore()
})
describe('tab property setters', () => {
it('setTabLabel preserves tab map references when the label is unchanged', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().setTabLabel(tab.id, 'zsh')
const before = store.getState().unifiedTabsByWorktree
store.getState().setTabLabel(tab.id, 'zsh')
expect(store.getState().unifiedTabsByWorktree).toBe(before)
})
})
describe('pinTab / unpinTab', () => {
it('pins a tab and promotes preview to permanent', async () => {
store.setState({
@@ -102,124 +90,6 @@ vi.mock('@/runtime/runtime-layout-client', async (importOriginal) =>
main.close()
}
})
it('moves pinned tabs before unpinned siblings', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().pinTab(t3.id)
store.getState().pinTab(t2.id)
expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([t3.id, t2.id, t1.id])
expect(store.getState().unifiedTabsByWorktree[WT].map((tab) => tab.sortOrder)).toEqual([
2, 1, 0
])
})
it('keeps remaining pinned tabs before a tab that was unpinned', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().pinTab(t2.id)
store.getState().pinTab(t3.id)
store.getState().unpinTab(t2.id)
expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([t3.id, t2.id, t1.id])
})
it('syncs isPinned to the TerminalTab in tabsByWorktree (reconcile echo guard)', async () => {
// Sync legacy isPinned too or reconciliation unpins the tab during host-snapshot echo.
const tab = store.getState().createUnifiedTab(WT, 'terminal')
store.setState((state) => ({
tabsByWorktree: {
...state.tabsByWorktree,
[WT]: [
{
id: tab.id,
ptyId: null,
worktreeId: WT,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
}
}))
// A layout-owner build draws the color from main's frame.
const main = await drawTabsFromMain(store)
try {
const interaction = vi.fn()
store.setState({ recordFeatureInteraction: interaction })
store.getState().pinTab(tab.id, { recordInteraction: false })
expect(store.getState().tabsByWorktree[WT][0].isPinned).toBe(true)
store.getState().unpinTab(tab.id, { recordInteraction: false })
expect(store.getState().tabsByWorktree[WT][0].isPinned).toBe(false)
store.getState().setTabColor(tab.entityId, '#ff0000', { recordInteraction: false })
await main.settle()
expect(store.getState().tabsByWorktree[WT][0].color).toBe('#ff0000')
expect(interaction).not.toHaveBeenCalled()
store.getState().pinTab(tab.id)
store.getState().unpinTab(tab.id)
store.getState().setTabColor(tab.entityId, null)
await main.settle()
expect(interaction).toHaveBeenCalledTimes(3)
} finally {
main.close()
}
})
})
})
}
{
createTabsSliceMockApi()
const mockWindow = globalThis.window
const WT = 'repo1::/tmp/feature'
describe('createEmptySplitGroup', () => {
beforeEach(() => {
globalThis.window = mockWindow
})
let store: ReturnType<typeof createTestStore>
beforeEach(() => {
store = createTestStore()
})
it('activates the new group by default so terminal splits land in the empty pane', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right')
expect(targetGroupId).toBeTruthy()
expect(store.getState().activeGroupIdByWorktree[WT]).toBe(targetGroupId)
expect(
store.getState().groupsByWorktree[WT].find((group) => group.id === sourceGroupId)
).toEqual(expect.objectContaining({ tabOrder: [tab.id] }))
})
it('keeps the source group focused when activate is false', () => {
store.getState().createUnifiedTab(WT, 'editor', { id: 'file-a.ts', label: 'file-a.ts' })
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right', {
activate: false
})
expect(targetGroupId).toBeTruthy()
expect(store.getState().activeGroupIdByWorktree[WT]).toBe(sourceGroupId)
expect(store.getState().groupsByWorktree[WT].map((group) => group.id)).toEqual([
sourceGroupId,
targetGroupId
])
})
})
}
@@ -25,535 +25,6 @@ describe('TabsSlice', () => {
})
describe('reconcileWorktreeTabModel', () => {
it('drops unified tabs whose backing content no longer exists', () => {
const groupId = 'g-1'
store.setState({
unifiedTabsByWorktree: {
[WT]: [
{
id: 'stale-terminal',
entityId: 'stale-terminal',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
groupsByWorktree: {
[WT]: [
{
id: groupId,
worktreeId: WT,
activeTabId: 'stale-terminal',
tabOrder: ['stale-terminal']
}
]
},
activeGroupIdByWorktree: { [WT]: groupId },
tabsByWorktree: { [WT]: [] }
})
const result = store.getState().reconcileWorktreeTabModel(WT)
expect(result.renderableTabCount).toBe(0)
expect(result.activeRenderableTabId).toBeNull()
expect(store.getState().unifiedTabsByWorktree[WT]).toEqual([])
expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([])
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBeNull()
})
// Reconnect-map-only liveness must prevent orphan sweep from deleting terminals before rebind (#9911).
it('keeps a reconnecting terminal whose live session survives only in a reconnect map', () => {
store.setState({
tabsByWorktree: {
[WT]: [
{
id: 'reconnecting-terminal',
ptyId: null,
worktreeId: WT,
title: 'claude',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'reconnecting-terminal': [] },
pendingReconnectPtyIdByTabId: { 'reconnecting-terminal': 'session-live' },
unifiedTabsByWorktree: { [WT]: [] },
groupsByWorktree: {},
activeGroupIdByWorktree: {}
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()
expect(state.tabsByWorktree[WT].map((tab) => tab.id)).toContain('reconnecting-terminal')
expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.entityId)).toContain(
'reconnecting-terminal'
)
expect(result.renderableTabCount).toBe(1)
})
it('restores a marker-only terminal when the host loss omitted its unified row', () => {
store.setState({
tabsByWorktree: {
[WT]: [
{
id: 'host-lost-terminal',
ptyId: null,
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'host-lost-terminal': [] },
unverifiedPtyLossTabIds: { 'host-lost-terminal': true },
unifiedTabsByWorktree: { [WT]: [] },
groupsByWorktree: {},
activeGroupIdByWorktree: {}
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()
expect(result.renderableTabCount).toBe(1)
expect(state.unifiedTabsByWorktree[WT]?.map((tab) => tab.entityId)).toContain(
'host-lost-terminal'
)
})
// Mirrored layouts could append a second leaf for one group and repeat tab strips; collapse duplicates.
it('collapses a layout that repeats one group across leaves', () => {
const groupId = 'g-1'
store.setState({
unifiedTabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
entityId: 'terminal-1',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
tabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
ptyId: 'pty-1',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'terminal-1': ['pty-1'] },
groupsByWorktree: {
[WT]: [
{ id: groupId, worktreeId: WT, activeTabId: 'terminal-1', tabOrder: ['terminal-1'] }
]
},
activeGroupIdByWorktree: { [WT]: groupId },
layoutByWorktree: {
[WT]: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId },
second: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId },
second: { type: 'leaf', groupId }
}
}
}
})
store.getState().reconcileWorktreeTabModel(WT)
expect(store.getState().layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId })
})
it('keeps simulator tabs because they reconnect their own backing stream', () => {
const terminalGroupId = 'g-terminal'
const simulatorGroupId = 'g-simulator'
store.setState({
unifiedTabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
entityId: 'terminal-1',
groupId: terminalGroupId,
worktreeId: WT,
contentType: 'terminal',
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'simulator-1',
entityId: 'simulator-1',
groupId: simulatorGroupId,
worktreeId: WT,
contentType: 'simulator',
label: 'iPhone 17 Pro',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 2
}
]
},
groupsByWorktree: {
[WT]: [
{
id: terminalGroupId,
worktreeId: WT,
activeTabId: 'terminal-1',
tabOrder: ['terminal-1']
},
{
id: simulatorGroupId,
worktreeId: WT,
activeTabId: 'simulator-1',
tabOrder: ['simulator-1']
}
]
},
layoutByWorktree: {
[WT]: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId: terminalGroupId },
second: { type: 'leaf', groupId: simulatorGroupId }
}
},
activeGroupIdByWorktree: { [WT]: simulatorGroupId },
tabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
ptyId: 'pty-1',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'terminal-1': ['pty-1'] }
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()
expect(result.renderableTabCount).toBe(2)
expect(result.activeRenderableTabId).toBe('simulator-1')
expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.id)).toEqual([
'terminal-1',
'simulator-1'
])
expect(state.groupsByWorktree[WT].map((group) => group.tabOrder)).toEqual([
['terminal-1'],
['simulator-1']
])
expect(state.layoutByWorktree[WT]).toEqual({
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId: terminalGroupId },
second: { type: 'leaf', groupId: simulatorGroupId }
})
})
it('keeps a structured session activation target during worktree reconciliation', () => {
const groupId = 'g-structured'
store.setState({
unifiedTabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
entityId: 'terminal-1',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'structured-session-1',
entityId: 'session-1',
groupId,
worktreeId: WT,
contentType: 'agent-session',
label: 'Codex Chat',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2,
agentSessionAgent: 'codex'
}
]
},
groupsByWorktree: {
[WT]: [
{
id: groupId,
worktreeId: WT,
activeTabId: 'structured-session-1',
tabOrder: ['terminal-1', 'structured-session-1']
}
]
},
activeGroupIdByWorktree: { [WT]: groupId },
tabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
ptyId: 'pty-1',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'terminal-1': ['pty-1'] }
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()
expect(result).toEqual({
renderableTabCount: 2,
activeRenderableTabId: 'structured-session-1'
})
expect(state.unifiedTabsByWorktree[WT].map((tab) => tab.id)).toEqual([
'terminal-1',
'structured-session-1'
])
expect(state.groupsByWorktree[WT][0]).toMatchObject({
activeTabId: 'structured-session-1',
tabOrder: ['terminal-1', 'structured-session-1']
})
})
it('collapses empty split groups when reconciliation drops a stale tab', () => {
const terminalGroupId = 'g-terminal'
const staleGroupId = 'g-stale'
store.setState({
unifiedTabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
entityId: 'terminal-1',
groupId: terminalGroupId,
worktreeId: WT,
contentType: 'terminal',
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'stale-browser',
entityId: 'missing-browser',
groupId: staleGroupId,
worktreeId: WT,
contentType: 'browser',
label: 'Missing browser',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
groupsByWorktree: {
[WT]: [
{
id: terminalGroupId,
worktreeId: WT,
activeTabId: 'terminal-1',
tabOrder: ['terminal-1']
},
{
id: staleGroupId,
worktreeId: WT,
activeTabId: 'stale-browser',
tabOrder: ['stale-browser']
}
]
},
layoutByWorktree: {
[WT]: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', groupId: terminalGroupId },
second: { type: 'leaf', groupId: staleGroupId }
}
},
activeGroupIdByWorktree: { [WT]: staleGroupId },
tabsByWorktree: {
[WT]: [
{
id: 'terminal-1',
ptyId: 'pty-1',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { 'terminal-1': ['pty-1'] },
browserTabsByWorktree: { [WT]: [] }
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()
expect(result.renderableTabCount).toBe(1)
expect(result.activeRenderableTabId).toBe('terminal-1')
expect(state.groupsByWorktree[WT]).toEqual([
expect.objectContaining({ id: terminalGroupId, tabOrder: ['terminal-1'] })
])
expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: terminalGroupId })
expect(state.activeGroupIdByWorktree[WT]).toBe(terminalGroupId)
})
it('restores live runtime terminal tabs into the unified tab model', () => {
const runtimeTerminalId = 'runtime-terminal-1'
store.setState({
tabsByWorktree: {
[WT]: [
{
id: runtimeTerminalId,
ptyId: 'pty-4',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: {
[runtimeTerminalId]: ['pty-4']
},
unifiedTabsByWorktree: {
[WT]: []
},
groupsByWorktree: {
[WT]: []
},
activeGroupIdByWorktree: {}
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const state = store.getState()
const restoredTab = state.unifiedTabsByWorktree[WT]?.[0]
const restoredGroup = state.groupsByWorktree[WT]?.[0]
expect(result.renderableTabCount).toBe(1)
expect(result.activeRenderableTabId).toBe(runtimeTerminalId)
expect(restoredTab).toMatchObject({
id: runtimeTerminalId,
entityId: runtimeTerminalId,
contentType: 'terminal',
label: 'Terminal 1'
})
expect(restoredGroup).toMatchObject({
activeTabId: runtimeTerminalId,
tabOrder: [runtimeTerminalId]
})
expect(state.layoutByWorktree[WT]).toEqual({
type: 'leaf',
groupId: restoredGroup?.id
})
})
it('promotes legacy terminals to the worktree remembered tab, not always the first one', () => {
// Why (regression): reconcile seeded the group with restoredLegacyTabs[0], dropping the remembered selection so it always reopened Terminal 1.
const firstTerminalId = 'runtime-terminal-1'
const secondTerminalId = 'runtime-terminal-2'
store.setState({
tabsByWorktree: {
[WT]: [
{
id: firstTerminalId,
ptyId: 'pty-1',
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: secondTerminalId,
ptyId: 'pty-2',
worktreeId: WT,
title: 'Terminal 2',
customTitle: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
ptyIdsByTabId: {
[firstTerminalId]: ['pty-1'],
[secondTerminalId]: ['pty-2']
},
unifiedTabsByWorktree: { [WT]: [] },
groupsByWorktree: { [WT]: [] },
activeGroupIdByWorktree: {},
activeTabIdByWorktree: { [WT]: secondTerminalId }
})
const result = store.getState().reconcileWorktreeTabModel(WT)
const restoredGroup = store.getState().groupsByWorktree[WT]?.[0]
expect(result.renderableTabCount).toBe(2)
expect(result.activeRenderableTabId).toBe(secondTerminalId)
expect(restoredGroup?.activeTabId).toBe(secondTerminalId)
})
it('keeps a sole terminal renderable after its PTY exits so a failed direnv does not strand the worktree', () => {
// Why (regression): a promoted terminal whose PTY dies must stay renderable, not orphan and bounce to Landing.
const tab = store
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type * as AgentStatusModule from '@/lib/agent-status'
import { getDefaultUIState } from '../../../../shared/constants'
import '../../../../shared/constants'
import { buildMobileSessionTabSnapshots } from '../../runtime/sync-runtime-graph/mobile-session-snapshots'
import { closeMobileSessionTabInStore } from '../../runtime/mobile-session-tab-close'
import { createTabsSliceMockApi } from './tabs-slice-test-harness'
@@ -10,8 +10,7 @@ import {
makeOpenFile,
makeTab,
makeTabGroup,
makeUnifiedTab,
makeWorktree
makeUnifiedTab
} from './store-test-helpers'
import { makeBrowserTab } from './store-session-test-harness'
import { drawTabsFromMain } from './tabs-drawn-from-main.test-fixture'
@@ -63,202 +62,7 @@ describe('TabsSlice', () => {
store = createTestStore()
})
describe('createUnifiedTab', () => {
it('creates a terminal tab and auto-creates a group', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
expect(tab.contentType).toBe('terminal')
expect(tab.worktreeId).toBe(WT)
expect(tab.label).toMatch(/^Terminal/)
const state = store.getState()
expect(state.unifiedTabsByWorktree[WT]).toHaveLength(1)
expect(state.groupsByWorktree[WT]).toHaveLength(1)
expect(state.groupsByWorktree[WT][0].activeTabId).toBe(tab.id)
expect(state.groupsByWorktree[WT][0].tabOrder).toEqual([tab.id])
})
it('creates an editor tab with filePath as id', () => {
const tab = store.getState().createUnifiedTab(WT, 'editor', {
id: '/tmp/feature/src/main.ts',
label: 'main.ts'
})
expect(tab.id).toBe('/tmp/feature/src/main.ts')
expect(tab.contentType).toBe('editor')
expect(tab.label).toBe('main.ts')
})
it('stamps tabs with the active execution host', () => {
store.setState({
activeWorktreeId: WT,
activeWorkspaceExecutionHostId: 'runtime:host-b'
})
expect(store.getState().createUnifiedTab(WT, 'simulator').executionHostId).toBe(
'runtime:host-b'
)
})
it('stamps active local tabs when the local host field is null', () => {
store.setState({ activeWorktreeId: WT, activeWorkspaceExecutionHostId: null })
expect(store.getState().createUnifiedTab(WT, 'browser').executionHostId).toBe('local')
})
it("stamps an SSH worktree's own host when activation passed none", () => {
store.setState({
repos: [
{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }
],
worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', hostId: 'ssh:box' })] },
activeWorktreeId: WT,
activeWorkspaceExecutionHostId: null
})
expect(store.getState().createUnifiedTab(WT, 'browser').executionHostId).toBe('ssh:box')
})
it('activates the newly created tab', () => {
const tab1 = store.getState().createUnifiedTab(WT, 'terminal')
const tab2 = store.getState().createUnifiedTab(WT, 'terminal')
const group = store.getState().groupsByWorktree[WT][0]
expect(group.activeTabId).toBe(tab2.id)
expect(group.tabOrder).toEqual([tab1.id, tab2.id])
})
it('can create a tab without activating it', () => {
const tab1 = store.getState().createUnifiedTab(WT, 'terminal')
const tab2 = store.getState().createUnifiedTab(WT, 'browser', { activate: false })
const group = store.getState().groupsByWorktree[WT][0]
expect(group.activeTabId).toBe(tab1.id)
expect(group.tabOrder).toEqual([tab1.id, tab2.id])
expect(group.recentTabIds).toEqual([tab1.id])
})
it('replaces existing preview tab when creating a new preview', () => {
const preview1 = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts',
isPreview: true
})
store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-b.ts',
label: 'file-b.ts',
isPreview: true
})
const tabs = store.getState().unifiedTabsByWorktree[WT]
expect(tabs).toHaveLength(1)
expect(tabs[0].id).toBe('file-b.ts')
const group = store.getState().groupsByWorktree[WT][0]
expect(group.tabOrder).toEqual(['file-b.ts'])
expect(group.tabOrder).not.toContain(preview1.id)
})
it('replaces editor preview tabs with diff preview tabs', () => {
store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts',
isPreview: true
})
store.getState().createUnifiedTab(WT, 'diff', {
id: 'diff-file-b.ts',
entityId: 'diff-file-b.ts',
label: 'file-b.ts',
isPreview: true
})
expect(store.getState().unifiedTabsByWorktree[WT]).toEqual([
expect.objectContaining({
id: 'diff-file-b.ts',
contentType: 'diff',
isPreview: true
})
])
expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual(['diff-file-b.ts'])
})
it('reuses the existing group for the worktree', () => {
store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'editor', { id: 'f.ts', label: 'f.ts' })
expect(store.getState().groupsByWorktree[WT]).toHaveLength(1)
})
})
describe('terminal tab creation tracking', () => {
it('records normal terminal tab creation without recording activation fallback tabs', () => {
const setMock = vi.mocked(window.api.ui.set)
store.getState().hydratePersistedUI(getDefaultUIState())
setMock.mockClear()
store.getState().createTab(WT)
store.getState().createTab(WT, undefined, undefined, { pendingActivationSpawn: true })
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({
featureInteractions: {
'terminal-tabs': expect.objectContaining({ interactionCount: 1 })
}
})
})
})
describe('closeUnifiedTab', () => {
it('removes the tab and selects right neighbor', () => {
store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().activateTab(t2.id)
const result = store.getState().closeUnifiedTab(t2.id)
expect(result).toEqual({ closedTabId: t2.id, wasLastTab: false, worktreeId: WT })
const state = store.getState()
expect(state.unifiedTabsByWorktree[WT]).toHaveLength(2)
expect(state.groupsByWorktree[WT][0].activeTabId).toBe(t3.id)
})
it('selects left neighbor when closing the rightmost tab', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const result = store.getState().closeUnifiedTab(t2.id)
expect(result?.wasLastTab).toBe(false)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id)
})
it('returns wasLastTab: true when closing the only tab', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const result = store.getState().closeUnifiedTab(t1.id)
expect(result?.wasLastTab).toBe(true)
expect(store.getState().unifiedTabsByWorktree[WT]).toHaveLength(0)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBeNull()
})
it('does not change active tab when closing a non-active tab', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().closeUnifiedTab(t1.id)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t3.id)
})
it('returns null for nonexistent tab', () => {
const result = store.getState().closeUnifiedTab('nonexistent')
expect(result).toBeNull()
})
it('removes a mobile-closed markdown tab from open files so it is not republished', async () => {
const groupId = 'editor-group'
const file = makeOpenFile({
@@ -312,59 +116,6 @@ describe('TabsSlice', () => {
expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs ?? []).toEqual([])
})
it('removes a mobile-closed regular file tab from open files so fallback closes do not resurrect', async () => {
const groupId = 'editor-group'
const file = makeOpenFile({
id: '/tmp/feature/src/app.ts',
filePath: '/tmp/feature/src/app.ts',
relativePath: 'src/app.ts',
language: 'typescript',
worktreeId: WT
})
const tab = makeUnifiedTab({
id: 'app-unified',
entityId: file.id,
contentType: 'editor',
label: 'app.ts',
worktreeId: WT,
groupId
})
store.setState({
openFiles: [file],
unifiedTabsByWorktree: { [WT]: [tab] },
groupsByWorktree: {
[WT]: [
makeTabGroup({
id: groupId,
worktreeId: WT,
activeTabId: tab.id,
tabOrder: [tab.id],
recentTabIds: [tab.id]
})
]
},
activeGroupIdByWorktree: { [WT]: groupId },
activeFileId: file.id,
activeFileIdByWorktree: { [WT]: file.id },
activeWorktreeId: WT,
activeTabType: 'editor',
activeTabTypeByWorktree: { [WT]: 'editor' }
})
expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs).toMatchObject([
{ id: tab.id, type: 'file', filePath: file.filePath }
])
const main = await drawTabsFromMain(store)
expect(closeMobileSessionTabInStore(store.getState(), WT, tab.id)).toBe(true)
// A layout-owner build closes the tab in main; the file goes after its frame drops the tab.
await main.settle()
main.close()
expect(store.getState().openFiles).toEqual([])
expect(buildMobileSessionTabSnapshots(store.getState())[0]?.tabs ?? []).toEqual([])
})
it('closes a mobile fallback file-id tab after the unified wrapper is already gone', () => {
const file = makeOpenFile({
id: '/tmp/feature/src/app.ts',
@@ -417,263 +168,5 @@ describe('TabsSlice', () => {
.sort()
).toEqual([t1.id, t2.id].sort())
})
it('falls back to neighbor selection when the MRU stack has no prior tab', () => {
// Build state manually (no prior activations) — mirrors a freshly-hydrated session with only an active tab known.
const groupId = 'mru-fallback-group'
store.setState({
unifiedTabsByWorktree: {
[WT]: [
{
id: 'a',
entityId: 'a',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'a',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: 'b',
entityId: 'b',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'b',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
},
{
id: 'c',
entityId: 'c',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'c',
customLabel: null,
color: null,
sortOrder: 2,
createdAt: 3
}
]
},
groupsByWorktree: {
[WT]: [
{
id: groupId,
worktreeId: WT,
activeTabId: 'b',
tabOrder: ['a', 'b', 'c'],
recentTabIds: ['b']
}
]
},
activeGroupIdByWorktree: { [WT]: groupId }
})
store.getState().closeUnifiedTab('b')
// MRU only contains 'b' itself, so fallback picks the right neighbor 'c'.
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe('c')
})
it('tracks an independent MRU history per tab group', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const secondGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right')
expect(secondGroupId).toBeTruthy()
const t2 = store.getState().createUnifiedTab(WT, 'terminal', {
targetGroupId: secondGroupId!
})
const t3 = store.getState().createUnifiedTab(WT, 'terminal', {
targetGroupId: secondGroupId!
})
// Focus the source group without changing the second group’s MRU.
store.getState().activateTab(t1.id)
// Re-focus the second group via t2, then close it: expect the same-group previous tab (t3), not a source-group neighbor.
store.getState().activateTab(t3.id)
store.getState().activateTab(t2.id)
store.getState().closeUnifiedTab(t2.id)
const secondGroup = store.getState().groupsByWorktree[WT].find((g) => g.id === secondGroupId)
expect(secondGroup?.activeTabId).toBe(t3.id)
const sourceGroup = store.getState().groupsByWorktree[WT].find((g) => g.id === sourceGroupId)
expect(sourceGroup?.activeTabId).toBe(t1.id)
})
it('records generic pane interaction when creating an empty split group', () => {
const setMock = vi.mocked(window.api.ui.set)
store.getState().hydratePersistedUI(getDefaultUIState())
setMock.mockClear()
store.getState().createUnifiedTab(WT, 'terminal')
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right')
expect(store.getState().featureInteractions['terminal-pane-split']).toBeUndefined()
expect(store.getState().featureInteractions['terminal-panes']).toMatchObject({
interactionCount: 1
})
})
})
describe('closeOtherTabs', () => {
it('closes all tabs except the target and pinned tabs', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().pinTab(t1.id)
const closed = store.getState().closeOtherTabs(t2.id)
expect(closed).toEqual([t3.id])
const tabs = store.getState().unifiedTabsByWorktree[WT]
expect(tabs).toHaveLength(2)
expect(tabs.map((t) => t.id)).toContain(t1.id)
expect(tabs.map((t) => t.id)).toContain(t2.id)
})
it('activates the target tab', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'terminal')
store.getState().closeOtherTabs(t1.id)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id)
})
it('returns empty when nothing to close', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const closed = store.getState().closeOtherTabs(t1.id)
expect(closed).toEqual([])
})
})
describe('closeTabsToRight', () => {
it('closes unpinned tabs to the right of target', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
const t4 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().pinTab(t3.id)
const closed = store.getState().closeTabsToRight(t1.id)
expect(closed).toEqual([t2.id, t4.id])
const tabs = store.getState().unifiedTabsByWorktree[WT]
expect(tabs.map((t) => t.id)).toEqual([t1.id, t3.id])
})
it('activates target if active tab was closed', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'terminal')
store.getState().closeTabsToRight(t1.id)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id)
})
})
describe('closeTabsToLeft', () => {
it('closes unpinned tabs to the left of target', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
const t4 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().pinTab(t2.id)
const closed = store.getState().closeTabsToLeft(t4.id)
expect(closed).toEqual([t1.id, t3.id])
const tabs = store.getState().unifiedTabsByWorktree[WT]
expect(tabs.map((t) => t.id)).toEqual([t2.id, t4.id])
})
it('returns empty when target is the leftmost tab', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'terminal')
const closed = store.getState().closeTabsToLeft(t1.id)
expect(closed).toEqual([])
expect(store.getState().unifiedTabsByWorktree[WT]).toHaveLength(2)
})
it('activates target if active tab was closed', () => {
store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().activateTab(t2.id)
store.getState().closeTabsToLeft(t3.id)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t3.id)
})
})
describe('getActiveTab / getTab', () => {
it('getActiveTab returns the active tab for a worktree', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'editor', { id: 'f.ts', label: 'f.ts' })
store.getState().activateTab(t1.id)
expect(store.getState().getActiveTab(WT)?.id).toBe(t1.id)
})
it('getActiveTab returns null for worktree with no tabs', () => {
expect(store.getState().getActiveTab(WT)).toBeNull()
})
it('getTab finds a tab by id across worktrees', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
expect(store.getState().getTab(tab.id)?.id).toBe(tab.id)
})
it('getTab returns null for unknown id', () => {
expect(store.getState().getTab('unknown')).toBeNull()
})
})
describe('cross-content-type neighbor selection', () => {
it('selects an editor tab as neighbor when closing a terminal tab', () => {
const term = store.getState().createUnifiedTab(WT, 'terminal')
const editor = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file.ts',
label: 'file.ts'
})
store.getState().activateTab(term.id)
store.getState().closeUnifiedTab(term.id)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(editor.id)
})
it('selects a terminal tab as neighbor when closing an editor tab', async () => {
seedContentRecords(store, { terminalId: 'term-1', fileId: 'file.ts' })
const term = store.getState().createUnifiedTab(WT, 'terminal', { id: 'term-1' })
const editor = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file.ts',
label: 'file.ts'
})
const main = await drawTabsFromMain(store)
store.getState().closeUnifiedTab(editor.id)
await main.settle()
main.close()
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(term.id)
})
})
})
@@ -24,55 +24,7 @@ describe('TabsSlice', () => {
store = createTestStore()
})
describe('reorderUnifiedTabs', () => {
it('updates tabOrder on the group and sortOrder on tabs', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
const t2 = store.getState().createUnifiedTab(WT, 'terminal')
const t3 = store.getState().createUnifiedTab(WT, 'terminal')
const groupId = store.getState().groupsByWorktree[WT][0].id
store.getState().reorderUnifiedTabs(groupId, [t3.id, t1.id, t2.id])
const group = store.getState().groupsByWorktree[WT][0]
expect(group.tabOrder).toEqual([t3.id, t1.id, t2.id])
const tabs = store.getState().unifiedTabsByWorktree[WT]
const sorted = [...tabs].sort((a, b) => a.sortOrder - b.sortOrder)
expect(sorted.map((t) => t.id)).toEqual([t3.id, t1.id, t2.id])
})
})
describe('setTabGroupSplitRatio', () => {
it('updates the persisted ratio for the targeted split node', () => {
store.setState({
layoutByWorktree: {
[WT]: {
type: 'split',
direction: 'horizontal',
ratio: 0.5,
first: { type: 'leaf', groupId: 'g-1' },
second: {
type: 'split',
direction: 'vertical',
ratio: 0.5,
first: { type: 'leaf', groupId: 'g-2' },
second: { type: 'leaf', groupId: 'g-3' }
}
}
}
})
store.getState().setTabGroupSplitRatio(WT, 'second', 0.7)
const layout = store.getState().layoutByWorktree[WT]
expect(layout.type).toBe('split')
if (layout.type !== 'split' || layout.second.type !== 'split') {
throw new Error('expected nested split layout')
}
expect(layout.ratio).toBe(0.5)
expect(layout.second.ratio).toBe(0.7)
})
it('keeps state identity when the ratio is unchanged', () => {
store.setState({
layoutByWorktree: {
@@ -106,87 +58,6 @@ describe('TabsSlice', () => {
})
describe('move/copy/merge group operations', () => {
it('moves a unified tab into another group', () => {
const tab = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts'
})
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right')
expect(targetGroupId).toBeTruthy()
store.getState().moveUnifiedTabToGroup(tab.id, targetGroupId!)
const state = store.getState()
const moved = state.unifiedTabsByWorktree[WT].find((item) => item.id === tab.id)
expect(moved?.groupId).toBe(targetGroupId)
expect(state.groupsByWorktree[WT].find((group) => group.id === sourceGroupId)).toBeUndefined()
expect(
state.groupsByWorktree[WT].find((group) => group.id === targetGroupId)?.tabOrder
).toEqual([tab.id])
})
it('drops a unified tab into another group and collapses an emptied source group', () => {
const tab = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts'
})
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const targetGroupId = store.getState().createEmptySplitGroup(WT, sourceGroupId, 'right')
expect(targetGroupId).toBeTruthy()
const moved = store.getState().dropUnifiedTab(tab.id, { groupId: targetGroupId! })
expect(moved).toBe(true)
const state = store.getState()
expect(state.groupsByWorktree[WT]).toHaveLength(1)
expect(state.groupsByWorktree[WT][0].id).toBe(targetGroupId)
expect(state.groupsByWorktree[WT][0].tabOrder).toEqual([tab.id])
expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: targetGroupId })
expect(state.activeGroupIdByWorktree[WT]).toBe(targetGroupId)
})
it('drops a unified tab onto a pane edge to create a sibling split', () => {
const first = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts'
})
const second = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-b.ts',
label: 'file-b.ts'
})
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const moved = store.getState().dropUnifiedTab(second.id, {
groupId: sourceGroupId,
splitDirection: 'right'
})
expect(moved).toBe(true)
const state = store.getState()
expect(state.groupsByWorktree[WT]).toHaveLength(2)
const originGroup = state.groupsByWorktree[WT].find((group) => group.id === sourceGroupId)
expect(originGroup?.tabOrder).toEqual([first.id])
const movedTab = state.unifiedTabsByWorktree[WT].find((tab) => tab.id === second.id)
const newGroupId = movedTab?.groupId
expect(newGroupId).toBeTruthy()
expect(newGroupId).not.toBe(sourceGroupId)
expect(state.groupsByWorktree[WT].find((group) => group.id === newGroupId)?.tabOrder).toEqual(
[second.id]
)
const layout = state.layoutByWorktree[WT]
expect(layout.type).toBe('split')
if (layout.type !== 'split') {
throw new Error('expected split layout after edge drop')
}
expect(layout.direction).toBe('horizontal')
expect(layout.first).toEqual({ type: 'leaf', groupId: sourceGroupId })
expect(layout.second).toEqual({ type: 'leaf', groupId: newGroupId })
})
it('creates a unified tab directly in a sibling split without publishing a source-group midpoint', () => {
const terminal = store.getState().createUnifiedTab(WT, 'terminal', {
id: 'terminal-1',
@@ -238,101 +109,5 @@ describe('TabsSlice', () => {
expect(layout.first).toEqual({ type: 'leaf', groupId: sourceGroupId })
expect(layout.second).toEqual({ type: 'leaf', groupId: simulatorGroupId })
})
it('creates a split tab without stealing focus when activation is disabled', () => {
store.getState().createUnifiedTab(WT, 'terminal', {
id: 'terminal-1',
label: 'Terminal 1'
})
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
store.setState({ activeWorktreeId: WT })
const simulator = store.getState().createUnifiedTabInSplit(
WT,
'simulator',
{
sourceGroupId,
splitDirection: 'right'
},
{
id: 'simulator-1',
label: 'Mobile Emulator',
activate: false
}
)
expect(simulator).not.toBeNull()
const state = store.getState()
expect(state.activeGroupIdByWorktree[WT]).toBe(sourceGroupId)
expect(state.activeTabType).toBe('terminal')
expect(
state.groupsByWorktree[WT].find((group) => group.id === simulator!.groupId)?.recentTabIds
).toEqual([])
})
it('treats splitting the only tab onto its own pane body as a no-op', () => {
const onlyTab = store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts'
})
const sourceGroupId = store.getState().groupsByWorktree[WT][0].id
const moved = store.getState().dropUnifiedTab(onlyTab.id, {
groupId: sourceGroupId,
splitDirection: 'down'
})
expect(moved).toBe(false)
const state = store.getState()
expect(state.groupsByWorktree[WT]).toHaveLength(1)
expect(state.groupsByWorktree[WT][0].tabOrder).toEqual([onlyTab.id])
expect(state.layoutByWorktree[WT]).toEqual({ type: 'leaf', groupId: sourceGroupId })
})
it('treats splitting the only tab onto the adjacent sibling edge as a no-op', () => {
store.getState().createUnifiedTab(WT, 'editor', {
id: 'file-a.ts',
label: 'file-a.ts'
})
const right = store.getState().createUnifiedTab(WT, 'terminal', {
id: 'terminal-1',
label: 'Terminal 1'
})
const leftGroupId = store.getState().groupsByWorktree[WT][0].id
expect(
store.getState().dropUnifiedTab(right.id, {
groupId: leftGroupId,
splitDirection: 'right'
})
).toBe(true)
const rightGroupId = store
.getState()
.unifiedTabsByWorktree[WT].find((tab) => tab.id === right.id)?.groupId
expect(rightGroupId).toBeTruthy()
const moved = store.getState().dropUnifiedTab(right.id, {
groupId: leftGroupId,
splitDirection: 'right'
})
expect(moved).toBe(false)
expect(
store.getState().unifiedTabsByWorktree[WT].find((tab) => tab.id === right.id)?.groupId
).toBe(rightGroupId)
})
})
describe('tabOrder dedupe', () => {
it('deduplicates drag reorder payloads before persisting group order', () => {
const first = store.getState().createUnifiedTab(WT, 'terminal')
const second = store.getState().createUnifiedTab(WT, 'terminal')
const groupId = store.getState().groupsByWorktree[WT][0].id
store.getState().reorderUnifiedTabs(groupId, [second.id, first.id, second.id, first.id])
expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual([second.id, first.id])
})
})
})
@@ -1,400 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { Tab, TabGroup } from '../../../../shared/tab-types'
import type * as AgentStatusModule from '@/lib/agent-status'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants'
import { createTabsSliceMockApi } from './tabs-slice-test-harness'
import { createTestStore, makeTabGroup, makeUnifiedTab, makeWorktree } from './store-test-helpers'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('@/lib/agent-status', async (importOriginal) => {
const actual = await importOriginal<typeof AgentStatusModule>()
return {
...actual,
detectAgentStatusFromTitle: vi.fn().mockReturnValue(null)
}
})
createTabsSliceMockApi()
const WT = 'repo1::/tmp/feature'
describe('TabsSlice', () => {
let store: ReturnType<typeof createTestStore>
beforeEach(() => {
store = createTestStore()
})
describe('hydrateTabsSession', () => {
it('hydrates floating workspace unified tabs without a repo worktree', () => {
store.getState().hydrateTabsSession({
activeRepoId: null,
activeWorktreeId: FLOATING_TERMINAL_WORKTREE_ID,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {},
unifiedTabs: {
[FLOATING_TERMINAL_WORKTREE_ID]: [
{
id: 'floating-browser-1',
entityId: 'floating-browser-1',
groupId: 'floating-group-1',
worktreeId: FLOATING_TERMINAL_WORKTREE_ID,
contentType: 'browser',
label: 'Browser',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
tabGroups: {
[FLOATING_TERMINAL_WORKTREE_ID]: [
{
id: 'floating-group-1',
worktreeId: FLOATING_TERMINAL_WORKTREE_ID,
activeTabId: 'floating-browser-1',
tabOrder: ['floating-browser-1']
}
]
}
})
expect(store.getState().unifiedTabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toHaveLength(1)
})
it('hydrates from unified format', () => {
store.setState({
worktreesByRepo: {
repo1: [
{
id: WT,
repoId: 'repo1',
path: '/tmp/feature',
head: 'abc',
branch: 'feature',
isBare: false,
isMainWorktree: false,
displayName: 'feature',
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
linkedGitLabMR: null,
linkedGitLabIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0
}
]
}
})
const groupId = 'g-1'
const tabs: Tab[] = [
{
id: 't-1',
entityId: 't-1',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'zsh',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1000
},
{
id: '/file.ts',
entityId: '/file.ts',
groupId,
worktreeId: WT,
contentType: 'editor',
label: 'file.ts',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2000
}
]
const groups: TabGroup[] = [
{ id: groupId, worktreeId: WT, activeTabId: '/file.ts', tabOrder: ['t-1', '/file.ts'] }
]
store.getState().hydrateTabsSession({
activeRepoId: 'repo1',
activeWorktreeId: WT,
activeTabId: 't-1',
tabsByWorktree: {},
terminalLayoutsByTabId: {},
unifiedTabs: { [WT]: tabs },
tabGroups: { [WT]: groups }
})
const state = store.getState()
expect(state.unifiedTabsByWorktree[WT]).toHaveLength(2)
expect(state.groupsByWorktree[WT][0].activeTabId).toBe('/file.ts')
})
it('deduplicates persisted tab order during unified hydration', () => {
store.setState({
worktreesByRepo: {
repo1: [
{
id: WT,
repoId: 'repo1',
path: '/tmp/feature',
head: 'abc',
branch: 'feature',
isBare: false,
isMainWorktree: false,
displayName: 'feature',
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
linkedGitLabMR: null,
linkedGitLabIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0
}
]
}
})
const groupId = 'g-1'
const tabs: Tab[] = [
{
id: 't-1',
entityId: 't-1',
groupId,
worktreeId: WT,
contentType: 'terminal',
label: 'zsh',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1000
},
{
id: '/file.ts',
entityId: '/file.ts',
groupId,
worktreeId: WT,
contentType: 'editor',
label: 'file.ts',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2000
}
]
const groups: TabGroup[] = [
{
id: groupId,
worktreeId: WT,
activeTabId: '/file.ts',
tabOrder: ['t-1', 't-1', '/file.ts', '/file.ts']
}
]
store.getState().hydrateTabsSession({
activeRepoId: 'repo1',
activeWorktreeId: WT,
activeTabId: 't-1',
tabsByWorktree: {},
terminalLayoutsByTabId: {},
unifiedTabs: { [WT]: tabs },
tabGroups: { [WT]: groups }
})
expect(store.getState().groupsByWorktree[WT][0].tabOrder).toEqual(['t-1', '/file.ts'])
})
it('filters out invalid worktree IDs during hydration', () => {
store.setState({ worktreesByRepo: {} })
store.getState().hydrateTabsSession({
activeRepoId: null,
activeWorktreeId: null,
activeTabId: null,
tabsByWorktree: {
'nonexistent-wt': [
{
id: 't-1',
ptyId: null,
worktreeId: 'nonexistent-wt',
title: 'zsh',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1000
}
]
},
terminalLayoutsByTabId: {}
})
expect(store.getState().unifiedTabsByWorktree).toEqual({})
})
it('replaces only explicitly scoped worktree tab chrome', () => {
const siblingWorktreeId = 'repo2::/tmp/sibling'
const targetGroup = makeTabGroup({
id: 'group-target',
worktreeId: WT,
activeTabId: 'target-old',
tabOrder: ['target-old']
})
const siblingGroup = makeTabGroup({
id: 'group-sibling',
worktreeId: siblingWorktreeId,
activeTabId: 'sibling-tab',
tabOrder: ['sibling-tab']
})
const siblingTabs = [
makeUnifiedTab({
id: 'sibling-tab',
worktreeId: siblingWorktreeId,
groupId: siblingGroup.id
})
]
const siblingGroups = [siblingGroup]
store.setState({
worktreesByRepo: {
repo1: [makeWorktree({ id: WT, repoId: 'repo1' })],
repo2: [makeWorktree({ id: siblingWorktreeId, repoId: 'repo2' })]
},
unifiedTabsByWorktree: {
[WT]: [makeUnifiedTab({ id: 'target-old', worktreeId: WT, groupId: targetGroup.id })],
[siblingWorktreeId]: siblingTabs
},
groupsByWorktree: {
[WT]: [targetGroup],
[siblingWorktreeId]: siblingGroups
},
activeGroupIdByWorktree: {
[WT]: targetGroup.id,
[siblingWorktreeId]: siblingGroup.id
},
layoutByWorktree: {
[WT]: { type: 'leaf', groupId: targetGroup.id },
[siblingWorktreeId]: { type: 'leaf', groupId: siblingGroup.id }
}
})
const targetNew = makeUnifiedTab({
id: 'target-new',
worktreeId: WT,
groupId: targetGroup.id,
label: 'Remote target'
})
store.getState().hydrateTabsSession(
{
activeRepoId: 'repo1',
activeWorktreeId: WT,
activeTabId: targetNew.id,
tabsByWorktree: {},
terminalLayoutsByTabId: {},
unifiedTabs: {
[WT]: [targetNew],
[siblingWorktreeId]: [
makeUnifiedTab({
id: 'sibling-replaced',
worktreeId: siblingWorktreeId,
groupId: siblingGroup.id
})
]
},
tabGroups: {
[WT]: [{ ...targetGroup, activeTabId: targetNew.id, tabOrder: [targetNew.id] }],
[siblingWorktreeId]: [
{ ...siblingGroup, activeTabId: 'sibling-replaced', tabOrder: ['sibling-replaced'] }
]
}
},
{ replaceWorkspaceKeys: [WT] }
)
expect(store.getState().unifiedTabsByWorktree[WT]).toEqual([targetNew])
expect(store.getState().unifiedTabsByWorktree[siblingWorktreeId]).toBe(siblingTabs)
expect(store.getState().groupsByWorktree[siblingWorktreeId]).toBe(siblingGroups)
})
it('deletes omitted target chrome while preserving sibling references', () => {
const siblingWorktreeId = 'repo2::/tmp/sibling'
const targetGroup = makeTabGroup({
id: 'group-target',
worktreeId: WT,
activeTabId: 'target-tab',
tabOrder: ['target-tab']
})
const siblingGroup = makeTabGroup({
id: 'group-sibling',
worktreeId: siblingWorktreeId,
activeTabId: 'sibling-tab',
tabOrder: ['sibling-tab']
})
const siblingTabs = [
makeUnifiedTab({
id: 'sibling-tab',
worktreeId: siblingWorktreeId,
groupId: siblingGroup.id
})
]
const siblingGroups = [siblingGroup]
const siblingLayout = { type: 'leaf' as const, groupId: siblingGroup.id }
store.setState({
worktreesByRepo: {
repo1: [makeWorktree({ id: WT, repoId: 'repo1' })],
repo2: [makeWorktree({ id: siblingWorktreeId, repoId: 'repo2' })]
},
unifiedTabsByWorktree: {
[WT]: [makeUnifiedTab({ id: 'target-tab', worktreeId: WT, groupId: targetGroup.id })],
[siblingWorktreeId]: siblingTabs
},
groupsByWorktree: {
[WT]: [targetGroup],
[siblingWorktreeId]: siblingGroups
},
activeGroupIdByWorktree: {
[WT]: targetGroup.id,
[siblingWorktreeId]: siblingGroup.id
},
layoutByWorktree: {
[WT]: { type: 'leaf', groupId: targetGroup.id },
[siblingWorktreeId]: siblingLayout
}
})
store.getState().hydrateTabsSession(
{
activeRepoId: 'repo1',
activeWorktreeId: WT,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {},
unifiedTabs: {},
tabGroups: {}
},
{ replaceWorkspaceKeys: [WT] }
)
const state = store.getState()
expect(state.unifiedTabsByWorktree).not.toHaveProperty(WT)
expect(state.groupsByWorktree).not.toHaveProperty(WT)
expect(state.activeGroupIdByWorktree).not.toHaveProperty(WT)
expect(state.layoutByWorktree).not.toHaveProperty(WT)
expect(state.unifiedTabsByWorktree[siblingWorktreeId]).toBe(siblingTabs)
expect(state.groupsByWorktree[siblingWorktreeId]).toBe(siblingGroups)
expect(state.layoutByWorktree[siblingWorktreeId]).toBe(siblingLayout)
})
})
})
@@ -153,16 +153,4 @@ describe('creating a tab directly into a new split', () => {
).toEqual(layoutProjection(chained.store.getState(), chained.sourceGroupId, chainedGroupId!))
}
)
it('records the pane interaction the empty split used to record', () => {
const { store, sourceGroupId } = seededStore()
const recordFeatureInteraction = vi.fn()
store.setState({ recordFeatureInteraction })
store.getState().createTab(WT, undefined, undefined, {
split: { ...SPLIT, sourceGroupId }
})
expect(recordFeatureInteraction).toHaveBeenCalledWith('terminal-panes')
})
})
@@ -40,15 +40,6 @@ describe('TabsSlice', () => {
})
describe('activateTab', () => {
it('sets the active tab on the group', () => {
const t1 = store.getState().createUnifiedTab(WT, 'terminal')
store.getState().createUnifiedTab(WT, 'terminal')
store.getState().activateTab(t1.id)
expect(store.getState().groupsByWorktree[WT][0].activeTabId).toBe(t1.id)
})
it('promotes a preview tab to permanent on activation', async () => {
store.setState({ openFiles: [makeOpenFile({ id: 'f.ts', worktreeId: WT, isPreview: true })] })
const preview = store.getState().createUnifiedTab(WT, 'editor', {
@@ -106,244 +97,6 @@ describe('TabsSlice', () => {
})
})
// Ghostty "show until interact": BEL always marks unread (even focused/visible tabs); the on-screen read dismisses it.
describe('lastFocusedAt', () => {
it('stamps a newly created tab that activates', () => {
const before = Date.now()
const tab = store.getState().createUnifiedTab(WT, 'terminal')
const stored = store.getState().unifiedTabsByWorktree[WT].find((t) => t.id === tab.id)
expect(stored?.lastFocusedAt).toBeGreaterThanOrEqual(before)
})
it('leaves a background-created tab unstamped', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal', { activate: false })
const stored = store.getState().unifiedTabsByWorktree[WT].find((t) => t.id === tab.id)
expect(stored?.lastFocusedAt).toBeUndefined()
})
it('stamps a tab created into a new split group', () => {
const source = store.getState().createUnifiedTab(WT, 'terminal')
const before = Date.now()
const split = store.getState().createUnifiedTabInSplit(WT, 'terminal', {
sourceGroupId: source.groupId,
splitDirection: 'right'
})
const stored = store.getState().unifiedTabsByWorktree[WT].find((t) => t.id === split?.id)
expect(stored?.lastFocusedAt).toBeGreaterThanOrEqual(before)
})
})
describe('markTerminalBell tab marker', () => {
it('marks the tab even when it is active in a visible split group of the active worktree', () => {
const tabA = store.getState().createUnifiedTab(WT, 'terminal')
const groupAId = store.getState().groupsByWorktree[WT][0].id
// Split/focus group B so group A’s tab is visible but unfocused.
const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right')
if (!groupBId) {
throw new Error('createEmptySplitGroup returned null')
}
store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId })
store.getState().focusGroup(WT, groupBId)
store.setState({ activeWorktreeId: WT })
// Seed the backing legacy terminal tab so the owner-missing guard doesn't short-circuit.
store.setState({
tabsByWorktree: {
[WT]: [
{
id: tabA.entityId,
ptyId: null,
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: Date.now()
}
]
}
})
// Visible unfocused tabs still get BEL markers; only pane input dismisses them.
store
.getState()
.markTerminalBell({ worktreeId: WT, tabId: tabA.entityId, paneKey: `${tabA.entityId}:0` })
expect(store.getState().unreadTerminalTabs[tabA.entityId]).toBe('terminal-bell')
})
it('does mark a tab that is not the active tab of any visible group', () => {
const tabA1 = store.getState().createUnifiedTab(WT, 'terminal')
const tabA2 = store.getState().createUnifiedTab(WT, 'terminal')
const groupAId = store.getState().groupsByWorktree[WT][0].id
store.getState().activateTab(tabA1.id)
// Create/focus group B to exercise bells with two visible groups.
const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right')
if (!groupBId) {
throw new Error('createEmptySplitGroup returned null')
}
store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId })
store.getState().focusGroup(WT, groupBId)
store.setState({ activeWorktreeId: WT })
// Bell marking requires backing legacy terminal rows, as every production terminal has.
store.setState({
tabsByWorktree: {
[WT]: [
{
id: tabA2.entityId,
ptyId: null,
worktreeId: WT,
title: 'Terminal 2',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: Date.now()
}
]
}
})
store
.getState()
.markTerminalBell({ worktreeId: WT, tabId: tabA2.entityId, paneKey: `${tabA2.entityId}:0` })
expect(store.getState().unreadTerminalTabs[tabA2.entityId]).toBe('terminal-bell')
})
// Why: under show-until-interact, BEL fires unconditionally even on a non-terminal/offscreen surface — a legitimate unread.
it('still marks the tab when the active surface is not terminal', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
// Point active* at this tab but mark a different worktree active (skips the visible-groups check); only activeTabType='editor' remains as a guard.
// Why: seed tabsByWorktree — the tab marker guards against a missing owner tab.
store.setState({
activeWorktreeId: 'other-wt::/path/x',
activeTabId: tab.entityId,
activeTabType: 'editor',
tabsByWorktree: {
[WT]: [
{
id: tab.entityId,
ptyId: null,
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: Date.now()
}
]
}
})
store
.getState()
.markTerminalBell({ worktreeId: WT, tabId: tab.entityId, paneKey: `${tab.entityId}:0` })
expect(store.getState().unreadTerminalTabs[tab.entityId]).toBe('terminal-bell')
})
it('is a no-op when the tab is already flagged', () => {
const tab = store.getState().createUnifiedTab(WT, 'terminal')
// Why: seed tabsByWorktree so the owner-missing guard doesn't short-circuit before we reach the "already flagged" branch.
store.setState({
unreadTerminalTabs: { [tab.entityId]: true as const },
activeTabId: 'something-else',
activeTabType: 'terminal',
activeWorktreeId: 'other-wt',
tabsByWorktree: {
[WT]: [
{
id: tab.entityId,
ptyId: null,
worktreeId: WT,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: Date.now()
}
]
}
})
const before = store.getState().unreadTerminalTabs
store
.getState()
.markTerminalBell({ worktreeId: WT, tabId: tab.entityId, paneKey: `${tab.entityId}:0` })
// Same object reference => no state mutation occurred.
expect(store.getState().unreadTerminalTabs).toBe(before)
})
// Why: the bell's tab marker is agent-agnostic — blocking the working→idle dot here would swallow the agent's completion signal.
it('marks unread for an agent tab when it is not focused', () => {
const agentTabId = 'agent-tab-1'
store.setState({
activeTabId: 'something-else',
activeTabType: 'terminal',
activeWorktreeId: 'other-wt',
tabsByWorktree: {
[WT]: [
{
id: agentTabId,
ptyId: null,
worktreeId: WT,
title: '* Claude done',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: Date.now()
}
]
}
})
store
.getState()
.markTerminalBell({ worktreeId: WT, tabId: agentTabId, paneKey: `${agentTabId}:0` })
expect(store.getState().unreadTerminalTabs[agentTabId]).toBe('terminal-bell')
})
})
// The on-screen scan's read of a visible tab.
describe('readOnScreenAttention tab marker', () => {
it('removes the tab from unreadTerminalTabs', () => {
const tabId = 'bell-tab-1'
store.setState({
unreadTerminalTabs: { [tabId]: true as const, 'other-tab': true as const }
})
store
.getState()
.readOnScreenAttention(
{ workspaceIds: [WT], targets: [{ worktreeId: WT, tabId }] },
{ screenArrived: false }
)
expect(store.getState().unreadTerminalTabs).toEqual({ 'other-tab': true })
})
it('is a reference-preserving no-op when the tab is not flagged', () => {
const initial = { 'other-tab': true as const }
store.setState({ unreadTerminalTabs: initial })
store
.getState()
.readOnScreenAttention(
{ workspaceIds: [WT], targets: [{ worktreeId: WT, tabId: 'bell-tab-1' }] },
{ screenArrived: false }
)
expect(store.getState().unreadTerminalTabs).toBe(initial)
})
})
// Already-active group clicks skip activateTab; focusGroup must still expose its tab to the attention scan.
describe('focusGroup', () => {
it('does not broadcast active-surface writes when the focused group is already current', () => {
@@ -419,23 +172,5 @@ describe('TabsSlice', () => {
surfaceKind: 'terminal'
})
})
it('puts the active tab of every side-by-side group on screen', () => {
const tabA = store.getState().createUnifiedTab(WT, 'terminal')
const groupAId = store.getState().groupsByWorktree[WT][0].id
const groupBId = store.getState().createEmptySplitGroup(WT, groupAId, 'right')
if (!groupBId) {
throw new Error('createEmptySplitGroup returned null')
}
const tabB = store.getState().createUnifiedTab(WT, 'terminal', { targetGroupId: groupBId })
store.setState({ activeWorktreeId: WT, activeView: 'terminal' })
store.getState().focusGroup(WT, groupAId)
expect(resolveAutoAckTabTargets(store.getState())).toEqual([
{ tabId: tabA.entityId, worktreeId: WT, surfaceKind: 'terminal' },
{ tabId: tabB.entityId, worktreeId: WT, surfaceKind: 'terminal' }
])
})
})
})
@@ -1,72 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createTabsSliceMockApi } from '../tabs-slice-test-harness'
import { createTestStore, makeTab } from '../store-test-helpers'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
createTabsSliceMockApi()
const WT = 'repo1::/tmp/feature'
// Main draws the tab bar from its frames; these shared paths must not write structure of their own.
describe('shared tab paths in a layout-owner build', () => {
let store: ReturnType<typeof createTestStore>
beforeEach(() => {
store = createTestStore()
})
it('reconcile counts what would render and leaves the tab bar to main', () => {
const entry = {
id: 'stale-terminal',
entityId: 'stale-terminal',
groupId: 'g-1',
worktreeId: WT,
contentType: 'terminal' as const,
label: 'Terminal 1',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
store.setState({
unifiedTabsByWorktree: { [WT]: [entry] },
groupsByWorktree: {
[WT]: [{ id: 'g-1', worktreeId: WT, activeTabId: entry.id, tabOrder: [entry.id] }]
},
activeGroupIdByWorktree: { [WT]: 'g-1' },
tabsByWorktree: { [WT]: [] }
})
const before = store.getState()
expect(store.getState().reconcileWorktreeTabModel(WT)).toEqual({
renderableTabCount: 0,
activeRenderableTabId: null
})
store.getState().reconcileWorktreeTabModels([WT])
expect(store.getState().unifiedTabsByWorktree).toBe(before.unifiedTabsByWorktree)
expect(store.getState().groupsByWorktree).toBe(before.groupsByWorktree)
})
// A row's ptyId is the window's own field (the frame merge keeps it), so reconnect sets only that.
it('reconnect advertises restored terminals and changes only each row ptyId', async () => {
const rows = { [WT]: [makeTab({ id: 'tab-1', worktreeId: WT, ptyId: null })] }
store.setState({
tabsByWorktree: rows,
terminalLayoutsByTabId: {},
pendingReconnectWorktreeIds: [WT],
pendingReconnectTabByWorktree: { [WT]: ['tab-1'] },
pendingReconnectPtyIdByTabId: { 'tab-1': 'pty-1' }
})
await store.getState().reconnectPersistedTerminals()
expect(store.getState().ptyIdsByTabId['tab-1']).toEqual(['pty-1'])
expect(store.getState().tabsByWorktree).toEqual({
[WT]: [{ ...rows[WT][0], ptyId: 'pty-1' }]
})
expect(store.getState().workspaceSessionReady).toBe(true)
})
})
@@ -79,21 +79,6 @@ afterEach(() => {
})
describe('closing a structured chat from outside its workspace', () => {
it('stops it on the host stamped on its tab, not on whichever host shares its id', () => {
const store = storeWith(chatTab('runtime:server-1'))
const layoutOwner = store.getState()
store.getState().closeUnifiedTab('agent-session:chat-1')
expect(mocks.beginClose).toHaveBeenCalledWith(
expect.objectContaining({
target: { kind: 'environment', environmentId: 'server-1' },
sessionId: 'chat-1',
layoutOwner
})
)
})
// Switch on, main's layout holds only chats this machine's host placed, so the stamp is a fact.
it('an unstamped chat whose workspace two hosts publish: no host off, main’s host on', async () => {
const store = storeWith(chatTab())
@@ -1,227 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { Tab, TabContentType } from '../../../../../shared/tab-types'
import { buildHydratedTabState } from '../tabs-hydration'
import { resolveActivatedWorktreeSurface } from '../worktrees/session/active-worktree-surface'
import { deriveActiveSurfaceForWorktree } from './tabs-surface'
type SelectionState = Parameters<typeof resolveActivatedWorktreeSurface>[0]
const workspace = 'repo::/workspace'
function selectedTab(contentType: TabContentType): Tab {
return {
id: 'selected',
entityId: 'selected-entity',
groupId: 'group',
worktreeId: workspace,
contentType,
label: 'Selected',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
}
function selectionState(tab: Tab | null): SelectionState {
return {
rightSidebarExplorerViewByWorktree: {},
activeGroupIdByWorktree: { [workspace]: 'group' },
groupsByWorktree: {
[workspace]: [
{
id: 'group',
worktreeId: workspace,
activeTabId: tab?.id ?? null,
tabOrder: tab ? [tab.id] : []
}
]
},
unifiedTabsByWorktree: { [workspace]: tab ? [tab] : [] },
layoutByWorktree: {},
activeTabIdByWorktree: { [workspace]: 'remembered-terminal' },
activeFileIdByWorktree: { [workspace]: 'remembered-file' },
activeBrowserTabIdByWorktree: { [workspace]: 'remembered-browser' },
activeTabTypeByWorktree: { [workspace]: 'browser' },
tabsByWorktree: {
[workspace]: [
{
id: 'remembered-terminal',
worktreeId: workspace,
ptyId: null,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
browserTabsByWorktree: {
[workspace]: [
{
id: 'remembered-browser',
worktreeId: workspace,
url: 'about:blank',
title: 'Browser',
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 1
}
]
},
openFiles: [
{
id: 'remembered-file',
worktreeId: workspace,
filePath: '/workspace/file',
relativePath: 'file',
language: 'plaintext',
isDirty: false,
mode: 'edit'
}
]
}
}
function activate(state: SelectionState) {
const { restoredRightSidebarExplorerView: _view, ...surface } = resolveActivatedWorktreeSurface(
state,
workspace,
undefined,
null
)
return surface
}
describe('tab selection and hydration ownership', () => {
it.each([
['terminal', 'terminal'],
['editor', 'editor'],
['diff', 'editor'],
['conflict-review', 'editor'],
['check-details', 'editor'],
['browser', 'browser'],
['simulator', 'simulator'],
['agent-session', 'agent-session']
] as const)(
'projects %s selection while retaining other remembered surfaces',
(kind, visible) => {
const state = selectionState(selectedTab(kind))
const expected = {
activeTabType: visible,
activeTabId: kind === 'terminal' ? 'selected-entity' : 'remembered-terminal',
activeFileId: visible === 'editor' ? 'selected-entity' : 'remembered-file',
activeBrowserTabId: kind === 'browser' ? 'selected-entity' : 'remembered-browser'
}
expect(deriveActiveSurfaceForWorktree(state, workspace)).toEqual(expected)
expect(activate(state)).toEqual(expected)
}
)
it('keeps empty groups authoritative over remembered browser/editor surfaces', () => {
const state = selectionState(null)
expect(activate(state).activeTabType).toBe('terminal')
expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('terminal')
})
it('keeps layout-only ownership authoritative during staged hydration', () => {
const state = selectionState(null)
state.groupsByWorktree = {}
state.layoutByWorktree = { [workspace]: { type: 'leaf', groupId: 'pending' } }
expect(activate(state).activeTabType).toBe('terminal')
expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('terminal')
})
it('distinguishes workspace restoration from group-focus legacy fallback', () => {
const state = selectionState(null)
state.groupsByWorktree = {}
state.activeTabTypeByWorktree[workspace] = 'terminal'
expect(activate(state).activeTabType).toBe('terminal')
expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('browser')
})
it('does not select a preferred tab owned by another group', () => {
const state = selectionState(selectedTab('browser'))
state.unifiedTabsByWorktree[workspace].push({
...selectedTab('editor'),
id: 'foreign',
groupId: 'other'
})
expect(resolveActivatedWorktreeSurface(state, workspace, 'foreign', null).activeTabType).toBe(
'terminal'
)
})
it('resolves stale active-group IDs to the first group consistently', () => {
const state = selectionState(selectedTab('simulator'))
state.activeGroupIdByWorktree[workspace] = 'removed'
expect(activate(state).activeTabType).toBe('simulator')
expect(deriveActiveSurfaceForWorktree(state, workspace).activeTabType).toBe('simulator')
})
it('requires group ownership even for an explicit preferred tab during hydration', () => {
const state = selectionState(selectedTab('simulator'))
state.groupsByWorktree = {}
state.activeTabTypeByWorktree[workspace] = 'terminal'
expect(resolveActivatedWorktreeSurface(state, workspace, 'selected', null).activeTabType).toBe(
'terminal'
)
})
it('honors a preferred tab in the selected group without mutating selection', () => {
const state = selectionState(selectedTab('browser'))
const preferred = { ...selectedTab('simulator'), id: 'preferred' }
state.unifiedTabsByWorktree[workspace].push(preferred)
state.groupsByWorktree[workspace][0].tabOrder.push(preferred.id)
expect(
resolveActivatedWorktreeSurface(state, workspace, preferred.id, null).activeTabType
).toBe('simulator')
expect(state.groupsByWorktree[workspace][0].activeTabId).toBe('selected')
})
it.each([
['terminal', 'terminal', 'remembered-file'],
['editor', 'editor', 'remembered-file'],
['browser', 'browser', 'remembered-file'],
// Closed chats/simulators cannot render from remembered type; fall back to browser and clear the remembered file.
['agent-session', 'browser', null],
['simulator', 'browser', null]
] as const)(
'projects legacy %s memory as %s when unified groups are absent',
(activeTabType, visible, activeFileId) => {
const state = selectionState(null)
state.groupsByWorktree = {}
state.activeTabTypeByWorktree[workspace] = activeTabType
expect(activate(state)).toEqual({
activeTabType: visible,
activeTabId: 'remembered-terminal',
activeFileId,
activeBrowserTabId: 'remembered-browser'
})
}
)
it('hydrates unified selection without allowing conflicting legacy memories to choose it', () => {
const tab = selectedTab('simulator')
const state = selectionState(tab)
const session = {
activeRepoId: null,
activeWorktreeId: workspace,
activeTabId: 'remembered-terminal',
tabsByWorktree: {},
terminalLayoutsByTabId: {},
unifiedTabs: state.unifiedTabsByWorktree,
tabGroups: state.groupsByWorktree,
activeGroupIdByWorktree: state.activeGroupIdByWorktree,
activeTabTypeByWorktree: { [workspace]: 'browser' as const },
activeTabIdByWorktree: state.activeTabIdByWorktree
}
const before = structuredClone(session)
const hydrated = buildHydratedTabState(session, new Set([workspace]))
expect(activate({ ...state, ...hydrated }).activeTabType).toBe('simulator')
expect(session).toEqual(before)
})
})
@@ -1,119 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { recordLayoutApply, sendLayoutApply } from '@/runtime/layout-apply-send'
import type { Tab } from '../../../../../shared/tab-types'
import { createTestStore } from '../store-test-helpers'
import { createTabsSliceMockApi } from '../tabs-slice-test-harness'
const mocks = vi.hoisted(() => {
const held: {
send: ReturnType<typeof vi.fn<typeof recordLayoutApply>>
sendFirst: ReturnType<typeof vi.fn<typeof sendLayoutApply>>
store: unknown
} = {
send: vi.fn<typeof recordLayoutApply>(),
sendFirst: vi.fn<typeof sendLayoutApply>(() => true),
store: null
}
return held
})
vi.mock('../../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
vi.mock('@/runtime/layout-apply-send', () => ({
recordLayoutApply: mocks.send,
sendLayoutApply: mocks.sendFirst
}))
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('@/store', () => ({
get useAppStore() {
return mocks.store
}
}))
createTabsSliceMockApi()
const WT = 'repo1::/path/wt1'
const GROUP = 'group-1'
function tab(id: string, extra: Partial<Tab> = {}): Tab {
return {
id,
entityId: id,
groupId: GROUP,
worktreeId: WT,
contentType: 'browser',
label: id,
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1,
...extra
}
}
function seeded(tabs: Tab[]) {
const store = createTestStore()
store.setState({
unifiedTabsByWorktree: { [WT]: tabs },
groupsByWorktree: {
[WT]: [{ id: GROUP, worktreeId: WT, activeTabId: null, tabOrder: tabs.map((t) => t.id) }]
},
activeGroupIdByWorktree: { [WT]: GROUP }
})
mocks.store = store
return store
}
const moves = () =>
mocks.send.mock.calls.flatMap(([, worktreeId, command]) =>
command.type === 'moveTab' ? [{ worktreeId, ...command }] : []
)
beforeEach(() => {
mocks.send.mockReset()
mocks.sendFirst.mockClear()
})
describe('tab activation in a layout-owner build', () => {
it('asks main to end a preview, writing no preview flag itself', () => {
const store = seeded([tab('tab-a'), tab('tab-b', { isPreview: true })])
store.getState().activateTab('tab-a')
store.getState().activateTab('tab-b')
const [a, b] = store.getState().unifiedTabsByWorktree[WT]!
expect(a).not.toHaveProperty('isPreview')
// Main's frame ends it (editor-tab-layout-owner.test.ts, "clears a promoted preview").
expect(b?.isPreview).toBe(true)
expect(
mocks.sendFirst.mock.calls.map(([, worktreeId, command]) => [worktreeId, command])
).toEqual([[WT, { type: 'promotePreviewTab', tabId: 'tab-b' }]])
})
})
describe('tab order in a layout-owner build', () => {
it('records a reversed order as moves main replays to the same order', () => {
const store = seeded([tab('tab-a'), tab('tab-b'), tab('tab-c')])
store.getState().reorderUnifiedTabs(GROUP, ['tab-c', 'tab-b', 'tab-a'])
let order = ['tab-a', 'tab-b', 'tab-c']
for (const move of moves()) {
order = order.filter((id) => id !== move.tabId)
order.splice(move.index, 0, move.tabId)
// Each step's anchor is the tab its slot follows in the wanted order.
expect(move.afterTabId).toBe(order[move.index - 1] ?? null)
}
expect(order).toEqual(['tab-c', 'tab-b', 'tab-a'])
})
it('sends nothing for an order the caller already had main make', () => {
const store = seeded([tab('tab-a'), tab('tab-b')])
store.getState().reorderUnifiedTabs(GROUP, ['tab-b', 'tab-a'], { layoutOwnerHandled: true })
expect(moves()).toEqual([])
expect(store.getState().groupsByWorktree[WT]![0]!.tabOrder).toEqual(['tab-b', 'tab-a'])
})
})
@@ -1,160 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
createWorktreeTabModelReconciliationBatch,
writeBatchedWorkspaceRecordEntry
} from './tabs-reconciliation-batch'
import { projectWorktreeTabModelReconciliation } from './tabs-reconciliation'
import { createTestStore } from '../store-test-helpers'
const WORKTREE = 'repo::/tmp/app'
describe('projectWorktreeTabModelReconciliation identity', () => {
it('keeps every tab-model map when only an orphan runtime terminal changed', () => {
const groupId = 'g-1'
const store = createTestStore()
store.setState({
unifiedTabsByWorktree: {
[WORKTREE]: [
{
id: 'sim-1',
entityId: 'sim-1',
groupId,
worktreeId: WORKTREE,
contentType: 'simulator',
label: 'Simulator',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
groupsByWorktree: {
[WORKTREE]: [
{
id: groupId,
worktreeId: WORKTREE,
activeTabId: 'sim-1',
tabOrder: ['sim-1']
}
]
},
activeGroupIdByWorktree: { [WORKTREE]: groupId },
layoutByWorktree: { [WORKTREE]: { type: 'leaf', groupId } },
// Orphan: a runtime terminal with no unified row and no live PTY.
tabsByWorktree: {
[WORKTREE]: [
{
id: 'orphan',
ptyId: null,
worktreeId: WORKTREE,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
ptyIdsByTabId: { orphan: [] }
})
const before = store.getState()
const { patch } = projectWorktreeTabModelReconciliation(before, WORKTREE)
expect(patch.tabsByWorktree?.[WORKTREE]).toEqual([])
expect(patch.unifiedTabsByWorktree).toBe(before.unifiedTabsByWorktree)
expect(patch.groupsByWorktree).toBe(before.groupsByWorktree)
expect(patch.activeGroupIdByWorktree).toBe(before.activeGroupIdByWorktree)
expect(patch.layoutByWorktree).toBeUndefined()
})
})
describe('writeBatchedWorkspaceRecordEntry identity', () => {
it('returns the same record when the entry already holds that value', () => {
const groups = [{ id: 'group-1' }]
const current = { [WORKTREE]: groups }
const next = writeBatchedWorkspaceRecordEntry(
current,
'groupsByWorktree',
WORKTREE,
groups,
undefined
)
// A new reference here rerenders every component selecting the map.
expect(next).toBe(current)
})
it('does not claim ownership of a map it never cloned', () => {
const groups = [{ id: 'group-1' }]
const current = { [WORKTREE]: groups }
const batch = createWorktreeTabModelReconciliationBatch({ openFiles: [] })
const unchanged = writeBatchedWorkspaceRecordEntry(
current,
'groupsByWorktree',
WORKTREE,
groups,
batch
)
expect(unchanged).toBe(current)
expect(batch.ownedStateKeys.has('groupsByWorktree')).toBe(false)
// A later real change must therefore still copy rather than mutate the caller's map.
const changed = writeBatchedWorkspaceRecordEntry(
current,
'groupsByWorktree',
WORKTREE,
[{ id: 'group-2' }],
batch
)
expect(changed).not.toBe(current)
expect(current[WORKTREE]).toBe(groups)
expect(batch.ownedStateKeys.has('groupsByWorktree')).toBe(true)
})
it('copies when the value differs', () => {
const current = { [WORKTREE]: 'group-1' }
const next = writeBatchedWorkspaceRecordEntry(
current,
'activeGroupIdByWorktree',
WORKTREE,
'group-2',
undefined
)
expect(next).not.toBe(current)
expect(next[WORKTREE]).toBe('group-2')
})
it('still stores an absent key, including an undefined value', () => {
const current: Record<string, string | undefined> = { other: 'group-1' }
const next = writeBatchedWorkspaceRecordEntry(
current,
'activeGroupIdByWorktree',
WORKTREE,
undefined,
undefined
)
// The spread this replaces added the key; dropping it would change Object.keys.
expect(next).not.toBe(current)
expect(WORKTREE in next).toBe(true)
expect(next[WORKTREE]).toBeUndefined()
})
it('keeps mutating in place once the batch owns the map', () => {
const batch = createWorktreeTabModelReconciliationBatch({ openFiles: [] })
batch.ownedStateKeys.add('groupsByWorktree')
const draft: Record<string, unknown> = { [WORKTREE]: 'old' }
const next = writeBatchedWorkspaceRecordEntry(draft, 'groupsByWorktree', WORKTREE, 'new', batch)
expect(next).toBe(draft)
expect(draft[WORKTREE]).toBe('new')
})
})
@@ -44,13 +44,7 @@ function splitBesideSource(store: ReturnType<typeof createTestStore>, workspaceI
return { store, sourceGroupId, emptyGroupId }
}
function splitWorkspace(workspaceId: string, source: 'terminal' | 'agent-session' = 'terminal') {
const store = createTestStore()
seedSource(store, workspaceId, source)
return splitBesideSource(store, workspaceId)
}
/** As splitWorkspace, with main holding the source tab and drawing the store from its frames. */
/** Main holds the source tab and draws the store from its frames. */
async function drawnSplitWorkspace(workspaceId: string, source: 'terminal' | 'agent-session') {
const store = createTestStore()
seedSource(store, workspaceId, source)
@@ -103,29 +97,4 @@ describe.each(['repo1::/tmp/feature', 'folder:folder-1'])('empty groups in %s',
).toMatchObject({ activeTabId: 'source', tabOrder: ['source'] })
}
)
it('removes a group emptied by stale-tab cleanup while preserving an already empty group', () => {
const { store, sourceGroupId, emptyGroupId } = splitWorkspace(workspaceId)
const layoutWithEmptyNeighbor = store.getState().layoutByWorktree[workspaceId]
const staleGroupId = store.getState().createEmptySplitGroup(workspaceId, emptyGroupId, 'right')
if (!staleGroupId) {
throw new Error('Expected a stale split group')
}
store.getState().createUnifiedTab(workspaceId, 'browser', {
id: 'stale-browser',
entityId: 'missing-browser',
targetGroupId: staleGroupId
})
store.getState().reconcileWorktreeTabModel(workspaceId)
const state = store.getState()
expect(state.groupsByWorktree[workspaceId].map((group) => group.id)).toEqual([
sourceGroupId,
emptyGroupId
])
expect(state.layoutByWorktree[workspaceId]).toEqual(layoutWithEmptyNeighbor)
expect(state.activeGroupIdByWorktree[workspaceId]).toBe(sourceGroupId)
expect(state.unifiedTabsByWorktree[workspaceId].map((tab) => tab.id)).toEqual(['source'])
})
})
@@ -1,35 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host'
import { loadWorkspaceLayout } from '../../../../../shared/workspace-layout/workspace-layout-load'
import { nameBasedLoadContext } from '../../../../../shared/workspace-layout/workspace-layout-minted-ids'
import {
addWorkspace,
emptySession,
FOLDER_KEY,
GIT_KEY,
leaf
} from '../../../../../shared/workspace-layout/workspace-layout-session.test-fixture'
import { createTabsSliceMockApi } from '../tabs-slice-test-harness'
import { createTestStore } from '../store-test-helpers'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
createTabsSliceMockApi()
describe('ensureWorktreeRootGroup', () => {
it.each([GIT_KEY, FOLDER_KEY])('mints the group main mints for %s', (workspaceKey) => {
const stored = addWorkspace(emptySession(), workspaceKey, [
{ id: 'g1', tabs: [{ id: 'tab-a', leaves: [[leaf(1), 'pty-a']] }] }
])
stored.unifiedTabs = {}
stored.tabGroups = {}
stored.tabGroupLayouts = {}
const loaded = loadWorkspaceLayout(LOCAL_EXECUTION_HOST_ID, stored, nameBasedLoadContext())
const groupId = createTestStore().getState().ensureWorktreeRootGroup(workspaceKey)
expect(loaded.layout.workspaces[workspaceKey]?.groups.map((group) => group.id)).toEqual([
groupId
])
})
})
@@ -69,14 +69,6 @@ describe('recordTerminalInput store writes are coalesced', () => {
expect(store.getState().lastTerminalInputAtByPaneKey[PANE]).toBe(1_200)
})
it('writes the very first stamp for a pane synchronously', () => {
const store = createTestStore()
store.getState().recordTerminalInput(PANE, 1_000)
expect(store.getState().lastTerminalInputAtByPaneKey[PANE]).toBe(1_000)
})
it('does not resurrect a pane key a purge deleted', () => {
const store = createTestStore()
@@ -92,13 +84,4 @@ describe('recordTerminalInput store writes are coalesced', () => {
expect(readLastTerminalInputAt(stored, PANE)).toBeUndefined()
expect(mergePendingTerminalInputActivity(stored)[PANE]).toBeUndefined()
})
it('ignores invalid pane keys and timestamps', () => {
const store = createTestStore()
store.getState().recordTerminalInput('', 1_000)
store.getState().recordTerminalInput(PANE, Number.NaN)
expect(store.getState().lastTerminalInputAtByPaneKey).toEqual({})
})
})
@@ -1,11 +1,11 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { makePaneKey } from '../../../../shared/stable-pane-id'
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
import '../../../../shared/constants'
import {
resetAgentPaneAuthorityAliasesForTests,
resolveAgentPaneAuthorityKey
} from './agent-pane-authority'
import { createTestStore, makeTab, makeWorktree, seedStore } from './store-test-helpers'
import { createTestStore } from './store-test-helpers'
const LEAF_1 = '11111111-1111-4111-8111-111111111111'
const LEAF_2 = '22222222-2222-4222-8222-222222222222'
@@ -15,54 +15,6 @@ describe('setTabLayout PTY ownership', () => {
resetAgentPaneAuthorityAliasesForTests()
})
it('normalizes duplicate PTY surfaces at the renderer state boundary', () => {
const store = createTestStore()
store.getState().setTabLayout('tab-1', {
root: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: LEAF_1 },
second: { type: 'leaf', leafId: LEAF_2 }
},
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: {
[LEAF_1]: 'pty-agent',
[LEAF_2]: 'pty-agent'
}
})
expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({
root: { type: 'leaf', leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'pty-agent' }
})
})
it('preserves valid live layouts and legacy leaf ids by identity', () => {
const store = createTestStore()
const layout = {
root: {
type: 'split' as const,
direction: 'horizontal' as const,
first: { type: 'leaf' as const, leafId: 'pane:1' },
second: { type: 'leaf' as const, leafId: 'pane:2' }
},
activeLeafId: 'pane:2',
expandedLeafId: 'pane:1',
ptyIdsByLeafId: {
'pane:1': 'pty-local',
'pane:2': 'remote:env-1@@term_remote'
}
}
store.getState().setTabLayout('tab-1', layout)
expect(store.getState().terminalLayoutsByTabId['tab-1']).toBe(layout)
})
it('moves live and future pane authority onto the retained PTY leaf', () => {
const store = createTestStore()
const removedPaneKey = makePaneKey('tab-1', LEAF_1)
@@ -100,53 +52,6 @@ describe('setTabLayout PTY ownership', () => {
expect(store.getState().agentStatusByPaneKey[retainedPaneKey]?.prompt).toBe('after repair')
})
it('moves hydrated pane authority onto the retained PTY leaf', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
const removedPaneKey = makePaneKey('tab-1', LEAF_1)
const retainedPaneKey = makePaneKey('tab-1', LEAF_2)
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
store.getState().setAgentStatus(removedPaneKey, {
state: 'working',
prompt: 'before hydration',
agentType: 'codex'
})
store.getState().hydrateWorkspaceSession({
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'pty-agent' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: LEAF_1 },
second: { type: 'leaf', leafId: LEAF_2 }
},
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: {
[LEAF_1]: 'pty-agent',
[LEAF_2]: 'pty-agent'
}
}
}
})
expect(store.getState().agentStatusByPaneKey[removedPaneKey]).toBeUndefined()
expect(store.getState().agentStatusByPaneKey[retainedPaneKey]?.prompt).toBe('before hydration')
expect(resolveAgentPaneAuthorityKey(removedPaneKey)).toBe(retainedPaneKey)
})
it('does not steal authority from a pane that was already detached to another tab', () => {
const store = createTestStore()
const removedPaneKey = makePaneKey('source-tab', LEAF_1)
@@ -183,53 +88,4 @@ describe('setTabLayout PTY ownership', () => {
expect(resolveAgentPaneAuthorityKey(detachedPaneKey)).toBe(detachedPaneKey)
expect(resolveAgentPaneAuthorityKey(retainedPaneKey)).toBe(retainedPaneKey)
})
it('repairs duplicate legacy leaf ownership without throwing', () => {
const store = createTestStore()
expect(() =>
store.getState().setTabLayout('tab-1', {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: 'pane:1' },
second: { type: 'leaf', leafId: 'pane:2' }
},
activeLeafId: 'pane:2',
expandedLeafId: null,
ptyIdsByLeafId: {
'pane:1': 'pty-agent',
'pane:2': 'pty-agent'
}
})
).not.toThrow()
expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({
root: { type: 'leaf', leafId: 'pane:2' },
activeLeafId: 'pane:2',
expandedLeafId: null,
ptyIdsByLeafId: { 'pane:2': 'pty-agent' }
})
})
it('scopes ownership to a tab so detach handoffs can share a PTY across tabs', () => {
const store = createTestStore()
const sourceLayout = {
root: { type: 'leaf' as const, leafId: LEAF_1 },
activeLeafId: LEAF_1,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_1]: 'pty-detached' }
}
const targetLayout = {
root: { type: 'leaf' as const, leafId: LEAF_2 },
activeLeafId: LEAF_2,
expandedLeafId: null,
ptyIdsByLeafId: { [LEAF_2]: 'pty-detached' }
}
store.getState().setTabLayout('source-tab', sourceLayout)
store.getState().setTabLayout('target-tab', targetLayout)
expect(store.getState().terminalLayoutsByTabId['source-tab']).toBe(sourceLayout)
expect(store.getState().terminalLayoutsByTabId['target-tab']).toBe(targetLayout)
})
})
@@ -1,114 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { TerminalTab } from '../../../../shared/terminal-tab-types'
import { getOrphanTerminalIds } from './terminal-orphan-helpers'
import { buildTerminalTabRetirementPlan } from './terminal-tab-retirement'
// Reconnect-map sessions count as retirement ownership and must also prevent orphan deletion before rebind (#9911).
// Use one state fixture to prove retirement and orphan sweep agree on liveness.
type TestState = Parameters<typeof buildTerminalTabRetirementPlan>[0] &
Parameters<typeof getOrphanTerminalIds>[0]
function makeTab(overrides: Partial<TerminalTab> & { id: string }): TerminalTab {
return {
ptyId: null,
worktreeId: 'wt-1',
title: 'claude',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 0,
...overrides
}
}
function makeState(overrides: Partial<TestState> = {}): TestState {
return {
worktreesByRepo: { repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'local' }] },
tabsByWorktree: {},
unifiedTabsByWorktree: {},
ptyIdsByTabId: {},
terminalLayoutsByTabId: {},
lastKnownRelayPtyIdByTabId: {},
deferredSshSessionIdsByTabId: {},
pendingReconnectPtyIdByTabId: {},
unverifiedPtyLossTabIds: {},
...overrides
} as TestState
}
describe('getOrphanTerminalIds reconnect-map liveness', () => {
it('does not orphan a tab whose live session survives in pendingReconnectPtyIdByTabId', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1', ptyId: null })] },
ptyIdsByTabId: { T1: [] },
unifiedTabsByWorktree: { 'wt-1': [] },
pendingReconnectPtyIdByTabId: { T1: 'session-live' }
})
expect(buildTerminalTabRetirementPlan(state, 'T1').ptyIds).toContain('session-live')
expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1')
})
it('does not orphan a tab whose live session survives in lastKnownRelayPtyIdByTabId', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1' })] },
ptyIdsByTabId: { T1: [] },
unifiedTabsByWorktree: { 'wt-1': [] },
lastKnownRelayPtyIdByTabId: { T1: 'relay:conn@@pty-live' }
})
expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1')
})
it('does not orphan a tab whose live session survives in deferredSshSessionIdsByTabId', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'T1' })] },
ptyIdsByTabId: { T1: [] },
unifiedTabsByWorktree: { 'wt-1': [] },
deferredSshSessionIdsByTabId: { T1: 'ssh-session-live' }
})
expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('T1')
})
it('still orphans a tab with no live PTY evidence anywhere', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'dead', ptyId: null })] },
ptyIdsByTabId: { dead: [] },
unifiedTabsByWorktree: { 'wt-1': [] }
})
expect(getOrphanTerminalIds(state, 'wt-1')).toContain('dead')
})
it('does not orphan a tab whose PTY loss is unverified', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'host-lost', ptyId: null })] },
ptyIdsByTabId: { 'host-lost': [] },
unifiedTabsByWorktree: { 'wt-1': [] },
unverifiedPtyLossTabIds: { 'host-lost': true }
})
expect(getOrphanTerminalIds(state, 'wt-1')).not.toContain('host-lost')
})
// SSH removal leaves persisted layout bindings behind; these cannot prove liveness or dead relay tabs stay forever.
it('still orphans a tab whose only reference is a stale layout leaf binding', () => {
const state = makeState({
tabsByWorktree: { 'wt-1': [makeTab({ id: 'stale-layout', ptyId: null })] },
ptyIdsByTabId: { 'stale-layout': [] },
unifiedTabsByWorktree: { 'wt-1': [] },
terminalLayoutsByTabId: {
'stale-layout': {
root: { type: 'leaf', leafId: 'leaf-1' },
activeLeafId: 'leaf-1',
expandedLeafId: null,
ptyIdsByLeafId: { 'leaf-1': 'dead-relay-pty' }
}
}
})
expect(getOrphanTerminalIds(state, 'wt-1')).toContain('stale-layout')
})
})
@@ -170,25 +170,6 @@ function collect(args: {
}
describe('detach completed split pane → sidebar retention', () => {
it('recognizes the same run at its transferred authority without a suppressor', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
const state = store.getState()
const result = collect({ currentPaneKey: TARGET_PANE_KEY, currentTabId: TARGET_TAB })
expect(state.agentStatusByPaneKey[SOURCE_PANE_KEY]).toBeUndefined()
expect(state.agentStatusByPaneKey[TARGET_PANE_KEY]?.state).toBe('done')
expect(state.retentionSuppressedPaneKeys[SOURCE_PANE_KEY]).toBeUndefined()
expect(result.toRetain).toEqual([])
expect(result.consumedSuppressedPaneKeys).toEqual([])
})
it('recognizes the same run after chained transfers', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
@@ -237,140 +218,6 @@ describe('detach completed split pane → sidebar retention', () => {
expect(store.getState().agentStatusByPaneKey[extraPaneKey]?.prompt).toBe('late post')
})
it('still retains the source when a different run occupies the transferred key', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
const result = collect({
currentPaneKey: TARGET_PANE_KEY,
currentTabId: TARGET_TAB,
currentStartedAt: 900
})
expect(result.toRetain).toHaveLength(1)
expect(result.toRetain[0]?.entry.paneKey).toBe(SOURCE_PANE_KEY)
})
it('still retains when a new agent reuses the pty and inherits its terminal handle', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
// Why: terminalHandle is pty-scoped, so a fresh codex run carries the same handle.
const result = collect({
currentPaneKey: TARGET_PANE_KEY,
currentTabId: TARGET_TAB,
currentStartedAt: 900,
currentAgentType: 'codex',
terminalHandle: 'term_shared'
})
expect(result.toRetain).toHaveLength(1)
expect(result.toRetain[0]?.entry.paneKey).toBe(SOURCE_PANE_KEY)
})
it('treats differing terminal handles as different runs', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
// Why: identical startedAt/agentType can collide, so a differing handle is the
// only signal that these are separate terminals.
const result = collectRetainedAgentsOnDisappear({
previousAgents: new Map([
[
SOURCE_PANE_KEY,
{
row: makeRow(SOURCE_PANE_KEY, SOURCE_TAB, 100, { terminalHandle: 'term_source' }),
worktreeId: WORKTREE_ID
}
]
]),
currentAgents: new Map([
[
TARGET_PANE_KEY,
{
row: makeRow(TARGET_PANE_KEY, TARGET_TAB, 100, { terminalHandle: 'term_other' }),
worktreeId: WORKTREE_ID
}
]
]),
retainedAgentsByPaneKey: {},
retentionSuppressedPaneKeys: {},
recentlyClosedAgentStatusTabIds: {},
recentlyRetiredAgentStatusPaneKeys: {}
})
expect(result.toRetain).toHaveLength(1)
})
it('recognizes the same run when resume identity lands only after the move', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
// Provider session arrives in separate IPC; a stamped destination and unstamped source do not prove separate runs.
const result = collect({
currentPaneKey: TARGET_PANE_KEY,
currentTabId: TARGET_TAB,
currentProviderSession: { key: 'session_id', id: 'session-1' }
})
expect(result.toRetain).toEqual([])
})
it('treats mismatched resume identities as different runs', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
const result = collect({
currentPaneKey: TARGET_PANE_KEY,
currentTabId: TARGET_TAB,
previousProviderSession: { key: 'session_id', id: 'session-1' },
currentProviderSession: { key: 'session_id', id: 'session-2' }
})
expect(result.toRetain).toHaveLength(1)
})
it('recognizes a handle-less local pty run at its transferred authority', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
state: 'done',
prompt: 'Fix it',
agentType: 'claude'
})
detach(store, SOURCE_TAB, TARGET_TAB)
// Local PTY rows can lack terminalHandle; requiring it would revive moved-row ghosts.
const result = collect({ currentPaneKey: TARGET_PANE_KEY, currentTabId: TARGET_TAB })
expect(result.toRetain[0]?.entry.terminalHandle).toBeUndefined()
expect(result.toRetain).toEqual([])
})
it('does not resurrect the source when the transferred owner immediately closes', () => {
const store = createDetachStore()
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
@@ -417,13 +264,4 @@ describe('detach completed split pane → sidebar retention', () => {
expect(retained[0]?.tab).toBe(destinationTab)
expect(retained[0]?.tab.title).toBe('Destination')
})
it('does not create suppressors for a plain terminal detach', () => {
const store = createDetachStore()
detach(store, SOURCE_TAB, TARGET_TAB)
expect(store.getState().retentionSuppressedPaneKeys[SOURCE_PANE_KEY]).toBeUndefined()
expect(store.getState().retentionSuppressedPaneKeys[TARGET_PANE_KEY]).toBeUndefined()
})
})
@@ -1,52 +1,9 @@
import { describe, expect, it } from 'vitest'
import { createTestStore, makeTab, seedStore } from './store-test-helpers'
import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types'
import type { TerminalLayoutSnapshot } from '../../../../shared/terminal-tab-types'
{
describe('terminal PTY identity replacement', () => {
it('keeps repeated remote handle rotations bounded to the live identity', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
const firstPtyId = 'remote:env-1@@terminal-1'
const secondPtyId = 'remote:env-1@@terminal-2'
const thirdPtyId = 'remote:env-1@@terminal-3'
seedStore(store, {
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: firstPtyId })]
},
ptyIdsByTabId: { 'tab-1': [firstPtyId] },
suppressedPtyExitIds: { [firstPtyId]: true }
})
store.getState().updateTabPtyId('tab-1', secondPtyId, firstPtyId)
store.getState().updateTabPtyId('tab-1', thirdPtyId, secondPtyId)
const state = store.getState()
expect(state.ptyIdsByTabId['tab-1']).toEqual([thirdPtyId])
expect(state.tabsByWorktree[worktreeId][0]?.ptyId).toBe(thirdPtyId)
expect(state.lastKnownRelayPtyIdByTabId['tab-1']).toBe(thirdPtyId)
expect(state.suppressedPtyExitIds).toEqual({ [thirdPtyId]: true })
})
it('migrates stale PTY state when the host snapshot published the replacement first', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
const stalePtyId = 'remote:env-1@@terminal-stale'
const replacementPtyId = 'remote:env-1@@terminal-replacement'
seedStore(store, {
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: replacementPtyId })]
},
ptyIdsByTabId: { 'tab-1': [replacementPtyId] },
pendingPaneAccountRestarts: { [stalePtyId]: 'codex' }
})
store.getState().updateTabPtyId('tab-1', replacementPtyId, stalePtyId)
expect(store.getState().ptyIdsByTabId['tab-1']).toEqual([replacementPtyId])
expect(store.getState().pendingPaneAccountRestarts).toEqual({ [replacementPtyId]: 'codex' })
})
it('publishes pane and tab replacement identities in one store commit', () => {
const store = createTestStore()
const worktreeId = 'repo1::/path/wt1'
@@ -126,23 +83,6 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter
expect(store.getState().cacheTimerByKey[paneKey]).toBeNull()
})
it('wakes zero subscribers across 1,000 repeats of the same timestamp', () => {
const store = createTestStore()
const paneKey = 'tab-1:leaf-a'
store.getState().setCacheTimerStartedAt(paneKey, 1_700_000_000_000)
let wakeups = 0
const unsubscribe = store.subscribe(() => {
wakeups += 1
})
for (let i = 0; i < REPEATS; i += 1) {
store.getState().setCacheTimerStartedAt(paneKey, 1_700_000_000_000)
}
unsubscribe()
expect(wakeups).toBe(0)
})
it('still publishes when the timestamp actually changes', () => {
const store = createTestStore()
const paneKey = 'tab-1:leaf-a'
@@ -159,33 +99,6 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter
expect(wakeups).toBe(2)
expect(store.getState().cacheTimerByKey[paneKey]).toBeNull()
})
it('records the first write for a key even when the value is null', () => {
const store = createTestStore()
const paneKey = 'tab-1:leaf-a'
let wakeups = 0
const unsubscribe = store.subscribe(() => {
wakeups += 1
})
store.getState().setCacheTimerStartedAt(paneKey, null)
unsubscribe()
expect(wakeups).toBe(1)
expect(paneKey in store.getState().cacheTimerByKey).toBe(true)
})
it('still clears a stale :seed sentinel when the pane value is unchanged', () => {
// Without this carve-out the bailout would strand the sentinel and leave a phantom timer.
const store = createTestStore()
const paneKey = 'tab-1:leaf-a'
store.getState().setCacheTimerStartedAt(paneKey, null)
store.setState((s) => ({ cacheTimerByKey: { ...s.cacheTimerByKey, 'tab-1:seed': 42 } }))
store.getState().setCacheTimerStartedAt(paneKey, null)
expect('tab-1:seed' in store.getState().cacheTimerByKey).toBe(false)
})
})
describe('setTabLayout identity bailout', () => {
@@ -206,16 +119,6 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter
expect(wakeups).toBe(0)
})
it('keeps the stored snapshot reference stable when nothing changed', () => {
const store = createTestStore()
store.getState().setTabLayout('tab-1', makeLayout())
const first = store.getState().terminalLayoutsByTabId['tab-1']
store.getState().setTabLayout('tab-1', makeLayout())
expect(store.getState().terminalLayoutsByTabId['tab-1']).toBe(first)
})
it('publishes when any tracked field changes', () => {
const store = createTestStore()
store.getState().setTabLayout('tab-1', makeLayout())
@@ -259,173 +162,5 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter
expect(wakeups, `expected a publish for ${JSON.stringify(mutation)}`).toBe(1)
}
})
it('does not fire pane-ownership transfers for a bailed-out identical layout', () => {
// Duplicate-PTY normalization transfers ownership; replaying its normalized result must publish nothing.
const store = createTestStore()
const duplicate = makeLayout({
ptyIdsByLeafId: { 'leaf-a': 'pty-a', 'leaf-b': 'pty-a' }
})
store.getState().setTabLayout('tab-1', duplicate)
const normalized = store.getState().terminalLayoutsByTabId['tab-1']
expect(normalized.ptyIdsByLeafId).not.toEqual(duplicate.ptyIdsByLeafId)
store.setState({ unreadTerminalPanes: { 'tab-1:leaf-a': 'terminal-bell' } })
const beforeUnread = { ...store.getState().unreadTerminalPanes }
for (let i = 0; i < REPEATS; i += 1) {
store.getState().setTabLayout('tab-1', { ...normalized })
}
expect(store.getState().terminalLayoutsByTabId['tab-1']).toBe(normalized)
expect(store.getState().unreadTerminalPanes).toEqual(beforeUnread)
})
it('still deletes the layout on a clearing call, and bails when already absent', () => {
const store = createTestStore()
store.getState().setTabLayout('tab-1', makeLayout())
store.getState().setTabLayout('tab-1', null)
expect('tab-1' in store.getState().terminalLayoutsByTabId).toBe(false)
let wakeups = 0
const unsubscribe = store.subscribe(() => {
wakeups += 1
})
store.getState().setTabLayout('tab-1', null)
unsubscribe()
expect(wakeups).toBe(0)
})
})
}
{
function terminalTab(id: string, worktreeId: string): TerminalTab {
return {
id,
ptyId: null,
worktreeId,
title: 'Terminal 1',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
}
describe('pane foreground agent slice', () => {
it('sets, value-bails, and clears entries per pane key', () => {
const store = createTestStore()
store
.getState()
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
const first = store.getState().paneForegroundAgentByPaneKey
store
.getState()
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
expect(store.getState().paneForegroundAgentByPaneKey).toBe(first)
store.getState().setPaneForegroundAgent('tab-1:leaf-1', {
agent: 'aider',
routingRevoked: true,
routingConfirmationPending: true,
shellForeground: false
})
expect(store.getState().paneForegroundAgentByPaneKey).not.toBe(first)
expect(store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']?.routingRevoked).toBe(
true
)
expect(
store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']?.routingConfirmationPending
).toBe(true)
store.getState().clearPaneForegroundAgent('tab-1:leaf-1')
expect(store.getState().paneForegroundAgentByPaneKey).toEqual({})
})
// Confirmation settle can change only routingConfirmationPending; equality must allow clearing it or CSI-u stays enabled.
it('lands the publish that clears a pending confirmation', () => {
const store = createTestStore()
store.getState().setPaneForegroundAgent('tab-1:leaf-1', {
agent: 'pi',
routingRevoked: true,
routingConfirmationPending: true,
shellForeground: false
})
// Exactly the entry the inconclusive-settle path republishes.
store.getState().setPaneForegroundAgent('tab-1:leaf-1', {
agent: 'pi',
routingRevoked: true,
shellForeground: false
})
expect(store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']).toEqual({
agent: 'pi',
routingRevoked: true,
shellForeground: false
})
})
// Same-agent confirmation must still replace launch-only evidence so sidebar recognizes process-backed identity.
it('lands a process read that confirms a launch-record agent', () => {
const store = createTestStore()
store.getState().setPaneForegroundAgent('tab-1:leaf-1', {
agent: 'codex',
agentEvidence: 'launch-record',
shellForeground: false
})
store.getState().setPaneForegroundAgent('tab-1:leaf-1', {
agent: 'codex',
agentEvidence: 'process-read',
shellForeground: false
})
expect(store.getState().paneForegroundAgentByPaneKey['tab-1:leaf-1']?.agentEvidence).toBe(
'process-read'
)
})
it('sweeps only the closed tab prefix, not sibling tabs or prefix-share ids', () => {
const store = createTestStore()
store
.getState()
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
store
.getState()
.setPaneForegroundAgent('tab-10:leaf-1', { agent: 'codex', shellForeground: false })
store.getState().clearPaneForegroundAgentByTabPrefix('tab-1')
expect(Object.keys(store.getState().paneForegroundAgentByPaneKey)).toEqual(['tab-10:leaf-1'])
})
it('sweeps every tab of a worktree on wholesale teardown', () => {
const store = createTestStore()
store.setState({
tabsByWorktree: {
'wt-1': [terminalTab('tab-1', 'wt-1'), terminalTab('tab-2', 'wt-1')],
'wt-2': [terminalTab('tab-3', 'wt-2')]
}
})
store
.getState()
.setPaneForegroundAgent('tab-1:leaf-1', { agent: 'aider', shellForeground: false })
store
.getState()
.setPaneForegroundAgent('tab-2:leaf-1', { agent: null, shellForeground: true })
store
.getState()
.setPaneForegroundAgent('tab-3:leaf-1', { agent: 'codex', shellForeground: false })
const before = store.getState().paneForegroundAgentByPaneKey
store.getState().clearPaneForegroundAgentByWorktree('wt-missing')
expect(store.getState().paneForegroundAgentByPaneKey).toBe(before)
store.getState().clearPaneForegroundAgentByWorktree('wt-1')
expect(Object.keys(store.getState().paneForegroundAgentByPaneKey)).toEqual(['tab-3:leaf-1'])
})
})
}
@@ -1,153 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types'
import { buildHydratedTabState } from './tabs-hydration'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('@/runtime/sync-runtime-graph', () => ({
scheduleRuntimeGraphSync: vi.fn()
}))
vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({
registerEagerPtyBuffer: vi.fn(),
ensurePtyDispatcher: vi.fn()
}))
const apiProxy = (): unknown =>
new Proxy(() => undefined, {
get: (_target, prop) => (prop === 'then' ? undefined : apiProxy()),
apply: () => Promise.resolve(null)
})
// @ts-expect-error -- mocked browser preload API
globalThis.window = { api: apiProxy() }
import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers'
const BAD_TAB_ID = 'host-tab::11111111-1111-4111-8111-111111111111'
const GOOD_TAB_ID = 'terminal-good'
const WORKTREE_ID = 'repo1::/wt-1'
function makeBaseSession(): WorkspaceSessionState {
return {
activeRepoId: null,
activeWorktreeId: null,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {}
}
}
describe('terminal tab id hydration', () => {
it('drops unified terminal tabs whose IDs cannot form pane keys', () => {
const session: WorkspaceSessionState = {
...makeBaseSession(),
unifiedTabs: {
w1: [
{
id: BAD_TAB_ID,
entityId: BAD_TAB_ID,
groupId: 'g1',
worktreeId: 'w1',
contentType: 'terminal',
label: 'Bad remote terminal',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
},
{
id: GOOD_TAB_ID,
entityId: GOOD_TAB_ID,
groupId: 'g1',
worktreeId: 'w1',
contentType: 'terminal',
label: 'Good terminal',
customLabel: null,
color: null,
sortOrder: 1,
createdAt: 2
}
]
},
tabGroups: {
w1: [
{
id: 'g1',
worktreeId: 'w1',
activeTabId: BAD_TAB_ID,
tabOrder: [BAD_TAB_ID, GOOD_TAB_ID]
}
]
}
}
const result = buildHydratedTabState(session, new Set(['w1']))
expect(result.unifiedTabsByWorktree.w1.map((tab) => tab.id)).toEqual([GOOD_TAB_ID])
expect(result.groupsByWorktree.w1[0]).toMatchObject({
activeTabId: null,
tabOrder: [GOOD_TAB_ID]
})
})
it('drops runtime terminal state whose IDs cannot form pane keys', () => {
const store = createTestStore()
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: WORKTREE_ID,
activeTabId: BAD_TAB_ID,
tabsByWorktree: {
[WORKTREE_ID]: [
makeTab({ id: BAD_TAB_ID, worktreeId: WORKTREE_ID, ptyId: 'bad-pty', sortOrder: 0 }),
makeTab({ id: GOOD_TAB_ID, worktreeId: WORKTREE_ID, ptyId: 'good-pty', sortOrder: 1 })
]
},
terminalLayoutsByTabId: {
[BAD_TAB_ID]: makeLayout(),
[GOOD_TAB_ID]: makeLayout()
},
activeTabIdByWorktree: {
[WORKTREE_ID]: BAD_TAB_ID
},
remoteSessionIdsByTabId: {
[BAD_TAB_ID]: 'bad-remote',
[GOOD_TAB_ID]: 'good-remote'
},
activeWorktreeIdsOnShutdown: [WORKTREE_ID]
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().tabsByWorktree[WORKTREE_ID].map((tab) => tab.id)).toEqual([GOOD_TAB_ID])
expect(store.getState().activeTabId).toBeNull()
expect(store.getState().activeTabIdByWorktree[WORKTREE_ID]).toBeUndefined()
expect(store.getState().terminalLayoutsByTabId[BAD_TAB_ID]).toBeUndefined()
expect(store.getState().terminalLayoutsByTabId[GOOD_TAB_ID]).toBeDefined()
expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({
[GOOD_TAB_ID]: 'good-remote'
})
})
it('does not turn a rejected terminal row into an explicit-empty tombstone', () => {
const store = createTestStore()
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/wt-1' })]
}
})
store.getState().hydrateWorkspaceSession({
...makeBaseSession(),
tabsByWorktree: {
[WORKTREE_ID]: [makeTab({ id: BAD_TAB_ID, worktreeId: WORKTREE_ID })]
}
})
expect(Object.hasOwn(store.getState().tabsByWorktree, WORKTREE_ID)).toBe(false)
})
})
@@ -103,31 +103,6 @@ describe('terminal tab owner index', () => {
expect(bucketVisits).toBe(0)
})
it('replaces the topology on hydration across every workspace key kind', () => {
const index = createTerminalTabOwnerIndex()
index.getOwners({ stale: [{ id: 'stale-tab' }] })
const hydrated = {
'repo-local::/Users/me/project': [{ id: 'local-tab' }],
'folder:folder-workspace-id': [{ id: 'folder-tab' }],
'repo-ssh::/srv/project': [{ id: 'ssh-tab' }],
'repo-wsl::\\\\wsl.localhost\\Ubuntu\\home\\me\\project': [{ id: 'wsl-tab' }],
'worktree:repo-runtime::/workspace::workspace:paired-runtime-id': [
{ id: 'paired-runtime-tab' }
]
}
const owners = index.getOwners(hydrated)
expect(Object.fromEntries(owners)).toEqual({
'local-tab': 'repo-local::/Users/me/project',
'folder-tab': 'folder:folder-workspace-id',
'ssh-tab': 'repo-ssh::/srv/project',
'wsl-tab': 'repo-wsl::\\\\wsl.localhost\\Ubuntu\\home\\me\\project',
'paired-runtime-tab': 'worktree:repo-runtime::/workspace::workspace:paired-runtime-id'
})
expect(owners.has('stale-tab')).toBe(false)
})
it('preserves last-wins object order for duplicate ids when only outer keys reorder', () => {
let idReads = 0
const firstBucket = [
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createTestStore, makeWorktree, seedStore } from './store-test-helpers'
import { isTerminalTabPresent } from './terminal-tab-retirement'
import './terminal-tab-retirement'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants'
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
import { createStoreSessionMockApi } from './store-session-test-harness'
@@ -26,99 +26,6 @@ function seedWorktreeWithTab(store: ReturnType<typeof createTestStore>): string
return store.getState().createTab(WORKTREE_ID).id
}
describe('remountTerminalTabForRecovery', () => {
it('bumps the tab generation so TerminalPane remounts', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
const before = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === tabId)
const remounted = store.getState().remountTerminalTabForRecovery(tabId)
expect(remounted.remounted).toBe(true)
const after = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === tabId)
expect(after?.generation ?? 0).toBe((before?.generation ?? 0) + 1)
// Recovery is not user interaction — the remount's PTY updates must not
// reshuffle Recent, mirroring the activation-time generation bump.
expect(after?.pendingActivationSpawn).toBeTruthy()
})
it('gives a remounted pane a distinct queued startup owner', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
const startup = { command: 'echo recover' }
store.getState().queueTabStartupCommand(tabId, startup)
const before = store.getState().pendingStartupByTabId[tabId]
expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(true)
const after = store.getState().pendingStartupByTabId[tabId]
expect(after).toEqual(before)
expect(after).not.toBe(before)
})
it('leaves sibling tabs untouched', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
const siblingId = store.getState().createTab(WORKTREE_ID).id
store.getState().remountTerminalTabForRecovery(tabId)
const sibling = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === siblingId)
expect(sibling?.generation ?? 0).toBe(0)
expect(sibling?.pendingActivationSpawn).toBeFalsy()
})
it('returns false when the tab no longer exists', () => {
const store = createTestStore()
seedWorktreeWithTab(store)
expect(store.getState().remountTerminalTabForRecovery('missing-tab')).toEqual({
remounted: false,
declinedBy: 'tab-missing'
})
})
})
// Recovery budget must follow the terminal-row index; temporary unified-index absence previously released the budget on every remount (b5cfc6ca).
describe('isTerminalTabPresent as the recovery existence check', () => {
it('answers true for a tab remountTerminalTabForRecovery can still remount', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
expect(isTerminalTabPresent(store.getState(), tabId)).toBe(true)
expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(true)
})
it('stays true when the tab is missing from the unified tab index', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
store.setState({ unifiedTabsByWorktree: {} })
expect(store.getState().getTab(tabId)).toBeNull()
expect(isTerminalTabPresent(store.getState(), tabId)).toBe(true)
})
it('answers false once the tab leaves the remount index', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
store.setState({ tabsByWorktree: { [WORKTREE_ID]: [] } })
expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false)
expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(false)
})
// The budget release still has to fire for a real close, or a closed tab's
// timestamps and pending retry outlive it.
it('answers false after a genuine closeTab', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
store.getState().closeTab(tabId)
expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false)
})
})
// Recovery ledger follows tab rows across worktree, folder and floating buckets; no repository-only lookup may strand it.
describe.each([
['a repository worktree', WORKTREE_ID],
@@ -168,42 +75,10 @@ describe.each([
.remounted
).toBe(true)
})
it('drops the ledger with the row when the tab closes', () => {
const store = createTestStore()
const tabId = seedBucket(store)
store.getState().remountTerminalTabForRecovery(tabId, AUTOMATIC)
store.getState().closeTab(tabId)
expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false)
expect(store.getState().tabsByWorktree[bucketId]?.some((tab) => tab.id === tabId)).toBeFalsy()
})
})
// Pane mount snapshots startup commands once; recovery must retain queued commands until owning-pane spawn or leave quick commands at a bare prompt (STA-4876).
describe('queued startup command retention', () => {
it('survives a recovery remount so the next mount can still deliver it', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
store.getState().queueTabStartupCommand(tabId, { command: 'echo hi' })
store.getState().remountTerminalTabForRecovery(tabId)
expect(store.getState().pendingStartupByTabId[tabId]).toEqual({ command: 'echo hi' })
})
// Commands are tab-scoped but binds are pane-scoped; a sibling’s earlier bind must not consume the owner’s remount command.
it('is not spent by a sibling pane binding a pty to the same tab', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
store.getState().queueTabStartupCommand(tabId, { command: 'echo hi' })
store.getState().updateTabPtyId(tabId, 'pty-sibling')
expect(store.getState().pendingStartupByTabId[tabId]).toEqual({ command: 'echo hi' })
})
// Only the owning pane spends it, via this action, once its own fresh spawn exists.
it('is spent through consumeTabStartupCommand and does not replay afterwards', () => {
const store = createTestStore()
@@ -216,27 +91,4 @@ describe('queued startup command retention', () => {
expect(store.getState().pendingStartupByTabId[tabId]).toBeUndefined()
expect(store.getState().consumeTabStartupCommand(tabId)).toBeNull()
})
// Why: retention is bounded by tab lifetime, so a spawn that never binds cannot leak forever.
it('is dropped when the tab closes without ever spawning', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
store.getState().queueTabStartupCommand(tabId, { command: 'echo hi' })
store.getState().closeTab(tabId)
expect(store.getState().pendingStartupByTabId[tabId]).toBeUndefined()
})
it('leaves a sibling tab’s queued command alone', () => {
const store = createTestStore()
const tabId = seedWorktreeWithTab(store)
const siblingId = store.getState().createTab(WORKTREE_ID).id
store.getState().queueTabStartupCommand(tabId, { command: 'echo mine' })
store.getState().queueTabStartupCommand(siblingId, { command: 'echo theirs' })
store.getState().consumeTabStartupCommand(tabId)
expect(store.getState().pendingStartupByTabId[siblingId]).toEqual({ command: 'echo theirs' })
})
})
@@ -145,30 +145,6 @@ describe('terminal tab retirement store boundary', () => {
expect(mockKill).not.toHaveBeenCalled()
})
it('preserves shared-owner snapshots while closing the source tab', async () => {
const store = createRetirementStore()
const snapshot = { snapshot: 'shared snapshot' }
const coldRestore = { scrollback: 'shared scrollback', cwd: 'C:\\workspace' }
seedStore(store, {
tabsByWorktree: {
'wt-1': [
makeTab({ id: 'tab-1', worktreeId: 'wt-1', ptyId: 'pty-shared' }),
makeTab({ id: 'tab-2', worktreeId: 'wt-1', ptyId: 'pty-shared' })
]
},
ptyIdsByTabId: { 'tab-1': ['pty-shared'], 'tab-2': ['pty-shared'] },
pendingSnapshotByPtyId: { 'pty-shared': snapshot },
pendingColdRestoreByPtyId: { 'pty-shared': coldRestore }
})
store.getState().closeTab('tab-1')
await Promise.resolve()
expect(mockKill).not.toHaveBeenCalled()
expect(store.getState().pendingSnapshotByPtyId['pty-shared']).toBe(snapshot)
expect(store.getState().pendingColdRestoreByPtyId['pty-shared']).toBe(coldRestore)
})
it('reconciles natural exit without issuing teardown or revoking resume authority', async () => {
const store = createRetirementStore()
const record = sleepingRecord('tab-1:leaf-1', 'tab-1')
@@ -188,15 +164,6 @@ describe('terminal tab retirement store boundary', () => {
expect(store.getState().sleepingAgentSessionsByPaneKey['tab-1:leaf-1']).toBe(record)
})
it('does not recreate PTY indexes for a tab that no longer exists', () => {
const store = createRetirementStore()
store.getState().updateTabPtyId('closed-tab', 'pty-after-close')
expect(store.getState().ptyIdsByTabId['closed-tab']).toBeUndefined()
expect(store.getState().lastKnownRelayPtyIdByTabId['closed-tab']).toBeUndefined()
})
it('retires a unified-only terminal instead of removing only its wrapper', async () => {
const store = createRetirementStore()
const unified = makeUnifiedTab({
@@ -228,22 +195,6 @@ describe('terminal tab retirement store boundary', () => {
expect(store.getState().ptyIdsByTabId['terminal-tab-1']).toBeUndefined()
})
it('lets a paired host own runtime teardown while pruning local state', async () => {
const store = createRetirementStore()
seedStore(store, {
tabsByWorktree: {
'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', ptyId: 'remote:terminal-1' })]
},
ptyIdsByTabId: { 'tab-1': ['remote:terminal-1'] }
})
store.getState().closeTab('tab-1', { remoteCloseOwnedByHost: true })
await Promise.resolve()
expect(mockRuntimeCall).not.toHaveBeenCalled()
expect(store.getState().tabsByWorktree['wt-1']).toEqual([])
})
it('retires parked ownership before teardown and sweeps published state before unified close', () => {
const store = createRetirementStore()
const events: string[] = []
@@ -326,28 +277,4 @@ describe('terminal tab retirement store boundary', () => {
)
warn.mockRestore()
})
it('keeps the tab retired and reports provider rejection without an unhandled promise', async () => {
const store = createRetirementStore()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
mockKill.mockRejectedValueOnce(new Error('provider unavailable'))
seedStore(store, {
tabsByWorktree: {
'wt-1': [makeTab({ id: 'tab-1', worktreeId: 'wt-1', ptyId: 'pty-1' })]
},
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
})
store.getState().closeTab('tab-1')
await vi.waitFor(() =>
expect(warn).toHaveBeenCalledWith('[terminal-retirement] provider teardown failed', {
tabId: 'tab-1',
localOrSshFailures: 1,
runtimeFailures: 0
})
)
expect(store.getState().tabsByWorktree['wt-1']).toEqual([])
warn.mockRestore()
})
})
@@ -1,15 +1,11 @@
import { describe, expect, it } from 'vitest'
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { TerminalTab } from '../../../../shared/terminal-tab-types'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants'
import { brandEphemeralSetupTerminalWorktreeId } from '../../../../shared/ephemeral-setup-terminal-worktree-id'
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
import {
buildTerminalTabRetirementPlan,
buildTerminalTabRetirementPlans,
isTerminalTabPresent,
removeSleepingAgentSessionsForTab
} from './terminal-tab-retirement'
import '../../../../shared/constants'
import '../../../../shared/ephemeral-setup-terminal-worktree-id'
import '../../../../shared/workspace-scope'
import type { buildTerminalTabRetirementPlan } from './terminal-tab-retirement'
import { buildTerminalTabRetirementPlans } from './terminal-tab-retirement'
type RetirementState = Parameters<typeof buildTerminalTabRetirementPlan>[0]
@@ -45,390 +41,7 @@ function makeState(overrides: Partial<RetirementState> = {}): RetirementState {
}
}
function makeSleepingRecord(paneKey: string, tabId?: string): SleepingAgentSessionRecord {
return {
paneKey,
tabId,
worktreeId: 'wt-1',
agent: 'codex',
providerSession: { key: 'session_id', id: paneKey },
prompt: 'continue',
state: 'working',
capturedAt: 1,
updatedAt: 1
}
}
describe('terminal tab retirement planning', () => {
it('collects and deduplicates every ownership source before routing providers', () => {
const state = makeState({
tabsByWorktree: {
'wt-1': [makeTab('tab-1', 'wt-1', 'pty-row')]
},
ptyIdsByTabId: { 'tab-1': ['pty-index', 'pty-row'] },
terminalLayoutsByTabId: {
'tab-1': {
root: null,
activeLeafId: null,
expandedLeafId: null,
ptyIdsByLeafId: {
leaf1: 'pty-layout',
leaf2: 'remote:env-1@@terminal-1'
}
}
},
lastKnownRelayPtyIdByTabId: { 'tab-1': 'ssh:ssh-1@@relay-pty' },
deferredSshSessionIdsByTabId: { 'tab-1': 'pty-deferred' },
pendingReconnectPtyIdByTabId: { 'tab-1': 'pty-pending' }
})
expect(buildTerminalTabRetirementPlan(state, 'tab-1')).toEqual({
tabId: 'tab-1',
worktreeId: 'wt-1',
ptyIds: [
'pty-index',
'pty-row',
'pty-layout',
'remote:env-1@@terminal-1',
'ssh:ssh-1@@relay-pty',
'pty-deferred',
'pty-pending'
],
localOrSshPtyIds: [
'pty-index',
'pty-row',
'pty-layout',
'ssh:ssh-1@@relay-pty',
'pty-deferred',
'pty-pending'
],
runtimeTerminals: [
{
ptyId: 'remote:env-1@@terminal-1',
environmentId: 'env-1',
handle: 'terminal-1'
}
],
cleanupOnlyPtyIds: [],
sharedPtyIds: [],
unroutablePtyIds: []
})
expect(isTerminalTabPresent(state, 'tab-1')).toBe(true)
})
it('recognizes a tab after it is rehomed into a new worktree bucket', () => {
const state = makeState({
tabsByWorktree: {
'wt-old': [],
'wt-new': [makeTab('tab-rehomed', 'wt-new', null)]
}
})
expect(isTerminalTabPresent(state, 'tab-rehomed')).toBe(true)
})
it('does not retire a PTY still referenced by another live surface', () => {
const shared = 'pty-in-transfer'
const state = makeState({
tabsByWorktree: {
'wt-1': [makeTab('tab-1', 'wt-1', shared), makeTab('tab-2', 'wt-1', null)]
},
ptyIdsByTabId: { 'tab-1': [shared], 'tab-2': [shared] },
terminalLayoutsByTabId: {
'tab-2': {
root: null,
activeLeafId: null,
expandedLeafId: null,
ptyIdsByLeafId: { leaf2: shared }
}
}
})
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.sharedPtyIds).toEqual([shared])
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.runtimeTerminals).toEqual([])
})
it('protects a scoped runtime terminal referenced through its legacy alias', () => {
const scoped = 'remote:env-1@@terminal-1'
const legacy = 'remote:terminal-1'
const state = makeState({
settings: { activeRuntimeEnvironmentId: 'env-1' },
worktreesByRepo: {
repo: [
{ id: 'wt-1', repoId: 'repo', hostId: 'runtime:env-1' },
{ id: 'wt-2', repoId: 'repo', hostId: 'runtime:env-1' }
]
},
tabsByWorktree: {
'wt-1': [makeTab('tab-1', 'wt-1', legacy)],
'wt-2': [makeTab('tab-2', 'wt-2', scoped)]
},
ptyIdsByTabId: { 'tab-1': [legacy], 'tab-2': [scoped] }
})
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.sharedPtyIds).toEqual([legacy])
expect(plan.runtimeTerminals).toEqual([])
})
it('deduplicates legacy and scoped aliases owned by the closing tab', () => {
const state = makeState({
settings: { activeRuntimeEnvironmentId: 'env-1' },
worktreesByRepo: { repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'runtime:env-1' }] },
tabsByWorktree: {
'wt-1': [makeTab('tab-1', 'wt-1', 'remote:terminal-1')]
},
ptyIdsByTabId: {
'tab-1': ['remote:terminal-1', 'remote:env-1@@terminal-1']
}
})
expect(buildTerminalTabRetirementPlan(state, 'tab-1').runtimeTerminals).toEqual([
{
ptyId: 'remote:terminal-1',
environmentId: null,
handle: 'terminal-1'
}
])
})
describe('legacy runtime ids in a local twin of a server', () => {
const TWIN = 'twin-repo::/w'
const legacy = 'remote:terminal-1'
const twinRows = {
repos: [
{ id: 'twin-repo', executionHostId: 'local' as const },
{ id: 'twin-repo', executionHostId: 'runtime:env-b' as const },
{ id: 'repo', executionHostId: 'local' as const }
],
worktreesByRepo: {
'twin-repo': [
{ id: TWIN, repoId: 'twin-repo', hostId: 'local' as const },
{
id: TWIN,
repoId: 'twin-repo',
hostId: 'runtime:env-b' as const,
runtimeOwnerEnvironmentId: 'env-b'
}
],
repo: [{ id: 'wt-1', repoId: 'repo', hostId: 'local' as const }]
}
}
it("does not merge a twin's legacy id with the same id on another host", () => {
const state = makeState({
...twinRows,
tabsByWorktree: {
[TWIN]: [makeTab('tab-twin', TWIN, legacy)],
'wt-1': [makeTab('tab-local', 'wt-1', legacy)]
},
ptyIdsByTabId: { 'tab-twin': [legacy], 'tab-local': [legacy] }
})
expect(buildTerminalTabRetirementPlan(state, 'tab-local').sharedPtyIds).toEqual([])
expect(buildTerminalTabRetirementPlan(state, 'tab-twin').sharedPtyIds).toEqual([])
})
it("still protects a twin's legacy id held by a second tab of the same twin", () => {
const state = makeState({
...twinRows,
tabsByWorktree: {
[TWIN]: [makeTab('tab-a', TWIN, legacy), makeTab('tab-b', TWIN, legacy)]
},
ptyIdsByTabId: { 'tab-a': [legacy], 'tab-b': [legacy] }
})
expect(buildTerminalTabRetirementPlan(state, 'tab-a').sharedPtyIds).toEqual([legacy])
})
})
it('ignores stale ownership maps and never routes malformed remote ids locally', () => {
const malformedRemote = 'remote:'
const state = makeState({
tabsByWorktree: {
'wt-1': [makeTab('tab-1', 'wt-1', malformedRemote)]
},
ptyIdsByTabId: {
'tab-1': [malformedRemote, 'pty-live'],
'stale-tab': ['pty-live']
}
})
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.unroutablePtyIds).toEqual([malformedRemote])
expect(plan.localOrSshPtyIds).toEqual(['pty-live'])
expect(plan.sharedPtyIds).toEqual([])
})
it('never kills a HUB-native PTY when duplicate worktree ownership is ambiguous', () => {
const state = makeState({
worktreesByRepo: {
repo: [
{ id: 'wt-1', repoId: 'repo', hostId: 'ssh:private', runtimeOwnerEnvironmentId: 'hub-a' },
{ id: 'wt-1', repoId: 'repo', hostId: 'ssh:private', runtimeOwnerEnvironmentId: 'hub-b' }
]
},
tabsByWorktree: {
'wt-1': [makeTab('tab-1', 'wt-1', 'ssh:private@@pty-1')]
}
})
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.runtimeTerminals).toEqual([])
expect(plan.unroutablePtyIds).toEqual(['ssh:private@@pty-1'])
})
it('never falls an unknown stale worktree through to local PTY teardown', () => {
const state = makeState({
worktreesByRepo: {},
tabsByWorktree: {
'stale-worktree': [makeTab('tab-1', 'stale-worktree', 'ssh:private@@pty-1')]
}
})
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.unroutablePtyIds).toEqual(['ssh:private@@pty-1'])
})
// Ownerless host-agnostic surfaces still own local PTYs; teardown previously dropped them without killing (STA-2639).
describe('host-agnostic terminal surfaces are killed, not dropped', () => {
const localSurfaces: [string, string][] = [
['floating terminal', FLOATING_TERMINAL_WORKTREE_ID],
['ephemeral setup terminal', brandEphemeralSetupTerminalWorktreeId('panel-1')],
['folder workspace', folderWorkspaceKey('fw-1')]
]
for (const [label, worktreeId] of localSurfaces) {
it(`kills a local ${label} PTY while a runtime is focused`, () => {
// Runtime focus changes during catalog hydration; it cannot retarget teardown of local surfaces.
const state = makeState({
settings: { activeRuntimeEnvironmentId: 'hub-a' },
runtimeEnvironments: [{ id: 'hub-a' }],
folderWorkspaces: [{ id: 'fw-1', projectGroupId: 'pg-1', connectionId: null }],
projectGroups: [{ id: 'pg-1', connectionId: null, executionHostId: null }],
tabsByWorktree: { [worktreeId]: [makeTab('tab-1', worktreeId, 'pty-1')] }
} as unknown as Partial<RetirementState>)
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual(['pty-1'])
expect(plan.unroutablePtyIds).toEqual([])
})
}
it('closes a runtime-hosted floating terminal over RPC instead of killing it locally', () => {
const state = makeState({
settings: { activeRuntimeEnvironmentId: 'hub-a' },
runtimeEnvironments: [{ id: 'hub-a' }],
tabsByWorktree: {
[FLOATING_TERMINAL_WORKTREE_ID]: [
makeTab('tab-1', FLOATING_TERMINAL_WORKTREE_ID, 'remote:hub-a@@handle-1')
]
}
} as unknown as Partial<RetirementState>)
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.runtimeTerminals).toEqual([
{ ptyId: 'remote:hub-a@@handle-1', environmentId: 'hub-a', handle: 'handle-1' }
])
})
it('never kills a HUB-owned folder workspace PTY', () => {
const state = makeState({
folderWorkspaces: [{ id: 'fw-1', projectGroupId: 'pg-1', connectionId: null }],
projectGroups: [{ id: 'pg-1', connectionId: null, executionHostId: 'runtime:hub-a' }],
tabsByWorktree: {
[folderWorkspaceKey('fw-1')]: [makeTab('tab-1', folderWorkspaceKey('fw-1'), 'pty-hub')]
}
} as unknown as Partial<RetirementState>)
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.unroutablePtyIds).toEqual(['pty-hub'])
})
it('never kills a HUB wake hint on a worktree owned only by the focused runtime', () => {
// Ownerless legacy rows may spawn on focused runtime with ssh:-shaped hints; shape alone must not route kill to the wrong host.
const state = makeState({
repos: [{ id: 'repo1', connectionId: null }],
worktreesByRepo: { repo1: [{ id: 'wt-legacy', repoId: 'repo1' }] },
settings: { activeRuntimeEnvironmentId: 'legacy-hub' },
runtimeEnvironments: [{ id: 'legacy-hub' }],
tabsByWorktree: {
'wt-legacy': [makeTab('tab-1', 'wt-legacy', 'ssh:hub-private@@pty-2')]
}
} as unknown as Partial<RetirementState>)
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.unroutablePtyIds).toEqual(['ssh:hub-private@@pty-2'])
})
it('never kills a PTY whose owning tab row is already gone', () => {
// Why: a vanished row is the ambiguity #9994 guards — nothing proves which host holds the PTY.
const state = makeState({ ptyIdsByTabId: { 'tab-1': ['pty-ghost'] } })
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.unroutablePtyIds).toEqual(['pty-ghost'])
})
it('never kills an unknown worktree PTY when every owner catalog is absent', () => {
// Spawn may fall back during catalog hydration; teardown must refuse unknown ownership rather than kill by guess.
const state = makeState({
worktreesByRepo: undefined,
detectedWorktreesByRepo: undefined,
repos: undefined,
tabsByWorktree: { 'wt-unknown': [makeTab('tab-1', 'wt-unknown', 'pty-1')] }
} as unknown as Partial<RetirementState>)
const plan = buildTerminalTabRetirementPlan(state, 'tab-1')
expect(plan.localOrSshPtyIds).toEqual([])
expect(plan.unroutablePtyIds).toEqual(['pty-1'])
})
})
it('deduplicates batch-owned PTYs while protecting owners outside the close set', () => {
const state = makeState({
tabsByWorktree: {
'wt-1': [
makeTab('tab-1', 'wt-1', 'pty-batch'),
makeTab('tab-2', 'wt-1', 'pty-batch'),
makeTab('later-tab', 'wt-1', 'pty-external')
]
},
ptyIdsByTabId: {
'tab-1': ['pty-batch', 'pty-external'],
'tab-2': ['pty-batch'],
'later-tab': ['pty-external']
}
})
const plans = buildTerminalTabRetirementPlans(state, ['tab-1', 'tab-2'])
expect(plans.get('tab-1')).toMatchObject({
localOrSshPtyIds: ['pty-batch'],
sharedPtyIds: ['pty-external']
})
expect(plans.get('tab-2')).toMatchObject({
localOrSshPtyIds: [],
cleanupOnlyPtyIds: ['pty-batch'],
sharedPtyIds: []
})
})
it('indexes live owners once for a 100-tab batch', () => {
const tabs = Array.from({ length: 100 }, (_, index) =>
makeTab(`tab-${index}`, 'wt-1', `pty-${index}`)
@@ -467,19 +80,3 @@ describe('terminal tab retirement planning', () => {
expect(unifiedStoreScans).toBe(1)
})
})
describe('sleeping agent retirement', () => {
it('removes key- and metadata-owned records while preserving siblings by reference', () => {
const sibling = makeSleepingRecord('tab-2:leaf-2', 'tab-2')
const records = {
'tab-1:leaf-1': makeSleepingRecord('tab-1:leaf-1'),
'legacy-pane-key': makeSleepingRecord('legacy-pane-key', 'tab-1'),
'tab-2:leaf-2': sibling
}
const next = removeSleepingAgentSessionsForTab(records, 'tab-1')
expect(next).toEqual({ 'tab-2:leaf-2': sibling })
expect(next['tab-2:leaf-2']).toBe(sibling)
expect(removeSleepingAgentSessionsForTab(next, 'missing-tab')).toBe(next)
})
})
@@ -163,142 +163,6 @@ describe('terminal tab title batches', () => {
expect(store.getState().tabsByWorktree['wt-299']?.[0]?.title).toBe('Second warm title')
})
it('preserves ordered duplicate updates and last-owner duplicate-id routing', () => {
const store = createTestStore()
seedStore(store, {
tabsByWorktree: {
first: [makeTab({ id: 'duplicate-tab', worktreeId: 'first', title: 'First owner' })],
second: [makeTab({ id: 'duplicate-tab', worktreeId: 'second', title: 'Second owner' })]
}
})
store.getState().updateTabTitles([
{ tabId: 'duplicate-tab', title: 'Intermediate' },
{ tabId: 'duplicate-tab', title: 'Final' }
])
expect(store.getState().tabsByWorktree.first?.[0]?.title).toBe('First owner')
expect(store.getState().tabsByWorktree.second?.[0]?.title).toBe('Final')
})
it('updates every same-owner backing duplicate but only the first unified row', async () => {
const store = createTestStore()
seedStore(store, {
settings: { ...getDefaultSettings('/tmp'), tabAutoGenerateTitle: true },
tabsByWorktree: {
owner: [
makeTab({ id: 'duplicate-tab', worktreeId: 'owner', title: 'First backing' }),
makeTab({ id: 'duplicate-tab', worktreeId: 'owner', title: 'Second backing' })
]
},
unifiedTabsByWorktree: {
owner: [
makeUnifiedTab({
id: 'duplicate-tab',
worktreeId: 'owner',
groupId: 'group-1',
label: 'First visible'
}),
makeUnifiedTab({
id: 'duplicate-tab',
worktreeId: 'owner',
groupId: 'group-2',
label: 'Second visible'
})
]
}
})
store.getState().updateTabTitles([{ tabId: 'duplicate-tab', title: 'Final live title' }])
store.getState().setGeneratedTabTitlesFromAgentPrompts([
{
paneKey: makePaneKey('duplicate-tab', LEAF_ID),
prompt: 'Generated duplicate title for remote startup'
}
])
expect(store.getState().tabsByWorktree.owner?.map((tab) => tab.title)).toEqual([
'Final live title',
'Final live title'
])
// The live title is the window's own write in both builds.
expect(store.getState().unifiedTabsByWorktree.owner?.map((tab) => tab.label)).toEqual([
'Final live title',
'Second visible'
])
if (ORCA_LAYOUT_OWNER_IS_MAIN) {
// Main derives the generated title from its own agent status and its frame draws it: the
// window sends and writes none.
await new Promise<void>((resolve) => setTimeout(resolve, 0))
expect(main.commands).toEqual([])
expect(store.getState().tabsByWorktree.owner?.map((tab) => tab.generatedTitle)).toEqual([
undefined,
undefined
])
expect(
store.getState().unifiedTabsByWorktree.owner?.map((tab) => tab.generatedLabel)
).toEqual([undefined, undefined])
return
}
expect(store.getState().tabsByWorktree.owner?.map((tab) => tab.generatedTitle)).toEqual([
'Generated duplicate title for remote',
'Generated duplicate title for remote'
])
expect(store.getState().unifiedTabsByWorktree.owner?.map((tab) => tab.generatedLabel)).toEqual([
'Generated duplicate title for remote',
undefined
])
})
it('matches sequential live and generated title semantics in event order', () => {
const sequentialStore = createTestStore()
const batchStore = createTestStore()
const fixture = {
settings: { ...getDefaultSettings('/tmp'), tabAutoGenerateTitle: true },
tabsByWorktree: {
owner: [makeTab({ id: 'tab-1', worktreeId: 'owner', title: 'Terminal 1' })]
},
unifiedTabsByWorktree: {
owner: [makeUnifiedTab({ id: 'tab-1', worktreeId: 'owner', groupId: 'group-1' })]
}
}
seedStore(sequentialStore, structuredClone(fixture))
seedStore(batchStore, structuredClone(fixture))
const liveUpdates = [
{ tabId: 'tab-1', title: 'Codex' },
{ tabId: 'tab-1', title: '⠋ Codex is thinking' },
{ tabId: 'tab-1', title: '⠙ Codex is thinking' },
{ tabId: 'tab-1', title: '' },
{ tabId: 'tab-1', title: 'Final stable title' }
]
const generatedUpdates = [
{ paneKey: makePaneKey('tab-1', LEAF_ID), prompt: 'First generated title wins here' },
{ paneKey: makePaneKey('tab-1', LEAF_ID), prompt: 'Ignored later generated title' },
{
paneKey: makePaneKey('tab-1', LEAF_ID),
prompt: 'Forced replacement generated title',
options: { replaceExistingGeneratedTitle: true }
}
]
for (const update of liveUpdates) {
sequentialStore.getState().updateTabTitle(update.tabId, update.title)
}
for (const update of generatedUpdates) {
sequentialStore
.getState()
.setGeneratedTabTitleFromAgentPrompt(update.paneKey, update.prompt, update.options)
}
batchStore.getState().updateTabTitles(liveUpdates)
batchStore.getState().setGeneratedTabTitlesFromAgentPrompts(generatedUpdates)
expect(batchStore.getState().tabsByWorktree).toEqual(sequentialStore.getState().tabsByWorktree)
expect(batchStore.getState().unifiedTabsByWorktree).toEqual(
sequentialStore.getState().unifiedTabsByWorktree
)
expect(batchStore.getState().sortEpoch).toBe(sequentialStore.getState().sortEpoch)
})
it('coalesces generated titles while preserving first-write and replacement semantics', async () => {
const store = createTestStore()
const fixture = makeScaleState(100)
@@ -1,82 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
import { createTestStore, makeWorktree, seedStore } from './store-test-helpers'
import { shouldAutoCreateInitialTerminal } from '@/components/terminal/initial-terminal'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
vi.mock('@/runtime/sync-runtime-graph', () => ({ scheduleRuntimeGraphSync: vi.fn() }))
vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({
registerEagerPtyBuffer: vi.fn(),
ensurePtyDispatcher: vi.fn()
}))
// @ts-expect-error -- hydration does not call the mocked preload surface.
globalThis.window = { api: {} }
describe('explicit empty terminal hydration', () => {
it('preserves a git worktree terminal tombstone', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
store.getState().hydrateWorkspaceSession({
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
tabsByWorktree: { [worktreeId]: [] }
})
expect(store.getState().tabsByWorktree).toEqual({ [worktreeId]: [] })
})
it('preserves a folder workspace terminal tombstone', () => {
const store = createTestStore()
const workspaceKey = folderWorkspaceKey('folder-1')
store.getState().hydrateWorkspaceSession(
{
...getDefaultWorkspaceSession(),
activeWorkspaceKey: workspaceKey,
activeWorktreeId: workspaceKey,
tabsByWorktree: { [workspaceKey]: [] }
},
{ additionalValidWorkspaceKeys: [workspaceKey] }
)
expect(store.getState().tabsByWorktree).toEqual({ [workspaceKey]: [] })
})
})
// Hydrated explicit-empty workspaces must suppress passive terminal creation (#15513); mirror terminal-tab-close-restart-persistence.spec.ts’s decision locally.
describe('hydrated active workspace with a terminal tombstone', () => {
it('reports no auto-create for the restored active worktree', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
store.getState().hydrateWorkspaceSession({
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
tabsByWorktree: { [worktreeId]: [] }
})
const state = store.getState()
expect(state.activeWorktreeId).toBe(worktreeId)
expect(state.tabsByWorktree[worktreeId]).toEqual([])
const { renderableTabCount } = state.reconcileWorktreeTabModel(worktreeId)
// The exact inputs Terminal.tsx's auto-create effect feeds shouldAutoCreateInitialTerminal.
expect(renderableTabCount).toBe(0)
expect(Object.hasOwn(state.tabsByWorktree, worktreeId)).toBe(true)
expect(shouldAutoCreateInitialTerminal(renderableTabCount, true)).toBe(false)
})
})
@@ -2,12 +2,12 @@
import './terminal-hydration-store-test-bootstrap'
import { describe, expect, it, vi } from 'vitest'
import { getOrphanTerminalIds } from './terminal-orphan-helpers'
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { Tab } from '../../../../shared/tab-types'
import type { TerminalTab } from '../../../../shared/terminal-tab-types'
import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types'
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
import { buildWorkspaceSessionPayload } from '@/lib/workspace-session'
import '@/lib/workspace-session'
import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
@@ -67,20 +67,6 @@ function makeSession(args: {
}
}
function makeSleepingRecord(paneKey: string, tabId: string): SleepingAgentSessionRecord {
return {
paneKey,
tabId,
worktreeId: WORKTREE_ID,
agent: 'claude',
providerSession: { key: 'session_id', id: `session-${paneKey}` },
prompt: '',
state: 'waiting',
capturedAt: 1,
updatedAt: 1
}
}
function hydrate(session: WorkspaceSessionState): ReturnType<typeof createTestStore> {
const store = createTestStore()
seedStore(store, {
@@ -94,166 +80,6 @@ function hydrate(session: WorkspaceSessionState): ReturnType<typeof createTestSt
}
describe('hydrateWorkspaceSession canonical PTY overlap', () => {
it('keeps the valid local row when an invalid-id canonical mirror shares its PTY', () => {
const sharedPtyId = 'daemon-session-1'
const mirrorTabId = 'host-tab::11111111-1111-4111-8111-111111111111'
const session = makeSession({
tabs: [
makeTab({ id: mirrorTabId, worktreeId: WORKTREE_ID, ptyId: sharedPtyId }),
makeTab({ id: 'local-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId, sortOrder: 1 })
],
layouts: {
[mirrorTabId]: { ...makeLayout(), ptyIdsByLeafId: { 'mirror-leaf': sharedPtyId } },
'local-tab': { ...makeLayout(), ptyIdsByLeafId: { 'local-leaf': sharedPtyId } }
},
canonicalEntityIds: [mirrorTabId]
})
const state = hydrate(session).getState()
const persisted = buildWorkspaceSessionPayload(state)
expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual(['local-tab'])
expect(state.pendingReconnectPtyIdByTabId['local-tab']).toBe(sharedPtyId)
expect(persisted.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual(['local-tab'])
expect(persisted.terminalLayoutsByTabId[mirrorTabId]).toBeUndefined()
})
it('keeps a legacy split tab whose second pane owns an independent PTY', () => {
const sharedPtyId = 'daemon-shared'
const soloPtyId = 'daemon-solo'
const session = makeSession({
tabs: [
makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }),
makeTab({ id: 'split-tab', worktreeId: WORKTREE_ID, ptyId: soloPtyId, sortOrder: 1 })
],
layouts: {
'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } },
'split-tab': {
root: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: 'leaf-a' },
second: { type: 'leaf', leafId: 'leaf-b' }
},
activeLeafId: 'leaf-a',
expandedLeafId: null,
ptyIdsByLeafId: { 'leaf-a': sharedPtyId, 'leaf-b': soloPtyId }
}
},
canonicalEntityIds: ['canonical-tab']
})
const state = hydrate(session).getState()
const persisted = buildWorkspaceSessionPayload(state)
expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'split-tab'
])
expect(state.pendingReconnectPtyIdByTabId['split-tab']).toBe(soloPtyId)
// Why: the split row keeps its own PTY and gives up the one the canonical row owns.
expect(Object.values(state.terminalLayoutsByTabId['split-tab']?.ptyIdsByLeafId ?? {})).toEqual([
soloPtyId
])
expect(persisted.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'split-tab'
])
expect(
Object.values(persisted.terminalLayoutsByTabId['split-tab']?.ptyIdsByLeafId ?? {})
).toEqual([soloPtyId])
})
it('ignores a canonical row’s stale leaf binding when scoring another row’s live PTY', () => {
const canonicalPtyId = 'daemon-canonical'
const livePtyId = 'daemon-live'
const session = makeSession({
tabs: [
makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: canonicalPtyId }),
makeTab({ id: 'live-tab', worktreeId: WORKTREE_ID, ptyId: livePtyId, sortOrder: 1 })
],
layouts: {
// 'ghost-leaf' left the tree but its binding was never pruned, so it must not claim livePtyId.
'canonical-tab': {
root: { type: 'leaf', leafId: 'canonical-leaf' },
activeLeafId: 'canonical-leaf',
expandedLeafId: null,
ptyIdsByLeafId: { 'canonical-leaf': canonicalPtyId, 'ghost-leaf': livePtyId }
},
'live-tab': { ...makeLayout(), ptyIdsByLeafId: { 'live-leaf': livePtyId } }
},
canonicalEntityIds: ['canonical-tab']
})
const state = hydrate(session).getState()
expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'live-tab'
])
expect(state.pendingReconnectPtyIdByTabId['live-tab']).toBe(livePtyId)
})
it('strips a retained row’s stale binding to a PTY the canonical row owns', () => {
const sharedPtyId = 'daemon-shared'
const soloPtyId = 'daemon-solo'
const session = makeSession({
tabs: [
makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }),
makeTab({ id: 'legacy-tab', worktreeId: WORKTREE_ID, ptyId: soloPtyId, sortOrder: 1 })
],
layouts: {
'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } },
'legacy-tab': {
root: { type: 'leaf', leafId: 'leaf-a' },
activeLeafId: 'leaf-a',
expandedLeafId: null,
ptyIdsByLeafId: { 'leaf-a': soloPtyId, 'ghost-leaf': sharedPtyId }
}
},
canonicalEntityIds: ['canonical-tab']
})
const state = hydrate(session).getState()
expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'legacy-tab'
])
// Why: reconnect publishes every recorded leaf PTY, so a leftover binding would re-duplicate ownership.
expect(Object.values(state.terminalLayoutsByTabId['legacy-tab']?.ptyIdsByLeafId ?? {})).toEqual(
[soloPtyId]
)
})
it('ignores a rootless canonical row’s extra bindings when scoring another row’s live PTY', () => {
const canonicalPtyId = 'daemon-canonical'
const livePtyId = 'daemon-live'
const session = makeSession({
tabs: [
makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: canonicalPtyId }),
makeTab({ id: 'live-tab', worktreeId: WORKTREE_ID, ptyId: livePtyId, sortOrder: 1 })
],
layouts: {
// Rootless proves ownership only for a sole off-tree pane; a second never-pruned binding proves nothing.
'canonical-tab': {
...makeLayout(),
ptyIdsByLeafId: { 'canonical-leaf': canonicalPtyId, 'ghost-leaf': livePtyId }
},
'live-tab': { ...makeLayout(), ptyIdsByLeafId: { 'live-leaf': livePtyId } }
},
canonicalEntityIds: ['canonical-tab']
})
const state = hydrate(session).getState()
expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'live-tab'
])
expect(state.pendingReconnectPtyIdByTabId['live-tab']).toBe(livePtyId)
})
it('advertises a retained row’s own PTY after its tab-level id went to the canonical row', async () => {
const sharedPtyId = 'daemon-shared'
const soloPtyId = 'daemon-solo'
@@ -296,64 +122,4 @@ describe('hydrateWorkspaceSession canonical PTY overlap', () => {
// Why: liveness reads ptyIdsByTabId; without this the surviving pane's PTY reads as an orphan until mount.
expect(state.ptyIdsByTabId['split-tab']).toEqual([soloPtyId])
})
it('drops a sleeping agent record on the leaf whose PTY moved to the canonical row', () => {
const sharedPtyId = 'daemon-shared'
const soloPtyId = 'daemon-solo'
const sharedLeafId = '11111111-1111-4111-8111-111111111111'
const soloLeafId = '22222222-2222-4222-8222-222222222222'
const session = {
...makeSession({
tabs: [
makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }),
makeTab({ id: 'split-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId, sortOrder: 1 })
],
layouts: {
'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } },
'split-tab': {
root: {
type: 'split' as const,
direction: 'vertical' as const,
first: { type: 'leaf' as const, leafId: sharedLeafId },
second: { type: 'leaf' as const, leafId: soloLeafId }
},
activeLeafId: sharedLeafId,
expandedLeafId: null,
ptyIdsByLeafId: { [sharedLeafId]: sharedPtyId, [soloLeafId]: soloPtyId }
}
},
canonicalEntityIds: ['canonical-tab']
}),
sleepingAgentSessionsByPaneKey: {
[`split-tab:${sharedLeafId}`]: makeSleepingRecord(`split-tab:${sharedLeafId}`, 'split-tab'),
[`split-tab:${soloLeafId}`]: makeSleepingRecord(`split-tab:${soloLeafId}`, 'split-tab')
}
}
const state = hydrate(session).getState()
expect(Object.keys(state.sleepingAgentSessionsByPaneKey)).toEqual([`split-tab:${soloLeafId}`])
})
it('retains a non-canonical row that owns no PTY at all', () => {
const sharedPtyId = 'daemon-shared'
const session = makeSession({
tabs: [
makeTab({ id: 'canonical-tab', worktreeId: WORKTREE_ID, ptyId: sharedPtyId }),
makeTab({ id: 'empty-tab', worktreeId: WORKTREE_ID, ptyId: null, sortOrder: 1 })
],
layouts: {
'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } },
'empty-tab': makeLayout()
},
canonicalEntityIds: ['canonical-tab']
})
const state = hydrate(session).getState()
expect(state.tabsByWorktree[WORKTREE_ID]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'empty-tab'
])
})
})
@@ -1,6 +1,6 @@
import './terminal-hydration-store-test-bootstrap'
import { describe, expect, it, vi } from 'vitest'
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types'
import { getDefaultWorkspaceSession } from '../../../../shared/constants'
import { buildWorkspaceSessionPayload } from '@/lib/workspace-session'
@@ -121,119 +121,4 @@ describe('hydrateWorkspaceSession canonical terminal rows', () => {
expect(state.activeTabId).toBe('canonical-tab')
expect(state.activeTabIdByWorktree).toEqual({ [worktreeId]: 'canonical-tab' })
})
it('clears sleeping-agent records for subsumed and invalid-id rows only', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
const sharedPtyId = 'daemon-session-1'
const recoveryPtyId = 'daemon-session-2'
const invalidTabId = 'host-tab::11111111-1111-4111-8111-111111111111'
const leafId = '22222222-2222-4222-8222-222222222222'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const makeSleepingRecord = (tabId: string): SleepingAgentSessionRecord => ({
paneKey: `${tabId}:${leafId}`,
tabId,
worktreeId,
agent: 'codex',
providerSession: { key: 'session_id', id: `session-${tabId}` },
prompt: 'continue',
state: 'working',
capturedAt: 1,
updatedAt: 1
})
const session: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeWorktreeIdsOnShutdown: [worktreeId],
tabsByWorktree: {
[worktreeId]: [
makeTab({ id: 'canonical-tab', worktreeId, ptyId: sharedPtyId }),
makeTab({ id: 'stale-tab', worktreeId, ptyId: sharedPtyId }),
makeTab({ id: invalidTabId, worktreeId, ptyId: null }),
makeTab({ id: 'recovery-tab', worktreeId, ptyId: recoveryPtyId })
]
},
terminalLayoutsByTabId: {
'canonical-tab': { ...makeLayout(), ptyIdsByLeafId: { 'canonical-leaf': sharedPtyId } },
'stale-tab': { ...makeLayout(), ptyIdsByLeafId: { 'stale-leaf': sharedPtyId } },
'recovery-tab': { ...makeLayout(), ptyIdsByLeafId: { 'recovery-leaf': recoveryPtyId } }
},
sleepingAgentSessionsByPaneKey: {
[`stale-tab:${leafId}`]: makeSleepingRecord('stale-tab'),
[`${invalidTabId}:${leafId}`]: makeSleepingRecord(invalidTabId),
[`recovery-tab:${leafId}`]: makeSleepingRecord('recovery-tab')
},
unifiedTabs: {
[worktreeId]: [
{
id: 'canonical-unified-tab',
entityId: 'canonical-tab',
groupId: 'group-1',
worktreeId,
contentType: 'terminal',
label: 'Grok',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
},
tabGroups: {
[worktreeId]: [
{
id: 'group-1',
worktreeId,
activeTabId: 'canonical-unified-tab',
tabOrder: ['canonical-unified-tab']
}
]
}
}
store.getState().hydrateWorkspaceSession(session)
const state = store.getState()
expect(state.tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([
'canonical-tab',
'recovery-tab'
])
// Why: both dropped classes keep a valid worktreeId, so only the per-tab sweep can evict them.
expect(Object.keys(state.sleepingAgentSessionsByPaneKey)).toEqual([`recovery-tab:${leafId}`])
})
it('drops stale unverified-loss markers when full hydration removes their rows', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
const retainedTab = makeTab({ id: 'retained-tab', worktreeId, ptyId: null })
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
},
tabsByWorktree: { [worktreeId]: [retainedTab] },
unverifiedPtyLossTabIds: {
[retainedTab.id]: true,
'dropped-tab': true
}
})
store.getState().hydrateWorkspaceSession({
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: retainedTab.id,
tabsByWorktree: { [worktreeId]: [retainedTab] },
terminalLayoutsByTabId: {}
})
expect(store.getState().unverifiedPtyLossTabIds).toEqual({
[retainedTab.id]: true
})
})
})
@@ -91,19 +91,9 @@ const mockApi = {
globalThis.window = { api: mockApi }
import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types'
import {
FLOATING_TERMINAL_WORKTREE_ID,
getDefaultWorkspaceSession
} from '../../../../shared/constants'
import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope'
import {
createTestStore,
makeLayout,
makeTab,
makeWorktree,
seedStore,
TEST_REPO
} from './store-test-helpers'
import '../../../../shared/constants'
import '../../../../shared/workspace-scope'
import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers'
import { canGoBackWorktreeHistory } from './worktree-nav-history'
describe('hydrateWorkspaceSession', () => {
@@ -111,294 +101,6 @@ describe('hydrateWorkspaceSession', () => {
vi.clearAllMocks()
})
it('preserves ptyIdsByLeafId so reconnect can reattach each split-pane leaf', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'old-pty' })]
},
terminalLayoutsByTabId: {
'tab-1': {
...makeLayout(),
ptyIdsByLeafId: { 'pane:1': 'daemon-session-1' },
buffersByLeafId: { 'pane:1': 'buffer' }
}
}
}
store.getState().hydrateWorkspaceSession(session)
// Why: ptyIdsByLeafId holds daemon session IDs that survive restart, letting each split-pane leaf reattach to its own session.
expect(store.getState().terminalLayoutsByTabId['tab-1']).toEqual({
...makeLayout(),
ptyIdsByLeafId: { 'pane:1': 'daemon-session-1' },
buffersByLeafId: { 'pane:1': 'buffer' }
})
})
it('hydrates runtime-owned tabs from host partitions before remote catalogs load', () => {
const store = createTestStore()
const worktreeId = 'remote-repo::/srv/remote-wt'
const session: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeRepoId: 'remote-repo',
activeWorktreeId: worktreeId,
activeTabId: 'remote-tab',
activeWorktreeIdsOnShutdown: [worktreeId],
tabsByWorktree: {
[worktreeId]: [
makeTab({
id: 'remote-tab',
worktreeId,
ptyId: 'remote-session'
})
]
},
remoteSessionIdsByTabId: { 'remote-tab': 'remote-session' }
}
store.getState().hydrateWorkspaceSession(session, {
runtimeHostIdByWorkspaceSessionKey: { [worktreeId]: 'runtime:env-1' }
})
expect(store.getState().tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([
'remote-tab'
])
expect(store.getState().activeWorktreeId).toBe(worktreeId)
expect(store.getState().activeRepoId).toBe('remote-repo')
expect(store.getState().pendingReconnectWorktreeIds).toEqual([worktreeId])
expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({
'remote-tab': 'remote-session'
})
expect(store.getState().repos).toEqual([
expect.objectContaining({
id: 'remote-repo',
executionHostId: 'runtime:env-1'
})
])
expect(store.getState().worktreesByRepo['remote-repo']).toEqual([
expect.objectContaining({
id: worktreeId,
hostId: 'runtime:env-1'
})
])
})
it('strips the synthetic workspace suffix from folder-workspace instance placeholders', () => {
const store = createTestStore()
const workspaceUuid = '123e4567-e89b-12d3-a456-426614174000'
const worktreeId = `folder-repo::/home/user::workspace:${workspaceUuid}`
const session: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeRepoId: 'folder-repo',
activeWorktreeId: worktreeId,
activeTabId: 'folder-tab',
activeWorktreeIdsOnShutdown: [worktreeId],
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'folder-tab', worktreeId, ptyId: 'folder-session' })]
}
}
store.getState().hydrateWorkspaceSession(session, {
runtimeHostIdByWorkspaceSessionKey: {
[worktreeWorkspaceKey(worktreeId)]: 'runtime:env-1'
}
})
// Why: id keeps the ::workspace:<uuid> suffix, but path/displayName must resolve to the real folder so callers don't spawn against a missing cwd.
expect(store.getState().worktreesByRepo['folder-repo']).toEqual([
expect.objectContaining({ id: worktreeId, path: '/home/user', displayName: 'user' })
])
expect(store.getState().repos).toEqual([
expect.objectContaining({ id: 'folder-repo', path: '/home/user' })
])
})
it('avoids duplicate repo placeholders when a same-id local repo is already loaded', () => {
const store = createTestStore()
const worktreeId = 'same-repo::/srv/remote-wt'
store.setState({
repos: [
{
id: 'same-repo',
path: '/Users/me/same-repo',
displayName: 'Same repo',
badgeColor: '#000',
addedAt: 1,
connectionId: null,
executionHostId: 'local'
}
],
worktreesByRepo: {}
})
const session: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeRepoId: 'same-repo',
activeWorktreeId: worktreeId,
activeTabId: 'remote-tab',
activeWorktreeIdsOnShutdown: [worktreeId],
tabsByWorktree: {
[worktreeId]: [
makeTab({
id: 'remote-tab',
worktreeId,
ptyId: 'remote-session'
})
]
}
}
store.getState().hydrateWorkspaceSession(session, {
runtimeHostIdByWorkspaceSessionKey: {
[worktreeWorkspaceKey(worktreeId)]: 'runtime:env-1'
}
})
expect(store.getState().repos.map((repo) => `${repo.id}:${repo.executionHostId}`)).toEqual([
'same-repo:local'
])
expect(store.getState().worktreesByRepo['same-repo']).toEqual([
expect.objectContaining({ id: worktreeId, hostId: 'runtime:env-1' })
])
expect(store.getState().tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([
'remote-tab'
])
})
it('hydrates runtime folder workspace tabs before remote folder catalogs load', () => {
const store = createTestStore()
const folderKey = folderWorkspaceKey('folder-1')
const session: WorkspaceSessionState = {
...getDefaultWorkspaceSession(),
activeWorkspaceKey: folderKey,
activeWorktreeId: folderKey,
activeTabId: 'remote-folder-tab',
activeWorktreeIdsOnShutdown: [folderKey],
tabsByWorktree: {
[folderKey]: [
makeTab({
id: 'remote-folder-tab',
worktreeId: folderKey,
ptyId: 'remote-folder-session'
})
]
},
remoteSessionIdsByTabId: { 'remote-folder-tab': 'remote-folder-session' }
}
store.getState().hydrateWorkspaceSession(session, {
additionalValidWorkspaceKeys: [folderKey],
runtimeHostIdByWorkspaceSessionKey: { [folderKey]: 'runtime:env-1' }
})
expect(store.getState().tabsByWorktree[folderKey]?.map((tab) => tab.id)).toEqual([
'remote-folder-tab'
])
expect(store.getState().activeWorktreeId).toBe(folderKey)
expect(store.getState().activeWorkspaceKey).toBe(folderKey)
expect(store.getState().pendingReconnectWorktreeIds).toEqual([folderKey])
expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({
'remote-folder-tab': 'remote-folder-session'
})
expect(store.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({
[folderKey]: 'runtime:env-1'
})
})
it('moves restored active focus from a dead split leaf to a pty-backed sibling', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
const liveLeftLeafId = '9ee09218-72a5-4e1c-b075-729e937d4e29'
const liveRightLeafId = 'f5fc66b1-ec43-404b-b7b0-a06f0db34940'
const deadActiveLeafId = 'fbf63fd9-34d6-4387-9109-562f7c02bc4c'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'old-pty' })]
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: liveLeftLeafId },
second: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: liveRightLeafId },
second: { type: 'leaf', leafId: deadActiveLeafId }
}
},
activeLeafId: deadActiveLeafId,
expandedLeafId: null,
ptyIdsByLeafId: {
[liveLeftLeafId]: 'daemon-session-left',
[liveRightLeafId]: 'daemon-session-right'
},
buffersByLeafId: {
[deadActiveLeafId]: 'retained scrollback'
}
}
}
}
store.getState().hydrateWorkspaceSession(session)
// Why: restart can preserve scrollback for an exited pane, so focus must land on a live PTY-backed pane, not the dead leaf.
expect(store.getState().terminalLayoutsByTabId['tab-1']?.activeLeafId).toBe(liveLeftLeafId)
})
it('hydrates floating terminal tabs even though they are not repo worktrees', () => {
const store = createTestStore()
const session: WorkspaceSessionState = {
activeRepoId: null,
activeWorktreeId: null,
activeTabId: null,
tabsByWorktree: {
[FLOATING_TERMINAL_WORKTREE_ID]: [
makeTab({
id: 'floating-tab-1',
worktreeId: FLOATING_TERMINAL_WORKTREE_ID,
ptyId: 'floating-pty-1'
})
]
},
terminalLayoutsByTabId: {
'floating-tab-1': makeLayout()
},
activeTabIdByWorktree: {
[FLOATING_TERMINAL_WORKTREE_ID]: 'floating-tab-1'
},
activeWorktreeIdsOnShutdown: [FLOATING_TERMINAL_WORKTREE_ID]
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().tabsByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toHaveLength(1)
expect(store.getState().activeTabIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID]).toBe(
'floating-tab-1'
)
expect(store.getState().pendingReconnectWorktreeIds).toEqual([FLOATING_TERMINAL_WORKTREE_ID])
})
it('batches restored terminal reconnect wake hints into one store update', async () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
@@ -450,252 +152,6 @@ describe('hydrateWorkspaceSession', () => {
])
})
it('stashes deferred SSH session ids for worktrees not yet in worktreesByRepo', async () => {
// Cold-start SSH rows may lack worktree metadata; infer repo from composite ID or restored panes report inactive SSH.
const store = createTestStore()
const worktreeId = 'repo1::/home/user/remote-project'
const sshSessionId = 'ssh:ssh-target-1@@pty-7'
seedStore(store, {
repos: [{ ...TEST_REPO, connectionId: 'ssh-target-1' }],
worktreesByRepo: {}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: null })]
},
terminalLayoutsByTabId: {},
activeWorktreeIdsOnShutdown: [worktreeId],
remoteSessionIdsByTabId: { 'tab-1': sshSessionId }
}
store.getState().hydrateWorkspaceSession(session)
await store.getState().reconnectPersistedTerminals()
expect(store.getState().deferredSshSessionIdsByTabId).toMatchObject({
'tab-1': sshSessionId
})
})
it('stops deferring a session once its SSH target is known-absent, but keeps deferring present targets', async () => {
// Authoritative target removal makes deferred sessions dead liveness evidence (#9911); skip them or orphan sweep pins dead tabs. Disconnected present targets still defer.
const store = createTestStore()
const goneWt = 'repo-gone::/home/user/remote-gone'
const liveWt = 'repo-live::/home/user/remote-live'
seedStore(store, {
repos: [
{ ...TEST_REPO, id: 'repo-gone', connectionId: 'ssh-target-removed' },
{ ...TEST_REPO, id: 'repo-live', connectionId: 'ssh-target-present' }
],
worktreesByRepo: {},
sshTargetsHydrated: true,
sshTargetLabels: new Map([['ssh-target-present', 'Present']])
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo-live',
activeWorktreeId: liveWt,
activeTabId: 'tab-live',
tabsByWorktree: {
[goneWt]: [makeTab({ id: 'tab-gone', worktreeId: goneWt, ptyId: null })],
[liveWt]: [makeTab({ id: 'tab-live', worktreeId: liveWt, ptyId: null })]
},
terminalLayoutsByTabId: {},
activeWorktreeIdsOnShutdown: [goneWt, liveWt],
remoteSessionIdsByTabId: {
'tab-gone': 'ssh:ssh-target-removed@@pty-7',
'tab-live': 'ssh:ssh-target-present@@pty-8'
}
}
store.getState().hydrateWorkspaceSession(session)
await store.getState().reconnectPersistedTerminals()
expect(store.getState().deferredSshSessionIdsByTabId['tab-gone']).toBeUndefined()
expect(store.getState().pendingReconnectPtyIdByTabId['tab-gone']).toBeUndefined()
expect(store.getState().deferredSshSessionIdsByTabId['tab-live']).toBe(
'ssh:ssh-target-present@@pty-8'
)
})
it('resets persisted agent titles to the fallback label on hydration', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: 'tab-1',
terminalLayoutsByTabId: {},
tabsByWorktree: {
[worktreeId]: [makeTab({ id: 'tab-1', worktreeId, title: '* Claude done', ptyId: '207' })]
}
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().tabsByWorktree[worktreeId]).toEqual([
expect.objectContaining({
id: 'tab-1',
title: 'Terminal 1',
ptyId: null
})
])
})
it('hydrates the default-tab idempotency marker', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: null,
terminalLayoutsByTabId: {},
tabsByWorktree: {},
defaultTerminalTabsAppliedByWorktreeId: { [worktreeId]: true }
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().defaultTerminalTabsAppliedByWorktreeId).toEqual({
[worktreeId]: true
})
})
it('seeds worktree nav history with the restored active worktree', () => {
// Seed restored workspace at history[0] so the first switch enables Back.
const store = createTestStore()
const worktreeId = 'repo1::/wt-1'
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-1' })]
}
})
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {}
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().worktreeNavHistory).toEqual([worktreeId])
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('restores the active repo main worktree when the session has no active terminal tabs', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-main'
seedStore(store, {
worktreesByRepo: {
repo1: [
makeWorktree({
id: worktreeId,
repoId: 'repo1',
path: '/wt-main',
isMainWorktree: true
})
]
}
})
store.getState().hydrateWorkspaceSession({
activeRepoId: 'repo1',
activeWorktreeId: null,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {}
})
expect(store.getState().activeWorktreeId).toBe(worktreeId)
expect(store.getState().activeWorkspaceKey).toBe(`worktree:${worktreeId}`)
expect(store.getState().worktreeNavHistory).toEqual([worktreeId])
})
it('ignores a persisted workspace key that disagrees with the restored active worktree', () => {
const store = createTestStore()
const worktreeId = 'repo1::/wt-current'
const staleFolderKey = folderWorkspaceKey('folder-stale')
seedStore(store, {
worktreesByRepo: {
repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/wt-current' })]
}
})
store.getState().hydrateWorkspaceSession(
{
...getDefaultWorkspaceSession(),
activeRepoId: 'repo1',
activeWorktreeId: worktreeId,
activeWorkspaceKey: staleFolderKey
},
{ additionalValidWorkspaceKeys: [staleFolderKey] }
)
expect(store.getState().activeWorkspaceKey).toBe(worktreeWorkspaceKey(worktreeId))
})
it('leaves nav history empty when no active worktree is restored', () => {
const store = createTestStore()
seedStore(store, { worktreesByRepo: {} })
// Seed stale history to prove hydration actively replaces it.
store.setState({ worktreeNavHistory: ['stale-a', 'stale-b'], worktreeNavHistoryIndex: 1 })
const session: WorkspaceSessionState = {
activeRepoId: null,
activeWorktreeId: null,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {}
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().worktreeNavHistory).toEqual([])
expect(store.getState().worktreeNavHistoryIndex).toBe(-1)
})
it('drops invalid restored worktree from nav history seed', () => {
// Seed only validated selection or deleted workspaces occupy history[0] and break Back.
const store = createTestStore()
seedStore(store, { worktreesByRepo: { repo1: [] } })
// Seed stale history to prove invalid selection actively clears it.
store.setState({ worktreeNavHistory: ['stale-a', 'stale-b'], worktreeNavHistoryIndex: 1 })
const session: WorkspaceSessionState = {
activeRepoId: 'repo1',
activeWorktreeId: 'repo1::/missing',
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {}
}
store.getState().hydrateWorkspaceSession(session)
expect(store.getState().activeWorktreeId).toBeNull()
expect(store.getState().worktreeNavHistory).toEqual([])
expect(store.getState().worktreeNavHistoryIndex).toBe(-1)
})
it('records a subsequent visit on top of the hydration seed so Back is enabled after the first click', () => {
// Restored history[0] enables Back on the first sidebar click.
const store = createTestStore()
@@ -726,38 +182,3 @@ describe('hydrateWorkspaceSession', () => {
expect(canGoBackWorktreeHistory(store.getState())).toBe(true)
})
})
describe('hydrationSucceeded flag (issue #1158)', () => {
it('defaults to false so the session writer is gated off at startup', () => {
// Gate persistence until clean hydration so startup errors cannot overwrite saved state with empty snapshots.
const store = createTestStore()
expect(store.getState().hydrationSucceeded).toBe(false)
})
it('setHydrationSucceeded toggles the flag both ways', () => {
const store = createTestStore()
store.getState().setHydrationSucceeded(true)
expect(store.getState().hydrationSucceeded).toBe(true)
store.getState().setHydrationSucceeded(false)
expect(store.getState().hydrationSucceeded).toBe(false)
})
it('hydrateWorkspaceSession does not flip hydrationSucceeded on its own', () => {
// Why: hydration can populate state then throw downstream, so App.tsx flips the flag only after a clean return.
const store = createTestStore()
const wt = 'repo1::/wt'
seedStore(store, {
worktreesByRepo: { repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/wt' })] }
})
store.getState().hydrateWorkspaceSession({
activeRepoId: 'repo1',
activeWorktreeId: wt,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {}
})
expect(store.getState().hydrationSucceeded).toBe(false)
})
})
@@ -1,129 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createUIStore } from './ui-slice-test-harness'
import type { AppState } from '../types'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import type { TerminalTab } from '../../../../shared/terminal-tab-types'
import { makePaneKey } from '../../../../shared/stable-pane-id'
// Ahead-of-client host clocks kept ackAt below turn timestamps, leaving rows unread and auto-ack looping into React #185.
const NOW = new Date('2026-06-02T12:00:00Z').getTime()
const SKEW_MS = 90_000
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
const PANE_KEY = makePaneKey('tab-1', LEAF_ID)
function makeAgentEntry(overrides: Partial<AgentStatusEntry> = {}): AgentStatusEntry {
return {
state: 'done',
prompt: 'Review complete',
updatedAt: NOW,
stateStartedAt: NOW,
agentType: 'codex',
paneKey: PANE_KEY,
stateHistory: [],
...overrides
}
}
function makeTerminalTab(id: string, worktreeId: string): TerminalTab {
return {
id,
worktreeId,
ptyId: null,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: NOW
}
}
describe('acknowledgeAgents with a clock-skewed execution host', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
it('clears unread for a live turn stamped ahead of the local clock in one acknowledge', () => {
const store = createUIStore()
const futureStartedAt = NOW + SKEW_MS
store.setState({
tabsByWorktree: { 'wt-1': [makeTerminalTab('tab-1', 'wt-1')] },
agentStatusByPaneKey: {
[PANE_KEY]: makeAgentEntry({ stateStartedAt: futureStartedAt, updatedAt: futureStartedAt })
}
} as Partial<AppState>)
store.getState().acknowledgeAgents([PANE_KEY])
const ackAt = store.getState().acknowledgedAgentsByPaneKey[PANE_KEY]
expect(ackAt).toBe(futureStartedAt)
expect(ackAt < futureStartedAt).toBe(false)
})
it('stops rewriting the ack map once a future-stamped turn is acknowledged', () => {
const store = createUIStore()
const futureStartedAt = NOW + SKEW_MS
store.setState({
agentStatusByPaneKey: {
[PANE_KEY]: makeAgentEntry({ stateStartedAt: futureStartedAt, updatedAt: futureStartedAt })
}
} as Partial<AppState>)
store.getState().acknowledgeAgents([PANE_KEY])
const firstMap = store.getState().acknowledgedAgentsByPaneKey
// Later millisecond, same turn: the retry that used to allocate a new map (and re-render forever).
vi.setSystemTime(NOW + 1_000)
store.getState().acknowledgeAgents([PANE_KEY])
expect(store.getState().acknowledgedAgentsByPaneKey).toBe(firstMap)
})
it('covers a retained row and a future history event on the same pane', () => {
const store = createUIStore()
const futureHistoryAt = NOW + SKEW_MS
store.setState({
retainedAgentsByPaneKey: {
[PANE_KEY]: {
entry: makeAgentEntry({
stateStartedAt: NOW + 1_000,
stateHistory: [{ state: 'blocked', prompt: 'p', startedAt: futureHistoryAt }]
}),
worktreeId: 'wt-1',
tab: makeTerminalTab('tab-1', 'wt-1'),
agentType: 'codex',
startedAt: NOW + 1_000
}
}
} as Partial<AppState>)
store.getState().acknowledgeAgents([PANE_KEY])
expect(store.getState().acknowledgedAgentsByPaneKey[PANE_KEY]).toBe(futureHistoryAt)
})
it('covers a future-stamped migration-unsupported row, which Activity renders as a blocked event', () => {
const store = createUIStore()
const futureUpdatedAt = NOW + SKEW_MS
store.setState({
migrationUnsupportedByPtyId: {
'pty-1': {
ptyId: 'pty-1',
paneKey: PANE_KEY,
reason: 'legacy-numeric-pane-key',
source: 'ssh',
updatedAt: futureUpdatedAt
}
}
} as Partial<AppState>)
store.getState().acknowledgeAgents([PANE_KEY])
expect(store.getState().acknowledgedAgentsByPaneKey[PANE_KEY]).toBe(futureUpdatedAt)
})
})
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TerminalTab } from '../../../../shared/terminal-tab-types'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import { makePaneKey } from '../../../../shared/stable-pane-id'
import { structuredAgentSessionPaneKey } from '../../../../shared/agent-session/view/structured-agent-session-projection'
import '../../../../shared/agent-session/view/structured-agent-session-projection'
import { buildAgentNotificationId } from '../../../../shared/agent-notification-id'
import type { AppState } from '../types'
import { createUIStore } from './ui-slice-test-harness'
@@ -189,50 +189,6 @@ describe('createUISlice agent send target mode', () => {
} as Partial<AppState>)
}
it('opens target mode with derived eligible and disabled pane keys', () => {
const store = createAgentSendStore()
seedAgentSendState(store)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send'
})
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
eligiblePaneKeys: [readyPaneKey, workingPaneKey],
disabledPaneKeys: {},
status: 'open'
})
expect(store.getState().pendingRevealWorktree).toMatchObject({
worktreeId,
behavior: 'auto',
highlight: true
})
})
it('switches out of the activity view because send targets render on workspace cards', () => {
const store = createAgentSendStore()
seedAgentSendState(store)
store.getState().setSidebarBody('agents')
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send'
})
expect(store.getState().sidebarBody).toBe('workspaces')
expect(store.getState().pendingRevealWorktree).toMatchObject({ worktreeId })
})
it('disables sidebar target rows that need permission', async () => {
const store = createAgentSendStore()
seedAgentSendState(store)
@@ -270,51 +226,6 @@ describe('createUISlice agent send target mode', () => {
expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
})
it('does not reveal the sidebar when the current workspace has no eligible targets', () => {
const store = createAgentSendStore()
seedAgentSendState(store)
store.setState({
terminalLayoutsByTabId: {
[tabId]: {
root: {
type: 'split',
direction: 'vertical',
first: { type: 'leaf', leafId: readyLeafId },
second: { type: 'leaf', leafId: workingLeafId }
},
activeLeafId: readyLeafId,
expandedLeafId: null,
ptyIdsByLeafId: {
[readyLeafId]: 'pty-ready',
[workingLeafId]: 'pty-working'
}
}
},
ptyIdsByTabId: {
[tabId]: []
}
})
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'browser-annotations',
prompt: 'Review this',
label: 'Browser annotations',
launchSource: 'notes_send'
})
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
eligiblePaneKeys: [],
disabledPaneKeys: {
[readyPaneKey]: 'Terminal is no longer available',
[workingPaneKey]: 'Terminal is no longer available'
}
})
expect(store.getState().pendingRevealWorktree).toBeNull()
})
it('sends to the live leaf PTY, runs delivery callback, tracks followup, and closes', async () => {
const store = createAgentSendStore()
const onPromptDelivered = vi.fn()
@@ -352,120 +263,6 @@ describe('createUISlice agent send target mode', () => {
expect(store.getState().agentSendPopoverTargetMode).toBeNull()
})
const chatTabId = 'structured-agent-session-claude_1'
const chatPaneKey = structuredAgentSessionPaneKey(chatTabId, 'claude_1')
function seedChatState(
store: StoreApi<AppState>,
agentStatusByPaneKey: AppState['agentStatusByPaneKey']
): void {
store.setState({
agentStatusByPaneKey,
tabsByWorktree: {},
terminalLayoutsByTabId: {},
ptyIdsByTabId: {},
unifiedTabsByWorktree: {
[worktreeId]: [
{
id: chatTabId,
entityId: 'claude_1',
groupId: 'group-1',
worktreeId,
contentType: 'agent-session',
agentSessionAgent: 'claude',
label: 'Claude Chat',
customLabel: null,
color: null,
sortOrder: 0,
createdAt: Date.now()
}
]
}
})
}
it('does not reveal the sidebar for a chat before its first turn, which has no row there', () => {
const store = createAgentSendStore()
seedChatState(store, {})
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send'
})
expect(store.getState().agentSendPopoverTargetMode?.eligiblePaneKeys).toEqual([])
expect(store.getState().pendingRevealWorktree).toBeNull()
})
it('sends to a structured chat by its session, not a terminal', async () => {
const store = createAgentSendStore()
const onPromptDelivered = vi.fn()
const now = Date.now()
seedChatState(store, {
[chatPaneKey]: {
state: 'done',
prompt: 'previous',
updatedAt: now,
stateStartedAt: now,
agentType: 'claude',
paneKey: chatPaneKey,
stateHistory: []
}
})
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send',
onPromptDelivered
})
expect(store.getState().agentSendPopoverTargetMode?.eligiblePaneKeys).toEqual([chatPaneKey])
await expect(store.getState().sendPromptToSidebarAgentTarget(chatPaneKey)).resolves.toBe(true)
expect(mocks.sendStructuredAgentSessionMessage).toHaveBeenCalledWith({
sessionId: 'claude_1',
target: { kind: 'local' },
text: 'Review this',
callerKeepsText: true
})
expect(mocks.relaunchFailedStructuredAgentSessionWithMessage).toHaveBeenCalledWith(
worktreeId,
'claude_1',
'Review this',
{ callerKeepsText: true }
)
expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
expect(onPromptDelivered).toHaveBeenCalledTimes(1)
expect(mocks.toastSuccess).toHaveBeenCalledWith('Sent to Claude')
})
it('sends nothing to a sidebar agent when every note is already on its way', async () => {
const store = createAgentSendStore()
const onPromptHandedOff = vi.fn()
seedAgentSendState(store)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: '',
label: 'All unsent notes',
launchSource: 'notes_send',
onPromptHandedOff
})
await expect(store.getState().sendPromptToSidebarAgentTarget(readyPaneKey)).resolves.toBe(false)
expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
expect(onPromptHandedOff).not.toHaveBeenCalled()
})
it('keeps target mode open and does not run delivery callback when send fails', async () => {
const store = createAgentSendStore()
const onPromptDelivered = vi.fn()
@@ -495,31 +292,6 @@ describe('createUISlice agent send target mode', () => {
})
})
it('sends to a working agent row through the selected-target note helper', async () => {
const store = createAgentSendStore()
seedAgentSendState(store)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'browser-annotations',
prompt: 'Review this',
label: 'Browser annotations',
launchSource: 'notes_send'
})
await expect(store.getState().sendPromptToSidebarAgentTarget(workingPaneKey)).resolves.toBe(
true
)
expect(mocks.sendNotesToActiveAgentSession).toHaveBeenCalledWith({
worktreeId,
prompt: 'Review this',
noteTarget: { tabId, leafId: workingLeafId }
})
expect(mocks.toastSuccess).toHaveBeenCalledWith('Sent to Codex')
expect(store.getState().agentSendPopoverTargetMode).toBeNull()
})
it('acknowledges delivery when the picker closes before the send completes', async () => {
const store = createAgentSendStore()
const onPromptDelivered = vi.fn()
@@ -741,133 +513,4 @@ describe('createUISlice acknowledgeAgents notification dismissal', () => {
// Nothing rebuilt twice; main still gets the subjects so it can retire what it announced.
expect(dismiss).toHaveBeenCalledWith([], [livePaneKey, retainedPaneKey])
})
it('falls back to live entry worktree attribution and skips unresolved live entries', () => {
const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 })
vi.stubGlobal('window', { api: { notifications: { dismiss } } })
const store = createAgentSendStore()
const fallbackPaneKey = makePaneKey('tab-fallback', '44444444-4444-4444-8444-444444444444')
store.setState({
tabsByWorktree: {},
agentStatusByPaneKey: {
[fallbackPaneKey]: {
...makeAgentEntry(fallbackPaneKey, 1_000),
worktreeId: 'wt-from-entry'
},
[livePaneKey]: makeAgentEntry(livePaneKey, 2_000)
},
retainedAgentsByPaneKey: {}
} as Partial<AppState>)
store.getState().acknowledgeAgents([fallbackPaneKey, livePaneKey])
expect(dismiss).toHaveBeenCalledWith(
[
buildAgentNotificationId({
worktreeId: 'wt-from-entry',
paneKey: fallbackPaneKey,
stateStartedAt: 1_000
})
],
[fallbackPaneKey, livePaneKey]
)
})
it('dedupes identical live and retained notification ids for the same pane', () => {
const dismiss = vi.fn().mockResolvedValue({ dismissed: 0 })
vi.stubGlobal('window', { api: { notifications: { dismiss } } })
const store = createAgentSendStore()
store.setState({
tabsByWorktree: {
'wt-live': [makeTerminalTab(tabId, 'wt-live')]
},
agentStatusByPaneKey: {
[livePaneKey]: makeAgentEntry(livePaneKey, 1_000)
},
retainedAgentsByPaneKey: {
[livePaneKey]: {
entry: makeAgentEntry(livePaneKey, 1_000),
worktreeId: 'wt-live',
tab: makeTerminalTab(tabId, 'wt-live'),
agentType: 'codex',
startedAt: 1_000
}
}
} as Partial<AppState>)
store.getState().acknowledgeAgents([livePaneKey])
expect(dismiss).toHaveBeenCalledWith(
[
buildAgentNotificationId({
worktreeId: 'wt-live',
paneKey: livePaneKey,
stateStartedAt: 1_000
})
],
[livePaneKey]
)
})
})
describe('openDiffNotesSendMenuForActiveWorktree', () => {
function stubDiffNotesStore(
comments: { sentAt?: number }[],
activeWorktreeId: string | null = 'wt-1'
): { store: StoreApi<AppState>; setRightSidebarTab: ReturnType<typeof vi.fn> } {
const store = createAgentSendStore()
const setRightSidebarTab = vi.fn()
store.setState({
activeWorktreeId,
getDiffComments: () => comments,
setRightSidebarTab,
setRightSidebarOpen: vi.fn()
} as unknown as Partial<AppState>)
return { store, setRightSidebarTab }
}
it('reveals Source Control and bumps the open request when unsent notes exist', () => {
const { store, setRightSidebarTab } = stubDiffNotesStore([{ sentAt: 10 }, {}])
expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(true)
expect(setRightSidebarTab).toHaveBeenCalledWith('source-control')
expect(store.getState().diffNotesSendMenuOpenRequest).toMatchObject({
worktreeId: 'wt-1',
nonce: 1
})
expect(store.getState().diffNotesSendMenuOpenRequest?.issuedAt).toBeTypeOf('number')
// A second request increments the nonce so the menu reopens.
expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(true)
expect(store.getState().diffNotesSendMenuOpenRequest).toMatchObject({
worktreeId: 'wt-1',
nonce: 2
})
})
it('is a no-op when every note is already sent', () => {
const { store, setRightSidebarTab } = stubDiffNotesStore([{ sentAt: 10 }])
expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(false)
expect(setRightSidebarTab).not.toHaveBeenCalled()
expect(store.getState().diffNotesSendMenuOpenRequest).toBeNull()
})
it('is a no-op when there is no active worktree', () => {
const { store } = stubDiffNotesStore([{}], null)
expect(store.getState().openDiffNotesSendMenuForActiveWorktree()).toBe(false)
expect(store.getState().diffNotesSendMenuOpenRequest).toBeNull()
})
it('clears the request only for the matching worktree', () => {
const { store } = stubDiffNotesStore([{}])
store.getState().openDiffNotesSendMenuForActiveWorktree()
store.getState().consumeDiffNotesSendMenuOpenRequest('other-wt')
expect(store.getState().diffNotesSendMenuOpenRequest).not.toBeNull()
store.getState().consumeDiffNotesSendMenuOpenRequest('wt-1')
expect(store.getState().diffNotesSendMenuOpenRequest).toBeNull()
})
})
@@ -1,542 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types'
import type { ContextualTourId } from '../../../../shared/contextual-tours'
import { createUIStore, makePersistedUI } from './ui-slice-test-harness'
const mocks = vi.hoisted(() => ({
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession
}))
vi.mock('@/lib/telemetry', () => ({
track: mocks.track
}))
vi.mock('sonner', () => ({
toast: {
message: mocks.toastMessage,
success: mocks.toastSuccess,
error: mocks.toastError
}
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
beforeEach(() => {
mocks.sendNotesToActiveAgentSession.mockReset()
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
mocks.track.mockReset()
mocks.toastMessage.mockReset()
mocks.toastSuccess.mockReset()
mocks.toastError.mockReset()
})
function stubContextualTourTargets(selectors: readonly string[]): void {
const selectorSet = new Set(selectors)
vi.stubGlobal('document', {
querySelector: vi.fn((selector: string) =>
selectorSet.has(selector)
? {
getBoundingClientRect: () => ({
left: 10,
top: 10,
right: 110,
bottom: 50,
width: 100,
height: 40
})
}
: null
)
})
}
describe('createUISlice contextual tours', () => {
function makeAutoTourEligibleUI(overrides: Partial<PersistedUIState> = {}): PersistedUIState {
return makePersistedUI({
contextualToursAutoEligible: true,
...overrides
})
}
it('normalizes persisted contextual tour ids during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
contextualToursSeenIds: ['tasks', 'unknown', 'tasks', 'browser'] as never
})
)
expect(store.getState().contextualToursSeenIds).toEqual(['tasks', 'browser'])
})
it('normalizes persisted contextual tour auto eligibility during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI())
expect(store.getState().contextualToursAutoEligible).toBeNull()
store.getState().hydratePersistedUI(makePersistedUI({ contextualToursAutoEligible: false }))
expect(store.getState().contextualToursAutoEligible).toBe(false)
store
.getState()
.hydratePersistedUI(makePersistedUI({ contextualToursAutoEligible: 'yes' as never }))
expect(store.getState().contextualToursAutoEligible).toBeNull()
})
it('persists contextual tour auto eligibility once classified', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().setContextualToursAutoEligible(false)
store.getState().setContextualToursAutoEligible(false)
expect(store.getState().contextualToursAutoEligible).toBe(false)
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ contextualToursAutoEligible: false })
})
it('marks contextual tours seen and persists them once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().markContextualToursSeen(['tasks'])
store.getState().markContextualToursSeen(['tasks'])
expect(store.getState().contextualToursSeenIds).toEqual(['tasks'])
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ contextualToursSeenIds: ['tasks'] })
})
it('starts a tour only after persisted UI and required first target are ready', () => {
const store = createUIStore()
const tasksFirstSelector = '[data-contextual-tour-target="tasks-source-filters"]'
stubContextualTourTargets([tasksFirstSelector])
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourId).toBeNull()
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourId).toBe('tasks')
expect(store.getState().activeContextualTourStepIndex).toBe(0)
expect(store.getState().activeContextualTourSource).toBe('tasks_open')
expect(store.getState().contextualTourShownThisSession).toBe(true)
expect(store.getState().contextualToursSeenIds).toEqual([])
})
it('stores whether the feature was interacted with before the tour request', () => {
const store = createUIStore()
const tasksFirstSelector = '[data-contextual-tour-target="tasks-source-filters"]'
stubContextualTourTargets([tasksFirstSelector])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().recordFeatureInteraction('tasks')
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(true)
})
it('lets the caller preserve the pre-enable interaction snapshot for telemetry', () => {
const store = createUIStore()
const tasksFirstSelector = '[data-contextual-tour-target="tasks-source-filters"]'
stubContextualTourTargets([tasksFirstSelector])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().recordFeatureInteraction('tasks')
store.getState().requestContextualTour('tasks', 'tasks_open', false)
expect(store.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false)
})
it('does not bias first-visit contextual tour telemetry from navigation actions', () => {
stubContextualTourTargets([
'[data-contextual-tour-target="tasks-source-filters"]',
'[data-contextual-tour-target="automations-create"]',
'[data-contextual-tour-target="workspace-creation-project"]'
])
const tasksStore = createUIStore()
tasksStore.getState().hydratePersistedUI(makeAutoTourEligibleUI())
tasksStore.getState().openTaskPage()
tasksStore.getState().requestContextualTour('tasks', 'tasks_open')
expect(tasksStore.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false)
const automationsStore = createUIStore()
automationsStore.getState().hydratePersistedUI(makeAutoTourEligibleUI())
automationsStore.getState().openAutomationsPage()
automationsStore.getState().requestContextualTour('automations', 'automations_open')
expect(automationsStore.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(
false
)
const composerStore = createUIStore()
composerStore.getState().hydratePersistedUI(makeAutoTourEligibleUI())
composerStore.getState().openModal('new-workspace-composer')
composerStore.getState().requestContextualTour('workspace-creation', 'workspace_creation_modal')
expect(composerStore.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false)
})
it('does not mark seen when the required first target is absent', () => {
const store = createUIStore()
stubContextualTourTargets([])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourId).toBeNull()
expect(store.getState().contextualToursSeenIds).toEqual([])
expect(store.getState().contextualTourShownThisSession).toBe(false)
})
it('does not start while a root confirmation surface is visible', () => {
const store = createUIStore()
stubContextualTourTargets(['[data-contextual-tour-target="tasks-source-filters"]'])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().setContextualToursBlockingSurfaceVisible(true)
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourId).toBeNull()
expect(store.getState().contextualTourShownThisSession).toBe(false)
})
it('does not auto-start tours for profiles that are not eligible', () => {
const store = createUIStore()
stubContextualTourTargets(['[data-contextual-tour-target="tasks-source-filters"]'])
store.getState().hydratePersistedUI(makePersistedUI({ contextualToursAutoEligible: false }))
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourId).toBeNull()
expect(store.getState().contextualTourShownThisSession).toBe(false)
})
it('force-starts a tour from an explicit user action even after auto tours are unavailable', () => {
const store = createUIStore()
stubContextualTourTargets([
'[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]'
])
store.getState().hydratePersistedUI(
makePersistedUI({
contextualToursAutoEligible: false,
contextualToursSeenIds: ['workspace-agent-sessions']
})
)
store
.getState()
.requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, {
force: true
})
expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions')
expect(store.getState().activeContextualTourSource).toBe('setup_guide_parallel_work')
expect(store.getState().activeContextualTourWasFeaturePreviouslyInteracted).toBe(false)
})
it('preserves the bounded setup-guide parallel-work source on forced tour requests', () => {
const store = createUIStore()
stubContextualTourTargets([
'[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]'
])
store.getState().hydratePersistedUI(
makePersistedUI({
contextualToursAutoEligible: false,
contextualToursSeenIds: ['workspace-agent-sessions']
})
)
store
.getState()
.requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, {
force: true
})
expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions')
expect(store.getState().activeContextualTourSource).toBe('setup_guide_parallel_work')
})
it('allows only workspace creation over its workspace composer modal', () => {
const store = createUIStore()
stubContextualTourTargets([
'[data-contextual-tour-target="tasks-source-filters"]',
'[data-contextual-tour-target="workspace-creation-project"]'
])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().openModal('new-workspace-composer')
store.getState().requestContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourId).toBeNull()
store.getState().requestContextualTour('workspace-creation', 'workspace_creation_modal')
expect(store.getState().activeContextualTourId).toBe('workspace-creation')
})
it('advances across visible steps and leaves completion to the overlay', () => {
const store = createUIStore()
const visibleSelectors = [
'[data-contextual-tour-target="browser-grab-control"]',
'[data-contextual-tour-target="browser-annotation-control"]',
'[data-contextual-tour-target="browser-import-cookies-control"]'
]
stubContextualTourTargets(visibleSelectors)
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().requestContextualTour('browser', 'browser_visible')
store.getState().advanceContextualTour()
expect(store.getState().activeContextualTourStepIndex).toBe(1)
store.getState().advanceContextualTour()
expect(store.getState().activeContextualTourId).toBe('browser')
expect(store.getState().activeContextualTourStepIndex).toBe(2)
})
it('advances the browser tour to the cookie step before Import Cookies is measurable', () => {
const store = createUIStore()
const visibleSelectors = [
'[data-contextual-tour-target="browser-grab-control"]',
'[data-contextual-tour-target="browser-annotation-control"]'
]
stubContextualTourTargets(visibleSelectors)
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
store.getState().requestContextualTour('browser', 'browser_visible')
store.getState().advanceContextualTour()
expect(store.getState().activeContextualTourStepIndex).toBe(1)
store.getState().advanceContextualTour()
expect(store.getState().activeContextualTourStepIndex).toBe(2)
})
it('advances the active split step when the split command interaction is recorded', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
stubContextualTourTargets([
'[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]',
'[data-contextual-tour-target="workspace-create-control"]'
])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI())
setMock.mockClear()
store
.getState()
.requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, {
force: true
})
store.getState().recordFeatureInteraction('terminal-pane-split')
expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions')
expect(store.getState().activeContextualTourStepIndex).toBe(1)
expect(store.getState().featureInteractions['terminal-pane-split']).toMatchObject({
interactionCount: 1
})
})
it('opens the sidebar and advances the split step when the create-worktree target is hidden', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
stubContextualTourTargets([
'[data-contextual-tour-target="terminal-pane-split-target"], [data-contextual-tour-target="workspace-agent-terminal-tip"]'
])
store.getState().hydratePersistedUI(makeAutoTourEligibleUI({ sidebarOpen: false }))
store
.getState()
.requestContextualTour('workspace-agent-sessions', 'setup_guide_parallel_work', false, {
force: true
})
store.getState().recordFeatureInteraction('terminal-pane-split')
expect(store.getState().sidebarOpen).toBe(true)
expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions')
expect(store.getState().activeContextualTourStepIndex).toBe(1)
expect(store.getState().contextualToursSeenIds).toEqual([])
expect(store.getState().lastCompletedContextualTourId).toBeNull()
})
it('marks the active contextual tour suppressed when its owning source disables', () => {
const store = createUIStore()
store.setState({
activeContextualTourId: 'browser',
activeContextualTourStepIndex: 0,
activeContextualTourSource: 'browser_visible',
activeContextualTourWasFeaturePreviouslyInteracted: false,
contextualTourShownThisSession: true
})
store.getState().suppressContextualTour('tasks', 'tasks_open')
expect(store.getState().activeContextualTourSuppressed).toBe(false)
store.getState().suppressContextualTour('browser', 'browser_visible')
expect(store.getState().activeContextualTourSuppressed).toBe(true)
})
it('keeps an intentionally detached contextual tour active when its owning source disables', () => {
const store = createUIStore()
store.setState({
activeContextualTourId: 'workspace-agent-sessions',
activeContextualTourStepIndex: 3,
activeContextualTourSource: 'workspace_agent_sessions_visible',
activeContextualTourWasFeaturePreviouslyInteracted: false,
contextualTourShownThisSession: true
})
store
.getState()
.detachContextualTourSource('workspace-agent-sessions', 'workspace_agent_sessions_visible')
store
.getState()
.suppressContextualTour('workspace-agent-sessions', 'workspace_agent_sessions_visible')
expect(store.getState().activeContextualTourSourceDetached).toBe(true)
expect(store.getState().activeContextualTourSuppressed).toBe(false)
expect(store.getState().activeContextualTourId).toBe('workspace-agent-sessions')
})
it('cancels a not-yet-rendered tour without persistence churn', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.setState({
activeContextualTourId: 'tasks',
activeContextualTourStepIndex: 0,
activeContextualTourSource: 'tasks_open',
contextualTourShownThisSession: true
})
store.getState().cancelContextualTour('tasks')
expect(store.getState().activeContextualTourId).toBeNull()
expect(store.getState().contextualTourShownThisSession).toBe(false)
expect(store.getState().lastCompletedContextualTourId).toBeNull()
expect(store.getState().contextualToursSeenIds).toEqual([])
expect(setMock).not.toHaveBeenCalled()
})
it('preserves the session guard when canceling an already-rendered tour', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.setState({
activeContextualTourId: 'tasks',
activeContextualTourStepIndex: 0,
activeContextualTourSource: 'tasks_open',
contextualTourShownThisSession: true,
contextualToursSeenIds: ['tasks']
})
store.getState().cancelContextualTour('tasks')
expect(store.getState().activeContextualTourId).toBeNull()
expect(store.getState().contextualTourShownThisSession).toBe(true)
expect(store.getState().contextualToursSeenIds).toEqual<ContextualTourId[]>(['tasks'])
expect(setMock).not.toHaveBeenCalled()
})
it('dismisses active tours as seen', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.setState({
activeContextualTourId: 'automations',
activeContextualTourStepIndex: 0,
activeContextualTourSource: 'automations_open',
contextualTourShownThisSession: true
})
store.getState().dismissContextualTour('automations')
expect(store.getState().activeContextualTourId).toBeNull()
expect(store.getState().contextualToursSeenIds).toEqual<ContextualTourId[]>(['automations'])
expect(store.getState().lastCompletedContextualTourId).toBeNull()
expect(setMock).toHaveBeenCalledWith({ contextualToursSeenIds: ['automations'] })
})
it('ignores stale dismissals for a different active tour', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.setState({
activeContextualTourId: 'tasks',
activeContextualTourStepIndex: 0,
activeContextualTourSource: 'tasks_open',
contextualTourShownThisSession: true
})
store.getState().dismissContextualTour('browser')
expect(store.getState().activeContextualTourId).toBe('tasks')
expect(store.getState().contextualToursSeenIds).toEqual([])
expect(setMock).not.toHaveBeenCalled()
})
})
@@ -7,20 +7,6 @@ beforeEach(() => {
afterEach(() => vi.unstubAllGlobals())
describe('host visibility across saved UI broadcasts', () => {
it('keeps a newly revealed remote host when an older UI snapshot arrives', () => {
const store = createUIStore()
const previous = makePersistedUI({
workspaceHostScope: 'local',
visibleWorkspaceHostIds: ['local']
})
store.getState().hydratePersistedUI(previous)
store.getState().setVisibleWorkspaceHostIds(['local', 'runtime:m4air'])
store.getState().hydratePersistedUI(previous, 'sync')
expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'runtime:m4air'])
})
it('keeps All hosts while the prior selection is being saved', () => {
const store = createUIStore()
const previous = makePersistedUI({ workspaceHostScope: 'all', visibleWorkspaceHostIds: null })
@@ -40,19 +26,4 @@ describe('host visibility across saved UI broadcasts', () => {
expect(store.getState().workspaceHostScope).toBe('all')
expect(store.getState().visibleWorkspaceHostIds).toBeNull()
})
it('accepts another client’s host selection when there is no local edit', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI())
store.getState().hydratePersistedUI(
makePersistedUI({
workspaceHostScope: 'runtime:m4air',
visibleWorkspaceHostIds: ['runtime:m4air']
}),
'sync'
)
expect(store.getState().workspaceHostScope).toBe('runtime:m4air')
expect(store.getState().visibleWorkspaceHostIds).toEqual(['runtime:m4air'])
})
})
@@ -1,742 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { getDefaultUIState } from '../../../../shared/constants'
import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types'
import type { Repo } from '../../../../shared/repo-types'
import type { AppState } from '../types'
import { getSetupScriptPromptDismissalKey } from '../../lib/setup-script-prompt'
import { getRepoHostIdentityForParts } from './repo-host-identity'
import { createUIStore, makePersistedUI } from './ui-slice-test-harness'
const mocks = vi.hoisted(() => ({
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession
}))
vi.mock('@/lib/telemetry', () => ({
track: mocks.track
}))
vi.mock('sonner', () => ({
toast: {
message: mocks.toastMessage,
success: mocks.toastSuccess,
error: mocks.toastError
}
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
beforeEach(() => {
mocks.sendNotesToActiveAgentSession.mockReset()
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
mocks.track.mockReset()
mocks.toastMessage.mockReset()
mocks.toastSuccess.mockReset()
mocks.toastError.mockReset()
})
describe('sidebar reveal actions', () => {
it('skip reveals while the activity view is showing instead of switching bodies', () => {
const store = createUIStore()
store.getState().setSidebarBody('agents')
store.getState().revealWorktreeInSidebar('wt-1', { highlight: true })
store.getState().revealSidebarRow('repo:r1')
expect(store.getState().sidebarBody).toBe('agents')
expect(store.getState().pendingRevealWorktree).toBeNull()
expect(store.getState().pendingRevealSidebarRow).toBeNull()
})
it('reveal after an explicit switch to the workspace list', () => {
const store = createUIStore()
store.getState().setSidebarBody('agents')
store.getState().setSidebarBody('workspaces')
store.getState().revealWorktreeInSidebar('wt-1', { highlight: true })
store.getState().revealSidebarRow('repo:r1')
expect(store.getState().sidebarBody).toBe('workspaces')
expect(store.getState().pendingRevealWorktree).toBeNull()
expect(store.getState().pendingRevealSidebarRow?.rowKey).toBe('repo:r1')
const oldRow = store.getState().pendingRevealSidebarRow
store.getState().revealWorktreeInSidebar('wt-2', { rowKey: 'pinned:wt-2' })
const newer = store.getState().pendingRevealWorktree
store.getState().clearPendingRevealSidebarRow(oldRow)
store.getState().revealWorktreeInSidebar('wt-2', { rowKey: 'pinned:wt-2' })
store.getState().clearPendingRevealWorktreeId(newer)
expect(store.getState().pendingRevealSidebarRow).toBeNull()
expect(store.getState().pendingRevealWorktree?.rowKey).toBe('pinned:wt-2')
})
})
describe('createUISlice hydratePersistedUI', () => {
it('defaults persisted right sidebar visibility to open', () => {
expect(getDefaultUIState().rightSidebarOpen).toBe(true)
})
it('defaults to showing sleeping workspaces', () => {
const store = createUIStore()
expect(store.getState().showSleepingWorkspaces).toBe(true)
})
it('defaults the default-branch sleeping exemption to on', () => {
expect(getDefaultUIState().alwaysShowDefaultBranchWorkspace).toBe(true)
expect(createUIStore().getState().alwaysShowDefaultBranchWorkspace).toBe(true)
})
it('treats a legacy profile with no default-branch exemption key as opted in', () => {
// Pre-#8873 profiles omit this key; absence must enable the exemption rather than hide main again.
const store = createUIStore()
const legacy = makePersistedUI()
delete (legacy as Partial<PersistedUIState>).alwaysShowDefaultBranchWorkspace
store.getState().hydratePersistedUI(legacy, 'startup')
expect(store.getState().alwaysShowDefaultBranchWorkspace).toBe(true)
})
it('preserves an explicit default-branch exemption opt-out on hydration', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ alwaysShowDefaultBranchWorkspace: false }), 'startup')
expect(store.getState().alwaysShowDefaultBranchWorkspace).toBe(false)
})
it('defaults workspace host scope to all hosts', () => {
expect(getDefaultUIState().workspaceHostScope).toBe('all')
expect(createUIStore().getState().workspaceHostScope).toBe('all')
expect(getDefaultUIState().visibleWorkspaceHostIds).toBeNull()
expect(createUIStore().getState().visibleWorkspaceHostIds).toBeNull()
expect(getDefaultUIState().workspaceHostOrder).toEqual([])
expect(createUIStore().getState().workspaceHostOrder).toEqual([])
expect(getDefaultUIState().manualRepoOrder).toEqual([])
expect(createUIStore().getState().manualRepoOrder).toEqual([])
})
it('defaults the persisted active view to terminal', () => {
expect(getDefaultUIState().activeView).toBe('terminal')
expect(createUIStore().getState().activeView).toBe('terminal')
})
it('restores the persisted active top-level view on hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'tasks' }), 'startup')
expect(store.getState().activeView).toBe('tasks')
})
it('falls back to terminal when persisted active view is missing (older data)', () => {
const store = createUIStore()
store.setState({ activeView: 'tasks' })
store.getState().hydratePersistedUI(
{
...makePersistedUI(),
activeView: undefined as unknown as PersistedUIState['activeView']
},
'startup'
)
expect(store.getState().activeView).toBe('terminal')
})
it('restores a persisted skills view', () => {
const store = createUIStore()
store.setState({ activeView: 'tasks' })
store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'skills' }), 'startup')
expect(store.getState().activeView).toBe('skills')
})
it('falls back to terminal when the persisted active view is not a known view', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
activeView: 'not-a-real-view' as unknown as PersistedUIState['activeView']
}),
'startup'
)
expect(store.getState().activeView).toBe('terminal')
})
it('keeps a persisted activity view when the settings fetch failed', () => {
// A failed window.api.settings.get() leaves settings null; downgrading here would let the
// persisted-UI writer overwrite the saved view with terminal.
const store = createUIStore()
store.setState({ settings: null as unknown as AppState['settings'] })
store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'activity' }), 'startup')
expect(store.getState().activeView).toBe('activity')
})
it('restores a default-on view (mobile) even when its nav button is hidden', () => {
const store = createUIStore()
store.setState({
settings: { showMobileButton: false } as AppState['settings']
})
store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'mobile' }), 'startup')
expect(store.getState().activeView).toBe('mobile')
})
it('does not overwrite the current view on a later cross-window sync hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'tasks' }), 'startup')
expect(store.getState().activeView).toBe('tasks')
store
.getState()
.hydratePersistedUI(
makePersistedUI({ activeView: 'terminal', rightSidebarOpen: false }),
'sync'
)
expect(store.getState().activeView).toBe('tasks')
expect(store.getState().rightSidebarOpen).toBe(false)
})
it('preserves the current right sidebar width when older persisted UI omits it', () => {
const store = createUIStore()
store.setState({ rightSidebarWidth: 360 })
store.getState().hydratePersistedUI({
...makePersistedUI(),
rightSidebarWidth: undefined as unknown as number
})
expect(store.getState().rightSidebarWidth).toBe(360)
})
it('hydrates a persisted closed left sidebar preference', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ sidebarOpen: false }))
expect(store.getState().sidebarOpen).toBe(false)
})
it('hydrates a persisted open left sidebar preference', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ sidebarOpen: true }))
expect(store.getState().sidebarOpen).toBe(true)
})
it('hydrates a missing left sidebar preference as open', () => {
const store = createUIStore()
store.setState({ sidebarOpen: false })
store.getState().hydratePersistedUI({ ...makePersistedUI(), sidebarOpen: undefined })
expect(store.getState().sidebarOpen).toBe(true)
})
it('keeps an unsaved left sidebar close when a sync omits the left sidebar preference', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI(), 'startup')
store.getState().setSidebarOpen(false)
store.getState().hydratePersistedUI({ ...makePersistedUI(), sidebarOpen: undefined }, 'sync')
// Why: the baseline must stay open or the writer sees no diff and the close never persists.
expect(store.getState().sidebarOpen).toBe(false)
expect(store.getState().persistedUIWriteBaseline?.sidebarOpen).toBe(true)
})
it('hydrates a persisted closed right sidebar preference', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarOpen: false }))
expect(store.getState().rightSidebarOpen).toBe(false)
})
it('hydrates a persisted open right sidebar preference', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarOpen: true }))
expect(store.getState().rightSidebarOpen).toBe(true)
})
it('hydrates a persisted right sidebar tab preference', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarTab: 'checks' }))
expect(store.getState().rightSidebarTab).toBe('checks')
expect(store.getState().rightSidebarExplorerView).toBe('files')
})
it('preserves persisted repo filters until repos are loaded', () => {
const store = createUIStore()
const remoteDismissalKey = getSetupScriptPromptDismissalKey(
getRepoHostIdentityForParts('remote-repo', 'runtime:env-1')
)
store.getState().hydratePersistedUI(
makePersistedUI({
filterRepoIds: ['remote-repo', 12 as never, 'stale-repo'],
trustedOrcaHooks: {
'remote-repo': { all: { approvedAt: 1 } },
'bad-shape': 'yes' as never
},
setupScriptPromptDismissedRepoIds: [remoteDismissalKey, 'remote-repo', remoteDismissalKey]
})
)
expect(store.getState().filterRepoIds).toEqual(['remote-repo', 'stale-repo'])
expect(store.getState().trustedOrcaHooks).toEqual({
'remote-repo': { all: { approvedAt: 1 } }
})
expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([remoteDismissalKey])
})
it('validates persisted repo filters when repos are already loaded', () => {
const store = createUIStore()
const localDismissalKey = getSetupScriptPromptDismissalKey(
getRepoHostIdentityForParts('local-repo', 'local')
)
const staleDismissalKey = getSetupScriptPromptDismissalKey(
getRepoHostIdentityForParts('stale-repo', 'local')
)
store.setState({
repos: [
{ id: 'local-repo', path: '/local', displayName: 'Local', badgeColor: '#000', addedAt: 1 }
]
} as Partial<AppState>)
store.getState().hydratePersistedUI(
makePersistedUI({
filterRepoIds: ['local-repo', 'stale-repo'],
trustedOrcaHooks: {
'local-repo': { all: { approvedAt: 1 } },
'stale-repo': { all: { approvedAt: 2 } }
},
setupScriptPromptDismissedRepoIds: [localDismissalKey, staleDismissalKey]
})
)
expect(store.getState().filterRepoIds).toEqual(['local-repo'])
expect(store.getState().trustedOrcaHooks).toEqual({
'local-repo': { all: { approvedAt: 1 } }
})
expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([localDismissalKey])
})
it('hydrates legacy persisted search tab as Explorer search', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ rightSidebarTab: 'search' }))
expect(store.getState().rightSidebarTab).toBe('explorer')
expect(store.getState().rightSidebarExplorerView).toBe('search')
})
it('hydrates persisted Explorer search view', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(
makePersistedUI({ rightSidebarTab: 'explorer', rightSidebarExplorerView: 'search' })
)
expect(store.getState().rightSidebarTab).toBe('explorer')
expect(store.getState().rightSidebarExplorerView).toBe('search')
})
it('hydrates a persisted workspace host scope', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ workspaceHostScope: 'ssh:win%20vm' }))
expect(store.getState().workspaceHostScope).toBe('ssh:win%20vm')
expect(store.getState().visibleWorkspaceHostIds).toEqual(['ssh:win%20vm'])
})
it('hydrates a persisted visible workspace host set', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
workspaceHostScope: 'ssh:win%20vm',
visibleWorkspaceHostIds: [
'local',
'ssh:win%20vm',
'bogus' as NonNullable<PersistedUIState['visibleWorkspaceHostIds']>[number],
'local'
]
})
)
expect(store.getState().workspaceHostScope).toBe('ssh:win%20vm')
expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'ssh:win%20vm'])
})
it('hydrates a persisted workspace host order', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
workspaceHostOrder: [
'ssh:win%20vm',
'bogus' as NonNullable<PersistedUIState['workspaceHostOrder']>[number],
'local',
'ssh:win%20vm'
]
})
)
expect(store.getState().workspaceHostOrder).toEqual(['ssh:win%20vm', 'local'])
})
it('hydrates and immediately applies the manual cross-host repo order', () => {
const store = createUIStore()
const local: Repo = {
id: 'same',
path: '/local',
displayName: 'Local',
badgeColor: '#000',
addedAt: 1,
executionHostId: 'local'
}
const remote: Repo = {
...local,
path: '/remote',
displayName: 'Remote',
executionHostId: 'runtime:node-b'
}
store.setState({ repos: [local, remote] })
store.getState().hydratePersistedUI(
makePersistedUI({
manualRepoOrder: [
{ hostId: 'runtime:node-b', repoId: 'same' },
{ hostId: 'invalid' as never, repoId: 'ignored' },
{ hostId: 'local', repoId: 'same' }
]
})
)
expect(store.getState().manualRepoOrder).toEqual([
{ hostId: 'runtime:node-b', repoId: 'same' },
{ hostId: 'local', repoId: 'same' }
])
expect(store.getState().repos).toEqual([remote, local])
})
it('falls back to all hosts for invalid persisted workspace host scopes', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(
makePersistedUI({ workspaceHostScope: 'bogus' as PersistedUIState['workspaceHostScope'] })
)
expect(store.getState().workspaceHostScope).toBe('all')
expect(store.getState().visibleWorkspaceHostIds).toBeNull()
})
it('tracks the per-project settings host selection without persisting it', () => {
const setUI = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setSettingsProjectHostSelection('git:acme/app', 'runtime:home-mac')
expect(store.getState().settingsProjectHostSelection).toEqual({
'git:acme/app': 'runtime:home-mac'
})
expect(store.getState().settingsProjectSetupSelection).toEqual({})
store
.getState()
.setSettingsProjectHostSelection('git:acme/app', 'runtime:home-mac', 'jump-setup')
expect(store.getState().settingsProjectSetupSelection).toEqual({
'git:acme/app': 'jump-setup'
})
expect(setUI).not.toHaveBeenCalled()
})
it('updates workspace host scope for the guarded UI writer', () => {
const setUI = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setWorkspaceHostScope('runtime:env-1')
expect(store.getState().workspaceHostScope).toBe('runtime:env-1')
expect(store.getState().visibleWorkspaceHostIds).toEqual(['runtime:env-1'])
expect(setUI).not.toHaveBeenCalled()
})
it('updates host visibility independently of focused host for the guarded UI writer', () => {
const setUI = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setWorkspaceHostScope('runtime:env-1')
store.getState().setVisibleWorkspaceHostIds(['local', 'runtime:env-1'])
expect(store.getState().workspaceHostScope).toBe('runtime:env-1')
expect(store.getState().visibleWorkspaceHostIds).toEqual(['local', 'runtime:env-1'])
expect(setUI).not.toHaveBeenCalled()
})
it('persists workspace host order changes', () => {
const setUI = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setWorkspaceHostOrder(['ssh:win%20vm', 'bogus' as never, 'local'])
expect(store.getState().workspaceHostOrder).toEqual(['ssh:win%20vm', 'local'])
expect(setUI).toHaveBeenCalledWith({ workspaceHostOrder: ['ssh:win%20vm', 'local'] })
})
it('persists group changes with collapsed groups cleared', () => {
const setUI = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.setState({ collapsedGroups: new Set(['repo:old']) })
store.getState().setGroupBy('none')
expect(store.getState().groupBy).toBe('none')
expect([...store.getState().collapsedGroups]).toEqual([])
expect(setUI).toHaveBeenCalledWith({ groupBy: 'none', collapsedGroups: [] })
})
it('hydrates persisted per-worktree explorer roots', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
explorerDisplayRootByWorktree: {
'repo-1::/repo': '/',
'repo-2::/repo': 'packages/app'
}
})
)
expect(store.getState().explorerDisplayRootByWorktree).toEqual({
'repo-1::/repo': '/',
'repo-2::/repo': 'packages/app'
})
})
it('hydrates persisted per-worktree dotfile visibility', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
showDotfilesByWorktree: {
'repo-1::/repo': false,
'repo-2::/repo': true
}
})
)
expect(store.getState().showDotfilesByWorktree).toEqual({
'repo-1::/repo': false,
'repo-2::/repo': true
})
})
it('does not churn persisted UI references when hydration is identical by value', () => {
const store = createUIStore()
const persistedUI = makePersistedUI({
featureTipsSeenIds: ['voice-dictation'],
contextualToursSeenIds: ['tasks'],
showDotfilesByWorktree: { 'repo-1::/repo': false },
collapsedGroups: ['repo:one'],
workspaceHostOrder: ['local'],
worktreeCardProperties: ['status', 'unread', 'ports'],
acknowledgedAgentsByPaneKey: { 'tab-1::pane-1': Date.now() }
})
store.getState().hydratePersistedUI(persistedUI)
const before = store.getState()
const references = {
acknowledgedAgentsByPaneKey: before.acknowledgedAgentsByPaneKey,
featureTipsSeenIds: before.featureTipsSeenIds,
contextualToursSeenIds: before.contextualToursSeenIds,
workspaceHostOrder: before.workspaceHostOrder,
showDotfilesByWorktree: before.showDotfilesByWorktree,
collapsedGroups: before.collapsedGroups,
worktreeCardProperties: before.worktreeCardProperties
}
store.getState().hydratePersistedUI(makePersistedUI({ ...persistedUI }))
const after = store.getState()
expect(after.acknowledgedAgentsByPaneKey).toBe(references.acknowledgedAgentsByPaneKey)
expect(after.featureTipsSeenIds).toBe(references.featureTipsSeenIds)
expect(after.contextualToursSeenIds).toBe(references.contextualToursSeenIds)
expect(after.workspaceHostOrder).toBe(references.workspaceHostOrder)
expect(after.showDotfilesByWorktree).toBe(references.showDotfilesByWorktree)
expect(after.collapsedGroups).toBe(references.collapsedGroups)
expect(after.worktreeCardProperties).toBe(references.worktreeCardProperties)
})
it('drops invalid persisted per-worktree dotfile visibility entries', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
showDotfilesByWorktree: {
'repo-1::/repo': false,
'repo-2::/repo': 'nope',
constructor: false
} as never
})
)
expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-1::/repo': false })
})
it('stores only per-worktree dotfile visibility opt-outs', () => {
const store = createUIStore()
store.getState().setShowDotfilesForWorktree('repo-1::/repo', false)
expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-1::/repo': false })
store.getState().setShowDotfilesForWorktree('repo-1::/repo', true)
expect(store.getState().showDotfilesByWorktree).toEqual({})
})
it('toggles per-worktree dotfile visibility independently', () => {
const store = createUIStore()
store.getState().toggleShowDotfilesForWorktree('repo-1::/repo')
store.getState().toggleShowDotfilesForWorktree('repo-2::/repo')
store.getState().toggleShowDotfilesForWorktree('repo-2::/repo')
expect(store.getState().showDotfilesByWorktree).toEqual({ 'repo-1::/repo': false })
})
it('falls back to explorer for invalid persisted right sidebar tabs', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(
makePersistedUI({ rightSidebarTab: 'bogus' as PersistedUIState['rightSidebarTab'] })
)
expect(store.getState().rightSidebarTab).toBe('explorer')
expect(store.getState().rightSidebarExplorerView).toBe('files')
})
it('clamps persisted sidebar widths into the supported range', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
sidebarWidth: 100,
rightSidebarWidth: 100
})
)
expect(store.getState().sidebarWidth).toBe(220)
expect(store.getState().rightSidebarWidth).toBe(220)
})
it('clamps persisted markdown toc panel widths into the supported range', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
markdownTocPanelWidth: 100
})
)
expect(store.getState().markdownTocPanelWidth).toBe(200)
})
it('clamps persisted combined diff file tree widths into the supported range', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ combinedDiffFileTreeWidth: 100 }))
expect(store.getState().combinedDiffFileTreeWidth).toBe(200)
store.getState().hydratePersistedUI(makePersistedUI({ combinedDiffFileTreeWidth: 5_000 }))
expect(store.getState().combinedDiffFileTreeWidth).toBe(640)
})
it('preserves right sidebar widths above the former 500px cap', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
sidebarWidth: 260,
rightSidebarWidth: 900
})
)
expect(store.getState().sidebarWidth).toBe(260)
expect(store.getState().rightSidebarWidth).toBe(900)
})
it('stores pending sidebar reveal rename requests', () => {
const store = createUIStore()
store.getState().revealWorktreeInSidebar('repo1::/feature', {
behavior: 'smooth',
highlight: true,
beginRename: true
})
expect(store.getState().pendingRevealWorktree).toEqual({
worktreeId: 'repo1::/feature',
behavior: 'smooth',
highlight: true,
beginRename: true
})
})
it('falls back to existing sidebar widths when persisted values are not finite', () => {
const store = createUIStore()
store.getState().setSidebarWidth(320)
store.setState({ rightSidebarWidth: 360 })
store.getState().hydratePersistedUI(
makePersistedUI({
sidebarWidth: Number.NaN,
rightSidebarWidth: Number.POSITIVE_INFINITY
})
)
expect(store.getState().sidebarWidth).toBe(320)
expect(store.getState().rightSidebarWidth).toBe(360)
})
})
@@ -1,77 +0,0 @@
import { describe, expect, it } from 'vitest'
import { createDefaultWorkspaceCleanupBrowseState } from '../../../../shared/workspace-cleanup-browse-state'
import { createUIStore, makePersistedUI } from './ui-slice-test-harness'
function persistedWithIdleDays(idleMinDays: number | null) {
const browse = createDefaultWorkspaceCleanupBrowseState()
browse.filters.activity.idleMinDays = idleMinDays
return makePersistedUI({ workspaceCleanup: { dismissals: {}, browse } })
}
describe('workspace cleanup browse hydration', () => {
it('restores persisted filters on startup', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(persistedWithIdleDays(30), 'startup')
expect(store.getState().workspaceCleanupBrowse.filters.activity.idleMinDays).toBe(30)
})
it('does not let a sync broadcast revert a filter the user just set', () => {
// Other ui.set broadcasts carry stale browse state until its debounced writer runs.
const store = createUIStore()
store.getState().hydratePersistedUI(persistedWithIdleDays(30), 'startup')
const edited = createDefaultWorkspaceCleanupBrowseState()
edited.filters.activity.idleMinDays = 45
store.setState({ workspaceCleanupBrowse: edited })
store.getState().hydratePersistedUI(persistedWithIdleDays(30), 'sync')
expect(store.getState().workspaceCleanupBrowse.filters.activity.idleMinDays).toBe(45)
})
it('does not let a sync broadcast revert a typed query', () => {
const store = createUIStore()
const edited = createDefaultWorkspaceCleanupBrowseState()
edited.filters.query = 'release'
store.setState({ workspaceCleanupBrowse: edited })
store.getState().hydratePersistedUI(persistedWithIdleDays(null), 'sync')
expect(store.getState().workspaceCleanupBrowse.filters.query).toBe('release')
})
it('defaults an absent source to sync, so an unlabelled broadcast cannot revert either', () => {
const store = createUIStore()
const edited = createDefaultWorkspaceCleanupBrowseState()
edited.filters.activity.idleMinDays = 45
store.setState({ workspaceCleanupBrowse: edited })
store.getState().hydratePersistedUI(persistedWithIdleDays(30))
expect(store.getState().workspaceCleanupBrowse.filters.activity.idleMinDays).toBe(45)
})
it('still hydrates dismissals on sync, which are main-owned and not edited here', () => {
const store = createUIStore()
const dismissal = {
worktreeId: 'repo-1::/repo/one',
dismissedAt: Date.now(),
fingerprint: 'fp-1',
classifierVersion: 2
}
store.getState().hydratePersistedUI(
makePersistedUI({
workspaceCleanup: {
dismissals: { [dismissal.worktreeId]: dismissal },
browse: createDefaultWorkspaceCleanupBrowseState()
}
}),
'sync'
)
expect(store.getState().workspaceCleanupDismissals[dismissal.worktreeId]).toBeDefined()
})
})
@@ -1,928 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { getWorktreeCardModeProperties } from '../../../../shared/constants'
import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types'
import type { AppState } from '../types'
import { createUIStore, makePersistedUI } from './ui-slice-test-harness'
const mocks = vi.hoisted(() => ({
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession
}))
vi.mock('@/lib/telemetry', () => ({
track: mocks.track
}))
vi.mock('sonner', () => ({
toast: {
message: mocks.toastMessage,
success: mocks.toastSuccess,
error: mocks.toastError
}
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
beforeEach(() => {
mocks.sendNotesToActiveAgentSession.mockReset()
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
mocks.track.mockReset()
mocks.toastMessage.mockReset()
mocks.toastSuccess.mockReset()
mocks.toastError.mockReset()
})
describe('createUISlice hydratePersistedUI', () => {
it('does not restore the retired active-only filter from persisted UI state', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
showActiveOnly: true
})
)
expect(store.getState().showActiveOnly).toBe(false)
})
it('restores the new hide-sleeping filter from persisted UI state', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
hideSleepingWorkspaces: true
})
)
expect(store.getState().showSleepingWorkspaces).toBe(false)
})
it('ignores legacy hidden-sleeping preference so existing users start with sleeping visible', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
showSleepingWorkspaces: false
})
)
expect(store.getState().showSleepingWorkspaces).toBe(true)
})
it('ignores the legacy show-inactive filter so existing users start with sleeping visible', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
showSleepingWorkspaces: undefined,
showInactiveWorkspaces: false
})
)
expect(store.getState().showSleepingWorkspaces).toBe(true)
})
it('restores the hide-default-branch filter from persisted UI state', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
hideDefaultBranchWorkspace: true
})
)
expect(store.getState().hideDefaultBranchWorkspace).toBe(true)
})
it('restores selected card properties during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
worktreeCardProperties: ['inline-agents']
})
)
expect(store.getState().worktreeCardProperties).toEqual(['status', 'unread', 'inline-agents'])
})
it('adds default-on status items once for older persisted UI', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
statusBarItems: ['claude', 'resource-usage'],
_portsStatusBarDefaultAdded: false
})
)
expect(store.getState().statusBarItems).toEqual([
'claude',
'resource-usage',
'ports',
'kimi',
'minimax',
'antigravity',
'grok',
'cursor',
'zcode'
])
expect(setUI).toHaveBeenCalledWith({
statusBarItems: [
'claude',
'resource-usage',
'ports',
'kimi',
'minimax',
'antigravity',
'grok',
'cursor',
'zcode'
],
_portsStatusBarDefaultAdded: true,
_kimiStatusBarDefaultAdded: true,
_minimaxStatusBarDefaultAdded: true,
_antigravityStatusBarDefaultAdded: true,
_grokStatusBarDefaultAdded: true,
_cursorStatusBarDefaultAdded: true,
_zcodeStatusBarDefaultAdded: true
})
})
it('preserves user-hidden default-on status items after one-shot migrations ran', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
statusBarItems: ['claude', 'resource-usage'],
_portsStatusBarDefaultAdded: true,
_kimiStatusBarDefaultAdded: true,
_minimaxStatusBarDefaultAdded: true,
_antigravityStatusBarDefaultAdded: true,
_grokStatusBarDefaultAdded: true,
_cursorStatusBarDefaultAdded: true,
_zcodeStatusBarDefaultAdded: true
})
)
expect(store.getState().statusBarItems).toEqual(['claude', 'resource-usage'])
expect(setUI).not.toHaveBeenCalled()
})
it('persists and hydrates the usage percentage display preference', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setUsagePercentageDisplay('used')
expect(store.getState().usagePercentageDisplay).toBe('used')
// Why: adapting the control also permanently dismisses the one-time change notice.
expect(setUI).toHaveBeenCalledWith({
usagePercentageDisplay: 'used',
usagePercentageDisplayChangeNoticeDismissed: true
})
expect(store.getState().usagePercentageDisplayChangeNoticeDismissed).toBe(true)
store.getState().hydratePersistedUI(makePersistedUI({ usagePercentageDisplay: 'remaining' }))
expect(store.getState().usagePercentageDisplay).toBe('remaining')
})
it('hydrates and dismisses the usage percentage display change notice', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ usagePercentageDisplayChangeNoticeDismissed: false }))
expect(store.getState().usagePercentageDisplayChangeNoticeDismissed).toBe(false)
store.getState().dismissUsagePercentageDisplayChangeNotice()
expect(store.getState().usagePercentageDisplayChangeNoticeDismissed).toBe(true)
expect(setUI).toHaveBeenCalledWith({ usagePercentageDisplayChangeNoticeDismissed: true })
setUI.mockClear()
store.getState().dismissUsagePercentageDisplayChangeNotice()
expect(setUI).not.toHaveBeenCalled()
})
it('defaults invalid usage percentage display values to used', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
usagePercentageDisplay: 'left' as PersistedUIState['usagePercentageDisplay']
})
)
expect(store.getState().usagePercentageDisplay).toBe('used')
})
it('initializes new users with compact status bar usage', () => {
expect(createUIStore().getState().statusBarUsageMode).toBe('compact')
})
it.each(['verbose', 'compact'] as const)(
'persists and hydrates explicit %s usage mode',
(mode) => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setStatusBarUsageMode(mode)
expect(store.getState().statusBarUsageMode).toBe(mode)
expect(setUI).toHaveBeenCalledWith({ statusBarUsageMode: mode })
const restoredStore = createUIStore()
restoredStore.getState().hydratePersistedUI(makePersistedUI({ statusBarUsageMode: mode }))
expect(restoredStore.getState().statusBarUsageMode).toBe(mode)
}
)
it.each([undefined, null, 'expanded'])(
'hydrates missing or invalid status bar usage mode %j as compact',
(value) => {
const store = createUIStore()
const ui = makePersistedUI()
if (value === undefined) {
delete ui.statusBarUsageMode
} else {
Reflect.set(ui, 'statusBarUsageMode', value)
}
store.getState().hydratePersistedUI(ui)
expect(store.getState().statusBarUsageMode).toBe('compact')
}
)
it('hydrates and permanently dismisses the Compact change notice', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true)
store
.getState()
.hydratePersistedUI(makePersistedUI({ statusBarCompactChangeNoticeDismissed: false }))
expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(false)
setUI.mockClear()
store.getState().dismissStatusBarCompactChangeNotice()
expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true)
expect(setUI).toHaveBeenCalledWith({ statusBarCompactChangeNoticeDismissed: true })
store.getState().dismissStatusBarCompactChangeNotice()
expect(setUI).toHaveBeenCalledTimes(1)
})
it.each(['verbose', 'compact'] as const)(
'dismisses the Compact notice when choosing %s',
(mode) => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ statusBarCompactChangeNoticeDismissed: false }))
store.getState().setStatusBarUsageMode(mode)
expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true)
expect(setUI).toHaveBeenCalledWith({
statusBarUsageMode: mode,
statusBarCompactChangeNoticeDismissed: true
})
}
)
it('keeps the Compact notice hidden with an older host that omits its flag', () => {
const store = createUIStore()
const ui = makePersistedUI()
delete ui.statusBarCompactChangeNoticeDismissed
store.getState().hydratePersistedUI(ui)
expect(store.getState().statusBarCompactChangeNoticeDismissed).toBe(true)
})
it('clamps persisted workspace board column width', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
workspaceBoardColumnWidth: 900
})
)
expect(store.getState().workspaceBoardColumnWidth).toBe(520)
})
it('defaults workspace board task status sync off and persists changes', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
expect(store.getState().syncTaskStatusFromWorkspaceBoard).toBe(false)
store.getState().hydratePersistedUI(
makePersistedUI({
syncTaskStatusFromWorkspaceBoard: true
})
)
expect(store.getState().syncTaskStatusFromWorkspaceBoard).toBe(true)
store.getState().setSyncTaskStatusFromWorkspaceBoard(false)
expect(store.getState().syncTaskStatusFromWorkspaceBoard).toBe(false)
expect(setUI).toHaveBeenCalledWith({ syncTaskStatusFromWorkspaceBoard: false })
})
it('hydrates a valid Kagi session link', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
browserKagiSessionLink: 'https://kagi.com/search?token=secret&q=%s'
})
)
expect(store.getState().browserKagiSessionLink).toBe('https://kagi.com/search?token=secret')
})
it('hydrates and normalizes the default browser zoom level', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
browserDefaultZoomLevel: 1.26
})
)
// 1.26 is about 130%, which snaps to Chrome's 125% preset.
expect(1.2 ** store.getState().browserDefaultZoomLevel).toBeCloseTo(1.25)
})
it('persists normalized default browser zoom changes', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setBrowserDefaultZoomLevel(10)
// Clamped to Chrome's 500% maximum.
const { browserDefaultZoomLevel } = store.getState()
expect(1.2 ** browserDefaultZoomLevel).toBeCloseTo(5)
expect(setUI).toHaveBeenCalledWith({ browserDefaultZoomLevel })
})
it('drops an invalid Kagi session link during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
browserKagiSessionLink: 'https://example.com/search?token=secret'
})
)
expect(store.getState().browserKagiSessionLink).toBeNull()
})
it('hydrates legacy sidekick persisted keys into pet state', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
petVisible: undefined,
petId: undefined,
petSize: undefined,
customPets: undefined,
sidekickVisible: false,
sidekickId: 'custom-pet',
sidekickSize: 240,
customSidekicks: [
{
id: 'custom-pet',
label: 'Legacy pet',
fileName: 'custom-pet.webp',
mimeType: 'image/webp',
kind: 'image'
}
]
})
)
expect(store.getState().petVisible).toBe(false)
expect(store.getState().petId).toBe('custom-pet')
expect(store.getState().petSize).toBe(240)
expect(store.getState().customPets).toEqual([
{
id: 'custom-pet',
label: 'Legacy pet',
fileName: 'custom-pet.webp',
mimeType: 'image/webp',
kind: 'image'
}
])
})
it('sanitizes task resume state field-by-field during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
taskResumeState: {
githubMode: 'project',
githubItemsPreset: 'invalid',
githubItemsQuery: 42,
linearPreset: 'completed',
linearQuery: 'label:bug',
jiraPreset: 'reported',
jiraQuery: 99
} as unknown as PersistedUIState['taskResumeState']
})
)
expect(store.getState().taskResumeState).toEqual({
githubMode: 'project',
linearPreset: 'completed',
linearQuery: 'label:bug',
jiraPreset: 'reported'
})
})
// Ignore legacy host-persisted Linear views: now device-local, their key is rejected by strict ui.set.
it('ignores a stale host-persisted Linear issue view during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
taskResumeState: {
linearQuery: 'label:bug',
linearIssueView: { viewMode: 'board', groupBy: 'assignee' }
} as unknown as PersistedUIState['taskResumeState']
})
)
expect(store.getState().taskResumeState).toEqual({ linearQuery: 'label:bug' })
})
it('restores acknowledgedAgentsByPaneKey from persisted UI state', () => {
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: { 'tab-a:0': now, 'tab-b:1': now - 5_000 }
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-a:0': now,
'tab-b:1': now - 5_000
})
} finally {
vi.useRealTimers()
}
})
it('falls back to an empty ack map when persisted UI omits acknowledgedAgentsByPaneKey', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI())
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is null', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey:
null as unknown as PersistedUIState['acknowledgedAgentsByPaneKey']
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is a string', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey:
'oops' as unknown as PersistedUIState['acknowledgedAgentsByPaneKey']
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('falls back to an empty ack map when persisted acknowledgedAgentsByPaneKey is an array', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: [
'a',
'b'
] as unknown as PersistedUIState['acknowledgedAgentsByPaneKey']
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({})
})
it('drops non-number / non-finite / non-positive entries from acknowledgedAgentsByPaneKey', () => {
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: {
'tab-a:0': now,
'tab-b:1': now - 1000,
'tab-c:2': 'not-a-number',
'tab-d:3': Number.NaN,
'tab-e:4': Number.POSITIVE_INFINITY,
'tab-f:5': -1
} as unknown as Record<string, number>
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-a:0': now,
'tab-b:1': now - 1000
})
} finally {
vi.useRealTimers()
}
})
it('keeps agents scope filter array identities stable across unchanged re-hydrations', () => {
const store = createUIStore()
const persisted = makePersistedUI({
agentsVisibleHostIds: ['ssh:devbox'],
agentsFilterRepoIds: ['repo-1']
})
store.getState().hydratePersistedUI(persisted)
const firstHostIds = store.getState().agentsVisibleHostIds
const firstRepoIds = store.getState().agentsFilterRepoIds
// Sync fires on every ui:changed; preserve array identity to avoid rebuilding agent scope memos.
store.getState().hydratePersistedUI(makePersistedUI({ ...persisted }))
expect(store.getState().agentsVisibleHostIds).toBe(firstHostIds)
expect(store.getState().agentsFilterRepoIds).toBe(firstRepoIds)
store
.getState()
.hydratePersistedUI(makePersistedUI({ ...persisted, agentsVisibleHostIds: ['ssh:otherbox'] }))
expect(store.getState().agentsVisibleHostIds).toEqual(['ssh:otherbox'])
expect(store.getState().agentsFilterRepoIds).toBe(firstRepoIds)
})
it('hydrates agents view preferences with safe defaults for absent fields', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({}))
expect(store.getState().agentsVisibleHostIds).toBeNull()
expect(store.getState().agentsFilterRepoIds).toEqual([])
expect(store.getState().agentsHideWorkspacesFromOtherDevices).toBe(false)
expect(store.getState().agentsHideAutomationGeneratedWorkspaces).toBe(false)
expect(store.getState().agentsHideCliCreatedWorkspaces).toBe(false)
expect(store.getState().agentsShowChildAgents).toBe(false)
expect(store.getState().agentsCompactMode).toBe(true)
expect(store.getState().agentsShowSearch).toBe(true)
expect(store.getState().agentsReadFilter).toBe('all')
expect(store.getState().agentsGroupBy).toBe('status')
})
it('restores the agents workspace-origin filters independently of the workspace-nav ones', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
agentsHideWorkspacesFromOtherDevices: true,
agentsHideAutomationGeneratedWorkspaces: true,
agentsHideCliCreatedWorkspaces: true,
hideCliCreatedWorkspaces: false
})
)
expect(store.getState().agentsHideWorkspacesFromOtherDevices).toBe(true)
expect(store.getState().agentsHideAutomationGeneratedWorkspaces).toBe(true)
expect(store.getState().agentsHideCliCreatedWorkspaces).toBe(true)
expect(store.getState().hideCliCreatedWorkspaces).toBe(false)
})
it('restores a hidden agents search field', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ agentsShowSearch: false }))
expect(store.getState().agentsShowSearch).toBe(false)
})
it('restores the persisted agents read filter and grouping, rejecting unknown values', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ agentsReadFilter: 'unread', agentsGroupBy: 'project' }))
expect(store.getState().agentsReadFilter).toBe('unread')
expect(store.getState().agentsGroupBy).toBe('project')
store.getState().hydratePersistedUI(
makePersistedUI({
agentsReadFilter: 'bogus' as unknown as PersistedUIState['agentsReadFilter'],
agentsGroupBy: 'bogus' as unknown as PersistedUIState['agentsGroupBy']
})
)
expect(store.getState().agentsReadFilter).toBe('all')
expect(store.getState().agentsGroupBy).toBe('status')
})
it('sanitizes malformed agents repo filters before the repo catalog loads', () => {
const store = createUIStore()
expect(() =>
store.getState().hydratePersistedUI(
makePersistedUI({
agentsFilterRepoIds: 'repo-1' as unknown as PersistedUIState['agentsFilterRepoIds']
})
)
).not.toThrow()
expect(store.getState().agentsFilterRepoIds).toEqual([])
store.getState().hydratePersistedUI(
makePersistedUI({
agentsFilterRepoIds: [
'repo-1',
42,
'missing'
] as unknown as PersistedUIState['agentsFilterRepoIds']
})
)
expect(store.getState().agentsFilterRepoIds).toEqual(['repo-1', 'missing'])
})
it('sanitizes and prunes agents repo filters against a loaded repo catalog', () => {
const store = createUIStore()
store.setState({
repos: [
{
id: 'repo-1',
path: '/tmp/repo-1',
displayName: 'Repo 1',
badgeColor: 'gray',
addedAt: 1,
kind: 'git'
}
]
})
expect(() =>
store.getState().hydratePersistedUI(
makePersistedUI({
agentsFilterRepoIds: [
'repo-1',
null,
'missing'
] as unknown as PersistedUIState['agentsFilterRepoIds']
})
)
).not.toThrow()
expect(store.getState().agentsFilterRepoIds).toEqual(['repo-1'])
})
it('prunes acknowledgedAgentsByPaneKey entries older than the 7-day TTL during hydration', () => {
// HYDRATE_MAX_AGE_MS lives in src/renderer/src/store/slices/ui.ts and matches
// the constant in src/main/agent-hooks/server.ts.
const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: {
'tab-recent:0': now,
'tab-old:1': now - SEVEN_DAYS_MS - 1
}
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-recent:0': now
})
} finally {
// Shared teardown leaves timers intact; restore real timers so later tests cannot inherit this clock.
vi.useRealTimers()
}
})
it('drops prototype-pollution keys from acknowledgedAgentsByPaneKey during hydration', () => {
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
const malicious: Record<string, number> = {}
// Define __proto__ as an own enumerable property rather than changing Object.prototype.
Object.defineProperty(malicious, '__proto__', {
value: now,
enumerable: true,
configurable: true,
writable: true
})
Object.defineProperty(malicious, 'constructor', {
value: now,
enumerable: true,
configurable: true,
writable: true
})
Object.defineProperty(malicious, 'prototype', {
value: now,
enumerable: true,
configurable: true,
writable: true
})
malicious['tab-safe:0'] = now
store.getState().hydratePersistedUI(
makePersistedUI({
acknowledgedAgentsByPaneKey: malicious
})
)
expect(store.getState().acknowledgedAgentsByPaneKey).toEqual({
'tab-safe:0': now
})
} finally {
vi.useRealTimers()
}
})
it('merges and persists partial task resume updates', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.setState({ taskResumeState: { githubMode: 'project', linearPreset: 'all' } })
store.getState().setTaskResumeState({ githubItemsPreset: 'my-prs' })
const expected = { githubMode: 'project', linearPreset: 'all', githubItemsPreset: 'my-prs' }
expect(store.getState().taskResumeState).toEqual(expected)
expect(setUI).toHaveBeenCalledWith({ taskResumeState: expected })
})
it('sets Default worktree card mode with matching settings and UI writes', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
const setSettings = vi.fn().mockResolvedValue({ compactWorktreeCards: false })
vi.stubGlobal('window', {
api: { ui: { set: setUI }, settings: { set: setSettings } }
})
const store = createUIStore()
store.setState({
settings: { compactWorktreeCards: true } as AppState['settings'],
worktreeCardProperties: ['status', 'branch']
})
store.getState().setWorktreeCardMode('Default')
const expected = getWorktreeCardModeProperties('Default')
expect(store.getState().settings?.compactWorktreeCards).toBe(false)
expect(store.getState().worktreeCardProperties).toEqual(expected)
expect(setSettings).toHaveBeenCalledWith({ compactWorktreeCards: false })
expect(setUI).toHaveBeenCalledWith({
worktreeCardProperties: expected,
_worktreeCardModeDefaulted: true
})
})
it('sets Compact worktree card mode and removes migrated branch', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
const setSettings = vi.fn().mockResolvedValue({ compactWorktreeCards: true })
vi.stubGlobal('window', {
api: { ui: { set: setUI }, settings: { set: setSettings } }
})
const store = createUIStore()
store.setState({
settings: { compactWorktreeCards: false } as AppState['settings'],
worktreeCardProperties: ['status', 'branch', 'inline-agents']
})
store.getState().setWorktreeCardMode('Compact')
const expected = getWorktreeCardModeProperties('Compact')
expect(store.getState().settings?.compactWorktreeCards).toBe(true)
expect(store.getState().worktreeCardProperties).toEqual(expected)
expect(store.getState().worktreeCardProperties).not.toContain('branch')
expect(store.getState().worktreeCardProperties).not.toContain('inline-agents')
expect(setSettings).toHaveBeenCalledWith({ compactWorktreeCards: true })
expect(setUI).toHaveBeenCalledWith({
worktreeCardProperties: expected,
_worktreeCardModeDefaulted: true
})
})
it('sets custom worktree card properties', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setWorktreeCardProperties(['inline-agents', 'inline-agents'])
expect(store.getState().worktreeCardProperties).toEqual(['status', 'unread', 'inline-agents'])
expect(store.getState()._worktreeCardModeDefaulted).toBe(false)
expect(setUI).toHaveBeenCalledWith({
worktreeCardProperties: ['status', 'unread', 'inline-agents'],
_worktreeCardModeDefaulted: false
})
})
it('persists the agent activity display mode', () => {
const setUI = vi.fn().mockResolvedValue(undefined)
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().setAgentActivityDisplayMode('full')
expect(store.getState().agentActivityDisplayMode).toBe('full')
expect(setUI).toHaveBeenCalledWith({ agentActivityDisplayMode: 'full' })
})
it('normalizes invalid persisted agent activity display modes', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
agentActivityDisplayMode: 'bogus' as PersistedUIState['agentActivityDisplayMode']
})
)
expect(store.getState().agentActivityDisplayMode).toBe('compact')
})
})
describe('createUISlice hydratePersistedUI manual unread turns', () => {
it('restores manual unread stamps and prunes malformed or stale ones', () => {
const store = createUIStore()
const fresh = Date.now() - 60_000
const stale = Date.now() - 8 * 24 * 60 * 60 * 1000
store.getState().hydratePersistedUI(
makePersistedUI({
manuallyUnreadTurnsByPaneKey: {
'tab-a:1': fresh,
'tab-b:1': stale,
'tab-c:1': 'bogus' as unknown as number
}
})
)
expect(store.getState().manuallyUnreadTurnsByPaneKey).toEqual({ 'tab-a:1': fresh })
})
it('hydrates to an empty record when the field is absent from an older profile', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ manuallyUnreadTurnsByPaneKey: undefined }))
expect(store.getState().manuallyUnreadTurnsByPaneKey).toEqual({})
})
})
@@ -7,36 +7,6 @@ function dismissalData(onDismissed: () => void): Record<string, unknown> {
}
describe('UI modal slot dismissal', () => {
it('dismisses replaced and closed entries once', () => {
const store = createUIStore()
const firstDismissed = vi.fn()
const secondDismissed = vi.fn()
store.getState().openModal('worktree-palette', dismissalData(firstDismissed))
store.getState().openModal('quick-open', dismissalData(secondDismissed))
store.getState().closeModal()
store.getState().closeModal()
expect(firstDismissed).toHaveBeenCalledOnce()
expect(secondDismissed).toHaveBeenCalledOnce()
})
it('dismisses each entry across consecutive replacements', () => {
const store = createUIStore()
const firstDismissed = vi.fn()
const secondDismissed = vi.fn()
const thirdDismissed = vi.fn()
store.getState().openModal('worktree-palette', dismissalData(firstDismissed))
store.getState().openModal('quick-open', dismissalData(secondDismissed))
store.getState().openModal('add-repo', dismissalData(thirdDismissed))
store.getState().closeModal()
expect(firstDismissed).toHaveBeenCalledOnce()
expect(secondDismissed).toHaveBeenCalledOnce()
expect(thirdDismissed).toHaveBeenCalledOnce()
})
it('updates the slot before notifying the evicted entry', () => {
const store = createUIStore()
const observedModal = vi.fn(() => store.getState().activeModal)
@@ -47,15 +17,6 @@ describe('UI modal slot dismissal', () => {
expect(observedModal).toHaveReturnedWith('quick-open')
})
it('ignores modal data without a callable dismissal hook', () => {
const store = createUIStore()
store.getState().openModal('worktree-palette', { [MODAL_DISMISSED_KEY]: 'invalid' })
expect(() => store.getState().openModal('quick-open')).not.toThrow()
expect(store.getState().activeModal).toBe('quick-open')
})
it('settles reentrant replacement and close paths once', () => {
const store = createUIStore()
const replacementDismissed = vi.fn()
@@ -73,24 +34,4 @@ describe('UI modal slot dismissal', () => {
expect(reentrantDismissed).toHaveBeenCalledOnce()
expect(store.getState().activeModal).toBe('none')
})
it('performs one bounded notification per transition under repeated replacement', () => {
const store = createUIStore()
const dismissed = new Set<number>()
const transitionCount = 1_000
for (let id = 0; id < transitionCount; id += 1) {
store.getState().openModal(
'worktree-palette',
dismissalData(() => {
expect(dismissed.has(id)).toBe(false)
dismissed.add(id)
})
)
}
store.getState().closeModal()
expect(dismissed.size).toBe(transitionCount)
expect(store.getState().modalData).toEqual({})
})
})
@@ -1,384 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createUIStore, makePersistedUI } from './ui-slice-test-harness'
const mocks = vi.hoisted(() => ({
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession
}))
vi.mock('@/lib/telemetry', () => ({
track: mocks.track
}))
vi.mock('sonner', () => ({
toast: {
message: mocks.toastMessage,
success: mocks.toastSuccess,
error: mocks.toastError
}
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
beforeEach(() => {
mocks.sendNotesToActiveAgentSession.mockReset()
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
mocks.track.mockReset()
mocks.toastMessage.mockReset()
mocks.toastSuccess.mockReset()
mocks.toastError.mockReset()
})
describe('createUISlice feature tips', () => {
it('marks feature tips seen and persists them once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().markFeatureTipsSeen(['voice-dictation'])
store.getState().markFeatureTipsSeen(['voice-dictation'])
expect(store.getState().featureTipsSeenIds).toEqual(['voice-dictation'])
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ featureTipsSeenIds: ['voice-dictation'] })
})
it('normalizes persisted feature tip ids during hydration', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
featureTipsSeenIds: ['voice-dictation', 'unknown', 'voice-dictation'] as never
})
)
expect(store.getState().featureTipsSeenIds).toEqual(['voice-dictation'])
})
})
describe('createUISlice setup guide sidebar dismissal', () => {
it('persists sidebar dismissal changes once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().setSetupGuideSidebarDismissed(true)
store.getState().setSetupGuideSidebarDismissed(true)
expect(store.getState().setupGuideSidebarDismissed).toBe(true)
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ setupGuideSidebarDismissed: true })
})
it('hydrates only explicit sidebar dismissals as hidden', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ setupGuideSidebarDismissed: true }))
expect(store.getState().setupGuideSidebarDismissed).toBe(true)
store.getState().hydratePersistedUI(makePersistedUI({ setupGuideSidebarDismissed: undefined }))
expect(store.getState().setupGuideSidebarDismissed).toBe(false)
})
it('persists browser milestone migration result once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().markSetupGuideBrowserMilestoneMigrated(true)
store.getState().markSetupGuideBrowserMilestoneMigrated(true)
expect(store.getState().setupGuideBrowserMilestoneMigrated).toBe(true)
expect(store.getState().setupGuideBrowserMilestoneLegacyComplete).toBe(true)
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({
setupGuideBrowserMilestoneMigrated: true,
setupGuideBrowserMilestoneLegacyComplete: true
})
})
it('hydrates browser milestone migration fields explicitly', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(
makePersistedUI({
setupGuideBrowserMilestoneMigrated: true,
setupGuideBrowserMilestoneLegacyComplete: true
})
)
expect(store.getState().setupGuideBrowserMilestoneMigrated).toBe(true)
expect(store.getState().setupGuideBrowserMilestoneLegacyComplete).toBe(true)
store.getState().hydratePersistedUI(
makePersistedUI({
setupGuideBrowserMilestoneMigrated: undefined,
setupGuideBrowserMilestoneLegacyComplete: undefined
})
)
expect(store.getState().setupGuideBrowserMilestoneMigrated).toBe(false)
expect(store.getState().setupGuideBrowserMilestoneLegacyComplete).toBe(false)
})
})
describe('createUISlice mobile emulator agent setup dismissal', () => {
it('persists mobile emulator agent setup dismissal once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().dismissMobileEmulatorAgentSetup()
store.getState().dismissMobileEmulatorAgentSetup()
expect(store.getState().mobileEmulatorAgentSetupDismissed).toBe(true)
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ mobileEmulatorAgentSetupDismissed: true })
})
it('hydrates only explicit mobile emulator agent setup dismissals', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ mobileEmulatorAgentSetupDismissed: true }))
expect(store.getState().mobileEmulatorAgentSetupDismissed).toBe(true)
store
.getState()
.hydratePersistedUI(makePersistedUI({ mobileEmulatorAgentSetupDismissed: undefined }))
expect(store.getState().mobileEmulatorAgentSetupDismissed).toBe(false)
})
})
describe('createUISlice mobile emulator tab intro dismissal', () => {
it('persists mobile emulator tab intro dismissal once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().dismissMobileEmulatorTabIntro()
store.getState().dismissMobileEmulatorTabIntro()
expect(store.getState().mobileEmulatorTabIntroDismissed).toBe(true)
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ mobileEmulatorTabIntroDismissed: true })
})
it('hydrates only explicit mobile emulator tab intro dismissals', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ mobileEmulatorTabIntroDismissed: true }))
expect(store.getState().mobileEmulatorTabIntroDismissed).toBe(true)
store
.getState()
.hydratePersistedUI(makePersistedUI({ mobileEmulatorTabIntroDismissed: undefined }))
expect(store.getState().mobileEmulatorTabIntroDismissed).toBe(false)
})
})
describe('createUISlice browser import hint dismissal', () => {
it('persists browser import hint dismissal changes once', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const store = createUIStore()
store.getState().setBrowserImportHintHidden(true)
store.getState().setBrowserImportHintHidden(true)
expect(store.getState().browserImportHintHidden).toBe(true)
expect(setMock).toHaveBeenCalledTimes(1)
expect(setMock).toHaveBeenCalledWith({ browserImportHintHidden: true })
})
it('hydrates only explicit browser import hint dismissals as hidden', () => {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI({ browserImportHintHidden: true }))
expect(store.getState().browserImportHintHidden).toBe(true)
store.getState().hydratePersistedUI(makePersistedUI({ browserImportHintHidden: undefined }))
expect(store.getState().browserImportHintHidden).toBe(false)
})
})
describe('createUISlice Codex shared-settings notice', () => {
it('counts as seen until hydration, then follows the persisted flag', () => {
const store = createUIStore()
expect(store.getState().codexSharedSettingsNoticeSeen).toBe(true)
store.getState().hydratePersistedUI(makePersistedUI({}))
expect(store.getState().codexSharedSettingsNoticeSeen).toBe(false)
store.getState().hydratePersistedUI(makePersistedUI({ codexSharedSettingsNoticeSeen: true }))
expect(store.getState().codexSharedSettingsNoticeSeen).toBe(true)
})
})
describe('createUISlice Claude diff panel notice', () => {
it('counts as seen until hydration, then follows the persisted flag', () => {
const store = createUIStore()
expect(store.getState().claudeDiffPanelNoticeSeen).toBe(true)
store.getState().hydratePersistedUI(makePersistedUI({}))
expect(store.getState().claudeDiffPanelNoticeSeen).toBe(false)
store.getState().hydratePersistedUI(makePersistedUI({ claudeDiffPanelNoticeSeen: true }))
expect(store.getState().claudeDiffPanelNoticeSeen).toBe(true)
})
})
describe('createUISlice clearOsc52ClipboardDefaultOnNotice', () => {
it('restores the armed notice from persisted UI', () => {
const store = createUIStore()
expect(store.getState().osc52ClipboardDefaultOnNoticePending).toBe(false)
store
.getState()
.hydratePersistedUI(makePersistedUI({ osc52ClipboardDefaultOnNoticePending: true }))
expect(store.getState().osc52ClipboardDefaultOnNoticePending).toBe(true)
})
it('stops the toast this session even when the persist fails', () => {
// Dismiss locally before persisting so failure cannot repeatedly toast this session; next launch may re-arm.
const setUI = vi.fn(() => Promise.reject(new Error('runtime offline')))
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store
.getState()
.hydratePersistedUI(makePersistedUI({ osc52ClipboardDefaultOnNoticePending: true }))
store.getState().clearOsc52ClipboardDefaultOnNotice()
expect(store.getState().osc52ClipboardDefaultOnNoticePending).toBe(false)
expect(setUI).toHaveBeenCalledWith({ osc52ClipboardDefaultOnNoticePending: false })
})
})
describe('unexpected sign-out dismissal persistence', () => {
it('persists a dismissal once even when effects repeat', () => {
const setUI = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', { api: { ui: { set: setUI } } })
const store = createUIStore()
store.getState().dismissUnexpectedSignoutCard('1.2.3')
store.getState().dismissUnexpectedSignoutCard('1.2.3')
expect(store.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3')
expect(setUI).toHaveBeenCalledExactlyOnceWith({ dismissedUnexpectedSignoutVersion: '1.2.3' })
})
it.each([undefined, null, '1.2.2'])(
'does not re-arm a local dismissal from stale hydration (%s)',
(dismissedUnexpectedSignoutVersion) => {
vi.stubGlobal('window', { api: { ui: { set: vi.fn(() => Promise.resolve()) } } })
const store = createUIStore()
store.getState().dismissUnexpectedSignoutCard('1.2.3')
store.getState().hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion }))
expect(store.getState().unexpectedSignoutDismissedVersions).toContain('1.2.3')
}
)
it('defaults legacy profiles and restores dismissal on reopen', () => {
const store = createUIStore()
expect(store.getState().dismissedUnexpectedSignoutVersion).toBeNull()
store
.getState()
.hydratePersistedUI(
makePersistedUI({ dismissedUnexpectedSignoutVersion: undefined }),
'startup'
)
expect(store.getState().dismissedUnexpectedSignoutVersion).toBeNull()
const reopened = createUIStore()
reopened
.getState()
.hydratePersistedUI(
makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }),
'startup'
)
expect(reopened.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3')
})
it('accepts another window dismissal after hydrating an older version', () => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(
makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.2' }),
'startup'
)
store
.getState()
.hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }))
expect(store.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3')
})
})
describe('unexpected sign-out hydrated dismissal history', () => {
it.each([undefined, null, '1.2.2', '1.2.4'])(
'retains an observed dismissal after a different version sync (%s)',
(dismissedUnexpectedSignoutVersion) => {
const store = createUIStore()
store
.getState()
.hydratePersistedUI(
makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }),
'startup'
)
store.getState().hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion }))
expect(store.getState().unexpectedSignoutDismissedVersions).toContain('1.2.3')
}
)
})
@@ -1,756 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { getDefaultSettings } from '../../../../shared/constants'
import type { GitHubWorkItem } from '../../../../shared/github/work-item-types'
import type { LinearIssue } from '../../../../shared/linear/issue-types'
import type { GitLabWorkItem } from '../../../../shared/gitlab-types'
import type { Worktree } from '../../../../shared/worktree/types'
import type { FeatureInteractionState } from '../../../../shared/feature-interactions'
import type { TaskSourceContext } from '../../../../shared/task-source-context'
import type { AppState } from '../types'
import type { JiraIssue } from '../../../../shared/jira/jira-types'
import { createUIStore, makePersistedUI } from './ui-slice-test-harness'
const mocks = vi.hoisted(() => ({
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession
}))
vi.mock('@/lib/telemetry', () => ({
track: mocks.track
}))
vi.mock('sonner', () => ({
toast: {
message: mocks.toastMessage,
success: mocks.toastSuccess,
error: mocks.toastError
}
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
beforeEach(() => {
mocks.sendNotesToActiveAgentSession.mockReset()
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
mocks.track.mockReset()
mocks.toastMessage.mockReset()
mocks.toastSuccess.mockReset()
mocks.toastError.mockReset()
})
function makeWorktree(id: string): Worktree {
return { id } as unknown as Worktree
}
function makeGitHubWorkItem(overrides: Partial<GitHubWorkItem> = {}): GitHubWorkItem {
return {
id: 'pr-95',
type: 'pr',
number: 95,
title: 'feat: add file upload command',
state: 'open',
url: 'https://github.com/acme/repo/pull/95',
labels: [],
updatedAt: '2026-05-20T00:00:00.000Z',
author: 'octocat',
repoId: 'repo-1',
...overrides
}
}
function makeLinearIssue(overrides: Partial<LinearIssue> = {}): LinearIssue {
return {
id: 'lin-1',
identifier: 'ORC-1',
title: 'Fix task flow',
url: 'https://linear.app/orca/issue/ORC-1/fix-task-flow',
state: { name: 'Todo', type: 'unstarted', color: '#999' },
priority: 0,
estimate: null,
assignee: null,
labels: [],
labelIds: [],
team: { id: 'team-1', name: 'Orca', key: 'ORC' },
workspaceId: 'workspace-1',
updatedAt: '2026-05-30T00:00:00.000Z',
createdAt: '2026-05-30T00:00:00.000Z',
...overrides
} as LinearIssue
}
function makeJiraIssue(overrides: Partial<JiraIssue> = {}): JiraIssue {
return {
id: 'ORC-1',
key: 'ORC-1',
title: 'Fix task source context',
url: 'https://example.atlassian.net/browse/ORC-1',
siteId: 'site-1',
siteName: 'Example Jira',
project: { id: '10000', key: 'ORC', name: 'Orca', siteId: 'site-1' },
issueType: { id: '10001', name: 'Bug' },
status: { id: '1', name: 'Todo', categoryKey: 'new', categoryName: 'To Do' },
labels: [],
createdAt: '2026-05-30T00:00:00.000Z',
updatedAt: '2026-05-30T00:00:00.000Z',
...overrides
}
}
function makeGitLabWorkItem(overrides: Partial<GitLabWorkItem> = {}): GitLabWorkItem {
return {
id: 'mr-12',
type: 'mr',
number: 12,
title: 'Fix runner routing',
state: 'opened',
url: 'https://gitlab.com/acme/repo/-/merge_requests/12',
labels: [],
updatedAt: '2026-05-30T00:00:00.000Z',
author: 'gitlab-user',
repoId: 'repo-1',
...overrides
}
}
describe('createUISlice settings navigation', () => {
it('accepts a host-qualified setup guide target', () => {
const store = createUIStore()
store.getState().openSettingsTarget({ pane: 'setup-guide', repoId: null, hostId: 'ssh:host-1' })
expect(store.getState().settingsNavigationTarget).toEqual({
pane: 'setup-guide',
repoId: null,
hostId: 'ssh:host-1'
})
})
it('rejects malformed settings targets before storing them', () => {
const store = createUIStore()
const openSettingsTarget = store.getState().openSettingsTarget as unknown as (
target: unknown
) => void
expect(() =>
openSettingsTarget({ pane: 'repo', repoId: 'repo-1', hostId: 'invalid' })
).toThrowError('openSettingsTarget received an invalid navigation target')
expect(store.getState().settingsNavigationTarget).toBeNull()
})
it('prefetches the restored default task source when provider settings drifted', () => {
const store = createUIStore()
const prefetchWorkItems = vi.fn()
const prefetchLinearIssues = vi.fn()
store.setState({
repos: [
{
id: 'repo-1',
path: '/repo',
displayName: 'Repo',
badgeColor: 'blue',
addedAt: 1,
kind: 'git'
}
],
settings: {
visibleTaskProviders: ['linear'],
defaultTaskSource: 'github',
defaultTaskViewPreset: 'all'
} as unknown as AppState['settings'],
linearStatus: { connected: true } as AppState['linearStatus'],
preflightStatus: { glab: { installed: false } } as AppState['preflightStatus'],
prefetchWorkItems,
prefetchLinearIssues
} as unknown as Partial<AppState>)
store.getState().openTaskPage()
expect(prefetchWorkItems).toHaveBeenCalledWith(
'repo-1',
'/repo',
expect.any(Number),
'is:issue is:open',
{ sourceContext: null }
)
expect(prefetchLinearIssues).not.toHaveBeenCalled()
})
it('prefetches direct GitHub task opens with their source context', () => {
const store = createUIStore()
const prefetchWorkItems = vi.fn()
const workItem = makeGitHubWorkItem()
const sourceContext: TaskSourceContext = {
kind: 'task-source',
provider: 'github',
projectId: 'project-1',
hostId: 'ssh:devbox',
projectHostSetupId: 'setup-1',
repoId: 'repo-1',
providerIdentity: { provider: 'github', owner: 'acme', repo: 'repo' }
}
store.setState({
repos: [
{
id: 'repo-1',
path: '/repo',
displayName: 'Repo',
badgeColor: 'blue',
addedAt: 1,
kind: 'git'
}
],
settings: {
visibleTaskProviders: ['github'],
defaultTaskSource: 'github',
defaultTaskViewPreset: 'all'
} as unknown as AppState['settings'],
prefetchWorkItems
} as unknown as Partial<AppState>)
store.getState().openTaskPage({
taskSource: 'github',
preselectedRepoId: 'repo-1',
openGitHubWorkItem: workItem,
openGitHubSourceContext: sourceContext
})
expect(prefetchWorkItems).toHaveBeenCalledWith(
'repo-1',
'/repo',
expect.any(Number),
'is:issue is:open',
{ sourceContext }
)
})
it('prefetches direct Linear task opens with their source context', () => {
const store = createUIStore()
const prefetchLinearIssues = vi.fn()
const linearIssue = makeLinearIssue()
const sourceContext: TaskSourceContext = {
kind: 'task-source',
provider: 'linear',
projectId: 'project-1',
hostId: 'runtime:remote-server',
providerIdentity: { provider: 'linear', workspaceId: 'workspace-1' }
}
store.setState({
settings: {
visibleTaskProviders: ['linear'],
defaultTaskSource: 'linear'
} as unknown as AppState['settings'],
linearStatus: { connected: true } as AppState['linearStatus'],
prefetchLinearIssues
} as unknown as Partial<AppState>)
store.getState().openTaskPage({
taskSource: 'linear',
openLinearIssue: linearIssue,
openLinearSourceContext: sourceContext
})
expect(prefetchLinearIssues).toHaveBeenCalledWith(
{ kind: 'list', filter: 'all', limit: expect.any(Number) },
{ sourceContext }
)
})
it('returns to the tasks page after visiting settings from an in-progress draft', () => {
const store = createUIStore()
store.getState().openTaskPage({ preselectedRepoId: 'repo-1' })
store.getState().openSettingsPage()
expect(store.getState().activeView).toBe('settings')
expect(store.getState().previousViewBeforeSettings).toBe('tasks')
store.getState().closeSettingsPage()
expect(store.getState().activeView).toBe('tasks')
})
it('keeps the original return target when settings is reopened while already visible', () => {
const store = createUIStore()
store.getState().openTaskPage()
store.getState().openSettingsPage()
store.getState().openSettingsPage()
expect(store.getState().previousViewBeforeSettings).toBe('tasks')
store.getState().closeSettingsPage()
expect(store.getState().activeView).toBe('tasks')
})
it('returns to the graduated Agents view after visiting settings', () => {
const store = createUIStore()
store.getState().openActivityPage()
expect(store.getState().activeView).toBe('activity')
store.getState().openSettingsPage()
store.getState().closeSettingsPage()
expect(store.getState().activeView).toBe('activity')
})
it('clears transient settings search when opening settings', () => {
const store = createUIStore()
store.setState({ settingsSearchInputQuery: 'terminal', settingsSearchQuery: 'terminal' })
store.getState().openSettingsPage()
expect(store.getState().activeView).toBe('settings')
expect(store.getState().settingsSearchInputQuery).toBe('')
expect(store.getState().settingsSearchQuery).toBe('')
})
})
describe('createUISlice page navigation history', () => {
it('records and rewinds Tasks visits on close', () => {
const store = createUIStore()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openTaskPage()
expect(store.getState().worktreeNavHistory).toEqual(['a', 'tasks'])
expect(store.getState().worktreeNavHistoryIndex).toBe(1)
store.getState().closeTaskPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('rewinds Tasks detail visits on close', () => {
const store = createUIStore()
const workItem = makeGitHubWorkItem()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openTaskPage({ taskSource: 'github', openGitHubWorkItem: workItem })
expect(store.getState().worktreeNavHistory).toEqual([
'a',
'tasks',
{
kind: 'task-detail',
source: 'github',
workItem,
sourceContext: undefined,
initialTab: undefined
}
])
expect(store.getState().worktreeNavHistoryIndex).toBe(2)
store.getState().closeTaskPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().taskPageData).toEqual({})
expect(store.getState().githubTaskDrawerWorkItem).toBeNull()
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('records provider-depth interactions for direct Tasks detail opens', () => {
const store = createUIStore()
const recordFeatureInteraction = vi.fn()
store.setState({ recordFeatureInteraction } as Partial<AppState>)
const workItem = makeGitHubWorkItem()
const linearIssue = makeLinearIssue()
const jiraIssue = makeJiraIssue()
store.getState().openTaskPage({ taskSource: 'github', openGitHubWorkItem: workItem })
store.getState().openTaskPage({ taskSource: 'linear', openLinearIssue: linearIssue })
store.getState().openTaskPage({ taskSource: 'jira', openJiraIssue: jiraIssue })
expect(recordFeatureInteraction).toHaveBeenCalledWith('tasks')
expect(recordFeatureInteraction).toHaveBeenCalledWith('github-tasks')
expect(recordFeatureInteraction).toHaveBeenCalledWith('linear-tasks')
expect(recordFeatureInteraction).toHaveBeenCalledWith('jira-tasks')
})
it('preserves GitHub task detail source context in navigation history', () => {
const store = createUIStore()
const workItem = makeGitHubWorkItem({ repoId: 'repo-remote' })
const sourceContext: TaskSourceContext = {
kind: 'task-source',
provider: 'github',
projectId: 'project-1',
hostId: 'ssh:devbox',
projectHostSetupId: 'setup-1',
repoId: 'repo-remote',
providerIdentity: { provider: 'github', owner: 'stablyai', repo: 'orca' }
}
store.getState().openTaskPage({
taskSource: 'github',
openGitHubWorkItem: workItem,
openGitHubSourceContext: sourceContext
})
expect(store.getState().worktreeNavHistory.at(-1)).toEqual({
kind: 'task-detail',
source: 'github',
workItem,
sourceContext,
initialTab: undefined
})
})
it('preserves Linear task detail source context in navigation history', () => {
const store = createUIStore()
const linearIssue = makeLinearIssue()
const sourceContext: TaskSourceContext = {
kind: 'task-source',
provider: 'linear',
projectId: 'project-1',
hostId: 'runtime:remote-server',
providerIdentity: { provider: 'linear', workspaceId: 'workspace-1' }
}
store.getState().openTaskPage({
taskSource: 'linear',
openLinearIssue: linearIssue,
openLinearSourceContext: sourceContext
})
expect(store.getState().worktreeNavHistory.at(-1)).toEqual({
kind: 'task-detail',
source: 'linear',
issue: linearIssue,
sourceContext
})
})
it('preserves GitLab task detail source context in navigation history', () => {
const store = createUIStore()
const workItem = makeGitLabWorkItem({ repoId: 'repo-remote' })
const sourceContext: TaskSourceContext = {
kind: 'task-source',
provider: 'gitlab',
projectId: 'project-1',
hostId: 'ssh:devbox',
projectHostSetupId: 'setup-1',
repoId: 'repo-remote',
providerIdentity: { provider: 'gitlab', projectId: '1234' }
}
store.getState().openTaskPage({
taskSource: 'gitlab',
openGitLabWorkItem: workItem,
openGitLabSourceContext: sourceContext
})
expect(store.getState().worktreeNavHistory.at(-1)).toEqual({
kind: 'task-detail',
source: 'gitlab',
workItem,
sourceContext
})
})
it('preserves Jira task detail source context in navigation history', () => {
const store = createUIStore()
const issue = makeJiraIssue()
const sourceContext: TaskSourceContext = {
kind: 'task-source',
provider: 'jira',
projectId: 'project-1',
hostId: 'runtime:remote-server',
providerIdentity: { provider: 'jira', siteId: 'site-1' },
accountLabel: 'Example Jira'
}
store.getState().openTaskPage({
taskSource: 'jira',
openJiraIssue: issue,
openJiraSourceContext: sourceContext
})
expect(store.getState().worktreeNavHistory.at(-1)).toEqual({
kind: 'task-detail',
source: 'jira',
issue,
sourceContext
})
})
it('can suppress the Tasks surface interaction for in-page provider navigation', () => {
const store = createUIStore()
const recordFeatureInteraction = vi.fn()
store.setState({ recordFeatureInteraction } as Partial<AppState>)
const workItem = makeGitHubWorkItem()
const linearIssue = makeLinearIssue()
const jiraIssue = makeJiraIssue()
store
.getState()
.openTaskPage(
{ taskSource: 'github', openGitHubWorkItem: workItem },
{ recordTasksInteraction: false }
)
store
.getState()
.openTaskPage(
{ taskSource: 'linear', openLinearIssue: linearIssue },
{ recordTasksInteraction: false }
)
store
.getState()
.openTaskPage(
{ taskSource: 'jira', openJiraIssue: jiraIssue },
{ recordTasksInteraction: false }
)
expect(recordFeatureInteraction).not.toHaveBeenCalledWith('tasks')
expect(recordFeatureInteraction).toHaveBeenCalledWith('github-tasks')
expect(recordFeatureInteraction).toHaveBeenCalledWith('linear-tasks')
expect(recordFeatureInteraction).toHaveBeenCalledWith('jira-tasks')
})
it('skips the whole Tasks detail stack on close', () => {
const store = createUIStore()
const workItem = makeGitHubWorkItem()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openTaskPage({ taskSource: 'github', openGitHubWorkItem: workItem })
store.getState().openTaskPage({ taskSource: 'linear' })
expect(store.getState().worktreeNavHistory).toEqual([
'a',
'tasks',
{
kind: 'task-detail',
source: 'github',
workItem,
sourceContext: undefined,
initialTab: undefined
},
'tasks'
])
store.getState().closeTaskPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('records and rewinds Automations visits on close', () => {
const store = createUIStore()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openAutomationsPage()
expect(store.getState().worktreeNavHistory).toEqual(['a', 'automations'])
expect(store.getState().worktreeNavHistoryIndex).toBe(1)
store.getState().closeAutomationsPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('dedupes repeated Automations opens against the current history entry', () => {
const store = createUIStore()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openAutomationsPage()
store.getState().openAutomationsPage()
expect(store.getState().activeView).toBe('automations')
expect(store.getState().worktreeNavHistory).toEqual(['a', 'automations'])
expect(store.getState().worktreeNavHistoryIndex).toBe(1)
})
it('keeps the Automations history index when Automations is the only entry', () => {
const store = createUIStore()
store.getState().openAutomationsPage()
expect(store.getState().worktreeNavHistory).toEqual(['automations'])
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
store.getState().closeAutomationsPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('skips deleted prior worktrees when closing Automations', () => {
const store = createUIStore()
store.setState({
activeView: 'automations',
previousViewBeforeAutomations: 'terminal',
worktreesByRepo: { 'repo-1': [makeWorktree('c')] },
worktreeNavHistory: ['c', 'a', 'automations'],
worktreeNavHistoryIndex: 2
})
store.getState().closeAutomationsPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
})
describe('createUISlice space navigation', () => {
it('opens desktop Space without replacing the current view', () => {
const openWindow = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: { set: vi.fn(() => Promise.resolve()) },
workspaceSpace: { openWindow }
}
})
const store = createUIStore()
store.getState().openTaskPage()
store.getState().openSpacePage()
expect(openWindow).toHaveBeenCalledOnce()
expect(store.getState().activeView).toBe('tasks')
})
it('records Space page opens as workspace cleanup interactions', () => {
const setMock = vi.fn(() => Promise.resolve())
vi.stubGlobal('window', {
api: {
ui: {
set: setMock
}
}
})
const now = 1_700_000_000_000
vi.useFakeTimers()
vi.setSystemTime(now)
try {
const store = createUIStore()
store.getState().hydratePersistedUI(makePersistedUI())
setMock.mockClear()
store.getState().openSpacePage()
const expected: FeatureInteractionState = {
'workspace-cleanup': { firstInteractedAt: now, interactionCount: 1 }
}
expect(store.getState().featureInteractions).toEqual(expected)
expect(setMock).toHaveBeenCalledWith({ featureInteractions: expected })
} finally {
vi.useRealTimers()
}
})
it('returns to the tasks page after opening Space from an in-progress draft', () => {
const store = createUIStore()
store.getState().openTaskPage({ preselectedRepoId: 'repo-1' })
store.getState().openSpacePage()
expect(store.getState().activeView).toBe('space')
expect(store.getState().previousViewBeforeSpace).toBe('tasks')
store.getState().closeSpacePage()
expect(store.getState().activeView).toBe('tasks')
})
it('keeps the original return target when Space is reopened while already visible', () => {
const store = createUIStore()
store.getState().openTaskPage()
store.getState().openSpacePage()
store.getState().openSpacePage()
expect(store.getState().previousViewBeforeSpace).toBe('tasks')
store.getState().closeSpacePage()
expect(store.getState().activeView).toBe('tasks')
})
it('returns to the originating view after closing Artifacts', () => {
const store = createUIStore()
store.getState().openTaskPage()
store.getState().openArtifactsPage()
expect(store.getState().activeView).toBe('artifacts')
expect(store.getState().previousViewBeforeArtifacts).toBe('tasks')
store.getState().closeArtifactsPage()
expect(store.getState().activeView).toBe('tasks')
})
it('records and rewinds Artifacts visits on close', () => {
const store = createUIStore()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openArtifactsPage()
expect(store.getState().worktreeNavHistory).toEqual(['a', 'artifacts'])
expect(store.getState().worktreeNavHistoryIndex).toBe(1)
store.getState().closeArtifactsPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('records and rewinds Skills visits on close', () => {
const store = createUIStore()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openSkillsPage()
expect(store.getState().worktreeNavHistory).toEqual(['a', 'skills'])
expect(store.getState().worktreeNavHistoryIndex).toBe(1)
store.getState().closeSkillsPage()
expect(store.getState().activeView).toBe('terminal')
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('records Artifacts and Skills as separate back/forward entries', () => {
const store = createUIStore()
store.setState({ worktreesByRepo: { 'repo-1': [makeWorktree('a')] } })
store.getState().recordWorktreeVisit('a')
store.getState().openArtifactsPage()
store.getState().openSkillsPage()
store.getState().openSkillsPage()
expect(store.getState().worktreeNavHistory).toEqual(['a', 'artifacts', 'skills'])
expect(store.getState().worktreeNavHistoryIndex).toBe(2)
})
it('records a Skills visit when opening a shared skill link', () => {
const store = createUIStore()
store.getState().openSkillShare('share-1')
store.getState().openSkillsSharedLinks()
expect(store.getState().worktreeNavHistory).toEqual(['skills'])
expect(store.getState().worktreeNavHistoryIndex).toBe(0)
})
it('opens and restores Artifacts when its sidebar shortcut is hidden', () => {
const store = createUIStore()
store.setState({ settings: { ...getDefaultSettings('/tmp'), showArtifactsButton: false } })
store.getState().openArtifactsPage()
expect(store.getState().activeView).toBe('artifacts')
store.getState().hydratePersistedUI(makePersistedUI({ activeView: 'artifacts' }), 'startup')
expect(store.getState().activeView).toBe('artifacts')
})
})
@@ -74,32 +74,6 @@ it.each([
)
})
it.each(['folder', 'git'] as const)('preserves a live %s terminal on repeat activation', (kind) => {
const { store, workspaceId, activate } = seedWorkspace(kind, 'local')
store.setState({ ptyIdsByTabId: { terminal: ['live-pty'] } })
activate()
const activated = store.getState()
activate()
expect(store.getState()).toBe(activated)
expect(store.getState().tabsByWorktree[workspaceId][0].generation).toBe(3)
})
it.each(['folder', 'git'] as const)(
'wakes an already-selected %s after its PTY is released',
(kind) => {
const { store, workspaceId, activate } = seedWorkspace(kind, 'local')
store.setState({ ptyIdsByTabId: { terminal: ['live-pty'] } })
activate()
store.setState({ ptyIdsByTabId: {} })
activate()
expect(store.getState().tabsByWorktree[workspaceId][0].generation).toBe(4)
}
)
it('reads only the selected folder owner on screen and persists to that host', () => {
const { store, activate } = seedWorkspace('folder', 'ssh:remote')
const updateFolderWorkspace = vi.fn().mockResolvedValue(null)
@@ -121,12 +95,3 @@ it('reads only the selected folder owner on screen and persists to that host', (
{ executionHostId: 'ssh:remote' }
)
})
it('leaves selection unchanged when the requested folder owner is absent', () => {
const { store } = seedWorkspace('folder', 'local')
const before = store.getState()
store.getState().setActiveFolderWorkspace(FOLDER_ID, 'ssh:missing')
expect(store.getState()).toBe(before)
})