diff --git a/src/main/agent-launch/agent-launch-mode.ts b/src/main/agent-launch/agent-launch-mode.ts index e9b814884d6..b796f4c3888 100644 --- a/src/main/agent-launch/agent-launch-mode.ts +++ b/src/main/agent-launch/agent-launch-mode.ts @@ -23,6 +23,10 @@ import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { AgentLaunchSurface } from '../../shared/agent-launch/contracts/agent-launch-surface' import { formatAgentTypeLabel } from '../../shared/agent-status/presentation/agent-type-label' import { AgentLaunchSurfaceUnavailableError } from './agent-launch-surface-refusal' +import { + withWslHostChatRecovery, + type WslHostChatSettingsSource +} from './agent-launch-wsl-host-recovery' type AgentLaunchDowngradeReason = Exclude @@ -168,7 +172,8 @@ export function decideAgentLaunchMode(args: { /** Refuse explicit chat only before effects; a created workspace keeps its terminal fallback. */ export async function resolveAgentLaunchModeOnHost( - runtime: Pick, + runtime: Pick & + WslHostChatSettingsSource, receipt: AgentLaunchModeReceipt, worktreeId: string | undefined, agent: TuiAgent | undefined, @@ -190,12 +195,13 @@ export async function resolveAgentLaunchModeOnHost( launchCwdRelation(context) === 'custom' ) } - return downgradeAgentLaunchModeForHost( - receipt, - await readStructuredCreateSupport(runtime, worktreeId, agent), - vocabulary, - context ? { ...context, agent } : undefined - ) + const support = await readStructuredCreateSupport(runtime, worktreeId, agent) + const settlement = context ? { ...context, agent } : undefined + try { + return downgradeAgentLaunchModeForHost(receipt, support, vocabulary, settlement) + } catch (error) { + throw await withWslHostChatRecovery(error, context?.workspacePath, runtime) + } } /** Unknown host support must fall back to a terminal. */ @@ -282,7 +288,8 @@ function unavailableLaunchMode( ): AgentLaunchModeReceipt { if (requested && conclusive && context?.phase === 'before-effects') { throw new AgentLaunchSurfaceUnavailableError( - `${formatAgentTypeLabel(context.agent)} can't open as a chat here because ${DOWNGRADE_DETAIL[reason]}. Start it in a terminal instead.` + `${formatAgentTypeLabel(context.agent)} can't open as a chat here because ${DOWNGRADE_DETAIL[reason]}. Start it in a terminal instead.`, + reason ) } return downgraded(reason, vocabulary, requested) diff --git a/src/main/agent-launch/agent-launch-surface-refusal.ts b/src/main/agent-launch/agent-launch-surface-refusal.ts index 1ab5aeac97d..eb52e009115 100644 --- a/src/main/agent-launch/agent-launch-surface-refusal.ts +++ b/src/main/agent-launch/agent-launch-surface-refusal.ts @@ -3,7 +3,13 @@ import { OrchestrationError } from '../runtime/orchestration/orchestration-error /** Proves no launch effects occurred, so replay may return the same definitive refusal. */ export class AgentLaunchSurfaceUnavailableError extends OrchestrationError { - constructor(message: string) { - super(AGENT_LAUNCH_SURFACE_UNAVAILABLE_CODE, message) + /** `data` adds recovery (`nextSteps`) only; the code and message stay what older clients match. */ + constructor( + message: string, + /** Why the chat can't open, so a caller can add the recovery that fits it. */ + readonly reason?: string, + data?: Record + ) { + super(AGENT_LAUNCH_SURFACE_UNAVAILABLE_CODE, message, data) } } diff --git a/src/main/agent-launch/agent-launch-wsl-host-recovery.test.ts b/src/main/agent-launch/agent-launch-wsl-host-recovery.test.ts new file mode 100644 index 00000000000..13c7b0f3d0a --- /dev/null +++ b/src/main/agent-launch/agent-launch-wsl-host-recovery.test.ts @@ -0,0 +1,128 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +type ServiceFake = { + hasServerFiles: () => boolean + isKnownDistro: (distro: string) => Promise +} + +const host = vi.hoisted( + (): { acceptsNewWork: boolean; settingOn: boolean; service: ServiceFake | null } => ({ + acceptsNewWork: true, + settingOn: false, + service: null + }) +) +vi.mock('../wsl/host-lifecycle/wsl-host-gate', () => ({ + wslHostsAcceptNewWork: () => host.acceptsNewWork +})) +vi.mock('../wsl/host-lifecycle/wsl-host-service-instance', () => ({ + getWslHostService: () => host.service +})) + +import { resolveAgentLaunchModeOnHost } from './agent-launch-mode' +import { AgentLaunchSurfaceUnavailableError } from './agent-launch-surface-refusal' +import { wslHostChatRecovery } from './agent-launch-wsl-host-recovery' + +const requestedChat = { + mode: 'structured', + preferred: 'structured', + reason: 'requested', + detail: 'Started a structured chat session, as requested.' +} as const + +const UBUNTU_REPO = '\\\\wsl.localhost\\Ubuntu-24.04\\home\\me\\repo' + +async function refuse(reason: 'wsl' | 'remote', workspacePath: string): Promise { + const runtime = { + getStructuredAgentSessionCreateSupport: async () => ({ supported: false, reason }), + requireStore: () => ({ getSettings: () => ({ experimentalWslHosts: host.settingOn }) }) + } + return resolveAgentLaunchModeOnHost(runtime, requestedChat, 'repo::path', 'claude', undefined, { + phase: 'before-effects', + agent: 'claude', + workspacePath + }).then( + () => { + throw new Error('expected a refusal') + }, + (error: unknown) => error + ) +} + +function facts(settingOn: boolean, hostAdded: boolean) { + return async () => ({ settingOn, hostAdded }) +} + +describe('WSL chat refusal recovery', () => { + beforeEach(() => { + host.acceptsNewWork = true + host.settingOn = false + host.service = { + hasServerFiles: () => true, + isKnownDistro: async () => false + } + }) + + it('points a WSL folder at a WSL host for its distro when hosts can be added', async () => { + const error = await refuse('wsl', UBUNTU_REPO) + expect(error).toBeInstanceOf(AgentLaunchSurfaceUnavailableError) + // Older clients match the code and message, so both stay as they were. + expect(error).toMatchObject({ + code: 'agent_launch_surface_unavailable', + message: + "Claude can't open as a chat here because this workspace runs under WSL. Start it in a terminal instead.", + data: { + wslDistro: 'Ubuntu-24.04', + nextSteps: [ + expect.stringMatching( + /turn on Settings → Experimental → WSL hosts, then add Ubuntu-24\.04 as a host.*then choose “Move to Ubuntu-24\.04 host…”/ + ), + expect.stringContaining('--surface terminal') + ] + } + }) + }) + + it('keeps the plain refusal while WSL hosts cannot take new work', async () => { + host.acceptsNewWork = false + expect(await refuse('wsl', UBUNTU_REPO)).toMatchObject({ data: undefined }) + host.acceptsNewWork = true + host.service = { + hasServerFiles: () => false, + isKnownDistro: async () => false + } + expect(await refuse('wsl', UBUNTU_REPO)).toMatchObject({ data: undefined }) + host.service = null + expect(await refuse('wsl', UBUNTU_REPO)).toMatchObject({ data: undefined }) + }) + + it('adds no WSL host steps to other refusals', async () => { + expect(await refuse('remote', UBUNTU_REPO)).toMatchObject({ data: undefined }) + }) + + it('offers no move for a Windows drive reached through the distro', async () => { + expect(await refuse('wsl', '\\\\wsl.localhost\\Ubuntu\\mnt\\c\\repo')).toMatchObject({ + data: undefined + }) + }) + + it('says only the move once the distro is a host and the setting is on', async () => { + host.settingOn = true + host.service = { hasServerFiles: () => true, isKnownDistro: async () => true } + const error = await refuse('wsl', UBUNTU_REPO) + expect(error).toMatchObject({ data: { nextSteps: [expect.any(String), expect.any(String)] } }) + const recovery = await wslHostChatRecovery(UBUNTU_REPO, facts(true, true)) + expect(error).toMatchObject({ data: recovery }) + expect(recovery?.nextSteps[0]).toBe( + 'Chat works when the project runs on the Ubuntu-24.04 WSL host. In Orca, choose “Move to Ubuntu-24.04 host…” on the project in the sidebar, then launch the chat there.' + ) + }) + + it('skips the add for a saved host while the setting is off', async () => { + const recovery = await wslHostChatRecovery(UBUNTU_REPO, facts(false, true)) + expect(recovery?.nextSteps[0]).toContain( + 'turn on Settings → Experimental → WSL hosts, then choose' + ) + expect(recovery?.nextSteps[0]).not.toContain('Add WSL distro') + }) +}) diff --git a/src/main/agent-launch/agent-launch-wsl-host-recovery.ts b/src/main/agent-launch/agent-launch-wsl-host-recovery.ts new file mode 100644 index 00000000000..22ffba433c0 --- /dev/null +++ b/src/main/agent-launch/agent-launch-wsl-host-recovery.ts @@ -0,0 +1,84 @@ +/** What a chat refused in a Windows-opened WSL folder can do instead: run it on a WSL host. */ + +import { wslHostMovableDistroOfPath } from '../../shared/file-access/wsl-paths' +import { wslHostsAcceptNewWork } from '../wsl/host-lifecycle/wsl-host-gate' +import { getWslHostService } from '../wsl/host-lifecycle/wsl-host-service-instance' +import { AgentLaunchSurfaceUnavailableError } from './agent-launch-surface-refusal' + +export type WslHostChatFacts = { settingOn: boolean; hostAdded: boolean } + +export type WslHostChatRecovery = { wslDistro: string; nextSteps: string[] } + +/** Read only to word a WSL refusal's next steps. */ +export type WslHostChatSettingsSource = { requireStore?: () => { getSettings(): object | null } } + +function readWslHostsSettingOn(source: WslHostChatSettingsSource): boolean { + try { + const settings = source.requireStore?.().getSettings() + return ( + !!settings && 'experimentalWslHosts' in settings && settings.experimentalWslHosts === true + ) + } catch { + return false + } +} + +/** Null where this launch can't add WSL hosts, which the renderer's offer also requires. */ +function wslHostChatFactsReader( + settingOn: () => boolean +): (distro: string) => Promise { + return async (distro) => { + const service = getWslHostService() + if (!service || !wslHostsAcceptNewWork() || !service.hasServerFiles()) { + return null + } + return { settingOn: settingOn(), hostAdded: await service.isKnownDistro(distro) } + } +} + +/** Null for a Windows drive reached through the distro, or while WSL hosts can't be added. */ +export async function wslHostChatRecovery( + workspacePath: string | undefined, + readFacts: (distro: string) => Promise +): Promise { + const distro = workspacePath ? wslHostMovableDistroOfPath(workspacePath) : null + const facts = distro ? await readFacts(distro) : null + if (!distro || !facts) { + return null + } + const move = `choose “Move to ${distro} host…” on the project in the sidebar, then launch the chat there.` + const setup = [ + ...(facts.settingOn ? [] : ['turn on Settings → Experimental → WSL hosts']), + ...(facts.hostAdded + ? [] + : [`add ${distro} as a host (Add a project → Add remote host → Add WSL distro)`]) + ] + return { + wslDistro: distro, + nextSteps: [ + `Chat works when the project runs on the ${distro} WSL host. In Orca, ${[...setup, move].join(', then ')}`, + 'Or run the same command with --surface terminal to start the agent in a terminal.' + ] + } +} + +/** Adds the WSL host path to a WSL refusal; any other error passes through unchanged. */ +export async function withWslHostChatRecovery( + error: unknown, + workspacePath: string | undefined, + settings: WslHostChatSettingsSource +): Promise { + if ( + !(error instanceof AgentLaunchSurfaceUnavailableError) || + error.reason !== 'wsl_execution_runtime' + ) { + return error + } + const recovery = await wslHostChatRecovery( + workspacePath, + wslHostChatFactsReader(() => readWslHostsSettingOn(settings)) + ).catch(() => null) + return recovery + ? new AgentLaunchSurfaceUnavailableError(error.message, error.reason, recovery) + : error +} diff --git a/src/renderer/src/components/native-chat/messages/notices/native-chat-structured-session-notices.ts b/src/renderer/src/components/native-chat/messages/notices/native-chat-structured-session-notices.ts index 49a8ebb111a..75972063b8e 100644 --- a/src/renderer/src/components/native-chat/messages/notices/native-chat-structured-session-notices.ts +++ b/src/renderer/src/components/native-chat/messages/notices/native-chat-structured-session-notices.ts @@ -4,6 +4,11 @@ import type { Translate } from '@/i18n/use-translate' import type { StructuredAgentSessionLaunchLifecycle } from '@/lib/agent-session/launch/structured-agent-session-launch-registry' import { agentSessionRefusalCauseParts } from '../../../../../../shared/agent-session/failures/agent-session-refusal-notice' import type { StructuredLaunchFailure } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' +import { + wslHostChatOfferAction, + wslHostChatOfferText, + type WslHostChatOffer +} from '@/lib/agent-session/launch/structured-chat-wsl-host-offer' import type { AgentSessionRefusalReference } from '../../../../../../shared/agent-session/failures/agent-session-wire-refusals' import { joinSentences } from '../../../../../../shared/text/sentence-joining' import { agentSessionWriteNoticeText } from './agent-session-write-notice-text' @@ -22,7 +27,9 @@ function nativeChatLaunchNotice( failure = null, agentLabel, onRetry, - setup = null + setup = null, + wslHostOffer = null, + wslHostOfferSettingUp = false }: { lifecycle: StructuredAgentSessionLaunchLifecycle | null failure?: StructuredLaunchFailure | null @@ -30,6 +37,9 @@ function nativeChatLaunchNotice( onRetry: () => void /** Replace Retry with the host setup step (sign in, install) that fixes the failure. */ setup?: NativeChatHostSetup | null + /** A WSL folder's chat runs on its distro's host; Retry here would only refuse again. */ + wslHostOffer?: WslHostChatOffer | null + wslHostOfferSettingUp?: boolean }, t: Translate = translate ): NativeChatComposerNotice | null { @@ -43,6 +53,14 @@ function nativeChatLaunchNotice( 'auto.components.native.chat.NativeChatLaunchRetry.unknown', 'Chat connection could not be confirmed.' ) + if (lifecycle === 'failed' && wslHostOffer) { + return { + key: 'launch', + kind: 'error', + text: joinSentences([message, wslHostChatOfferText(t)]), + action: wslHostChatOfferAction(wslHostOffer, t, wslHostOfferSettingUp) + } + } const cause = failure ? (failure.causeText ?? agentSessionWriteNoticeText( @@ -85,7 +103,9 @@ export function structuredSessionNotices( composerError, setup = null, availability = null, - hostPermission = null + hostPermission = null, + wslHostOffer = null, + wslHostOfferSettingUp = false }: { launch: { lifecycle: StructuredAgentSessionLaunchLifecycle | null @@ -99,6 +119,9 @@ export function structuredSessionNotices( setup?: NativeChatHostSetup | null availability?: NativeChatComposerNotice | null hostPermission?: NativeChatComposerNotice | null + wslHostOffer?: WslHostChatOffer | null + /** This distro's host is being set up, so its button shows busy. */ + wslHostOfferSettingUp?: boolean }, t?: Translate ): NativeChatComposerNotice[] { @@ -109,7 +132,9 @@ export function structuredSessionNotices( failure: launch.failure, agentLabel, onRetry: launch.retry, - setup + setup, + wslHostOffer, + wslHostOfferSettingUp }, t ) diff --git a/src/renderer/src/components/native-chat/messages/notices/use-native-chat-structured-pane-notices.ts b/src/renderer/src/components/native-chat/messages/notices/use-native-chat-structured-pane-notices.ts index f4e77786883..e64714b3ff0 100644 --- a/src/renderer/src/components/native-chat/messages/notices/use-native-chat-structured-pane-notices.ts +++ b/src/renderer/src/components/native-chat/messages/notices/use-native-chat-structured-pane-notices.ts @@ -1,4 +1,10 @@ import { useCallback } from 'react' +import { useShallow } from 'zustand/react/shallow' +import { useAppStore } from '@/store/index' +import { + readWslHostChatOfferForLaunch, + useWslHostChatOfferSettingUp +} from '@/lib/agent-session/launch/structured-chat-wsl-host-offer' import { useNativeChatHostSetup } from '../../host-access/native-chat-host-setup' import { useNativeChatAvailabilityNotice } from './use-native-chat-availability-notice' import { structuredSessionNotices } from './native-chat-structured-session-notices' @@ -85,6 +91,10 @@ export function useNativeChatStructuredPaneNotices({ submissions: controller.submissions, deliveryNotices }) + const wslHostOffer = useAppStore( + useShallow((s) => readWslHostChatOfferForLaunch(s, provisionalLaunch, ownerWorktreeId)) + ) + const wslHostOfferSettingUp = useWslHostChatOfferSettingUp(wslHostOffer?.distro) // While Install shows, it says what to do; a start failure's "send again" or Retry can't help. const notices = structuredSessionNotices( { @@ -97,7 +107,9 @@ export function useNativeChatStructuredPaneNotices({ composerError: composerError ?? continuation.continueError, setup, availability, - hostPermission: hostSendGate.notice + hostPermission: hostSendGate.notice, + wslHostOffer, + wslHostOfferSettingUp }, t ) diff --git a/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts b/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts index deaf5b1d822..d9487b0097c 100644 --- a/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts +++ b/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts @@ -18,6 +18,90 @@ export type WslHostOfferDeps = { moveAddedProject: (offer: WslHostOffer) => void } +type WslHostAddRefusal = Extract + +// One run per distro, joined by every caller (add-project offer, chat refusals). +const runningByDistro = new Map>() +const runningListeners = new Set<() => void>() +// Runs in flight share the setting: the first records it, the last restores it if none added. +let batch: { active: number; previous: boolean; added: boolean } | null = null +let restoring: Promise = Promise.resolve() + +function notifyRunning(): void { + for (const listener of runningListeners) { + listener() + } +} + +export function subscribeWslDistroHostRuns(listener: () => void): () => void { + runningListeners.add(listener) + return () => runningListeners.delete(listener) +} + +/** The distro's run in flight from any caller; undefined when none. */ +export function runningWslDistroAsHost( + distro: string +): Promise | undefined { + return runningByDistro.get(distro.toLowerCase()) +} + +/** + * Turns WSL hosts on and adds the distro as a host; an already-added distro counts as added. + * Returns the refusal when the add fails. A call while the same distro runs joins that run; + * other distros run alongside it, and the setting goes back only once every run failed. + */ +export function runWslDistroAsHost( + distro: string, + deps: Pick +): Promise { + const key = distro.toLowerCase() + const running = runningByDistro.get(key) + if (running) { + return running + } + const run = addDistroAsHost(distro, deps).finally(() => { + runningByDistro.delete(key) + notifyRunning() + }) + runningByDistro.set(key, run) + notifyRunning() + return run +} + +async function addDistroAsHost( + distro: string, + deps: Pick +): Promise { + if (!batch) { + // Read the setting only after the last batch put it back. + await restoring + } + batch ??= { active: 0, previous: deps.readWslHostsSetting(), added: false } + const current = batch + current.active += 1 + try { + await deps.updateSettings({ experimentalWslHosts: true }) + // Accepting is the user's ask to run this distro, so a stopped one may start. + const result = await deps.addWslHost({ distro, startIfStopped: true }) + if (result.ok || result.kind === 'already-added') { + current.added = true + return null + } + return result + } finally { + current.active -= 1 + if (current.active === 0) { + batch = null + // Left on after a failure, a later "Add on this computer" would still be auto-moved. + if (!current.added) { + const restore = deps.updateSettings({ experimentalWslHosts: current.previous }) + restoring = restore.catch(() => undefined) + await restore + } + } + } +} + /** * Turns WSL hosts on, adds the distro, adds the project as before, then moves that one project * onto the host. The distro's other bridge projects stay put. Returns the refusal when the add fails. @@ -25,22 +109,10 @@ export type WslHostOfferDeps = { export async function acceptWslHostOffer( offer: WslHostOffer, deps: WslHostOfferDeps -): Promise | null> { - const previous = deps.readWslHostsSetting() - // Left on after a failure, a later "Add on this computer" would still be auto-moved. - const restore = (): Promise => deps.updateSettings({ experimentalWslHosts: previous }) - let result: WslHostAddResult - try { - await deps.updateSettings({ experimentalWslHosts: true }) - // Accepting is the user's ask to run this distro, so a stopped one may start. - result = await deps.addWslHost({ distro: offer.distro, startIfStopped: true }) - } catch (cause) { - await restore() - throw cause - } - if (!result.ok && result.kind !== 'already-added') { - await restore() - return result +): Promise { + const refusal = await runWslDistroAsHost(offer.distro, deps) + if (refusal) { + return refusal } await deps.addLocalPath(offer.path, offer.source) deps.moveAddedProject(offer) diff --git a/src/renderer/src/components/sidebar/wsl-host-offer.ts b/src/renderer/src/components/sidebar/wsl-host-offer.ts index c198f2a62d0..d6dd1f5803b 100644 --- a/src/renderer/src/components/sidebar/wsl-host-offer.ts +++ b/src/renderer/src/components/sidebar/wsl-host-offer.ts @@ -4,6 +4,7 @@ import { type ExecutionHostId } from '../../../../shared/execution-host/execution-host' import type { AppState } from '@/store/types' +import type { GlobalSettings } from '../../../../shared/settings/global-settings-types' import { listWslHostWindowsPathAccess, type WslHostWindowsPathAccess @@ -28,7 +29,9 @@ export function shouldOfferWslHost(gate: WslHostOfferGate): boolean { } export function readWslHostOfferGate( - state: Pick + state: Pick & { + settings: Pick | null + } ): WslHostOfferGate { return { gateOpen: diff --git a/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.test.ts b/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.test.ts new file mode 100644 index 00000000000..313726e13c3 --- /dev/null +++ b/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.test.ts @@ -0,0 +1,77 @@ +// @vitest-environment happy-dom +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const mocks = vi.hoisted(() => ({ + toastError: vi.fn(), + admission: vi.fn(), + openMove: vi.fn() +})) + +vi.mock('sonner', () => ({ + toast: { error: mocks.toastError, loading: vi.fn(), dismiss: vi.fn(), success: vi.fn() } +})) +vi.mock('@/runtime/native-chat/host-capabilities/structured-agent-session-host-support', () => ({ + structuredAgentSessionHostSupports: async () => true +})) +vi.mock('@/lib/agent-session/launch/structured-agent-session-host-admission', () => ({ + admitStructuredLaunchOnHost: mocks.admission +})) +vi.mock('@/components/wsl-move/wsl-move-entry', () => ({ openWslMoveDialogFor: mocks.openMove })) + +import { useAppStore } from '@/store/index' +import { admitCliChatResumeClose } from './cli-chat-resume-close-admission' +import { makeRepo } from '../../worktree-jump/worktree-jump-palette-test-fixtures' + +const REPO_PATH = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' +const WORKTREE_ID = `repo-1::${REPO_PATH}` + +const source = { + tabId: 'term-1', + workspaceId: WORKTREE_ID, + paneKey: 'term-1:11111111-1111-4111-8111-111111111111', + agent: 'claude', + providerSessionId: 'provider-1', + executionHostId: 'local' +} as const + +function admit(): Promise { + return admitCliChatResumeClose( + source, + 'claude', + { kind: 'local' }, + false, + () => true, + new AbortController().signal + ) +} + +beforeEach(() => { + vi.clearAllMocks() + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + repos: [{ ...makeRepo(), id: 'repo-1', path: REPO_PATH }], + wslHostsAcceptNewWork: true, + wslHostServerFiles: 'present' + }) + vi.stubGlobal('window', { ...window, api: { runtimeEnvironments: { wslHosts: {} } } }) + mocks.admission.mockResolvedValue({ kind: 'declined', reason: 'wsl' }) +}) + +describe('resuming a WSL terminal conversation in chat', () => { + it('offers the WSL host path on the refusal toast', async () => { + expect(await admit()).toBeNull() + expect(mocks.toastError).toHaveBeenCalledWith( + expect.stringContaining('Run the project on a WSL host'), + { action: { label: 'Run Ubuntu as a host', onClick: expect.any(Function) } } + ) + }) + + it('keeps the plain toast where WSL hosts cannot be added', async () => { + useAppStore.setState({ wslHostsAcceptNewWork: false }) + await admit() + expect(mocks.toastError).toHaveBeenCalledWith( + 'Chat is not available in WSL. Open the agent in a terminal instead.', + undefined + ) + }) +}) diff --git a/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.ts b/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.ts index c707623aab3..b713c53d63c 100644 --- a/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.ts +++ b/src/renderer/src/components/tab-bar/session-actions/cli-chat-resume-close-admission.ts @@ -2,7 +2,7 @@ import { toast } from 'sonner' import { useAppStore } from '@/store/index' import { getExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' import { admitStructuredLaunchOnHost } from '@/lib/agent-session/launch/structured-agent-session-host-admission' -import { structuredChatUnavailableText } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' +import { structuredChatUnavailableToast } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' import { notifyHostPermissionRefused } from '@/lib/agent-session/launch/structured-agent-session-launch-permission-notice' import { toRuntimeWorktreeSelector } from '@/runtime/rpc/targets/runtime-worktree-selector' import { readStructuredChatHostPermissionVerdict } from '@/runtime/native-chat/host-capabilities/structured-chat-host-permission' @@ -156,7 +156,11 @@ export async function admitCliChatResumeClose( return null } if (support.kind === 'declined') { - toast.error(structuredChatUnavailableText(support.reason)) + const { description, action } = structuredChatUnavailableToast( + support.reason, + source.workspaceId + ) + toast.error(description, action ? { action } : undefined) return null } // A host that could not say whether it checked the other writers still lets the switch go on: diff --git a/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts b/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts index 01d8853847b..435fd75ed4e 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts +++ b/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts @@ -23,7 +23,7 @@ import { } from '../../../../shared/workspace/identity/workspace-scope' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' import type { Worktree } from '../../../../shared/worktree/types' -import { parseWslUncPath } from '../../../../shared/file-access/wsl-paths' +import { wslHostMovableDistroOfPath } from '../../../../shared/file-access/wsl-paths' import type { WslMoveBlocker, WslMoveRowRef @@ -47,18 +47,12 @@ export type WslMoveCounts = { chats: number } -// Rule D7: a repo on a Windows drive reached through the distro stays a Windows project. -const WINDOWS_DRIVE_MOUNT = /^\/mnt\/[a-z](\/|$)/i - /** The distro a local folder lives in when it could move to that distro's host; else null. */ -export function wslMoveDistroOfPath(path: string): string | null { - const parsed = parseWslUncPath(path) - return parsed && !WINDOWS_DRIVE_MOUNT.test(parsed.linuxPath) ? parsed.distro : null -} +export const wslMoveDistroOfPath = wslHostMovableDistroOfPath /** The added WSL host of a distro, matched as WSL matches names: case-insensitively. */ export function findWslHostForDistro( - environments: readonly PublicKnownRuntimeEnvironment[], + environments: readonly Pick[], distro: string ): { distro: string; name: string } | null { const wanted = distro.toLowerCase() @@ -196,17 +190,41 @@ export function wslMoveCatalogCandidates( wslMoveDistroOfPath(path)?.toLowerCase() === distro.toLowerCase() return { repoIds: catalog.repos - .filter( - (repo) => getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID && inDistro(repo.path) - ) + .filter((repo) => isLocalRepo(repo) && inDistro(repo.path)) .map((repo) => repo.id), folderWorkspaceIds: catalog.folders - .filter( - (folder) => - (folder.executionHostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID && - !folder.connectionId && - inDistro(folder.folderPath) - ) + .filter((folder) => isLocalFolder(folder) && inDistro(folder.folderPath)) .map((folder) => folder.id) } } + +/** The local project holding a workspace, and the distro whose host it could move to. */ +export function wslMoveProjectOfWorkspace( + catalog: { + repos: readonly Pick[] + folders: readonly Pick< + FolderWorkspace, + 'id' | 'folderPath' | 'connectionId' | 'executionHostId' + >[] + }, + workspaceKey: string +): { ref: WslMoveRowRef; distro: string } | null { + const ref = projectOfWorkspaceKey(workspaceKey) + const path = + ref.kind === 'repo' + ? catalog.repos.find((repo) => repo.id === ref.id && isLocalRepo(repo))?.path + : catalog.folders.find((folder) => folder.id === ref.id && isLocalFolder(folder))?.folderPath + const distro = path ? wslMoveDistroOfPath(path) : null + return distro ? { ref, distro } : null +} + +function isLocalRepo(repo: Pick): boolean { + return getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID +} + +function isLocalFolder(folder: Pick): boolean { + return ( + (folder.executionHostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID && + !folder.connectionId + ) +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 0d69486326c..4b39bd9a45e 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21455,6 +21455,8 @@ "thoughtForDuration": "Thought for {{duration}}", "explicitChatWsl": "Chat is not available in WSL. Open the agent in a terminal instead.", "explicitChatWslAddHost": "Chat is not available in a WSL folder opened from Windows. Add the distro as a WSL host (Add a project → Add remote host → Add WSL distro) to chat there, or open the agent in a terminal.", + "explicitChatWslMoveToHost": "Chat is not available in a WSL folder opened from Windows. Run the project on a WSL host to chat there, or open the agent in a terminal.", + "explicitChatWslRunAsHost": "Run {{distro}} as a host", "explicitChatSsh": "Chat is not available over SSH. Open the agent in a terminal instead.", "explicitChatUnavailable": "This workspace cannot run the chat. Check the agent installation or open it in a terminal.", "structuredSessionHostDeclined": "Opened {{value0}} in a terminal", diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission-notices.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission-notices.ts index 60d76e4e23b..ea032f5c73c 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission-notices.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission-notices.ts @@ -7,16 +7,20 @@ import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' import { structuredAgentLabel } from '@/lib/agent-session/launch/structured-agent-session-launch-label' -import { structuredChatUnavailableText } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' +import { structuredChatUnavailableToast } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' -export function notifyExplicitChatFailure(agent: TuiAgent, reason?: string): void { +export function notifyExplicitChatFailure( + agent: TuiAgent, + reason?: string, + worktreeId?: string +): void { toast.error( translate( 'auto.components.tab.bar.QuickLaunchButton.chatUnavailableAfterSelection', "Couldn't start a {{value0}} chat.", { value0: structuredAgentLabel(agent) } ), - { description: structuredChatUnavailableText(reason) } + structuredChatUnavailableToast(reason, worktreeId) ) } diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission.ts index 123673b8454..994810eaf2d 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-admission.ts @@ -177,7 +177,7 @@ export function beginHostAdmittedStructuredLaunch(args: { notify = plan.requestedSurface === 'chat' ): StructuredAgentLaunchSettlement => { if (notify && !admitted) { - notifyExplicitChatFailure(plan.agent, reason) + notifyExplicitChatFailure(plan.agent, reason, args.worktreeId) resolveDelivery(NOT_DELIVERED_NOTIFIED) return { kind: 'failed', error, notified: true } } diff --git a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-failure.ts b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-failure.ts index bd363c9a4c4..d2da6e02772 100644 --- a/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-failure.ts +++ b/src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-failure.ts @@ -13,6 +13,12 @@ import { import { wslHostsAvailable } from '@/components/sidebar/use-wsl-hosts-enabled' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store/index' +import { + isWslHostChatOfferSettingUp, + readWslHostChatOffer, + wslHostChatOfferAction, + wslHostChatOfferText +} from './structured-chat-wsl-host-offer' import { StructuredAgentSessionCreateRefusalError, StructuredAgentSessionCreateSourceFailedError @@ -24,6 +30,8 @@ export type StructuredLaunchFailure = AgentSessionWriteRefusal & { causeText?: string /** The chat the refusal named as holding the conversation; null when it named none. */ owner?: AgentSessionConversationOwner | null + /** The host's word for why it can't run the chat here (`wsl`, `remote`), when it gave one. */ + hostReason?: string } /** A WSL distro added as a host runs chat itself, so point there once this desktop can add one. */ @@ -65,6 +73,23 @@ export function structuredChatUnavailableText(reason?: string): string { ) } +/** A toast's words for a declined chat, with the WSL host path for this workspace when it has one. */ +export function structuredChatUnavailableToast( + reason: string | undefined, + worktreeId: string | null | undefined +): { description: string; action?: { label: string; onClick: () => void } } { + const offer = reason === 'wsl' ? readWslHostChatOffer(useAppStore.getState(), worktreeId) : null + if (!offer) { + return { description: structuredChatUnavailableText(reason) } + } + const { label, onClick } = wslHostChatOfferAction( + offer, + translate, + isWslHostChatOfferSettingUp(offer.distro) + ) + return { description: wslHostChatOfferText(), action: { label, onClick } } +} + /** The host's refusal behind a failed launch; undefined when the failure carried none. */ export function structuredLaunchFailure(error: unknown): StructuredLaunchFailure | undefined { if (error instanceof StructuredAgentSessionCreateSourceFailedError) { @@ -78,7 +103,8 @@ export function structuredLaunchFailure(error: unknown): StructuredLaunchFailure return { kind: 'refused', code: 'structured_agent_session_unsupported', - causeText: structuredChatUnavailableText(error.hostReason) + causeText: structuredChatUnavailableText(error.hostReason), + hostReason: error.hostReason } } const refusal = launchRefusal(error) diff --git a/src/renderer/src/lib/agent-session/launch/structured-chat-wsl-host-offer.test.ts b/src/renderer/src/lib/agent-session/launch/structured-chat-wsl-host-offer.test.ts new file mode 100644 index 00000000000..fb3e1c547ac --- /dev/null +++ b/src/renderer/src/lib/agent-session/launch/structured-chat-wsl-host-offer.test.ts @@ -0,0 +1,457 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { WslHostAddResult } from '../../../../../shared/remote-runtime/wsl-hosts/wsl-host-types' + +const mocks = vi.hoisted(() => ({ + settings: { experimentalWslHosts: false }, + saveSetting: async (updates: { experimentalWslHosts?: boolean }): Promise => { + if (updates.experimentalWslHosts !== undefined) { + mocks.settings.experimentalWslHosts = updates.experimentalWslHosts + } + }, + updateSettingsOrThrow: vi.fn<(updates: { experimentalWslHosts?: boolean }) => Promise>(), + // Adds a test held open; released after each test so no run outlives it. + held: new Set<(result: WslHostAddResult) => void>(), + addWslHost: + vi.fn<(args: { distro: string; startIfStopped: boolean }) => Promise>(), + openMove: vi.fn(), + toastError: vi.fn(), + store: { + wslHostsAcceptNewWork: true, + wslHostServerFiles: 'present', + repos: [{ id: 'repo-1', path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' }], + folderWorkspaces: [], + runtimeEnvironments: [] + } +})) + +vi.mock('sonner', () => ({ + toast: { error: mocks.toastError, loading: vi.fn(() => 'adding'), dismiss: vi.fn() } +})) +vi.mock('@/store/index', () => ({ + useAppStore: { + getState: () => ({ + ...mocks.store, + settings: mocks.settings, + updateSettingsOrThrow: mocks.updateSettingsOrThrow + }) + } +})) +vi.mock('@/components/sidebar/host-admission/wsl/add-wsl-host-distro', () => ({ + addWslHostDistro: mocks.addWslHost +})) +vi.mock('@/components/wsl-move/wsl-move-entry', () => ({ openWslMoveDialogFor: mocks.openMove })) + +import { + readWslHostChatOffer, + readWslHostChatOfferForLaunch, + isWslHostChatOfferSettingUp, + wslHostChatOfferAction, + type WslHostChatOffer, + type WslHostChatOfferState +} from './structured-chat-wsl-host-offer' +import { acceptWslHostOffer } from '@/components/sidebar/wsl-host-offer-actions' +import { structuredChatUnavailableToast } from './structured-agent-session-launch-failure' +import { structuredSessionNotices } from '@/components/native-chat/messages/notices/native-chat-structured-session-notices' + +const REPO_PATH = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' +const WORKTREE_ID = `repo-1::${REPO_PATH}` + +function state(overrides: Partial = {}): WslHostChatOfferState { + return { + settings: null, + wslHostsAcceptNewWork: true, + wslHostServerFiles: 'present', + repos: [{ id: 'repo-1', path: REPO_PATH }], + folderWorkspaces: [], + runtimeEnvironments: [], + ...overrides + } +} + +const wslHost = { + name: 'Ubuntu (WSL)', + orcadDeployment: { kind: 'wsl', distro: 'Ubuntu', localPort: 7000, remotePort: 7001 } +} as const + +beforeEach(() => { + vi.clearAllMocks() + mocks.updateSettingsOrThrow.mockImplementation(mocks.saveSetting) + mocks.settings.experimentalWslHosts = false + vi.stubGlobal('window', { api: { runtimeEnvironments: { wslHosts: {} } } }) +}) + +afterEach(async () => { + for (const finish of mocks.held) { + finish({ ok: false, kind: 'failed', message: 'Released after the test.' }) + } + mocks.held.clear() + await vi.waitFor(() => + expect(['Ubuntu', 'Debian'].some((distro) => isWslHostChatOfferSettingUp(distro))).toBe(false) + ) +}) + +describe('readWslHostChatOffer', () => { + it('offers to run the distro as a host while the setting is still off', () => { + expect(readWslHostChatOffer(state(), WORKTREE_ID)).toEqual({ + distro: 'Ubuntu', + projectKind: 'repo', + projectId: 'repo-1', + hostReady: false + }) + }) + + it('offers only the move once the distro is a host and the setting is on', () => { + const offer = readWslHostChatOffer( + state({ settings: { experimentalWslHosts: true }, runtimeEnvironments: [wslHost] }), + WORKTREE_ID + ) + expect(offer?.hostReady).toBe(true) + }) + + it('offers a folder workspace in the distro', () => { + const offer = readWslHostChatOffer( + state({ repos: [], folderWorkspaces: [{ id: 'f1', folderPath: REPO_PATH }] }), + 'folder:f1' + ) + expect(offer).toMatchObject({ projectKind: 'folder', projectId: 'f1' }) + }) + + it('offers nothing while this desktop cannot add WSL hosts', () => { + expect(readWslHostChatOffer(state({ wslHostsAcceptNewWork: false }), WORKTREE_ID)).toBeNull() + expect(readWslHostChatOffer(state({ wslHostServerFiles: 'missing' }), WORKTREE_ID)).toBeNull() + vi.stubGlobal('window', { api: { runtimeEnvironments: {} } }) + expect(readWslHostChatOffer(state(), WORKTREE_ID)).toBeNull() + }) + + it('offers nothing for a Windows drive reached through the distro or an SSH project', () => { + const mount = '\\\\wsl.localhost\\Ubuntu\\mnt\\c\\repo' + expect( + readWslHostChatOffer(state({ repos: [{ id: 'repo-1', path: mount }] }), `repo-1::${mount}`) + ).toBeNull() + expect( + readWslHostChatOffer( + state({ repos: [{ id: 'repo-1', path: REPO_PATH, connectionId: 'ssh-1' }] }), + WORKTREE_ID + ) + ).toBeNull() + }) +}) + +describe('wslHostChatOfferAction', () => { + const offer: WslHostChatOffer = { + distro: 'Ubuntu', + projectKind: 'repo', + projectId: 'repo-1', + hostReady: false + } + + it('turns the setting on, adds the distro, then opens the move for this project', async () => { + mocks.addWslHost.mockResolvedValue({ ok: true, environmentId: 'env-ubuntu' }) + const action = wslHostChatOfferAction(offer) + expect(action.label).toBe('Run Ubuntu as a host') + action.onClick() + await vi.waitFor(() => expect(mocks.openMove).toHaveBeenCalled()) + expect(mocks.updateSettingsOrThrow).toHaveBeenCalledWith({ experimentalWslHosts: true }) + expect(mocks.addWslHost).toHaveBeenCalledWith({ distro: 'Ubuntu', startIfStopped: true }) + expect(mocks.openMove).toHaveBeenCalledWith('Ubuntu', { kind: 'repo', id: 'repo-1' }) + }) + + it('restores the setting and says why when the add fails', async () => { + mocks.addWslHost.mockResolvedValue({ + ok: false, + kind: 'unsupported-wsl1', + message: 'Ubuntu runs WSL 1.' + }) + wslHostChatOfferAction(offer).onClick() + await vi.waitFor(() => expect(mocks.toastError).toHaveBeenCalled()) + expect(mocks.settings.experimentalWslHosts).toBe(false) + expect(mocks.openMove).not.toHaveBeenCalled() + }) + + it('runs one setup for repeated and concurrent clicks across surfaces', async () => { + let finishAdd: (result: WslHostAddResult) => void = () => undefined + mocks.addWslHost.mockImplementation( + () => + new Promise((resolve) => { + finishAdd = resolve + mocks.held.add(resolve) + }) + ) + const first = wslHostChatOfferAction(offer) + first.onClick() + first.onClick() + // Another surface (the toast) for the same distro, spelled differently, joins too. + wslHostChatOfferAction({ ...offer, distro: 'ubuntu' }).onClick() + await vi.waitFor(() => expect(mocks.addWslHost).toHaveBeenCalledTimes(1)) + expect(isWslHostChatOfferSettingUp('UBUNTU')).toBe(true) + const busy = wslHostChatOfferAction(offer, undefined, true) + expect(busy).toMatchObject({ label: 'Setting up…', disabled: true }) + finishAdd({ ok: false, kind: 'failed', message: 'Could not start the server.' }) + await vi.waitFor(() => expect(isWslHostChatOfferSettingUp('Ubuntu')).toBe(false)) + expect(mocks.toastError).toHaveBeenCalledTimes(1) + // The one failed setup restores what it read: the setting stays off. + expect(mocks.settings.experimentalWslHosts).toBe(false) + expect(mocks.openMove).not.toHaveBeenCalled() + }) + + function holdAdds(): Record void> { + const finishes: Record void> = {} + mocks.addWslHost.mockImplementation( + ({ distro }) => + new Promise((resolve) => { + finishes[distro] = resolve + mocks.held.add(resolve) + }) + ) + return finishes + } + + function addProjectOfferDeps() { + return { + readWslHostsSetting: () => mocks.settings.experimentalWslHosts, + updateSettings: mocks.updateSettingsOrThrow, + addWslHost: mocks.addWslHost, + addLocalPath: vi.fn(async () => undefined), + moveAddedProject: vi.fn() + } + } + + const DEBIAN_OFFER = { + path: '\\\\wsl.localhost\\Debian\\repo', + distro: 'Debian', + source: 'local_folder_picker' + } as const + + it('runs setups for different distros side by side', async () => { + const finishes = holdAdds() + wslHostChatOfferAction(offer).onClick() + wslHostChatOfferAction({ ...offer, distro: 'Debian' }).onClick() + await vi.waitFor(() => expect(mocks.addWslHost).toHaveBeenCalledTimes(2)) + expect(Object.keys(finishes).sort()).toEqual(['Debian', 'Ubuntu']) + }) + + it('does not hold one distro behind another that hangs', async () => { + const finishes = holdAdds() + // The add-project offer's Debian add hangs; the chat's Ubuntu setup still finishes. + void acceptWslHostOffer(DEBIAN_OFFER, addProjectOfferDeps()) + wslHostChatOfferAction(offer).onClick() + await vi.waitFor(() => expect(finishes.Ubuntu).toBeDefined()) + finishes.Ubuntu({ ok: true, environmentId: 'env-ubuntu' }) + await vi.waitFor(() => + expect(mocks.openMove).toHaveBeenCalledWith('Ubuntu', { kind: 'repo', id: 'repo-1' }) + ) + expect(isWslHostChatOfferSettingUp('Debian')).toBe(true) + expect(mocks.settings.experimentalWslHosts).toBe(true) + }) + + it('restores the setting only once every run in flight failed', async () => { + const finishes = holdAdds() + const accepted = acceptWslHostOffer(DEBIAN_OFFER, addProjectOfferDeps()) + wslHostChatOfferAction(offer).onClick() + await vi.waitFor(() => expect(mocks.addWslHost).toHaveBeenCalledTimes(2)) + finishes.Debian({ ok: false, kind: 'failed', message: 'Debian could not start.' }) + expect(await accepted).toMatchObject({ ok: false }) + // Ubuntu still runs, so the first failure leaves the setting on. + expect(mocks.settings.experimentalWslHosts).toBe(true) + finishes.Ubuntu({ ok: false, kind: 'failed', message: 'Ubuntu could not start.' }) + await vi.waitFor(() => expect(isWslHostChatOfferSettingUp('Ubuntu')).toBe(false)) + expect(mocks.settings.experimentalWslHosts).toBe(false) + expect(mocks.openMove).not.toHaveBeenCalled() + }) + + it('keeps the setting on when any run in flight added its host', async () => { + const finishes = holdAdds() + const offerDeps = addProjectOfferDeps() + const accepted = acceptWslHostOffer(DEBIAN_OFFER, offerDeps) + wslHostChatOfferAction(offer).onClick() + await vi.waitFor(() => expect(mocks.addWslHost).toHaveBeenCalledTimes(2)) + finishes.Ubuntu({ ok: true, environmentId: 'env-ubuntu' }) + finishes.Debian({ ok: false, kind: 'failed', message: 'Debian could not start.' }) + expect(await accepted).toMatchObject({ ok: false }) + await vi.waitFor(() => expect(mocks.openMove).toHaveBeenCalled()) + expect(mocks.settings.experimentalWslHosts).toBe(true) + expect(offerDeps.addLocalPath).not.toHaveBeenCalled() + }) + + it('reads the setting for a new run only after the last one put it back', async () => { + let finishRestore: () => void = () => undefined + let restoreHeld = false + mocks.addWslHost.mockResolvedValue({ ok: false, kind: 'failed', message: 'No.' }) + mocks.updateSettingsOrThrow.mockImplementation(async (updates) => { + if (updates.experimentalWslHosts === false && !restoreHeld) { + restoreHeld = true + await new Promise((resolve) => { + finishRestore = resolve + }) + } + await mocks.saveSetting(updates) + }) + const failed = acceptWslHostOffer(DEBIAN_OFFER, addProjectOfferDeps()) + await vi.waitFor(() => + expect(mocks.updateSettingsOrThrow).toHaveBeenCalledWith({ experimentalWslHosts: false }) + ) + const reads: boolean[] = [] + const next = acceptWslHostOffer( + { ...DEBIAN_OFFER, distro: 'Ubuntu' }, + { + ...addProjectOfferDeps(), + readWslHostsSetting: () => { + reads.push(mocks.settings.experimentalWslHosts) + return mocks.settings.experimentalWslHosts + } + } + ) + expect(reads).toEqual([]) + finishRestore() + await failed + await next + expect(reads).toEqual([false]) + }) + + it('lets the add-project offer join a chat setup of the same distro', async () => { + let finishAdd: (result: WslHostAddResult) => void = () => undefined + mocks.addWslHost.mockImplementation( + () => + new Promise((resolve) => { + finishAdd = resolve + mocks.held.add(resolve) + }) + ) + wslHostChatOfferAction(offer).onClick() + await vi.waitFor(() => expect(mocks.addWslHost).toHaveBeenCalledTimes(1)) + const offerDeps = { + readWslHostsSetting: () => mocks.settings.experimentalWslHosts, + updateSettings: mocks.updateSettingsOrThrow, + addWslHost: mocks.addWslHost, + addLocalPath: vi.fn(async () => undefined), + moveAddedProject: vi.fn() + } + const accepted = acceptWslHostOffer( + { path: '\\\\wsl.localhost\\ubuntu\\repo', distro: 'ubuntu', source: 'local_folder_picker' }, + offerDeps + ) + finishAdd({ ok: true, environmentId: 'env-ubuntu' }) + expect(await accepted).toBeNull() + expect(mocks.addWslHost).toHaveBeenCalledTimes(1) + expect(offerDeps.addLocalPath).toHaveBeenCalledTimes(1) + expect(offerDeps.moveAddedProject).toHaveBeenCalledTimes(1) + }) + + it('opens the move straight away when the host is ready', async () => { + const action = wslHostChatOfferAction({ ...offer, hostReady: true }) + expect(action.label).toBe('Move to Ubuntu host…') + action.onClick() + await vi.waitFor(() => expect(mocks.openMove).toHaveBeenCalled()) + expect(mocks.addWslHost).not.toHaveBeenCalled() + }) +}) + +describe('readWslHostChatOfferForLaunch', () => { + const wslFailure = { + kind: 'refused', + code: 'structured_agent_session_unsupported', + hostReason: 'wsl' + } as const + + it('offers only for a failed start the host refused as WSL', () => { + expect( + readWslHostChatOfferForLaunch( + state(), + { lifecycle: 'failed', failure: wslFailure }, + WORKTREE_ID + ) + ).toMatchObject({ distro: 'Ubuntu' }) + expect( + readWslHostChatOfferForLaunch( + state(), + { lifecycle: 'failed', failure: { ...wslFailure, hostReason: 'remote' } }, + WORKTREE_ID + ) + ).toBeNull() + expect( + readWslHostChatOfferForLaunch( + state(), + { lifecycle: 'visibility-unknown', failure: wslFailure }, + WORKTREE_ID + ) + ).toBeNull() + expect( + readWslHostChatOfferForLaunch(state(), { lifecycle: 'failed', failure: null }, WORKTREE_ID) + ).toBeNull() + }) +}) + +describe('structuredChatUnavailableToast', () => { + it('keeps the plain words for other refusals', () => { + expect(structuredChatUnavailableToast('remote', WORKTREE_ID)).toEqual({ + description: 'Chat is not available over SSH. Open the agent in a terminal instead.' + }) + }) + + it('keeps the plain words when the workspace has no offer', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: {} } }) + expect(structuredChatUnavailableToast('wsl', WORKTREE_ID)).toEqual({ + description: 'Chat is not available in WSL. Open the agent in a terminal instead.' + }) + vi.stubGlobal('window', { api: { runtimeEnvironments: { wslHosts: {} } } }) + expect(structuredChatUnavailableToast('wsl', 'repo-unknown::/elsewhere')).not.toHaveProperty( + 'action' + ) + }) + + it('wires the toast button to the host setup for this project', async () => { + mocks.addWslHost.mockResolvedValue({ ok: true, environmentId: 'env-ubuntu' }) + const toastOptions = structuredChatUnavailableToast('wsl', WORKTREE_ID) + expect(toastOptions.description).toContain('Run the project on a WSL host') + expect(toastOptions.action?.label).toBe('Run Ubuntu as a host') + toastOptions.action?.onClick() + await vi.waitFor(() => + expect(mocks.openMove).toHaveBeenCalledWith('Ubuntu', { kind: 'repo', id: 'repo-1' }) + ) + }) +}) + +describe('the chat composer notice', () => { + it('replaces Retry with the WSL host path for a WSL folder', () => { + const [notice] = structuredSessionNotices({ + launch: { + lifecycle: 'failed', + failure: { + kind: 'refused', + code: 'structured_agent_session_unsupported', + hostReason: 'wsl' + }, + retry: vi.fn() + }, + agentLabel: 'Claude', + sessionError: null, + composerError: null, + wslHostOffer: { + distro: 'Ubuntu', + projectKind: 'repo', + projectId: 'repo-1', + hostReady: false + } + }) + expect(notice?.text).toContain('Run the project on a WSL host to chat there') + expect(notice?.action?.label).toBe('Run Ubuntu as a host') + }) + + it('shows the button busy while the host is being set up', () => { + const [notice] = structuredSessionNotices({ + launch: { lifecycle: 'failed', failure: null, retry: vi.fn() }, + agentLabel: 'Claude', + sessionError: null, + composerError: null, + wslHostOffer: { + distro: 'Ubuntu', + projectKind: 'repo', + projectId: 'repo-1', + hostReady: false + }, + wslHostOfferSettingUp: true + }) + expect(notice?.action).toMatchObject({ label: 'Setting up…', disabled: true }) + }) +}) diff --git a/src/renderer/src/lib/agent-session/launch/structured-chat-wsl-host-offer.ts b/src/renderer/src/lib/agent-session/launch/structured-chat-wsl-host-offer.ts new file mode 100644 index 00000000000..fe5138cf25b --- /dev/null +++ b/src/renderer/src/lib/agent-session/launch/structured-chat-wsl-host-offer.ts @@ -0,0 +1,163 @@ +// A chat refused in a Windows-opened WSL folder runs once its project moves onto a WSL host. + +import { useSyncExternalStore } from 'react' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import type { Translate } from '@/i18n/use-translate' +import { useAppStore } from '@/store/index' +import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields' +import { readIpcErrorDetail } from '@/runtime/errors/ipc-error' +import { readWslHostOfferGate } from '@/components/sidebar/wsl-host-offer' +import { + runningWslDistroAsHost, + runWslDistroAsHost, + subscribeWslDistroHostRuns +} from '@/components/sidebar/wsl-host-offer-actions' +import { addWslHostDistro } from '@/components/sidebar/host-admission/wsl/add-wsl-host-distro' +import { wslHostAddRefusalMessage } from '@/components/sidebar/wsl-host-failure-text' +import { openWslMoveDialogFor } from '@/components/wsl-move/wsl-move-entry' +import { + findWslHostForDistro, + wslMoveProjectOfWorkspace +} from '@/components/wsl-move/wsl-move-scope-rows' +import type { WslMoveRowRef } from '../../../../../shared/wsl-move/wsl-move-driver-types' + +/** Flat so a shallow-compared selector can return it. */ +export type WslHostChatOffer = { + distro: string + projectKind: WslMoveRowRef['kind'] + projectId: string + /** The distro is already a host and the setting is on, so only the move remains. */ + hostReady: boolean +} + +export type WslHostChatAction = { + label: string + primary: true + disabled: boolean + onClick: () => void +} + +/** This workspace's local WSL project, while this desktop can add WSL hosts; else null. */ +export type WslHostChatOfferState = Parameters[0] & { + repos: Parameters[0]['repos'] + folderWorkspaces?: Parameters[0]['folders'] + runtimeEnvironments: Parameters[0] +} + +export function readWslHostChatOffer( + state: WslHostChatOfferState, + worktreeId: string | null | undefined +): WslHostChatOffer | null { + if (!worktreeId || !readWslHostOfferGate(state).gateOpen) { + return null + } + const project = wslMoveProjectOfWorkspace( + { repos: state.repos, folders: selectFolderWorkspaces(state) ?? [] }, + worktreeId + ) + if (!project) { + return null + } + return { + distro: project.distro, + projectKind: project.ref.kind, + projectId: project.ref.id, + hostReady: + state.settings?.experimentalWslHosts === true && + findWslHostForDistro(state.runtimeEnvironments, project.distro) !== null + } +} + +/** The offer for a chat whose start the host refused because the workspace runs under WSL. */ +export function readWslHostChatOfferForLaunch( + state: WslHostChatOfferState, + launch: { lifecycle: string | null; failure?: { hostReason?: string } | null }, + worktreeId: string | null | undefined +): WslHostChatOffer | null { + return launch.lifecycle === 'failed' && launch.failure?.hostReason === 'wsl' + ? readWslHostChatOffer(state, worktreeId) + : null +} + +export function wslHostChatOfferText(t: Translate = translate): string { + return t( + 'components.native-chat.explicitChatWslMoveToHost', + 'Chat is not available in a WSL folder opened from Windows. Run the project on a WSL host to chat there, or open the agent in a terminal.' + ) +} + +export function isWslHostChatOfferSettingUp(distro: string): boolean { + return runningWslDistroAsHost(distro) !== undefined +} + +/** True while this distro is being set up as a host from any surface. */ +export function useWslHostChatOfferSettingUp(distro: string | null | undefined): boolean { + return useSyncExternalStore(subscribeWslDistroHostRuns, () => + distro ? isWslHostChatOfferSettingUp(distro) : false + ) +} + +/** Turns the setting on and adds the distro when needed, then opens the move for this project. */ +export function wslHostChatOfferAction( + offer: WslHostChatOffer, + t: Translate = translate, + settingUpNow = false +): WslHostChatAction { + const only: WslMoveRowRef = { kind: offer.projectKind, id: offer.projectId } + return { + label: settingUpNow + ? t('auto.components.sidebar.AddWslHostFormPanel.adding', 'Setting up…') + : offer.hostReady + ? t('wslMove.entry.projectMenu', 'Move to {{distro}} host…', { distro: offer.distro }) + : t('components.native-chat.explicitChatWslRunAsHost', 'Run {{distro}} as a host', { + distro: offer.distro + }), + primary: true, + disabled: settingUpNow, + onClick: () => void runWslHostChatOffer(offer.hostReady, offer.distro, only) + } +} + +/** Resolves when this click's work is done; a click during a setup joins it and opens nothing. */ +export async function runWslHostChatOffer( + hostReady: boolean, + distro: string, + only: WslMoveRowRef +): Promise { + const running = runningWslDistroAsHost(distro) + if (running) { + await running.catch(() => undefined) + return + } + // The user's Move in the dialog is what moves the project. + if (hostReady || (await setUpWslHostForChat(distro))) { + openWslMoveDialogFor(distro, only) + } +} + +async function setUpWslHostForChat(distro: string): Promise { + const adding = toast.loading( + translate( + 'auto.components.sidebar.AddWslHostFormPanel.addingHint', + 'Installing and starting the Orca server in the distro. The first time can take a minute.' + ) + ) + try { + const refusal = await runWslDistroAsHost(distro, { + readWslHostsSetting: () => useAppStore.getState().settings?.experimentalWslHosts === true, + updateSettings: (updates) => useAppStore.getState().updateSettingsOrThrow(updates), + addWslHost: addWslHostDistro + }) + if (refusal) { + toast.error(wslHostAddRefusalMessage(refusal)) + return false + } + return true + } catch (cause) { + toast.error(readIpcErrorDetail(cause) ?? String(cause)) + return false + } finally { + toast.dismiss(adding) + } +} diff --git a/src/shared/file-access/wsl-paths.ts b/src/shared/file-access/wsl-paths.ts index b71949a4d23..dcf23e9adcd 100644 --- a/src/shared/file-access/wsl-paths.ts +++ b/src/shared/file-access/wsl-paths.ts @@ -130,6 +130,15 @@ export function isDrvfsLinuxPath(linuxPath: string): boolean { return DRVFS_LINUX_PATH.test(linuxPath) } +// Rule D7: a repo on a Windows drive reached through the distro stays a Windows project. +const WINDOWS_DRIVE_MOUNT = /^\/mnt\/[a-z](\/|$)/i + +/** The distro a `\\wsl.localhost` folder could move to a WSL host of; null for a Windows drive. */ +export function wslHostMovableDistroOfPath(path: string): string | null { + const parsed = parseWslUncPath(path) + return parsed && !WINDOWS_DRIVE_MOUNT.test(parsed.linuxPath) ? parsed.distro : null +} + /** Drvfs bytes belong to a Windows drive regardless of which distro mounted it. */ export function toWindowsWslDrivePath(linuxPath: string): string | null { // Dot excludes line terminators, preventing stray CR/output lines from becoming drive paths.