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-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/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/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/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 { 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/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/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/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(); 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/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/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(); 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: 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("(这是)"); + }); }); diff --git a/release/public-source.json b/release/public-source.json index c1be1bbd5..7e9473fff 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", @@ -3239,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/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); } diff --git a/test/vitest-suites.json b/test/vitest-suites.json index 1389b5189..c0c437f5c 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", @@ -235,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", 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);