From 5da41d4ed6739876d89a80b6a1420e595eac93be Mon Sep 17 00:00:00 2001 From: gatsby74 <166927047+gatsby74@users.noreply.github.com> Date: Fri, 3 Jul 2026 01:47:38 +0200 Subject: [PATCH] [codex] Add file explorer open in terminal Add an Open in Terminal action for file-explorer directories and preserve terminal startup cwd through restore/session paths. --- src/main/ipc/pty.test.ts | 6 +- src/main/ipc/pty.ts | 38 +++-- src/main/persistence.ts | 3 + .../runtime/orca-runtime-terminal-cwd.test.ts | 154 ++++++++++++++++++ src/main/runtime/orca-runtime.ts | 122 ++++++++------ .../rpc/methods/session-tabs-schemas.ts | 1 + .../runtime/rpc/methods/session-tabs.test.ts | 2 + src/main/runtime/rpc/methods/session-tabs.ts | 1 + .../attach-main-window-services.test.ts | 6 +- .../window/attach-main-window-services.ts | 2 + src/preload/api-types.ts | 1 + src/preload/index.ts | 2 + src/renderer/src/components/Terminal.tsx | 2 +- .../right-sidebar/FileExplorer.test.tsx | 61 +++++++ .../components/right-sidebar/FileExplorer.tsx | 11 ++ .../right-sidebar/FileExplorerRow.tsx | 16 ++ .../right-sidebar/FileExplorerVirtualRows.tsx | 3 + ...FileExplorerVirtualRowsAddProject.test.tsx | 1 + .../file-explorer-drag-scroll-marker.test.tsx | 1 + .../tab-group/useTabGroupWorkspaceModel.ts | 1 + .../TerminalPaneOverlayLayer.tsx | 5 +- .../terminal/terminal-tab-actions.test.ts | 49 +++++- .../terminal/terminal-tab-actions.ts | 11 +- src/renderer/src/hooks/useIpcEvents.test.ts | 6 +- src/renderer/src/hooks/useIpcEvents.ts | 25 ++- src/renderer/src/i18n/locales/en.json | 8 +- src/renderer/src/i18n/locales/es.json | 6 +- src/renderer/src/i18n/locales/ja.json | 6 +- src/renderer/src/i18n/locales/ko.json | 6 +- src/renderer/src/i18n/locales/zh.json | 6 +- .../src/runtime/web-runtime-session.test.ts | 2 + .../src/runtime/web-runtime-session.ts | 2 + .../src/runtime/web-session-tabs-sync.test.ts | 44 +++++ .../src/runtime/web-session-tabs-sync.ts | 6 + .../src/store/slices/store-cascades.test.ts | 24 +++ src/renderer/src/store/slices/terminals.ts | 3 + src/shared/runtime-types.ts | 2 + src/shared/terminal-startup-cwd.test.ts | 71 ++++++++ src/shared/terminal-startup-cwd.ts | 52 ++++++ src/shared/types.ts | 3 + src/shared/workspace-session-schema.ts | 1 + .../workspace-session-terminal-schema.test.ts | 72 ++++++++ 42 files changed, 758 insertions(+), 86 deletions(-) create mode 100644 src/main/runtime/orca-runtime-terminal-cwd.test.ts create mode 100644 src/shared/terminal-startup-cwd.test.ts create mode 100644 src/shared/terminal-startup-cwd.ts create mode 100644 src/shared/workspace-session-terminal-schema.test.ts diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index c12f8466d..e34756928 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -4314,7 +4314,8 @@ describe('registerPtyHandlers', () => { worktreeId: 'wt-1', tabId: 'tab-race', leafId, - ptyId: 'pty-shared' + ptyId: 'pty-shared', + startupCwd: '/tmp' }) }) @@ -4427,7 +4428,8 @@ describe('registerPtyHandlers', () => { worktreeId: 'wt-1', tabId: 'tab-race', leafId, - ptyId: 'pty-renderer' + ptyId: 'pty-renderer', + startupCwd: '/tmp' }) }) diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index af29900b3..c32526194 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -77,6 +77,7 @@ import { parseLegacyNumericPaneKey, parsePaneKey } from '../../shared/stable-pane-id' +import { resolveTerminalStartupCwdForWorkspace } from '../../shared/terminal-startup-cwd' import { clearMigrationUnsupportedPty, clearMigrationUnsupportedPtysForPaneKey @@ -1960,6 +1961,17 @@ export function registerPtyHandlers( assertFolderWorkspacePathUsable(status) } + const resolveGuardedPtySpawnCwd = ( + worktreeId: string | undefined, + cwd: string | undefined + ): string | undefined => + resolveTerminalStartupCwdForWorkspace({ + workspaceId: worktreeId, + requestedCwd: cwd, + resolveFolderWorkspacePath: (folderWorkspaceId) => + store?.getFolderWorkspace(folderWorkspaceId)?.folderPath + }) + // Why: the runtime controller must route through getProviderForPty() so that // CLI commands (terminal.send, terminal.stop) work for both local and remote PTYs. // Hardcoding localProvider.getPtyProcess() would silently fail for remote PTYs. @@ -1970,6 +1982,7 @@ export function registerPtyHandlers( await startupPromise } await assertFolderWorkspacePtyPathUsable(args.worktreeId) + const cwd = resolveGuardedPtySpawnCwd(args.worktreeId, args.cwd) const provider = getProvider(args.connectionId) const isClaudeLaunch = !args.connectionId && isClaudeLaunchCommand(args.command) if (isClaudeLaunch && isClaudeAuthSwitchInProgress()) { @@ -1989,7 +2002,7 @@ export function registerPtyHandlers( const daemonShellOverride = terminalRuntimeOptions.shellOverride const codexSelectionTarget = getCodexSelectionTargetForPty( daemonShellOverride, - args.cwd, + cwd, terminalRuntimeOptions.terminalWindowsWslDistro ?? null ) const claudeAuth = @@ -2057,7 +2070,7 @@ export function registerPtyHandlers( : null const skipCodexHomeEnv = isDaemonHostSpawn && - shouldSkipCodexHomeEnvForWindowsShell(daemonShellOverride, args.cwd) && + shouldSkipCodexHomeEnvForWindowsShell(daemonShellOverride, cwd) && !selectedCodexHomePath if (isDaemonHostSpawn && sessionId) { if (!isSafePtySessionId(sessionId, app.getPath('userData'))) { @@ -2071,7 +2084,7 @@ export function registerPtyHandlers( githubAttributionEnabled: getSettings?.()?.enableGitHubAttribution ?? false, launchCommand: args.command, shellPath: daemonShellOverride ?? process.env.COMSPEC, - isWsl: shouldSkipCodexHomeEnvForWindowsShell(daemonShellOverride, args.cwd), + isWsl: shouldSkipCodexHomeEnvForWindowsShell(daemonShellOverride, cwd), agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()), networkProxySettings: getSettings?.() }) @@ -2084,7 +2097,7 @@ export function registerPtyHandlers( const spawnOptions: PtySpawnOptions = { cols: args.cols, rows: args.rows, - cwd: args.cwd, + cwd, env, ...(isMintedSessionId ? { isNewSession: true } : {}) } @@ -2204,7 +2217,8 @@ export function registerPtyHandlers( worktreeId: hostSessionBinding.worktreeId, tabId: hostSessionBinding.tabId, leafId: hostSessionBinding.leafId, - ptyId: result.id + ptyId: result.id, + ...(cwd ? { startupCwd: cwd } : {}) }) } catch (err) { console.error('[pty] failed to persist runtime PTY binding after spawn:', err) @@ -2540,6 +2554,7 @@ export function registerPtyHandlers( await startupPromise } await assertFolderWorkspacePtyPathUsable(args.worktreeId) + const cwd = resolveGuardedPtySpawnCwd(args.worktreeId, args.cwd) spawnTiming.mark('preflight') const provider = getProvider(args.connectionId) const isClaudeLaunch = !args.connectionId && isClaudeLaunchCommand(args.command) @@ -2558,7 +2573,7 @@ export function registerPtyHandlers( const initialShellOverride = terminalRuntimeOptions.shellOverride const initialSelectionTarget = getCodexSelectionTargetForPty( initialShellOverride, - args.cwd, + cwd, terminalRuntimeOptions.terminalWindowsWslDistro ?? null ) const claudeAuth = @@ -2729,7 +2744,7 @@ export function registerPtyHandlers( const effectiveShellOverride = terminalRuntimeOptions.shellOverride const codexSelectionTarget = getCodexSelectionTargetForPty( effectiveShellOverride, - args.cwd, + cwd, terminalRuntimeOptions.terminalWindowsWslDistro ?? null ) const selectedCodexHomePath = isDaemonHostSpawn @@ -2740,7 +2755,7 @@ export function registerPtyHandlers( : null const skipCodexHomeEnv = isDaemonHostSpawn && - shouldSkipCodexHomeEnvForWindowsShell(effectiveShellOverride, args.cwd) && + shouldSkipCodexHomeEnvForWindowsShell(effectiveShellOverride, cwd) && !selectedCodexHomePath if (isDaemonHostSpawn) { if (effectiveSessionId === undefined) { @@ -2769,7 +2784,7 @@ export function registerPtyHandlers( githubAttributionEnabled: getSettings?.()?.enableGitHubAttribution ?? false, launchCommand: args.command, shellPath: effectiveShellOverride ?? process.env.COMSPEC, - isWsl: shouldSkipCodexHomeEnvForWindowsShell(effectiveShellOverride, args.cwd), + isWsl: shouldSkipCodexHomeEnvForWindowsShell(effectiveShellOverride, cwd), agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()), networkProxySettings: getSettings?.() }) @@ -2811,7 +2826,7 @@ export function registerPtyHandlers( const spawnOptions: PtySpawnOptions = { cols: args.cols, rows: args.rows, - cwd: args.cwd, + cwd, env: spawnEnv, ...(isMintedSessionId ? { isNewSession: true } : {}) } @@ -3003,7 +3018,8 @@ export function registerPtyHandlers( worktreeId: args.worktreeId, tabId: args.tabId, leafId: validatedLeafId, - ptyId: result.id + ptyId: result.id, + ...(cwd ? { startupCwd: cwd } : {}) }) } catch (err) { console.error('[pty] failed to persist PTY binding after spawn:', err) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 14f3da845..9ac1fcc42 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2352,6 +2352,7 @@ function createMinimalPersistedTerminalTab(args: { tabId: string ptyId: string existingTabCount: number + startupCwd?: string }): TerminalTab { const ordinal = args.existingTabCount + 1 const defaultTitle = `Terminal ${ordinal}` @@ -2365,6 +2366,7 @@ function createMinimalPersistedTerminalTab(args: { color: null, sortOrder: args.existingTabCount, createdAt: Date.now(), + ...(args.startupCwd ? { startupCwd: args.startupCwd } : {}), pendingActivationSpawn: true } } @@ -5749,6 +5751,7 @@ export class Store { tabId: string leafId: string ptyId: string + startupCwd?: string }): void { const session = this.state.workspaceSession if (!session) { diff --git a/src/main/runtime/orca-runtime-terminal-cwd.test.ts b/src/main/runtime/orca-runtime-terminal-cwd.test.ts new file mode 100644 index 000000000..214d2a208 --- /dev/null +++ b/src/main/runtime/orca-runtime-terminal-cwd.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from './orca-runtime' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { + on: vi.fn(), + removeListener: vi.fn() + }, + app: { getPath: vi.fn(() => '/tmp') } +})) + +function stubLaunchScope(runtime: OrcaRuntimeService, path = '/repo/app'): void { + const internals = runtime as unknown as { + resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise<{ + id: string + path: string + connectionId: string | null + repo: null + folderWorkspace: null + }> + } + vi.spyOn(internals, 'resolveTerminalWorkspaceLaunchScope').mockResolvedValue({ + id: 'wt-1', + path, + connectionId: null, + repo: null, + folderWorkspace: null + }) +} + +describe('OrcaRuntimeService terminal startup cwd', () => { + it('spawns terminals inside the requested worktree subdirectory', async () => { + const runtime = new OrcaRuntimeService() + stubLaunchScope(runtime) + const spawn = vi.fn().mockResolvedValue({ id: 'pty-1' }) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + await runtime.createTerminal('id:wt-1', { cwd: '/repo/app/packages/web' }) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: '/repo/app/packages/web', + worktreeId: 'wt-1' + }) + ) + }) + + it('rejects requested terminal cwd values outside the selected worktree', async () => { + const runtime = new OrcaRuntimeService() + stubLaunchScope(runtime) + const spawn = vi.fn().mockResolvedValue({ id: 'pty-1' }) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + await expect(runtime.createTerminal('id:wt-1', { cwd: '/repo/app-other' })).rejects.toThrow( + 'Terminal cwd must be inside the selected worktree.' + ) + expect(spawn).not.toHaveBeenCalled() + }) + + it('reveals main-spawned terminals with their nested startup cwd', async () => { + const runtime = new OrcaRuntimeService() + stubLaunchScope(runtime) + const spawn = vi.fn().mockResolvedValue({ id: 'pty-1' }) + const revealTerminalSession = vi.fn().mockResolvedValue({ tabId: 'tab-1' }) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + runtime.setNotifier({ + worktreesChanged: vi.fn(), + reposChanged: vi.fn(), + activateWorktree: vi.fn(), + createTerminal: vi.fn(), + revealTerminalSession, + splitTerminal: vi.fn(), + renameTerminal: vi.fn(), + focusTerminal: vi.fn(), + closeTerminal: vi.fn(), + sleepWorktree: vi.fn(), + terminalFitOverrideChanged: vi.fn(), + terminalDriverChanged: vi.fn() + }) + + await runtime.createTerminal('id:wt-1', { cwd: '/repo/app/packages/web' }) + + expect(revealTerminalSession).toHaveBeenCalledWith( + 'wt-1', + expect.objectContaining({ cwd: '/repo/app/packages/web' }) + ) + }) + + it('materializes restored headless mobile tabs in the persisted startup cwd', async () => { + const store = { + getWorkspaceSession: () => ({ + activeRepoId: null, + activeWorktreeId: 'wt-1', + activeTabId: 'tab-1', + tabsByWorktree: { + 'wt-1': [ + { + id: 'tab-1', + ptyId: null, + worktreeId: 'wt-1', + title: 'Terminal 1', + defaultTitle: 'Terminal 1', + startupCwd: '/repo/app/packages/web', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0 + } + ] + }, + terminalLayoutsByTabId: {} + }) + } + const runtime = new OrcaRuntimeService(store as never) + stubLaunchScope(runtime) + const spawn = vi.fn().mockResolvedValue({ id: 'pty-1' }) + runtime.setPtyController({ + spawn, + write: () => true, + kill: () => true, + getForegroundProcess: async () => null + }) + + const listed = await runtime.listMobileSessionTabs('id:wt-1') + const tab = listed.tabs.find((candidate) => candidate.type === 'terminal') + expect(tab).toMatchObject({ startupCwd: '/repo/app/packages/web' }) + + await runtime.activateMobileSessionTab('id:wt-1', tab!.id) + + expect(spawn).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: '/repo/app/packages/web', + worktreeId: 'wt-1' + }) + ) + }) +}) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 69dbea1eb..79dbbdea4 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -198,6 +198,7 @@ import { isPathInsideOrEqual, normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { resolveTerminalStartupCwd } from '../../shared/terminal-startup-cwd' import { isWslUncPath } from '../../shared/wsl-paths' import { folderWorkspaceKey, @@ -1122,6 +1123,7 @@ type RuntimeNotifier = { worktreeId: string, opts: { command?: string + cwd?: string env?: Record title?: string presentation?: RuntimeTerminalPresentation @@ -1132,6 +1134,7 @@ type RuntimeNotifier = { opts: { ptyId: string title?: string | null + cwd?: string launchConfig?: SleepingAgentLaunchConfig launchToken?: string launchAgent?: TuiAgent @@ -3249,6 +3252,7 @@ export class OrcaRuntimeService { title: string | null activate: boolean selectIfNoActiveTab?: boolean + startupCwd?: string split?: { splitFromLeafId: string; direction: 'horizontal' | 'vertical' } } ): void { @@ -3287,6 +3291,7 @@ export class OrcaRuntimeService { ptyId: pty.ptyId, title, ...(pty.launchAgent ? { launchAgent: pty.launchAgent } : {}), + ...(args.startupCwd ? { startupCwd: args.startupCwd } : {}), parentLayout, isActive: args.activate || (args.selectIfNoActiveTab !== false && existing?.activeTabId == null) @@ -3392,6 +3397,7 @@ export class OrcaRuntimeService { leafId, title, ...(ptyId ? { ptyId } : {}), + ...(tab.startupCwd ? { startupCwd: tab.startupCwd } : {}), ...(tab.launchAgent ? { launchAgent: tab.launchAgent } : {}), ...(layout ? { parentLayout: this.cloneTerminalLayoutSnapshot(layout) } : {}), ...(tab.color != null ? { color: tab.color } : {}), @@ -3823,21 +3829,16 @@ export class OrcaRuntimeService { group.tabOrder.includes(tab.parentTabId) )?.id try { - await this.createHeadlessMobileSessionTerminal( - worktreeId, - true, - undefined, - undefined, - undefined, - undefined, - { + await this.createHeadlessMobileSessionTerminal(worktreeId, true, undefined, { + identity: { tabId: tab.parentTabId, leafId: tab.leafId, sessionId }, - tab.launchAgent, + cwd: tab.startupCwd, + launchAgent: tab.launchAgent, targetGroupId - ) + }) } catch (err) { if (sessionId && parseAppSshPtyId(sessionId)) { // Why: an expired SSH reattach clears durable bindings in the store, @@ -15132,6 +15133,7 @@ export class OrcaRuntimeService { opts: { command?: string claudeAgentTeamsSourceCommand?: string + cwd?: string env?: Record launchConfig?: WorktreeStartupLaunch['launchConfig'] launchToken?: string @@ -15175,6 +15177,7 @@ export class OrcaRuntimeService { throw new Error('runtime_unavailable') } const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) + const cwd = resolveTerminalStartupCwd(workspace.path, opts.cwd) ?? workspace.path const preAllocatedHandle = this.createPreAllocatedTerminalHandle() // Why: mint tabId in main before spawn so paneKey is known at PTY env // build time. Hook-based agent status (Claude/Codex/Cursor/Gemini) keys @@ -15262,7 +15265,7 @@ export class OrcaRuntimeService { const result = await this.ptyController.spawn({ cols: 120, rows: 40, - cwd: workspace.path, + cwd, command: sequencedStartupCommand ? opts.command : (agentTeamsPlan?.command ?? opts.command), commandDelivery: 'provider', startupCommandDelivery: opts.startupCommandDelivery, @@ -15307,7 +15310,8 @@ export class OrcaRuntimeService { activate: presentation === 'focused', // Why: explicit background presentation may carry legacy activate // metadata from an already-owned renderer pane; don't select it on mobile. - selectIfNoActiveTab: presentation !== 'background' + selectIfNoActiveTab: presentation !== 'background', + ...(cwd !== workspace.path ? { startupCwd: cwd } : {}) }) } let surface: RuntimeTerminalCreate['surface'] = 'background' @@ -15321,6 +15325,7 @@ export class OrcaRuntimeService { await this.notifier.revealTerminalSession(workspace.id, { ptyId: result.id, title: opts.title ?? null, + ...(cwd !== workspace.path ? { cwd } : {}), ...(effectiveLaunchConfig ? { launchConfig: effectiveLaunchConfig } : {}), ...(launchToken ? { launchToken } : {}), ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), @@ -15353,9 +15358,11 @@ export class OrcaRuntimeService { const win = rendererWindow ?? this.getAuthoritativeWindow() // Why: mirrors browserTabCreate — when no worktree is specified, pass // undefined so the renderer uses its current active worktree. - const worktreeId = worktreeSelector - ? (await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector)).id - : undefined + const workspace = worktreeSelector + ? await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) + : null + const worktreeId = workspace?.id + const cwd = workspace ? resolveTerminalStartupCwd(workspace.path, opts.cwd) : opts.cwd const requestId = randomUUID() // Why: terminal creation is a renderer-side Zustand store operation (like @@ -15387,6 +15394,7 @@ export class OrcaRuntimeService { requestId, worktreeId, command: opts.command, + cwd, ...(opts.env ? { env: opts.env } : {}), ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), ...(opts.launchToken ? { launchToken: opts.launchToken } : {}), @@ -15443,6 +15451,7 @@ export class OrcaRuntimeService { afterTabId?: string targetGroupId?: string command?: string + cwd?: string env?: Record startupCommandDelivery?: WorktreeStartupLaunch['startupCommandDelivery'] agent?: TuiAgent @@ -15483,6 +15492,7 @@ export class OrcaRuntimeService { afterTabId?: string targetGroupId?: string command?: string + cwd?: string env?: Record startupCommandDelivery?: WorktreeStartupLaunch['startupCommandDelivery'] agent?: TuiAgent @@ -15495,6 +15505,7 @@ export class OrcaRuntimeService { this.assertGraphReady() const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector) const worktreeId = workspace.id + const cwd = resolveTerminalStartupCwd(workspace.path, opts.cwd) this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId) let afterDesktopTabId: string | undefined if (opts.afterTabId) { @@ -15513,13 +15524,15 @@ export class OrcaRuntimeService { worktreeId, opts.activate !== false, opts.afterTabId, - startupCommand.command, - startupCommand.env, - startupCommand.startupCommandDelivery, - undefined, - startupCommand.launchAgent, - opts.targetGroupId, - startupCommand.launchConfig + { + command: startupCommand.command, + cwd, + env: startupCommand.env, + startupCommandDelivery: startupCommand.startupCommandDelivery, + launchAgent: startupCommand.launchAgent, + targetGroupId: opts.targetGroupId, + launchConfig: startupCommand.launchConfig + } ) } const requestId = randomUUID() @@ -15551,6 +15564,7 @@ export class OrcaRuntimeService { afterTabId: afterDesktopTabId, targetGroupId: opts.targetGroupId, command: startupCommand.command, + cwd, ...(startupCommand.env ? { env: startupCommand.env } : {}), ...(startupCommand.launchConfig ? { launchConfig: startupCommand.launchConfig } : {}), ...(startupCommand.launchAgent ? { launchAgent: startupCommand.launchAgent } : {}), @@ -15588,13 +15602,16 @@ export class OrcaRuntimeService { worktreeId, opts.activate !== false, opts.afterTabId, - startupCommand.command, - startupCommand.env, - startupCommand.startupCommandDelivery, - { tabId: pendingSurface.tab.parentTabId, leafId: pendingSurface.tab.leafId }, - startupCommand.launchAgent, - opts.targetGroupId, - startupCommand.launchConfig + { + command: startupCommand.command, + cwd, + env: startupCommand.env, + startupCommandDelivery: startupCommand.startupCommandDelivery, + identity: { tabId: pendingSurface.tab.parentTabId, leafId: pendingSurface.tab.leafId }, + launchAgent: startupCommand.launchAgent, + targetGroupId: opts.targetGroupId, + launchConfig: startupCommand.launchConfig + } ) } catch (error) { // Why: the renderer created the tab but its terminal surface never @@ -15680,30 +15697,35 @@ export class OrcaRuntimeService { worktreeId: string, activate: boolean, afterTabId?: string, - command?: string, - env?: Record, - startupCommandDelivery?: WorktreeStartupLaunch['startupCommandDelivery'], - identity?: { tabId: string; leafId: string; sessionId?: string }, - launchAgent?: TuiAgent, - targetGroupId?: string, - launchConfig?: SleepingAgentLaunchConfig + opts: { + command?: string + cwd?: string + env?: Record + startupCommandDelivery?: WorktreeStartupLaunch['startupCommandDelivery'] + identity?: { tabId: string; leafId: string; sessionId?: string } + launchAgent?: TuiAgent + targetGroupId?: string + launchConfig?: SleepingAgentLaunchConfig + } = {} ): Promise { const workspace = await this.resolveTerminalWorkspaceLaunchScope(`id:${worktreeId}`) + const cwd = resolveTerminalStartupCwd(workspace.path, opts.cwd) // Why: SshPtyProvider treats sessionId as a relay reattach request. Only // synthesize local serve ids; SSH fresh terminals must call pty.spawn. const stableSessionId = - identity?.sessionId ?? (workspace.connectionId ? undefined : `serve-${randomUUID()}`) + opts.identity?.sessionId ?? (workspace.connectionId ? undefined : `serve-${randomUUID()}`) const terminal = await this.createTerminal(`id:${worktreeId}`, { focus: false, - command, - env, - ...(launchConfig ? { launchConfig } : {}), - ...(launchAgent ? { launchAgent } : {}), - startupCommandDelivery, - ...(identity + command: opts.command, + cwd, + env: opts.env, + ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), + ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), + startupCommandDelivery: opts.startupCommandDelivery, + ...(opts.identity ? { - tabId: identity.tabId, - leafId: identity.leafId, + tabId: opts.identity.tabId, + leafId: opts.identity.leafId, ...(stableSessionId ? { sessionId: stableSessionId } : {}) } : stableSessionId @@ -15740,7 +15762,8 @@ export class OrcaRuntimeService { leafId, ptyId: livePty.pty.ptyId, title: terminal.title ?? livePty.pty.title ?? 'Terminal', - ...(launchAgent ? { launchAgent } : {}), + ...(cwd ? { startupCwd: cwd } : {}), + ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), parentLayout, isActive: activate } @@ -15766,8 +15789,8 @@ export class OrcaRuntimeService { // Why: activating the new tab also focuses its group, so when "+" targeted // a specific split group, make that group active too. activeGroupId: - activate && targetGroupId - ? targetGroupId + activate && opts.targetGroupId + ? opts.targetGroupId : (existing?.activeGroupId ?? this.getHeadlessMobileSessionGroupId(worktreeId)), activeTabId: activate ? tab.id : (existing?.activeTabId ?? null), activeTabType: activate ? 'terminal' : (existing?.activeTabType ?? null), @@ -15776,7 +15799,7 @@ export class OrcaRuntimeService { tabs, activate ? tab : null, existing?.tabGroups, - targetGroupId ? { tabId: parentTabId, groupId: targetGroupId } : undefined + opts.targetGroupId ? { tabId: parentTabId, groupId: opts.targetGroupId } : undefined ), // Why: keep the group split geometry when a new tab is created, otherwise // opening a terminal while split loses the groups' arrangement. @@ -18202,6 +18225,7 @@ export class OrcaRuntimeService { ...(launchAgent ? { launchAgent } : {}), ...(agentStatus ?? this.buildPtyMobileAgentStatus(livePty ?? pty, tab, terminalHandle)), ...(tab.parentLayout ? { parentLayout: tab.parentLayout } : {}), + ...(tab.startupCwd ? { startupCwd: tab.startupCwd } : {}), ...(tab.color != null ? { color: tab.color } : {}), ...(tab.isPinned ? { isPinned: true } : {}), ...(tab.viewMode ? { viewMode: tab.viewMode } : {}), diff --git a/src/main/runtime/rpc/methods/session-tabs-schemas.ts b/src/main/runtime/rpc/methods/session-tabs-schemas.ts index 2c7c31839..0c21af7de 100644 --- a/src/main/runtime/rpc/methods/session-tabs-schemas.ts +++ b/src/main/runtime/rpc/methods/session-tabs-schemas.ts @@ -113,6 +113,7 @@ export const CreateTerminalTab = WorktreeTabSelector.extend({ afterTabId: z.string().optional(), targetGroupId: z.string().optional(), command: z.string().optional(), + cwd: z.string().min(1).optional(), env: z.record(z.string(), z.string()).optional(), startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), launchConfig: sleepingAgentLaunchConfigSchema, diff --git a/src/main/runtime/rpc/methods/session-tabs.test.ts b/src/main/runtime/rpc/methods/session-tabs.test.ts index e6c369fa5..625959f6d 100644 --- a/src/main/runtime/rpc/methods/session-tabs.test.ts +++ b/src/main/runtime/rpc/methods/session-tabs.test.ts @@ -140,6 +140,7 @@ describe('session tab RPC methods', () => { worktree: 'id:wt-1', targetGroupId: 'group-left', command: 'zsh', + cwd: '/repo/packages/app', env: { CODEX_PROFILE: 'captured' }, launchToken: 'launch-token-123', launchConfig: { @@ -156,6 +157,7 @@ describe('session tab RPC methods', () => { afterTabId: undefined, targetGroupId: 'group-left', command: 'zsh', + cwd: '/repo/packages/app', env: { CODEX_PROFILE: 'captured' }, startupCommandDelivery: undefined, agent: undefined, diff --git a/src/main/runtime/rpc/methods/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs.ts index ebdcc2a7f..f2bf1641b 100644 --- a/src/main/runtime/rpc/methods/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs.ts @@ -46,6 +46,7 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ afterTabId: params.afterTabId, targetGroupId: params.targetGroupId, command: params.command, + cwd: params.cwd, ...(params.env ? { env: params.env } : {}), startupCommandDelivery: params.startupCommandDelivery, agent: params.agent, diff --git a/src/main/window/attach-main-window-services.test.ts b/src/main/window/attach-main-window-services.test.ts index 323342c18..35bc56c02 100644 --- a/src/main/window/attach-main-window-services.test.ts +++ b/src/main/window/attach-main-window-services.test.ts @@ -614,12 +614,13 @@ describe('attachMainWindowServices', () => { const notifier = runtime.setNotifier.mock.calls[0][0] as { revealTerminalSession: ( worktreeId: string, - opts: { ptyId: string; title?: string; activate?: boolean } + opts: { ptyId: string; title?: string; cwd?: string; activate?: boolean } ) => Promise<{ tabId: string; title?: string }> } const revealPromise = notifier.revealTerminalSession('wt-1', { ptyId: 'pty-1', - title: 'SSH tmux' + title: 'SSH tmux', + cwd: '/repo/packages/web' }) const sentPayload = sendMock.mock.calls.find( ([channel]) => channel === 'ui:createTerminal' @@ -627,6 +628,7 @@ describe('attachMainWindowServices', () => { const handler = onMock.mock.calls.find( ([channel]) => channel === 'terminal:tabCreateReply' )?.[1] + expect(sentPayload.cwd).toBe('/repo/packages/web') handler?.( { sender: { send: vi.fn() } }, diff --git a/src/main/window/attach-main-window-services.ts b/src/main/window/attach-main-window-services.ts index 429243923..904d99b8e 100644 --- a/src/main/window/attach-main-window-services.ts +++ b/src/main/window/attach-main-window-services.ts @@ -252,6 +252,7 @@ function registerRuntimeWindowLifecycle( send('ui:createTerminal', { worktreeId, command: opts.command, + ...(opts.cwd ? { cwd: opts.cwd } : {}), ...(opts.env ? { env: opts.env } : {}), title: opts.title, ...(opts.presentation ? { presentation: opts.presentation } : {}) @@ -286,6 +287,7 @@ function registerRuntimeWindowLifecycle( worktreeId, ptyId: opts.ptyId, title: opts.title ?? undefined, + ...(opts.cwd ? { cwd: opts.cwd } : {}), ...(opts.launchConfig ? { launchConfig: opts.launchConfig } : {}), ...(opts.launchToken ? { launchToken: opts.launchToken } : {}), ...(opts.launchAgent ? { launchAgent: opts.launchAgent } : {}), diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 3f31cc560..35bf79384 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -2587,6 +2587,7 @@ export type PreloadApi = { requestId?: string worktreeId: string command?: string + cwd?: string env?: Record launchConfig?: SleepingAgentLaunchConfig launchToken?: string diff --git a/src/preload/index.ts b/src/preload/index.ts index 9a162aa54..333e298ea 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -3210,6 +3210,7 @@ const api = { requestId?: string worktreeId: string command?: string + cwd?: string env?: Record launchConfig?: SleepingAgentLaunchConfig launchToken?: string @@ -3231,6 +3232,7 @@ const api = { requestId?: string worktreeId: string command?: string + cwd?: string env?: Record launchConfig?: SleepingAgentLaunchConfig launchToken?: string diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 6da91641a..8a17d67af 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -1886,7 +1886,7 @@ function Terminal(): React.JSX.Element | null { key={`${tab.id}-${tab.generation ?? 0}`} tabId={tab.id} worktreeId={workspace.id} - cwd={workspace.path} + cwd={tab.startupCwd ?? workspace.path} isActive={isActiveTerminalTab || activityTerminalPortal?.active === true} // Why: the activity page hosts this existing pane via // portal while the workspace surface remains hidden. diff --git a/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx b/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx index 1722a4ed8..0b0dee707 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx @@ -18,6 +18,7 @@ import { shouldShowCollapseFolderAction, shouldShowFindInFolderAction, shouldShowCopyFileAction, + shouldShowOpenInTerminalAction, shouldShowRemoteDownloadAction } from './FileExplorerRow' import { FileExplorerVirtualRows } from './FileExplorerVirtualRows' @@ -575,6 +576,11 @@ describe('FileExplorerRow collapse folder action', () => { ).toBe(false) }) + it('only shows open in terminal for directories', () => { + expect(shouldShowOpenInTerminalAction(directoryNode)).toBe(true) + expect(shouldShowOpenInTerminalAction(fileNode)).toBe(false) + }) + it('shows remote download only for desktop SSH or Remote Host file-like rows', () => { const runtimeContext = { settings: { activeRuntimeEnvironmentId: 'runtime-1' }, @@ -776,6 +782,7 @@ describe('FileExplorerRow collapse folder action', () => { onDuplicate: vi.fn(), onAddFolderAsProject: vi.fn(), canAddFolderAsProject: () => false, + onOpenInTerminal: vi.fn(), onRequestDelete: vi.fn(), onCollapseFolderSubtree, onFindInFolder: vi.fn(), @@ -827,6 +834,7 @@ describe('FileExplorerRow collapse folder action', () => { onDuplicate: vi.fn(), onAddFolderAsProject: vi.fn(), canAddFolderAsProject: () => false, + onOpenInTerminal: vi.fn(), onRequestDelete: vi.fn(), onCollapseFolderSubtree: vi.fn(), onFindInFolder, @@ -878,6 +886,7 @@ describe('FileExplorerRow collapse folder action', () => { onDuplicate: vi.fn(), onAddFolderAsProject: vi.fn(), canAddFolderAsProject: () => false, + onOpenInTerminal: vi.fn(), onRequestDelete: vi.fn(), onCollapseFolderSubtree: vi.fn(), onFindInFolder: vi.fn(), @@ -896,4 +905,56 @@ describe('FileExplorerRow collapse folder action', () => { expect(row.props.connectionId).toBe('ssh-1') }) + + it('passes the row node to the open in terminal handler', () => { + const onOpenInTerminal = vi.fn() + const element = FileExplorerVirtualRows({ + virtualizer: { + getTotalSize: () => 26, + getVirtualItems: () => [{ index: 0, key: 'src', start: 0 }], + measureElement: vi.fn() + } as never, + inlineInputIndex: -1, + rowProjection: createFileExplorerRowProjection([directoryNode]), + inlineInput: null, + handleInlineSubmit: vi.fn(), + dismissInlineInput: vi.fn(), + folderStatusByRelativePath: new Map(), + statusByRelativePath: new Map(), + ignoredByRelativePath: new Set(), + expanded: new Set([directoryNode.path]), + dirCache: {}, + selectedPaths: new Set(), + activeFileId: null, + flashingPath: null, + deleteShortcutLabel: 'Del', + onClick: vi.fn(), + onDoubleClick: vi.fn(), + onContextMenuSelect: vi.fn(), + onCopyPaths: vi.fn(), + onStartNew: vi.fn(), + onStartRename: vi.fn(), + onDuplicate: vi.fn(), + onAddFolderAsProject: vi.fn(), + canAddFolderAsProject: () => false, + onOpenInTerminal, + onRequestDelete: vi.fn(), + onCollapseFolderSubtree: vi.fn(), + onFindInFolder: vi.fn(), + onMoveDrop: vi.fn(), + onDragTargetChange: vi.fn(), + onDragSourceChange: vi.fn(), + onDragExpandDir: vi.fn(), + onNativeDragTargetChange: vi.fn(), + onNativeDragExpandDir: vi.fn(), + dropTargetDir: null, + dragSourcePath: null, + nativeDropTargetDir: null + }) + + const row = findFileExplorerRow(element) + ;(row.props.onOpenInTerminal as () => void)() + + expect(onOpenInTerminal).toHaveBeenCalledWith(directoryNode) + }) }) diff --git a/src/renderer/src/components/right-sidebar/FileExplorer.tsx b/src/renderer/src/components/right-sidebar/FileExplorer.tsx index ff2363539..83defe0e7 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorer.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorer.tsx @@ -54,6 +54,7 @@ import { translate } from '@/i18n/i18n' import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/components/tab-bar/SortableTab' import type { RightSidebarExplorerView } from '../../../../shared/types' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { createNewTerminalTab } from '@/components/terminal/terminal-tab-actions' function FileExplorerFiles(): React.JSX.Element { const explorerView = useAppStore((s) => s.rightSidebarExplorerView) @@ -577,6 +578,15 @@ function FileExplorerFiles(): React.JSX.Element { }, [activeRepo, openModal] ) + const handleOpenInTerminal = useCallback( + (node: TreeNode) => { + if (!activeWorktreeId || !node.isDirectory) { + return + } + createNewTerminalTab(activeWorktreeId, undefined, { startupCwd: node.path }) + }, + [activeWorktreeId] + ) if (!worktreePath) { return ( @@ -743,6 +753,7 @@ function FileExplorerFiles(): React.JSX.Element { onDuplicate={handleDuplicate} onAddFolderAsProject={handleAddFolderAsProject} canAddFolderAsProject={(node) => canShowAddAsProjectAction(node, activeRepo)} + onOpenInTerminal={handleOpenInTerminal} onRequestDelete={handleContextMenuDelete} onCollapseFolderSubtree={handleCollapseFolderSubtree} onFindInFolder={handleFindInFolder} diff --git a/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx b/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx index d24d3d656..765c1071b 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx @@ -20,6 +20,7 @@ import { Loader2, Pencil, Search, + SquareTerminal, Trash2 } from 'lucide-react' import { toast } from 'sonner' @@ -285,6 +286,7 @@ type FileExplorerRowProps = { onDuplicate: (node: TreeNode) => void onAddFolderAsProject: () => void canAddAsProject: boolean + onOpenInTerminal: () => void onRequestDelete: () => void onCollapseFolderSubtree: () => void onFindInFolder: () => void @@ -304,6 +306,10 @@ export function shouldShowFindInFolderAction(node: TreeNode): boolean { return node.isDirectory } +export function shouldShowOpenInTerminalAction(node: TreeNode): boolean { + return node.isDirectory +} + export function shouldShowRemoteDownloadAction( node: TreeNode, connectionId?: string | null, @@ -422,6 +428,7 @@ export function FileExplorerRow({ onDuplicate, onAddFolderAsProject, canAddAsProject, + onOpenInTerminal, onRequestDelete, onCollapseFolderSubtree, onFindInFolder, @@ -696,6 +703,15 @@ export function FileExplorerRow({ )} )} + {shouldShowOpenInTerminalAction(node) && ( + + + {translate( + 'auto.components.right.sidebar.FileExplorerRow.e887fa4b2e', + 'Open in Terminal' + )} + + )} {!node.isDirectory && activeWorktreeId && ( diff --git a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx index a400fef2c..fe4e71dd6 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx @@ -37,6 +37,7 @@ type FileExplorerVirtualRowsProps = { onDuplicate: (node: TreeNode) => void onAddFolderAsProject: (node: TreeNode) => void canAddFolderAsProject: (node: TreeNode) => boolean + onOpenInTerminal: (node: TreeNode) => void onRequestDelete: (node: TreeNode) => void onCollapseFolderSubtree: (node: TreeNode) => void onFindInFolder: (node: TreeNode) => void @@ -80,6 +81,7 @@ export function FileExplorerVirtualRows(props: FileExplorerVirtualRowsProps): Re onDuplicate, onAddFolderAsProject, canAddFolderAsProject, + onOpenInTerminal, onRequestDelete, onCollapseFolderSubtree, onFindInFolder, @@ -185,6 +187,7 @@ export function FileExplorerVirtualRows(props: FileExplorerVirtualRowsProps): Re onDuplicate={onDuplicate} onAddFolderAsProject={() => onAddFolderAsProject(n)} canAddAsProject={canAddFolderAsProject(n)} + onOpenInTerminal={() => onOpenInTerminal(n)} onRequestDelete={() => onRequestDelete(n)} onCollapseFolderSubtree={() => onCollapseFolderSubtree(n)} onFindInFolder={() => onFindInFolder(n)} diff --git a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx index 7910c5f8f..16236cbd7 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx @@ -77,6 +77,7 @@ describe('FileExplorerVirtualRows add-as-project action', () => { onDuplicate: vi.fn(), onAddFolderAsProject, canAddFolderAsProject: (node) => node.path === directoryNode.path, + onOpenInTerminal: vi.fn(), onRequestDelete: vi.fn(), onCollapseFolderSubtree: vi.fn(), onFindInFolder: vi.fn(), diff --git a/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx index ded3aa0cb..a9d1d9a46 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx @@ -78,6 +78,7 @@ function virtualRowsElement(nodes: TreeNode[]): React.JSX.Element { onDuplicate: vi.fn(), onAddFolderAsProject: vi.fn(), canAddFolderAsProject: () => false, + onOpenInTerminal: vi.fn(), onRequestDelete: vi.fn(), onCollapseFolderSubtree: vi.fn(), onFindInFolder: vi.fn(), diff --git a/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts b/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts index fe50561d2..e4b6b151c 100644 --- a/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts +++ b/src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts @@ -151,6 +151,7 @@ export function useTabGroupWorkspaceModel({ createdAt: item.createdAt, generation: terminalTab?.generation, shellOverride: terminalTab?.shellOverride, + startupCwd: terminalTab?.startupCwd, // Why: carry the launched agent through the rebuilt tab so the tab // bar can show the provider icon before the agent's first hook — // this object is reconstructed from the unified-tab model, so any diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx index dd71eba0c..0e68af912 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx @@ -50,6 +50,7 @@ type TerminalOverlaySlotProps = { terminalGeneration: number | undefined worktreeId: string worktreePath: string + startupCwd: string | undefined groupId: string | undefined isWorktreeActive: boolean isVisible: boolean @@ -66,6 +67,7 @@ const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ terminalGeneration, worktreeId, worktreePath, + startupCwd, groupId, isWorktreeActive, isVisible, @@ -223,7 +225,7 @@ const TerminalOverlaySlot = memo(function TerminalOverlaySlot({ key={`${terminalTabId}-${terminalGeneration ?? 0}`} tabId={terminalTabId} worktreeId={worktreeId} - cwd={worktreePath} + cwd={startupCwd ?? worktreePath} isActive={isActive || activityTerminalPortal?.active === true} // Why: split-group changes reparent TabGroupPanel subtrees. Keeping the // TerminalPane mounted here preserves alt-screen TUI state while this @@ -365,6 +367,7 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ terminalGeneration={terminalTab.generation} worktreeId={worktreeId} worktreePath={worktreePath} + startupCwd={terminalTab.startupCwd} groupId={assignment?.groupId} isWorktreeActive={isWorktreeActive} isVisible={isVisible} diff --git a/src/renderer/src/components/terminal/terminal-tab-actions.test.ts b/src/renderer/src/components/terminal/terminal-tab-actions.test.ts index ba1443477..a070cdc93 100644 --- a/src/renderer/src/components/terminal/terminal-tab-actions.test.ts +++ b/src/renderer/src/components/terminal/terminal-tab-actions.test.ts @@ -73,7 +73,7 @@ describe('createNewTerminalTab', () => { createNewTerminalTab('wt-1', 'zsh') - expect(createTab).toHaveBeenCalledWith('wt-1', undefined, 'zsh') + expect(createTab).toHaveBeenCalledWith('wt-1', undefined, 'zsh', undefined) expect(setActiveTabType).toHaveBeenCalledWith('terminal') expect(setTabBarOrder).toHaveBeenCalledWith('wt-1', ['tab-1']) expect(createWebRuntimeSessionTerminalMock).not.toHaveBeenCalled() @@ -123,6 +123,53 @@ describe('createNewTerminalTab', () => { }) expect(createTab).not.toHaveBeenCalled() }) + + it('creates local terminal tabs with a requested startup cwd', () => { + const createTab = vi.fn(() => ({ id: 'tab-1' })) + const setActiveTabType = vi.fn() + const setTabBarOrder = vi.fn() + getStateMock + .mockReturnValueOnce({ + settings: { activeRuntimeEnvironmentId: null }, + createTab, + setActiveTabType, + setTabBarOrder + }) + .mockReturnValueOnce({ + tabsByWorktree: { 'wt-1': [{ id: 'tab-1' }] }, + openFiles: [], + tabBarOrderByWorktree: {}, + setTabBarOrder + }) + + createNewTerminalTab('wt-1', undefined, { startupCwd: '/repo/packages/app' }) + + expect(createTab).toHaveBeenCalledWith('wt-1', undefined, undefined, { + startupCwd: '/repo/packages/app' + }) + expect(setActiveTabType).toHaveBeenCalledWith('terminal') + }) + + it('delegates requested startup cwd to host runtime terminals', () => { + const createTab = vi.fn(() => ({ id: 'tab-1' })) + isWebRuntimeSessionActiveMock.mockReturnValue(true) + getStateMock.mockReturnValue({ + settings: { activeRuntimeEnvironmentId: 'web-runtime' }, + createTab, + setActiveTabType: vi.fn() + }) + + createNewTerminalTab('wt-1', undefined, { startupCwd: '/repo/packages/app' }) + + expect(createWebRuntimeSessionTerminalMock).toHaveBeenCalledWith({ + worktreeId: 'wt-1', + environmentId: 'web-runtime', + command: undefined, + cwd: '/repo/packages/app', + activate: true + }) + expect(createTab).not.toHaveBeenCalled() + }) }) describe('closeTerminalTab', () => { diff --git a/src/renderer/src/components/terminal/terminal-tab-actions.ts b/src/renderer/src/components/terminal/terminal-tab-actions.ts index 77f604b74..9991b7648 100644 --- a/src/renderer/src/components/terminal/terminal-tab-actions.ts +++ b/src/renderer/src/components/terminal/terminal-tab-actions.ts @@ -101,7 +101,8 @@ function isPinnedVisibleTab( export function createNewTerminalTab( activeWorktreeId: string | null, - shellOverride?: string + shellOverride?: string, + options?: { startupCwd?: string } ): void { if (!activeWorktreeId) { return @@ -116,11 +117,17 @@ export function createNewTerminalTab( worktreeId: activeWorktreeId, environmentId: runtimeEnvironmentId, command: shellOverride, + ...(options?.startupCwd ? { cwd: options.startupCwd } : {}), activate: true }) return } - const newTab = state.createTab(activeWorktreeId, undefined, shellOverride) + const newTab = state.createTab( + activeWorktreeId, + undefined, + shellOverride, + options?.startupCwd ? { startupCwd: options.startupCwd } : undefined + ) state.setActiveTabType('terminal') // Why: persist the tab bar order with the new terminal at the end of the // current visual order. Without this, reconcileTabOrder falls back to diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index d21df9674..b86a258bd 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -1738,6 +1738,7 @@ describe('useIpcEvents updater integration', () => { afterTabId?: string targetGroupId?: string command?: string + cwd?: string launchConfig?: SleepingAgentLaunchConfig launchAgent?: TuiAgent title?: string @@ -1883,6 +1884,7 @@ describe('useIpcEvents updater integration', () => { afterTabId?: string targetGroupId?: string command?: string + cwd?: string launchConfig?: SleepingAgentLaunchConfig launchAgent?: TuiAgent title?: string @@ -2144,6 +2146,7 @@ describe('useIpcEvents updater integration', () => { targetGroupId: 'group-left', title: 'Codex', command: 'codex', + cwd: '/repo/packages/app', launchConfig: { agentArgs: '--model gpt-5', agentEnv: { CODEX_PROFILE: 'request' } @@ -2156,7 +2159,8 @@ describe('useIpcEvents updater integration', () => { activate: false, recordInteraction: false, launchAgent: 'codex', - viewMode: 'chat' + viewMode: 'chat', + startupCwd: '/repo/packages/app' }) expect(setActiveView).not.toHaveBeenCalled() expect(setActiveWorktree).not.toHaveBeenCalled() diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index c0ab880a9..f5b8f67a5 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -1351,6 +1351,7 @@ export function useIpcEvents(): void { requestId, worktreeId, command, + cwd, env, launchConfig, launchToken, @@ -1426,6 +1427,7 @@ export function useIpcEvents(): void { ...initialAgentTabViewModeProps(store.settings) } : {}), + ...(cwd ? { startupCwd: cwd } : {}), // Why: tabId hint comes from CLI-spawned PTYs whose env // already has the pane key baked in. Adopting the tab under // the same id keeps hook-event attribution working. @@ -1435,7 +1437,15 @@ export function useIpcEvents(): void { worktreeId, undefined, undefined, - shouldActivate ? undefined : { activate: false, recordInteraction: false } + shouldActivate + ? cwd + ? { startupCwd: cwd } + : undefined + : { + activate: false, + recordInteraction: false, + ...(cwd ? { startupCwd: cwd } : {}) + } )) // Why: when an existing tab already owns this ptyId, we reuse it instead of // minting a new one — but the PTY env already carries a paneKey from main. @@ -1602,11 +1612,18 @@ export function useIpcEvents(): void { ? { ...(shouldActivate ? {} : { activate: false, recordInteraction: false }), launchAgent: data.launchAgent, - ...initialAgentTabViewModeProps(store.settings) + ...initialAgentTabViewModeProps(store.settings), + ...(data.cwd ? { startupCwd: data.cwd } : {}) } : shouldActivate - ? undefined - : { activate: false, recordInteraction: false } + ? data.cwd + ? { startupCwd: data.cwd } + : undefined + : { + activate: false, + recordInteraction: false, + ...(data.cwd ? { startupCwd: data.cwd } : {}) + } const tab = store.createTab(worktreeId, data.targetGroupId, undefined, tabOptions) if (data.afterTabId) { const createdUnifiedTab = useAppStore diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 66b74f5c0..88287a0b5 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -4118,7 +4118,8 @@ "groupDeleteFailed": "Failed to delete group", "groupDeleteFailedDesc": "Something went wrong while deleting the group. No projects were removed.", "failedNestWorkspace": "Failed to nest workspace", - "sidebarRowMissing": "Target no longer exists" + "sidebarRowMissing": "Target no longer exists", + "failedUnnestWorkspace": "Failed to unnest workspace" }, "WorktreeMetaDialog": { "3db0a2a593": "Cancel", @@ -6404,8 +6405,6 @@ "a62b4cb39a": "Save Changes", "29af933cd5": "New SSH Target", "f2331ce599": "Edit SSH Target", - "7c13f58c91": "Until reset", - "55c56cf2c7": "Timeout after disconnect (seconds)", "4a342f44c1": "Advanced Connection", "e9609ddca6": "Proxy, jump host, and connection reuse", "8c922dffba": "Reuse SSH connection for faster setup", @@ -8821,7 +8820,8 @@ "98a79948b3": "Copy", "b234ab25b4": "Could not copy the file to the clipboard", "f9d7ca753d": "Copy Paths", - "3161c4e425": "folder" + "3161c4e425": "folder", + "e887fa4b2e": "Open in Terminal" }, "FileExplorerToolbar": { "d238264654": "Show Git Ignored Files", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 0981dc1e9..dccd120a4 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -4095,7 +4095,8 @@ "hostAuthNeeded": "Autenticación requerida", "hostDisconnected": "Desconectado", "failedNestWorkspace": "No se pudo anidar el espacio de trabajo", - "sidebarRowMissing": "El destino ya no existe" + "sidebarRowMissing": "El destino ya no existe", + "failedUnnestWorkspace": "Failed to unnest workspace" }, "WorktreeMetaDialog": { "3db0a2a593": "Cancelar", @@ -8819,7 +8820,8 @@ "98a79948b3": "Copiar", "b234ab25b4": "No se pudo copiar el archivo al portapapeles", "f9d7ca753d": "Copiar rutas", - "3161c4e425": "carpeta" + "3161c4e425": "carpeta", + "e887fa4b2e": "Abrir en terminal" }, "FileExplorerToolbar": { "d238264654": "Mostrar archivos ignorados de Git", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index b2e321fc6..bdd01d85a 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -4076,7 +4076,8 @@ "hostAuthNeeded": "認証が必要です", "hostDisconnected": "切断済み", "failedNestWorkspace": "ワークスペースをネストできませんでした", - "sidebarRowMissing": "対象はもう存在しません" + "sidebarRowMissing": "対象はもう存在しません", + "failedUnnestWorkspace": "Failed to unnest workspace" }, "WorktreeMetaDialog": { "3db0a2a593": "キャンセル", @@ -8819,7 +8820,8 @@ "98a79948b3": "コピー", "b234ab25b4": "ファイルをクリップボードにコピーできませんでした", "f9d7ca753d": "パスのコピー", - "3161c4e425": "フォルダ" + "3161c4e425": "フォルダ", + "e887fa4b2e": "ターミナルで開く" }, "FileExplorerToolbar": { "d238264654": "Git で無視されたファイルを表示", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index eb7378ea9..a934f15ad 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -4076,7 +4076,8 @@ "hostAuthNeeded": "인증 필요", "hostDisconnected": "연결 끊김", "failedNestWorkspace": "워크스페이스를 중첩하지 못했습니다", - "sidebarRowMissing": "대상이 더 이상 존재하지 않습니다" + "sidebarRowMissing": "대상이 더 이상 존재하지 않습니다", + "failedUnnestWorkspace": "Failed to unnest workspace" }, "WorktreeMetaDialog": { "3db0a2a593": "취소", @@ -8819,7 +8820,8 @@ "98a79948b3": "복사", "b234ab25b4": "파일을 클립보드에 복사하지 못했습니다", "f9d7ca753d": "경로 복사", - "3161c4e425": "폴더" + "3161c4e425": "폴더", + "e887fa4b2e": "터미널에서 열기" }, "FileExplorerToolbar": { "d238264654": "Git이 무시한 파일 표시", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 595230d78..6114335ad 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -4076,7 +4076,8 @@ "hostAuthNeeded": "需要身份验证", "hostDisconnected": "已断开连接", "failedNestWorkspace": "无法嵌套工作区", - "sidebarRowMissing": "目标不再存在" + "sidebarRowMissing": "目标不再存在", + "failedUnnestWorkspace": "Failed to unnest workspace" }, "WorktreeMetaDialog": { "3db0a2a593": "取消", @@ -8819,7 +8820,8 @@ "98a79948b3": "复制", "b234ab25b4": "无法将文件复制到剪贴板", "f9d7ca753d": "复制路径", - "3161c4e425": "文件夹" + "3161c4e425": "文件夹", + "e887fa4b2e": "在终端中打开" }, "FileExplorerToolbar": { "d238264654": "显示 Git 忽略的文件", diff --git a/src/renderer/src/runtime/web-runtime-session.test.ts b/src/renderer/src/runtime/web-runtime-session.test.ts index 2a03f5548..52fbcf4ff 100644 --- a/src/renderer/src/runtime/web-runtime-session.test.ts +++ b/src/renderer/src/runtime/web-runtime-session.test.ts @@ -480,6 +480,7 @@ describe('createWebRuntimeSessionTerminal', () => { afterTabId: 'web-terminal-host-tab-1%3A%3Aleaf-1', targetGroupId: 'group-left', command: "codex 'linked issue context'", + cwd: '/repo/packages/app', env: { CODEX_PROFILE: 'captured' }, startupCommandDelivery: 'shell-ready', launchConfig: { @@ -499,6 +500,7 @@ describe('createWebRuntimeSessionTerminal', () => { afterTabId: 'host-tab-1::leaf-1', targetGroupId: 'group-left', command: "codex 'linked issue context'", + cwd: '/repo/packages/app', env: { CODEX_PROFILE: 'captured' }, startupCommandDelivery: 'shell-ready', launchConfig: { diff --git a/src/renderer/src/runtime/web-runtime-session.ts b/src/renderer/src/runtime/web-runtime-session.ts index 14408a962..b2e14dd16 100644 --- a/src/renderer/src/runtime/web-runtime-session.ts +++ b/src/renderer/src/runtime/web-runtime-session.ts @@ -50,6 +50,7 @@ export async function createWebRuntimeSessionTerminal(args: { afterTabId?: string targetGroupId?: string command?: string + cwd?: string env?: Record startupCommandDelivery?: StartupCommandDelivery launchConfig?: SleepingAgentLaunchConfig @@ -78,6 +79,7 @@ export async function createWebRuntimeSessionTerminal(args: { afterTabId: args.afterTabId ? toHostSessionTabId(args.afterTabId) : undefined, targetGroupId: args.targetGroupId, command: args.command, + cwd: args.cwd, ...(args.env ? { env: args.env } : {}), startupCommandDelivery: args.startupCommandDelivery, ...(args.launchConfig ? { launchConfig: args.launchConfig } : {}), diff --git a/src/renderer/src/runtime/web-session-tabs-sync.test.ts b/src/renderer/src/runtime/web-session-tabs-sync.test.ts index b567654ea..be97ef98b 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.test.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.test.ts @@ -748,6 +748,7 @@ describe('applyWebSessionTabsSnapshot', () => { leafId: LEAF_ID, isActive: true, launchAgent: 'codex', + startupCwd: '/worktree/packages/web', status: 'ready', terminal: 'terminal-1' } @@ -765,6 +766,7 @@ describe('applyWebSessionTabsSnapshot', () => { id: mirroredId, ptyId: 'remote:web-env-1@@terminal-1', launchAgent: 'codex', + startupCwd: '/worktree/packages/web', title: 'host shell', worktreeId: WT } @@ -827,6 +829,48 @@ describe('applyWebSessionTabsSnapshot', () => { expect(patch.tabsByWorktree?.[WT]?.[0]?.launchAgent).toBeUndefined() }) + it('drops mirrored startup cwd when a later host snapshot omits it', () => { + const existingTab: TerminalTab = { + id: toWebTerminalSurfaceTabId('host-tab-1'), + ptyId: 'remote:web-env-1@@terminal-1', + worktreeId: WT, + title: 'zsh', + defaultTitle: 'zsh', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: NOW, + startupCwd: '/worktree/packages/web' + } + + const patch = applyWebSessionTabsSnapshot( + makeState({ + tabsByWorktree: { [WT]: [existingTab] }, + ptyIdsByTabId: { [existingTab.id]: ['remote:web-env-1@@terminal-1'] } + }), + makeSnapshot([ + { + type: 'terminal', + id: HOST_SURFACE_ID, + title: 'zsh', + parentTabId: 'host-tab-1', + leafId: LEAF_ID, + isActive: true, + status: 'ready', + terminal: 'terminal-1' + } + ]), + ENV, + NOW + 1 + ) as Partial + + expect(patch.tabsByWorktree?.[WT]?.[0]).toMatchObject({ + id: existingTab.id, + title: 'zsh' + }) + expect(patch.tabsByWorktree?.[WT]?.[0]?.startupCwd).toBeUndefined() + }) + it('adopts host viewMode when this client has no prior tab', () => { const patch = applyWebSessionTabsSnapshot( makeState(), diff --git a/src/renderer/src/runtime/web-session-tabs-sync.ts b/src/renderer/src/runtime/web-session-tabs-sync.ts index 5c6b4677c..8d0eba136 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync.ts @@ -547,6 +547,10 @@ function buildMirroredTerminalTabs( activeSurface.quickCommandLabel?.trim() || surfaces.find((surface) => surface.quickCommandLabel?.trim())?.quickCommandLabel?.trim() || existing?.quickCommandLabel?.trim() + // Why: startup cwd is host-owned launch metadata; once the host omits it, + // mirrored clients must not resurrect stale subdirectory intent. + const startupCwd = + activeSurface.startupCwd || surfaces.find((surface) => surface.startupCwd)?.startupCwd // Why: tab color/pin echo back through host snapshots, so prefer the client's // own record (kept authoritative in tabsByWorktree by the pin/color setters) // and fall back to the host value only when this client has no prior tab — @@ -570,6 +574,7 @@ function buildMirroredTerminalTabs( title, defaultTitle: existing?.defaultTitle ?? title, ...(quickCommandLabel ? { quickCommandLabel } : {}), + ...(startupCwd ? { startupCwd } : {}), customTitle: existing?.customTitle ?? null, color, isPinned, @@ -1386,6 +1391,7 @@ function terminalTabEqual(a: TerminalTab, b: TerminalTab): boolean { a.title === b.title && a.defaultTitle === b.defaultTitle && a.quickCommandLabel === b.quickCommandLabel && + a.startupCwd === b.startupCwd && a.generatedTitle === b.generatedTitle && a.customTitle === b.customTitle && a.color === b.color && diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts index 6412e2c19..9e2f89bc1 100644 --- a/src/renderer/src/store/slices/store-cascades.test.ts +++ b/src/renderer/src/store/slices/store-cascades.test.ts @@ -1146,6 +1146,30 @@ describe('setActiveWorktree', () => { ) }) + it('stores terminal startup cwd exactly and omits empty values', () => { + const store = createTestStore() + const wt = 'repo1::/path/wt1' + + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] + } + }) + + const nested = store + .getState() + .createTab(wt, undefined, undefined, { startupCwd: '/path/wt1/packages/app ' }) + const empty = store.getState().createTab(wt, undefined, undefined, { startupCwd: '' }) + const state = store.getState() + + expect(state.tabsByWorktree[wt].find((tab) => tab.id === nested.id)?.startupCwd).toBe( + '/path/wt1/packages/app ' + ) + expect(state.tabsByWorktree[wt].find((tab) => tab.id === empty.id)).not.toHaveProperty( + 'startupCwd' + ) + }) + it('stamps the Windows default shell onto new terminal tabs', () => { const originalNavigator = globalThis.navigator Object.defineProperty(globalThis, 'navigator', { diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 559e06106..0e6f30dde 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -440,6 +440,7 @@ export type TerminalSlice = { * `'chat'` so the tab opens in the native chat view; omitted otherwise * so the tab keeps the implicit `'terminal'` default. */ viewMode?: Tab['viewMode'] + startupCwd?: string } ) => TerminalTab openNewTerminalTabInActiveWorkspace: (groupId: string) => Promise @@ -764,6 +765,7 @@ export const createTerminalSlice: StateCreator const nextOrdinal = getNextTerminalOrdinal(existing) const defaultTitle = `Terminal ${nextOrdinal}` const quickCommandLabel = options?.quickCommandLabel?.trim() + const startupCwd = options?.startupCwd const remoteConnectionId = getRemoteConnectionIdForWorktree(s, worktreeId) const isRemoteWorktree = Boolean(remoteConnectionId) const isWslWorktree = worktreeUsesWslPath(s, worktreeId) @@ -800,6 +802,7 @@ export const createTerminalSlice: StateCreator sortOrder: existing.length, createdAt: Date.now(), ...(createdShellOverride !== undefined ? { shellOverride: createdShellOverride } : {}), + ...(startupCwd && startupCwd.length > 0 ? { startupCwd } : {}), ...(options?.launchAgent ? { launchAgent: options.launchAgent } : {}), // Why: when Terminal.tsx's activation fallback auto-creates a tab for a // first-visit worktree, the resulting PTY spawn is caused by the user diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index bcd916c01..66f28e7ea 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -135,6 +135,7 @@ export type RuntimeMobileSessionTerminalTab = { terminalTheme?: RuntimeMobileTerminalTheme agentStatus?: AgentStatusEntry | null launchAgent?: TuiAgent + startupCwd?: string parentLayout?: TerminalLayoutSnapshot /** Tab-level color/pin (per parentTabId), host-persisted for remote servers. */ color?: string | null @@ -463,6 +464,7 @@ type RuntimeTerminalCreateBaseRequestPayload = { afterTabId?: string targetGroupId?: string command?: string + cwd?: string env?: Record launchConfig?: SleepingAgentLaunchConfig launchToken?: string diff --git a/src/shared/terminal-startup-cwd.test.ts b/src/shared/terminal-startup-cwd.test.ts new file mode 100644 index 000000000..e6ac5575c --- /dev/null +++ b/src/shared/terminal-startup-cwd.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'vitest' +import { + resolveTerminalStartupCwd, + resolveTerminalStartupCwdForWorkspace +} from './terminal-startup-cwd' +import { folderWorkspaceKey } from './workspace-scope' + +describe('resolveTerminalStartupCwd', () => { + it('accepts absolute child paths inside the worktree', () => { + expect(resolveTerminalStartupCwd('/repo/app', '/repo/app/packages/web')).toBe( + '/repo/app/packages/web' + ) + }) + + it('resolves relative paths against the worktree', () => { + expect(resolveTerminalStartupCwd('/repo/app', 'packages/web')).toBe('/repo/app/packages/web') + }) + + it('rejects sibling paths outside the worktree', () => { + expect(() => resolveTerminalStartupCwd('/repo/app', '/repo/app-other')).toThrow( + 'Terminal cwd must be inside the selected worktree.' + ) + }) + + it('rejects parent traversal outside the worktree', () => { + expect(() => resolveTerminalStartupCwd('/repo/app', '../other')).toThrow( + 'Terminal cwd must be inside the selected worktree.' + ) + }) + + it('handles Windows path containment without case drift', () => { + expect(resolveTerminalStartupCwd('C:\\Repo\\App', 'packages\\web')).toBe( + 'C:/Repo/App/packages/web' + ) + expect(() => resolveTerminalStartupCwd('C:\\Repo\\App', 'C:\\Repo\\AppOther')).toThrow( + 'Terminal cwd must be inside the selected worktree.' + ) + }) + + it('validates renderer PTY cwd values against raw worktree IDs', () => { + expect( + resolveTerminalStartupCwdForWorkspace({ + workspaceId: 'repo-1::/repo/app', + requestedCwd: '/repo/app/packages/web' + }) + ).toBe('/repo/app/packages/web') + expect(() => + resolveTerminalStartupCwdForWorkspace({ + workspaceId: 'repo-1::/repo/app', + requestedCwd: '/repo/app-other' + }) + ).toThrow('Terminal cwd must be inside the selected worktree.') + }) + + it('validates renderer PTY cwd values against folder workspace keys', () => { + expect( + resolveTerminalStartupCwdForWorkspace({ + workspaceId: folderWorkspaceKey('folder-1'), + requestedCwd: 'packages/web', + resolveFolderWorkspacePath: (id) => (id === 'folder-1' ? '/repo/app' : null) + }) + ).toBe('/repo/app/packages/web') + expect(() => + resolveTerminalStartupCwdForWorkspace({ + workspaceId: folderWorkspaceKey('folder-1'), + requestedCwd: '../other', + resolveFolderWorkspacePath: (id) => (id === 'folder-1' ? '/repo/app' : null) + }) + ).toThrow('Terminal cwd must be inside the selected worktree.') + }) +}) diff --git a/src/shared/terminal-startup-cwd.ts b/src/shared/terminal-startup-cwd.ts new file mode 100644 index 000000000..d71a0f7c3 --- /dev/null +++ b/src/shared/terminal-startup-cwd.ts @@ -0,0 +1,52 @@ +import { isPathInsideOrEqual, resolveRuntimePath } from './cross-platform-path' +import { parseWorkspaceKey } from './workspace-scope' +import { splitWorktreeIdForFilesystem } from './worktree-id' + +export function resolveTerminalStartupCwd( + worktreePath: string, + requestedCwd?: string | null +): string | undefined { + if (!requestedCwd || requestedCwd.trim().length === 0) { + return undefined + } + const resolvedCwd = resolveRuntimePath(worktreePath, requestedCwd) + if (!isPathInsideOrEqual(worktreePath, resolvedCwd)) { + // Why: remote/session clients can request terminal cwd; never let that + // become a shell outside the selected workspace. + throw new Error('Terminal cwd must be inside the selected worktree.') + } + return resolvedCwd +} + +export function resolveTerminalStartupCwdForWorkspace(args: { + workspaceId?: string + requestedCwd?: string | null + resolveFolderWorkspacePath?: (folderWorkspaceId: string) => string | null | undefined +}): string | undefined { + if (!args.requestedCwd || args.requestedCwd.trim().length === 0) { + return undefined + } + const workspacePath = resolveTerminalWorkspacePath( + args.workspaceId, + args.resolveFolderWorkspacePath + ) + if (!workspacePath) { + return args.requestedCwd + } + return resolveTerminalStartupCwd(workspacePath, args.requestedCwd) +} + +function resolveTerminalWorkspacePath( + workspaceId: string | undefined, + resolveFolderWorkspacePath: ((folderWorkspaceId: string) => string | null | undefined) | undefined +): string | null { + if (!workspaceId) { + return null + } + const scope = parseWorkspaceKey(workspaceId) + if (scope?.type === 'folder') { + return resolveFolderWorkspacePath?.(scope.folderWorkspaceId) ?? null + } + const worktreeId = scope?.type === 'worktree' ? scope.worktreeId : workspaceId + return splitWorktreeIdForFilesystem(worktreeId)?.worktreePath ?? null +} diff --git a/src/shared/types.ts b/src/shared/types.ts index d7ff1547d..e403caba2 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -836,6 +836,9 @@ export type TerminalTab = { * PTY and tab icon stay stable even if the default shell setting changes * later. Older persisted tabs may omit this field. */ shellOverride?: string + /** Why: explorer-created terminals can start below the workspace root while + * still belonging to that workspace for tab/session ownership. */ + startupCwd?: string /** Why: the coding-harness agent Orca launched in this tab. Lets the tab bar * show the provider icon immediately, before the agent emits its first hook * event (a freshly-launched, idle agent reports no live status yet). Live diff --git a/src/shared/workspace-session-schema.ts b/src/shared/workspace-session-schema.ts index 15ed90471..d58f6ddb3 100644 --- a/src/shared/workspace-session-schema.ts +++ b/src/shared/workspace-session-schema.ts @@ -78,6 +78,7 @@ const terminalTabSchema = z.object({ sortOrder: z.number(), createdAt: z.number(), generation: z.number().optional(), + startupCwd: z.string().min(1).optional(), // Why: persist the launched agent so a restored idle agent tab keeps its // provider icon before any hook fires. `.catch(undefined)` keeps a stale or // unknown agent id from failing the whole-session parse (which would reset diff --git a/src/shared/workspace-session-terminal-schema.test.ts b/src/shared/workspace-session-terminal-schema.test.ts new file mode 100644 index 000000000..367ee953f --- /dev/null +++ b/src/shared/workspace-session-terminal-schema.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import { parseWorkspaceSession } from './workspace-session-schema' + +describe('parseWorkspaceSession terminal fields', () => { + it('preserves terminal startup cwd while accepting older omitted fields', () => { + const result = parseWorkspaceSession({ + activeRepoId: null, + activeWorktreeId: 'wt', + activeTabId: 'tab1', + tabsByWorktree: { + wt: [ + { + id: 'tab1', + ptyId: null, + worktreeId: 'wt', + title: 'Terminal 1', + defaultTitle: 'Terminal 1', + startupCwd: '/repo/packages/app', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0 + }, + { + id: 'tab2', + ptyId: null, + worktreeId: 'wt', + title: 'Terminal 2', + customTitle: null, + color: null, + sortOrder: 1, + createdAt: 1 + } + ] + }, + terminalLayoutsByTabId: {} + }) + + expect(result.ok).toBe(true) + if (result.ok) { + expect(result.value.tabsByWorktree.wt[0].startupCwd).toBe('/repo/packages/app') + expect(result.value.tabsByWorktree.wt[1].startupCwd).toBeUndefined() + } + }) + + it('rejects empty terminal startup cwd values', () => { + const result = parseWorkspaceSession({ + activeRepoId: null, + activeWorktreeId: 'wt', + activeTabId: 'tab1', + tabsByWorktree: { + wt: [ + { + id: 'tab1', + ptyId: null, + worktreeId: 'wt', + title: 'Terminal 1', + defaultTitle: 'Terminal 1', + startupCwd: '', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0 + } + ] + }, + terminalLayoutsByTabId: {} + }) + + expect(result.ok).toBe(false) + }) +})