diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 65cd8ee85..e2d4b5892 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -57,7 +57,7 @@ import { import TabGroupSplitLayout from './tab-group/TabGroupSplitLayout' import AiVaultSessionDropLayer from './tab-group/AiVaultSessionDropLayer' import { shouldAutoCreateInitialTerminal } from './terminal/initial-terminal' -import { shouldRepairActiveTerminalTab } from './terminal/active-terminal-repair' +import { resolveRepairedActiveTerminalTabId } from './terminal/active-terminal-repair' import { scheduleBackgroundTerminalWorktreeMeasure } from './terminal/background-terminal-worktree-visibility' import { getEffectiveLayoutForWorktree as getEffectiveLayout, @@ -224,6 +224,7 @@ function Terminal(): React.JSX.Element | null { const activeView = useAppStore((s) => s.activeView) const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) const activeTabId = useAppStore((s) => s.activeTabId) + const activeTabIdByWorktree = useAppStore((s) => s.activeTabIdByWorktree) const createTab = useAppStore((s) => s.createTab) const closeTab = useAppStore((s) => s.closeTab) const setActiveTab = useAppStore((s) => s.setActiveTab) @@ -692,19 +693,38 @@ function Terminal(): React.JSX.Element | null { }, [queueEditorCloseRequests]) useEffect(() => { - if (!shouldRepairActiveTerminalTab({ activeTabType, activeTabId, tabs })) { + const rememberedTabId = renderedActiveWorktreeId + ? (activeTabIdByWorktree[renderedActiveWorktreeId] ?? null) + : null + // Why: prefer the worktree's remembered active tab over the first tab so a + // repair firing on a transient worktree-switch render restores the tab the + // user left on instead of permanently resetting the selection to Terminal 1. + const repairedTabId = resolveRepairedActiveTerminalTabId({ + activeTabType, + activeTabId, + rememberedTabId, + tabs + }) + if (!repairedTabId) { return } // Why: mutating Zustand during render trips React's "Cannot update a // component while rendering a different component" warning. Keep the repair // terminal-only so inactive CLI-created tabs cannot steal editor/browser focus. - setActiveTab(tabs[0].id) + setActiveTab(repairedTabId) // Why: `tabs` is intentionally the dependency here because the repair must // react to tab-order/content changes, not just scalar IDs. The list comes // from Zustand selectors and is small in practice, so this explicit repair // effect is preferred over duplicating reconciliation state. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [activeTabId, activeTabType, setActiveTab, tabs]) + }, [ + activeTabId, + activeTabType, + setActiveTab, + tabs, + activeTabIdByWorktree, + renderedActiveWorktreeId + ]) // Track which worktrees have been activated during this app session. // Only mount TerminalPanes for visited worktrees to prevent mass PTY diff --git a/src/renderer/src/components/terminal/active-terminal-repair.test.ts b/src/renderer/src/components/terminal/active-terminal-repair.test.ts index 2d08164d4..f62cd0e4d 100644 --- a/src/renderer/src/components/terminal/active-terminal-repair.test.ts +++ b/src/renderer/src/components/terminal/active-terminal-repair.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest' import type { TerminalTab } from '../../../../shared/types' -import { shouldRepairActiveTerminalTab } from './active-terminal-repair' +import { + resolveRepairedActiveTerminalTabId, + shouldRepairActiveTerminalTab +} from './active-terminal-repair' function tab(id: string): TerminalTab { return { @@ -50,3 +53,49 @@ describe('shouldRepairActiveTerminalTab', () => { ).toBe(false) }) }) + +describe('resolveRepairedActiveTerminalTabId', () => { + it('returns null when no repair is needed', () => { + expect( + resolveRepairedActiveTerminalTabId({ + activeTabType: 'terminal', + activeTabId: 'terminal-2', + rememberedTabId: 'terminal-1', + tabs: [tab('terminal-1'), tab('terminal-2')] + }) + ).toBeNull() + }) + + it('restores the remembered tab instead of the first tab when repairing', () => { + // Why (regression): a repair firing on a transient worktree-switch render + // must not reset the selection to Terminal 1 — it should land on the tab + // the worktree remembers the user was on. + expect( + resolveRepairedActiveTerminalTabId({ + activeTabType: 'terminal', + activeTabId: 'stale-from-other-worktree', + rememberedTabId: 'terminal-2', + tabs: [tab('terminal-1'), tab('terminal-2')] + }) + ).toBe('terminal-2') + }) + + it('falls back to the first tab when the remembered tab is missing or stale', () => { + expect( + resolveRepairedActiveTerminalTabId({ + activeTabType: 'terminal', + activeTabId: 'missing', + rememberedTabId: null, + tabs: [tab('terminal-1'), tab('terminal-2')] + }) + ).toBe('terminal-1') + expect( + resolveRepairedActiveTerminalTabId({ + activeTabType: 'terminal', + activeTabId: 'missing', + rememberedTabId: 'no-longer-open', + tabs: [tab('terminal-1'), tab('terminal-2')] + }) + ).toBe('terminal-1') + }) +}) diff --git a/src/renderer/src/components/terminal/active-terminal-repair.ts b/src/renderer/src/components/terminal/active-terminal-repair.ts index 8f6691f95..86a491775 100644 --- a/src/renderer/src/components/terminal/active-terminal-repair.ts +++ b/src/renderer/src/components/terminal/active-terminal-repair.ts @@ -16,3 +16,19 @@ export function shouldRepairActiveTerminalTab(args: { } return true } + +// Resolve which terminal tab to open after a project/agent is selected, or null if no repair is needed. +export function resolveRepairedActiveTerminalTabId(args: { + activeTabType: WorkspaceVisibleTabType + activeTabId: string | null + rememberedTabId: string | null | undefined + tabs: TerminalTab[] +}): string | null { + if (!shouldRepairActiveTerminalTab(args)) { + return null + } + if (args.rememberedTabId && args.tabs.some((tab) => tab.id === args.rememberedTabId)) { + return args.rememberedTabId + } + return args.tabs[0].id +} diff --git a/src/renderer/src/store/slices/tabs-hydration.test.ts b/src/renderer/src/store/slices/tabs-hydration.test.ts index a2db41f8c..afd5a05ec 100644 --- a/src/renderer/src/store/slices/tabs-hydration.test.ts +++ b/src/renderer/src/store/slices/tabs-hydration.test.ts @@ -307,6 +307,37 @@ describe('buildHydratedTabState – legacy format', () => { expect(group.activeTabId).toBe('/f1') }) + it('restores each worktree remembered terminal, not the globally-active one', () => { + // Why (regression): the legacy branch used the global session.activeTabId, + // so every worktree except the last-focused one lost its remembered + // terminal on restart and reopened on the first tab. Use the per-worktree + // activeTabIdByWorktree map instead. + const terminal = (id: string, worktreeId: string, sortOrder: number) => ({ + id, + ptyId: null, + worktreeId, + title: id, + customTitle: null, + color: null, + sortOrder, + createdAt: 100 + sortOrder + }) + const session: WorkspaceSessionState = { + ...makeBaseSession(), + // The globally-active tab belongs to w1. + activeTabId: 'w1-terminal-1', + tabsByWorktree: { + w1: [terminal('w1-terminal-1', 'w1', 0)], + w2: [terminal('w2-terminal-1', 'w2', 0), terminal('w2-terminal-2', 'w2', 1)] + }, + activeTabIdByWorktree: { w1: 'w1-terminal-1', w2: 'w2-terminal-2' } + } + + const result = buildHydratedTabState(session, new Set(['w1', 'w2'])) + expect(result.groupsByWorktree.w2[0].activeTabId).toBe('w2-terminal-2') + expect(result.groupsByWorktree.w1[0].activeTabId).toBe('w1-terminal-1') + }) + it('skips worktrees with no tabs or files', () => { const session: WorkspaceSessionState = { ...makeBaseSession(), diff --git a/src/renderer/src/store/slices/tabs-hydration.ts b/src/renderer/src/store/slices/tabs-hydration.ts index de2045441..bdf11e822 100644 --- a/src/renderer/src/store/slices/tabs-hydration.ts +++ b/src/renderer/src/store/slices/tabs-hydration.ts @@ -251,8 +251,17 @@ function hydrateLegacyFormat( let activeTabId: string | null = null if (activeTabType === 'editor') { activeTabId = session.activeFileIdByWorktree?.[worktreeId] ?? null - } else if (session.activeTabId && terminalTabs.some((t) => t.id === session.activeTabId)) { - activeTabId = session.activeTabId + } else { + // Why: honor this worktree's own remembered terminal before the global + // active tab. The global session.activeTabId only names the last-focused + // worktree's tab, so using it here reset every other worktree to its + // first terminal on restart. + const rememberedTabId = session.activeTabIdByWorktree?.[worktreeId] + if (rememberedTabId && terminalTabs.some((t) => t.id === rememberedTabId)) { + activeTabId = rememberedTabId + } else if (session.activeTabId && terminalTabs.some((t) => t.id === session.activeTabId)) { + activeTabId = session.activeTabId + } } if (activeTabId && !tabs.some((t) => t.id === activeTabId)) { activeTabId = tabs[0]?.id ?? null diff --git a/src/renderer/src/store/slices/tabs.test.ts b/src/renderer/src/store/slices/tabs.test.ts index 802261b84..ea5e42dd1 100644 --- a/src/renderer/src/store/slices/tabs.test.ts +++ b/src/renderer/src/store/slices/tabs.test.ts @@ -2125,6 +2125,59 @@ describe('TabsSlice', () => { }) }) + it('promotes legacy terminals to the worktree remembered tab, not always the first one', () => { + // Why (regression): selecting a non-first terminal, switching to another + // worktree, then returning must land on the remembered tab. Reconcile + // used to seed a freshly-ensured group with restoredLegacyTabs[0], so the + // remembered selection in activeTabIdByWorktree was silently dropped and + // the worktree always reopened on Terminal 1. + 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: {}, + // The user had Terminal 2 active before leaving this worktree. + 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 PR worktree's only terminal can die on startup (a // failing .envrc/direnv). pty-connection keeps that dead pane mounted diff --git a/src/renderer/src/store/slices/tabs.ts b/src/renderer/src/store/slices/tabs.ts index 41fa3646d..42759c342 100644 --- a/src/renderer/src/store/slices/tabs.ts +++ b/src/renderer/src/store/slices/tabs.ts @@ -1871,6 +1871,16 @@ export const createTabsSlice: StateCreator = (set, })) const reconciledUnifiedTabs = restoredLegacyTabs.length > 0 ? [...unifiedTabs, ...restoredLegacyTabs] : unifiedTabs + // Why: when a freshly-ensured group has no active tab yet, seed it from the + // worktree's remembered selection before the first restored tab. Otherwise + // returning to a worktree whose terminals only exist in the runtime slice + // always reopens on Terminal 1 and drops the tab the user left on. + const rememberedLegacyActiveTabId = state.activeTabIdByWorktree[worktreeId] + const restoredLegacyTabIds = new Set(restoredLegacyTabs.map((tab) => tab.id)) + const legacyFallbackActiveTabId = + rememberedLegacyActiveTabId && restoredLegacyTabIds.has(rememberedLegacyActiveTabId) + ? rememberedLegacyActiveTabId + : (restoredLegacyTabs[0]?.id ?? null) const reconciledGroups = restoredLegacyTabs.length > 0 && reconciliationGroup ? updateGroup(ensuredGroupState!.groupsByWorktree[worktreeId] ?? [], { @@ -1879,7 +1889,7 @@ export const createTabsSlice: StateCreator = (set, // after split groups became the source of truth. Restoring them // into the active/root group keeps existing live PTYs reachable // instead of making activation spawn a duplicate "Terminal 2". - activeTabId: reconciliationGroup.activeTabId ?? restoredLegacyTabs[0]?.id ?? null, + activeTabId: reconciliationGroup.activeTabId ?? legacyFallbackActiveTabId, tabOrder: dedupeTabOrder([ ...reconciliationGroup.tabOrder, ...restoredLegacyTabs.map((tab) => tab.id)