diff --git a/src/main/native-chat/host-readable-transcript-path.test.ts b/src/main/native-chat/host-readable-transcript-path.test.ts new file mode 100644 index 000000000..97513c788 --- /dev/null +++ b/src/main/native-chat/host-readable-transcript-path.test.ts @@ -0,0 +1,186 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { + isGuestAbsoluteLinuxPath, + needsWslHostTranslation, + resetHostReadableTranscriptPathCacheForTests, + toHostReadableTranscriptPath, + wslCodexSessionsDirs +} from './host-readable-transcript-path' + +const UBUNTU_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' +const DEBIAN_HOME = '\\\\wsl.localhost\\Debian\\home\\other' +const ROLLOUT_LINUX = + '/home/ada/.local/share/orca/codex-runtime-home/home/sessions/2026/07/24/rollout-sess.jsonl' +const ROLLOUT_UNC = + '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\24\\rollout-sess.jsonl' + +beforeEach(() => { + resetHostReadableTranscriptPathCacheForTests() +}) + +describe('isGuestAbsoluteLinuxPath', () => { + it('accepts absolute POSIX guest paths', () => { + expect(isGuestAbsoluteLinuxPath('/home/ada/.codex/sessions/rollout.jsonl')).toBe(true) + }) + + it('rejects UNC, relative, and drive-letter forms', () => { + expect(isGuestAbsoluteLinuxPath('\\\\wsl.localhost\\Ubuntu\\home\\ada\\x.jsonl')).toBe(false) + expect(isGuestAbsoluteLinuxPath('//wsl.localhost/Ubuntu/home/ada/x.jsonl')).toBe(false) + expect(isGuestAbsoluteLinuxPath('relative/path.jsonl')).toBe(false) + expect(isGuestAbsoluteLinuxPath('C:\\Users\\ada\\x.jsonl')).toBe(false) + expect(isGuestAbsoluteLinuxPath('/C:/Users/ada/x.jsonl')).toBe(false) + }) +}) + +describe('needsWslHostTranslation', () => { + it('is win32-only', () => { + expect(needsWslHostTranslation(ROLLOUT_LINUX, 'win32')).toBe(true) + expect(needsWslHostTranslation(ROLLOUT_LINUX, 'darwin')).toBe(false) + expect(needsWslHostTranslation(ROLLOUT_UNC, 'win32')).toBe(false) + }) +}) + +describe('toHostReadableTranscriptPath', () => { + it('translates a WSL guest path to its UNC twin on Windows (#10326)', async () => { + await expect( + toHostReadableTranscriptPath(ROLLOUT_LINUX, { + platform: 'win32', + pathExists: (candidate) => candidate === ROLLOUT_UNC, + listWslHomeDirs: async () => [UBUNTU_HOME] + }) + ).resolves.toBe(ROLLOUT_UNC) + }) + + it('never probes the bare guest path on Windows', async () => { + // Why: Win32 resolves `/home/...` against the current drive (`C:\home\...`), + // so probing first could bind chat to a local look-alike file. + const seen: string[] = [] + await expect( + toHostReadableTranscriptPath('/home/ada/x.jsonl', { + platform: 'win32', + pathExists: (candidate) => { + seen.push(candidate) + return true + }, + listWslHomeDirs: async () => [UBUNTU_HOME] + }) + ).resolves.toBe('\\\\wsl.localhost\\Ubuntu\\home\\ada\\x.jsonl') + expect(seen).not.toContain('/home/ada/x.jsonl') + }) + + it('leaves drive-letter and UNC paths untranslated', async () => { + const existing = ['C:/home/ada/x.jsonl', ROLLOUT_UNC] + for (const path of existing) { + await expect( + toHostReadableTranscriptPath(path, { + platform: 'win32', + pathExists: (candidate) => candidate === path, + listWslHomeDirs: async () => { + throw new Error('should not enumerate distros') + } + }) + ).resolves.toBe(path) + } + }) + + it('tries the distro whose $HOME prefixes the guest path first', async () => { + const seen: string[] = [] + await expect( + toHostReadableTranscriptPath('/home/ada/.codex/sessions/rollout.jsonl', { + platform: 'win32', + pathExists: (candidate) => { + seen.push(candidate) + return true + }, + listWslHomeDirs: async () => [DEBIAN_HOME, UBUNTU_HOME] + }) + ).resolves.toBe('\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions\\rollout.jsonl') + expect(seen).toHaveLength(1) + }) + + it('returns null when no distro maps to an existing file', async () => { + await expect( + toHostReadableTranscriptPath(ROLLOUT_LINUX, { + platform: 'win32', + pathExists: () => false, + listWslHomeDirs: async () => [UBUNTU_HOME] + }) + ).resolves.toBeNull() + }) + + it('does not translate guest paths off Windows', async () => { + await expect( + toHostReadableTranscriptPath('/home/ada/rollout.jsonl', { + platform: 'darwin', + pathExists: (candidate) => candidate === '/home/ada/rollout.jsonl', + listWslHomeDirs: async () => { + throw new Error('should not enumerate distros') + } + }) + ).resolves.toBe('/home/ada/rollout.jsonl') + }) + + it('enumerates WSL homes once across repeated resolve-poll ticks', async () => { + // Why: getWslHomeAsync does not cache failures; re-spawning wsl.exe on every + // 500ms poll tick would hammer the main process. + const listWslHomeDirs = vi.fn(async () => [UBUNTU_HOME]) + for (let tick = 0; tick < 5; tick += 1) { + await toHostReadableTranscriptPath(ROLLOUT_LINUX, { + platform: 'win32', + pathExists: () => false, + listWslHomeDirs + }) + } + await wslCodexSessionsDirs({ platform: 'win32', listWslHomeDirs }) + expect(listWslHomeDirs).toHaveBeenCalledTimes(1) + }) + + it('re-probes after the TTL so a distro that was booting is not excluded forever', async () => { + // Why: getWslHomeAsync returns null for a distro whose 5s $HOME probe timed + // out on a cold boot. Latching that partial list for the process lifetime + // would leave that distro's transcripts permanently unresolvable (#10326). + vi.useFakeTimers() + try { + const listWslHomeDirs = vi + .fn<() => Promise>() + .mockResolvedValueOnce([UBUNTU_HOME]) + .mockResolvedValue([UBUNTU_HOME, DEBIAN_HOME]) + + const debianRollout = '\\\\wsl.localhost\\Debian\\home\\other\\x.jsonl' + const call = (): Promise => + toHostReadableTranscriptPath('/home/other/x.jsonl', { + platform: 'win32', + pathExists: (candidate) => candidate === debianRollout, + listWslHomeDirs + }) + + await expect(call()).resolves.toBeNull() + await expect(call()).resolves.toBeNull() + expect(listWslHomeDirs).toHaveBeenCalledTimes(1) + + vi.setSystemTime(Date.now() + 6 * 60_000) + await expect(call()).resolves.toBe(debianRollout) + expect(listWslHomeDirs).toHaveBeenCalledTimes(2) + } finally { + vi.useRealTimers() + } + }) +}) + +describe('wslCodexSessionsDirs', () => { + it('returns nothing off Windows', async () => { + await expect( + wslCodexSessionsDirs({ platform: 'darwin', listWslHomeDirs: async () => [UBUNTU_HOME] }) + ).resolves.toEqual([]) + }) + + it('lists the managed and system Codex roots per distro home', async () => { + await expect( + wslCodexSessionsDirs({ platform: 'win32', listWslHomeDirs: async () => [UBUNTU_HOME] }) + ).resolves.toEqual([ + `${UBUNTU_HOME}\\.local\\share\\orca\\codex-runtime-home\\home\\sessions`, + `${UBUNTU_HOME}\\.codex\\sessions` + ]) + }) +}) diff --git a/src/main/native-chat/host-readable-transcript-path.ts b/src/main/native-chat/host-readable-transcript-path.ts new file mode 100644 index 000000000..c9ed265dc --- /dev/null +++ b/src/main/native-chat/host-readable-transcript-path.ts @@ -0,0 +1,163 @@ +import { existsSync } from 'node:fs' +import { isAbsolute } from 'node:path' +import { parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths' +import { WSL_CODEX_RUNTIME_HOME_SEGMENTS } from '../pty/codex-home-wsl-env' +import { getWslHomeAsync, listWslDistrosAsync } from '../wsl' + +/** + * True for guest-absolute Linux paths that Win32 cannot open as-is. + * Drive letters, UNC shares, and relative paths are left alone. + */ +export function isGuestAbsoluteLinuxPath(path: string): boolean { + if (!path.startsWith('/') || path.startsWith('//')) { + return false + } + // Why: a Windows drive path normalized with forward slashes (`/C:/…`) must not + // be rewritten as a WSL guest path. + if (/^\/[A-Za-z]:(\/|$)/.test(path)) { + return false + } + return isAbsolute(path) +} + +/** True when this host is Windows and `path` is a WSL guest path it cannot open. */ +export function needsWslHostTranslation( + path: string, + platform: NodeJS.Platform = process.platform +): boolean { + return platform === 'win32' && isGuestAbsoluteLinuxPath(path.trim()) +} + +export type HostReadableTranscriptPathDeps = { + platform?: NodeJS.Platform + pathExists?: (path: string) => boolean + /** Each installed WSL distro's `$HOME` as a Windows UNC path. */ + listWslHomeDirs?: () => Promise +} + +// Why: resolveSessionFilePath runs on a 500ms–5s poll loop. listWslDistrosAsync +// caches, but getWslHomeAsync does NOT cache failures, so a cold/stopped distro +// would re-spawn wsl.exe on every tick. Cache the composed answer here instead. +const WSL_HOME_DIRS_EMPTY_RETRY_MS = 30_000 +// Why: a distro that was booting when we first probed resolves to no $HOME and +// would otherwise be excluded for the whole session. Both branches expire so it +// is retried; getWslHomeAsync caches successes, so a refresh only re-spawns +// wsl.exe for the distros that actually failed. +const WSL_HOME_DIRS_TTL_MS = 5 * 60_000 +let cachedWslHomeDirs: string[] | null = null +let cachedWslHomeDirsExpiresAt = 0 +let inflightWslHomeDirs: Promise | null = null + +async function defaultListWslHomeDirs(): Promise { + const homes = await Promise.all( + (await listWslDistrosAsync()).map((distro) => getWslHomeAsync(distro)) + ) + return homes.filter((home): home is string => Boolean(home)) +} + +async function wslHomeDirs(load: () => Promise): Promise { + if (cachedWslHomeDirs && Date.now() < cachedWslHomeDirsExpiresAt) { + return cachedWslHomeDirs + } + if (inflightWslHomeDirs) { + return inflightWslHomeDirs + } + inflightWslHomeDirs = load() + .catch(() => [] as string[]) + .then((dirs) => { + cachedWslHomeDirs = dirs + cachedWslHomeDirsExpiresAt = + Date.now() + (dirs.length > 0 ? WSL_HOME_DIRS_TTL_MS : WSL_HOME_DIRS_EMPTY_RETRY_MS) + inflightWslHomeDirs = null + return dirs + }) + return inflightWslHomeDirs +} + +export function resetHostReadableTranscriptPathCacheForTests(): void { + cachedWslHomeDirs = null + cachedWslHomeDirsExpiresAt = 0 + inflightWslHomeDirs = null +} + +/** + * Map a hook-reported transcript path to a path the local main process can open. + * + * WSL Codex hooks report guest Linux paths (`/home/…/rollout-….jsonl`). On + * Windows the main process must open the equivalent `\\wsl.localhost\…` UNC + * form; without this, Chat UI never finds the live transcript (#10326). + * + * Non-guest paths (macOS/Linux hosts, SSH remote mains, already-UNC or drive + * paths) are returned unchanged when they exist. When translation is needed, + * distros whose `$HOME` prefixes the guest path are tried first so multi-distro + * machines pick the owner. + */ +export async function toHostReadableTranscriptPath( + transcriptPath: string, + deps: HostReadableTranscriptPathDeps = {} +): Promise { + const path = transcriptPath.trim() + if (!path) { + return null + } + const pathExists = deps.pathExists ?? existsSync + const platform = deps.platform ?? process.platform + // Why: classify BEFORE probing — Win32 resolves a bare `/home/…` against the + // current drive (`C:\home\…`), so a probe first could bind chat to a local + // look-alike file instead of the real WSL transcript. + if (!needsWslHostTranslation(path, platform)) { + return pathExists(path) ? path : null + } + + const homeDirs = await wslHomeDirs(deps.listWslHomeDirs ?? defaultListWslHomeDirs) + for (const distro of rankDistrosForGuestPath(homeDirs, path)) { + const uncPath = toWindowsWslPath(path, distro) + if (pathExists(uncPath)) { + return uncPath + } + } + return null +} + +function rankDistrosForGuestPath(wslHomeUncDirs: readonly string[], guestPath: string): string[] { + const preferred: string[] = [] + const others: string[] = [] + for (const homeUnc of wslHomeUncDirs) { + const parsed = parseWslUncPath(homeUnc) + if (!parsed || preferred.includes(parsed.distro) || others.includes(parsed.distro)) { + continue + } + const guestHome = parsed.linuxPath.replace(/\/+$/, '') + if (guestHome && (guestPath === guestHome || guestPath.startsWith(`${guestHome}/`))) { + preferred.push(parsed.distro) + } else { + others.push(parsed.distro) + } + } + return [...preferred, ...others] +} + +/** + * WSL Codex sessions live under the guest home, not Windows AppData. Mirror AI + * Vault's dual-root discovery so the id-based resolve still finds them when the + * hook path is absent. + */ +export async function wslCodexSessionsDirs( + deps: Pick = {} +): Promise { + const platform = deps.platform ?? process.platform + if (platform !== 'win32') { + return [] + } + const homeDirs = await wslHomeDirs(deps.listWslHomeDirs ?? defaultListWslHomeDirs) + return homeDirs.flatMap((home) => [ + joinUnderWslHome(home, ...WSL_CODEX_RUNTIME_HOME_SEGMENTS, 'sessions'), + joinUnderWslHome(home, '.codex', 'sessions') + ]) +} + +// Why: node:path.join is posix-flavoured off Windows and would mangle the +// `\\wsl.localhost\` share prefix these roots must keep. +function joinUnderWslHome(home: string, ...segments: string[]): string { + return `${home.replace(/[\\/]+$/, '')}\\${segments.join('\\')}` +} diff --git a/src/main/native-chat/session-file-resolver-wsl.test.ts b/src/main/native-chat/session-file-resolver-wsl.test.ts new file mode 100644 index 000000000..6195fca93 --- /dev/null +++ b/src/main/native-chat/session-file-resolver-wsl.test.ts @@ -0,0 +1,100 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsModule from 'node:fs' + +const UBUNTU_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' +const WSL_MANAGED_SESSIONS_DIR = `${UBUNTU_HOME}\\.local\\share\\orca\\codex-runtime-home\\home\\sessions` +const ROLLOUT_LINUX = + '/home/ada/.local/share/orca/codex-runtime-home/home/sessions/2026/07/24/rollout-wsl-sess.jsonl' +const ROLLOUT_UNC = + '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\24\\rollout-wsl-sess.jsonl' + +vi.mock('../wsl', () => ({ + listWslDistrosAsync: vi.fn(async () => ['Ubuntu']), + getWslHomeAsync: vi.fn(async () => UBUNTU_HOME) +})) + +// Only WSL UNC paths are readable; the guest Linux path is not (as on a real +// Windows host, where it would misresolve against the current drive). +const fsState = vi.hoisted(() => ({ existsAll: false })) +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + existsSync: (path: string) => + fsState.existsAll || path.startsWith('\\\\wsl.localhost\\') || actual.existsSync(path) + } +}) + +const HOST_ROLLOUT = 'C:\\host\\sessions\\rollout-wsl-sess.jsonl' +const scanned = vi.hoisted(() => ({ dirs: [] as string[], hostRootHasRollout: false })) +vi.mock('../ai-vault/session-scanner-discovery', () => ({ + walkSessionFiles: async (dir: string) => { + scanned.dirs.push(dir) + const isWslRoot = dir.startsWith('\\\\wsl.localhost\\') + return scanned.hostRootHasRollout && !isWslRoot + ? ['C:\\host\\sessions\\rollout-wsl-sess.jsonl'] + : [] + } +})) + +import { resetHostReadableTranscriptPathCacheForTests } from './host-readable-transcript-path' +import { resolveSessionFilePath } from './session-file-resolver' +import { getWslHomeAsync, listWslDistrosAsync } from '../wsl' + +const realPlatform = process.platform + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) +} + +beforeEach(() => { + resetHostReadableTranscriptPathCacheForTests() + vi.mocked(getWslHomeAsync).mockClear() + vi.mocked(listWslDistrosAsync).mockClear() + scanned.dirs = [] + scanned.hostRootHasRollout = false + fsState.existsAll = false + setPlatform('win32') +}) + +afterEach(() => { + setPlatform(realPlatform) +}) + +describe('resolveSessionFilePath on a Windows host with WSL', () => { + it('translates a WSL hook transcript path to its host-readable UNC twin (#10326)', async () => { + const resolved = await resolveSessionFilePath('codex', 'wsl-sess', { + transcriptPath: ROLLOUT_LINUX, + codexSessionsDirs: [] + }) + expect(resolved).toBe(ROLLOUT_UNC) + }) + + it('searches the WSL managed Codex sessions root when no hook path is known', async () => { + await resolveSessionFilePath('codex', 'wsl-sess') + expect(scanned.dirs).toContain(WSL_MANAGED_SESSIONS_DIR) + expect(scanned.dirs).toContain(`${UBUNTU_HOME}\\.codex\\sessions`) + }) + + it('does not enumerate WSL distros when a host Codex root already has the rollout', async () => { + // Why: listing WSL homes spawns wsl.exe per distro, which boots distros the + // user deliberately left stopped. It must stay a last resort. + fsState.existsAll = true + scanned.hostRootHasRollout = true + + await expect(resolveSessionFilePath('codex', 'wsl-sess')).resolves.toBe(HOST_ROLLOUT) + + expect(scanned.dirs.some((dir) => dir.startsWith('\\\\wsl.localhost\\'))).toBe(false) + expect(vi.mocked(listWslDistrosAsync)).not.toHaveBeenCalled() + expect(vi.mocked(getWslHomeAsync)).not.toHaveBeenCalled() + }) + + it('leaves the guest path alone on non-Windows hosts', async () => { + setPlatform('darwin') + const resolved = await resolveSessionFilePath('codex', 'wsl-sess', { + transcriptPath: ROLLOUT_LINUX, + codexSessionsDirs: [] + }) + expect(resolved).toBeNull() + }) +}) diff --git a/src/main/native-chat/session-file-resolver.ts b/src/main/native-chat/session-file-resolver.ts index 136e3ea22..2761f99ea 100644 --- a/src/main/native-chat/session-file-resolver.ts +++ b/src/main/native-chat/session-file-resolver.ts @@ -11,6 +11,7 @@ import { findGrokChatHistoryBySessionId, resolveGrokSessionsDir } from '../../shared/grok-session-paths' +import { toHostReadableTranscriptPath, wslCodexSessionsDirs } from './host-readable-transcript-path' // Why: these mirror the path constants in ai-vault/session-scanner.ts. Reads // run in the main process against the runtime's own home directory; over SSH @@ -27,6 +28,7 @@ function claudeProjectsDir(): string { // first (that's where this main process's Codex sessions actually live), then // fall back to CODEX_HOME/~/.codex so a non-Orca Codex transcript still resolves. // Duplicates are filtered so a managed-home symlink to ~/.codex isn't scanned twice. +// WSL roots are a separate lazy tier — see resolveCodexSessionFile. function codexSessionsDirs(): string[] { const candidates = [ join(getOrcaManagedCodexHomePath(), 'sessions'), @@ -85,12 +87,15 @@ export async function resolveSessionFilePath( return null } // Why: the hook's transcript_path is the exact file the agent is writing, so it - // beats reconstructing a path from the session id. Guard with existsSync so a - // stale/remote path falls through to the id-based search rather than returning - // a non-existent file. + // beats reconstructing a path from the session id. Route it through the host + // readability check so a WSL guest path becomes an openable UNC on Windows; + // stale/missing paths fall through to the id-based search. const hookPath = options.transcriptPath?.trim() - if (hookPath && extname(hookPath) === '.jsonl' && existsSync(hookPath)) { - return hookPath + if (hookPath && extname(hookPath) === '.jsonl') { + const hostReadable = await toHostReadableTranscriptPath(hookPath) + if (hostReadable) { + return hostReadable + } } const trimmedId = sessionId.trim() @@ -102,7 +107,14 @@ export async function resolveSessionFilePath( return resolveClaudeSessionFile(trimmedId, options.claudeProjectsDir ?? claudeProjectsDir()) } if (transcriptAgent === 'codex') { - return resolveCodexSessionFile(trimmedId, options.codexSessionsDirs ?? codexSessionsDirs()) + const overrideDirs = options.codexSessionsDirs + return resolveCodexSessionFile( + trimmedId, + overrideDirs ?? codexSessionsDirs(), + // Why: enumerating WSL homes spawns wsl.exe per distro, which boots ones the + // user left stopped. Only pay that after this host's own Codex roots miss. + overrideDirs ? undefined : wslCodexSessionsDirs + ) } if (transcriptAgent === 'grok') { return resolveGrokSessionFile(trimmedId, options.grokSessionsDir ?? grokSessionsDir()) @@ -127,11 +139,29 @@ async function resolveClaudeSessionFile( async function resolveCodexSessionFile( sessionId: string, - sessionsDirs: string[] + sessionsDirs: string[], + loadFallbackDirs?: () => Promise ): Promise { // Codex rollout file names embed the session id (rollout--.jsonl), so // match the id as a suffix of the file's base name rather than an exact name. // Search each candidate root (managed home first) and stop at the first match. + const hit = await findCodexRolloutInDirs(sessionId, sessionsDirs) + if (hit) { + return hit + } + if (!loadFallbackDirs) { + return null + } + // Why: a WSL-hosted session's rollout only exists inside the distro, so fall + // back to each distro's Codex homes when the host's own roots came up empty (#10326). + const fallbackDirs = (await loadFallbackDirs()).filter((dir) => !sessionsDirs.includes(dir)) + return findCodexRolloutInDirs(sessionId, fallbackDirs) +} + +async function findCodexRolloutInDirs( + sessionId: string, + sessionsDirs: string[] +): Promise { for (const sessionsDir of sessionsDirs) { if (!existsSync(sessionsDir)) { continue diff --git a/src/main/native-chat/transcript-watch-resolve-poll.test.ts b/src/main/native-chat/transcript-watch-resolve-poll.test.ts index be4e60ded..3dd336596 100644 --- a/src/main/native-chat/transcript-watch-resolve-poll.test.ts +++ b/src/main/native-chat/transcript-watch-resolve-poll.test.ts @@ -1,8 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as HostReadableTranscriptPathModule from './host-readable-transcript-path' const mocks = vi.hoisted(() => ({ install: vi.fn(), - resolve: vi.fn() + resolve: vi.fn(), + toHostReadable: vi.fn() })) vi.mock('./session-file-resolver', () => ({ @@ -12,17 +14,35 @@ vi.mock('./transcript-watch-engine', () => ({ getActiveNativeChatWatcherCount: vi.fn(() => 0), installTranscriptWatcher: mocks.install })) +vi.mock('./host-readable-transcript-path', async (importOriginal) => ({ + ...(await importOriginal()), + toHostReadableTranscriptPath: mocks.toHostReadable +})) import { subscribeNativeChatTranscript } from './transcript-watch' +const realPlatform = process.platform + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) +} + describe('native chat transcript resolve polling', () => { beforeEach(() => { vi.useFakeTimers() mocks.install.mockReset().mockReturnValue(null) mocks.resolve.mockReset().mockResolvedValue(null) + mocks.toHostReadable.mockReset().mockResolvedValue(null) + // Why: a POSIX exact path is a WSL guest path on win32 and is deliberately + // never installed raw there, so pin the platform instead of inheriting the + // host's — otherwise these cases only hold on non-Windows machines. + setPlatform('linux') }) - afterEach(() => vi.useRealTimers()) + afterEach(() => { + setPlatform(realPlatform) + vi.useRealTimers() + }) it('fast-probes an exact hook path without repeatedly scanning the session tree', async () => { const subscription = await subscribeNativeChatTranscript({ @@ -47,6 +67,51 @@ describe('native chat transcript resolve polling', () => { expect(mocks.install).toHaveBeenCalledTimes(callsAfterUnsubscribe) }) + it('retries the WSL translation on the slow cadence, never installing the raw guest path', async () => { + // Why: each translation sync-stats the UNC twin per distro over the 9P + // share; doing it every fast tick would hammer the main process (#10326). + setPlatform('win32') + const subscription = await subscribeNativeChatTranscript({ + agent: 'codex', + sessionId: 'session-id', + transcriptPath: '/home/ada/.codex/sessions/rollout-session-id.jsonl', + resolvePollIntervalMs: 10, + onAppend: () => {} + }) + + await vi.advanceTimersByTimeAsync(100) + expect(mocks.toHostReadable).toHaveBeenCalledTimes(1) + expect(mocks.install.mock.calls.some(([filePath]) => String(filePath).startsWith('/'))).toBe( + false + ) + + await vi.advanceTimersByTimeAsync(5_100) + expect(mocks.toHostReadable).toHaveBeenCalledTimes(2) + + subscription.unsubscribe() + }) + + it('installs the translated UNC path once the WSL transcript becomes readable', async () => { + setPlatform('win32') + const unc = '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.codex\\sessions\\rollout-session-id.jsonl' + mocks.toHostReadable.mockResolvedValue(unc) + + const subscription = await subscribeNativeChatTranscript({ + agent: 'codex', + sessionId: 'session-id', + transcriptPath: '/home/ada/.codex/sessions/rollout-session-id.jsonl', + resolvePollIntervalMs: 10, + onAppend: () => {} + }) + + await vi.advanceTimersByTimeAsync(100) + expect(mocks.install.mock.calls.some(([filePath]) => filePath === unc)).toBe(true) + // Memoized: a successful translation is not re-probed on later ticks. + expect(mocks.toHostReadable).toHaveBeenCalledTimes(1) + + subscription.unsubscribe() + }) + it('keeps resolving on every retry when no exact hook path is available', async () => { const subscription = await subscribeNativeChatTranscript({ agent: 'claude', diff --git a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts new file mode 100644 index 000000000..e84bc329c --- /dev/null +++ b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as NodeFsModule from 'node:fs' + +const UBUNTU_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\ada' +const ROLLOUT_LINUX = + '/home/ada/.local/share/orca/codex-runtime-home/home/sessions/2026/07/24/rollout-wsl.jsonl' +const ROLLOUT_UNC = + '\\\\wsl.localhost\\Ubuntu\\home\\ada\\.local\\share\\orca\\codex-runtime-home\\home\\sessions\\2026\\07\\24\\rollout-wsl.jsonl' + +const mocks = vi.hoisted(() => ({ + install: vi.fn(), + resolve: vi.fn() +})) + +vi.mock('./session-file-resolver', () => ({ + resolveSessionFilePath: mocks.resolve +})) +vi.mock('./transcript-watch-engine', () => ({ + getActiveNativeChatWatcherCount: vi.fn(() => 0), + installTranscriptWatcher: mocks.install +})) +vi.mock('../wsl', () => ({ + listWslDistrosAsync: vi.fn(async () => ['Ubuntu']), + getWslHomeAsync: vi.fn(async () => UBUNTU_HOME) +})) +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + existsSync: (path: string) => path === ROLLOUT_UNC || actual.existsSync(path) + } +}) + +import { resetHostReadableTranscriptPathCacheForTests } from './host-readable-transcript-path' +import { subscribeNativeChatTranscript } from './transcript-watch' + +const realPlatform = process.platform + +function setPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) +} + +describe('exact hook path install on a Windows host with WSL (#10326)', () => { + beforeEach(() => { + vi.useFakeTimers() + resetHostReadableTranscriptPathCacheForTests() + mocks.install.mockReset().mockReturnValue(null) + mocks.resolve.mockReset().mockResolvedValue(null) + }) + + afterEach(() => { + vi.useRealTimers() + setPlatform(realPlatform) + }) + + it('installs the watcher on the WSL UNC twin of the guest transcript path', async () => { + setPlatform('win32') + const subscription = await subscribeNativeChatTranscript({ + agent: 'codex', + sessionId: 'wsl-sess', + transcriptPath: ROLLOUT_LINUX, + resolvePollIntervalMs: 10, + onAppend: () => {} + }) + + await vi.advanceTimersByTimeAsync(50) + expect(mocks.install).toHaveBeenCalledWith(ROLLOUT_UNC, expect.anything(), expect.anything()) + expect(mocks.install.mock.calls.every(([path]) => path !== ROLLOUT_LINUX)).toBe(true) + subscription.unsubscribe() + }) + + it('passes the raw path through untouched off Windows', async () => { + setPlatform('darwin') + const subscription = await subscribeNativeChatTranscript({ + agent: 'codex', + sessionId: 'wsl-sess', + transcriptPath: ROLLOUT_LINUX, + resolvePollIntervalMs: 10, + onAppend: () => {} + }) + + await vi.advanceTimersByTimeAsync(50) + expect(mocks.install).toHaveBeenCalledWith(ROLLOUT_LINUX, expect.anything(), expect.anything()) + subscription.unsubscribe() + }) +}) diff --git a/src/main/native-chat/transcript-watch.ts b/src/main/native-chat/transcript-watch.ts index 72c609b02..cc02c70c3 100644 --- a/src/main/native-chat/transcript-watch.ts +++ b/src/main/native-chat/transcript-watch.ts @@ -1,5 +1,9 @@ import { extname } from 'node:path' import type { NativeChatMessage } from '../../shared/native-chat-types' +import { + needsWslHostTranslation, + toHostReadableTranscriptPath +} from './host-readable-transcript-path' import { resolveSessionFilePath } from './session-file-resolver' import { installTranscriptWatcher } from './transcript-watch-engine' import type { @@ -60,6 +64,11 @@ function subscribeViaResolvePoll( let delay = args.resolvePollIntervalMs ?? INITIAL_RESOLVE_POLL_MS let lastFallbackResolveAt = Date.now() const exactPath = exactTranscriptPath(args) + // Why: WSL hooks report guest Linux paths the Windows host cannot open; the + // UNC twin is resolved lazily (the distro may still be cold) and memoized so + // the exact-path install doesn't wait on the slower id-glob (#10326). + let hostReadableExactPath: string | null = null + let lastWslTranslateAt = 0 function scheduleAttempt(): void { if (closed) { @@ -91,7 +100,24 @@ function subscribeViaResolvePoll( } let result: NativeChatTranscriptSubscription | null try { - result = exactPath ? await attemptInstall({ ...args, filePath: exactPath }, decode) : null + if (exactPath && !hostReadableExactPath) { + if (!needsWslHostTranslation(exactPath)) { + // Non-WSL paths stay raw: installTranscriptWatcher already handles a + // not-yet-created file, so don't spend an extra probe per tick. + hostReadableExactPath = exactPath + } else if (Date.now() - lastWslTranslateAt >= FALLBACK_RESOLVE_POLL_MS) { + // Why: translating sync-stats the UNC twin per distro over the 9P + // share, and the guest file usually appears well after the hook does, + // so retry on the slow cadence rather than every fast tick. The raw + // guest path is never installed on Windows — it would resolve against + // the current drive (`C:\home\…`) and bind chat to a look-alike file. + lastWslTranslateAt = Date.now() + hostReadableExactPath = await toHostReadableTranscriptPath(exactPath) + } + } + result = hostReadableExactPath + ? await attemptInstall({ ...args, filePath: hostReadableExactPath }, decode) + : null if ( !result && (!exactPath || Date.now() - lastFallbackResolveAt >= FALLBACK_RESOLVE_POLL_MS)