From 3a8e23cc86b732476393ad29481491c570bc18e3 Mon Sep 17 00:00:00 2001 From: zhongxingxing Date: Fri, 27 Nov 2026 15:17:24 +0800 Subject: [PATCH 1/3] fix(webui): open the Windows folder picker through a koffi worker Replace the PowerShell/C# picker with a short-lived koffi worker that owns the modal IFileOpenDialog. The worker presses Alt immediately before Show so a dialog spawned by a background server still activates in front, and reports the selected path over IPC. Eligibility no longer depends on a TTY or WEBUI_OPEN_BROWSER: a local desktop loopback launch can create the picker. Add koffi to the package, update the installed-app acceptance driver, tests and install docs, and remove the PowerShell picker. --- README.md | 2 +- README_ZH.md | 2 +- packages/webui/README.md | 4 +- packages/webui/docs/client/composer.md | 6 +- release/public-source.json | 5 +- release/webui-npm/README.md | 11 +- release/webui-npm/bin/mcode-webui.mjs | 6 +- .../bin/native-directory-picker-win32.mjs | 99 ++++++++++++ .../bin/native-directory-picker-worker.cjs | 150 ++++++++++++++++++ .../webui-npm/bin/native-directory-picker.mjs | 53 +++---- .../webui-npm/bin/native-directory-picker.ps1 | 65 -------- release/webui-npm/package.json | 1 + scripts/lib/webui-windows-folder-dialog.ps1 | 30 ++-- scripts/verify-webui-package.mjs | 8 +- test/source-sync.test.mjs | 72 ++++----- 15 files changed, 343 insertions(+), 171 deletions(-) create mode 100644 release/webui-npm/bin/native-directory-picker-win32.mjs create mode 100644 release/webui-npm/bin/native-directory-picker-worker.cjs delete mode 100644 release/webui-npm/bin/native-directory-picker.ps1 diff --git a/README.md b/README.md index dd63c0999..1d5207ff6 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ mcode-webui With **npm 12 or later**, explicitly allow the native dependency install scripts: ```bash -npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate +npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate ``` The service listens on `http://127.0.0.1:2233/` and opens your default browser when launched in an interactive terminal. If it does not open, use the address printed in the terminal. Keep the process running while you work; press **Ctrl+C** to stop it. diff --git a/README_ZH.md b/README_ZH.md index b2b6e9d27..f294f7170 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -43,7 +43,7 @@ mcode-webui 使用 **npm 12 及以上版本**时,需要显式允许原生依赖的安装脚本: ```bash -npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate +npm install --global @minimax-webui/minimax-code --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate ``` 服务默认监听 `http://127.0.0.1:2233/`,在交互式终端启动时会打开默认浏览器。如果没有自动打开,使用终端打印的地址。使用期间保持服务进程运行,按 **Ctrl+C** 停止。 diff --git a/packages/webui/README.md b/packages/webui/README.md index 6bf57a928..1180b7587 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -22,7 +22,7 @@ With npm 12 or later, explicitly allow the native dependency install scripts: ```sh npm install --global @minimax-webui/minimax-code \ - --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate + --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate ``` To install the preview channel, use `@minimax-webui/minimax-code@preview` instead. @@ -198,7 +198,7 @@ node scripts/package-webui-npm.mjs --version 0.1.6-dev.1 \ --outdir ../minimax-code-webui-build/package npm pack ../minimax-code-webui-build/package --pack-destination ../minimax-code-webui-build npm install --global ../minimax-code-webui-build/minimax-webui-minimax-code-0.1.6-dev.1.tgz \ - --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate + --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate mcode-webui --version WEBUI_OPEN_BROWSER=0 mcode-webui --full-access ``` diff --git a/packages/webui/docs/client/composer.md b/packages/webui/docs/client/composer.md index 625aa6ae4..698fa5cbc 100644 --- a/packages/webui/docs/client/composer.md +++ b/packages/webui/docs/client/composer.md @@ -36,8 +36,10 @@ the notice shows a transfer error beside its action so the user can select anoth ## Workspace folder selection On the home page, `选择新项目` opens the system folder chooser in the browser -paired by an interactive local `mcode-webui` launch. Windows and macOS use their -system dialogs. On a Linux desktop the launcher uses Zenity or KDialog. Zenity opens +paired by an interactive local `mcode-webui` launch. Windows opens the native +`IFileOpenDialog` from a short-lived koffi worker, which also brings the dialog +to the foreground when the server was started in the background; macOS uses its +system dialog. On a Linux desktop the launcher uses Zenity or KDialog. Zenity opens in the last folder confirmed during this launch if it still exists, or in the user's home directory. This lets the chooser open even if a desktop application previously selected a folder that has since been removed. Confirming diff --git a/release/public-source.json b/release/public-source.json index 374113ffc..3df31cc80 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -61,6 +61,8 @@ ".gitignore", ".gitleaks.toml", ".npmrc", + ".openidea/.gitignore", + ".openidea/changelists.json", ".plan/browser-use/board/.notes-numbers", ".plan/browser-use/board/.spec-number", ".plan/browser-use/board/HANDOFF.md", @@ -5283,8 +5285,9 @@ "release/public-source.json", "release/webui-npm/README.md", "release/webui-npm/bin/mcode-webui.mjs", + "release/webui-npm/bin/native-directory-picker-win32.mjs", + "release/webui-npm/bin/native-directory-picker-worker.cjs", "release/webui-npm/bin/native-directory-picker.mjs", - "release/webui-npm/bin/native-directory-picker.ps1", "release/webui-npm/package.json", "schemas/plugins/app-v1.schema.json", "schemas/plugins/host-binding-v1.schema.json", diff --git a/release/webui-npm/README.md b/release/webui-npm/README.md index 7d6d32aa7..af46a555d 100644 --- a/release/webui-npm/README.md +++ b/release/webui-npm/README.md @@ -14,18 +14,19 @@ explicitly — npm 12 blocks dependency install scripts unless they are named: ```sh npm install --global @minimax-webui/minimax-code \ - --allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate + --allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate ``` Or allow them for every global install: ```sh -npm config set allow-scripts=better-sqlite3,bufferutil,node-pty,utf-8-validate --location=user +npm config set allow-scripts=better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate --location=user ``` -An install that skipped them leaves `better-sqlite3` without its binding, and -`mcode-webui` then stops at startup and prints the reinstall command instead of -running. npm 11 and earlier print the same warning but still run the scripts. +An install that skipped them leaves a native module (`better-sqlite3` or +`koffi`) without its binding, and `mcode-webui` then stops at startup and prints +the reinstall command instead of running. npm 11 and earlier print the same +warning but still run the scripts. The server listens on `http://127.0.0.1:2233/`. Set `WEBUI_SERVER_PORT` to change the port or `MINIMAX_DATA_DIR` to change the local data directory. The diff --git a/release/webui-npm/bin/mcode-webui.mjs b/release/webui-npm/bin/mcode-webui.mjs index fedae6991..bf11d728c 100644 --- a/release/webui-npm/bin/mcode-webui.mjs +++ b/release/webui-npm/bin/mcode-webui.mjs @@ -92,7 +92,7 @@ process.env.MAVIS_BUILTIN_AGENTS_DIR ??= path.join(packageRoot, "assets/agents") * The check is here, at the composition root, because it is the last place that * knows both the dependency list and the package name a person can reinstall. */ -const NATIVE_MODULES = ["better-sqlite3", "node-pty"]; +const NATIVE_MODULES = ["better-sqlite3", ...(process.platform === "win32" ? ["koffi"] : []), "node-pty"]; /** * Load each module the way the runtime will. * @@ -105,6 +105,7 @@ const NATIVE_PROBES = { "better-sqlite3": (module) => { new module(":memory:").close(); }, + "koffi": () => {}, "node-pty": () => {}, }; const unbuilt = []; @@ -260,8 +261,7 @@ await browser.initialize(); const { nativeDirectoryPickerEligible, createNativeDirectoryPicker, nativeDirectoryLaunchUrl } = await import("./native-directory-picker.mjs"); const nativeDirectoryPicker = nativeDirectoryPickerEligible({ - platform: process.platform, tty: Boolean(process.stdout.isTTY), bindHost, - fullAccess: args["full-access"], browserSetting: process.env.WEBUI_OPEN_BROWSER, + platform: process.platform, bindHost, fullAccess: args["full-access"], }) ? createNativeDirectoryPicker() : undefined; const service = new WebuiService({ nativeDirectoryPicker, diff --git a/release/webui-npm/bin/native-directory-picker-win32.mjs b/release/webui-npm/bin/native-directory-picker-win32.mjs new file mode 100644 index 000000000..5da1f05a2 --- /dev/null +++ b/release/webui-npm/bin/native-directory-picker-win32.mjs @@ -0,0 +1,99 @@ +// Windows native folder chooser driver. The dialog lives in a child process +// (native-directory-picker-worker.cjs) so the server event loop never blocks +// inside the modal Win32 call; this module only owns the IPC conversation and +// keeps one pick in flight, exactly like the other platform adapters. + +import { spawn } from 'node:child_process'; +import { randomUUID } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; + +const WORKER = fileURLToPath(new URL('./native-directory-picker-worker.cjs', import.meta.url)); +const TITLE = '选择文件夹'; +const unavailable = () => new Error('Native folder selection is unavailable'); + +export function createWin32DirectoryPicker({ spawnProcess = spawn, timeoutMs = 120_000 } = {}) { + let active; + let disposed = false; + + function choose(signal) { + if (disposed || active || signal.aborted) return Promise.reject(unavailable()); + return new Promise((resolve, reject) => { + let child; + let settled = false; + let aborting = false; + let timer; + let killWatchdog; + let markClosed; + const closed = new Promise((resolveClosed) => { markClosed = resolveClosed; }); + + const finish = (error, result) => { + if (settled) return; + settled = true; + clearTimeout(timer); + clearTimeout(killWatchdog); + signal.removeEventListener('abort', abort); + child?.unref?.(); + if (error) reject(unavailable()); else resolve(result); + }; + + const abort = () => { + if (aborting || settled) return; + aborting = true; + try { child?.kill(); } catch { /* The close event still decides the outcome. */ } + // Never release the HTTP flight before the process is known to be gone. + killWatchdog = setTimeout(() => { disposed = true; finish(unavailable()); }, 1000); + }; + + timer = setTimeout(abort, timeoutMs); + try { + child = spawnProcess(process.execPath, [WORKER], { + env: { ...process.env, MCODE_DIALOG_TITLE: TITLE }, + stdio: ['ignore', 'ignore', 'ignore', 'ipc'], + windowsHide: true, + }); + } catch { + finish(unavailable()); + return; + } + active = { abort, closed }; + signal.addEventListener('abort', abort, { once: true }); + if (signal.aborted) abort(); + child.once('error', () => finish(unavailable())); + child.once('close', () => { + active = undefined; + markClosed(); + if (!settled) finish(unavailable()); + }); + child.on('message', (message) => { + if (!message || typeof message !== 'object') return; + if (message.kind === 'error') { finish(unavailable()); return; } + if (message.kind !== 'done') return; + if (message.path === null || message.path === undefined || message.path === '') { + finish(null, { kind: 'cancelled' }); + return; + } + if (typeof message.path !== 'string' || !path.win32.isAbsolute(message.path) || /[\0\r\n]/.test(message.path)) { + finish(unavailable()); + return; + } + finish(null, { kind: 'selected', directory: message.path }); + }); + }); + } + + return { + grant: randomUUID(), + choose, + async dispose() { + disposed = true; + const pending = active; + if (!pending) return; + pending.abort(); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(unavailable()), 1000); + pending.closed.then(() => { clearTimeout(timer); resolve(); }); + }); + }, + }; +} \ No newline at end of file diff --git a/release/webui-npm/bin/native-directory-picker-worker.cjs b/release/webui-npm/bin/native-directory-picker-worker.cjs new file mode 100644 index 000000000..def1fc9ba --- /dev/null +++ b/release/webui-npm/bin/native-directory-picker-worker.cjs @@ -0,0 +1,150 @@ +'use strict'; + +// The dialog child: the WebUI server must not block inside the Win32 modal +// call, and a child spawned by a background server has no foreground rights. +// This process owns the IFileOpenDialog through koffi, presses Alt once before +// Show so the dialog activates, and reports the selection over IPC. + +if (typeof process.send !== 'function') process.exit(1); +const send = process.send.bind(process); +function post(message, final) { + if (!process.connected) return; + send(message, () => { if (final && process.connected) process.disconnect(); }); +} +process.on('disconnect', () => process.exit(0)); + +let koffi; +try { + koffi = require('koffi'); +} catch (error) { + post({ kind: 'error', message: String(error && error.message || error) }, true); + setTimeout(() => process.exit(1), 10); +} + +const COINIT_APARTMENTTHREADED = 0x2; +const CLSCTX_INPROC_SERVER = 0x1; +const SIGDN_FILESYSPATH = 0x80058000 | 0; +const HRESULT_CANCELLED = 0x800704c7 | 0; +const FOS_PICKFOLDERS = 0x20; +const FOS_FORCEFILESYSTEM = 0x40; +const FOS_NOCHANGEDIR = 0x8; +const DPI_AWARENESS_CONTEXTS = [-4, -3, -2]; +const VK_MENU = 0x12; +const KEYEVENTF_KEYUP = 0x2; +const SLOT_RELEASE = 2; +const SLOT_SHOW = 3; +const SLOT_SET_OPTIONS = 9; +const SLOT_SET_TITLE = 17; +const SLOT_GET_RESULT = 20; +const SLOT_GET_DISPLAY_NAME = 5; +const TITLE = process.env.MCODE_DIALOG_TITLE || '选择文件夹'; + +function guidBytes(text) { + const match = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(text); + if (!match) throw new Error('invalid GUID'); + const bytes = Buffer.alloc(16); + bytes.writeUInt32LE(parseInt(match[1], 16), 0); + bytes.writeUInt16LE(parseInt(match[2], 16), 4); + bytes.writeUInt16LE(parseInt(match[3], 16), 6); + Buffer.from(match[4] + match[5], 'hex').copy(bytes, 8); + return bytes; +} + +const CLSID_FILE_OPEN_DIALOG = guidBytes('dc1c5a9c-e88a-4dde-a5a1-60f82a20aef7'); +const IID_IFILE_OPEN_DIALOG = guidBytes('d57c7288-d4ad-4768-be02-9d969532d960'); + +function readUtf16(address, pointerSize) { + const pointer = Buffer.alloc(8); + pointer.writeBigUInt64LE(BigInt(address)); + return koffi.decode(pointer.subarray(0, pointerSize), 'str16'); +} + +function check(hr, what) { + if (hr < 0) throw new Error(what + ' failed: HRESULT 0x' + (hr >>> 0).toString(16)); + return hr; +} + +function runFolderDialog(onShowing) { + const ole32 = koffi.load('ole32.dll'); + const user32 = koffi.load('user32.dll'); + const kernel32 = koffi.load('kernel32.dll'); + const pointerSize = koffi.sizeof('void *'); + const coInitializeEx = ole32.func('__stdcall', 'CoInitializeEx', 'int32', ['void *', 'uint32']); + const coUninitialize = ole32.func('__stdcall', 'CoUninitialize', 'void', []); + const coCreateInstance = ole32.func('__stdcall', 'CoCreateInstance', 'int32', ['void *', 'void *', 'uint32', 'void *', 'void *']); + const coTaskMemFree = ole32.func('__stdcall', 'CoTaskMemFree', 'void', ['void *']); + const getCurrentThreadId = kernel32.func('__stdcall', 'GetCurrentThreadId', 'uint32', []); + const keybdEvent = user32.func('__stdcall', 'keybd_event', 'void', ['uint8', 'uint8', 'uint32', 'uintptr']); + + const protoShow = koffi.proto('int32 __stdcall McodeDialogShow(void *self, void *owner)'); + const protoSetOptions = koffi.proto('int32 __stdcall McodeDialogSetOptions(void *self, uint32 options)'); + const protoSetTitle = koffi.proto('int32 __stdcall McodeDialogSetTitle(void *self, str16 title)'); + const protoGetResult = koffi.proto('int32 __stdcall McodeDialogGetResult(void *self, _Out_ void **item)'); + const protoGetDisplayName = koffi.proto('int32 __stdcall McodeItemGetDisplayName(void *self, int32 form, _Out_ void **name)'); + const protoRelease = koffi.proto('uint32 __stdcall McodeComRelease(void *self)'); + + function method(self, slot, proto) { + const vtable = koffi.decode(self, 'void *'); + const fn = koffi.decode(vtable, slot * pointerSize, 'void *'); + return (...args) => koffi.call(fn, proto, self, ...args); + } + + function setThreadDpiAwareness() { + let setContext; + try { + setContext = user32.func('__stdcall', 'SetThreadDpiAwarenessContext', 'void *', ['intptr']); + } catch { + return; + } + for (const context of DPI_AWARENESS_CONTEXTS) { + try { if (setContext(context) !== null) return; } catch { return; } + } + } + + function pressAltForForeground() { + keybdEvent(VK_MENU, 0, 0, 0); + keybdEvent(VK_MENU, 0, KEYEVENTF_KEYUP, 0); + } + + setThreadDpiAwareness(); + check(coInitializeEx(null, COINIT_APARTMENTTHREADED), 'CoInitializeEx'); + try { + const out = Buffer.alloc(pointerSize); + check(coCreateInstance(CLSID_FILE_OPEN_DIALOG, null, CLSCTX_INPROC_SERVER, IID_IFILE_OPEN_DIALOG, out), 'CoCreateInstance'); + const dialog = koffi.decode(out, 'void *'); + try { + check(method(dialog, SLOT_SET_OPTIONS, protoSetOptions)(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR), 'SetOptions'); + check(method(dialog, SLOT_SET_TITLE, protoSetTitle)(TITLE), 'SetTitle'); + onShowing(getCurrentThreadId()); + pressAltForForeground(); + const shown = method(dialog, SLOT_SHOW, protoShow)(null); + if (shown === HRESULT_CANCELLED) return null; + check(shown, 'Show'); + const itemOut = [null]; + check(method(dialog, SLOT_GET_RESULT, protoGetResult)(itemOut), 'GetResult'); + const item = itemOut[0]; + try { + const nameOut = [null]; + check(method(item, SLOT_GET_DISPLAY_NAME, protoGetDisplayName)(SIGDN_FILESYSPATH, nameOut), 'GetDisplayName'); + const selected = readUtf16(nameOut[0], pointerSize); + coTaskMemFree(nameOut[0]); + return selected; + } finally { + method(item, SLOT_RELEASE, protoRelease)(); + } + } finally { + method(dialog, SLOT_RELEASE, protoRelease)(); + } + } finally { + coUninitialize(); + } +} + +if (koffi) { + try { + const selected = runFolderDialog((threadId) => post({ kind: 'showing', threadId }, false)); + post({ kind: 'done', path: selected }, true); + } catch (error) { + post({ kind: 'error', message: String(error && error.message || error) }, true); + } +} \ No newline at end of file diff --git a/release/webui-npm/bin/native-directory-picker.mjs b/release/webui-npm/bin/native-directory-picker.mjs index 5dbb2ed33..d613675a5 100644 --- a/release/webui-npm/bin/native-directory-picker.mjs +++ b/release/webui-npm/bin/native-directory-picker.mjs @@ -1,17 +1,19 @@ import { spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { accessSync, constants } from 'node:fs'; -import { access, readFile } from 'node:fs/promises'; +import { access } from 'node:fs/promises'; import { homedir } from 'node:os'; import path from 'node:path'; -export function nativeDirectoryPickerEligible({ platform, tty, bindHost, fullAccess, browserSetting, env = process.env }) { - const setting = browserSetting?.trim().toLowerCase(); +import { createWin32DirectoryPicker } from './native-directory-picker-win32.mjs'; + +export function nativeDirectoryPickerEligible({ platform, bindHost, fullAccess, env = process.env }) { + // No TTY requirement: the Win32 worker activates its own dialog, so a + // background desktop launch still has a usable native chooser. const desktop = platform === 'win32' || platform === 'darwin' || (platform === 'linux' && Boolean(env.DISPLAY || env.WAYLAND_DISPLAY)); - return desktop && tty === true && !fullAccess && !env.SSH_CONNECTION && !env.SSH_TTY - && ['127.0.0.1', '::1'].includes(bindHost) - && !['0', 'false', 'no', 'off', 'never'].includes(setting); + return desktop && !fullAccess && !env.SSH_CONNECTION && !env.SSH_TTY + && ['127.0.0.1', '::1'].includes(bindHost); } export function nativeDirectoryLaunchUrl(url, grant) { @@ -68,23 +70,14 @@ function unixDirectoryCommand(platform, env, executable) { function directoryResult(platform, code, output, cancelExitCode) { if (platform === 'linux' && code === cancelExitCode && output === '') return { kind: 'cancelled' }; if (code !== 0) throw unavailable(); - if (platform === 'win32') { - const result = JSON.parse(output.replace(/^\uFEFF/, '').trim()); - if (result.kind === 'cancelled') return { kind: 'cancelled' }; - if (result.kind === 'selected' && typeof result.directory === 'string' - && path.win32.isAbsolute(result.directory) && !/[\0\r\n]/.test(result.directory)) { - return { kind: 'selected', directory: result.directory }; - } - } else { - // Remove just the command's line terminator. Spaces and newlines can belong to a Unix folder name. - const directory = output.endsWith('\n') ? output.slice(0, -1) : output; - if (platform === 'darwin' && directory === 'cancelled') return { kind: 'cancelled' }; - if (path.posix.isAbsolute(directory) && !directory.includes('\0')) { - // macOS folder aliases include a trailing slash. Match existing project paths, keeping - // a separator after significant whitespace so workspaceDir.trim() preserves the folder. - const folder = directory.replace(/\/+$/u, '') || '/'; - return { kind: 'selected', directory: /\s$/u.test(folder) ? folder + '/' : folder }; - } + // Remove just the command's line terminator. Spaces and newlines can belong to a Unix folder name. + const directory = output.endsWith('\n') ? output.slice(0, -1) : output; + if (platform === 'darwin' && directory === 'cancelled') return { kind: 'cancelled' }; + if (path.posix.isAbsolute(directory) && !directory.includes('\0')) { + // macOS folder aliases include a trailing slash. Match existing project paths, keeping + // a separator after significant whitespace so workspaceDir.trim() preserves the folder. + const folder = directory.replace(/\/+$/u, '') || '/'; + return { kind: 'selected', directory: /\s$/u.test(folder) ? folder + '/' : folder }; } throw unavailable(); } @@ -94,11 +87,11 @@ const unavailable = () => new Error('Native folder selection is unavailable'); // A narrow launcher-owned provider, never a shell/command execution endpoint. export function createNativeDirectoryPicker({ platform = process.platform, env = process.env, executable = isExecutable, - spawnProcess = spawn, readScript = () => readFile(new URL('./native-directory-picker.ps1', import.meta.url), 'utf8'), - windowsRoot = env.SystemRoot, architecture = process.arch, + spawnProcess = spawn, } = {}) { + if (platform === 'win32') return createWin32DirectoryPicker({ spawnProcess }); const command = unixDirectoryCommand(platform, env, executable); - if (platform !== 'win32' && !command) return; + if (!command) return; const zenity = command && path.posix.basename(command[0]) === 'zenity'; // GTK startup also exits 1 when the display is gone. Give user dismissal its own status. const cancelExitCode = zenity ? 9 : 1; @@ -115,14 +108,6 @@ export function createNativeDirectoryPicker({ // Without current_folder the GNOME portal restores its own possibly deleted last folder. const folder = await zenityStartingFolder(lastZenityDirectory, env.HOME ?? homedir()); invocation = [command[0], [...command[1], '--filename=' + folder]]; - } else if (platform === 'win32') { - if (!windowsRoot || !path.win32.isAbsolute(windowsRoot)) throw unavailable(); - let script; - try { script = await readScript(); } catch { throw unavailable(); } - // A 32-bit launcher must reach 64-bit Windows PowerShell, not its redirected SysWOW64 copy. - const system = architecture === 'ia32' ? 'Sysnative' : 'System32'; - invocation = [path.win32.join(windowsRoot, system, 'WindowsPowerShell', 'v1.0', 'powershell.exe'), - ['-NoLogo', '-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]]; } if (disposed || active || signal.aborted) throw unavailable(); return new Promise((resolve, reject) => { diff --git a/release/webui-npm/bin/native-directory-picker.ps1 b/release/webui-npm/bin/native-directory-picker.ps1 deleted file mode 100644 index f8a8c6188..000000000 --- a/release/webui-npm/bin/native-directory-picker.ps1 +++ /dev/null @@ -1,65 +0,0 @@ -# Fixed launcher-owned program. No request text is accepted as code or arguments. -$ErrorActionPreference = 'Stop' -[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) -if (-not [Environment]::UserInteractive -or [Diagnostics.Process]::GetCurrentProcess().SessionId -eq 0) { exit 3 } -Add-Type -TypeDefinition @' -using System; -using System.Runtime.InteropServices; -namespace WebuiFolderPicker { - [ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")] class FileOpenDialog {} - [ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IFileDialog { - [PreserveSig] int Show(IntPtr owner); - void SetFileTypes(uint count, IntPtr filters); - void SetFileTypeIndex(uint index); - void GetFileTypeIndex(out uint index); - void Advise(IntPtr events, out uint cookie); - void Unadvise(uint cookie); - void SetOptions(uint options); - void GetOptions(out uint options); - void SetDefaultFolder(IShellItem item); - void SetFolder(IShellItem item); - void GetFolder(out IShellItem item); - void GetCurrentSelection(out IShellItem item); - void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); - void GetFileName(out IntPtr name); - void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); - void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label); - void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); - void GetResult(out IShellItem item); - } - [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IShellItem { - void BindToHandler(IntPtr context, ref Guid handler, ref Guid iid, out IntPtr result); - void GetParent(out IShellItem parent); - void GetDisplayName(uint name, out IntPtr result); - void GetAttributes(uint mask, out uint attributes); - void Compare(IShellItem other, uint hint, out int order); - } - public static class Picker { - public static string Choose() { - object instance = new FileOpenDialog(); IShellItem item = null; IntPtr name = IntPtr.Zero; - try { - var dialog = (IFileDialog)instance; - uint flags; dialog.GetOptions(out flags); - // PICKFOLDERS | FORCEFILESYSTEM | PATHMUSTEXIST | DONTADDTORECENT. - dialog.SetOptions(flags | 0x20u | 0x40u | 0x800u | 0x2000000u); - int result = dialog.Show(IntPtr.Zero); - if (result == unchecked((int)0x800704C7)) return null; - Marshal.ThrowExceptionForHR(result); - dialog.GetResult(out item); item.GetDisplayName(0x80058000u, out name); - return Marshal.PtrToStringUni(name); - } finally { - if (name != IntPtr.Zero) Marshal.FreeCoTaskMem(name); - if (item != null) Marshal.FinalReleaseComObject(item); - Marshal.FinalReleaseComObject(instance); - } - } - } -} -'@ -try { - $directory = [WebuiFolderPicker.Picker]::Choose() - if ($null -eq $directory) { '{"kind":"cancelled"}' } - else { @{kind='selected';directory=$directory} | ConvertTo-Json -Compress } -} catch { exit 3 } diff --git a/release/webui-npm/package.json b/release/webui-npm/package.json index 473f3ffd2..c45c7abe5 100644 --- a/release/webui-npm/package.json +++ b/release/webui-npm/package.json @@ -28,6 +28,7 @@ "dependencies": { "@larksuiteoapi/node-sdk": "1.73.3", "better-sqlite3": "12.11.1", + "koffi": "3.1.1", "node-pty": "1.1.0" }, "optionalDependencies": { diff --git a/scripts/lib/webui-windows-folder-dialog.ps1 b/scripts/lib/webui-windows-folder-dialog.ps1 index 1332382f3..ae6de72b9 100644 --- a/scripts/lib/webui-windows-folder-dialog.ps1 +++ b/scripts/lib/webui-windows-folder-dialog.ps1 @@ -3,7 +3,7 @@ #requires -Version 5.1 param( [Parameter(Mandatory)][int]$LauncherPid, - [Parameter(Mandatory)][string]$PickerScript, + [Parameter(Mandatory)][string]$PickerWorker, [Parameter(Mandatory)][ValidateSet('select', 'cancel')][string]$Action, [string]$Directory ) @@ -166,7 +166,7 @@ $launchRoot = Get-Process -Id $LauncherPid if ($launchRoot.SessionId -ne [Diagnostics.Process]::GetCurrentProcess().SessionId) { throw "The launcher PID $LauncherPid is in another Windows session." } -$launcherPath = Join-Path (Get-Item -LiteralPath $PickerScript).DirectoryName 'mcode-webui.mjs' +$launcherPath = Join-Path (Get-Item -LiteralPath $PickerWorker).DirectoryName 'mcode-webui.mjs' # A Windows npm bin shim may put cmd.exe above node.exe. Search only this launch tree. # The entry point is Node's first argument, whether the absolute path needs quoting or not. function Find-LauncherNode($process) { @@ -186,13 +186,11 @@ $nodes = @(Find-LauncherNode $startProcess) if ($nodes.Count -ne 1) { throw "Expected one installed WebUI Node entry in the tree of PID $LauncherPid; found $($nodes.Count)." } $launcher = Get-Process -Id $nodes[0].ProcessId [void]$launcher.Handle -# Node encodes the UTF-8 source (including its original line endings) as UTF-16LE. -# Compare the argument, never print the encoded command or inspect unrelated processes. -$sourceBytes = [IO.File]::ReadAllBytes($PickerScript) -$source = [Text.Encoding]::UTF8.GetString($sourceBytes) -$payload = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($source)) -$expectedArgument = '-EncodedCommand\s+"?' + [regex]::Escape($payload) + '"?\s*$' -$filter = "ParentProcessId=$($launcher.Id) AND Name='powershell.exe'" +# The worker is the launcher's direct node child whose entry point is the +# installed native-directory-picker-worker.cjs. Compare the argument, never +# print or inspect unrelated processes. +$expectedArgument = '"?' + [regex]::Escape($PickerWorker) + '"?\s*$' +$filter = "ParentProcessId=$($launcher.Id) AND Name='node.exe'" $clock = [Diagnostics.Stopwatch]::StartNew() $picker = $null $dialog = $null @@ -201,11 +199,11 @@ $children = [System.Windows.Automation.TreeScope]::Children while ($clock.Elapsed.TotalSeconds -lt 20) { if ($launcher.HasExited) { throw "The WebUI launcher PID $LauncherPid exited before showing the chooser." } if (-not $picker) { - $matchesScript = @(Get-CimInstance Win32_Process -Filter $filter -Property $processFields | + $matchesWorker = @(Get-CimInstance Win32_Process -Filter $filter -Property $processFields | Where-Object { $_.CommandLine -cmatch $expectedArgument }) - if ($matchesScript.Count -gt 1) { throw 'More than one child matches the installed picker script.' } - if ($matchesScript.Count -eq 1) { - $picker = Get-Process -Id $matchesScript[0].ProcessId -ErrorAction SilentlyContinue + if ($matchesWorker.Count -gt 1) { throw 'More than one child matches the installed picker worker.' } + if ($matchesWorker.Count -eq 1) { + $picker = Get-Process -Id $matchesWorker[0].ProcessId -ErrorAction SilentlyContinue if ($picker) { [void]$picker.Handle $pidCondition = [System.Windows.Automation.PropertyCondition]::new( @@ -214,7 +212,7 @@ while ($clock.Elapsed.TotalSeconds -lt 20) { } } if ($picker) { - if ($picker.HasExited) { throw "The matching PowerShell PID $($picker.Id) exited without showing its folder dialog." } + if ($picker.HasExited) { throw "The matching picker worker PID $($picker.Id) exited without showing its folder dialog." } $visible = @($root.FindAll($children, $pidCondition) | Where-Object { $_.Current.ClassName -eq '#32770' -and -not $_.Current.IsOffscreen }) if ($visible.Count -gt 1) { throw "Ambiguous chooser: PID $($picker.Id) owns multiple visible dialogs." } @@ -225,8 +223,8 @@ while ($clock.Elapsed.TotalSeconds -lt 20) { } Start-Sleep -Milliseconds 120 } -if (-not $picker) { throw "No PowerShell child of launcher PID $LauncherPid matched the installed chooser script." } -if (-not $dialog) { throw "The matching PowerShell PID $($picker.Id) did not display a visible #32770 dialog." } +if (-not $picker) { throw "No node child of launcher PID $LauncherPid matched the installed picker worker." } +if (-not $dialog) { throw "The matching picker worker PID $($picker.Id) did not display a visible #32770 dialog." } $window = [IntPtr]$dialog.Current.NativeWindowHandle if (-not [WebuiTestDesktop]::OwnsDialog($window, $picker.Id)) { throw 'The visible UI element has no matching native dialog handle.' } function Open-AddressEdit { diff --git a/scripts/verify-webui-package.mjs b/scripts/verify-webui-package.mjs index 07bfbb745..4ecdde715 100644 --- a/scripts/verify-webui-package.mjs +++ b/scripts/verify-webui-package.mjs @@ -87,13 +87,13 @@ let child; await withCleanup(async () => { const archive = values.archive ? path.resolve(values.archive) : packCandidate(); const prefix = path.join(work, "install"); - // npm 12 blocks dependency install scripts unless they are named, and the two + // npm 12 blocks dependency install scripts unless they are named, and the // native modules this package needs are built by those scripts. A global // install is the shape that accepts the flag — npm 12 refuses it for a // project-scoped install — so the acceptance installs the way a person must, // which is also the only way the startup below can be exercised at all. const npmMajor = Number(run(npm, ["--version"]).trim().split(".")[0]); - const allowScripts = "better-sqlite3,bufferutil,node-pty,utf-8-validate"; + const allowScripts = "better-sqlite3,bufferutil,koffi,node-pty,utf-8-validate"; run( npm, npmMajor >= 12 @@ -242,10 +242,10 @@ async function verifyWindowsProjectSelection(installed) { const directory = mkdtempSync(path.join(work, "Project 示例 ")); const browser = await launchNativeProjectBrowser({ installed, work, port: await availablePort(), miniappPort: await availablePort() }); const driver = path.join(root, "scripts/lib/webui-windows-folder-dialog.ps1"); - const pickerScript = path.join(installed, "bin/native-directory-picker.ps1"); + const pickerWorker = path.join(installed, "bin/native-directory-picker-worker.cjs"); const driveDialog = async ({ action, signal }) => { const args = ["-NoProfile", "-NonInteractive", "-STA", "-ExecutionPolicy", "Bypass", "-File", driver, - "-LauncherPid", String(browser.launcherPid), "-PickerScript", pickerScript, "-Action", action]; + "-LauncherPid", String(browser.launcherPid), "-PickerWorker", pickerWorker, "-Action", action]; if (action === "select") args.push("-Directory", directory); const { stdout } = await promisify(execFile)("powershell.exe", args, { signal, timeout: 45_000, windowsHide: true }); console.log(stdout.trim()); diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index 107f558f1..b11e3b6f7 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -1589,18 +1589,17 @@ test('the desktop version the marketplace is filtered by is declared in exactly assert.deepEqual(offenders, [], 'the declared desktop version is written in the shared module only'); }); -test('native folder launcher grant is restricted to authenticated interactive desktop loopback', () => { - const local = { platform: 'win32', tty: true, bindHost: '127.0.0.1', fullAccess: false, env: {} }; +test('native folder launcher grant is restricted to local desktop loopback', () => { + const local = { platform: 'win32', bindHost: '127.0.0.1', fullAccess: false, env: {} }; for (const change of [{}, { platform: 'darwin' }, { platform: 'linux', env: { DISPLAY: ':0' } }, - { platform: 'linux', env: { WAYLAND_DISPLAY: 'wayland-0' } }]) { + { platform: 'linux', env: { WAYLAND_DISPLAY: 'wayland-0' } }, { tty: false }]) { assert.equal(nativeDirectoryPickerEligible({ ...local, ...change }), true); } for (const change of [{ platform: 'linux' }, { platform: 'freebsd' }, { env: { SSH_TTY: '/dev/pts/0' } }, { platform: 'linux', env: { DISPLAY: ':0', SSH_CONNECTION: 'forwarded session' } }, - { tty: false }, { fullAccess: true }, { bindHost: '0.0.0.0' }, { bindHost: '192.168.1.1' }, { browserSetting: 'off' }]) { + { fullAccess: true }, { bindHost: '0.0.0.0' }, { bindHost: '192.168.1.1' }]) { assert.equal(nativeDirectoryPickerEligible({ ...local, ...change }), false); } - assert.equal(nativeDirectoryPickerEligible({ ...local, tty: false, browserSetting: '1' }), false); const plain = 'http://127.0.0.1:2233/?token=fixture'; const granted = nativeDirectoryLaunchUrl(plain, 'synthetic-native-grant'); assert.equal(granted.split('#')[0], plain); @@ -1700,39 +1699,40 @@ test('native folder Zenity starts in an existing folder even after the previousl await choose('/'); }); -test('native folder chooser uses a fixed STA program and narrow selected/cancel results', async () => { +test('native folder chooser drives the koffi worker and narrow selected/cancel results', async () => { const { EventEmitter } = await import('node:events'); - const { PassThrough } = await import('node:stream'); let child; let invocation; - const picker = createNativeDirectoryPicker({ platform: 'win32', windowsRoot: 'C:\\Windows', architecture: 'ia32', readScript: async () => 'fixed script', spawnProcess: (...args) => { - invocation = args; child = new EventEmitter(); child.stdout = new PassThrough(); child.kill = () => true; return child; + const picker = createNativeDirectoryPicker({ platform: 'win32', spawnProcess: (...args) => { + invocation = args; child = new EventEmitter(); child.kill = () => true; child.unref = () => {}; return child; } }); const selected = picker.choose(new AbortController().signal); await Promise.resolve(); - assert.match(invocation[0], /Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe$/); - assert.deepEqual(invocation[1].slice(0, 5), ['-NoLogo', '-NoProfile', '-NonInteractive', '-STA', '-EncodedCommand']); - assert.equal(Buffer.from(invocation[1][5], 'base64').toString('utf16le'), 'fixed script'); - assert.equal(invocation[2].shell, false); - child.stdout.write(JSON.stringify({ kind: 'selected', directory: 'D:\\项目\\work' })); child.emit('close', 0); + assert.equal(invocation[0], process.execPath); + assert.match(invocation[1][0], /native-directory-picker-worker\.cjs$/); + assert.deepEqual(invocation[2].stdio, ['ignore', 'ignore', 'ignore', 'ipc']); + assert.equal(invocation[2].windowsHide, true); + child.emit('message', { kind: 'showing', threadId: 7 }); + child.emit('message', { kind: 'done', path: 'D:\\项目\\work' }); + child.emit('close', 0); assert.deepEqual(await selected, { kind: 'selected', directory: 'D:\\项目\\work' }); const cancelled = picker.choose(new AbortController().signal); await Promise.resolve(); - child.stdout.write('{"kind":"cancelled"}'); child.emit('close', 0); + child.emit('message', { kind: 'done', path: null }); + child.emit('close', 0); assert.deepEqual(await cancelled, { kind: 'cancelled' }); await picker.dispose(); await assert.rejects(picker.choose(new AbortController().signal), /unavailable/); - const script = readFileSync(new URL('../release/webui-npm/bin/native-directory-picker.ps1', import.meta.url), 'utf8'); - assert.match(script, /UserInteractive/); assert.match(script, /SessionId -eq 0/); - assert.match(script, /0x20u \| 0x40u \| 0x800u \| 0x2000000u/); - assert.match(script, /0x800704C7/); assert.match(script, /dialog.Show\(IntPtr.Zero\)/); - assert.doesNotMatch(script, /\$args|Invoke-Expression|Start-Process/); + const worker = readFileSync(new URL('../release/webui-npm/bin/native-directory-picker-worker.cjs', import.meta.url), 'utf8'); + assert.match(worker, /require\('koffi'\)/); + assert.match(worker, /keybd_event/); + assert.match(worker, /dc1c5a9c-e88a-4dde-a5a1-60f82a20aef7/); + assert.doesNotMatch(worker, /Invoke-Expression|Start-Process/); }); -test('native folder abort kills its child and keeps it busy until close; failures disclose no output', async () => { +test('native folder abort kills its worker and keeps it busy until close; failures disclose no output', async () => { const { EventEmitter } = await import('node:events'); - const { PassThrough } = await import('node:stream'); let child; let killed = 0; - const picker = createNativeDirectoryPicker({ platform: 'win32', windowsRoot: 'C:\\Windows', readScript: async () => 'fixed', spawnProcess: () => { - child = new EventEmitter(); child.stdout = new PassThrough(); child.kill = () => { killed++; return true; }; return child; + const picker = createNativeDirectoryPicker({ platform: 'win32', spawnProcess: () => { + child = new EventEmitter(); child.kill = () => { killed++; return true; }; child.unref = () => {}; return child; } }); const controller = new AbortController(); const pending = picker.choose(controller.signal); await Promise.resolve(); let settled = false; @@ -1744,23 +1744,24 @@ test('native folder abort kills its child and keeps it busy until close; failure await assert.rejects(picker.choose(new AbortController().signal), /unavailable/); child.emit('close', 1); await rejection; const malformed = picker.choose(new AbortController().signal); await Promise.resolve(); - child.stdout.write('private-path-or-error'); child.emit('close', 0); + child.emit('message', { kind: 'error', message: 'private-path-or-error' }); + child.emit('close', 0); await assert.rejects(malformed, /^Error: Native folder selection is unavailable$/); await picker.dispose(); }); -test('native folder chooser rejects pre-abort and malformed output and waits for disposal close', async () => { +test('native folder chooser rejects pre-abort and malformed paths and waits for disposal close', async () => { const { EventEmitter } = await import('node:events'); - const { PassThrough } = await import('node:stream'); let child; let launches = 0; - const picker = createNativeDirectoryPicker({ platform: 'win32', windowsRoot: 'C:\\Windows', readScript: async () => 'fixed', spawnProcess: () => { - launches++; child = new EventEmitter(); child.stdout = new PassThrough(); child.kill = () => true; return child; + const picker = createNativeDirectoryPicker({ platform: 'win32', spawnProcess: () => { + launches++; child = new EventEmitter(); child.kill = () => true; child.unref = () => {}; return child; } }); const aborted = new AbortController(); aborted.abort(); await assert.rejects(picker.choose(aborted.signal), /unavailable/); assert.equal(launches, 0); - for (const output of ['{"kind":"selected","directory":"relative"}', '{"kind":"unexpected"}']) { + for (const candidate of ['relative', 'C:\\bad\0path']) { const pending = picker.choose(new AbortController().signal); await Promise.resolve(); - child.stdout.write(output); child.emit('close', 0); + child.emit('message', { kind: 'done', path: candidate }); + child.emit('close', 0); await assert.rejects(pending, /unavailable/); } const pending = picker.choose(new AbortController().signal); await Promise.resolve(); @@ -1771,19 +1772,16 @@ test('native folder chooser rejects pre-abort and malformed output and waits for child.emit('close', 1); await rejected; await disposal; assert.equal(disposed, true); }); -test('native folder termination watchdog permanently fails closed if the process does not exit', async () => { +test('native folder termination watchdog permanently fails closed if the worker does not exit', async () => { const { EventEmitter } = await import('node:events'); - const { PassThrough } = await import('node:stream'); let child; let kills = 0; - const picker = createNativeDirectoryPicker({ platform: 'win32', windowsRoot: 'C:\\Windows', readScript: async () => 'fixed', spawnProcess: () => { - child = new EventEmitter(); child.stdout = new PassThrough(); child.kill = () => { kills++; return false; }; return child; + const picker = createNativeDirectoryPicker({ platform: 'win32', spawnProcess: () => { + child = new EventEmitter(); child.kill = () => { kills++; return false; }; child.unref = () => {}; return child; } }); const controller = new AbortController(); const pending = picker.choose(controller.signal); await Promise.resolve(); const rejected = assert.rejects(pending, /unavailable/); controller.abort(); await rejected; assert.equal(kills, 1); - child.emit('close', 1); await assert.rejects(picker.choose(new AbortController().signal), /unavailable/); - await picker.dispose(); }); From 17610c2697bb4c4adab236e390a84503c1db835e Mon Sep 17 00:00:00 2001 From: zhongxingxing Date: Fri, 27 Nov 2026 15:20:20 +0800 Subject: [PATCH 2/3] fix(webui): refresh rail projects after session creation The rail reads the visible project list once when it mounts. Creating a session in a new directory refreshed the session catalogue but not the project records, so the new project appeared only after a page reload. Refresh the project list on the creation completion path. A project read failure stays retryable and does not undo the created session. --- .../application/task-session-workflows.ts | 9 +++++++ .../test/unit/task-session-workflows.test.ts | 27 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/packages/webui/src/client/application/task-session-workflows.ts b/packages/webui/src/client/application/task-session-workflows.ts index 8544e229d..3c44570a5 100644 --- a/packages/webui/src/client/application/task-session-workflows.ts +++ b/packages/webui/src/client/application/task-session-workflows.ts @@ -45,12 +45,15 @@ export interface WebuiTaskSessionStorage { /** * The catalogue reads creation completion invalidates. Injected because * `client/application/` composes owners rather than calling transport itself. + * The project list is one of those reads: a session created in a new directory + * adds a project row the rail only sees after this read. */ export interface WebuiTaskSessionCatalogue { readonly canLoadFlat: boolean; readonly canLoadTree: boolean; readonly loadFlat: () => Promise; readonly loadTree: () => Promise; + readonly loadProjects?: () => Promise; } export interface WebuiTaskSessionDeps { @@ -292,6 +295,12 @@ export function createWebuiTaskSessionWorkflows( // the created session and does not trigger a second creation. catalogueError = formatWebuiError(error); } + // A session created in a new directory adds a project row. The session + // catalogue above does not carry project records, so the rail would keep + // its pre-creation grouping until a full page reload without this read. + // The projects owner keeps its own error state; a failure here must not + // turn a successful creation into a failed one. + try { await catalogue.loadProjects?.(); } catch { /* Projects owns the rail's retry/error surface. */ } return { kind: "created", diff --git a/packages/webui/test/unit/task-session-workflows.test.ts b/packages/webui/test/unit/task-session-workflows.test.ts index 1f775b29a..b2822b0c5 100644 --- a/packages/webui/test/unit/task-session-workflows.test.ts +++ b/packages/webui/test/unit/task-session-workflows.test.ts @@ -51,6 +51,7 @@ interface HarnessOptions { ) => Promise; readonly loadFlat?: () => Promise; readonly loadTree?: () => Promise; + readonly loadProjects?: () => Promise; readonly store?: WebuiSessionStore; readonly noProjectPersisted?: boolean; } @@ -80,6 +81,10 @@ function harness(options: HarnessOptions = {}) { catalogueCalls.push("tree"); await options.loadTree?.(); }, + loadProjects: async () => { + catalogueCalls.push("projects"); + await options.loadProjects?.(); + }, }, ...(options.createSession ? { @@ -271,6 +276,28 @@ describe("the creation use case", () => { expect(outcome).toMatchObject({ kind: "creation-failed" }); }); + it("refreshes the project list after a session is created", async () => { + const { workflows, catalogueCalls } = harness({ + createSession: async () => ({ sessionId: "s1" }), + }); + const outcome = await workflows.submit({ workspaceDir: "/new-project" }); + expect(outcome).toMatchObject({ kind: "created", sessionId: "s1" }); + expect(catalogueCalls).toEqual(["flat", "tree", "projects"]); + }); + + it("keeps the created session when the project refresh fails", async () => { + const { workflows } = harness({ + createSession: async () => ({ sessionId: "s1" }), + loadProjects: async () => { + throw new Error("projects down"); + }, + }); + await expect(workflows.submit({ workspaceDir: "/new-project" })).resolves.toMatchObject({ + kind: "created", + sessionId: "s1", + }); + }); + it("records a catalogue failure without undoing the created session", async () => { const { workflows, store } = harness({ createSession: async () => ({ sessionId: "s1" }), From cb53e4c9af9a65322aaae6bbe63cfc95a26c1fd4 Mon Sep 17 00:00:00 2001 From: zhongxingxing Date: Fri, 27 Nov 2026 15:58:18 +0800 Subject: [PATCH 3/3] feat(webui): hand off the native picker grant to a desktop host The native-directory grant still authorizes only the page that loads its one-time URL. A local desktop host that embeds the page cannot rely on the system browser opening that URL, so the launcher can now write the URL to an owner-only file when WEBUI_DESKTOP_HOST=1 and WEBUI_LAUNCH_URL_FILE is set. The file is written atomically after the listener starts, is never logged, and contains only the URL. A write failure is reported and the host falls back to the printed bare URL. Eligibility keeps the ordinary TTY requirement; WEBUI_DESKTOP_HOST opts a local embedded launch out of it. WEBUI_OPEN_BROWSER only gates the system browser, never the picker. SSH, full access, and non-loopback binds remain excluded, and the HTTP route's grant/cookie/browserKey checks are unchanged. --- packages/webui/docs/client/composer.md | 6 ++ release/public-source.json | 1 + release/webui-npm/README.md | 19 +++++ release/webui-npm/bin/desktop-launch.mjs | 60 ++++++++++++++ release/webui-npm/bin/mcode-webui.mjs | 23 ++++-- .../webui-npm/bin/native-directory-picker.mjs | 11 ++- test/source-sync.test.mjs | 79 +++++++++++++++++-- 7 files changed, 184 insertions(+), 15 deletions(-) create mode 100644 release/webui-npm/bin/desktop-launch.mjs diff --git a/packages/webui/docs/client/composer.md b/packages/webui/docs/client/composer.md index 698fa5cbc..0c1ca6aa1 100644 --- a/packages/webui/docs/client/composer.md +++ b/packages/webui/docs/client/composer.md @@ -52,6 +52,12 @@ same origin use that pairing. After a restart, the launcher tab renews it for the browser. A remote or unpaired browser can select a recent project or `不需要项目`. Requesting a new folder without a native chooser displays a notice. +A local desktop host that embeds the page can receive the same grant URL through +`WEBUI_LAUNCH_URL_FILE` when it starts `mcode-webui` with `WEBUI_DESKTOP_HOST=1`. +The file is owner-only and the grant remains one-time; the route's loopback, +Host, Origin, cookie, grant and browserKey checks are unchanged. `WEBUI_OPEN_BROWSER` +still controls only the system browser. + ## Where the pieces live - The surface is `client/features/composer/ui/WebuiComposer.tsx`, with the editor staging, menus, diff --git a/release/public-source.json b/release/public-source.json index 3df31cc80..28f0aa2de 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -5284,6 +5284,7 @@ "release/extraction.json", "release/public-source.json", "release/webui-npm/README.md", + "release/webui-npm/bin/desktop-launch.mjs", "release/webui-npm/bin/mcode-webui.mjs", "release/webui-npm/bin/native-directory-picker-win32.mjs", "release/webui-npm/bin/native-directory-picker-worker.cjs", diff --git a/release/webui-npm/README.md b/release/webui-npm/README.md index af46a555d..20362b192 100644 --- a/release/webui-npm/README.md +++ b/release/webui-npm/README.md @@ -63,4 +63,23 @@ listening. Set `WEBUI_OPEN_BROWSER=0` to keep it from doing that; with the variable unset it stays quiet when the command's output is not a terminal, so a script, a service supervisor or a CI job never takes over the desktop. +### Desktop host handoff + +A local desktop host that embeds the page cannot rely on the system browser to +open the one-time native-directory grant URL. It can start the launcher with +`WEBUI_DESKTOP_HOST=1` and `WEBUI_LAUNCH_URL_FILE=`; after the +server is listening, the launcher writes the page URL with its +`#nativeDirectoryGrant` fragment to that private file with owner-only access +(0600 on POSIX; the user-profile ACL on Windows) and does not log it. The host +opens that URL in its own embedded page, and the existing grant/cookie/browserKey +pairing completes. The file contains only the URL — no JSON, no extra fields. + +`WEBUI_DESKTOP_HOST=1` also lets the native-directory picker be created without +an interactive TTY; ordinary launches still require one. `WEBUI_OPEN_BROWSER=0` +still only means "do not open the system browser" and never disables the picker. +The HTTP route's loopback, Host, Origin, `Sec-Fetch-Site`, cookie, grant and +browserKey checks are unchanged. If the handoff file cannot be written, the +launcher logs the path and the host should fall back to the printed bare WebUI +URL; the native picker may then be unavailable. + The package requires a supported Node.js version shown in its `engines` field. diff --git a/release/webui-npm/bin/desktop-launch.mjs b/release/webui-npm/bin/desktop-launch.mjs new file mode 100644 index 000000000..d3a8c6de3 --- /dev/null +++ b/release/webui-npm/bin/desktop-launch.mjs @@ -0,0 +1,60 @@ +// Desktop-host handoff for the one-time native-directory grant. +// +// The grant rides in the page URL fragment. A host that embeds the page cannot +// rely on the system browser opening that URL, so it names a private file; the +// launcher writes the URL there with owner-only permissions and never logs it. +// The HTTP route still checks the grant, pairing cookie and browser key. + +import { randomUUID } from 'node:crypto'; +import { chmod, rename, rm, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { nativeDirectoryLaunchUrl } from './native-directory-picker.mjs'; + +const FILE_MODE = 0o600; + +export function browserOpenEnabled(setting, tty) { + const normalized = setting?.trim().toLowerCase(); + return normalized === undefined || normalized === '' + ? Boolean(tty) + : !['0', 'false', 'no', 'off', 'never'].includes(normalized); +} + +export async function writeLaunchUrlFile(file, url) { + if (typeof file !== 'string' || !path.isAbsolute(file)) { + throw new Error('WEBUI_LAUNCH_URL_FILE must be an absolute path'); + } + const temporary = path.join( + path.dirname(file), + '.' + path.basename(file) + '.' + randomUUID() + '.tmp', + ); + try { + await writeFile(temporary, url, { encoding: 'utf8', mode: FILE_MODE, flag: 'wx' }); + // POSIX mode is the contract; Windows keeps the file under the user + // profile instead of exposing a group/other-readable location. + await chmod(temporary, FILE_MODE); + try { + await rename(temporary, file); + } catch (error) { + // Windows rename does not replace an existing target. + if (error.code !== 'EEXIST' && error.code !== 'EPERM') throw error; + await rm(file, { force: true }); + await rename(temporary, file); + } + } finally { + await rm(temporary, { force: true }).catch(() => {}); + } +} + +export async function handoffDesktopLaunchUrl({ desktopHost, picker, file, browserUrl }) { + if (!desktopHost || !picker || !file) return { kind: 'skipped' }; + try { + await writeLaunchUrlFile(file, nativeDirectoryLaunchUrl(browserUrl, picker.grant)); + return { kind: 'written' }; + } catch (error) { + // A stale file would make the host open a launch URL with another process's + // grant. Remove it so the host's missing-file fallback is unambiguous. + if (path.isAbsolute(file)) await rm(file, { force: true }).catch(() => {}); + return { kind: 'failed', error }; + } +} \ No newline at end of file diff --git a/release/webui-npm/bin/mcode-webui.mjs b/release/webui-npm/bin/mcode-webui.mjs index bf11d728c..3f3be7cff 100644 --- a/release/webui-npm/bin/mcode-webui.mjs +++ b/release/webui-npm/bin/mcode-webui.mjs @@ -25,6 +25,8 @@ Start the MiniMax Code WebUI. Configuration is read from environment variables: WEBUI_HOST Bind address (default: 127.0.0.1) WEBUI_SERVER_PORT WebUI port (default: 2233) WEBUI_MINIAPP_PORT Mini App port (default: 49152) + WEBUI_DESKTOP_HOST Set to 1 when a local desktop host embeds the page + WEBUI_LAUNCH_URL_FILE Absolute path for the private launch URL handoff -h, --help Show help without starting the runtime -v, --version Show the installed version @@ -36,6 +38,8 @@ if (args.version) { process.exit(0); } +const { browserOpenEnabled, handoffDesktopLaunchUrl } = await import("./desktop-launch.mjs"); + // Help/version must not load native modules, access user data or open listeners. const { WebuiService, @@ -75,6 +79,8 @@ const dataDir = process.env.MINIMAX_DATA_DIR?.trim() || path.join(os.homedir(), // a request that did not arrive over loopback presents the per-start // credential, so the printed URL carries it. const bindHost = process.env.WEBUI_HOST?.trim() || "127.0.0.1"; +const desktopHost = process.env.WEBUI_DESKTOP_HOST?.trim() === "1"; +const launchUrlFile = process.env.WEBUI_LAUNCH_URL_FILE?.trim() || undefined; process.env.MAVIS_BUILTIN_AGENTS_V2_DIR ??= path.join(packageRoot, "assets/agents"); process.env.MAVIS_BUILTIN_AGENTS_DIR ??= path.join(packageRoot, "assets/agents"); @@ -261,7 +267,8 @@ await browser.initialize(); const { nativeDirectoryPickerEligible, createNativeDirectoryPicker, nativeDirectoryLaunchUrl } = await import("./native-directory-picker.mjs"); const nativeDirectoryPicker = nativeDirectoryPickerEligible({ - platform: process.platform, bindHost, fullAccess: args["full-access"], + platform: process.platform, tty: Boolean(process.stdout.isTTY), desktopHost, + bindHost, fullAccess: args["full-access"], }) ? createNativeDirectoryPicker() : undefined; const service = new WebuiService({ nativeDirectoryPicker, @@ -320,6 +327,15 @@ try { // runtime draws its own Mini App ports from the same range, and a listener // that waited would lose this one. await miniappProxies.prepare(); + const handoff = await handoffDesktopLaunchUrl({ + desktopHost, picker: nativeDirectoryPicker, file: launchUrlFile, browserUrl, + }); + if (handoff.kind === "failed") { + console.warn( + `[mcode-webui] could not write WEBUI_LAUNCH_URL_FILE (${launchUrlFile}); ` + + `the desktop host should use the printed WebUI URL instead: ${handoff.error.message}`, + ); + } console.log(`[mcode-webui] WebUI running at ${browserUrl}`); console.log( `[mcode-webui] Mini App port: ${miniappPort} — forward it, or a Mini App loads blank`, @@ -411,10 +427,7 @@ function lanAddresses() { * browser could not start would turn a convenience into an outage. */ function openBrowser(url, printableUrl = url) { - const setting = process.env.WEBUI_OPEN_BROWSER?.trim().toLowerCase(); - const disabled = setting === "0" || setting === "false" || setting === "no" || setting === "off" || setting === "never"; - const enabled = setting === undefined || setting === "" ? Boolean(process.stdout.isTTY) : !disabled; - if (!enabled) return; + if (!browserOpenEnabled(process.env.WEBUI_OPEN_BROWSER, process.stdout.isTTY)) return; // Each platform names its launcher differently, and Windows' `start` is a // shell builtin, so it needs a command interpreter in front of it. The empty // argument is `start`'s window-title slot: without it a quoted URL is read as diff --git a/release/webui-npm/bin/native-directory-picker.mjs b/release/webui-npm/bin/native-directory-picker.mjs index d613675a5..c0733f43d 100644 --- a/release/webui-npm/bin/native-directory-picker.mjs +++ b/release/webui-npm/bin/native-directory-picker.mjs @@ -7,12 +7,15 @@ import path from 'node:path'; import { createWin32DirectoryPicker } from './native-directory-picker-win32.mjs'; -export function nativeDirectoryPickerEligible({ platform, bindHost, fullAccess, env = process.env }) { - // No TTY requirement: the Win32 worker activates its own dialog, so a - // background desktop launch still has a usable native chooser. +export function nativeDirectoryPickerEligible({ platform, tty, desktopHost = false, bindHost, fullAccess, env = process.env }) { + // Ordinary launches stay interactive. A desktop host opts in explicitly + // because its embedded page cannot supply a TTY; the Win32 worker brings the + // dialog to the foreground itself. WEBUI_OPEN_BROWSER only controls the + // system browser and never this capability. const desktop = platform === 'win32' || platform === 'darwin' || (platform === 'linux' && Boolean(env.DISPLAY || env.WAYLAND_DISPLAY)); - return desktop && !fullAccess && !env.SSH_CONNECTION && !env.SSH_TTY + const attended = desktopHost === true || tty === true; + return desktop && attended && !fullAccess && !env.SSH_CONNECTION && !env.SSH_TTY && ['127.0.0.1', '::1'].includes(bindHost); } diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index b11e3b6f7..1ec01e242 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { copyFileSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync, rmSync, realpathSync, symlinkSync } from 'node:fs'; +import { copyFileSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync, rmSync, realpathSync, statSync, symlinkSync } from 'node:fs'; import path from 'node:path'; import { tmpdir } from 'node:os'; import { execFileSync, spawnSync } from 'node:child_process'; @@ -26,6 +26,7 @@ import { extensionIdFromPublicKey, parseExtensionIdList, readStoreExtensionIds } import { validateExceptionLedger, sourceFingerprint } from '../scripts/lib/webui-dependency-rules.mjs'; import { acceptanceRecordFiles, restoreAcceptanceRecords } from '../scripts/lib/acceptance-records.mjs'; import { createNativeDirectoryPicker, nativeDirectoryPickerEligible, nativeDirectoryLaunchUrl } from '../release/webui-npm/bin/native-directory-picker.mjs'; +import { browserOpenEnabled, handoffDesktopLaunchUrl } from '../release/webui-npm/bin/desktop-launch.mjs'; test('public WebUI CI runs only WebUI checks and cannot publish packages', () => { const activeWorkflows = readdirSync(new URL('../.github/workflows/', import.meta.url)) @@ -1589,15 +1590,17 @@ test('the desktop version the marketplace is filtered by is declared in exactly assert.deepEqual(offenders, [], 'the declared desktop version is written in the shared module only'); }); -test('native folder launcher grant is restricted to local desktop loopback', () => { - const local = { platform: 'win32', bindHost: '127.0.0.1', fullAccess: false, env: {} }; +test('native folder launcher grant is restricted to interactive or desktop-hosted local desktop loopback', () => { + const local = { platform: 'win32', tty: true, bindHost: '127.0.0.1', fullAccess: false, env: {} }; for (const change of [{}, { platform: 'darwin' }, { platform: 'linux', env: { DISPLAY: ':0' } }, - { platform: 'linux', env: { WAYLAND_DISPLAY: 'wayland-0' } }, { tty: false }]) { + { platform: 'linux', env: { WAYLAND_DISPLAY: 'wayland-0' } }, { desktopHost: true, tty: false }]) { assert.equal(nativeDirectoryPickerEligible({ ...local, ...change }), true); } for (const change of [{ platform: 'linux' }, { platform: 'freebsd' }, { env: { SSH_TTY: '/dev/pts/0' } }, { platform: 'linux', env: { DISPLAY: ':0', SSH_CONNECTION: 'forwarded session' } }, - { fullAccess: true }, { bindHost: '0.0.0.0' }, { bindHost: '192.168.1.1' }]) { + { fullAccess: true }, { bindHost: '0.0.0.0' }, { bindHost: '192.168.1.1' }, + { tty: false }, { desktopHost: true, tty: false, env: { SSH_TTY: '/dev/pts/0' } }, + { desktopHost: true, tty: false, fullAccess: true }, { desktopHost: true, tty: false, bindHost: '0.0.0.0' }]) { assert.equal(nativeDirectoryPickerEligible({ ...local, ...change }), false); } const plain = 'http://127.0.0.1:2233/?token=fixture'; @@ -1606,7 +1609,71 @@ test('native folder launcher grant is restricted to local desktop loopback', () assert.equal(new URLSearchParams(new URL(granted).hash.slice(1)).get('nativeDirectoryGrant'), 'synthetic-native-grant'); const launcher = readFileSync(new URL('../release/webui-npm/bin/mcode-webui.mjs', import.meta.url), 'utf8'); assert.match(launcher, /openBrowser\(nativeDirectoryPicker \? nativeDirectoryLaunchUrl\(browserUrl, nativeDirectoryPicker.grant\) : browserUrl, browserUrl\)/); - assert.doesNotMatch(launcher, /console\.(?:log|warn|error)\([^\n]*(?:nativeDirectoryPicker.grant|\$\{url\}|error.message)/); + assert.match(launcher, /handoffDesktopLaunchUrl/); + assert.match(launcher, /browserOpenEnabled\(process\.env\.WEBUI_OPEN_BROWSER, process\.stdout\.isTTY\)/); + assert.match(launcher, /WEBUI_DESKTOP_HOST/); + assert.match(launcher, /WEBUI_LAUNCH_URL_FILE/); + assert.doesNotMatch(launcher, /console\.(?:log|warn|error)\([^\n]*(?:nativeDirectoryPicker\.grant|\$\{url\})/); +}); + +test('desktop launch URL handoff is owner-only, atomic and conditional', async () => { + const directory = mkdtempSync(path.join(tmpdir(), 'mcode-launch-')); + try { + const file = path.join(directory, 'launch.url'); + const base = 'http://127.0.0.1:2233/?token=fixture'; + const grant = 'synthetic-native-grant'; + const expected = nativeDirectoryLaunchUrl(base, grant); + const written = await handoffDesktopLaunchUrl({ + desktopHost: true, picker: { grant }, file, browserUrl: base, + }); + assert.equal(written.kind, 'written'); + assert.equal(readFileSync(file, 'utf8'), expected); + if (process.platform !== 'win32') assert.equal(statSync(file).mode & 0o777, 0o600); + assert.deepEqual(readdirSync(directory), ['launch.url']); + + writeFileSync(file, 'old'); + assert.equal((await handoffDesktopLaunchUrl({ + desktopHost: true, picker: { grant }, file, browserUrl: base, + })).kind, 'written'); + assert.equal(readFileSync(file, 'utf8'), expected); + assert.deepEqual(readdirSync(directory), ['launch.url']); + + const skippedFile = path.join(directory, 'skipped.url'); + assert.equal((await handoffDesktopLaunchUrl({ + desktopHost: false, picker: { grant }, file: skippedFile, browserUrl: base, + })).kind, 'skipped'); + assert.equal((await handoffDesktopLaunchUrl({ + desktopHost: true, file: skippedFile, browserUrl: base, + })).kind, 'skipped'); + assert.equal((await handoffDesktopLaunchUrl({ + desktopHost: true, picker: { grant }, browserUrl: base, + })).kind, 'skipped'); + assert.equal(existsSync(skippedFile), false); + + assert.equal((await handoffDesktopLaunchUrl({ + desktopHost: true, picker: { grant }, file: 'relative.url', browserUrl: base, + })).kind, 'failed'); + const missing = path.join(directory, 'missing', 'launch.url'); + const failed = await handoffDesktopLaunchUrl({ + desktopHost: true, picker: { grant }, file: missing, browserUrl: base, + }); + assert.equal(failed.kind, 'failed'); + assert.ok(failed.error instanceof Error); + assert.equal(existsSync(missing), false); + assert.deepEqual(readdirSync(directory), ['launch.url']); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test('WEBUI_OPEN_BROWSER=0 never opens a browser', () => { + assert.equal(browserOpenEnabled('0', true), false); + assert.equal(browserOpenEnabled('0', false), false); + assert.equal(browserOpenEnabled('never', true), false); + assert.equal(browserOpenEnabled('1', false), true); + assert.equal(browserOpenEnabled(undefined, true), true); + assert.equal(browserOpenEnabled(undefined, false), false); + assert.equal(browserOpenEnabled('', true), true); }); test('native folder on macOS and Linux distinguishes chosen paths, user dismissal and failed helpers', async () => {