From f3ef62dcac00050cf01a1a7889e2c5277869a32d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:27:05 -0700 Subject: [PATCH 1/3] fix(native-chat): an empty workspace opens the default agent as a chat when chat is the default view With "open agent tabs in chat" on, clicking a workspace with no tabs still seeded a bare shell. The seeding path now opens the user's default agent through the shared launch funnel when that launch routes to a chat, and keeps the shell otherwise. A Blank Terminal pick at create time is now passed to activation as agent: null so it still gets a shell. --- .../editor/CheckRunDetailsPanel.copy.test.tsx | 1 + .../components/editor/IpynbRendering.test.tsx | 5 +- ...nPreview.link-routing.interaction.test.tsx | 5 +- ...rkdownPreview.toc-visibility-gate.test.tsx | 5 +- ...rktreeContextMenu.delete-shortcut.test.tsx | 1 + ...rtsStatusSegment.render-stability.test.tsx | 1 + .../ResourceUsageStatusSegment.rows.test.tsx | 1 + ...agent-launch-caller-profile-census.test.ts | 3 +- ...ent-launch-caller-profiles-test-harness.ts | 15 + ...agent-launch-routing-caller-census.test.ts | 1 + ...empty-workspace-default-agent-chat.test.ts | 79 +++++ .../lib/empty-workspace-default-agent-chat.ts | 53 ++++ .../src/lib/launch-agent-in-new-tab.ts | 4 + ...tree-activation-default-agent-chat.test.ts | 113 +++++++ .../worktree-activation-gated-empty-reseed.ts | 20 +- .../lib/worktree-activation-store-contract.ts | 3 + .../worktree-activation-surface-selection.ts | 9 +- src/renderer/src/lib/worktree-activation.ts | 39 ++- .../src/lib/worktree-creation-flow-execute.ts | 3 +- ...orktree-creation-flow-launch-draft.test.ts | 298 ++++++++++++++++++ .../src/lib/worktree-creation-flow.test.ts | 162 +--------- .../lib/worktree-initial-terminal-seeding.ts | 24 +- 22 files changed, 648 insertions(+), 197 deletions(-) create mode 100644 src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts create mode 100644 src/renderer/src/lib/empty-workspace-default-agent-chat.ts create mode 100644 src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts create mode 100644 src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts 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/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/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/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..3fc83f372dba --- /dev/null +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts @@ -0,0 +1,79 @@ +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 { openDefaultAgentChatInEmptyWorkspace } from './empty-workspace-default-agent-chat' + +const mocks = vi.hoisted(() => ({ + launchAgentInNewTab: vi.fn(), + planAgentSessionLaunch: vi.fn() +})) + +vi.mock('@/lib/launch-agent-in-new-tab', () => ({ + launchAgentInNewTab: mocks.launchAgentInNewTab +})) +vi.mock('@/lib/agent-session-launch-plan', () => ({ + planAgentSessionLaunch: mocks.planAgentSessionLaunch +})) +vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) + +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.planAgentSessionLaunch.mockReturnValue({ route: 'structured-native-chat' }) + mocks.launchAgentInNewTab.mockReturnValue({ + surface: { kind: 'local-agent-session', tabId: 'chat-tab', sessionId: 's-1' } + }) +}) + +afterEach(() => { + 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() + }) +}) 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..ef269f3727c0 --- /dev/null +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.ts @@ -0,0 +1,53 @@ +import { agentTabsDefaultToNativeChat } from '../../../shared/structured-native-chat-launch-route' +import { pickTuiAgent } from '../../../shared/tui-agent-selection' +import { useAppStore } from '@/store' +import { getConnectionId } from '@/lib/connection-context' +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' + +/** + * 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() + if (!agentTabsDefaultToNativeChat(state.settings)) { + return null + } + const connectionId = getConnectionId(worktreeId) + const detectedAgentIds = + typeof connectionId === 'string' + ? state.remoteDetectedAgentIds[connectionId] + : state.detectedAgentIds + // Why: a 'blank' default means the user wants workspaces to open without an agent. + const agent = pickTuiAgent( + state.settings?.defaultTuiAgent, + detectedAgentIds ?? [], + 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/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/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..bdda68c792eb --- /dev/null +++ b/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts @@ -0,0 +1,113 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { activateAndRevealWorktree } from './worktree-activation' +import { ensureWorktreeHasInitialTerminal } from './worktree-initial-terminal-seeding' +import { + makeCreatedAgentWorktree as makeWorktree, + seedEmptyActivatableWorktree +} from '@/lib/worktree-activation-created-agent-test-state' +import { + createMockStore, + registerWorktreeActivationReset +} from './worktree-activation-test-harness' + +const openDefaultChat = vi.hoisted(() => vi.fn()) + +vi.mock('@/lib/empty-workspace-default-agent-chat', () => ({ + openDefaultAgentChatInEmptyWorkspace: openDefaultChat +})) + +const initialAppStoreState = useAppStore.getState() + +registerWorktreeActivationReset() + +beforeEach(() => { + openDefaultChat.mockReset() +}) + +afterEach(() => { + vi.restoreAllMocks() + useAppStore.setState(initialAppStoreState, true) +}) + +// 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', () => { + openDefaultChat.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(openDefaultChat).toHaveBeenCalledWith('wt-1') + expect(primaryTabId).toBe('chat-tab') + expect(createTab).not.toHaveBeenCalled() + }) + + it('falls back to a shell when no chat can open', () => { + openDefaultChat.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(openDefaultChat).not.toHaveBeenCalled() + }) + + it('plain navigation to an empty workspace asks for the default surface', () => { + openDefaultChat.mockReturnValue({ primaryTabId: null }) + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + + activateAndRevealWorktree(worktree.id, { notifyHostRuntime: false }) + + expect(openDefaultChat).toHaveBeenCalledWith(worktree.id) + }) + + it('a Blank Terminal pick or a target directory keeps the shell', () => { + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + + activateAndRevealWorktree(worktree.id, { agent: null, notifyHostRuntime: false }) + expect(openDefaultChat).not.toHaveBeenCalled() + + useAppStore.setState(initialAppStoreState, true) + seedEmptyActivatableWorktree(worktree) + activateAndRevealWorktree(worktree.id, { + initialCwd: `${worktree.path}/packages/app`, + notifyHostRuntime: false + }) + expect(openDefaultChat).not.toHaveBeenCalled() + expect(useAppStore.getState().tabsByWorktree[worktree.id]).toHaveLength(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..d1d7833a957d 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,11 @@ -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' const latestReseedIntentByGate = new WeakMap< Promise, @@ -17,14 +14,9 @@ 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) { @@ -32,7 +24,7 @@ export function gateAndReseedEmptyWorkspace( } latestReseedIntentByGate.delete(gate) if (outcome === 'empty') { - reseedGatedEmptyWorkspace(workspaceKey, intent.callerProvidesSurface, intent.executionHostId) + reseedGatedEmptyWorkspace(workspaceKey, intent) } }) } diff --git a/src/renderer/src/lib/worktree-activation-store-contract.ts b/src/renderer/src/lib/worktree-activation-store-contract.ts index 3608c9def1c1..995e8ffb7af8 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 + /** Nothing chose this workspace's first surface (plain navigation, not a Blank Terminal pick or a + * target directory), so it may open the user's 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..e1f1f9687891 100644 --- a/src/renderer/src/lib/worktree-activation-surface-selection.ts +++ b/src/renderer/src/lib/worktree-activation-surface-selection.ts @@ -9,7 +9,7 @@ import type { WorktreeStartupPayload } from '@/lib/worktree-startup-payload' import type { IssueCommandLaunch } from '@/lib/worktree-setup-issue-command-queue' export type WorktreeActivationSurfaceSelection = { - /** The create picker's selection; null means Blank Terminal. */ + /** The create picker's selection; null means Blank Terminal, absent means no pick was made. */ agent?: TuiAgent | null /** A navigation caller is about to open its own editor, diff, or other non-terminal surface. */ providesInitialSurface?: boolean @@ -38,3 +38,10 @@ export function activationProvidesInitialSurface( ): boolean { return selection?.providesInitialSurface === true || selection?.agent != null } + +/** No pick and no caller-owned surface: an empty workspace gets the user's default surface. */ +export function activationSeedsUserDefaultSurface( + selection?: WorktreeActivationSurfaceSelection +): boolean { + return 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..f63ec1e112f2 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) && !opts?.initialCwd // 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-creation-flow-execute.ts b/src/renderer/src/lib/worktree-creation-flow-execute.ts index a47d7def194b..8ebe67ecf0ad 100644 --- a/src/renderer/src/lib/worktree-creation-flow-execute.ts +++ b/src/renderer/src/lib/worktree-creation-flow-execute.ts @@ -176,7 +176,8 @@ export async function executeWorktreeCreation( try { activation = activateAndRevealWorktree(worktree.id, { sidebarRevealBehavior: 'auto', - ...(preparedRequest.agent !== null ? { agent: preparedRequest.agent } : {}), + // Why: pass a Blank Terminal pick (null) through so the workspace opens a shell, not the default chat. + agent: preparedRequest.agent, ...(result.setup ? { setup: result.setup } : {}), ...(result.defaultTabs ? { defaultTabs: result.defaultTabs } : {}), ...(startupOpt ? { startup: startupOpt } : {}), diff --git a/src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts b/src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts new file mode 100644 index 000000000000..5bb3997335ba --- /dev/null +++ b/src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts @@ -0,0 +1,298 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { + PendingWorktreeCreation, + WorktreeCreationRequest +} from '@/lib/pending-worktree-creation' + +const { prepareEphemeralVmWorkspaceTargetMock } = vi.hoisted(() => ({ + prepareEphemeralVmWorkspaceTargetMock: vi.fn() +})) + +type TestActiveView = 'terminal' | 'tasks' + +const store = { + settings: { + activeRuntimeEnvironmentId: null as string | null, + experimentalNativeChat: undefined as boolean | undefined, + openAgentTabsInChatByDefault: undefined as boolean | undefined + }, + activeView: 'terminal' as TestActiveView, + activePendingCreationId: 'creation-1' as string | null, + repos: [{ id: 'repo-runtime', connectionId: null }], + pendingWorktreeCreations: {} as Record, + beginPendingWorktreeCreation: vi.fn((entry: PendingWorktreeCreation) => { + store.pendingWorktreeCreations[entry.creationId] = entry + store.activePendingCreationId = entry.creationId + }), + updatePendingWorktreeCreation: vi.fn( + (creationId: string, patch: Partial) => { + const entry = store.pendingWorktreeCreations[creationId] + if (entry) { + store.pendingWorktreeCreations[creationId] = { ...entry, ...patch } + } + } + ), + removePendingWorktreeCreation: vi.fn((creationId: string) => { + delete store.pendingWorktreeCreations[creationId] + }), + updateWorktreeMeta: vi.fn(), + setActivePendingWorktreeCreation: vi.fn(), + setActiveView: vi.fn(), + setSidebarOpen: vi.fn(), + createWorktree: vi.fn(() => new Promise(() => {})), + setupProjectExistingFolder: vi.fn(), + refreshRuntimeEnvironmentStatus: vi.fn(), + seedNativeChatLaunchDraft: vi.fn(), + setTabViewMode: vi.fn(), + tabsByWorktree: {} as Record, + unifiedTabsByWorktree: {} +} + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => store + } +})) + +vi.mock('@/lib/browser-uuid', () => ({ + createBrowserUuid: () => 'creation-1' +})) + +vi.mock('@/lib/worktree-activation', () => ({ + activateAndRevealWorktree: vi.fn(() => false) +})) + +vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ + ensureWorktreeHasInitialTerminal: vi.fn() +})) + +vi.mock('@/lib/workspace-activation-terminal-focus', () => ({ + queueWorkspaceActivationTerminalFocus: vi.fn() +})) + +vi.mock('@/lib/new-workspace', () => ({ + ensureAgentStartupInTerminal: vi.fn() +})) + +vi.mock('sonner', () => ({ + toast: { + error: vi.fn() + } +})) + +vi.mock('@/lib/ephemeral-vm-workspace-target', () => ({ + prepareEphemeralVmWorkspaceTarget: prepareEphemeralVmWorkspaceTargetMock +})) + +import { activateAndRevealWorktree } from '@/lib/worktree-activation' +import { ensureWorktreeHasInitialTerminal } from '@/lib/worktree-initial-terminal-seeding' +import { continueBackgroundWorktreeCreation } from './worktree-creation-flow' + +beforeEach(() => { + vi.clearAllMocks() + store.settings.activeRuntimeEnvironmentId = null + store.settings.experimentalNativeChat = undefined + store.settings.openAgentTabsInChatByDefault = undefined + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.repos = [] + store.pendingWorktreeCreations = { 'creation-1': makePendingCreation(makeRequest()) } + store.createWorktree.mockImplementation(() => new Promise(() => {})) + store.tabsByWorktree = {} + store.unifiedTabsByWorktree = {} + vi.mocked(ensureWorktreeHasInitialTerminal).mockReturnValue('tab-1') +}) + +function makeRequest(overrides: Partial = {}): WorktreeCreationRequest { + return { + repoId: 'repo-1', + name: 'feature', + setupDecision: 'inherit', + agent: null, + pendingFirstAgentMessageRename: false, + note: '', + startupPlan: null, + quickPrompt: '', + quickTelemetry: null, + ...overrides + } +} + +function makePendingCreation(request: WorktreeCreationRequest): PendingWorktreeCreation { + return { + creationId: 'creation-1', + phase: 'preparing', + status: 'creating', + startedAt: 1, + indeterminate: false, + loaderVisible: true, + request + } +} + +describe('worktree creation launch draft seeding', () => { + beforeEach(() => { + vi.stubGlobal('window', { api: {} }) + }) + + it('seeds the chat-composer launch draft on completion for draft launches', async () => { + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) + + const started = continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: 'claude --prefill x', + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: 'https://github.com/o/r/issues/12' + }) + ) + + expect(started).toBe(true) + await vi.waitFor(() => + expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith({ + tabId: 'tab-1', + agent: 'claude', + text: 'https://github.com/o/r/issues/12', + createdAt: expect.any(Number) + }) + ) + }) + + it('seeds the backend-spawned agent tab, not the worktree default terminal tab', async () => { + // Repo default tabs ("dev server", "logs", …) make activation's primaryTabId + // a tab that runs no agent; main's startup terminal is the agent's own tab. + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.tabsByWorktree = { 'wt-1': [{ id: 'dev-server' }, { id: 'agent-tab' }] } + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' }, + startupTerminal: { tabId: 'agent-tab', spawned: true } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'dev-server' }) + + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: 'claude --prefill x', + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: 'https://github.com/o/r/issues/12' + }) + ) + + await vi.waitFor(() => expect(store.seedNativeChatLaunchDraft).toHaveBeenCalled()) + expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith( + expect.objectContaining({ tabId: 'agent-tab' }) + ) + const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined + expect(createCall?.[25]).toEqual({ + startupDraft: 'https://github.com/o/r/issues/12' + }) + }) + + it.each([ + ['mirrorable local Grok', 'grok', 'https://github.com/o/r/issues/12', 'chat'], + ['multi-line Claude', 'claude', 'note\nhttps://github.com/o/r/issues/12', 'chat'] + ] as const)('passes %s draft mode to backend startup', async (_label, agent, draft, viewMode) => { + store.settings.experimentalNativeChat = true + store.settings.openAgentTabsInChatByDefault = true + store.repos = [{ id: 'repo-1', connectionId: null }] + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent, + startup: { command: `${agent} --prefill x`, launchAgent: agent }, + startupPlan: { + agent, + launchCommand: `${agent} --prefill x`, + expectedProcess: agent, + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: draft + }) + ) + + await vi.waitFor(() => expect(store.createWorktree).toHaveBeenCalled()) + const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined + expect(createCall?.[16]).toEqual({ + command: `${agent} --prefill x`, + launchAgent: agent, + viewMode + }) + }) + + it('carries launchDraftText into activation for an argv-prefill launch', async () => { + // Why: the draft rides inside `launchCommand` here, so the plan sets no + // draftPrompt — without launchDraftText the initial view-mode decision + // never sees a draft and opens chat on an unmirrorable one. + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) + + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: "claude --prefill 'https://github.com/o/r/issues/12'", + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: 'https://github.com/o/r/issues/12' + }) + ) + + await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) + const startup = vi.mocked(activateAndRevealWorktree).mock.calls[0]?.[1]?.startup + expect(startup?.draftPrompt).toBeUndefined() + expect(startup?.launchDraftText).toBe('https://github.com/o/r/issues/12') + }) + + it('does not seed a launch draft without draft launch context', async () => { + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) + + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: 'claude', + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + } + }) + ) + + await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) + expect(store.seedNativeChatLaunchDraft).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/lib/worktree-creation-flow.test.ts b/src/renderer/src/lib/worktree-creation-flow.test.ts index a599a2655134..9788f26ba0d9 100644 --- a/src/renderer/src/lib/worktree-creation-flow.test.ts +++ b/src/renderer/src/lib/worktree-creation-flow.test.ts @@ -573,6 +573,7 @@ describe('staged background worktree creation', () => { expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-1', { sidebarRevealBehavior: 'auto', + agent: null, backendStartupTerminalSpawned: true }) expect(ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() @@ -675,167 +676,6 @@ describe('staged background worktree creation', () => { expect(ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() }) - it('seeds the chat-composer launch draft on completion for draft launches', async () => { - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) - - const started = continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: 'claude --prefill x', - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: 'https://github.com/o/r/issues/12' - }) - ) - - expect(started).toBe(true) - await vi.waitFor(() => - expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith({ - tabId: 'tab-1', - agent: 'claude', - text: 'https://github.com/o/r/issues/12', - createdAt: expect.any(Number) - }) - ) - }) - - it('seeds the backend-spawned agent tab, not the worktree default terminal tab', async () => { - // Repo default tabs ("dev server", "logs", …) make activation's primaryTabId - // a tab that runs no agent; main's startup terminal is the agent's own tab. - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.tabsByWorktree = { 'wt-1': [{ id: 'dev-server' }, { id: 'agent-tab' }] } - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' }, - startupTerminal: { tabId: 'agent-tab', spawned: true } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'dev-server' }) - - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: 'claude --prefill x', - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: 'https://github.com/o/r/issues/12' - }) - ) - - await vi.waitFor(() => expect(store.seedNativeChatLaunchDraft).toHaveBeenCalled()) - expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith( - expect.objectContaining({ tabId: 'agent-tab' }) - ) - const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined - expect(createCall?.[25]).toEqual({ - startupDraft: 'https://github.com/o/r/issues/12' - }) - }) - - it.each([ - ['mirrorable local Grok', 'grok', 'https://github.com/o/r/issues/12', 'chat'], - ['multi-line Claude', 'claude', 'note\nhttps://github.com/o/r/issues/12', 'chat'] - ] as const)('passes %s draft mode to backend startup', async (_label, agent, draft, viewMode) => { - store.settings.experimentalNativeChat = true - store.settings.openAgentTabsInChatByDefault = true - store.repos = [{ id: 'repo-1', connectionId: null }] - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent, - startup: { command: `${agent} --prefill x`, launchAgent: agent }, - startupPlan: { - agent, - launchCommand: `${agent} --prefill x`, - expectedProcess: agent, - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: draft - }) - ) - - await vi.waitFor(() => expect(store.createWorktree).toHaveBeenCalled()) - const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined - expect(createCall?.[16]).toEqual({ - command: `${agent} --prefill x`, - launchAgent: agent, - viewMode - }) - }) - - it('carries launchDraftText into activation for an argv-prefill launch', async () => { - // Why: the draft rides inside `launchCommand` here, so the plan sets no - // draftPrompt — without launchDraftText the initial view-mode decision - // never sees a draft and opens chat on an unmirrorable one. - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) - - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: "claude --prefill 'https://github.com/o/r/issues/12'", - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: 'https://github.com/o/r/issues/12' - }) - ) - - await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) - const startup = vi.mocked(activateAndRevealWorktree).mock.calls[0]?.[1]?.startup - expect(startup?.draftPrompt).toBeUndefined() - expect(startup?.launchDraftText).toBe('https://github.com/o/r/issues/12') - }) - - it('does not seed a launch draft without draft launch context', async () => { - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) - - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: 'claude', - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - } - }) - ) - - await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) - expect(store.seedNativeChatLaunchDraft).not.toHaveBeenCalled() - }) - // Why: activation no longer rebuilds a startup from `createdWithAgent`, so this // caller's own `startup` is the only thing that launches the agent it created. it('passes its own startup to activation when the create requested an agent', async () => { diff --git a/src/renderer/src/lib/worktree-initial-terminal-seeding.ts b/src/renderer/src/lib/worktree-initial-terminal-seeding.ts index b0a6296b30e8..f9b1288f5c53 100644 --- a/src/renderer/src/lib/worktree-initial-terminal-seeding.ts +++ b/src/renderer/src/lib/worktree-initial-terminal-seeding.ts @@ -29,6 +29,7 @@ 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' function getSetupRunnerCommandPlatformForLaunch(setup: WorktreeSetupLaunch): 'windows' | 'posix' { return getSetupRunnerCommandPlatformForPath( @@ -37,12 +38,18 @@ 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 || @@ -59,7 +66,8 @@ export function reseedGatedEmptyWorkspace( undefined, undefined, { - reseedEmptiedWorkspace: true + reseedEmptiedWorkspace: true, + ...(seedUserDefaultSurface ? { seedUserDefaultSurface: true } : {}) } ) } @@ -216,6 +224,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. From d89c995a77bc62c6d704e0d5c0657f0383188ece Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 28 Sep 2026 21:58:23 -0700 Subject: [PATCH 2/3] fix(native-chat): only a deliberate workspace open starts the default agent chat Round-1 review of the empty-workspace default chat: activation treated any call with no agent and no caller surface as user navigation, so CLI/phone creates, fallbacks after a failed agent launch, fork fallbacks, and the move to a neighbour after a delete all opened an agent chat nobody picked. - Opt in instead: activation options gain navigationIntent: 'user-open', set only by user navigation (sidebar row, keyboard cycling, Cmd+J, the workspace digit shortcut, back/forward, open-parent, jump-to-workspace, and the open-attached-workspace / space-manager actions). Every other activation keeps today's shell, so the Blank Terminal pass-through in the create flow is no longer needed and is reverted. - The Electron gated reseed now waits (bounded, 5 s) for the workspace host's agent list when it has not loaded, holding a per-workspace claim that the passive seed and other reseeds respect, then re-checks the active workspace, host, and emptiness. Host resolution reuses the detection target key, so an unresolved owner stays unknown. - Tests cover the gated path for worktrees and folders, non-opted activations, history navigation, the detection wait and its failure, and the passive seed deferring to the claim. --- .../components/WorktreeJumpPalette.test.tsx | 3 + .../activity/activity-thread-actions.test.ts | 1 + .../open-dialog/github-item-dialog.tsx | 4 +- .../pull-request-page/page/surface.tsx | 4 +- .../sleep-worktree-activation-race.test.ts | 2 + .../use-worktree-context-menu-commands.ts | 2 +- .../navigation/use-keyboard.focus.test.tsx | 5 +- .../use-keyboard.host-identity.test.tsx | 6 +- .../worktree-list/navigation/use-keyboard.ts | 8 +- ...pace-space-manager-source-boundary.test.ts | 2 +- .../workspace-space-manager-table.tsx | 6 +- ...k-page-workspace-composer-boundary.test.ts | 2 +- ...nitial-terminal-structured-launch.test.tsx | 17 + .../use-task-page-workspace-actions.ts | 4 +- .../use-terminal-watcher-effects.ts | 4 +- ...worktree-jump-palette-selection-actions.ts | 8 +- .../workspace-shortcut-ipc-bridge.ts | 9 +- .../useIpcEvents-cmd-j-digit-chord.test.ts | 5 +- ...empty-workspace-default-agent-chat.test.ts | 72 ++++- .../lib/empty-workspace-default-agent-chat.ts | 70 +++- .../empty-workspace-default-surface-claims.ts | 20 ++ .../lib/linear-issue-workspace-open.test.ts | 2 + .../src/lib/linear-issue-workspace-open.ts | 16 +- .../lib/sidebar-worktree-activation.test.ts | 7 +- .../src/lib/sidebar-worktree-activation.ts | 12 +- ...tree-activation-default-agent-chat.test.ts | 234 ++++++++++++-- .../worktree-activation-gated-empty-reseed.ts | 24 +- .../worktree-activation-nav-registration.ts | 5 +- .../lib/worktree-activation-store-contract.ts | 4 +- .../worktree-activation-surface-selection.ts | 12 +- src/renderer/src/lib/worktree-activation.ts | 2 +- .../src/lib/worktree-creation-flow-execute.ts | 3 +- ...orktree-creation-flow-launch-draft.test.ts | 298 ------------------ .../src/lib/worktree-creation-flow.test.ts | 162 +++++++++- .../lib/worktree-initial-terminal-seeding.ts | 2 + .../src/lib/worktree-jump-navigation.test.ts | 11 +- .../src/lib/worktree-jump-navigation.ts | 1 + 37 files changed, 664 insertions(+), 385 deletions(-) create mode 100644 src/renderer/src/lib/empty-workspace-default-surface-claims.ts delete mode 100644 src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts 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/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/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/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..f03c1f1988c9 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 = {} @@ -202,6 +206,19 @@ 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') + try { + await finishGate('empty') + expect(mocks.createTab).not.toHaveBeenCalled() + } finally { + releaseEmptyWorkspaceDefaultSurface('wt-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..d5a2c768e503 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' @@ -229,8 +230,9 @@ export function useTerminalWatcherEffects(controller: TerminalWatcherController) if (outcome !== 'empty') { return } - // A pending or unanswered chat create owns the surface even before its tab is published. + // A reseed awaiting agent detection, or a pending chat create, owns the surface already. if ( + isEmptyWorkspaceDefaultSurfacePending(activeWorktreeId) || AGENT_SESSION_PROVIDER_HANDLE_PROVIDERS.some( (agent) => getStructuredAgentLaunchStatus(activeWorktreeId, agent) !== 'idle' ) 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/empty-workspace-default-agent-chat.test.ts b/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts index 3fc83f372dba..7b3545375c20 100644 --- a/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts @@ -2,11 +2,16 @@ 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 { openDefaultAgentChatInEmptyWorkspace } from './empty-workspace-default-agent-chat' +import { + emptyWorkspaceDefaultChatAwaitsDetection, + loadEmptyWorkspaceDefaultChatDetection, + openDefaultAgentChatInEmptyWorkspace +} from './empty-workspace-default-agent-chat' const mocks = vi.hoisted(() => ({ launchAgentInNewTab: vi.fn(), - planAgentSessionLaunch: vi.fn() + planAgentSessionLaunch: vi.fn(), + detectionTargetKey: vi.fn<() => string | undefined>() })) vi.mock('@/lib/launch-agent-in-new-tab', () => ({ @@ -15,7 +20,10 @@ vi.mock('@/lib/launch-agent-in-new-tab', () => ({ vi.mock('@/lib/agent-session-launch-plan', () => ({ planAgentSessionLaunch: mocks.planAgentSessionLaunch })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) +vi.mock('@/hooks/useAgentDetectionTarget', async (importOriginal) => ({ + ...(await importOriginal>()), + getAgentDetectionTargetKeyForWorktree: mocks.detectionTargetKey +})) const initialAppStoreState = useAppStore.getState() @@ -34,6 +42,7 @@ function seedSettings(settings: Partial): void { } 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' } @@ -41,6 +50,7 @@ beforeEach(() => { }) afterEach(() => { + vi.useRealTimers() vi.clearAllMocks() useAppStore.setState(initialAppStoreState, true) }) @@ -76,4 +86,60 @@ describe('openDefaultAgentChatInEmptyWorkspace', () => { 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) + }) + + 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 index ef269f3727c0..9d2b29c8e418 100644 --- a/src/renderer/src/lib/empty-workspace-default-agent-chat.ts +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.ts @@ -1,11 +1,67 @@ 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 { getConnectionId } from '@/lib/connection-context' +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 + +function defaultChatDetectionTarget( + state: AppState, + worktreeId: string +): AgentDetectionTarget | undefined { + 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() + if (!agentTabsDefaultToNativeChat(state.settings)) { + return false + } + 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. @@ -17,15 +73,15 @@ export function openDefaultAgentChatInEmptyWorkspace( if (!agentTabsDefaultToNativeChat(state.settings)) { return null } - const connectionId = getConnectionId(worktreeId) - const detectedAgentIds = - typeof connectionId === 'string' - ? state.remoteDetectedAgentIds[connectionId] - : state.detectedAgentIds + // Why: an unresolved owner is an unknown host, not the local machine. + const target = defaultChatDetectionTarget(state, worktreeId) + if (!target) { + return null + } // Why: a 'blank' default means the user wants workspaces to open without an agent. const agent = pickTuiAgent( state.settings?.defaultTuiAgent, - detectedAgentIds ?? [], + readDetectedAgents(state, target) ?? [], state.settings?.disabledTuiAgents ) if (!agent) { 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..d66a9b17b4f3 --- /dev/null +++ b/src/renderer/src/lib/empty-workspace-default-surface-claims.ts @@ -0,0 +1,20 @@ +// 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. +const workspacesAwaitingDefaultSurface = new Set() + +/** False when another reseed already owns this workspace's default surface. */ +export function claimEmptyWorkspaceDefaultSurface(workspaceKey: string): boolean { + if (workspacesAwaitingDefaultSurface.has(workspaceKey)) { + return false + } + workspacesAwaitingDefaultSurface.add(workspaceKey) + return true +} + +export function releaseEmptyWorkspaceDefaultSurface(workspaceKey: string): void { + workspacesAwaitingDefaultSurface.delete(workspaceKey) +} + +export function isEmptyWorkspaceDefaultSurfacePending(workspaceKey: string): boolean { + return workspacesAwaitingDefaultSurface.has(workspaceKey) +} 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 index bdda68c792eb..bdd61a3a0825 100644 --- a/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts +++ b/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts @@ -1,7 +1,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' -import { activateAndRevealWorktree } from './worktree-activation' -import { ensureWorktreeHasInitialTerminal } from './worktree-initial-terminal-seeding' +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 @@ -11,30 +20,86 @@ import { registerWorktreeActivationReset } from './worktree-activation-test-harness' -const openDefaultChat = vi.hoisted(() => vi.fn()) +const defaultChat = vi.hoisted(() => ({ + open: vi.fn(), + awaitsDetection: vi.fn(), + loadDetection: vi.fn() +})) vi.mock('@/lib/empty-workspace-default-agent-chat', () => ({ - openDefaultAgentChatInEmptyWorkspace: openDefaultChat + 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(() => { - openDefaultChat.mockReset() + 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', () => { - openDefaultChat.mockReturnValue({ primaryTabId: 'chat-tab' }) + defaultChat.open.mockReturnValue({ primaryTabId: 'chat-tab' }) const createTab = vi.fn(() => ({ id: 'shell-tab' })) const store = createMockStore({ createTab }) @@ -48,13 +113,13 @@ describe('empty workspace seeding with a default agent chat', () => { { seedUserDefaultSurface: true } ) - expect(openDefaultChat).toHaveBeenCalledWith('wt-1') + 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', () => { - openDefaultChat.mockReturnValue(null) + defaultChat.open.mockReturnValue(null) const createTab = vi.fn(() => ({ id: 'shell-tab' })) const store = createMockStore({ createTab }) @@ -81,33 +146,160 @@ describe('empty workspace seeding with a default agent chat', () => { activateCreatedTabs: false }) - expect(openDefaultChat).not.toHaveBeenCalled() + expect(defaultChat.open).not.toHaveBeenCalled() }) - it('plain navigation to an empty workspace asks for the default surface', () => { - openDefaultChat.mockReturnValue({ primaryTabId: null }) + 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, { notifyHostRuntime: false }) + 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 + }) - expect(openDefaultChat).toHaveBeenCalledWith(worktree.id) + useAppStore.getState().goBackWorktree() + + expect(defaultChat.open).toHaveBeenCalledWith(worktree.id) }) - it('a Blank Terminal pick or a target directory keeps the shell', () => { + // 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, { agent: null, notifyHostRuntime: false }) - expect(openDefaultChat).not.toHaveBeenCalled() + activateAndRevealWorktree(worktree.id, { ...selection, notifyHostRuntime: false }) + + expect(defaultChat.open).not.toHaveBeenCalled() + expect(tabCount(worktree.id)).toBe(1) + }) +}) - useAppStore.setState(initialAppStoreState, true) +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) - activateAndRevealWorktree(worktree.id, { - initialCwd: `${worktree.path}/packages/app`, + const gate = useElectronActivationGate() + + const result = activateAndRevealWorktree(worktree.id, { + ...USER_OPEN, notifyHostRuntime: false }) - expect(openDefaultChat).not.toHaveBeenCalled() - expect(useAppStore.getState().tabsByWorktree[worktree.id]).toHaveLength(1) + 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) + }) + + 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 d1d7833a957d..bf837cdbf002 100644 --- a/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts +++ b/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts @@ -6,6 +6,14 @@ import { reseedGatedEmptyWorkspace, type GatedEmptyWorkspaceReseedIntent } from './worktree-initial-terminal-seeding' +import { + emptyWorkspaceDefaultChatAwaitsDetection, + loadEmptyWorkspaceDefaultChatDetection +} from './empty-workspace-default-agent-chat' +import { + claimEmptyWorkspaceDefaultSurface, + releaseEmptyWorkspaceDefaultSurface +} from './empty-workspace-default-surface-claims' const latestReseedIntentByGate = new WeakMap< Promise, @@ -23,8 +31,22 @@ export function gateAndReseedEmptyWorkspace( return } latestReseedIntentByGate.delete(gate) - if (outcome === 'empty') { + if (outcome !== 'empty') { + return + } + if (!intent.seedUserDefaultSurface || !emptyWorkspaceDefaultChatAwaitsDetection(workspaceKey)) { + reseedGatedEmptyWorkspace(workspaceKey, intent) + return + } + // Why: the default agent depends on the host's list; seeding before it loads locks in a shell. + if (!claimEmptyWorkspaceDefaultSurface(workspaceKey)) { + return + } + const settle = (): void => { + releaseEmptyWorkspaceDefaultSurface(workspaceKey) + // Re-checks the active workspace, host, and emptiness the wait may have changed. reseedGatedEmptyWorkspace(workspaceKey, intent) } + 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 995e8ffb7af8..66de89e85e35 100644 --- a/src/renderer/src/lib/worktree-activation-store-contract.ts +++ b/src/renderer/src/lib/worktree-activation-store-contract.ts @@ -77,7 +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 - /** Nothing chose this workspace's first surface (plain navigation, not a Blank Terminal pick or a - * target directory), so it may open the user's default agent chat instead of a bare shell. */ + /** 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 e1f1f9687891..9b78a23cd09a 100644 --- a/src/renderer/src/lib/worktree-activation-surface-selection.ts +++ b/src/renderer/src/lib/worktree-activation-surface-selection.ts @@ -9,10 +9,12 @@ import type { WorktreeStartupPayload } from '@/lib/worktree-startup-payload' import type { IssueCommandLaunch } from '@/lib/worktree-setup-issue-command-queue' export type WorktreeActivationSurfaceSelection = { - /** The create picker's selection; null means Blank Terminal, absent means no pick was made. */ + /** The create picker's selection; null means Blank Terminal. */ 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 & { @@ -39,9 +41,13 @@ export function activationProvidesInitialSurface( return selection?.providesInitialSurface === true || selection?.agent != null } -/** No pick and no caller-owned surface: an empty workspace gets the user's default surface. */ +/** 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?.agent === undefined && selection?.providesInitialSurface !== true + 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 f63ec1e112f2..f63b1189097d 100644 --- a/src/renderer/src/lib/worktree-activation.ts +++ b/src/renderer/src/lib/worktree-activation.ts @@ -196,7 +196,7 @@ export function activateAndRevealWorktree( opts?.startup || opts?.setup || opts?.defaultTabs || opts?.issueCommand ) const providesInitialSurface = activationProvidesInitialSurface(opts) - const seedUserDefaultSurface = activationSeedsUserDefaultSurface(opts) && !opts?.initialCwd + 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 && diff --git a/src/renderer/src/lib/worktree-creation-flow-execute.ts b/src/renderer/src/lib/worktree-creation-flow-execute.ts index 8ebe67ecf0ad..a47d7def194b 100644 --- a/src/renderer/src/lib/worktree-creation-flow-execute.ts +++ b/src/renderer/src/lib/worktree-creation-flow-execute.ts @@ -176,8 +176,7 @@ export async function executeWorktreeCreation( try { activation = activateAndRevealWorktree(worktree.id, { sidebarRevealBehavior: 'auto', - // Why: pass a Blank Terminal pick (null) through so the workspace opens a shell, not the default chat. - agent: preparedRequest.agent, + ...(preparedRequest.agent !== null ? { agent: preparedRequest.agent } : {}), ...(result.setup ? { setup: result.setup } : {}), ...(result.defaultTabs ? { defaultTabs: result.defaultTabs } : {}), ...(startupOpt ? { startup: startupOpt } : {}), diff --git a/src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts b/src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts deleted file mode 100644 index 5bb3997335ba..000000000000 --- a/src/renderer/src/lib/worktree-creation-flow-launch-draft.test.ts +++ /dev/null @@ -1,298 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - PendingWorktreeCreation, - WorktreeCreationRequest -} from '@/lib/pending-worktree-creation' - -const { prepareEphemeralVmWorkspaceTargetMock } = vi.hoisted(() => ({ - prepareEphemeralVmWorkspaceTargetMock: vi.fn() -})) - -type TestActiveView = 'terminal' | 'tasks' - -const store = { - settings: { - activeRuntimeEnvironmentId: null as string | null, - experimentalNativeChat: undefined as boolean | undefined, - openAgentTabsInChatByDefault: undefined as boolean | undefined - }, - activeView: 'terminal' as TestActiveView, - activePendingCreationId: 'creation-1' as string | null, - repos: [{ id: 'repo-runtime', connectionId: null }], - pendingWorktreeCreations: {} as Record, - beginPendingWorktreeCreation: vi.fn((entry: PendingWorktreeCreation) => { - store.pendingWorktreeCreations[entry.creationId] = entry - store.activePendingCreationId = entry.creationId - }), - updatePendingWorktreeCreation: vi.fn( - (creationId: string, patch: Partial) => { - const entry = store.pendingWorktreeCreations[creationId] - if (entry) { - store.pendingWorktreeCreations[creationId] = { ...entry, ...patch } - } - } - ), - removePendingWorktreeCreation: vi.fn((creationId: string) => { - delete store.pendingWorktreeCreations[creationId] - }), - updateWorktreeMeta: vi.fn(), - setActivePendingWorktreeCreation: vi.fn(), - setActiveView: vi.fn(), - setSidebarOpen: vi.fn(), - createWorktree: vi.fn(() => new Promise(() => {})), - setupProjectExistingFolder: vi.fn(), - refreshRuntimeEnvironmentStatus: vi.fn(), - seedNativeChatLaunchDraft: vi.fn(), - setTabViewMode: vi.fn(), - tabsByWorktree: {} as Record, - unifiedTabsByWorktree: {} -} - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => store - } -})) - -vi.mock('@/lib/browser-uuid', () => ({ - createBrowserUuid: () => 'creation-1' -})) - -vi.mock('@/lib/worktree-activation', () => ({ - activateAndRevealWorktree: vi.fn(() => false) -})) - -vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ - ensureWorktreeHasInitialTerminal: vi.fn() -})) - -vi.mock('@/lib/workspace-activation-terminal-focus', () => ({ - queueWorkspaceActivationTerminalFocus: vi.fn() -})) - -vi.mock('@/lib/new-workspace', () => ({ - ensureAgentStartupInTerminal: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { - error: vi.fn() - } -})) - -vi.mock('@/lib/ephemeral-vm-workspace-target', () => ({ - prepareEphemeralVmWorkspaceTarget: prepareEphemeralVmWorkspaceTargetMock -})) - -import { activateAndRevealWorktree } from '@/lib/worktree-activation' -import { ensureWorktreeHasInitialTerminal } from '@/lib/worktree-initial-terminal-seeding' -import { continueBackgroundWorktreeCreation } from './worktree-creation-flow' - -beforeEach(() => { - vi.clearAllMocks() - store.settings.activeRuntimeEnvironmentId = null - store.settings.experimentalNativeChat = undefined - store.settings.openAgentTabsInChatByDefault = undefined - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.repos = [] - store.pendingWorktreeCreations = { 'creation-1': makePendingCreation(makeRequest()) } - store.createWorktree.mockImplementation(() => new Promise(() => {})) - store.tabsByWorktree = {} - store.unifiedTabsByWorktree = {} - vi.mocked(ensureWorktreeHasInitialTerminal).mockReturnValue('tab-1') -}) - -function makeRequest(overrides: Partial = {}): WorktreeCreationRequest { - return { - repoId: 'repo-1', - name: 'feature', - setupDecision: 'inherit', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null, - ...overrides - } -} - -function makePendingCreation(request: WorktreeCreationRequest): PendingWorktreeCreation { - return { - creationId: 'creation-1', - phase: 'preparing', - status: 'creating', - startedAt: 1, - indeterminate: false, - loaderVisible: true, - request - } -} - -describe('worktree creation launch draft seeding', () => { - beforeEach(() => { - vi.stubGlobal('window', { api: {} }) - }) - - it('seeds the chat-composer launch draft on completion for draft launches', async () => { - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) - - const started = continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: 'claude --prefill x', - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: 'https://github.com/o/r/issues/12' - }) - ) - - expect(started).toBe(true) - await vi.waitFor(() => - expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith({ - tabId: 'tab-1', - agent: 'claude', - text: 'https://github.com/o/r/issues/12', - createdAt: expect.any(Number) - }) - ) - }) - - it('seeds the backend-spawned agent tab, not the worktree default terminal tab', async () => { - // Repo default tabs ("dev server", "logs", …) make activation's primaryTabId - // a tab that runs no agent; main's startup terminal is the agent's own tab. - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.tabsByWorktree = { 'wt-1': [{ id: 'dev-server' }, { id: 'agent-tab' }] } - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' }, - startupTerminal: { tabId: 'agent-tab', spawned: true } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'dev-server' }) - - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: 'claude --prefill x', - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: 'https://github.com/o/r/issues/12' - }) - ) - - await vi.waitFor(() => expect(store.seedNativeChatLaunchDraft).toHaveBeenCalled()) - expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith( - expect.objectContaining({ tabId: 'agent-tab' }) - ) - const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined - expect(createCall?.[25]).toEqual({ - startupDraft: 'https://github.com/o/r/issues/12' - }) - }) - - it.each([ - ['mirrorable local Grok', 'grok', 'https://github.com/o/r/issues/12', 'chat'], - ['multi-line Claude', 'claude', 'note\nhttps://github.com/o/r/issues/12', 'chat'] - ] as const)('passes %s draft mode to backend startup', async (_label, agent, draft, viewMode) => { - store.settings.experimentalNativeChat = true - store.settings.openAgentTabsInChatByDefault = true - store.repos = [{ id: 'repo-1', connectionId: null }] - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent, - startup: { command: `${agent} --prefill x`, launchAgent: agent }, - startupPlan: { - agent, - launchCommand: `${agent} --prefill x`, - expectedProcess: agent, - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: draft - }) - ) - - await vi.waitFor(() => expect(store.createWorktree).toHaveBeenCalled()) - const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined - expect(createCall?.[16]).toEqual({ - command: `${agent} --prefill x`, - launchAgent: agent, - viewMode - }) - }) - - it('carries launchDraftText into activation for an argv-prefill launch', async () => { - // Why: the draft rides inside `launchCommand` here, so the plan sets no - // draftPrompt — without launchDraftText the initial view-mode decision - // never sees a draft and opens chat on an unmirrorable one. - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) - - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: "claude --prefill 'https://github.com/o/r/issues/12'", - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - }, - launchDraftPrompt: 'https://github.com/o/r/issues/12' - }) - ) - - await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) - const startup = vi.mocked(activateAndRevealWorktree).mock.calls[0]?.[1]?.startup - expect(startup?.draftPrompt).toBeUndefined() - expect(startup?.launchDraftText).toBe('https://github.com/o/r/issues/12') - }) - - it('does not seed a launch draft without draft launch context', async () => { - store.activeView = 'terminal' - store.activePendingCreationId = 'creation-1' - store.createWorktree.mockResolvedValueOnce({ - worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } - }) - vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) - - continueBackgroundWorktreeCreation( - 'creation-1', - makeRequest({ - agent: 'claude', - startupPlan: { - agent: 'claude', - launchCommand: 'claude', - expectedProcess: 'claude', - followupPrompt: null, - launchConfig: { agentArgs: '', agentEnv: {} } - } - }) - ) - - await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) - expect(store.seedNativeChatLaunchDraft).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/worktree-creation-flow.test.ts b/src/renderer/src/lib/worktree-creation-flow.test.ts index 9788f26ba0d9..a599a2655134 100644 --- a/src/renderer/src/lib/worktree-creation-flow.test.ts +++ b/src/renderer/src/lib/worktree-creation-flow.test.ts @@ -573,7 +573,6 @@ describe('staged background worktree creation', () => { expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-1', { sidebarRevealBehavior: 'auto', - agent: null, backendStartupTerminalSpawned: true }) expect(ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() @@ -676,6 +675,167 @@ describe('staged background worktree creation', () => { expect(ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() }) + it('seeds the chat-composer launch draft on completion for draft launches', async () => { + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) + + const started = continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: 'claude --prefill x', + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: 'https://github.com/o/r/issues/12' + }) + ) + + expect(started).toBe(true) + await vi.waitFor(() => + expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith({ + tabId: 'tab-1', + agent: 'claude', + text: 'https://github.com/o/r/issues/12', + createdAt: expect.any(Number) + }) + ) + }) + + it('seeds the backend-spawned agent tab, not the worktree default terminal tab', async () => { + // Repo default tabs ("dev server", "logs", …) make activation's primaryTabId + // a tab that runs no agent; main's startup terminal is the agent's own tab. + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.tabsByWorktree = { 'wt-1': [{ id: 'dev-server' }, { id: 'agent-tab' }] } + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' }, + startupTerminal: { tabId: 'agent-tab', spawned: true } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'dev-server' }) + + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: 'claude --prefill x', + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: 'https://github.com/o/r/issues/12' + }) + ) + + await vi.waitFor(() => expect(store.seedNativeChatLaunchDraft).toHaveBeenCalled()) + expect(store.seedNativeChatLaunchDraft).toHaveBeenCalledWith( + expect.objectContaining({ tabId: 'agent-tab' }) + ) + const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined + expect(createCall?.[25]).toEqual({ + startupDraft: 'https://github.com/o/r/issues/12' + }) + }) + + it.each([ + ['mirrorable local Grok', 'grok', 'https://github.com/o/r/issues/12', 'chat'], + ['multi-line Claude', 'claude', 'note\nhttps://github.com/o/r/issues/12', 'chat'] + ] as const)('passes %s draft mode to backend startup', async (_label, agent, draft, viewMode) => { + store.settings.experimentalNativeChat = true + store.settings.openAgentTabsInChatByDefault = true + store.repos = [{ id: 'repo-1', connectionId: null }] + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent, + startup: { command: `${agent} --prefill x`, launchAgent: agent }, + startupPlan: { + agent, + launchCommand: `${agent} --prefill x`, + expectedProcess: agent, + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: draft + }) + ) + + await vi.waitFor(() => expect(store.createWorktree).toHaveBeenCalled()) + const createCall = store.createWorktree.mock.calls[0] as unknown[] | undefined + expect(createCall?.[16]).toEqual({ + command: `${agent} --prefill x`, + launchAgent: agent, + viewMode + }) + }) + + it('carries launchDraftText into activation for an argv-prefill launch', async () => { + // Why: the draft rides inside `launchCommand` here, so the plan sets no + // draftPrompt — without launchDraftText the initial view-mode decision + // never sees a draft and opens chat on an unmirrorable one. + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) + + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: "claude --prefill 'https://github.com/o/r/issues/12'", + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + }, + launchDraftPrompt: 'https://github.com/o/r/issues/12' + }) + ) + + await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) + const startup = vi.mocked(activateAndRevealWorktree).mock.calls[0]?.[1]?.startup + expect(startup?.draftPrompt).toBeUndefined() + expect(startup?.launchDraftText).toBe('https://github.com/o/r/issues/12') + }) + + it('does not seed a launch draft without draft launch context', async () => { + store.activeView = 'terminal' + store.activePendingCreationId = 'creation-1' + store.createWorktree.mockResolvedValueOnce({ + worktree: { id: 'wt-1', repoId: 'repo-1', path: '/repo/wt-1' } + }) + vi.mocked(activateAndRevealWorktree).mockReturnValueOnce({ primaryTabId: 'tab-1' }) + + continueBackgroundWorktreeCreation( + 'creation-1', + makeRequest({ + agent: 'claude', + startupPlan: { + agent: 'claude', + launchCommand: 'claude', + expectedProcess: 'claude', + followupPrompt: null, + launchConfig: { agentArgs: '', agentEnv: {} } + } + }) + ) + + await vi.waitFor(() => expect(activateAndRevealWorktree).toHaveBeenCalled()) + expect(store.seedNativeChatLaunchDraft).not.toHaveBeenCalled() + }) + // Why: activation no longer rebuilds a startup from `createdWithAgent`, so this // caller's own `startup` is the only thing that launches the agent it created. it('passes its own startup to activation when the create requested an agent', async () => { diff --git a/src/renderer/src/lib/worktree-initial-terminal-seeding.ts b/src/renderer/src/lib/worktree-initial-terminal-seeding.ts index f9b1288f5c53..feb01ef0b9b5 100644 --- a/src/renderer/src/lib/worktree-initial-terminal-seeding.ts +++ b/src/renderer/src/lib/worktree-initial-terminal-seeding.ts @@ -30,6 +30,7 @@ import { } 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( @@ -53,6 +54,7 @@ export function reseedGatedEmptyWorkspace( const state = useAppStore.getState() if ( callerProvidesSurface === true || + isEmptyWorkspaceDefaultSurfacePending(workspaceKey) || state.activeWorktreeId !== workspaceKey || (executionHostId !== undefined && state.activeWorkspaceExecutionHostId !== executionHostId) ) { 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 } : {}) }) From 01b4ba2ac51f7627fc254e0646bc04b66f90dfcd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:15:51 -0700 Subject: [PATCH 3/3] fix(native-chat): a reopen during the agent-list wait seeds for the latest open Round-2 review of the empty-workspace default chat: while a user open waited for the host's agent list, a second activation of the same workspace was dropped. Opening A from the sidebar, moving to B, then pressing Back to A during the wait left A active with no chat and no shell: the wait reseeded with the first open's host id, which no longer matched, and the passive seed had already marked A handled. - The pending wait now stores the latest activation's intent; a later activation (user open or plain) replaces it, and the wait seeds with it. - The passive seed no longer marks a workspace handled while a wait owns it, so leaving mid-wait and returning seeds a shell instead of nothing. - The wait and the open share one check, so a Blank Terminal default (or chat not being the default view) no longer waits up to 5 s before its shell. --- ...nitial-terminal-structured-launch.test.tsx | 21 ++++++- .../use-terminal-watcher-effects.ts | 8 ++- ...empty-workspace-default-agent-chat.test.ts | 9 +++ .../lib/empty-workspace-default-agent-chat.ts | 20 ++++--- .../empty-workspace-default-surface-claims.ts | 31 ++++++---- ...tree-activation-default-agent-chat.test.ts | 57 +++++++++++++++++++ .../worktree-activation-gated-empty-reseed.ts | 14 +++-- 7 files changed, 134 insertions(+), 26 deletions(-) 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 f03c1f1988c9..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 @@ -49,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 () => { @@ -210,7 +212,7 @@ describe('passive terminal seeding retries until a decision applies', () => { const finishGate = deferredGate() root = createRoot(document.createElement('div')) await act(async () => root?.render()) - claimEmptyWorkspaceDefaultSurface('wt-1') + claimEmptyWorkspaceDefaultSurface('wt-1', PENDING_INTENT) try { await finishGate('empty') expect(mocks.createTab).not.toHaveBeenCalled() @@ -219,6 +221,23 @@ describe('passive terminal seeding retries until a decision applies', () => { } }) + // 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-terminal-watcher-effects.ts b/src/renderer/src/components/use-terminal-watcher-effects.ts index d5a2c768e503..39764c873457 100644 --- a/src/renderer/src/components/use-terminal-watcher-effects.ts +++ b/src/renderer/src/components/use-terminal-watcher-effects.ts @@ -224,15 +224,19 @@ 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) if (outcome !== 'empty') { return } - // A reseed awaiting agent detection, or a pending chat create, owns the surface already. + // A pending or unanswered chat create owns the surface even before its tab is published. if ( - isEmptyWorkspaceDefaultSurfacePending(activeWorktreeId) || AGENT_SESSION_PROVIDER_HANDLE_PROVIDERS.some( (agent) => getStructuredAgentLaunchStatus(activeWorktreeId, agent) !== 'idle' ) 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 index 7b3545375c20..e3ad93eb3db4 100644 --- a/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.test.ts @@ -124,6 +124,15 @@ describe('agent detection for the default chat', () => { 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({}) diff --git a/src/renderer/src/lib/empty-workspace-default-agent-chat.ts b/src/renderer/src/lib/empty-workspace-default-agent-chat.ts index 9d2b29c8e418..84156f99927e 100644 --- a/src/renderer/src/lib/empty-workspace-default-agent-chat.ts +++ b/src/renderer/src/lib/empty-workspace-default-agent-chat.ts @@ -16,10 +16,22 @@ 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)) } @@ -39,9 +51,6 @@ function readDetectedAgents(state: AppState, target: AgentDetectionTarget): TuiA /** 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() - if (!agentTabsDefaultToNativeChat(state.settings)) { - return false - } const target = defaultChatDetectionTarget(state, worktreeId) return target !== undefined && readDetectedAgents(state, target) === null } @@ -70,15 +79,10 @@ export function openDefaultAgentChatInEmptyWorkspace( worktreeId: string ): { primaryTabId: string | null } | null { const state = useAppStore.getState() - if (!agentTabsDefaultToNativeChat(state.settings)) { - return null - } - // Why: an unresolved owner is an unknown host, not the local machine. const target = defaultChatDetectionTarget(state, worktreeId) if (!target) { return null } - // Why: a 'blank' default means the user wants workspaces to open without an agent. const agent = pickTuiAgent( state.settings?.defaultTuiAgent, readDetectedAgents(state, target) ?? [], diff --git a/src/renderer/src/lib/empty-workspace-default-surface-claims.ts b/src/renderer/src/lib/empty-workspace-default-surface-claims.ts index d66a9b17b4f3..61a989e6bfc0 100644 --- a/src/renderer/src/lib/empty-workspace-default-surface-claims.ts +++ b/src/renderer/src/lib/empty-workspace-default-surface-claims.ts @@ -1,20 +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. -const workspacesAwaitingDefaultSurface = new Set() +// Why the intent: the wait seeds for the latest activation, so a later one must not be dropped. +const pendingIntentByWorkspace = new Map() -/** False when another reseed already owns this workspace's default surface. */ -export function claimEmptyWorkspaceDefaultSurface(workspaceKey: string): boolean { - if (workspacesAwaitingDefaultSurface.has(workspaceKey)) { - return false - } - workspacesAwaitingDefaultSurface.add(workspaceKey) - return true +/** 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 } -export function releaseEmptyWorkspaceDefaultSurface(workspaceKey: string): void { - workspacesAwaitingDefaultSurface.delete(workspaceKey) +/** 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 workspacesAwaitingDefaultSurface.has(workspaceKey) + return pendingIntentByWorkspace.has(workspaceKey) } 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 index bdd61a3a0825..ae956cabd216 100644 --- a/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts +++ b/src/renderer/src/lib/worktree-activation-default-agent-chat.test.ts @@ -264,6 +264,63 @@ describe('the gated reseed that seeds an empty workspace in Electron', () => { 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 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 bf837cdbf002..2ab11bb14522 100644 --- a/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts +++ b/src/renderer/src/lib/worktree-activation-gated-empty-reseed.ts @@ -12,6 +12,7 @@ import { } from './empty-workspace-default-agent-chat' import { claimEmptyWorkspaceDefaultSurface, + isEmptyWorkspaceDefaultSurfacePending, releaseEmptyWorkspaceDefaultSurface } from './empty-workspace-default-surface-claims' @@ -34,18 +35,23 @@ export function gateAndReseedEmptyWorkspace( if (outcome !== 'empty') { return } - if (!intent.seedUserDefaultSurface || !emptyWorkspaceDefaultChatAwaitsDetection(workspaceKey)) { + 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. - if (!claimEmptyWorkspaceDefaultSurface(workspaceKey)) { + // A wait already pending takes this later intent instead, so the latest activation wins. + if (!claimEmptyWorkspaceDefaultSurface(workspaceKey, intent)) { return } const settle = (): void => { - releaseEmptyWorkspaceDefaultSurface(workspaceKey) + const latestIntent = releaseEmptyWorkspaceDefaultSurface(workspaceKey) // Re-checks the active workspace, host, and emptiness the wait may have changed. - reseedGatedEmptyWorkspace(workspaceKey, intent) + if (latestIntent) { + reseedGatedEmptyWorkspace(workspaceKey, latestIntent) + } } void loadEmptyWorkspaceDefaultChatDetection(workspaceKey).then(settle, settle) })