Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions src/main/agent-launch/agent-launch-account-env.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* `agent.launch`'s `accountEnv` reaches only terminal agents; a structured launch keeps its
* host-derived home and says so.
*/
import { describe, expect, it, vi } from 'vitest'
import { executeAgentLaunch, type AgentLaunchExecution } from './agent-launch-executor'
import type { AgentLaunchIntent } from '../../shared/agent-launch-intent'
import { STRUCTURED_ACCOUNT_ENV_IGNORED_WARNING } from '../../shared/agent-launch-account-env'

const ACCOUNT_ENV = { CLAUDE_CONFIG_DIR: '/home/u/.orca/claude/a', CODEX_HOME: '/home/u/.codex-b' }

function harness(structured: boolean) {
const createWorktree = vi.fn(async (args: { startupAgent: string | undefined }) => ({
worktreeId: 'wt-new',
connectionId: null,
startupTerminalHandle: args.startupAgent ? 'term_agent_first' : undefined
}))
const createStructuredSession = vi.fn(async () => ({
sessionId: 'sess-1',
handle: 'handle_structured',
fence: 4
}))
const createTerminalAgent = vi.fn(async () => ({ handle: 'term_1' }))
const runtime = {
getClientSettings: () => (structured ? { experimentalNativeChat: true } : null),
getStructuredAgentSessionCreateSupport: async () => ({ supported: true })
}
return {
createWorktree,
createStructuredSession,
createTerminalAgent,
run: (intent: AgentLaunchIntent) =>
executeAgentLaunch({
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the stub implements the two runtime methods the executor reaches; a missing one throws.
runtime: runtime as unknown as AgentLaunchExecution['runtime'],
intent,
surfaces: { createStructuredSession, createTerminalAgent },
workspaces: { createWorktree }
})
}
}

describe('agent.launch account env', () => {
it('passes the account env to a terminal agent in an existing workspace', async () => {
const h = harness(false)
const result = await h.run({
agent: 'claude',
target: { kind: 'existing', worktree: 'wt-7' },
accountEnv: ACCOUNT_ENV
})
expect(h.createTerminalAgent).toHaveBeenCalledWith(
expect.objectContaining({ accountEnv: ACCOUNT_ENV })
)
expect(result.warning).toBeUndefined()
})

it('passes it to the startup terminal of a worktree the launch creates', async () => {
const h = harness(false)
await h.run({
agent: 'codex',
target: { kind: 'create-worktree', create: { repo: 'id:repo-1', name: 'task' } },
accountEnv: ACCOUNT_ENV
})
expect(h.createWorktree).toHaveBeenCalledWith(
expect.objectContaining({ startupAgent: 'codex', accountEnv: ACCOUNT_ENV })
)
})

it('keeps a structured session on its host-derived home and warns', async () => {
const h = harness(true)
const result = await h.run({
agent: 'claude',
target: { kind: 'existing', worktree: 'wt-7' },
accountEnv: ACCOUNT_ENV
})
expect(result.outcome.kind).toBe('structured')
expect(h.createStructuredSession).toHaveBeenCalledWith(
expect.not.objectContaining({ accountEnv: expect.anything() })
)
expect(result.warning).toBe(STRUCTURED_ACCOUNT_ENV_IGNORED_WARNING)
})

it('adds no warning to a structured launch that carried none', async () => {
const h = harness(true)
const result = await h.run({ agent: 'claude', target: { kind: 'existing', worktree: 'wt-7' } })
expect(result.warning).toBeUndefined()
})
})
39 changes: 7 additions & 32 deletions src/main/agent-launch/agent-launch-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ import type {
AgentLaunchTarget
} from '../../shared/agent-launch-intent'
import { withoutReservedAgentCreateFields } from '../../shared/agent-launch-intent'
import {
combineLaunchWarnings,
ignoredStructuredLaunchInputsWarning
} from './agent-launch-warnings'
import {
argvLaunchPrompt,
deliverTerminalLaunchPrompt,
Expand Down Expand Up @@ -307,26 +311,12 @@ async function createSurface(
...(session.tabId ? { tabId: session.tabId } : {})
},
structured: session,
...ignoredStructuredAgentArgsWarning(intent)
...ignoredStructuredLaunchInputsWarning(intent)
}
}
return createTerminalSurface(execution, workspace)
}

/**
* Structured chat uses saved Arguments, so a per-call override still needs a truthful warning.
*/
function ignoredStructuredAgentArgsWarning(
intent: AgentLaunchIntent
): { warning: string } | undefined {
return intent.agentArgs === undefined
? undefined
: {
warning:
'Started a structured chat session using saved agent Arguments; the per-launch argument override was ignored.'
}
}

/** What every route that builds a terminal agent passes on, so the startup terminal of a new
* workspace and the terminal of an existing one start the same agent. */
function terminalLaunchInputs(intent: AgentLaunchIntent) {
Expand All @@ -336,7 +326,8 @@ function terminalLaunchInputs(intent: AgentLaunchIntent) {
...(intent.agentArgs !== undefined ? { agentArgs: intent.agentArgs } : {}),
...(intent.cwd ? { cwd: intent.cwd } : {}),
...(intent.launchSource ? { launchSource: intent.launchSource } : {}),
...(intent.paneKey ? { paneKey: intent.paneKey } : {})
...(intent.paneKey ? { paneKey: intent.paneKey } : {}),
...(intent.accountEnv ? { accountEnv: intent.accountEnv } : {})
}
}

Expand Down Expand Up @@ -368,22 +359,6 @@ async function createTerminalSurface(
}
}

/**
* Two warnings, both true, neither droppable.
*
* Mirrors how the create combines its own failures — `appendFailure` in
* runtime-local-worktree-terminal-startup.ts — which append rather than replace.
*/
export function combineLaunchWarnings(
create: string | undefined,
surface: string | undefined
): string | undefined {
if (!create || !surface) {
return create ?? surface
}
return `${create} Also ${surface[0].toLowerCase()}${surface.slice(1)}`
}

function existingWorktreeId(target: AgentLaunchTarget): string {
return target.kind === 'existing' ? target.worktree : ''
}
4 changes: 4 additions & 0 deletions src/main/agent-launch/agent-launch-surface-factories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export type AgentLaunchSurfaceFactory = {
paneKey?: string
/** The tab's first view, derived on the host by the window's own rule. */
viewMode?: 'terminal' | 'chat'
/** Account routing env merged over the agent's own (`agent.launch`'s `accountEnv`). */
accountEnv?: Readonly<Record<string, string>>
}): Promise<{
handle: string
/** The pane this create minted; a factory whose runtime reports none omits it, never invents. */
Expand Down Expand Up @@ -121,6 +123,8 @@ export type AgentLaunchWorkspaceFactory = {
paneKey?: string
/** The launch's session options, read as the startup terminal's model/effort/mode preferences. */
options?: Readonly<Record<string, unknown>>
/** Account routing env merged over the startup agent's own. */
accountEnv?: Readonly<Record<string, string>>
}): Promise<{
worktreeId: string
/** The new workspace's SSH connection; `null` is local. The executor carries it but nothing
Expand Down
35 changes: 35 additions & 0 deletions src/main/agent-launch/agent-launch-warnings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import type { AgentLaunchIntent } from '../../shared/agent-launch-intent'
import { STRUCTURED_ACCOUNT_ENV_IGNORED_WARNING } from '../../shared/agent-launch-account-env'

/**
* Two warnings, both true, neither droppable.
*
* Mirrors how the create combines its own failures — `appendFailure` in
* runtime-local-worktree-terminal-startup.ts — which append rather than replace.
*/
export function combineLaunchWarnings(
create: string | undefined,
surface: string | undefined
): string | undefined {
if (!create || !surface) {
return create ?? surface
}
return `${create} Also ${surface[0].toLowerCase()}${surface.slice(1)}`
}

/**
* Structured chat uses saved Arguments and its host-derived home, so a per-call override of either
* still needs a truthful warning.
*/
export function ignoredStructuredLaunchInputsWarning(
intent: AgentLaunchIntent
): { warning: string } | undefined {
const warning = combineLaunchWarnings(
intent.agentArgs === undefined
? undefined
: 'Started a structured chat session using saved agent Arguments; the per-launch argument override was ignored.',
// Why: a structured home stays host-derived (no client-chosen credential dirs).
intent.accountEnv ? STRUCTURED_ACCOUNT_ENV_IGNORED_WARNING : undefined
)
return warning ? { warning } : undefined
}
9 changes: 9 additions & 0 deletions src/main/claude-accounts/claude-profile-wsl-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,15 @@ describe.skipIf(!posixHost)('ClaudeWslProfileRouter', () => {
expect(f.setup.calls).toBe(3)
})

it('reads usage from the same guest folder a launch (local or WSL-host) runs in', async () => {
const f = fixture()
const launch = await f.router.prepareLaunch('Ubuntu')
const usage = await f.router.accountUsagePreparation('Ubuntu', 'a')
const poll = await f.router.preparation('Ubuntu')
expect(usage.wslLinuxConfigDir).toBe(launch.envPatch.CLAUDE_CONFIG_DIR)
expect(poll.wslLinuxConfigDir).toBe(launch.envPatch.CLAUDE_CONFIG_DIR)
})

it('makes a launch redo a first setup that was cut off after its ownership gate', async () => {
const f = fixture()
mkdirSync(f.profileHome, { recursive: true })
Expand Down
13 changes: 12 additions & 1 deletion src/main/ipc/runtime-environment-connectivity-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
getRuntimeEnvironmentStatus
} from './runtime-environment-transport-routing'
import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key'
import { withWslOrcadAccountEnv } from '../wsl/wsl-orcad-account-env'

function manuallyDisconnectedResponse(
environment: ReturnType<typeof resolveEnvironment>
Expand Down Expand Up @@ -224,13 +225,23 @@ function registerPassiveCallHandler(getUserDataPath: () => string): void {
if (isRuntimeEnvironmentManuallyDisconnected(environment.id)) {
return manuallyDisconnectedResponse(environment)
}
// Why here: every renderer call to a paired host passes this one handler.
const accounts = await withWslOrcadAccountEnv(environment.id, args.method, args.params)
if (!accounts.ok) {
return {
id: args.method,
ok: false,
error: { code: 'account_preparation_failed', message: accounts.message },
_meta: { runtimeId: environment.runtimeId }
}
}
let response: RuntimeRpcResponse<unknown>
try {
response = await callRuntimeEnvironment(
getUserDataPath(),
environment.id,
args.method,
args.params,
accounts.params,
args.timeoutMs,
args.expectedEnvironmentPairingRevision,
undefined,
Expand Down
13 changes: 13 additions & 0 deletions src/main/ipc/wsl-guest-windows-drive-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,16 @@ export function readGuestWindowsDriveMounts(): readonly string[] {
export function _resetGuestWindowsDriveMountsForTests(): void {
cachedGuestMounts = null
}

/** `pathEnv` (default: this process's PATH) without Windows drive dirs on a WSL guest; as given
* elsewhere. For launch-time CLI resolution, which must pick the Linux CLI as detection did. */
export function guestNativePathEnv(
pathEnv: string | null | undefined,
mounts: readonly string[] = readGuestWindowsDriveMounts()
): string | null | undefined {
if (mounts.length === 0) {
return pathEnv
}
const value = pathEnv ?? process.env.PATH ?? null
return value === null ? null : withoutWindowsDriveMountDirs(value, mounts)
}
83 changes: 83 additions & 0 deletions src/main/native-chat/structured-agent-command-guest-path.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type * as DrivePath from '../ipc/wsl-guest-windows-drive-path'

const guest = vi.hoisted((): { mounts: string[] } => ({ mounts: [] }))
vi.mock('../ipc/wsl-guest-windows-drive-path', async (original) => {
const actual = await original<typeof DrivePath>()
return {
...actual,
guestNativePathEnv: (pathEnv: string | null | undefined) =>
actual.guestNativePathEnv(pathEnv, guest.mounts)
}
})

import { guestNativePathEnv } from '../ipc/wsl-guest-windows-drive-path'
import { resolveStructuredAgentCommand } from './structured-agent-command-resolution'

const scratch: string[] = []
afterEach(() => {
guest.mounts = []
vi.unstubAllEnvs()
for (const dir of scratch.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})

function binDir(name: string): string {
const directory = mkdtempSync(join(tmpdir(), `orca-${name}-`))
scratch.push(directory)
for (const binary of ['codex', 'codex-custom']) {
writeFileSync(join(directory, binary), '#!/bin/sh\nexit 0\n')
chmodSync(join(directory, binary), 0o755)
}
return directory
}

// Why posix-only: the guest is Linux; Windows resolution never consults drive mounts.
describe.skipIf(process.platform === 'win32')('launch-time CLI resolution in a WSL guest', () => {
it('skips a Windows shim on a drive mount for the Linux CLI behind it', () => {
const windowsDrive = binDir('drive')
const linuxBin = binDir('linux')
guest.mounts = [windowsDrive]
expect(
resolveStructuredAgentCommand('codex', {}, { pathEnv: `${windowsDrive}:${linuxBin}` })
).toBe(join(linuxBin, 'codex'))
})

it("filters this process's PATH when the caller gives none", () => {
const windowsDrive = binDir('drive')
const linuxBin = binDir('linux')
guest.mounts = [windowsDrive]
vi.stubEnv('PATH', `${windowsDrive}:${linuxBin}`)
expect(resolveStructuredAgentCommand('codex', {})).toBe(join(linuxBin, 'codex'))
})

it('filters the PATH a Command setting resolves through', () => {
const windowsDrive = binDir('drive')
const linuxBin = binDir('linux')
guest.mounts = [windowsDrive]
const settings = {
agentCmdOverrides: { codex: 'codex-custom' },
agentDefaultEnv: { codex: { PATH: `${windowsDrive}:${linuxBin}` } }
}
expect(resolveStructuredAgentCommand('codex', settings)).toBe(join(linuxBin, 'codex-custom'))
})

it('keeps the first PATH match off a guest', () => {
const first = binDir('first')
const second = binDir('second')
expect(resolveStructuredAgentCommand('codex', {}, { pathEnv: `${first}:${second}` })).toBe(
join(first, 'codex')
)
})
})

describe('guestNativePathEnv', () => {
it('returns the PATH as given with no drive mounts', () => {
expect(guestNativePathEnv('/mnt/c/bin:/usr/bin')).toBe('/mnt/c/bin:/usr/bin')
expect(guestNativePathEnv(undefined)).toBeUndefined()
})
})
10 changes: 8 additions & 2 deletions src/main/native-chat/structured-agent-command-resolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
structuredAgentCommandToken
} from '../../shared/tui-agent-launch-command-override'
import { AgentSessionPreSpawnError } from './agent-session-wire/structured-agent-session-adapter'
import { guestNativePathEnv } from '../ipc/wsl-guest-windows-drive-path'

export type StructuredAgentCommandSettings = Partial<
Pick<GlobalSettings, 'agentCmdOverrides' | 'agentDefaultEnv'>
Expand All @@ -26,7 +27,7 @@ function resolveOverride(
return token
? resolveExecutableCommand(token, {
...options,
pathEnv: options.pathEnv ?? overlay?.PATH ?? overlay?.Path
pathEnv: guestNativePathEnv(options.pathEnv ?? overlay?.PATH ?? overlay?.Path)
})
: null
}
Expand All @@ -47,7 +48,12 @@ export function resolveStructuredAgentCommand(
stock: { command?: string; resolve?: typeof resolveCliCommand } = {}
): string {
if (!hasExplicitTuiLaunchCommand(settings, agent)) {
return (stock.resolve ?? resolveCliCommand)(stock.command ?? agent, options)
// Why: inside a WSL guest the inherited PATH ends in /mnt/<drive> dirs holding Windows shims.
const pathEnv = guestNativePathEnv(options.pathEnv)
return (stock.resolve ?? resolveCliCommand)(
stock.command ?? agent,
pathEnv === options.pathEnv ? options : { ...options, pathEnv }
)
}
const command = resolveOverride(agent, settings, options)
if (!command || !spawnableOn(options.platform ?? process.platform, command)) {
Expand Down
Loading
Loading