fix(subprocess-local): probe Linux again after a scope never starts or a new manager listens

A cached positive verdict let a hung user manager that still listens fail every
later command, and a cached negative verdict ignored a manager that started
later until the provider restarted.

- A scope launch whose bootstrap never consumed its launch request now fails
  with LinuxScopeNotStartedError, and the runtime clears the verdict it
  launched under, so the next eligible spawn probes again and records the
  fallback when that probe fails. A generation counter keeps launches from a
  superseded probe from forcing another probe.
- After a negative verdict, the runtime records the /proc/net/unix listener on
  $XDG_RUNTIME_DIR/systemd/private and probes again only when a different
  listener, meaning a new manager instance, appears.
This commit is contained in:
imccyu committed 2026-10-15 00:14:50 +08:00
1 parent 514e8893b5
commit 71de43d8ee
7 files changed
+189 -36

No files matched your search

@@ -63,8 +63,8 @@
en: e290ccc9b3c92c08
zh: d75d48f485447a74
/deepseek-ai-dsh-subprocess-local/known-limitations-and-deferred-work:
en: 48cf945eccc6d26d
zh: 85ae7fbfdd1fe5b9
en: e9e76a139fbbd62b
zh: 3d3ae5dbbee39cf4
/deepseek-ai-dsh-subprocess-local/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
@@ -147,7 +147,7 @@ These limits define when the provider is a poor fit or needs special operational
- **Linux direct exit has no independent deadline** — after direct `SIGKILL` is acknowledged, uninterruptible kernel I/O can keep disposal pending indefinitely; `graceMs` and scope-query polling budgets do not bound this wait.
- **Native ownership has explicit host requirements** — Linux needs a readable user manager whose `systemd-run` supports `--collect` (systemd 236 and later) and keeps scope arguments literal: version 254 and later receive `--expand-environment=no`, and earlier versions, whose scope mode never expands arguments, run without it. Hosts without a usable user manager use the warned PGID fallback. macOS always uses that fallback because no supported public persistent owner exists.
- **Native selection has bounded per-spawn costs** — Linux checks the bootstrap entry, libc `execve`/`fcntl` bindings, reachable user manager, and literal-argv scope probe once, on the first eligible ordinary or terminal spawn, and keeps that verdict for the provider lifetime, including a failed or timed-out first probe, so a user manager that starts later is used only after the provider restarts. After a positive verdict, each eligible spawn confirms the user manager: when the kernel's unix socket table (`/proc/net/unix`) shows a process in the same network namespace listening on `$XDG_RUNTIME_DIR/systemd/private`, the socket `systemd-run --user` connects through, no child process runs, and the read costs time proportional to that table's size; otherwise one `systemctl --user show` query decides, and that spawn uses the fallback when the query fails. A hung manager that still listens makes scope launches fail. Windows rechecks the runner entry, bindings, and current Job support before every ordinary spawn. Fallback-warning de-duplication also persists for the provider lifetime. All probes finish before the user command can run; each child-process probe has a 5-second timeout, and a `systemd-run` that rejects `--expand-environment=no` is probed once more without it. Each Linux launch creates a private request directory, checks unresolved scope establishment every 50 milliseconds, then exponentially backs off an established active scope to at most 5 seconds between queries; a Windows ordinary launch keeps one runner and IPC channel until the Job reports zero active processes. Target standard handles are inherited directly, with no named-pipe stdio or result files.
- **Native selection has bounded per-spawn costs** — Linux checks the bootstrap entry, libc `execve`/`fcntl` bindings, reachable user manager, and literal-argv scope probe on the first eligible ordinary or terminal spawn and keeps that verdict, including a failed or timed-out probe. The user manager is identified by the process listening on `$XDG_RUNTIME_DIR/systemd/private`, the socket `systemd-run --user` connects through, as listed in the kernel's unix socket table (`/proc/net/unix`) for the same network namespace; reading the table costs time proportional to its size. After a positive verdict, each eligible spawn confirms the manager: a listener confirms it without a child process; otherwise one `systemctl --user show` query decides, and that spawn uses the fallback when the query fails. A scope launch whose bootstrap never consumed its launch request, such as one sent to a hung manager that still listens, fails that command, and the next eligible spawn probes again. After a negative verdict, the provider probes again only when a different listener appears, so a manager that starts later is used without a restart. Windows rechecks the runner entry, bindings, and current Job support before every ordinary spawn. Fallback-warning de-duplication also persists for the provider lifetime. All probes finish before the user command can run; each child-process probe has a 5-second timeout, and a `systemd-run` that rejects `--expand-environment=no` is probed once more without it. Each Linux launch creates a private request directory, checks unresolved scope establishment every 50 milliseconds, then exponentially backs off an established active scope to at most 5 seconds between queries; a Windows ordinary launch keeps one runner and IPC channel until the Job reports zero active processes. Target standard handles are inherited directly, with no named-pipe stdio or result files.
- **Windows Job inheritance has defined exclusions** — ordinary descendants inherit the Job by default, but breakaway processes are outside the guarantee. The target starts only after Job assignment; external termination of the runner in the narrow create-to-assignment interval can leave a suspended target behind.
- **Windows terminal signalling is console-wide** — SIGINT is delivered as a `\x03` Ctrl-C input write that the console host turns into a console-wide CTRL_C event (on Windows that host is node-pty's bundled OpenConsole); SIGTSTP and SIGHUP are rejected as unavailable; a `taskkill` without `/F` does not terminate console processes, so the teardown TERM tier is a grace wait before the `/F` escalation. Windows readiness has no exact stdin-wait tier: the prompt-marker fast path compares the shell pid as the pseudo foreground group, and silence/timing tiers cover the rest.
- **Windows terminal allocation requires node-pty's bundled console host assets** — every Windows terminal is spawned with `useConptyDll: true`, so allocation resolves `conpty/conpty.dll` and `OpenConsole.exe` relative to node-pty's own addon; an asset that is missing or unpacked wrong makes `spawnTerminal` throw instead of falling back to the operating system console host. node-pty marks the option experimental, so a node-pty upgrade can change this behaviour. See the [bundled console host note](../../../.agents/notes/implemented/bug-fix/2026-09-28-pty-bundled-console-host.md).
@@ -147,7 +147,7 @@ spill 文件以 `0600` 权限、`O_EXCL` 与随机名称在 `0700` 每进程目
- **Linux 直接进程退出没有独立截止时间**——直接 `SIGKILL` 获得确认后,不可中断的内核 I/O 可能让 dispose 无限期等待;`graceMs` 和 scope 查询的轮询预算不限制此等待。
- **native ownership 有明确宿主要求**——Linux 需要可读的 user manager,且其 `systemd-run` 支持 `--collect`(systemd 236 及以上)并保持 scope 参数按字面传递:254 及以上版本传入 `--expand-environment=no`,更早版本的 scope 模式从不展开参数,因此不传该选项。没有可用 user manager 的宿主使用带告警的 PGID fallback。macOS 因没有受支持的公开 persistent owner,始终使用该 fallback。
- **native 选择具有有界的每次 spawn 成本**——Linux 只在第一次符合条件的普通命令或终端 spawn 时检查一次 bootstrap 入口、libc `execve`/`fcntl` bindings、可连接的 user manager 与 literal-argv scope 支持,并在提供方生命周期内保留这一结论,首次探测失败或超时的结论也是如此,因此之后才启动的 user manager 要等提供方重启后才会被使用。结论为可用时,每次符合条件的 spawn 都会确认 user manager:内核的 unix socket 表(`/proc/net/unix`)显示同一网络命名空间中有进程在 `$XDG_RUNTIME_DIR/systemd/private`(`systemd-run --user` 连接 manager 所用的 socket)上监听时,无需子进程即可确认,读取耗时与该表的大小成正比;否则由一次 `systemctl --user show` 查询决定,查询失败时这次 spawn 使用 fallback。卡死但仍在监听的 manager 会让 scope 启动失败。Windows 会在每次普通 spawn 前重新检查 runner 入口、bindings 与当前 Job 支持。fallback 告警去重同样在提供方生命周期内持续保留。所有探测都会在用户命令可能运行前完成;每次子进程探测的超时为 5 秒,`systemd-run` 拒绝 `--expand-environment=no` 时会去掉该选项再探测一次。每次 Linux 启动都会创建私有请求目录,以 50 毫秒间隔检查尚未确定的 scope 建立状态;scope 已建立且仍 active 后,查询间隔按指数增长,最多为 5 秒。Windows 普通命令会保留一个 runner 与一条 IPC 通道,直到 Job 报告活动进程数为零。目标会直接继承标准句柄,不使用 named-pipe stdio 或结果文件。
- **native 选择具有有界的每次 spawn 成本**——Linux 在第一次符合条件的普通命令或终端 spawn 时检查 bootstrap 入口、libc `execve`/`fcntl` bindings、可连接的 user manager 与 literal-argv scope 支持,并保留这一结论,探测失败或超时的结论也是如此。user manager 以内核 unix socket 表(`/proc/net/unix`)中同一网络命名空间里在 `$XDG_RUNTIME_DIR/systemd/private`(`systemd-run --user` 连接 manager 所用的 socket)上监听的进程来识别;读取该表的耗时与表的大小成正比。结论为可用时,每次符合条件的 spawn 都会确认 manager:有监听者时无需子进程即可确认;否则由一次 `systemctl --user show` 查询决定,查询失败时这次 spawn 使用 fallback。bootstrap 从未消费 launch request 的 scope 启动(例如发给卡死但仍在监听的 manager)会让这条命令失败,下一次符合条件的 spawn 会重新探测。结论为不可用时,只有出现不同的监听者才会重新探测,因此之后才启动的 manager 无需重启即可被使用。Windows 会在每次普通 spawn 前重新检查 runner 入口、bindings 与当前 Job 支持。fallback 告警去重同样在提供方生命周期内持续保留。所有探测都会在用户命令可能运行前完成;每次子进程探测的超时为 5 秒,`systemd-run` 拒绝 `--expand-environment=no` 时会去掉该选项再探测一次。每次 Linux 启动都会创建私有请求目录,以 50 毫秒间隔检查尚未确定的 scope 建立状态;scope 已建立且仍 active 后,查询间隔按指数增长,最多为 5 秒。Windows 普通命令会保留一个 runner 与一条 IPC 通道,直到 Job 报告活动进程数为零。目标会直接继承标准句柄,不使用 named-pipe stdio 或结果文件。
- **Windows Job inheritance 有明确排除项**——普通后代默认继承 Job,但 breakaway 进程不在保证范围。目标只在 Job 分配后启动;runner 若在 create-to-assignment 极窄区间遭外力终止,可能留下 suspended target。
- **Windows 终端信号是控制台级的**——SIGINT 以 `\x03` Ctrl-C 输入写入投递,由控制台宿主(Windows 上为 node-pty 自带的 OpenConsole)转为控制台级 CTRL_C 事件;SIGTSTP 与 SIGHUP 被拒绝(不可用);不带 `/F` 的 `taskkill` 无法终止控制台进程,因此拆卸的 TERM 档是 `/F` 升级前的宽限等待。Windows 就绪没有精确的 stdin-wait 档:prompt-marker 快路径把 shell pid 作为伪前台进程组比较,其余由静默与计时档覆盖。
- **Windows 终端分配依赖 node-pty 自带的控制台宿主资产**——每个 Windows 终端都以 `useConptyDll: true` 启动,分配时按 node-pty 自身 addon 的相对位置解析 `conpty/conpty.dll` 与 `OpenConsole.exe`;资产缺失或解包错误会让 `spawnTerminal` 抛错,而不是回退到操作系统控制台宿主。node-pty 把该选项标为实验性,升级 node-pty 可能改变这一行为。见[自带控制台宿主说明](../../../.agents/notes/implemented/bug-fix/2026-09-28-pty-bundled-console-host.zh.md)。
@@ -35,7 +35,9 @@ import { logSpillFailure, prepareManagedProcessBinding } from './output.ts'
import type { LocalSubprocessHandle, SpawnInternals } from './spawn.ts'
import {
confirmLinuxManager,
LinuxScopeNotStartedError,
launchLinuxScope,
linuxManagerListener,
prepareLinuxTerminalScope,
probeLinuxNative,
signalLinuxDirectProcess,
@@ -68,13 +70,18 @@ export class LocalSubprocessRuntime extends SubprocessRuntime {
internals: SpawnInternals = {}
/** Provider-lifetime latch suppressing repeated weaker-containment warnings. */
private fallbackWarningIssued = false
/** Whether the first eligible ordinary or terminal spawn has run the Linux native probe. */
/** Whether linuxLiteralArgv holds a Linux native probe result; cleared when that result must be probed again. */
private linuxProbed = false
/**
* Provider-lifetime result of that probe: literal-argv scope options, or undefined when unavailable.
* Each probe is a spawnSync that blocks the event loop and forks the host, so later spawns only confirm the user manager.
* Latest Linux native probe result: literal-argv scope options, or undefined when unavailable. Each probe is a
* spawnSync that blocks the event loop and forks the host, so it reruns only after a scope never started its
* target or a new user-manager listener appeared; a positive result otherwise only confirms the manager per spawn.
*/
private linuxLiteralArgv: LiteralArgvOptions | undefined
/** Count of Linux native probes; a failed scope launch resets the result only for the probe it launched under. */
private linuxProbeGeneration = 0
/** User-manager listener seen when the probe last failed; only a different listener triggers another probe. */
private linuxUnavailableListener: string | undefined
/** Test hook for platform process inspection; production resolves lazily on terminal spawn. */
terminalInspector: ProcessInspector | undefined
@@ -200,6 +207,7 @@ export class LocalSubprocessRuntime extends SubprocessRuntime {
? launchWindowsJob(spec, env)
: launchLinuxScope(spec, env, linuxScope)
handle = bindManagedProcess(spec, launch, binding)
if (linuxScope !== undefined) this.watchLinuxScopeStart(handle.done)
}
this.live.add(handle)
const control = handle.control
@@ -217,14 +225,32 @@ export class LocalSubprocessRuntime extends SubprocessRuntime {
return handle
}
/** Probe on the first eligible ordinary or terminal spawn; after a positive result, confirm the user manager before each launch. */
/**
* Probe on the first eligible ordinary or terminal spawn. After a positive result, confirm the user manager
* before each launch; after a negative one, probe again only when a new user-manager listener appears.
*/
private linuxScopeAvailable(): boolean {
if (this.linuxProbed && this.linuxLiteralArgv === undefined) {
const listener = linuxManagerListener()
if (listener === undefined || listener === this.linuxUnavailableListener) return false
this.linuxProbed = false
}
if (!this.linuxProbed) {
this.linuxProbed = true
this.linuxProbeGeneration += 1
this.linuxLiteralArgv = probeLinuxNative()
if (this.linuxLiteralArgv === undefined) this.linuxUnavailableListener = linuxManagerListener()
return this.linuxLiteralArgv !== undefined
}
return this.linuxLiteralArgv !== undefined && confirmLinuxManager()
return confirmLinuxManager()
}
/** Probe again before the next launch when a scope launched under the current probe never started its target. */
private watchLinuxScopeStart(done: Promise<unknown>): void {
const generation = this.linuxProbeGeneration
void done.catch((error: unknown) => {
if (error instanceof LinuxScopeNotStartedError && generation === this.linuxProbeGeneration) this.linuxProbed = false
})
}
private selectContainmentMode(
@@ -337,6 +363,7 @@ export class LocalSubprocessRuntime extends SubprocessRuntime {
spec.shellActivity === true,
)
this.terminals.add(handle)
if (scope !== undefined) this.watchLinuxScopeStart(handle.done)
const release = async (): Promise<void> => {
// terminate() can wait on this direct-exit promise.
directSettlement.resolve()
@@ -179,43 +179,51 @@ export function probeLinuxManager(internals: LinuxScopeInternals = {}): boolean
}
/**
* Report whether a process in this network namespace listens on a unix socket bound to path.
* The kernel lists a bound socket only while a process holds it open, so a socket file that
* a stopped or crashed listener left behind does not count.
* Find the socket a process in this network namespace listens on at path. The kernel lists a
* bound socket only while a process holds it open, so a socket file that a stopped or crashed
* listener left behind does not count.
*/
function unixSocketListening(path: string, table: string): boolean {
function unixSocketListener(path: string, table: string): string | undefined {
let text: string
try {
text = readFileSync(table, 'latin1')
} catch (_unreadableSocketTable) {
// Without the socket table nothing is known, so the caller queries systemctl.
return false
// Without the socket table nothing is known, so callers fall back to systemctl or keep their verdict.
return undefined
}
const suffix = ` ${path}`
return text.split('\n').some((line) => {
if (!line.endsWith(suffix)) return false
for (const line of text.split('\n')) {
if (!line.endsWith(suffix)) continue
const fields = line.trim().split(/\s+/u)
return fields.slice(7).join(' ') === path && (Number.parseInt(String(fields[3]), 16) & UNIX_SOCKET_ACCEPTING) !== 0
})
if (fields.slice(7).join(' ') === path && (Number.parseInt(String(fields[3]), 16) & UNIX_SOCKET_ACCEPTING) !== 0) {
return String(fields[6])
}
}
return undefined
}
/**
* Confirm the user manager before a scope launch. `systemd-run --user` connects through
* `$XDG_RUNTIME_DIR/systemd/private`; when the kernel socket table shows a process listening
* there, the confirmation needs no child process. Otherwise one systemctl query decides.
* A hung manager that still listens passes, and its scope launch fails.
* Identify the user manager's listener on `$XDG_RUNTIME_DIR/systemd/private`, the socket
* `systemd-run --user` connects through.
* @param internals - optional socket-table seam used by tests.
* @returns the listening socket's inode from the kernel socket table, or undefined when
* XDG_RUNTIME_DIR is unset or nothing in this network namespace listens there.
*/
export function linuxManagerListener(internals: LinuxScopeInternals = {}): string | undefined {
const runtimeDirectory = childEnv().XDG_RUNTIME_DIR
if (runtimeDirectory === undefined || runtimeDirectory === '') return undefined
return unixSocketListener(join(runtimeDirectory, 'systemd', 'private'), internals.unixSocketTable ?? '/proc/net/unix')
}
/**
* Confirm the user manager before a scope launch. A listener on its private socket confirms it
* without a child process; otherwise one systemctl query decides. A hung manager that still
* listens passes, and its scope launch fails with LinuxScopeNotStartedError.
* @param internals - optional socket-table and systemctl seams used by tests.
* @returns whether a scope launch can reach the user manager.
*/
export function confirmLinuxManager(internals: LinuxScopeInternals = {}): boolean {
const runtimeDirectory = childEnv().XDG_RUNTIME_DIR
if (runtimeDirectory !== undefined && runtimeDirectory !== '' && unixSocketListening(
join(runtimeDirectory, 'systemd', 'private'),
internals.unixSocketTable ?? '/proc/net/unix',
)) {
return true
}
return probeLinuxManager(internals)
return linuxManagerListener(internals) !== undefined || probeLinuxManager(internals)
}
interface DirectRange {
@@ -226,6 +234,13 @@ interface DirectRange {
settled: Promise<unknown>
}
/** A scope launch whose bootstrap never consumed its launch request, so its target never ran. */
export class LinuxScopeNotStartedError extends Error {
override readonly name = 'LinuxScopeNotStartedError'
/** Stable code for callers that classify failures without instanceof. */
readonly code = 'ERR_SUBPROCESS_SCOPE_NOT_STARTED'
}
class LinuxScopeStartup {
readonly terminationSignals = new Set<NodeJS.Signals>()
@@ -236,8 +251,8 @@ class LinuxScopeStartup {
if (startup !== undefined) throw deserializeRunnerError(startup.error)
if (existsSync(this.files.requestPath)
&& !(outcome.signal !== null && this.terminationSignals.has(outcome.signal))) {
throw new Error(
`${this.kind} scope exited before its bootstrap consumed the launch request; if the user-systemd manager is no longer reachable, restart the provider to probe native containment again`,
throw new LinuxScopeNotStartedError(
`${this.kind} scope exited before its bootstrap consumed the launch request; the provider probes native containment again before its next command`,
)
}
return outcome
@@ -8,7 +8,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
import {
confirmLinuxManager,
LinuxScopeNotStartedError,
launchLinuxScope,
linuxManagerListener,
prepareLinuxTerminalScope,
probeLinuxBootstrap,
probeLinuxManager,
@@ -260,7 +262,9 @@ describe('Linux native capability selection', () => {
writeFileSync(table, header + row('00000000', socket) + row('00010000', `listener ${socket}`))
expect(confirmLinuxManager({ spawnSync: failedQuery as never, unixSocketTable: table })).toBe(false)
expect(failedQuery).toHaveBeenCalledOnce()
expect(linuxManagerListener({ unixSocketTable: table })).toBeUndefined()
writeFileSync(table, header + row('00010000', socket))
expect(linuxManagerListener({ unixSocketTable: table })).toBe('2088859725')
expect(confirmLinuxManager({ spawnSync: failedQuery as never, unixSocketTable: table })).toBe(true)
expect(failedQuery).toHaveBeenCalledOnce()
expect(confirmLinuxManager({ spawnSync: failedQuery as never, unixSocketTable: join(runtime, 'missing') })).toBe(false)
@@ -269,6 +273,7 @@ describe('Linux native capability selection', () => {
for (const value of ['', undefined]) {
vi.stubEnv('XDG_RUNTIME_DIR', value)
const query = vi.fn(() => ({ status: 0, error: undefined }))
expect(linuxManagerListener({ unixSocketTable: table })).toBeUndefined()
expect(confirmLinuxManager({ spawnSync: query as never, unixSocketTable: table })).toBe(true)
expect(query).toHaveBeenCalledOnce()
}
@@ -343,7 +348,8 @@ describe('Linux scope establishment and quiescence', () => {
const { child, result } = launch(async () => missingUnit())
result.owner.signal('SIGTERM')
child.exit(outcome.exitCode, outcome.signal)
await expect(result.direct).rejects.toThrow(/before its bootstrap consumed.*restart the provider to probe native containment again/u)
await expect(result.direct).rejects.toBeInstanceOf(LinuxScopeNotStartedError)
await expect(result.direct).rejects.toThrow(/before its bootstrap consumed.*probes native containment again before its next command/u)
await expect(result.owner.waitForExit()).resolves.toBeUndefined()
result.owner.cleanup?.()
})
@@ -10,7 +10,7 @@ import type { IPtyForkOptions, IWindowsPtyForkOptions } from 'node-pty'
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import type { SubprocessSpawnSpec, SubprocessTerminalHandle, SubprocessTerminalSpawnSpec } from '@deepseek-ai/dsh-subprocess'
import { childEnv } from '../src/spawn.ts'
import { signalLinuxDirectProcess } from '../src/linux-scope.ts'
import { LinuxScopeNotStartedError, signalLinuxDirectProcess } from '../src/linux-scope.ts'
function mockWin32ForIsolatedRuntime(): void {
vi.doMock('@deepseek-ai/dsh-win32-process', () => ({
@@ -612,6 +612,8 @@ describe('LocalSubprocessRuntime', () => {
mockNodePtyForIsolatedRuntime(nodePtySpawn)
vi.doMock('../src/linux-scope.ts', () => ({
confirmLinuxManager: vi.fn(() => true),
LinuxScopeNotStartedError,
linuxManagerListener: vi.fn(() => undefined),
signalLinuxDirectProcess,
launchLinuxScope: vi.fn(),
prepareLinuxTerminalScope,
@@ -714,6 +716,8 @@ describe('LocalSubprocessRuntime', () => {
mockNodePtyForIsolatedRuntime(nodePtySpawn)
vi.doMock('../src/linux-scope.ts', () => ({
confirmLinuxManager: vi.fn(() => true),
LinuxScopeNotStartedError,
linuxManagerListener: vi.fn(() => undefined),
signalLinuxDirectProcess,
launchLinuxScope: vi.fn(),
prepareLinuxTerminalScope,
@@ -925,6 +929,8 @@ describe('LocalSubprocessRuntime', () => {
mockWin32ForIsolatedRuntime()
vi.doMock('../src/linux-scope.ts', () => ({
confirmLinuxManager,
LinuxScopeNotStartedError,
linuxManagerListener: vi.fn(() => undefined),
signalLinuxDirectProcess,
launchLinuxScope,
prepareLinuxTerminalScope: vi.fn(),
@@ -995,9 +1001,105 @@ describe('LocalSubprocessRuntime', () => {
}
})
it('keeps a failed Linux native probe for the provider lifetime and rechecks the Windows Job', async () => {
it('probes Linux again after a scope never starts its target or a new user-manager listener appears', async () => {
const probeLinuxNative = vi.fn<() => string[] | undefined>()
.mockReturnValueOnce([])
.mockReturnValueOnce(undefined)
.mockReturnValueOnce([])
const linuxManagerListener = vi.fn<() => string | undefined>()
.mockReturnValueOnce('101')
.mockReturnValueOnce(undefined)
.mockReturnValueOnce('101')
.mockReturnValueOnce('202')
const confirmLinuxManager = vi.fn(() => true)
const scopeOutcomes: Array<PromiseWithResolvers<{ exitCode: number; signal: null }>> = []
const fakeHandle = (done: Promise<{ exitCode: number; signal: null }>) => ({
collected: {},
done,
terminate: vi.fn(),
terminateForHostExit: vi.fn(),
waitForExit: vi.fn(async () => true),
})
const bindManagedProcess = vi.fn(() => {
const outcome = Promise.withResolvers<{ exitCode: number; signal: null }>()
scopeOutcomes.push(outcome)
return fakeHandle(outcome.promise)
})
const spawnSubprocess = vi.fn(() => fakeHandle(Promise.resolve({ exitCode: 0, signal: null })))
vi.resetModules()
mockWin32ForIsolatedRuntime()
vi.doMock('../src/linux-scope.ts', () => ({
confirmLinuxManager,
LinuxScopeNotStartedError,
linuxManagerListener,
signalLinuxDirectProcess,
launchLinuxScope: vi.fn(() => ({ kind: 'linux' })),
prepareLinuxTerminalScope: vi.fn(),
probeLinuxNative,
}))
vi.doMock('../src/spawn.ts', async importOriginal => ({
...await importOriginal<typeof import('../src/spawn.ts')>(),
bindManagedProcess,
spawnSubprocess,
}))
vi.doMock('../src/output.ts', async importOriginal => ({
...await importOriginal<typeof import('../src/output.ts')>(),
prepareManagedProcessBinding: vi.fn(() => ({ spillDir: '/tmp/dsh-test-spill' })),
}))
let fiber: { dispose(): Promise<void> } | undefined
try {
const { default: IsolatedLocalSubprocessRuntime } = await import('../src/index.ts')
const ctx = new Context()
vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
fiber = await ctx.plugin(IsolatedLocalSubprocessRuntime)
const runtime = ctx.subprocess as InstanceType<typeof IsolatedLocalSubprocessRuntime>
runtime.internals = { platform: 'linux' }
const settle = () => new Promise(resolve => setImmediate(resolve))
runtime.spawn(spec('true'))
runtime.spawn(spec('true'))
scopeOutcomes[0]?.reject(new Error('scope target failed after starting'))
await settle()
runtime.spawn(spec('true'))
expect(probeLinuxNative).toHaveBeenCalledOnce()
expect(confirmLinuxManager).toHaveBeenCalledTimes(2)
// A scope that never started its target makes the next spawn probe; the failed probe records listener 101.
scopeOutcomes[1]?.reject(new LinuxScopeNotStartedError('scope never started'))
await settle()
runtime.spawn(spec('true'))
expect(probeLinuxNative).toHaveBeenCalledTimes(2)
expect(spawnSubprocess).toHaveBeenCalledOnce()
// A launch from the superseded probe, no listener, and the same listener keep the fallback.
scopeOutcomes[2]?.reject(new LinuxScopeNotStartedError('superseded launch'))
await settle()
runtime.spawn(spec('true'))
runtime.spawn(spec('true'))
expect(probeLinuxNative).toHaveBeenCalledTimes(2)
expect(spawnSubprocess).toHaveBeenCalledTimes(3)
// A new listener means a new manager instance, which is probed once.
runtime.spawn(spec('true'))
expect(probeLinuxNative).toHaveBeenCalledTimes(3)
expect(bindManagedProcess).toHaveBeenCalledTimes(4)
expect(linuxManagerListener).toHaveBeenCalledTimes(4)
} finally {
for (const outcome of scopeOutcomes) outcome.resolve({ exitCode: 0, signal: null })
await fiber?.dispose()
vi.doUnmock('../src/linux-scope.ts')
vi.doUnmock('../src/spawn.ts')
vi.doUnmock('../src/output.ts')
unmockWin32ForIsolatedRuntime()
vi.resetModules()
}
})
it('keeps a failed Linux native probe while no new user-manager listener appears and rechecks the Windows Job', async () => {
const probeLinuxNative = vi.fn(() => undefined)
const confirmLinuxManager = vi.fn(() => true)
const linuxManagerListener = vi.fn(() => undefined)
const probeWindowsJob = vi.fn()
.mockReturnValueOnce(false)
.mockReturnValueOnce(true)
@@ -1007,6 +1109,8 @@ describe('LocalSubprocessRuntime', () => {
mockWin32ForIsolatedRuntime()
vi.doMock('../src/linux-scope.ts', () => ({
confirmLinuxManager,
LinuxScopeNotStartedError,
linuxManagerListener,
signalLinuxDirectProcess,
launchLinuxScope: vi.fn(),
prepareLinuxTerminalScope: vi.fn(),
@@ -1031,6 +1135,7 @@ describe('LocalSubprocessRuntime', () => {
expect(linuxSelect('ordinary')).toBe('fallback')
expect(probeLinuxNative).toHaveBeenCalledOnce()
expect(confirmLinuxManager).not.toHaveBeenCalled()
expect(linuxManagerListener).toHaveBeenCalledTimes(3)
const windowsContext = new Context()
vi.spyOn(windowsContext.logger, 'warn').mockImplementation(() => {})