diff --git a/src/renderer/src/components/WorktreeJumpPalette.test.tsx b/src/renderer/src/components/WorktreeJumpPalette.test.tsx index 0881dd10d783..cfe5de958320 100644 --- a/src/renderer/src/components/WorktreeJumpPalette.test.tsx +++ b/src/renderer/src/components/WorktreeJumpPalette.test.tsx @@ -421,6 +421,7 @@ describe('WorktreeJumpPalette', () => { // The first row names ITS OWN host — the wrong-host open is gone. await act(async () => fireEvent.click(rows[0]!)) expect(activateAndRevealWorktree).toHaveBeenLastCalledWith('shared', { + navigationIntent: 'user-open', executionHostId: 'local' }) }) @@ -443,6 +444,7 @@ describe('WorktreeJumpPalette', () => { await act(async () => fireEvent.click(rows[1]!)) expect(activateAndRevealWorktree).toHaveBeenLastCalledWith('shared', { + navigationIntent: 'user-open', executionHostId: 'ssh:box' }) }) @@ -487,6 +489,7 @@ describe('WorktreeJumpPalette', () => { await act(async () => fireEvent.click(hubARow!)) expect(activateAndRevealWorktree).toHaveBeenLastCalledWith('shared-runtime', { + navigationIntent: 'user-open', executionHostId: 'runtime:hub-a' }) }) diff --git a/src/renderer/src/components/activity/activity-thread-actions.test.ts b/src/renderer/src/components/activity/activity-thread-actions.test.ts index f9baff7d60dd..ce546f036970 100644 --- a/src/renderer/src/components/activity/activity-thread-actions.test.ts +++ b/src/renderer/src/components/activity/activity-thread-actions.test.ts @@ -258,6 +258,7 @@ describe('activity thread host routing', () => { expect(acknowledgeAgents).toHaveBeenCalledWith([thread.paneKey]) expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith(thread.worktree.id, { + navigationIntent: 'user-open', executionHostId: REMOTE_HOST }) }) diff --git a/src/renderer/src/components/editor/CheckRunDetailsPanel.copy.test.tsx b/src/renderer/src/components/editor/CheckRunDetailsPanel.copy.test.tsx index 23bc3d51c593..826b63ef4af7 100644 --- a/src/renderer/src/components/editor/CheckRunDetailsPanel.copy.test.tsx +++ b/src/renderer/src/components/editor/CheckRunDetailsPanel.copy.test.tsx @@ -9,6 +9,7 @@ import { CheckRunDetailsPanel } from './CheckRunDetailsPanel' const writeClipboardText = vi.fn<(text: string) => Promise>() vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, translate: (_key: string, fallback: string) => fallback })) diff --git a/src/renderer/src/components/editor/IpynbRendering.test.tsx b/src/renderer/src/components/editor/IpynbRendering.test.tsx index 2086e6b1878b..593104e23005 100644 --- a/src/renderer/src/components/editor/IpynbRendering.test.tsx +++ b/src/renderer/src/components/editor/IpynbRendering.test.tsx @@ -7,7 +7,10 @@ import { IpynbRunPrompt } from './IpynbCellToolbar' import { TooltipProvider } from '@/components/ui/tooltip' import type { IpynbCell, IpynbOutput } from './ipynb-parse' -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) +vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, + translate: (_key: string, fallback: string) => fallback +})) vi.mock('./use-document-dark-theme', () => ({ useDocumentDarkTheme: () => true })) vi.mock('@/lib/monaco-setup', () => ({ monaco: {} })) vi.mock('./MonacoCodeExcerpt', () => ({ diff --git a/src/renderer/src/components/editor/MarkdownPreview.link-routing.interaction.test.tsx b/src/renderer/src/components/editor/MarkdownPreview.link-routing.interaction.test.tsx index 9be38fdb1d23..e244a50865a3 100644 --- a/src/renderer/src/components/editor/MarkdownPreview.link-routing.interaction.test.tsx +++ b/src/renderer/src/components/editor/MarkdownPreview.link-routing.interaction.test.tsx @@ -71,7 +71,10 @@ vi.mock('@/lib/connection-context', () => ({ vi.mock('@/lib/connection-owner-resolution', () => ({ createConnectionIdForFileSelector: () => () => connectionOwner.value })) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) +vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, + translate: (_key: string, fallback: string) => fallback +})) vi.mock('./useLocalImageSrc', () => ({ useLocalImageSrc: (src?: string) => src })) vi.mock('./MermaidBlock', () => ({ default: () => null })) vi.mock('./CodeBlockCopyButton', () => ({ diff --git a/src/renderer/src/components/editor/MarkdownPreview.toc-visibility-gate.test.tsx b/src/renderer/src/components/editor/MarkdownPreview.toc-visibility-gate.test.tsx index 23f66fa9ee52..645d1f556d60 100644 --- a/src/renderer/src/components/editor/MarkdownPreview.toc-visibility-gate.test.tsx +++ b/src/renderer/src/components/editor/MarkdownPreview.toc-visibility-gate.test.tsx @@ -55,7 +55,10 @@ vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => null vi.mock('@/lib/connection-owner-resolution', () => ({ createConnectionIdForFileSelector: () => () => null })) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) +vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, + translate: (_key: string, fallback: string) => fallback +})) vi.mock('./useLocalImageSrc', () => ({ useLocalImageSrc: (src?: string) => src })) vi.mock('./MermaidBlock', () => ({ default: () => null })) vi.mock('./CodeBlockCopyButton', () => ({ diff --git a/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx b/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx index 71e580a21d51..f07fe236c70d 100644 --- a/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx +++ b/src/renderer/src/components/github-item-dialog/open-dialog/github-item-dialog.tsx @@ -58,7 +58,9 @@ export default function GitHubItemDialog({ return } - const result = activateAndRevealWorktree(currentAttached.id) + const result = activateAndRevealWorktree(currentAttached.id, { + navigationIntent: 'user-open' + }) if (result === false) { toast.error( translate( diff --git a/src/renderer/src/components/pull-request-page/page/surface.tsx b/src/renderer/src/components/pull-request-page/page/surface.tsx index a299a0caa875..ffa5f401e2b9 100644 --- a/src/renderer/src/components/pull-request-page/page/surface.tsx +++ b/src/renderer/src/components/pull-request-page/page/surface.tsx @@ -132,7 +132,9 @@ export default function PullRequestPage({ return } - const result = activateAndRevealWorktree(currentAttached.id) + const result = activateAndRevealWorktree(currentAttached.id, { + navigationIntent: 'user-open' + }) if (result === false) { toast.error( translate( diff --git a/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx b/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx index c6664b14e2cb..8bdac0ca1437 100644 --- a/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx @@ -79,6 +79,7 @@ vi.mock('lucide-react', async () => ) vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, translate: (_key: string, fallback: string) => fallback })) diff --git a/src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts b/src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts index bf7eb3c758eb..5f3b588f93c2 100644 --- a/src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts +++ b/src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts @@ -88,6 +88,7 @@ describe('sleep flow vs slept-workspace activation', () => { expect(mocks.resumeWorkspace).toHaveBeenCalledWith({ workspaceId: 'wt-parent' }) expect(mocks.activateAndRevealWorktree).toHaveBeenCalledTimes(1) expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('wt-parent', { + navigationIntent: 'user-open', revealInSidebar: false }) @@ -102,6 +103,7 @@ describe('sleep flow vs slept-workspace activation', () => { await activateWorktreeFromSidebar('wt-parent') expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('wt-parent', { + navigationIntent: 'user-open', revealInSidebar: false }) expect(mocks.toastError).toHaveBeenCalledWith( diff --git a/src/renderer/src/components/sidebar/use-worktree-context-menu-commands.ts b/src/renderer/src/components/sidebar/use-worktree-context-menu-commands.ts index ebef4544b231..30920343680f 100644 --- a/src/renderer/src/components/sidebar/use-worktree-context-menu-commands.ts +++ b/src/renderer/src/components/sidebar/use-worktree-context-menu-commands.ts @@ -164,7 +164,7 @@ export function useWorktreeContextMenuCommands(args: { }, [args]) const handleOpenParent = useCallback(() => { if (args.validParentWorktreeId) { - activateAndRevealWorktree(args.validParentWorktreeId) + activateAndRevealWorktree(args.validParentWorktreeId, { navigationIntent: 'user-open' }) } }, [args.validParentWorktreeId]) return { diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.focus.test.tsx b/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.focus.test.tsx index 53783410ef4b..c09637354f21 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.focus.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.focus.test.tsx @@ -146,7 +146,10 @@ describe('workspace list focus ownership', () => { expect(document.activeElement).toBe(list) press('ArrowUp') expect(activate.mock.calls.map(([id]) => id)).toEqual(['b', 'c', 'b']) - expect(activate).toHaveBeenLastCalledWith('b', { executionHostId: 'ssh:fixture' }) + expect(activate).toHaveBeenLastCalledWith('b', { + navigationIntent: 'user-open', + executionHostId: 'ssh:fixture' + }) expect(terminal.focus).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.host-identity.test.tsx b/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.host-identity.test.tsx index efac59a9c078..4944d69340ac 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.host-identity.test.tsx +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.host-identity.test.tsx @@ -101,7 +101,7 @@ describe('worktree keyboard cycling with a resolved active host', () => { press('down') - expect(activateAndRevealWorktree).toHaveBeenCalledWith('c', {}) + expect(activateAndRevealWorktree).toHaveBeenCalledWith('c', { navigationIntent: 'user-open' }) }) it('steps to the previous row when the active host resolved to local', () => { @@ -109,7 +109,7 @@ describe('worktree keyboard cycling with a resolved active host', () => { press('up') - expect(activateAndRevealWorktree).toHaveBeenCalledWith('a', {}) + expect(activateAndRevealWorktree).toHaveBeenCalledWith('a', { navigationIntent: 'user-open' }) }) it('still steps normally when the active host is unqualified', () => { @@ -117,6 +117,6 @@ describe('worktree keyboard cycling with a resolved active host', () => { press('down') - expect(activateAndRevealWorktree).toHaveBeenCalledWith('c', {}) + expect(activateAndRevealWorktree).toHaveBeenCalledWith('c', { navigationIntent: 'user-open' }) }) }) diff --git a/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.ts b/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.ts index cff03054692b..612bd82b505c 100644 --- a/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.ts +++ b/src/renderer/src/components/sidebar/worktree-list/navigation/use-keyboard.ts @@ -89,10 +89,10 @@ export function useWorktreeListKeyboardNavigation(args: { } // Why: keyboard cycling is real navigation; route through the activation helper that records history. - activateAndRevealWorktree( - nextWorktree.id, - nextWorktree.hostId ? { executionHostId: nextWorktree.hostId } : {} - ) + activateAndRevealWorktree(nextWorktree.id, { + navigationIntent: 'user-open', + ...(nextWorktree.hostId ? { executionHostId: nextWorktree.hostId } : {}) + }) const rowIndex = findPreferredRenderRowIndexForWorktreeIdentity( renderRows, diff --git a/src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx b/src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx index d6d4ad951840..3f518db6751b 100644 --- a/src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx +++ b/src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx @@ -30,6 +30,7 @@ vi.mock('@/lib/react-error-boundary-reporting', () => ({ })) vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, translate: (_key: string, fallback: string, options?: Record) => options ? fallback.replace(/{{(\w+)}}/g, (_match, name: string) => String(options[name] ?? '')) diff --git a/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx b/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx index 783202de0cb7..580c7f02f13b 100644 --- a/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx +++ b/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx @@ -23,6 +23,7 @@ vi.mock('@/components/ui/tooltip', () => ({ })) vi.mock('@/i18n/i18n', () => ({ + i18n: { language: 'en' }, translate: (_key: string, fallback: string, values?: Record) => values ? Object.entries(values).reduce( diff --git a/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts b/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts index 5c8c19757831..3bf7a94c1ddd 100644 --- a/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts +++ b/src/renderer/src/components/status-bar/workspace-space-manager-source-boundary.test.ts @@ -74,6 +74,6 @@ describe('workspace space manager source boundaries', () => { expect(controller).toContain( 'removeWorktree(\n { id: worktree.worktreeId, executionHostId: worktree.executionHostId ?? null },\n true,\n { allowUnverifiedPtyStop: true }\n )' ) - expect(table).toContain('activateAndRevealWorktree(worktree.worktreeId)') + expect(table).toContain('activateAndRevealWorktree(worktree.worktreeId, {') }) }) diff --git a/src/renderer/src/components/status-bar/workspace-space-manager-table.tsx b/src/renderer/src/components/status-bar/workspace-space-manager-table.tsx index d4a146555391..8b0ec305124c 100644 --- a/src/renderer/src/components/status-bar/workspace-space-manager-table.tsx +++ b/src/renderer/src/components/status-bar/workspace-space-manager-table.tsx @@ -140,7 +140,11 @@ export function WorkspaceSpaceManagerTable({ deleteState={getDeleteStateForWorktree(worktree)} onToggleSelected={() => toggleSelection(worktree)} onInspect={() => setInspectedWorktreeId(identity)} - onOpenWorkspace={() => activateAndRevealWorktree(worktree.worktreeId)} + onOpenWorkspace={() => + activateAndRevealWorktree(worktree.worktreeId, { + navigationIntent: 'user-open' + }) + } onDelete={() => deleteWorktrees([worktree])} onForceDelete={() => forceDeleteWorktree(worktree)} /> diff --git a/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts b/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts index a16128eee760..4eedb629f2aa 100644 --- a/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts +++ b/src/renderer/src/components/task-page-workspace-composer-boundary.test.ts @@ -110,7 +110,7 @@ describe('TaskPage workspace creation source boundaries', () => { expect(section).toContain('findGithubWorkItemWorkspaceAttachment(') expect(section).toContain('if (!currentAttached)') expect(section).toContain('handleUseWorkItem(item)') - expect(section).toContain('activateAndRevealWorktree(currentAttached.id)') + expect(section).toContain('activateAndRevealWorktree(currentAttached.id, {') }) it('uses the shared composer handler from GitHub detail and start-new actions', () => { diff --git a/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx b/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx index 734cef0f7956..ef45ae6cb3ec 100644 --- a/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx +++ b/src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx @@ -3,6 +3,10 @@ import { act, StrictMode } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' import { useTerminalWatcherEffects } from '../use-terminal-watcher-effects' +import { + claimEmptyWorkspaceDefaultSurface, + releaseEmptyWorkspaceDefaultSurface +} from '@/lib/empty-workspace-default-surface-claims' const mocks = vi.hoisted(() => { const storeTabsByWorktree: Record = {} @@ -45,6 +49,8 @@ vi.mock('../terminal-pane/terminal-parked-tab-watchers', () => ({ disposeAllParkedTerminalWatchers: vi.fn() })) +const PENDING_INTENT = { callerProvidesSurface: false, seedUserDefaultSurface: true } + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) let root: Root | undefined afterEach(async () => { @@ -202,6 +208,36 @@ describe('passive terminal seeding retries until a decision applies', () => { expect(mocks.createTab).toHaveBeenCalledTimes(1) }) + it('leaves the seed to an activation reseed awaiting agent detection', async () => { + const finishGate = deferredGate() + root = createRoot(document.createElement('div')) + await act(async () => root?.render()) + claimEmptyWorkspaceDefaultSurface('wt-1', PENDING_INTENT) + try { + await finishGate('empty') + expect(mocks.createTab).not.toHaveBeenCalled() + } finally { + releaseEmptyWorkspaceDefaultSurface('wt-1') + } + }) + + // Why: that reseed bails once the user leaves, so a workspace left mid-wait must seed on return. + it('seeds on return to a workspace left while a reseed awaited agent detection', async () => { + mocks.gate.mockResolvedValue('empty') + claimEmptyWorkspaceDefaultSurface('wt-1', PENDING_INTENT) + root = createRoot(document.createElement('div')) + try { + await act(async () => root?.render()) + expect(mocks.createTab).not.toHaveBeenCalled() + } finally { + releaseEmptyWorkspaceDefaultSurface('wt-1') + } + + await act(async () => root?.render()) + await act(async () => root?.render()) + expect(mocks.createTab).toHaveBeenCalledTimes(1) + }) + it('seeds after leaving and returning to a blocked workspace', async () => { mocks.gate.mockResolvedValue('blocked') root = createRoot(document.createElement('div')) diff --git a/src/renderer/src/components/use-task-page-workspace-actions.ts b/src/renderer/src/components/use-task-page-workspace-actions.ts index 2a88981b6756..5e2cb6f2aab5 100644 --- a/src/renderer/src/components/use-task-page-workspace-actions.ts +++ b/src/renderer/src/components/use-task-page-workspace-actions.ts @@ -60,7 +60,9 @@ export function useTaskPageWorkspaceActions(model: TaskPageSearchActionsModel) { handleUseWorkItem(item) return } - const result = activateAndRevealWorktree(currentAttached.id) + const result = activateAndRevealWorktree(currentAttached.id, { + navigationIntent: 'user-open' + }) if (result === false) { toast.error( item.type === 'pr' diff --git a/src/renderer/src/components/use-terminal-watcher-effects.ts b/src/renderer/src/components/use-terminal-watcher-effects.ts index f91c06bd7d7c..39764c873457 100644 --- a/src/renderer/src/components/use-terminal-watcher-effects.ts +++ b/src/renderer/src/components/use-terminal-watcher-effects.ts @@ -14,6 +14,7 @@ import { isTerminalWorkspaceEmptiedOnPurpose } from '../../../shared/closed-term import { gateWorktreeAgentActivation } from '@/lib/worktree-agent-activation-gate' import { createWorkspaceTerminalHostAuthoritySelector } from '@/lib/workspace-terminal-host-authority' import { getStructuredAgentLaunchStatus } from '@/lib/structured-agent-session-launch' +import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/empty-workspace-default-surface-claims' import { AGENT_SESSION_PROVIDER_HANDLE_PROVIDERS } from '../../../shared/agent-session-provider-handle' import type { TerminalColdActivationController } from './terminal-cold-activation' import { selectParkedEquivalentMountTabIds } from './terminal/startup-terminal-tab-hold' @@ -223,6 +224,11 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController) ) { return } + // A reseed awaiting agent detection owns the surface. Left unmarked: that reseed bails if the + // user leaves during the wait, so a later return must seed here. + if (outcome === 'empty' && isEmptyWorkspaceDefaultSurfacePending(activeWorktreeId)) { + return + } // Why mark only once a decision applies: a cancelled or blocked check must stay retryable, // and a rerun shares the gate's in-flight promise instead of repeating its work. startupActivationGateWorktreeIdsRef.current.add(activeWorktreeId) diff --git a/src/renderer/src/components/use-worktree-jump-palette-selection-actions.ts b/src/renderer/src/components/use-worktree-jump-palette-selection-actions.ts index e0da6c158fef..822a23f9e622 100644 --- a/src/renderer/src/components/use-worktree-jump-palette-selection-actions.ts +++ b/src/renderer/src/components/use-worktree-jump-palette-selection-actions.ts @@ -65,10 +65,10 @@ export function useWorktreeJumpPaletteSelectionActions({ ) return } - const activation = activateAndRevealWorktree( - worktree.id, - executionHostId ? { executionHostId } : {} - ) + const activation = activateAndRevealWorktree(worktree.id, { + navigationIntent: 'user-open', + ...(executionHostId ? { executionHostId } : {}) + }) recordFeatureInteraction('cmd-j-workspace-open') skipRestoreFocusRef.current = true closeModal() diff --git a/src/renderer/src/hooks/ipc-events/workspace-shortcut-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/workspace-shortcut-ipc-bridge.ts index 9e78916fef3d..496f885ebbb5 100644 --- a/src/renderer/src/hooks/ipc-events/workspace-shortcut-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/workspace-shortcut-ipc-bridge.ts @@ -93,11 +93,10 @@ export function registerWorkspaceShortcutIpcBridge(unsubs: (() => void)[]): void const visibleTargets = getVisibleWorktreeShortcutTargets() const target = visibleTargets[index] if (target) { - if (target.executionHostId) { - activateAndRevealWorkspace(target.id, { executionHostId: target.executionHostId }) - } else { - activateAndRevealWorkspace(target.id) - } + activateAndRevealWorkspace(target.id, { + navigationIntent: 'user-open', + ...(target.executionHostId ? { executionHostId: target.executionHostId } : {}) + }) } }) ) diff --git a/src/renderer/src/hooks/useIpcEvents-cmd-j-digit-chord.test.ts b/src/renderer/src/hooks/useIpcEvents-cmd-j-digit-chord.test.ts index a0ff1ea24dc9..ae61b9adcb9a 100644 --- a/src/renderer/src/hooks/useIpcEvents-cmd-j-digit-chord.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-cmd-j-digit-chord.test.ts @@ -52,7 +52,9 @@ describe('useIpcEvents digit-chord routing while Cmd+J is open', () => { expect(rowJumps).toEqual([]) // Why assert the activation and not just the silent bus: a premature return would also emit nothing. - expect(harness.activateAndRevealWorkspace).toHaveBeenCalledWith('wt-c') + expect(harness.activateAndRevealWorkspace).toHaveBeenCalledWith('wt-c', { + navigationIntent: 'user-open' + }) }) it('routes duplicate ids at different positions to their rendered hosts', async () => { @@ -67,6 +69,7 @@ describe('useIpcEvents digit-chord routing while Cmd+J is open', () => { harness.jumpToWorktreeIndex(1) expect(harness.activateAndRevealWorkspace).toHaveBeenCalledWith('repo::path', { + navigationIntent: 'user-open', executionHostId: 'ssh:box' }) }) diff --git a/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts b/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts index 5a3dadedf83c..0b168e66ef4b 100644 --- a/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts +++ b/src/renderer/src/lib/agent-launch-caller-profile-census.test.ts @@ -33,7 +33,7 @@ describe('agent launch caller profiles', () => { const ids = AGENT_LAUNCH_CALLER_PROFILES.map((profile) => profile.id) expect(new Set(ids).size).toBe(ids.length) - expect(ids.length).toBe(12) + expect(ids.length).toBe(13) }) it.each(AGENT_LAUNCH_CALLER_PROFILES.map((profile) => [profile.id, profile] as const))( @@ -70,6 +70,7 @@ describe('agent launch caller profiles', () => { // Why: this is the coupling a move to an async launch RPC threatens most directly — these // call sites cannot tolerate a tab id that only exists after the launch settles. expect(readers.sort()).toEqual([ + 'empty-workspace-default-chat', 'fix-checks', 'floating-default-agent', 'quick-command', diff --git a/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts b/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts index 39d7c77a13f0..5aaa913044fa 100644 --- a/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts +++ b/src/renderer/src/lib/agent-launch-caller-profiles-test-harness.ts @@ -58,6 +58,21 @@ export const AGENT_LAUNCH_CALLER_PROFILES: readonly AgentLaunchCallerProfile[] = passesOnPromptDelivered: false, readsBack: ['null-only'] }, + { + id: 'empty-workspace-default-chat', + caller: 'src/renderer/src/lib/empty-workspace-default-agent-chat.ts', + sourceMarkers: ["launchSource: 'unknown'", 'pendingActivationSpawn: true'], + args: { + agent: 'codex', + worktreeId: 'wt-1', + launchSource: 'unknown', + pendingActivationSpawn: true + }, + passesBeforeSurfaceOpen: false, + passesLaunchPlan: true, + passesOnPromptDelivered: false, + readsBack: ['surface-tab-id'] + }, { id: 'floating-default-agent', caller: 'src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx', diff --git a/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts b/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts index 3e91c5c8ec0c..2c9524c99957 100644 --- a/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts +++ b/src/renderer/src/lib/agent-launch-routing-caller-census.test.ts @@ -18,6 +18,7 @@ const LAUNCH_AGENT_IN_NEW_TAB_CALLERS = [ 'src/renderer/src/components/tab-bar/use-tab-bar-create-menu-controller.ts', 'src/renderer/src/components/terminal-pane/terminal-agent-session-fork.ts', 'src/renderer/src/components/use-terminal-create-actions.ts', + 'src/renderer/src/lib/empty-workspace-default-agent-chat.ts', 'src/renderer/src/lib/fix-checks-agent-launch.ts', 'src/renderer/src/lib/launch-agent-session-continuation.ts', 'src/renderer/src/lib/run-quick-command-in-new-tab.ts' diff --git a/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts b/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts new file mode 100644 index 000000000000..e3ad93eb3db4 --- /dev/null +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts @@ -0,0 +1,154 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { getDefaultSettings } from '../../../shared/constants' +import { useAppStore } from '@/store' +import { + emptyWorkspaceDefaultChatAwaitsDetection, + loadEmptyWorkspaceDefaultChatDetection, + openDefaultAgentChatInEmptyWorkspace +} from './empty-workspace-default-agent-chat' + +const mocks = vi.hoisted(() => ({ + launchAgentInNewTab: vi.fn(), + planAgentSessionLaunch: vi.fn(), + detectionTargetKey: vi.fn<() => string | undefined>() +})) + +vi.mock('@/lib/launch-agent-in-new-tab', () => ({ + launchAgentInNewTab: mocks.launchAgentInNewTab +})) +vi.mock('@/lib/agent-session-launch-plan', () => ({ + planAgentSessionLaunch: mocks.planAgentSessionLaunch +})) +vi.mock('@/hooks/useAgentDetectionTarget', async (importOriginal) => ({ + ...(await importOriginal>()), + getAgentDetectionTargetKeyForWorktree: mocks.detectionTargetKey +})) + +const initialAppStoreState = useAppStore.getState() + +function seedSettings(settings: Partial): void { + useAppStore.setState({ + detectedAgentIds: ['claude', 'codex'], + settings: { + ...getDefaultSettings('/tmp'), + experimentalNativeChat: true, + openAgentTabsInChatByDefault: true, + defaultTuiAgent: 'codex', + disabledTuiAgents: [], + ...settings + } + }) +} + +beforeEach(() => { + mocks.detectionTargetKey.mockReturnValue('local') + mocks.planAgentSessionLaunch.mockReturnValue({ route: 'structured-native-chat' }) + mocks.launchAgentInNewTab.mockReturnValue({ + surface: { kind: 'local-agent-session', tabId: 'chat-tab', sessionId: 's-1' } + }) +}) + +afterEach(() => { + vi.useRealTimers() + vi.clearAllMocks() + useAppStore.setState(initialAppStoreState, true) +}) + +describe('openDefaultAgentChatInEmptyWorkspace', () => { + it('launches the default agent as a chat', () => { + seedSettings({}) + + expect(openDefaultAgentChatInEmptyWorkspace('wt-1')).toEqual({ primaryTabId: 'chat-tab' }) + expect(mocks.launchAgentInNewTab).toHaveBeenCalledWith( + expect.objectContaining({ agent: 'codex', worktreeId: 'wt-1', pendingActivationSpawn: true }) + ) + }) + + it('does nothing unless new agent tabs open as chat', () => { + seedSettings({ openAgentTabsInChatByDefault: false }) + + expect(openDefaultAgentChatInEmptyWorkspace('wt-1')).toBeNull() + expect(mocks.launchAgentInNewTab).not.toHaveBeenCalled() + }) + + it('respects a Blank Terminal default agent', () => { + seedSettings({ defaultTuiAgent: 'blank' }) + + expect(openDefaultAgentChatInEmptyWorkspace('wt-1')).toBeNull() + expect(mocks.launchAgentInNewTab).not.toHaveBeenCalled() + }) + + it('does not start an agent that could only open as a terminal here', () => { + seedSettings({}) + mocks.planAgentSessionLaunch.mockReturnValue({ route: 'terminal-tui' }) + + expect(openDefaultAgentChatInEmptyWorkspace('wt-1')).toBeNull() + expect(mocks.launchAgentInNewTab).not.toHaveBeenCalled() + }) + + it('reads the agents detected on the workspace SSH host', () => { + seedSettings({}) + mocks.detectionTargetKey.mockReturnValue('ssh:conn-1') + useAppStore.setState({ remoteDetectedAgentIds: { 'conn-1': ['claude'] } }) + + openDefaultAgentChatInEmptyWorkspace('wt-1') + + expect(mocks.launchAgentInNewTab).toHaveBeenCalledWith( + expect.objectContaining({ agent: 'claude' }) + ) + }) + + it('treats a workspace whose host is unresolved as unknown', () => { + seedSettings({}) + mocks.detectionTargetKey.mockReturnValue(undefined) + + expect(emptyWorkspaceDefaultChatAwaitsDetection('wt-1')).toBe(false) + expect(openDefaultAgentChatInEmptyWorkspace('wt-1')).toBeNull() + expect(mocks.launchAgentInNewTab).not.toHaveBeenCalled() + }) +}) + +describe('agent detection for the default chat', () => { + it('waits only while chat is the default and the host list has not loaded', () => { + seedSettings({}) + mocks.detectionTargetKey.mockReturnValue('ssh:conn-1') + useAppStore.setState({ remoteDetectedAgentIds: {} }) + expect(emptyWorkspaceDefaultChatAwaitsDetection('wt-1')).toBe(true) + + useAppStore.setState({ remoteDetectedAgentIds: { 'conn-1': [] } }) + expect(emptyWorkspaceDefaultChatAwaitsDetection('wt-1')).toBe(false) + + seedSettings({ openAgentTabsInChatByDefault: false }) + useAppStore.setState({ remoteDetectedAgentIds: {} }) + expect(emptyWorkspaceDefaultChatAwaitsDetection('wt-1')).toBe(false) + }) + + // Why: Blank Terminal opens a shell whatever the host has, so waiting only delays that shell. + it('does not wait when the default agent is Blank Terminal', () => { + seedSettings({ defaultTuiAgent: 'blank' }) + mocks.detectionTargetKey.mockReturnValue('ssh:conn-1') + useAppStore.setState({ remoteDetectedAgentIds: {} }) + + expect(emptyWorkspaceDefaultChatAwaitsDetection('wt-1')).toBe(false) + }) + + it('probes the workspace host and gives up after a bounded wait', async () => { + vi.useFakeTimers() + seedSettings({}) + mocks.detectionTargetKey.mockReturnValue('ssh:conn-1') + const ensureRemoteDetectedAgents = vi.fn(() => new Promise(() => {})) + useAppStore.setState({ ensureRemoteDetectedAgents }) + let settled = false + + void loadEmptyWorkspaceDefaultChatDetection('wt-1').then(() => { + settled = true + }) + await vi.advanceTimersByTimeAsync(4_999) + expect(settled).toBe(false) + await vi.advanceTimersByTimeAsync(1) + + expect(ensureRemoteDetectedAgents).toHaveBeenCalledWith('conn-1') + expect(settled).toBe(true) + }) +}) diff --git a/src/renderer/src/lib/empty-workspace-default-agent-chat.ts b/src/renderer/src/lib/empty-workspace-default-agent-chat.ts new file mode 100644 index 000000000000..84156f99927e --- /dev/null +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.ts @@ -0,0 +1,113 @@ +import { agentTabsDefaultToNativeChat } from '../../../shared/structured-native-chat-launch-route' +import { pickTuiAgent } from '../../../shared/tui-agent-selection' +import type { TuiAgent } from '../../../shared/tui-agent' +import { withTimeout } from '../../../shared/promise-timeout-fallback' +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import { + getAgentDetectionTargetKeyForWorktree, + parseAgentDetectionTargetKey +} from '@/hooks/useAgentDetectionTarget' +import type { AgentDetectionTarget } from '@/hooks/useDetectedAgents' +import { workspaceKindForWorktreeId } from '@/lib/agent-launch-route-input' +import { planAgentSessionLaunch } from '@/lib/agent-session-launch-plan' +import { launchAgentInNewTab } from '@/lib/launch-agent-in-new-tab' + +// Why bounded: detection only decides chat vs shell, so a slow host must not hold the workspace empty. +const DEFAULT_CHAT_DETECTION_TIMEOUT_MS = 5_000 + +/** + * The host whose agent list picks the default chat; undefined when the workspace opens a shell + * whatever that list says. Shared by the wait and the open so they cannot drift. + */ +function defaultChatDetectionTarget( + state: AppState, + worktreeId: string +): AgentDetectionTarget | undefined { + // Why: a 'blank' default means the user wants workspaces to open without an agent. + if ( + !agentTabsDefaultToNativeChat(state.settings) || + state.settings?.defaultTuiAgent === 'blank' + ) { + return undefined + } + // Why: an unresolved owner is an unknown host, not the local machine. + return parseAgentDetectionTargetKey(getAgentDetectionTargetKeyForWorktree(state, worktreeId)) +} + +/** Same host lists the tab bar reads; null means that host's detection has not loaded. */ +function readDetectedAgents(state: AppState, target: AgentDetectionTarget): TuiAgent[] | null { + if (target.kind === 'ssh') { + return state.remoteDetectedAgentIds[target.connectionId] ?? null + } + if (target.kind === 'runtime') { + return state.runtimeDetectedAgentIds[target.environmentId] ?? null + } + return target.contextKey + ? (state.localDetectedAgentIdsByContext[target.contextKey] ?? null) + : state.detectedAgentIds +} + +/** True when the default chat could open here but the workspace host's agent list has not loaded. */ +export function emptyWorkspaceDefaultChatAwaitsDetection(worktreeId: string): boolean { + const state = useAppStore.getState() + const target = defaultChatDetectionTarget(state, worktreeId) + return target !== undefined && readDetectedAgents(state, target) === null +} + +/** Loads the workspace host's agent list; resolves on success, failure, or timeout. */ +export async function loadEmptyWorkspaceDefaultChatDetection(worktreeId: string): Promise { + const state = useAppStore.getState() + const target = defaultChatDetectionTarget(state, worktreeId) + if (!target) { + return + } + const detection = + target.kind === 'ssh' + ? state.ensureRemoteDetectedAgents(target.connectionId) + : target.kind === 'runtime' + ? state.ensureRuntimeDetectedAgents(target.environmentId) + : state.ensureDetectedAgents(target.worktreeId) + await withTimeout(detection, DEFAULT_CHAT_DETECTION_TIMEOUT_MS, []) +} + +/** + * When the user's new agent tabs open as chat, an empty workspace opens their default agent as a + * chat instead of a bare shell. Null means nothing opened and the caller seeds the shell. + */ +export function openDefaultAgentChatInEmptyWorkspace( + worktreeId: string +): { primaryTabId: string | null } | null { + const state = useAppStore.getState() + const target = defaultChatDetectionTarget(state, worktreeId) + if (!target) { + return null + } + const agent = pickTuiAgent( + state.settings?.defaultTuiAgent, + readDetectedAgents(state, target) ?? [], + state.settings?.disabledTuiAgents + ) + if (!agent) { + return null + } + const agentSessionLaunchPlan = planAgentSessionLaunch(state, { + agent, + workspace: { kind: workspaceKindForWorktreeId(worktreeId), worktreeId } + }) + // Why: an agent that can only open as a TUI here would replace the shell with a process nobody asked for. + if (agentSessionLaunchPlan.route === 'terminal-tui') { + return null + } + const result = launchAgentInNewTab({ + agent, + worktreeId, + launchSource: 'unknown', + agentSessionLaunchPlan, + pendingActivationSpawn: true + }) + if (!result) { + return null + } + return { primaryTabId: result.surface.kind === 'host-published' ? null : result.surface.tabId } +} diff --git a/src/renderer/src/lib/empty-workspace-default-surface-claims.ts b/src/renderer/src/lib/empty-workspace-default-surface-claims.ts new file mode 100644 index 000000000000..61a989e6bfc0 --- /dev/null +++ b/src/renderer/src/lib/empty-workspace-default-surface-claims.ts @@ -0,0 +1,29 @@ +import type { GatedEmptyWorkspaceReseedIntent } from './worktree-initial-terminal-seeding' + +// Why: while a gated reseed waits on agent detection, it owns the workspace's first surface; +// any other seeder landing in that wait would put a shell beside the chat it is about to open. +// Why the intent: the wait seeds for the latest activation, so a later one must not be dropped. +const pendingIntentByWorkspace = new Map() + +/** Records this activation's intent; false when a wait already pending now carries it instead. */ +export function claimEmptyWorkspaceDefaultSurface( + workspaceKey: string, + intent: GatedEmptyWorkspaceReseedIntent +): boolean { + const alreadyPending = pendingIntentByWorkspace.has(workspaceKey) + pendingIntentByWorkspace.set(workspaceKey, intent) + return !alreadyPending +} + +/** Ends the wait and returns the latest activation's intent. */ +export function releaseEmptyWorkspaceDefaultSurface( + workspaceKey: string +): GatedEmptyWorkspaceReseedIntent | undefined { + const intent = pendingIntentByWorkspace.get(workspaceKey) + pendingIntentByWorkspace.delete(workspaceKey) + return intent +} + +export function isEmptyWorkspaceDefaultSurfacePending(workspaceKey: string): boolean { + return pendingIntentByWorkspace.has(workspaceKey) +} diff --git a/src/renderer/src/lib/launch-agent-in-new-tab.ts b/src/renderer/src/lib/launch-agent-in-new-tab.ts index f4923c79b5e1..ce28d3c8ad18 100644 --- a/src/renderer/src/lib/launch-agent-in-new-tab.ts +++ b/src/renderer/src/lib/launch-agent-in-new-tab.ts @@ -60,6 +60,8 @@ export type LaunchAgentInNewTabArgs = { onPromptDeliveryUnconfirmed?: () => void /** Keeps a preflighted route authoritative across workspace creation. */ agentSessionLaunchPlan?: AgentSessionLaunchPlan + /** The launch seeds a workspace being opened, so its PTY spawn must not reshuffle Recent. */ + pendingActivationSpawn?: boolean /** Lets a workspace reveal itself before the selected surface opens. */ beforeSurfaceOpen?: ( surface: @@ -114,6 +116,7 @@ function launchAgentInNewTabInternal(args: LaunchAgentInNewTabArgs): LaunchAgent onPromptDelivered, onPromptDeliveryUnconfirmed, agentSessionLaunchPlan, + pendingActivationSpawn, beforeSurfaceOpen } = args const store = useAppStore.getState() @@ -245,6 +248,7 @@ function launchAgentInNewTabInternal(args: LaunchAgentInNewTabArgs): LaunchAgent const tab = store.createTab(worktreeId, groupId, undefined, { launchAgent: agent, quickCommandLabel, + ...(pendingActivationSpawn ? { pendingActivationSpawn: true } : {}), ...initialViewModeProps }) seedNativeChatAppliedSessionOptions(tab.id, agent, startupPlan.sessionOptions) diff --git a/src/renderer/src/lib/linear-issue-workspace-open.test.ts b/src/renderer/src/lib/linear-issue-workspace-open.test.ts index 86a72ab4df9d..e455c52308ab 100644 --- a/src/renderer/src/lib/linear-issue-workspace-open.test.ts +++ b/src/renderer/src/lib/linear-issue-workspace-open.test.ts @@ -87,6 +87,7 @@ describe('openLinearIssueWorkspaceOrStart', () => { expect(openLinearIssueWorkspaceOrStart({ identifier: 'ENG-1' }, vi.fn())).toBe('opened') expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('worktree-1', { + navigationIntent: 'user-open', executionHostId: 'ssh:builder' }) }) @@ -97,6 +98,7 @@ describe('openLinearIssueWorkspaceOrStart', () => { expect(openLinearIssueWorkspaceOrStart({ identifier: 'ENG-1' }, startWorkspace)).toBe('opened') expect(mocks.activateAndRevealFolderWorkspace).toHaveBeenCalledWith('folder-1', { + navigationIntent: 'user-open', executionHostId: 'local' }) expect(startWorkspace).not.toHaveBeenCalled() diff --git a/src/renderer/src/lib/linear-issue-workspace-open.ts b/src/renderer/src/lib/linear-issue-workspace-open.ts index 4b838176f444..63d2944c180c 100644 --- a/src/renderer/src/lib/linear-issue-workspace-open.ts +++ b/src/renderer/src/lib/linear-issue-workspace-open.ts @@ -35,14 +35,14 @@ export function openLinearIssueWorkspaceOrStart( const workspaceScope = parseWorkspaceKey(attached.id) const activation = workspaceScope?.type === 'folder' - ? activateAndRevealFolderWorkspace( - workspaceScope.folderWorkspaceId, - attached.hostId ? { executionHostId: attached.hostId } : undefined - ) - : activateAndRevealWorktree( - attached.id, - attached.hostId ? { executionHostId: attached.hostId } : {} - ) + ? activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId, { + navigationIntent: 'user-open', + ...(attached.hostId ? { executionHostId: attached.hostId } : {}) + }) + : activateAndRevealWorktree(attached.id, { + navigationIntent: 'user-open', + ...(attached.hostId ? { executionHostId: attached.hostId } : {}) + }) if (activation === false) { toast.error( translate( diff --git a/src/renderer/src/lib/sidebar-worktree-activation.test.ts b/src/renderer/src/lib/sidebar-worktree-activation.test.ts index a33f91565a25..a12ca8affa81 100644 --- a/src/renderer/src/lib/sidebar-worktree-activation.test.ts +++ b/src/renderer/src/lib/sidebar-worktree-activation.test.ts @@ -26,6 +26,7 @@ describe('sidebar worktree activation', () => { await activateWorktreeFromSidebar('wt-live') expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('wt-live', { + navigationIntent: 'user-open', revealInSidebar: false }) expect(mocks.activateAndRevealFolderWorkspace).not.toHaveBeenCalled() @@ -38,6 +39,7 @@ describe('sidebar worktree activation', () => { // sidebar click itself must switch app state immediately. expect(mocks.activateAndRevealWorktree).toHaveBeenCalledTimes(1) expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('wt-slept', { + navigationIntent: 'user-open', revealInSidebar: false }) }) @@ -57,6 +59,7 @@ describe('sidebar worktree activation', () => { const activation = activateWorktreeFromSidebar('wt-vm') expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('wt-vm', { + navigationIntent: 'user-open', revealInSidebar: false }) expect(resumeWorkspace).toHaveBeenCalledWith({ workspaceId: 'wt-vm' }) @@ -68,7 +71,9 @@ describe('sidebar worktree activation', () => { it('routes folder workspace activation through the guarded folder path', async () => { await activateWorktreeFromSidebar('folder:folder-workspace-1') - expect(mocks.activateAndRevealFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1') + expect(mocks.activateAndRevealFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1', { + navigationIntent: 'user-open' + }) expect(mocks.activateAndRevealWorktree).not.toHaveBeenCalled() }) }) diff --git a/src/renderer/src/lib/sidebar-worktree-activation.ts b/src/renderer/src/lib/sidebar-worktree-activation.ts index dd4eec3f0df6..01bb94ad11b8 100644 --- a/src/renderer/src/lib/sidebar-worktree-activation.ts +++ b/src/renderer/src/lib/sidebar-worktree-activation.ts @@ -13,17 +13,15 @@ export async function activateWorktreeFromSidebar( ): Promise { const workspaceScope = parseWorkspaceKey(worktreeId) if (workspaceScope?.type === 'folder') { - if (executionHostId) { - activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId, { - executionHostId - }) - } else { - activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId) - } + activateAndRevealFolderWorkspace(workspaceScope.folderWorkspaceId, { + navigationIntent: 'user-open', + ...(executionHostId ? { executionHostId } : {}) + }) return } // Keep navigation independent from an optional runtime wake IPC. activateAndRevealWorktree(worktreeId, { + navigationIntent: 'user-open', revealInSidebar: false, ...(executionHostId ? { executionHostId } : {}) }) diff --git a/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts b/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts new file mode 100644 index 000000000000..ae956cabd216 --- /dev/null +++ b/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts @@ -0,0 +1,362 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { activateAndRevealFolderWorkspace, activateAndRevealWorktree } from './worktree-activation' +import * as activationGate from './worktree-agent-activation-gate' +import { + ensureWorktreeHasInitialTerminal, + reseedGatedEmptyWorkspace +} from './worktree-initial-terminal-seeding' +import { + isEmptyWorkspaceDefaultSurfacePending, + releaseEmptyWorkspaceDefaultSurface +} from './empty-workspace-default-surface-claims' +import { folderWorkspaceKey } from '../../../shared/workspace-scope' +import { + makeCreatedAgentWorktree as makeWorktree, + seedEmptyActivatableWorktree +} from '@/lib/worktree-activation-created-agent-test-state' +import { + createMockStore, + registerWorktreeActivationReset +} from './worktree-activation-test-harness' + +const defaultChat = vi.hoisted(() => ({ + open: vi.fn(), + awaitsDetection: vi.fn(), + loadDetection: vi.fn() +})) + +vi.mock('@/lib/empty-workspace-default-agent-chat', () => ({ + openDefaultAgentChatInEmptyWorkspace: defaultChat.open, + emptyWorkspaceDefaultChatAwaitsDetection: defaultChat.awaitsDetection, + loadEmptyWorkspaceDefaultChatDetection: defaultChat.loadDetection +})) + +const USER_OPEN = { navigationIntent: 'user-open' } as const +const FOLDER_ID = 'folder-1' +const FOLDER_KEY = folderWorkspaceKey(FOLDER_ID) +const initialAppStoreState = useAppStore.getState() + +registerWorktreeActivationReset() + +beforeEach(() => { + defaultChat.open.mockReset() + defaultChat.awaitsDetection.mockReset().mockReturnValue(false) + defaultChat.loadDetection.mockReset().mockResolvedValue(undefined) +}) + +afterEach(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + releaseEmptyWorkspaceDefaultSurface(makeWorktree().id) + releaseEmptyWorkspaceDefaultSurface(FOLDER_KEY) + useAppStore.setState(initialAppStoreState, true) +}) + +/** Electron exposes the PTY inventory, so an empty workspace is seeded by the gated reseed. */ +function useElectronActivationGate(): ReturnType { + vi.stubGlobal('window', { api: { runtime: { call: vi.fn() }, pty: { listSessions: vi.fn() } } }) + return vi.spyOn(activationGate, 'gateWorktreeAgentActivation').mockResolvedValue('empty') +} + +function seedEmptyFolderWorkspace(): void { + useAppStore.setState({ + folderWorkspaces: [ + { + id: FOLDER_ID, + projectGroupId: 'group-1', + name: 'notes', + folderPath: '/local/notes', + executionHostId: 'local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0 + } + ], + activeView: 'terminal', + tabsByWorktree: {}, + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + getFreshFolderWorkspacePathStatus: () => ({ exists: true }), + markWorktreeVisited: vi.fn(), + recordWorktreeVisit: vi.fn(), + revealWorktreeInSidebar: vi.fn() + } as unknown as Partial>) +} + +function tabCount(workspaceKey: string): number { + return (useAppStore.getState().tabsByWorktree[workspaceKey] ?? []).length +} + +async function flushPromises(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +// Why: with chat as the default view, clicking an empty workspace used to open a bare shell the +// user then had to turn into a chat by hand. +describe('empty workspace seeding with a default agent chat', () => { + it('opens the default agent chat instead of a shell', () => { + defaultChat.open.mockReturnValue({ primaryTabId: 'chat-tab' }) + const createTab = vi.fn(() => ({ id: 'shell-tab' })) + const store = createMockStore({ createTab }) + + const primaryTabId = ensureWorktreeHasInitialTerminal( + store, + 'wt-1', + undefined, + undefined, + undefined, + undefined, + { seedUserDefaultSurface: true } + ) + + expect(defaultChat.open).toHaveBeenCalledWith('wt-1') + expect(primaryTabId).toBe('chat-tab') + expect(createTab).not.toHaveBeenCalled() + }) + + it('falls back to a shell when no chat can open', () => { + defaultChat.open.mockReturnValue(null) + const createTab = vi.fn(() => ({ id: 'shell-tab' })) + const store = createMockStore({ createTab }) + + const primaryTabId = ensureWorktreeHasInitialTerminal( + store, + 'wt-1', + undefined, + undefined, + undefined, + undefined, + { seedUserDefaultSurface: true } + ) + + expect(primaryTabId).toBe('shell-tab') + expect(createTab).toHaveBeenCalledTimes(1) + }) + + it('keeps the shell for seeds that did not ask for the default surface', () => { + const store = createMockStore({ createTab: vi.fn(() => ({ id: 'shell-tab' })) }) + + ensureWorktreeHasInitialTerminal(store, 'wt-1') + ensureWorktreeHasInitialTerminal(store, 'wt-2', undefined, undefined, undefined, undefined, { + seedUserDefaultSurface: true, + activateCreatedTabs: false + }) + + expect(defaultChat.open).not.toHaveBeenCalled() + }) + + it('a user open of an empty workspace asks for the default surface', () => { + defaultChat.open.mockReturnValue({ primaryTabId: null }) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + + activateAndRevealWorktree(worktree.id, { ...USER_OPEN, notifyHostRuntime: false }) + + expect(defaultChat.open).toHaveBeenCalledWith(worktree.id) + }) + + it('back/forward navigation asks for the default surface', () => { + defaultChat.open.mockReturnValue({ primaryTabId: null }) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + useAppStore.setState({ + worktreeNavHistory: [worktree.id, 'repo-1::/elsewhere'], + worktreeNavHistoryIndex: 1 + }) + + useAppStore.getState().goBackWorktree() + + expect(defaultChat.open).toHaveBeenCalledWith(worktree.id) + }) + + // Why: CLI/phone creates, fallbacks after a failed agent launch, and the move after a delete + // activate with no intent; none of them may start an agent nobody picked. + it.each([ + ['no navigation intent', {}], + ['a Blank Terminal pick', { ...USER_OPEN, agent: null }] + ])('keeps the shell for %s', (_label, selection) => { + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + + activateAndRevealWorktree(worktree.id, { ...selection, notifyHostRuntime: false }) + + expect(defaultChat.open).not.toHaveBeenCalled() + expect(tabCount(worktree.id)).toBe(1) + }) +}) + +describe('the gated reseed that seeds an empty workspace in Electron', () => { + it('opens the default agent chat for a user open', async () => { + defaultChat.open.mockReturnValue({ primaryTabId: null }) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + const result = activateAndRevealWorktree(worktree.id, { + ...USER_OPEN, + notifyHostRuntime: false + }) + expect(result === false ? 'failed' : result.primaryTabId).toBeNull() + await gate.mock.results[0]?.value + + expect(defaultChat.open).toHaveBeenCalledWith(worktree.id) + expect(tabCount(worktree.id)).toBe(0) + }) + + it('seeds a shell for an activation without a user open', async () => { + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false }) + await gate.mock.results[0]?.value + + expect(defaultChat.open).not.toHaveBeenCalled() + expect(tabCount(worktree.id)).toBe(1) + }) + + it('opens the default agent chat for a user-opened folder workspace', async () => { + defaultChat.open.mockReturnValue({ primaryTabId: null }) + seedEmptyFolderWorkspace() + const gate = useElectronActivationGate() + + activateAndRevealFolderWorkspace(FOLDER_ID, { ...USER_OPEN, executionHostId: 'local' }) + await gate.mock.results[0]?.value + + expect(defaultChat.open).toHaveBeenCalledWith(FOLDER_KEY) + expect(tabCount(FOLDER_KEY)).toBe(0) + }) + + it('waits for the host agent list and lets no other reseed seed a shell meanwhile', async () => { + defaultChat.open.mockReturnValue({ primaryTabId: null }) + defaultChat.awaitsDetection.mockReturnValue(true) + let finishDetection!: () => void + defaultChat.loadDetection.mockReturnValue( + new Promise((resolve) => { + finishDetection = resolve + }) + ) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + activateAndRevealWorktree(worktree.id, { ...USER_OPEN, notifyHostRuntime: false }) + await gate.mock.results[0]?.value + + expect(defaultChat.loadDetection).toHaveBeenCalledWith(worktree.id) + expect(isEmptyWorkspaceDefaultSurfacePending(worktree.id)).toBe(true) + reseedGatedEmptyWorkspace(worktree.id, { + callerProvidesSurface: false, + seedUserDefaultSurface: false + }) + expect(tabCount(worktree.id)).toBe(0) + expect(defaultChat.open).not.toHaveBeenCalled() + + finishDetection() + await flushPromises() + + expect(isEmptyWorkspaceDefaultSurfacePending(worktree.id)).toBe(false) + expect(defaultChat.open).toHaveBeenCalledTimes(1) + expect(tabCount(worktree.id)).toBe(0) + }) + + // Why: the wait used to keep the first activation's intent, so returning to the workspace through + // history (no host id) failed the first intent's host check and left it with no surface at all. + it('seeds for the latest activation when the workspace is reopened during the wait', async () => { + defaultChat.open.mockReturnValue({ primaryTabId: null }) + defaultChat.awaitsDetection.mockReturnValue(true) + let finishDetection!: () => void + defaultChat.loadDetection.mockReturnValue( + new Promise((resolve) => { + finishDetection = resolve + }) + ) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + activateAndRevealWorktree(worktree.id, { + ...USER_OPEN, + executionHostId: 'local', + notifyHostRuntime: false + }) + await gate.mock.results[0]?.value + useAppStore.setState({ activeWorktreeId: 'repo-1::/elsewhere' }) + activateAndRevealWorktree(worktree.id, { ...USER_OPEN, notifyHostRuntime: false }) + await gate.mock.results[1]?.value + expect(useAppStore.getState().activeWorkspaceExecutionHostId).toBeNull() + finishDetection() + await flushPromises() + + expect(defaultChat.loadDetection).toHaveBeenCalledTimes(1) + expect(isEmptyWorkspaceDefaultSurfacePending(worktree.id)).toBe(false) + expect(defaultChat.open).toHaveBeenCalledTimes(1) + }) + + it('seeds a shell when a plain activation follows the user open during the wait', async () => { + defaultChat.awaitsDetection.mockReturnValue(true) + let finishDetection!: () => void + defaultChat.loadDetection.mockReturnValue( + new Promise((resolve) => { + finishDetection = resolve + }) + ) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + activateAndRevealWorktree(worktree.id, { ...USER_OPEN, notifyHostRuntime: false }) + await gate.mock.results[0]?.value + activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false }) + await gate.mock.results[1]?.value + expect(tabCount(worktree.id)).toBe(0) + finishDetection() + await flushPromises() + + expect(defaultChat.open).not.toHaveBeenCalled() + expect(tabCount(worktree.id)).toBe(1) + }) + + it('re-checks the active workspace after the wait', async () => { + defaultChat.awaitsDetection.mockReturnValue(true) + let finishDetection!: () => void + defaultChat.loadDetection.mockReturnValue( + new Promise((resolve) => { + finishDetection = resolve + }) + ) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + activateAndRevealWorktree(worktree.id, { ...USER_OPEN, notifyHostRuntime: false }) + await gate.mock.results[0]?.value + useAppStore.setState({ activeWorktreeId: 'repo-1::/elsewhere' }) + finishDetection() + await flushPromises() + + expect(isEmptyWorkspaceDefaultSurfacePending(worktree.id)).toBe(false) + expect(defaultChat.open).not.toHaveBeenCalled() + expect(tabCount(worktree.id)).toBe(0) + }) + + it('seeds the shell when detection fails', async () => { + defaultChat.open.mockReturnValue(null) + defaultChat.awaitsDetection.mockReturnValue(true) + defaultChat.loadDetection.mockRejectedValue(new Error('ssh probe failed')) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + const gate = useElectronActivationGate() + + activateAndRevealWorktree(worktree.id, { ...USER_OPEN, notifyHostRuntime: false }) + await gate.mock.results[0]?.value + await flushPromises() + + expect(isEmptyWorkspaceDefaultSurfacePending(worktree.id)).toBe(false) + expect(tabCount(worktree.id)).toBe(1) + }) +}) diff --git a/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts b/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts index bb597d10e6ea..2ab11bb14522 100644 --- a/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts +++ b/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts @@ -1,14 +1,20 @@ -import type { ExecutionHostId } from '../../../shared/execution-host' import { gateWorktreeAgentActivation, type WorktreeAgentActivationOutcome } from './worktree-agent-activation-gate' -import { reseedGatedEmptyWorkspace } from './worktree-initial-terminal-seeding' - -type GatedEmptyWorkspaceReseedIntent = { - callerProvidesSurface: boolean - executionHostId?: ExecutionHostId -} +import { + reseedGatedEmptyWorkspace, + type GatedEmptyWorkspaceReseedIntent +} from './worktree-initial-terminal-seeding' +import { + emptyWorkspaceDefaultChatAwaitsDetection, + loadEmptyWorkspaceDefaultChatDetection +} from './empty-workspace-default-agent-chat' +import { + claimEmptyWorkspaceDefaultSurface, + isEmptyWorkspaceDefaultSurfacePending, + releaseEmptyWorkspaceDefaultSurface +} from './empty-workspace-default-surface-claims' const latestReseedIntentByGate = new WeakMap< Promise, @@ -17,22 +23,36 @@ const latestReseedIntentByGate = new WeakMap< export function gateAndReseedEmptyWorkspace( workspaceKey: string, - callerProvidesSurface: boolean, - executionHostId?: ExecutionHostId + intent: GatedEmptyWorkspaceReseedIntent ): void { const gate = gateWorktreeAgentActivation(workspaceKey) - const intent: GatedEmptyWorkspaceReseedIntent = { - callerProvidesSurface, - ...(executionHostId ? { executionHostId } : {}) - } latestReseedIntentByGate.set(gate, intent) void gate.then((outcome) => { if (latestReseedIntentByGate.get(gate) !== intent) { return } latestReseedIntentByGate.delete(gate) - if (outcome === 'empty') { - reseedGatedEmptyWorkspace(workspaceKey, intent.callerProvidesSurface, intent.executionHostId) + if (outcome !== 'empty') { + return + } + const awaitsDetection = + intent.seedUserDefaultSurface && emptyWorkspaceDefaultChatAwaitsDetection(workspaceKey) + if (!awaitsDetection && !isEmptyWorkspaceDefaultSurfacePending(workspaceKey)) { + reseedGatedEmptyWorkspace(workspaceKey, intent) + return + } + // Why: the default agent depends on the host's list; seeding before it loads locks in a shell. + // A wait already pending takes this later intent instead, so the latest activation wins. + if (!claimEmptyWorkspaceDefaultSurface(workspaceKey, intent)) { + return + } + const settle = (): void => { + const latestIntent = releaseEmptyWorkspaceDefaultSurface(workspaceKey) + // Re-checks the active workspace, host, and emptiness the wait may have changed. + if (latestIntent) { + reseedGatedEmptyWorkspace(workspaceKey, latestIntent) + } } + void loadEmptyWorkspaceDefaultChatDetection(workspaceKey).then(settle, settle) }) } diff --git a/src/renderer/src/lib/worktree-activation-nav-registration.ts b/src/renderer/src/lib/worktree-activation-nav-registration.ts index 11a0af533292..46ab7f30c632 100644 --- a/src/renderer/src/lib/worktree-activation-nav-registration.ts +++ b/src/renderer/src/lib/worktree-activation-nav-registration.ts @@ -4,13 +4,14 @@ import { } from '@/store/slices/worktree-nav-history' import type { WorktreeNavHistoryViewEntry } from '@/store/slices/worktree-nav-history' -type ActivateFn = (worktreeId: string) => unknown +type ActivateFn = (worktreeId: string, opts: { navigationIntent: 'user-open' }) => unknown type ViewActivateFn = (entry: WorktreeNavHistoryViewEntry) => void export function registerWorktreeActivation( activate: ActivateFn, activateView: ViewActivateFn ): void { - setWorktreeNavActivator(activate) + // Why: back/forward is the user reopening a workspace they chose, like a sidebar click. + setWorktreeNavActivator((worktreeId) => activate(worktreeId, { navigationIntent: 'user-open' })) setWorktreeNavViewActivator(activateView) } diff --git a/src/renderer/src/lib/worktree-activation-store-contract.ts b/src/renderer/src/lib/worktree-activation-store-contract.ts index 3608c9def1c1..66de89e85e35 100644 --- a/src/renderer/src/lib/worktree-activation-store-contract.ts +++ b/src/renderer/src/lib/worktree-activation-store-contract.ts @@ -77,4 +77,7 @@ export type InitialTerminalOptions = { * Setup/issue work still runs, but work that needs no host terminal must not seed a shell * beside the chat the caller is about to create. */ callerProvidesSurface?: boolean + /** The user deliberately opened this workspace with no surface choice, so it may open their + * default agent chat instead of a bare shell. */ + seedUserDefaultSurface?: boolean } diff --git a/src/renderer/src/lib/worktree-activation-surface-selection.ts b/src/renderer/src/lib/worktree-activation-surface-selection.ts index 4385994ff94d..9b78a23cd09a 100644 --- a/src/renderer/src/lib/worktree-activation-surface-selection.ts +++ b/src/renderer/src/lib/worktree-activation-surface-selection.ts @@ -13,6 +13,8 @@ export type WorktreeActivationSurfaceSelection = { agent?: TuiAgent | null /** A navigation caller is about to open its own editor, diff, or other non-terminal surface. */ providesInitialSurface?: boolean + /** Set only where the user deliberately opened this existing workspace; absent keeps the shell seed. */ + navigationIntent?: 'user-open' } export type WorktreeActivationOptions = WorktreeActivationSurfaceSelection & { @@ -38,3 +40,14 @@ export function activationProvidesInitialSurface( ): boolean { return selection?.providesInitialSurface === true || selection?.agent != null } + +/** A deliberate user open with no surface choice: an empty workspace gets the user's default surface. */ +export function activationSeedsUserDefaultSurface( + selection?: WorktreeActivationSurfaceSelection +): boolean { + return ( + selection?.navigationIntent === 'user-open' && + selection.agent === undefined && + selection.providesInitialSurface !== true + ) +} diff --git a/src/renderer/src/lib/worktree-activation.ts b/src/renderer/src/lib/worktree-activation.ts index f2e2ac8f85a9..f63b1189097d 100644 --- a/src/renderer/src/lib/worktree-activation.ts +++ b/src/renderer/src/lib/worktree-activation.ts @@ -28,6 +28,7 @@ import { ensureWebRuntimeWorktreeTerminalAfterWake } from '@/lib/web-runtime-wor import { applyWorktreeNavViewEntry } from '@/lib/worktree-nav-view-history-replay' import { activationProvidesInitialSurface, + activationSeedsUserDefaultSurface, type WorktreeActivationOptions, type WorktreeActivationSurfaceSelection } from './worktree-activation-surface-selection' @@ -47,7 +48,8 @@ export type ActivateAndRevealResult = { function ensureFolderWorkspaceInitialTerminal( folderWorkspace: FolderWorkspace, startup?: WorktreeStartupPayload, - providesInitialSurface?: boolean + providesInitialSurface?: boolean, + seedUserDefaultSurface?: boolean ): string | null { if (providesInitialSurface === true && startup === undefined) { return null @@ -61,7 +63,10 @@ function ensureFolderWorkspaceInitialTerminal( undefined, undefined, undefined, - { reseedEmptiedWorkspace: providesInitialSurface !== true } + { + reseedEmptiedWorkspace: providesInitialSurface !== true, + ...(seedUserDefaultSurface ? { seedUserDefaultSurface: true } : {}) + } ) return primaryTabId } @@ -128,6 +133,7 @@ export function activateAndRevealFolderWorkspace( const workspaceKey = folderWorkspaceKey(folderWorkspaceId) const providesInitialSurface = activationProvidesInitialSurface(opts) + const seedUserDefaultSurface = activationSeedsUserDefaultSurface(opts) state.markWorktreeVisited(workspaceKey) if (!state.isNavigatingHistory) { state.recordWorktreeVisit(workspaceKey) @@ -144,15 +150,20 @@ export function activateAndRevealFolderWorkspace( resumeSleepingAgentSessionsForWorktree(workspaceKey) } if (shouldGateAgentActivation) { - gateAndReseedEmptyWorkspace( - workspaceKey, - opts?.providesInitialSurface === true, - opts?.executionHostId - ) + gateAndReseedEmptyWorkspace(workspaceKey, { + callerProvidesSurface: opts?.providesInitialSurface === true, + seedUserDefaultSurface, + ...(opts?.executionHostId ? { executionHostId: opts.executionHostId } : {}) + }) } const primaryTabId = shouldGateAgentActivation ? null - : ensureFolderWorkspaceInitialTerminal(folderWorkspace, opts?.startup, providesInitialSurface) + : ensureFolderWorkspaceInitialTerminal( + folderWorkspace, + opts?.startup, + providesInitialSurface, + seedUserDefaultSurface + ) if (opts?.revealInSidebar !== false) { state.revealWorktreeInSidebar( @@ -185,6 +196,7 @@ export function activateAndRevealWorktree( opts?.startup || opts?.setup || opts?.defaultTabs || opts?.issueCommand ) const providesInitialSurface = activationProvidesInitialSurface(opts) + const seedUserDefaultSurface = activationSeedsUserDefaultSurface(opts) // Why: a plain reselect should still reveal the sidebar row but must not restamp focus recency or wake persistence. const isPlainAlreadyActiveTerminal = !hasActivationWork && @@ -243,11 +255,11 @@ export function activateAndRevealWorktree( resumeSleepingAgentSessionsForWorktree(worktreeId) } if (shouldGateAgentActivation) { - gateAndReseedEmptyWorkspace( - worktreeId, - opts?.providesInitialSurface === true, - opts?.executionHostId - ) + gateAndReseedEmptyWorkspace(worktreeId, { + callerProvidesSurface: opts?.providesInitialSurface === true, + seedUserDefaultSurface, + ...(opts?.executionHostId ? { executionHostId: opts.executionHostId } : {}) + }) } // 4. Ensure a focusable surface exists for externally-created worktrees @@ -266,6 +278,7 @@ export function activateAndRevealWorktree( ...(opts?.backendStartupTerminalSpawned ? { backendStartupTerminalSpawned: true } : {}), ...(opts?.createNewTerminalForStartup ? { createNewTerminalForStartup: true } : {}), ...(providesInitialSurface ? { callerProvidesSurface: true } : {}), + ...(seedUserDefaultSurface ? { seedUserDefaultSurface: true } : {}), reseedEmptiedWorkspace: !providesInitialSurface } ) diff --git a/src/renderer/src/lib/worktree-initial-terminal-seeding.ts b/src/renderer/src/lib/worktree-initial-terminal-seeding.ts index b0a6296b30e8..feb01ef0b9b5 100644 --- a/src/renderer/src/lib/worktree-initial-terminal-seeding.ts +++ b/src/renderer/src/lib/worktree-initial-terminal-seeding.ts @@ -29,6 +29,8 @@ import { type IssueCommandLaunch } from '@/lib/worktree-setup-issue-command-queue' import { applyDefaultTerminalTabs } from '@/lib/worktree-default-terminal-tabs' +import { openDefaultAgentChatInEmptyWorkspace } from '@/lib/empty-workspace-default-agent-chat' +import { isEmptyWorkspaceDefaultSurfacePending } from '@/lib/empty-workspace-default-surface-claims' function getSetupRunnerCommandPlatformForLaunch(setup: WorktreeSetupLaunch): 'windows' | 'posix' { return getSetupRunnerCommandPlatformForPath( @@ -37,15 +39,22 @@ function getSetupRunnerCommandPlatformForLaunch(setup: WorktreeSetupLaunch): 'wi ) } +export type GatedEmptyWorkspaceReseedIntent = { + callerProvidesSurface: boolean + seedUserDefaultSurface: boolean + executionHostId?: ExecutionHostId +} + /** Re-seed after an empty gate unless its activation owns the surface or no longer owns the host. */ export function reseedGatedEmptyWorkspace( workspaceKey: string, - callerProvidesSurface: boolean, - executionHostId?: ExecutionHostId + intent: GatedEmptyWorkspaceReseedIntent ): void { + const { callerProvidesSurface, seedUserDefaultSurface, executionHostId } = intent const state = useAppStore.getState() if ( callerProvidesSurface === true || + isEmptyWorkspaceDefaultSurfacePending(workspaceKey) || state.activeWorktreeId !== workspaceKey || (executionHostId !== undefined && state.activeWorkspaceExecutionHostId !== executionHostId) ) { @@ -59,7 +68,8 @@ export function reseedGatedEmptyWorkspace( undefined, undefined, { - reseedEmptiedWorkspace: true + reseedEmptiedWorkspace: true, + ...(seedUserDefaultSurface ? { seedUserDefaultSurface: true } : {}) } ) } @@ -216,6 +226,16 @@ export function ensureWorktreeHasInitialTerminal( if (templatedTabId) { return templatedTabId } + if ( + opts?.seedUserDefaultSurface === true && + !hasExplicitLaunchWork && + opts.activateCreatedTabs !== false + ) { + const defaultChat = openDefaultAgentChatInEmptyWorkspace(worktreeId) + if (defaultChat) { + return defaultChat.primaryTabId + } + } // Why: tag this activation-created tab so its PTY spawn doesn't count as activity and reshuffle the Recent sort. // Why: stamp the seeded agent before hooks arrive so native chat and provider chrome can resolve it immediately. diff --git a/src/renderer/src/lib/worktree-jump-navigation.test.ts b/src/renderer/src/lib/worktree-jump-navigation.test.ts index 4c76316556c9..af8072ac9c46 100644 --- a/src/renderer/src/lib/worktree-jump-navigation.test.ts +++ b/src/renderer/src/lib/worktree-jump-navigation.test.ts @@ -57,7 +57,9 @@ describe('worktree jump navigation', () => { expect(mocks.worktreePassesSidebarFilters).not.toHaveBeenCalled() expect(mocks.warning).not.toHaveBeenCalled() - expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('repo::/deleted', {}) + expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('repo::/deleted', { + navigationIntent: 'user-open' + }) }) it('switches the left sidebar to Spaces and warns when filters hide the target', () => { @@ -67,6 +69,7 @@ describe('worktree jump navigation', () => { expect(state.setSidebarBody).toHaveBeenCalledWith('workspaces') expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('repo::/target', { + navigationIntent: 'user-open', revealInSidebar: false, clearSidebarFilters: false }) @@ -98,7 +101,9 @@ describe('worktree jump navigation', () => { expect(jumpToWorktreeFromSidebar('wt-collapsed')).toBe(true) - expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('wt-collapsed', {}) + expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('wt-collapsed', { + navigationIntent: 'user-open' + }) expect(mocks.warning).not.toHaveBeenCalled() }) @@ -121,6 +126,7 @@ describe('worktree jump navigation', () => { expect(jumpToWorktreeFromSidebar('repo::/target', { executionHostId: 'ssh:beta' })).toBe(true) expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('repo::/target', { + navigationIntent: 'user-open', revealInSidebar: false, clearSidebarFilters: false, executionHostId: 'ssh:beta' @@ -134,6 +140,7 @@ describe('worktree jump navigation', () => { expect(jumpToWorktreeFromSidebar('folder:folder-1', { executionHostId: 'local' })).toBe(true) expect(mocks.activateAndRevealWorkspace).toHaveBeenCalledWith('folder:folder-1', { + navigationIntent: 'user-open', executionHostId: 'local' }) // Folder workspaces never get the filter-hidden treatment. diff --git a/src/renderer/src/lib/worktree-jump-navigation.ts b/src/renderer/src/lib/worktree-jump-navigation.ts index bfc0d6dd9364..38721b3337bc 100644 --- a/src/renderer/src/lib/worktree-jump-navigation.ts +++ b/src/renderer/src/lib/worktree-jump-navigation.ts @@ -60,6 +60,7 @@ export function jumpToWorktreeFromSidebar( // Why the workspace dispatcher: it owns the folder-vs-worktree split and the folder path-status gate. const activated = activateAndRevealWorkspace(worktreeId, { + navigationIntent: 'user-open', ...(hiddenBeforeActivation ? { revealInSidebar: false, clearSidebarFilters: false } : {}), ...(options?.executionHostId ? { executionHostId: options.executionHostId } : {}) })