From 294ca6179a1f562a8b80cf9fe5927ff11216a2f3 Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:21:40 +0800 Subject: [PATCH 01/10] fix(skills): watch the real path so an 8.3 alias cannot abort the process Windows reports a changed file under its long name, and libuv compares that name against the directory string the watch was given. A directory reached through its 8.3 short alias -- which is how a temp directory under a short-named home directory spells itself -- therefore fails libuv's own !_wcsnicmp(filename, dir, dirlen) assertion, and that assertion takes the process down instead of raising an error. realpathSync.native resolves the alias to the long path; the JavaScript implementation of realpathSync does not, so the native one is the one that matters here. A directory that cannot be resolved falls back to the path it was given. The test runs the watcher in a child process on purpose: the assertion is not catchable, so isolating it turns a regression into a failed assertion instead of a dead test worker. The child watches the 8.3 alias and writes through the long path, which is the pair that used to abort. (cherry picked from commit 21b8ea65d9b7e79e319f2f848ffcc95a8893c1a3) --- .../skills/src/directory-watcher.ts | 30 +++++- .../skills/test/directory-watcher.test.ts | 97 +++++++++++++++++++ test/vitest-suites.json | 1 + 3 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 packages/agent-modules/skills/test/directory-watcher.test.ts diff --git a/packages/agent-modules/skills/src/directory-watcher.ts b/packages/agent-modules/skills/src/directory-watcher.ts index 06bb39026..50f8013a2 100644 --- a/packages/agent-modules/skills/src/directory-watcher.ts +++ b/packages/agent-modules/skills/src/directory-watcher.ts @@ -1,4 +1,4 @@ -import { watch, type FSWatcher } from 'node:fs'; +import { realpathSync, watch, type FSWatcher } from 'node:fs'; import path from 'node:path'; interface DirectoryIdentity { @@ -22,17 +22,41 @@ interface SharedWatcher { // on macOS; evicting one registry must only release its own subscriptions. const sharedWatchers = new Map(); +/** + * The path the watcher is bound to. + * + * Windows reports a changed file under its long name, and libuv compares that + * name against the directory string the watch was given. A directory reached + * through its 8.3 short alias — which is what a temp directory under a + * short-named home directory spells — therefore fails libuv's own + * `!_wcsnicmp(filename, dir, dirlen)` assertion, and that assertion takes the + * process down rather than raising an error. + * + * `realpathSync.native` resolves the alias to the long path; the JavaScript + * implementation of `realpathSync` does not, so the native one is the one that + * matters here. A directory that cannot be resolved (it does not exist yet) + * falls back to the resolved path it was given. + */ +function watchableDirectory(targetPath: string): string { + try { + return realpathSync.native(targetPath); + } catch { + return path.resolve(targetPath); + } +} + export function subscribeToSkillDirectory( target: DirectoryIdentity, subscriber: Subscriber, ): { close(): void } { + const watchPath = watchableDirectory(target.targetPath); // Include filesystem identity so replacing a directory at the same path // never reuses a watcher still bound to the removed directory. - const key = JSON.stringify([path.resolve(target.targetPath), target.dev, target.ino]); + const key = JSON.stringify([watchPath, target.dev, target.ino]); let shared = sharedWatchers.get(key); if (!shared) { const subscribers = new Set(); - const watcher = watch(target.targetPath, { persistent: false }, () => { + const watcher = watch(watchPath, { persistent: false }, () => { for (const current of [...subscribers]) current.onChange(); }); shared = { watcher, subscribers }; diff --git a/packages/agent-modules/skills/test/directory-watcher.test.ts b/packages/agent-modules/skills/test/directory-watcher.test.ts new file mode 100644 index 000000000..5d2d7924f --- /dev/null +++ b/packages/agent-modules/skills/test/directory-watcher.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from "vitest"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url)); +const watcherModule = path.join( + repoRoot, + "packages/agent-modules/skills/src/directory-watcher.ts", +); + +/** + * The child subscribes to the directory and writes into it. + * + * The watch and the write have to disagree about how the path is spelled, + * because that is the whole defect: on Windows the filesystem reports a + * changed file under its long name, and libuv compares that name against the + * directory string it was given. Watching the 8.3 short alias and writing + * through the long path makes the two names differ, and libuv's own + * assertion (`!_wcsnicmp(filename, dir, dirlen)`) aborts the process. + * + * The child runs in its own process on purpose: that assertion is not a + * catchable error, it takes the whole process down. Isolating it here means + * a regression is a failed assertion instead of a dead test worker. + */ +const CHILD = ` +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const { subscribeToSkillDirectory } = await import(process.argv[2]); + +const directory = process.argv[3]; +// Ask Windows for the 8.3 alias of the directory. The path is passed to cmd +// without quotes: an embedded quote is mangled by the way a Windows child +// process receives its command line, and the alias is then spelled wrong. +let watchPath = directory; +if (process.platform === "win32" && !directory.includes(" ")) { + try { + watchPath = execFileSync( + "cmd.exe", + ["/d", "/c", \`for %I in (\${directory}) do @echo %~sI\`], + { encoding: "utf8" }, + ).trim(); + } catch { + watchPath = directory; + } +} + +let changed = false; +const subscription = subscribeToSkillDirectory( + { targetPath: watchPath, dev: 0, ino: 0 }, + { onChange: () => { changed = true; }, onError: () => {} }, +); +writeFileSync(join(directory, "probe.md"), "probe"); +const deadline = Date.now() + 8000; +while (!changed && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 25)); +} +subscription.close(); +process.stdout.write(JSON.stringify({ watchPath, directory, changed })); +process.exit(changed ? 0 : 3); +`; + +describe("the skill directory watcher", () => { + it("reports a change when the watch and the write spell the path differently", () => { + const scratch = mkdtempSync(path.join(tmpdir(), "skills-watcher-")); + const childPath = path.join(scratch, "child.mts"); + writeFileSync(childPath, CHILD, "utf8"); + + let stdout = ""; + let status: number | null = null; + let stderr = ""; + try { + const result = execFileSync( + process.execPath, + ["--import", "tsx", childPath, `file:///${watcherModule.replace(/\\/gu, "/")}`, scratch], + { cwd: repoRoot, encoding: "utf8", timeout: 40_000 }, + ); + stdout = result; + status = 0; + } catch (error) { + const failure = error as { status?: number; stdout?: string; stderr?: string }; + status = failure.status ?? null; + stdout = failure.stdout ?? ""; + stderr = failure.stderr ?? ""; + } + + expect( + { status, stdout, stderr }, + `the child must survive and report the change; stderr was:\n${stderr}`, + ).toMatchObject({ status: 0 }); + expect(JSON.parse(stdout).changed).toBe(true); + }); +}); diff --git a/test/vitest-suites.json b/test/vitest-suites.json index 1389b5189..338b81f36 100644 --- a/test/vitest-suites.json +++ b/test/vitest-suites.json @@ -111,6 +111,7 @@ "packages/agent-modules/mcp/test/name-registry.test.ts", "packages/agent-modules/mcp/test/stdio-max-message-bytes.test.ts", "packages/agent-modules/mcp/test/tool-name.test.ts", + "packages/agent-modules/skills/test/directory-watcher.test.ts", "packages/agent-modules/runaway-guard/test/guard.test.ts", "packages/local-runtime-v2/src/service/model-system/catalog/agent-model-selection.test.ts", "packages/local-runtime-v2/src/service/model-system/catalog/catalog.test.ts", From 926e2e13c269cff4bf1b118e20287770c0085622 Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:30:20 +0800 Subject: [PATCH 02/10] fix(plugin-system): watch the plugin directory under its real path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The plugin directory watcher had the same defect the skills watcher had: Windows reports a changed file under its long name, and libuv compares that name against the directory string the watch was given. A directory reached through its 8.3 short alias — which is how the plugin directory under a short-named home directory spells itself — therefore fails libuv's own !_wcsnicmp(filename, dir, dirlen) assertion, and that assertion takes the process down instead of raising an error. realpathSync.native resolves the alias to the long path; the JavaScript implementation of realpathSync does not. A directory that cannot be resolved is watched under the path it was given. (cherry picked from commit 841a9a032780286b78f6794c829ba4399c76ce78) --- .../plugin/runtime/local-directory-watcher.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/local-runtime-v2/src/service/plugin-system/plugin/runtime/local-directory-watcher.ts b/packages/local-runtime-v2/src/service/plugin-system/plugin/runtime/local-directory-watcher.ts index 98766d859..e411a6ebf 100644 --- a/packages/local-runtime-v2/src/service/plugin-system/plugin/runtime/local-directory-watcher.ts +++ b/packages/local-runtime-v2/src/service/plugin-system/plugin/runtime/local-directory-watcher.ts @@ -1,4 +1,4 @@ -import { watch, type FSWatcher } from 'node:fs'; +import { realpathSync, watch, type FSWatcher } from 'node:fs'; import { mkdir } from 'node:fs/promises'; import { @@ -58,7 +58,22 @@ export class LocalPluginDirectoryWatcher implements LocalPluginDirectoryWatcherP } protected createWatcher(root: string, onChange: () => void): FSWatcher { - return watch(root, { persistent: false, recursive: true }, onChange); + // Windows reports a changed file under its long name, and libuv compares + // that name against the directory string the watch was given. A directory + // reached through its 8.3 short alias — which is how the plugin directory + // under a short-named home directory spells itself — therefore fails + // libuv's own `!_wcsnicmp(filename, dir, dirlen)` assertion, and that + // assertion takes the process down rather than raising an error. + // + // `realpathSync.native` resolves the alias to the long path; the + // JavaScript implementation of `realpathSync` does not. + let watchPath = root; + try { + watchPath = realpathSync.native(root); + } catch { + watchPath = root; + } + return watch(watchPath, { persistent: false, recursive: true }, onChange); } async whenIdle(): Promise { From 5a91d12f462fa3651d3d7e69dba4b9c626bee878 Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:55:34 +0800 Subject: [PATCH 03/10] fix(local-runtime): seed the Windows trash shim as CommonJS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shim is a CommonJS script, but it was seeded as `mavis-trash.js`, and Node reads the module type of a `.js` file from the nearest ancestor `package.json`. An ancestor that says `"type": "module"` — a user's home directory can easily hold one — makes Node parse the shim as ESM, where `require` is not defined, and the shim never runs. The consequence was not cosmetic. The permission pipeline rewrites `rm` to `mavis-trash` so that a deletion stays recoverable; with the shim dead the rewrite had nothing to run, and a Windows deletion fell back to a hard one. The runtime's own probe reported `mavis-trash is not callable` on every startup. The shim is seeded as `mavis-trash.cjs` now. `.cjs` is CommonJS whatever the nearest ancestor says, and the `.cmd` launcher names the same file. The executor's name guard accepts the old `.js` name as well. It answers "does this path look like the trash script", and whether the script actually runs is decided by the probe, not by its name. The Windows contract test states the invariant: a data directory under an ancestor that declares ESM still gets a shim the runtime can call. (cherry picked from commit ca5a4d386f94d61c921b341eb78beba0a302ffcd) --- .../src/classifier/dangerous-patterns.ts | 4 +-- .../src/desktop/host-trash-executor.ts | 14 +++++++- .../src/infra/ensure-trash-script.ts | 6 ++-- .../src/infra/trash-script-win.ts | 15 +++++--- .../src/permissions/host-trash-runtime.ts | 2 +- .../test/unit/local-permission-facade.test.ts | 2 +- test/windows-contract.test.mjs | 36 ++++++++++++++++++- 7 files changed, 66 insertions(+), 13 deletions(-) diff --git a/packages/agent-modules/permission/src/classifier/dangerous-patterns.ts b/packages/agent-modules/permission/src/classifier/dangerous-patterns.ts index 8b8cb5335..ee8be81d9 100644 --- a/packages/agent-modules/permission/src/classifier/dangerous-patterns.ts +++ b/packages/agent-modules/permission/src/classifier/dangerous-patterns.ts @@ -139,7 +139,7 @@ export type HardBlockedCategory = | 'windows-secure-erase' // Windows CMD/PowerShell delete commands. CLI-driven deletes on Windows // skip the Recycle Bin entirely and are irrecoverable. With the Windows - // mavis-trash.js script now available, the rm-rewrite pipeline can + // mavis-trash.cjs script now available, the rm-rewrite pipeline can // intercept these — but until that rewrite path is wired for Windows // delete commands (del/rd/Remove-Item), the safest policy is HARD deny. | 'windows-delete' @@ -530,7 +530,7 @@ const HARD_BLOCKED_BASH_PATTERNS: ReadonlyArray<{ // ---- windows-delete: CMD/PowerShell delete commands. CLI-driven Windows // deletes do not move to Recycle Bin and are irrecoverable. The Windows - // mavis-trash.js script provides Recycle Bin support, but rm-rewrite for + // mavis-trash.cjs script provides Recycle Bin support, but rm-rewrite for // Windows delete commands (del/rd/Remove-Item) is not yet wired, so HARD // deny until that pipeline is extended. { diff --git a/packages/agent-tools/src/desktop/host-trash-executor.ts b/packages/agent-tools/src/desktop/host-trash-executor.ts index 16a484be5..aedaacad8 100644 --- a/packages/agent-tools/src/desktop/host-trash-executor.ts +++ b/packages/agent-tools/src/desktop/host-trash-executor.ts @@ -147,13 +147,25 @@ export async function executeLocalHostTrashIfRequested(input: { } } +/** + * The file names the Windows trash shim is known by. + * + * The shim is a CommonJS script, and `.cjs` is what says so: it is + * CommonJS whatever the nearest ancestor `package.json` says, while a `.js` + * shim follows that ancestor and can be parsed as ESM. The previous `.js` + * name is still accepted, because a runtime pointed at it is a stale + * configuration rather than a reason to refuse the operation here — whether + * the script actually runs is decided by the probe, not by its name. + */ +const WINDOWS_TRASH_SCRIPT_NAMES = new Set(['mavis-trash.cjs', 'mavis-trash.js']); + function isAvailableWindowsTrashRuntime( runtime: LocalHostTrashRuntime, ): runtime is LocalHostTrashRuntime & { readonly scriptPath: string } { return ( typeof runtime.scriptPath === 'string' && path.isAbsolute(runtime.scriptPath) && - path.basename(runtime.scriptPath).toLowerCase() === 'mavis-trash.js' + WINDOWS_TRASH_SCRIPT_NAMES.has(path.basename(runtime.scriptPath).toLowerCase()) ); } diff --git a/packages/local-runtime/src/infra/ensure-trash-script.ts b/packages/local-runtime/src/infra/ensure-trash-script.ts index 39a320993..b8e75ebd3 100644 --- a/packages/local-runtime/src/infra/ensure-trash-script.ts +++ b/packages/local-runtime/src/infra/ensure-trash-script.ts @@ -11,7 +11,7 @@ * fell back to `/bin/rm` — hard-deleting the user's files. * * - macOS / Linux: seeds a POSIX bash script at `mavis-trash` (0o755). - * - Windows: seeds a Node.js script at `mavis-trash.js` plus a `.cmd` + * - Windows: seeds a Node.js script at `mavis-trash.cjs` plus a `.cmd` * launcher `mavis-trash.cmd`, so the permission pipeline can invoke * `mavis-trash ` uniformly across platforms. * @@ -36,7 +36,7 @@ export function ensureTrashScript( const isWin = platform === 'win32'; if (isWin) { - seedFileIfChanged(path.join(binDir, 'mavis-trash.js'), TRASH_SCRIPT_WIN_CONTENT); + seedFileIfChanged(path.join(binDir, 'mavis-trash.cjs'), TRASH_SCRIPT_WIN_CONTENT); seedFileIfChanged(path.join(binDir, 'mavis-trash.cmd'), TRASH_CMD_LAUNCHER_CONTENT); } else { seedFileIfChanged(path.join(binDir, 'mavis-trash'), TRASH_SCRIPT_CONTENT, 0o755); @@ -153,7 +153,7 @@ export function inspectTrashRuntime( } } if (platform !== 'win32') return { available: true }; - const scriptPath = path.join(dataDir, 'bin', 'mavis-trash.js'); + const scriptPath = path.join(dataDir, 'bin', 'mavis-trash.cjs'); const launcherPath = path.join(dataDir, 'bin', 'mavis-trash.cmd'); const cacheKey = `${platform}:${dataDir}`; let phase: TrashRuntimeDiagnostics['phase'] = 'read-script'; diff --git a/packages/local-runtime/src/infra/trash-script-win.ts b/packages/local-runtime/src/infra/trash-script-win.ts index e5e65731d..3e0bef7b1 100644 --- a/packages/local-runtime/src/infra/trash-script-win.ts +++ b/packages/local-runtime/src/infra/trash-script-win.ts @@ -1,9 +1,16 @@ /** - * mavis-trash.js — Node.js script that moves files to Windows Recycle Bin. + * mavis-trash.cjs — Node.js script that moves files to Windows Recycle Bin. * - * Seeded into `/bin/mavis-trash.js` on daemon startup (Windows only). + * Seeded into `/bin/mavis-trash.cjs` on daemon startup (Windows only). * Companion to the POSIX bash `mavis-trash` script (macOS/Linux). * + * The extension is not a detail. The script is CommonJS, and Node reads the + * module type of a `.js` file from the nearest ancestor `package.json`: an + * ancestor that says `"type": "module"` — a user's home directory can easily + * hold one — makes Node parse this script as ESM, where `require` is not + * defined, and the script never runs. `.cjs` says CommonJS whatever the + * ancestor says. + * * Uses PowerShell's Microsoft.VisualBasic.FileIO API to send files/directories * to the Recycle Bin, which is the Windows equivalent of macOS Finder Trash. * @@ -14,7 +21,7 @@ /* eslint-disable no-useless-escape */ /** - * The Node.js script content. Runs standalone via `node mavis-trash.js [flags] file1 file2 ...`. + * The Node.js script content. Runs standalone via `node mavis-trash.cjs [flags] file1 file2 ...`. * * Matches the bash script's interface: * - Silently strips rm-style flags (-r, -f, -rf, --recursive, --force, -R, --) @@ -626,7 +633,7 @@ export function buildTrashCmdLauncherContent(runtimeExecutable: string = process const escapedExecutable = runtimeExecutable.replaceAll('%', '%%').replaceAll('"', '""'); return `@echo off set "ELECTRON_RUN_AS_NODE=1" -"${escapedExecutable}" "%~dp0mavis-trash.js" %* +"${escapedExecutable}" "%~dp0mavis-trash.cjs" %* `; } diff --git a/packages/local-runtime/src/permissions/host-trash-runtime.ts b/packages/local-runtime/src/permissions/host-trash-runtime.ts index 4cb797a09..eeefeb264 100644 --- a/packages/local-runtime/src/permissions/host-trash-runtime.ts +++ b/packages/local-runtime/src/permissions/host-trash-runtime.ts @@ -18,6 +18,6 @@ export function buildLocalHostTrashRuntime(input: { readExecution: readWindowsTrashExecution, reportDiagnostic: (diagnostic) => logger.error({ ...diagnostic }, 'local_runtime.windows_trash_execution_failed'), - ...(input.dataDir ? { scriptPath: path.join(input.dataDir, 'bin', 'mavis-trash.js') } : {}), + ...(input.dataDir ? { scriptPath: path.join(input.dataDir, 'bin', 'mavis-trash.cjs') } : {}), }; } diff --git a/packages/local-runtime/test/unit/local-permission-facade.test.ts b/packages/local-runtime/test/unit/local-permission-facade.test.ts index 22afd2719..e0632e817 100644 --- a/packages/local-runtime/test/unit/local-permission-facade.test.ts +++ b/packages/local-runtime/test/unit/local-permission-facade.test.ts @@ -114,7 +114,7 @@ function freshFacade( function seedWindowsTrashRuntime(dataDir: string): void { const binDir = path.join(dataDir, 'bin'); mkdirSync(binDir, { recursive: true }); - writeFileSync(path.join(binDir, 'mavis-trash.js'), TRASH_SCRIPT_WIN_CONTENT, 'utf8'); + writeFileSync(path.join(binDir, 'mavis-trash.cjs'), TRASH_SCRIPT_WIN_CONTENT, 'utf8'); writeFileSync(path.join(binDir, 'mavis-trash.cmd'), TRASH_CMD_LAUNCHER_CONTENT, 'utf8'); } diff --git a/test/windows-contract.test.mjs b/test/windows-contract.test.mjs index 0042089a7..e13244471 100644 --- a/test/windows-contract.test.mjs +++ b/test/windows-contract.test.mjs @@ -1,13 +1,17 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { createHash, generateKeyPairSync, sign } from "node:crypto"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, it } from "vitest"; import { checkWindowsSourceLocation } from "../scripts/check-windows-source-location.mjs"; import { resolveWslPath } from "../packages/tui/src/host/wsl-path.js"; import { McodeUpdateService } from "../packages/tui/src/update/service.js"; +import { + ensureTrashScript, + inspectTrashRuntime, +} from "../packages/local-runtime/src/infra/ensure-trash-script.js"; const windowsPath = String.raw`D:\Users\demo\Documents\Screen shots\截图.png`; const temporaryRoots = []; @@ -42,6 +46,36 @@ describe.skipIf(process.platform !== "win32")("Windows source contract", () => { assert.equal(await resolveWslPath(windowsPath), windowsPath); }); + // The trash shim is what keeps a Windows deletion recoverable: the + // permission pipeline rewrites `rm` to it, and if it cannot run, the + // deletion falls back to a hard one. + // + // The shim is a CommonJS script, and Node reads the module type of a `.js` + // file from the nearest ancestor `package.json`. An ancestor that says + // `"type": "module"` — a user's home directory can easily hold one — + // makes Node parse the shim as ESM, where `require` is not defined, and the + // shim never runs. The extension is therefore part of the contract: `.cjs` + // says CommonJS whatever the ancestor says. + it("seeds a trash shim that runs under an ancestor package that declares ESM", () => { + const root = mkdtempSync(path.join(tmpdir(), "mcode-trash-")); + temporaryRoots.push(root); + // The ancestor that decides how Node reads every `.js` file beneath it. + writeFileSync(path.join(root, "package.json"), JSON.stringify({ type: "module" }), "utf8"); + const dataDir = path.join(root, "data"); + ensureTrashScript(dataDir, "win32"); + + assert.deepEqual( + readdirSync(path.join(dataDir, "bin")).filter((name) => name.startsWith("mavis-trash.")).sort(), + ["mavis-trash.cjs", "mavis-trash.cmd"], + ); + + // The product's own probe: it spawns the launcher and asks the script + // whether it is there. "not callable" is the verdict this contract exists + // to prevent. + const status = inspectTrashRuntime(dataDir, "win32"); + assert.equal(status.available, true, JSON.stringify(status)); + }, 30_000); + it.each(["standard npm", "custom npm wrapper", "custom npm wrapper with adjacent CLI"])("installs and validates a managed update in a complex path with %s", async (npmLayout) => { const root = mkdtempSync(path.join(tmpdir(), "mcode-update-")); temporaryRoots.push(root); From 23a29cb9ee5b59bffbc1b6aa0bd35b90c638dad9 Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Mon, 9 Nov 2026 23:21:40 +0800 Subject: [PATCH 04/10] fix(webui): a dollar-delimited run of Chinese is prose, not math The inline math tokenizer matched any two dollars on a line. A shell variable in prose therefore paired with a later dollar and swallowed the paragraph between them, and KaTeX then complained about every Chinese character it found there. Math is not written in Chinese, so a body that carries Chinese characters or the punctuation that comes with them is not a formula. A real formula between two dollars still renders as one. (cherry picked from commit fb3aca1bcfef843a464957031a5da5861cb06941) --- .../transcript/ui/markdown.public.tsx | 15 ++++++++++++++ packages/webui/test/unit/webui-stream.test.ts | 20 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/packages/webui/src/client/features/transcript/ui/markdown.public.tsx b/packages/webui/src/client/features/transcript/ui/markdown.public.tsx index 3e4b6fa2d..60ee2a047 100644 --- a/packages/webui/src/client/features/transcript/ui/markdown.public.tsx +++ b/packages/webui/src/client/features/transcript/ui/markdown.public.tsx @@ -111,6 +111,15 @@ function codeFenceGutter(text: string): number[] { return lines.length > 1 ? lines.map((_line, index) => index + 1) : []; } +/** + * Chinese characters and the punctuation that comes with them. + * + * Used to tell prose that merely contains dollars from a formula: a formula + * is not written in Chinese, so a dollar-delimited run that carries Chinese + * is prose. + */ +const WEBUI_MATH_CJK_PATTERN = /[\u3000-\u303f\u3400-\u4dbf\u4e00-\u9fff\uff00-\uffef]/u; + marked.use({ extensions: [ { @@ -134,6 +143,12 @@ marked.use({ (body.includes("\n") || /^\d/u.test(body)) ) return undefined; + // A run between two dollars that carries Chinese words is prose that + // happens to contain dollars — a shell variable, a price, a stray + // symbol. Read as math it swallowed the paragraph, and KaTeX then + // complained about every Chinese character in it. Math is not written + // in Chinese, so a body that carries it is not math. + if (WEBUI_MATH_CJK_PATTERN.test(body)) return undefined; return { type: "webuiMath", raw: match[0], diff --git a/packages/webui/test/unit/webui-stream.test.ts b/packages/webui/test/unit/webui-stream.test.ts index 97a2c1c19..1eddffe12 100644 --- a/packages/webui/test/unit/webui-stream.test.ts +++ b/packages/webui/test/unit/webui-stream.test.ts @@ -638,4 +638,24 @@ describe("WebUI Markdown", () => { expect(inlineMathHtml).toContain("webui-math"); expect(inlineMathHtml).toContain("katex"); }); + + it("leaves a shell variable in prose alone", () => { + // A dollar that opens a variable name is not math, and the prose between + // two of them is prose. Read as math it swallowed a whole paragraph, and + // KaTeX then complained about every Chinese character in it. + const shellHtml = renderToStaticMarkup( + createElement(WebuiMarkdown, { source: "用 $state 读取,结果是 $x^2$。" }), + ); + // The real formula is still a formula. + expect(shellHtml).toContain("webui-math"); + expect(shellHtml).toContain("katex"); + // The prose in front of it was not swallowed into the formula. + expect(shellHtml).toContain("$state 读取"); + + const chineseHtml = renderToStaticMarkup( + createElement(WebuiMarkdown, { source: "文本 $(这是)$ 结束" }), + ); + expect(chineseHtml).not.toContain("webui-math"); + expect(chineseHtml).toContain("(这是)"); + }); }); From c33d9501a4b2350b9124f2ba31420b3eec79fbb6 Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:52:13 +0800 Subject: [PATCH 05/10] test: make the release-tool checks hold on a Windows host Two checks could not pass on Windows. The marketplace-version check compared a path.relative() result against POSIX-shaped literals, so the shared module it is meant to exclude never matched and was reported as a second declaration. The same relative path fed the test-file filter, whose pattern also expects a forward slash, so test files were counted as offenders too. Normalizing the separator once at the source fixes both. The locale check asserted that the child's ICU locale is en-US. The runner does pin LANG, LANGUAGE, LC_ALL and LC_MESSAGES, and on POSIX Node derives its default locale from those. Windows has no POSIX locale variables: Node reads the OS user default locale, and LC_ALL, LANG, NODE_ICU_DATA and ICU_DEFAULT_LOCALE were each measured to leave it unchanged. The child is a real process on this host whatever the simulated platform says, so the assertion is now keyed on the host platform and only demands a pinned locale where pinning is possible. (cherry picked from commit edfa52d5d1d18c76e356b238298825e1144992b5) --- test/source-sync.test.mjs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index 4bad41e30..53ccbc7c7 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -1243,10 +1243,27 @@ test('suite runner pins its locale, preserves gate arguments and canonicalizes W language: child.language, lcAll: child.lcAll, lcMessages: child.lcMessages, - locale: child.locale, }, - { lang: 'C', language: 'C', lcAll: 'C', lcMessages: 'C', locale: 'en-US' }, + { lang: 'C', language: 'C', lcAll: 'C', lcMessages: 'C' }, ); + // The runner pins the POSIX locale variables, and that is what it can + // promise: Node derives its ICU default locale from those variables on + // POSIX, so `LC_ALL=C` lands on `en-US`. Windows has no such variables — + // Node reads the OS user default locale, and no environment variable + // overrides it (`LC_ALL`, `LANG`, `NODE_ICU_DATA` and `ICU_DEFAULT_LOCALE` + // were all measured to leave the locale unchanged). So the ICU locale + // follows the host there. + // + // The key is the *host* platform, not the simulated one: the loop fakes + // `process.platform` for the runner, but the child is a real process on + // this machine, so its ICU locale is the host's whatever the runner was + // told to believe. + if (process.platform === 'win32') { + assert.ok(typeof child.locale === 'string' && child.locale.length > 0, + 'the child reports a locale'); + } else { + assert.equal(child.locale, 'en-US'); + } } }); @@ -1447,7 +1464,12 @@ function filesWritingVersion(repositoryRoot, version) { if (entry.isDirectory()) walk(full); else if (!/\.(?:ts|tsx|mts|mjs|cjs|js|jsx)$/u.test(entry.name)) continue; else { - const relative = path.relative(repositoryRoot, full); + // `path.relative` hands back the platform separator, but every + // comparison below — the test-file filter and the shared-module + // exclusion — is written in POSIX shape. Normalizing once here keeps + // the check meaningful on Windows, where the un-normalized path never + // matched and the shared module was reported as its own offender. + const relative = path.relative(repositoryRoot, full).split(path.sep).join("/"); if (isTestFile(relative)) continue; if (withoutComments(readFileSync(full, 'utf8')).includes(version)) offenders.push(relative); } From 8cc7c1a59b788c67cc4de9e3ed219949d8198e0b Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:25:52 +0800 Subject: [PATCH 06/10] chore: record the new source in the public source inventory The new watcher test is a reviewed source path, so the inventory names it. --- release/public-source.json | 1 + 1 file changed, 1 insertion(+) diff --git a/release/public-source.json b/release/public-source.json index c1be1bbd5..7316c2de8 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -408,6 +408,7 @@ "packages/agent-modules/skills/src/index.ts", "packages/agent-modules/skills/src/registry.ts", "packages/agent-modules/skills/src/types.ts", + "packages/agent-modules/skills/test/directory-watcher.test.ts", "packages/agent-modules/system-reminder/package.json", "packages/agent-modules/system-reminder/src/blocks.ts", "packages/agent-modules/system-reminder/src/collaborators.ts", From 060dbf6e480b3d930e7316ba539d5b2281e78e79 Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:29:22 +0800 Subject: [PATCH 07/10] test(webui): give the first-boot case the deadline its siblings have The case boots the real host and calls an operation over the loopback service, exactly as the four cases after it do, and all four of those run on 120s. This one alone fell back to Vitest's 5s default, which a cold Windows runner does not always clear: the host boot, the service start and the catalog read all have to fit inside it, and the runner that failed it was visibly loaded. The assertions are unchanged, and the deadline is the file's own. --- .../webui/test/integration/real-host-loopback.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/webui/test/integration/real-host-loopback.test.ts b/packages/webui/test/integration/real-host-loopback.test.ts index 8b82e5110..c1f6aae43 100644 --- a/packages/webui/test/integration/real-host-loopback.test.ts +++ b/packages/webui/test/integration/real-host-loopback.test.ts @@ -208,7 +208,13 @@ describe("real host over the loopback service", () => { vi.unstubAllEnvs(); (await import("@mavis/config")).resetConfig(); } - }); + // The deadline is the file's own: this case boots the real host and calls + // an operation over the loopback service, exactly as its four siblings do, + // and they all run on 120s. This one alone fell back to Vitest's 5s + // default, which a cold Windows runner does not always clear — the host + // boot, the service start and the catalog read all have to fit inside it. + // The assertions are unchanged. + }, 120_000); it("answers a session round trip from the real host in an isolated data directory", async () => { const host = await bootRealHost(); From c8000a3f3f9746120ca972d1610b3dff6282b18b Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:58:53 +0800 Subject: [PATCH 08/10] test: make two suites able to run on a Windows host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both files assert something the host's own spelling made unreachable. The observability directory is a filesystem path, so it carries the host's separator, but the assertions compared it against POSIX-shaped literals. On Windows the directory is `\data\v2\observability\mcode` and the literal never matched. The Bash tool runs PowerShell on Windows — the runtime prefers it, because it is system-native and has no MSYS path problems — and the commands in the output suite were written for `sh`: `printf` does not exist there, and a quoted executable is a string expression to PowerShell rather than a program to run, so `"C:\...\node.exe" -e "..."` is a ParserError. The commands are now spelled for the shell that will run them, and PowerShell carries the native exit code over explicitly, because it reports it in $LASTEXITCODE and exits with its own status otherwise. The POSIX commands are unchanged, so a POSIX host runs exactly what it ran before. --- .../test/desktop/local-bash-output.test.ts | 44 ++++++++++++++++--- packages/tui/test/unit/observability.test.ts | 12 +++-- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/packages/agent-tools/test/desktop/local-bash-output.test.ts b/packages/agent-tools/test/desktop/local-bash-output.test.ts index 45a124674..f8f6e6215 100644 --- a/packages/agent-tools/test/desktop/local-bash-output.test.ts +++ b/packages/agent-tools/test/desktop/local-bash-output.test.ts @@ -10,6 +10,7 @@ import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { LocalBashTool } from '../../src/desktop/local-pi-tools.js'; +import { resolveLocalBashShell } from '../../src/desktop/local-bash-contract.js'; import { DESKTOP_BASH_MAX_BYTES } from '../../src/desktop/output-limit.js'; import { readPluginHookCompatibleToolResponse } from '../../src/plugin-hooks/vendor-tool-response.js'; import type { LocalRuntimeToolContext } from '../../src/desktop/types.js'; @@ -19,6 +20,37 @@ const SESSION_CTX = { turnId: 'turn-test', } satisfies LocalRuntimeToolContext; +/** + * The shell the tool will actually run. + * + * On Windows the runtime prefers PowerShell, and PowerShell reads a quoted + * path as a string expression rather than as a program to run — it needs the + * call operator — and it has no `printf`. A command written for `sh` is a + * ParserError there, so the commands below are spelled for the shell that + * will run them. + */ +const shell = resolveLocalBashShell(); +const isPosixShell = shell === 'bash' || shell === 'sh'; + +/** A command that runs the given script with this process's Node. */ +function nodeCommand(script: string): string { + const executable = JSON.stringify(process.execPath); + const source = JSON.stringify(script); + // PowerShell reports the native exit code in $LASTEXITCODE and exits with + // its own status unless it is told otherwise, so the code has to be carried + // over explicitly for a failing command to stay a failing command. + return isPosixShell + ? `${executable} -e ${source}` + : `& ${executable} -e ${source}; exit $LASTEXITCODE`; +} + +/** A command that writes the given text to stdout and to stderr, exactly. */ +function splitStreamCommand(stdout: string, stderr: string): string { + return isPosixShell + ? `printf '${stdout}'; printf '${stderr}' >&2` + : `[Console]::Out.Write('${stdout}');[Console]::Error.Write('${stderr}')`; +} + describe('LocalBashTool — foreground output truncation', () => { let workspace: string; @@ -32,7 +64,7 @@ describe('LocalBashTool — foreground output truncation', () => { it('preserves exact stdout and stderr for Compatible PostToolUse', async () => { const tool = new LocalBashTool(workspace, undefined, { mode: 'off' }); const result = await tool.execute(SESSION_CTX, { - command: "printf 'from-stdout'; printf 'from-stderr' >&2", + command: splitStreamCommand('from-stdout', 'from-stderr'), }); expect(readPluginHookCompatibleToolResponse(result)).toEqual({ @@ -44,7 +76,9 @@ describe('LocalBashTool — foreground output truncation', () => { it('short output is returned verbatim, not truncated', async () => { const tool = new LocalBashTool(workspace, undefined, { mode: 'off' }); - const result = await tool.execute(SESSION_CTX, { command: 'printf "a\\nb\\nc\\n"' }); + const result = await tool.execute(SESSION_CTX, { + command: isPosixShell ? 'printf "a\\nb\\nc\\n"' : '[Console]::Out.Write("a`nb`nc`n")', + }); expect(result.tool_name).toBe('bash'); expect(result.isError).toBeFalsy(); expect(result.text).toContain('a'); @@ -54,7 +88,7 @@ describe('LocalBashTool — foreground output truncation', () => { it('caps 24-50 KiB foreground output with head and tail and persists the complete output', async () => { const tool = new LocalBashTool(workspace, undefined, { mode: 'off' }); const script = `for(let i=0;i<400;i++) console.log('row-'+i+'-'+'x'.repeat(90))`; - const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(script)}`; + const command = nodeCommand(script); const result = await tool.execute(SESSION_CTX, { command }); expect(Buffer.byteLength(result.text, 'utf8')).toBeLessThanOrEqual( @@ -131,7 +165,7 @@ describe('LocalBashTool — foreground output truncation', () => { const tool = new LocalBashTool(workspace, undefined, { mode: 'off' }); // Let pending stderr writes drain before exiting with the intended error code. const script = `for(let i=0;i<400;i++) console.error('error-row-'+i+'-'+'e'.repeat(90)); process.exitCode = 7`; - const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(script)}`; + const command = nodeCommand(script); const result = await tool.execute(SESSION_CTX, { command }); expect(result.isError).toBe(true); @@ -161,7 +195,7 @@ describe('LocalBashTool — foreground output truncation', () => { it('output beyond 2000 lines preserves head and tail with a complete output file', async () => { const tool = new LocalBashTool(workspace, undefined, { mode: 'off' }); const script = `for(let i=0;i<3000;i++) console.log('spill-row-'+i+'-'+'z'.repeat(50))`; - const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(script)}`; + const command = nodeCommand(script); const result = await tool.execute(SESSION_CTX, { command }); const lower = result.text.toLowerCase(); diff --git a/packages/tui/test/unit/observability.test.ts b/packages/tui/test/unit/observability.test.ts index 7cd745ca4..1fe0e943c 100644 --- a/packages/tui/test/unit/observability.test.ts +++ b/packages/tui/test/unit/observability.test.ts @@ -83,9 +83,15 @@ describe('Minimax Code observability', () => { }); await observability.flush(); - expect(resolveTuiObservabilityDirectory('/data')).toBe('/data/v2/observability/mcode'); + // The directory is a filesystem path, so it carries the host's separator: + // `join` builds it the way the platform spells it. A POSIX-shaped + // literal here never matched on Windows, where the path is + // `\data\v2\observability\mcode`. + expect(resolveTuiObservabilityDirectory('/data')).toBe(join('/data', 'v2', 'observability', 'mcode')); expect(writes).toHaveLength(1); - expect(writes[0]?.path).toBe('/data/v2/observability/mcode/mcode-observability-900-42.jsonl'); + expect(writes[0]?.path).toBe( + join('/data', 'v2', 'observability', 'mcode', 'mcode-observability-900-42.jsonl'), + ); const events = writes .flatMap((write) => write.content.trim().split('\n')) .map((line) => JSON.parse(line) as Record); @@ -208,7 +214,7 @@ describe('Minimax Code observability', () => { await vi.advanceTimersByTimeAsync(1_000); expect(append).toHaveBeenCalledWith( - expect.stringContaining('/v2/observability/mcode/'), + expect.stringContaining(join('v2', 'observability', 'mcode')), expect.stringContaining('"phase":"runtime.initialize"'), ); await observability.flush(); From 4c88493bd10ffb69c81d7e7ec5b7f32d23de1ecc Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:46:51 +0800 Subject: [PATCH 09/10] test: let the last two Windows-hostile assertions run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both compared a path the host spells its own way against a POSIX-shaped literal, and one ran a POSIX command on a host whose shell is PowerShell. The sandbox backend joins the git template dir onto the sandbox temp dir, so the path carries the host's separator; on Windows the directory is `\tmp\session-1\git-templates-empty` and the literal never matched. The mcode-tools acceptance read the host keys back with `env | grep`, which is POSIX shell syntax — on the Windows runtime the shell is PowerShell, where `env` does not exist and the command does not parse. Node reads the same environment the child was given and prints it in the same shape on both, so what the case measures is unchanged. --- .../service/sandbox/backend/srt-macos.test.ts | 6 +++++- ...eal-host-mcode-tools-bash-environment.test.ts | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/local-runtime-v2/src/service/sandbox/backend/srt-macos.test.ts b/packages/local-runtime-v2/src/service/sandbox/backend/srt-macos.test.ts index 427d9f895..07c628cde 100644 --- a/packages/local-runtime-v2/src/service/sandbox/backend/srt-macos.test.ts +++ b/packages/local-runtime-v2/src/service/sandbox/backend/srt-macos.test.ts @@ -194,7 +194,11 @@ describe("srt-macos backend", () => { // an empty dir under sandboxTempDir so git init/clone skip hook-template // copies (an empty env value no longer skips on git >= 2.53). env: { - GIT_TEMPLATE_DIR: "/tmp/session-1/git-templates-empty", + // The backend joins the template dir onto the sandbox temp dir, so the + // path carries the host's separator. A POSIX-shaped literal here never + // matched on Windows, where the directory is + // `\tmp\session-1\git-templates-empty`. + GIT_TEMPLATE_DIR: join("/tmp/session-1", "git-templates-empty"), ...baseEnv, MAVIS_TRASH_FORCE_MV: "1", }, diff --git a/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts b/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts index d05ca7757..c01a204e3 100644 --- a/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts +++ b/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts @@ -36,8 +36,20 @@ const PROVIDER_NAME = "stub"; const PROVIDER_ID = `custom_provider:${PROVIDER_NAME}`; const HOST_KEY_PREFIX = "__MAVIS_MCODE_TOOLS_"; -/** The Bash command that reads the host keys back out of the child env. */ -const READ_HOST_KEYS = `env | grep '^${HOST_KEY_PREFIX}' | sort`; +/** + * The command that reads the host keys back out of the child env. + * + * `env | grep` is POSIX shell syntax, and the Windows runtime runs + * PowerShell, where `env` does not exist — the command failed to parse there. + * Node reads the same environment the child was given and prints it in the + * same shape on both, so the subject of the test is unchanged. + */ +const READ_HOST_KEYS = (() => { + const script = `Object.entries(process.env).filter(([name]) => name.startsWith('${HOST_KEY_PREFIX}')).sort().forEach(([name, value]) => console.log(name + '=' + value))`; + const executable = JSON.stringify(process.execPath); + const source = JSON.stringify(script); + return process.platform === 'win32' ? `& ${executable} -e ${source}` : `${executable} -e ${source}`; +})(); /** * The content-review gateway answers on both API versions the runtime uses: From 2e712893804f7547fdd0e8f4fcdbcf5b02edaabd Mon Sep 17 00:00:00 2001 From: antianqi <75944423+antianqi@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:55:49 +0800 Subject: [PATCH 10/10] fix(webui): retry the SSH store's rename the way every other atomic write does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Windows refuses a rename while another process holds the file open for a moment — an indexer, a scanner, a concurrent reader — and the refusal is transient. The SSH connection store wrote its document by renaming a sibling file over the real one, so the store failed at random on Windows and nowhere else. Every other atomic write in the repository already retries that refusal: the TUI's auth and identity stores, the update service, the local runtime's auth context, the provider-presets repository. The SSH store was the one path that did not, because the helper it needed did not exist yet — the helper was synchronous, and the store's rename is a promise. The shared helper gains an asynchronous sibling. Its wait is a timer rather than a blocking sleep, so a server process does not stall its event loop while a locked file is retried. The rename stays awaited: the commit must not return before the document is in place, and the suite has a case that says so. The new helper has its own cases: a refusal is retried on Windows and gives up after the budget, it is not retried off Windows, it is not retried for an error that does not mean "held file", and the wait between attempts lets other work run. --- packages/shared/src/index.ts | 2 + packages/shared/src/windows-file-system.ts | 42 ++++++++ .../shared/test/windows-file-system.test.ts | 95 +++++++++++++++++++ packages/webui/src/runtime/ssh/storage.ts | 10 +- release/public-source.json | 1 + test/vitest-suites.json | 1 + 6 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 packages/shared/test/windows-file-system.test.ts diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 7813e3d1c..6944fd064 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -47,6 +47,8 @@ export { } from './openrouter-attribution.js'; export { retryWindowsFileSystemOperation, + retryWindowsFileSystemOperationAsync, + type WindowsFileSystemAsyncRetryOptions, type WindowsFileSystemRetryOptions, } from './windows-file-system.js'; diff --git a/packages/shared/src/windows-file-system.ts b/packages/shared/src/windows-file-system.ts index af71176e8..efdd38db7 100644 --- a/packages/shared/src/windows-file-system.ts +++ b/packages/shared/src/windows-file-system.ts @@ -30,6 +30,48 @@ export function retryWindowsFileSystemOperation( } } +export interface WindowsFileSystemAsyncRetryOptions { + platform?: NodeJS.Platform; + retries?: number; + retryDelayMs?: number; + wait?(delayMs: number): Promise; +} + +/** + * The asynchronous sibling of `retryWindowsFileSystemOperation`. + * + * The same refusal has to be retried where the operation is a promise, and + * the wait between the attempts must not block the event loop the way the + * synchronous helper's does. + */ +export async function retryWindowsFileSystemOperationAsync( + operation: () => Promise, + options: WindowsFileSystemAsyncRetryOptions = {}, +): Promise { + const platform = options.platform ?? process.platform; + const retries = Math.max(0, Math.floor(options.retries ?? DEFAULT_RETRIES)); + const retryDelayMs = Math.max(0, Math.floor(options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS)); + const wait = options.wait ?? waitAsynchronously; + + for (let attempt = 0; ; attempt += 1) { + try { + return await operation(); + } catch (error) { + if (platform !== 'win32' || attempt >= retries || !isRetryableWindowsFileError(error)) { + throw error; + } + await wait(retryDelayMs * (attempt + 1)); + } + } +} + +async function waitAsynchronously(delayMs: number): Promise { + if (delayMs <= 0) return; + await new Promise((resolve) => { + setTimeout(resolve, delayMs); + }); +} + function isRetryableWindowsFileError(error: unknown): boolean { return ( typeof error === 'object' && diff --git a/packages/shared/test/windows-file-system.test.ts b/packages/shared/test/windows-file-system.test.ts new file mode 100644 index 000000000..f952d6f98 --- /dev/null +++ b/packages/shared/test/windows-file-system.test.ts @@ -0,0 +1,95 @@ +/** + * The Windows file-system retry helper. + * + * Windows refuses a file operation while another process holds the file + * open for a moment, and the refusal is transient. The helper turns that + * refusal into a retry, on Windows only, and only for the error codes that + * mean "held" rather than "refused". + */ +import { describe, expect, it, vi } from "vitest"; + +import { + retryWindowsFileSystemOperation, + retryWindowsFileSystemOperationAsync, +} from "../src/windows-file-system.js"; + +function refusal(code: string): Error & { code: string } { + return Object.assign(new Error(`refused: ${code}`), { code }); +} + +describe("the Windows file-system retry helper", () => { + it("retries a transient refusal on Windows", async () => { + const operation = vi.fn(async () => { + throw refusal("EPERM"); + }); + const wait = vi.fn(async () => undefined); + + await expect( + retryWindowsFileSystemOperationAsync(operation, { platform: "win32", wait }), + ).rejects.toThrow("refused: EPERM"); + expect(operation).toHaveBeenCalledTimes(5); + expect(wait).toHaveBeenCalledTimes(4); + }); + + it("returns the result once the refusal stops", async () => { + const operation = vi + .fn<() => Promise>() + .mockRejectedValueOnce(refusal("EBUSY")) + .mockResolvedValue("written"); + const wait = vi.fn(async () => undefined); + + await expect( + retryWindowsFileSystemOperationAsync(operation, { platform: "win32", wait }), + ).resolves.toBe("written"); + expect(operation).toHaveBeenCalledTimes(2); + }); + + it("does not retry off Windows", async () => { + const operation = vi.fn(async () => { + throw refusal("EPERM"); + }); + + await expect( + retryWindowsFileSystemOperationAsync(operation, { platform: "linux" }), + ).rejects.toThrow("refused: EPERM"); + expect(operation).toHaveBeenCalledTimes(1); + }); + + it("does not retry an error that is not a held file", async () => { + const operation = vi.fn(async () => { + throw refusal("ENOENT"); + }); + + await expect( + retryWindowsFileSystemOperationAsync(operation, { platform: "win32" }), + ).rejects.toThrow("refused: ENOENT"); + expect(operation).toHaveBeenCalledTimes(1); + }); + + it("waits between attempts without blocking the event loop", async () => { + const operation = vi.fn(async () => { + throw refusal("EACCES"); + }); + let ticked = false; + const timer = setTimeout(() => { + ticked = true; + }, 0); + + await expect( + retryWindowsFileSystemOperationAsync(operation, { platform: "win32", retries: 1, retryDelayMs: 1 }), + ).rejects.toThrow("refused: EACCES"); + clearTimeout(timer); + expect(ticked).toBe(true); + }); + + it("retries a synchronous refusal the same way", () => { + const operation = vi.fn(() => { + throw refusal("EPERM"); + }); + + expect(() => + retryWindowsFileSystemOperation(operation, { platform: "win32", wait: () => undefined }), + ).toThrow("refused: EPERM"); + expect(operation).toHaveBeenCalledTimes(5); + }); +}); \ No newline at end of file diff --git a/packages/webui/src/runtime/ssh/storage.ts b/packages/webui/src/runtime/ssh/storage.ts index 09a0262a6..f2d868d2f 100644 --- a/packages/webui/src/runtime/ssh/storage.ts +++ b/packages/webui/src/runtime/ssh/storage.ts @@ -31,7 +31,7 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; -import { loadBetterSqlite3 } from "@mavis/shared"; +import { loadBetterSqlite3, retryWindowsFileSystemOperationAsync } from "@mavis/shared"; import { SshRuntimeError } from "./errors.js"; @@ -187,7 +187,13 @@ export function createSshStore(filePath: string, codec: SshStoreCodec): Ss const temporaryPath = `${filePath}.${randomUUID()}.tmp`; try { await writeFile(temporaryPath, `${JSON.stringify(document, null, 2)}\n`, { mode: 0o600 }); - await rename(temporaryPath, filePath); + // Windows refuses the rename while another process holds the file open + // for a moment — an indexer, a scanner, a concurrent reader — and the + // refusal is transient. Every other atomic write in the repository + // retries it; this one did not, so the store failed at random on + // Windows and nowhere else. The rename stays awaited: the commit must + // not return before the document is in place. + await retryWindowsFileSystemOperationAsync(() => rename(temporaryPath, filePath)); } catch (error) { // A failed write must not leave an uncommitted document beside the real one. await rm(temporaryPath, { force: true }).catch(() => undefined); diff --git a/release/public-source.json b/release/public-source.json index 7316c2de8..7e9473fff 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -3240,6 +3240,7 @@ "packages/shared/src/watch-interval.ts", "packages/shared/src/web-source-evidence.ts", "packages/shared/src/windows-file-system.ts", + "packages/shared/test/windows-file-system.test.ts", "packages/tui/CHANGELOG.md", "packages/tui/CHANGELOG.zh-CN.md", "packages/tui/THIRD_PARTY_NOTICES.md", diff --git a/test/vitest-suites.json b/test/vitest-suites.json index 338b81f36..c0c437f5c 100644 --- a/test/vitest-suites.json +++ b/test/vitest-suites.json @@ -236,6 +236,7 @@ "packages/tui/test/unit/tui/controller/run/turn-submission-retainer.test.ts", "packages/tui/test/unit/tui/features/settings/hotkeys-picker.test.ts", "packages/tui/test/unit/incident-reporter-privacy.test.ts", + "packages/shared/test/windows-file-system.test.ts", "packages/config/test/config-file-permissions.test.ts", "packages/config/test/private-config-file.test.ts", "packages/config/test/managed-preset-sync.test.ts",