diff --git a/src/main/ipc/app.ts b/src/main/ipc/app.ts index 59b672d19..486f213ad 100644 --- a/src/main/ipc/app.ts +++ b/src/main/ipc/app.ts @@ -1,4 +1,5 @@ import { app, ipcMain } from 'electron' +import { isWslAvailable } from '../wsl' export type AppRuntimeFlags = { /** Whether the persistent terminal daemon was actually started this session. @@ -39,6 +40,8 @@ export function registerAppHandlers(): void { return notice }) + ipcMain.handle('wsl:isAvailable', (): boolean => isWslAvailable()) + ipcMain.handle('app:relaunch', () => { // Why: small delay lets the renderer finish painting any "Restarting…" // UI state before the window tears down. `app.relaunch()` schedules a diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 8a9b9debf..429fdd626 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -474,6 +474,7 @@ export function registerPtyHandlers( connectionId?: string | null worktreeId?: string sessionId?: string + shellOverride?: string } ) => { const provider = getProvider(args.connectionId) @@ -559,6 +560,9 @@ export function registerPtyHandlers( if (effectiveSessionId !== undefined) { spawnOptions.sessionId = effectiveSessionId } + if (args.shellOverride !== undefined) { + spawnOptions.shellOverride = args.shellOverride + } const result = await provider.spawn(spawnOptions) ptyOwnership.set(result.id, args.connectionId ?? null) if (isClaudeLaunch) { diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 033a4c7a8..ef18fe6c0 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -5,7 +5,7 @@ files without a cleaner ownership seam. */ import { basename, win32 as pathWin32 } from 'path' import { existsSync } from 'fs' import * as pty from 'node-pty' -import { parseWslPath } from '../wsl' +import { parseWslPath, isWslAvailable } from '../wsl' import { injectHistoryEnv, updateHistFileForFallback, @@ -134,7 +134,10 @@ export class LocalPtyProvider implements IPtyProvider { effectiveCwd = getDefaultCwd() validationCwd = cwd } else if (process.platform === 'win32') { - shellPath = this.opts.getWindowsShell?.() || process.env.COMSPEC || 'powershell.exe' + // Why: shellOverride lets a single tab open in a different shell than the + // persisted default (e.g. "New WSL terminal" from the "+" submenu) without + // changing the user's setting. It takes priority over the setting. + shellPath = args.shellOverride || this.opts.getWindowsShell?.() || process.env.COMSPEC || 'powershell.exe' // Why: use path.win32.basename so backslash-separated Windows paths // are parsed correctly even when tests mock process.platform on Linux CI. const shellBasename = pathWin32.basename(shellPath).toLowerCase() @@ -146,6 +149,8 @@ export class LocalPtyProvider implements IPtyProvider { // byte sequences are misinterpreted as UTF-8. if (shellBasename === 'cmd.exe') { shellArgs = ['/K', 'chcp 65001 > nul'] + effectiveCwd = cwd + validationCwd = cwd } else if (shellBasename === 'powershell.exe' || shellBasename === 'pwsh.exe') { // Why: `-NoExit -Command` alone skips the user's $PROFILE, breaking // custom prompts (oh-my-posh, starship), aliases, and PSReadLine @@ -156,11 +161,27 @@ export class LocalPtyProvider implements IPtyProvider { '-Command', 'try { . $PROFILE } catch {}; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; [Console]::InputEncoding = [System.Text.Encoding]::UTF8' ] + effectiveCwd = cwd + validationCwd = cwd + } else if (shellBasename === 'wsl.exe') { + // Why: this branch handles the "user chose WSL as their shell" case, + // distinct from the wslInfo branch above which is for repos whose cwd + // lives on a WSL filesystem. Here the cwd is a normal Windows path, so + // we translate it to a Linux /mnt//... path and open a login + // bash in the user's default distro (no -d flag = default distro). + const driveMatch = cwd.replace(/\\/g, '/').match(/^([A-Za-z]):\/?(.*)$/) + const linuxCwd = driveMatch + ? `/mnt/${driveMatch[1].toLowerCase()}/${driveMatch[2]}` + : '/mnt/c' + const escapedLinuxCwd = linuxCwd.replace(/'/g, "'\\''") + shellArgs = ['--', 'bash', '-c', `cd '${escapedLinuxCwd}' && exec bash -l`] + effectiveCwd = getDefaultCwd() + validationCwd = cwd } else { shellArgs = [] + effectiveCwd = cwd + validationCwd = cwd } - effectiveCwd = cwd - validationCwd = cwd } else { shellPath = args.env?.SHELL || process.env.SHELL || '/bin/zsh' shellArgs = ['-l'] @@ -465,10 +486,14 @@ export class LocalPtyProvider implements IPtyProvider { async getProfiles(): Promise<{ name: string; path: string }[]> { if (process.platform === 'win32') { - return [ + const profiles: { name: string; path: string }[] = [ { name: 'PowerShell', path: 'powershell.exe' }, { name: 'Command Prompt', path: 'cmd.exe' } ] + if (isWslAvailable()) { + profiles.push({ name: 'WSL', path: 'wsl.exe' }) + } + return profiles } const shells = ['/bin/zsh', '/bin/bash', '/bin/sh'] return shells.filter((s) => existsSync(s)).map((s) => ({ name: basename(s), path: s })) diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 2ab00b507..3125ba797 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -25,6 +25,11 @@ export type PtySpawnOptions = { /** Daemon session ID for reattach. When provided, the daemon reconnects * to an existing session instead of creating a new one. */ sessionId?: string + /** Why: allows the renderer to request a specific shell for a single new + * terminal tab (e.g. "open this tab in WSL" from the "+" submenu) without + * changing the user's persistent default shell setting. Only consulted on + * Windows; ignored on macOS/Linux where shell selection is not exposed. */ + shellOverride?: string } export type PtySpawnResult = { diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 7ba28ac44..ab27b4fa4 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -53,6 +53,10 @@ type WorktreesApi = { onChanged: (callback: (data: { repoId: string }) => void) => () => void } +type WslApi = { + isAvailable: () => Promise +} + type PtyApi = { spawn: (opts: { cols: number @@ -63,6 +67,7 @@ type PtyApi = { connectionId?: string | null worktreeId?: string sessionId?: string + shellOverride?: string }) => Promise<{ id: string snapshot?: string @@ -228,6 +233,7 @@ type Api = PreloadApi & { notifications: NotificationsApi shell: ShellApi agentStatus: AgentStatusApi + wsl: WslApi } declare global { diff --git a/src/preload/index.ts b/src/preload/index.ts index f84a51ece..e5ae856a8 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -177,6 +177,10 @@ const api = { relaunch: (): Promise => ipcRenderer.invoke('app:relaunch') }, + wsl: { + isAvailable: (): Promise => ipcRenderer.invoke('wsl:isAvailable') + }, + repos: { list: (): Promise => ipcRenderer.invoke('repos:list'), @@ -281,6 +285,7 @@ const api = { connectionId?: string | null worktreeId?: string sessionId?: string + shellOverride?: string }): Promise<{ id: string snapshot?: string diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 8d052a41d..428fe8576 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -123,6 +123,14 @@ function Terminal(): React.JSX.Element | null { ? (browserTabsByWorktree[activeWorktreeId] ?? []).map((tab) => tab.id).join(',') : '' + const [wslAvailable, setWslAvailable] = useState(false) + useEffect(() => { + // Why: wsl:isAvailable is synchronous on the main-process side but we + // call it asynchronously so the renderer doesn't block on startup. The + // result only gates UI options, so a brief false→true transition is fine. + void window.api.wsl.isAvailable().then(setWslAvailable) + }, []) + // Save confirmation dialog state const [saveDialogFileId, setSaveDialogFileId] = useState(null) const saveDialogFile = saveDialogFileId ? openFiles.find((f) => f.id === saveDialogFileId) : null @@ -355,38 +363,41 @@ function Terminal(): React.JSX.Element | null { createTab(activeWorktreeId) }, [workspaceSessionReady, activeWorktreeId, createTab, reconcileWorktreeTabModel]) - const handleNewTab = useCallback(() => { - if (!activeWorktreeId) { - return - } - const newTab = createTab(activeWorktreeId) - setActiveTabType('terminal') - // Why: persist the tab bar order with the new terminal at the end of the - // current visual order. Without this, reconcileOrder falls back to - // terminals-first when tabBarOrderByWorktree is unset, causing a new - // terminal to jump to index 0 instead of appending after editor tabs. - const state = useAppStore.getState() - const currentTerminals = state.tabsByWorktree[activeWorktreeId] ?? [] - const currentEditors = state.openFiles.filter((f) => f.worktreeId === activeWorktreeId) - const currentBrowsers = state.browserTabsByWorktree[activeWorktreeId] ?? [] - const stored = state.tabBarOrderByWorktree[activeWorktreeId] - const termIds = currentTerminals.map((t) => t.id) - const editorIds = currentEditors.map((f) => f.id) - const browserIds = currentBrowsers.map((tab) => tab.id) - const validIds = new Set([...termIds, ...editorIds, ...browserIds]) - const base = (stored ?? []).filter((id) => validIds.has(id)) - const inBase = new Set(base) - for (const id of [...termIds, ...editorIds, ...browserIds]) { - if (!inBase.has(id)) { - base.push(id) - inBase.add(id) + const handleNewTab = useCallback( + (shellOverride?: string) => { + if (!activeWorktreeId) { + return } - } - // The new tab is already in base via termIds; move it to the end - const order = base.filter((id) => id !== newTab.id) - order.push(newTab.id) - setTabBarOrder(activeWorktreeId, order) - }, [activeWorktreeId, createTab, setActiveTabType, setTabBarOrder]) + const newTab = createTab(activeWorktreeId, undefined, shellOverride) + setActiveTabType('terminal') + // Why: persist the tab bar order with the new terminal at the end of the + // current visual order. Without this, reconcileOrder falls back to + // terminals-first when tabBarOrderByWorktree is unset, causing a new + // terminal to jump to index 0 instead of appending after editor tabs. + const state = useAppStore.getState() + const currentTerminals = state.tabsByWorktree[activeWorktreeId] ?? [] + const currentEditors = state.openFiles.filter((f) => f.worktreeId === activeWorktreeId) + const currentBrowsers = state.browserTabsByWorktree[activeWorktreeId] ?? [] + const stored = state.tabBarOrderByWorktree[activeWorktreeId] + const termIds = currentTerminals.map((t) => t.id) + const editorIds = currentEditors.map((f) => f.id) + const browserIds = currentBrowsers.map((tab) => tab.id) + const validIds = new Set([...termIds, ...editorIds, ...browserIds]) + const base = (stored ?? []).filter((id) => validIds.has(id)) + const inBase = new Set(base) + for (const id of [...termIds, ...editorIds, ...browserIds]) { + if (!inBase.has(id)) { + base.push(id) + inBase.add(id) + } + } + // The new tab is already in base via termIds; move it to the end + const order = base.filter((id) => id !== newTab.id) + order.push(newTab.id) + setTabBarOrder(activeWorktreeId, order) + }, + [activeWorktreeId, createTab, setActiveTabType, setTabBarOrder] + ) const handleNewBrowserTab = useCallback(() => { if (!activeWorktreeId) { @@ -955,9 +966,11 @@ function Terminal(): React.JSX.Element | null { onClose={handleCloseTab} onCloseOthers={handleCloseOthers} onCloseToRight={handleCloseTabsToRight} - onNewTerminalTab={handleNewTab} + onNewTerminalTab={() => handleNewTab()} + onNewTerminalWithShell={handleNewTab} onNewBrowserTab={handleNewBrowserTab} onNewFileTab={handleNewFile} + wslAvailable={wslAvailable} onSetCustomTitle={setTabCustomTitle} onSetTabColor={setTabColor} expandedPaneByTabId={expandedPaneByTabId} diff --git a/src/renderer/src/components/settings/Settings.tsx b/src/renderer/src/components/settings/Settings.tsx index 7aead6d73..6f29c0f23 100644 --- a/src/renderer/src/components/settings/Settings.tsx +++ b/src/renderer/src/components/settings/Settings.tsx @@ -143,6 +143,10 @@ function Settings(): React.JSX.Element { // the import trigger as a headerAction. The modal itself still lives inside // TerminalPane, driven by this shared state. const ghostty = useGhosttyImport(updateSettings, settings) + const [wslAvailable, setWslAvailable] = useState(false) + useEffect(() => { + void window.api.wsl.isAvailable().then(setWslAvailable) + }, []) const [terminalFontSuggestions, setTerminalFontSuggestions] = useState( getFallbackTerminalFonts() ) @@ -622,6 +626,7 @@ function Settings(): React.JSX.Element { scrollbackMode={scrollbackMode} setScrollbackMode={setScrollbackMode} ghostty={ghostty} + wslAvailable={wslAvailable} /> diff --git a/src/renderer/src/components/settings/TerminalPane.tsx b/src/renderer/src/components/settings/TerminalPane.tsx index d3c728dd4..9449bea76 100644 --- a/src/renderer/src/components/settings/TerminalPane.tsx +++ b/src/renderer/src/components/settings/TerminalPane.tsx @@ -62,6 +62,8 @@ type TerminalPaneProps = { * the section header can render the trigger button as a headerAction * instead of taking its own row inside the settings list. */ ghostty: UseGhosttyImportReturn + /** Whether WSL is installed on this Windows machine. */ + wslAvailable?: boolean } export function TerminalPane({ @@ -71,7 +73,8 @@ export function TerminalPane({ terminalFontSuggestions, scrollbackMode, setScrollbackMode, - ghostty + ghostty, + wslAvailable }: TerminalPaneProps): React.JSX.Element { const searchQuery = useAppStore((state) => state.settingsSearchQuery) const isWindows = isWindowsUserAgent() @@ -122,12 +125,11 @@ export function TerminalPane({ >
- {( - [ - { label: 'PowerShell', value: 'powershell.exe' }, - { label: 'Command Prompt', value: 'cmd.exe' } - ] as const - ).map(({ label, value }) => ( + {[ + { label: 'PowerShell', value: 'powershell.exe' }, + { label: 'Command Prompt', value: 'cmd.exe' }, + ...(wslAvailable ? [{ label: 'WSL', value: 'wsl.exe' }] : []) + ].map(({ label, value }) => (