From f9712ede01b03000c9664240d4fcc6d9bbaaa78d Mon Sep 17 00:00:00 2001 From: Trevin Chow Date: Thu, 28 May 2026 16:57:53 -0700 Subject: [PATCH] fix: stop worktree jumping to top of sidebar on re-click (#2889) * fix: stop worktree jumping to top of sidebar on re-click Returning to a worktree whose terminals had slept or disconnected bounced it to the top of its repo group, as if there were activity. The sidebar sorts by lastActivityAt, and click-driven activity is meant to be suppressed via the pendingActivationSpawn tag. But setActiveWorktree only applied that tag on a worktree's first activation. When the user returned to a worktree with no live PTYs, the allDead branch bumped the PTY generation, remounting the pane and fresh-spawning a PTY. That spawn was untagged, so updateTabPtyId treated it as real activity: it stamped lastActivityAt and bumped sortEpoch, floating the worktree to the top. Tag the tabs whenever the allDead generation bump fires, not only on first activation -- the respawn it triggers is always a click side-effect. The flag is consumed on the next updateTabPtyId, so genuine later activity still updates recency. This matches the intent already documented in the terminals slice. * fix activation spawn recency suppression Co-authored-by: Orca --------- Co-authored-by: Jinwoo-H Co-authored-by: Orca --- .../slices/store-session-cascades.test.ts | 160 ++++++++++++++++++ src/renderer/src/store/slices/terminals.ts | 61 +++++-- .../src/store/slices/worktree-helpers.ts | 7 +- src/renderer/src/store/slices/worktrees.ts | 33 +++- src/shared/types.ts | 10 +- 5 files changed, 247 insertions(+), 24 deletions(-) diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts index 49890c1d9..ed976943d 100644 --- a/src/renderer/src/store/slices/store-session-cascades.test.ts +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -1090,6 +1090,166 @@ describe('terminal slice behaviors', () => { expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined() }) + // Why: re-activating a worktree whose PTYs died while the user was away (e.g. + // relay disconnect, sleep) hits the allDead generation bump, which remounts + // TerminalPane and fresh-spawns a PTY. That respawn is a side-effect of the + // click, not real activity. First-activation tagging doesn't cover it + // (everActivatedWorktreeIds already has the worktree), so without tagging the + // allDead bump the worktree would stamp lastActivityAt and jump to the top of + // Recent on every re-click — the reported "click bounces it to the top" bug. + it('does not bump lastActivityAt when a re-activation respawns dead PTYs', () => { + const store = createTestStore() + const worktreeId = 'repo1::/path/wt1' + const originalLastActivityAt = 1000 + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [ + makeWorktree({ + id: worktreeId, + repoId: 'repo1', + path: '/path/wt1', + lastActivityAt: originalLastActivityAt + }) + ] + }, + // Tab retains a wake-hint ptyId but has no live PTY, and the worktree was + // already activated this session — so this is a re-activation, not a + // first activation. + tabsByWorktree: { + [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: 'wake-hint-session' })] + }, + ptyIdsByTabId: { 'tab-1': [] }, + everActivatedWorktreeIds: new Set([worktreeId]), + unifiedTabsByWorktree: { + [worktreeId]: [ + { + id: 'tab-1', + entityId: 'tab-1', + groupId: 'group-1', + worktreeId, + contentType: 'terminal', + label: 'Terminal 1', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + groupsByWorktree: { + [worktreeId]: [{ id: 'group-1', worktreeId, activeTabId: 'tab-1', tabOrder: ['tab-1'] }] + }, + activeGroupIdByWorktree: { [worktreeId]: 'group-1' } + }) + + store.getState().setActiveWorktree(worktreeId) + // The allDead generation bump must tag the tab so the click-driven respawn + // is suppressed, even though this is not the first activation. + expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBe(true) + + const sortEpochBeforeSpawn = store.getState().sortEpoch + + // Simulate the stale wake-hint reattach failing before TerminalPane falls + // back to a fresh spawn. The clear suppresses its own activity bump without + // consuming the spawn suppression. + store.getState().clearTabPtyId('tab-1', 'wake-hint-session') + expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBe(true) + + // Simulate the fresh spawn coming back from TerminalPane's remount. + store.getState().updateTabPtyId('tab-1', 'pty-fresh') + + const worktree = store.getState().worktreesByRepo.repo1[0] + expect(worktree.lastActivityAt).toBe(originalLastActivityAt) + expect(store.getState().sortEpoch).toBe(sortEpochBeforeSpawn) + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalledWith( + expect.objectContaining({ + updates: expect.objectContaining({ lastActivityAt: expect.any(Number) }) + }) + ) + // The flag is consumed so a later legitimate respawn still bumps. + expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined() + }) + + it('suppresses every pane spawn from a click-driven split-layout remount', () => { + const store = createTestStore() + const worktreeId = 'repo1::/path/wt1' + const originalLastActivityAt = 1000 + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [ + makeWorktree({ + id: worktreeId, + repoId: 'repo1', + path: '/path/wt1', + lastActivityAt: originalLastActivityAt + }) + ] + }, + tabsByWorktree: { + [worktreeId]: [makeTab({ id: 'tab-1', worktreeId, ptyId: null })] + }, + ptyIdsByTabId: { 'tab-1': [] }, + everActivatedWorktreeIds: new Set([worktreeId]), + terminalLayoutsByTabId: { + 'tab-1': { + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: 'leaf-1' }, + second: { type: 'leaf', leafId: 'leaf-2' } + }, + activeLeafId: 'leaf-1', + expandedLeafId: null + } + }, + unifiedTabsByWorktree: { + [worktreeId]: [ + { + id: 'tab-1', + entityId: 'tab-1', + groupId: 'group-1', + worktreeId, + contentType: 'terminal', + label: 'Terminal 1', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + }, + groupsByWorktree: { + [worktreeId]: [{ id: 'group-1', worktreeId, activeTabId: 'tab-1', tabOrder: ['tab-1'] }] + }, + activeGroupIdByWorktree: { [worktreeId]: 'group-1' } + }) + + store.getState().setActiveWorktree(worktreeId) + expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBe(2) + + store.getState().updateTabPtyId('tab-1', 'pty-pane-1') + expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBe(true) + + store.getState().updateTabPtyId('tab-1', 'pty-pane-2') + + const worktree = store.getState().worktreesByRepo.repo1[0] + expect(worktree.lastActivityAt).toBe(originalLastActivityAt) + expect(mockApi.worktrees.updateMeta).not.toHaveBeenCalledWith( + expect.objectContaining({ + updates: expect.objectContaining({ lastActivityAt: expect.any(Number) }) + }) + ) + expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined() + }) + // Why: first-visit worktrees (no tabs yet) trigger Terminal.tsx's activation // fallback which calls createTab(). That auto-created tab passes // pendingActivationSpawn: true so its PTY spawn is suppressed — otherwise diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 9c0162db8..e085ba752 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -61,6 +61,23 @@ function isRemoteRuntimePtyId(ptyId: string | null | undefined): boolean { return typeof ptyId === 'string' && parseRemoteRuntimePtyId(ptyId) !== null } +function getPendingActivationSpawnCount(value: boolean | number | undefined): number { + if (value === true) { + return 1 + } + return typeof value === 'number' && value > 0 ? value : 0 +} + +function consumePendingActivationSpawn( + value: boolean | number | undefined +): boolean | number | undefined { + const count = getPendingActivationSpawnCount(value) + if (count <= 1) { + return undefined + } + return count === 2 ? true : count - 1 +} + function getFallbackTabTitle(tab: TerminalTab, index?: number): string { return ( tab.customTitle?.trim() || @@ -1184,15 +1201,12 @@ export const createTerminalSlice: StateCreator } worktreeId = wId const tab = tabs[index] - if (tab.pendingActivationSpawn) { + if (getPendingActivationSpawnCount(tab.pendingActivationSpawn) > 0) { wasActivationSpawn = true } - // Why: consume pendingActivationSpawn here. The flag is set by - // setActiveWorktree when it bumps generation on all-dead tabs, and - // must be cleared on the first PTY that comes back or a later - // legitimate respawn (e.g. the user restarting a codex tab) would - // also be classified as activation and silently dropped from the - // recency sort. + // Why: consume one pendingActivationSpawn unit here. Split layouts can + // remount several panes for one click, and each pane's activation-time + // PTY callback must be suppressed without hiding later real activity. const { pendingActivationSpawn: _unused, ...rest } = tab void _unused // Why: tab.ptyId is the single-pane fallback used by legacy attach @@ -1200,9 +1214,16 @@ export const createTerminalSlice: StateCreator // primary binding from the original pane or remount/close flows can // reattach the tab to the wrong PTY and appear to "reset" panes. const nextTabPtyId = tab.ptyId ?? nextPtyIds[0] ?? null + const nextPendingActivationSpawn = consumePendingActivationSpawn(tab.pendingActivationSpawn) if (tab.pendingActivationSpawn || tab.ptyId !== nextTabPtyId) { const nextTabs = [...tabs] - nextTabs[index] = { ...rest, ptyId: nextTabPtyId } + nextTabs[index] = { + ...rest, + ...(nextPendingActivationSpawn + ? { pendingActivationSpawn: nextPendingActivationSpawn } + : {}), + ptyId: nextTabPtyId + } nextTabsByWorktree = { ...s.tabsByWorktree, [wId]: nextTabs } } break @@ -1255,24 +1276,34 @@ export const createTerminalSlice: StateCreator } worktreeId = wId const tab = tabs[index] - if (tab.pendingActivationSpawn) { + if (getPendingActivationSpawnCount(tab.pendingActivationSpawn) > 0) { wasActivationSpawn = true } if (!ptyId) { isRemoteRuntimeMirror = existingPtyIds.length > 0 && existingPtyIds.every((id) => isRemoteRuntimePtyId(id)) } - // Why: consume pendingActivationSpawn here too. Panes tearing down - // during a worktree switch (e.g. the previously-active worktree - // unmounting its panes) fire onExit → clearTabPtyId, which must - // not count as activity. Strip the flag on consumption so later - // legitimate exits still bump. + // Why: consume pendingActivationSpawn for real activation-time clears, + // but keep it when clearing a stale wake-hint id that was not live in + // ptyIdsByTabId. That path immediately falls back to a fresh spawn, + // and the spawn still needs the click-driven suppression. const { pendingActivationSpawn: _unused, ...rest } = tab void _unused const nextTabPtyId = remainingPtyIds.at(-1) ?? null + const shouldRetainActivationSpawn = + wasActivationSpawn && ptyId != null && !existingPtyIds.includes(ptyId) + const nextPendingActivationSpawn = shouldRetainActivationSpawn + ? tab.pendingActivationSpawn + : consumePendingActivationSpawn(tab.pendingActivationSpawn) if (tab.pendingActivationSpawn || tab.ptyId !== nextTabPtyId) { const nextTabs = [...tabs] - nextTabs[index] = { ...rest, ptyId: nextTabPtyId } + nextTabs[index] = { + ...rest, + ...(nextPendingActivationSpawn + ? { pendingActivationSpawn: nextPendingActivationSpawn } + : {}), + ptyId: nextTabPtyId + } nextTabsByWorktree = { ...s.tabsByWorktree, [wId]: nextTabs } } break diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index cc388285c..efa925e7e 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -44,9 +44,10 @@ export type WorktreeSlice = { * their PTYs, and the resulting `updateTabPtyId`/`clearTabPtyId` calls * are all side-effects of the click — not real activity. On first * activation we tag every terminal tab with `pendingActivationSpawn` so - * the bump is suppressed. After the first activation we do NOT re-tag, - * so subsequent events on the worktree (codex restart, new pane spawn, - * agent output) count normally. Session-only; never persisted. + * the bump is suppressed. Split-layout tabs may carry a numeric count so + * every click-driven pane remount is suppressed. After the first activation + * we do NOT re-tag, so subsequent events on the worktree (codex restart, + * new pane spawn, agent output) count normally. Session-only; never persisted. */ everActivatedWorktreeIds: Set /** diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index f58100597..20d6dd097 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -3,6 +3,8 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { DetectedWorktreeListResult, + TerminalLayoutSnapshot, + TerminalPaneLayoutNode, LocalBaseRefRefreshResult, Worktree, WorkspaceVisibleTabType, @@ -35,6 +37,25 @@ export type { WorktreeSlice, WorktreeDeleteState } from './worktree-helpers' // UI hydration parity this slice used before `worktree.detectedList` existed. const REMOTE_WORKTREE_LIST_PARITY_LIMIT = 10_000 +function countTerminalLayoutLeaves(node: TerminalPaneLayoutNode | null | undefined): number { + if (!node) { + return 0 + } + if (node.type === 'leaf') { + return 1 + } + return countTerminalLayoutLeaves(node.first) + countTerminalLayoutLeaves(node.second) +} + +function getActivationSpawnSuppression(layout: TerminalLayoutSnapshot | undefined): true | number { + const paneCount = Math.max( + 1, + countTerminalLayoutLeaves(layout?.root), + Object.keys(layout?.ptyIdsByLeafId ?? {}).length + ) + return paneCount === 1 ? true : paneCount +} + function showLocalBaseRefRefreshToast(result: LocalBaseRefRefreshResult | undefined): void { if (!result || result.status === 'updated') { return @@ -1875,7 +1896,17 @@ export const createWorktreeSlice: StateCreator [worktreeId!]: tabs.map((tab) => ({ ...tab, ...(allDead ? { generation: (tab.generation ?? 0) + 1 } : {}), - ...(shouldTagTabs ? { pendingActivationSpawn: true } : {}) + // Why: the allDead generation bump remounts panes and may + // fresh-spawn PTYs — click side-effects, not real activity. + // Split layouts remount several panes, so count the expected + // pane events instead of suppressing only the first one. + ...(allDead || shouldTagTabs + ? { + pendingActivationSpawn: getActivationSpawnSuppression( + s.terminalLayoutsByTabId[tab.id] + ) + } + : {}) })) } } diff --git a/src/shared/types.ts b/src/shared/types.ts index 0b50a7409..416574cbb 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -474,11 +474,11 @@ export type TerminalTab = { * not by the user doing work. Without this flag the resulting * `updateTabPtyId` call would call `bumpWorktreeActivity` and flip the * sidebar's recency sort on every click — the reorder-on-click bug. The - * flag is set by `setActiveWorktree` and consumed (cleared) by the first - * `updateTabPtyId` that follows, which then suppresses the activity bump - * and the `sortEpoch` increment. Never persisted — it is a transient - * handoff between the two calls. */ - pendingActivationSpawn?: boolean + * flag is set by `setActiveWorktree` and consumed by the activation-driven + * PTY lifecycle calls that follow, which then suppress activity bumps and + * `sortEpoch` increments. Split layouts use a numeric count because one tab + * can remount several panes. Never persisted — it is a transient handoff. */ + pendingActivationSpawn?: boolean | number } export type BrowserHistoryEntry = {