From 513bc68d942f7f21d4b644dcf0a9740978bcf246 Mon Sep 17 00:00:00 2001 From: Jiaxiaoyuan Date: Fri, 27 Nov 2026 16:10:32 +0800 Subject: [PATCH 1/4] test(webui): require equivalent project selection from each Windows entry --- .github/workflows/webui-ci.yml | 3 + scripts/lib/webui-native-project-journey.mjs | 23 +++-- scripts/lib/webui-native-project-launch.mjs | 98 +++++++++++++++++--- scripts/lib/webui-windows-folder-dialog.ps1 | 98 +++++++++++++------- scripts/verify-webui-package.mjs | 41 +++++--- test/source-sync.test.mjs | 9 +- 6 files changed, 203 insertions(+), 69 deletions(-) diff --git a/.github/workflows/webui-ci.yml b/.github/workflows/webui-ci.yml index 22c290c1..34bbfdcc 100644 --- a/.github/workflows/webui-ci.yml +++ b/.github/workflows/webui-ci.yml @@ -53,6 +53,9 @@ jobs: with: node-version: "24" cache: pnpm + - name: Verify the public source inventory on the clean checkout + if: runner.os == 'Linux' && matrix.lane.name == 'checks' + run: pnpm check:source - run: pnpm install --frozen-lockfile - name: Check WebUI types if: matrix.lane.name == 'checks' diff --git a/scripts/lib/webui-native-project-journey.mjs b/scripts/lib/webui-native-project-journey.mjs index ac5c6c8c..de6196cd 100644 --- a/scripts/lib/webui-native-project-journey.mjs +++ b/scripts/lib/webui-native-project-journey.mjs @@ -84,16 +84,20 @@ async function createAndReadSession(page, directory, timeoutMs) { await editor.fill('/new', { timeout: timeoutMs }); await page.getByRole('button', { name: '发送', exact: true }).click({ timeout: timeoutMs }); await expect(page.locator('[data-webui-command-output]')).toHaveText('New session created.', { timeout: timeoutMs }); - // Reload to discard the home selection and require a fresh read from the host. - await page.reload({ waitUntil: 'domcontentloaded', timeout: timeoutMs }); - await expect(project).toBeVisible({ timeout: timeoutMs }); - if (await project.getAttribute('aria-expanded') !== 'true') await project.click({ timeout: timeoutMs }); - // The rail groups sessions by the workspaceDir on the read-back session record. const session = project.locator('xpath=ancestor::li[1]').locator('[data-webui-session-link]'); - await expect(session).toHaveCount(1, { timeout: timeoutMs }); - await expect(session).toBeVisible({ timeout: timeoutMs }); + async function expectSessionInRail(stage) { + await expect(project, `The chosen project must appear in the rail ${stage}.`).toBeVisible({ timeout: timeoutMs }); + if (await project.getAttribute('aria-expanded') !== 'true') await project.click({ timeout: timeoutMs }); + await expect(session, `The chosen project must contain its new session ${stage}.`).toHaveCount(1, { timeout: timeoutMs }); + await expect(session).toBeVisible({ timeout: timeoutMs }); + } + await expectSessionInRail('before reload'); const sessionId = await session.getAttribute('data-webui-session-link'); - assert.ok(sessionId, 'The persisted project row did not identify its session.'); + assert.ok(sessionId, 'The live rail did not identify its new session.'); + // Reload only after observing the live update, then verify the same session survived. + await page.reload({ waitUntil: 'domcontentloaded', timeout: timeoutMs }); + await expectSessionInRail('after reload'); + await expect(session).toHaveAttribute('data-webui-session-link', sessionId, { timeout: timeoutMs }); return sessionId; } @@ -102,7 +106,7 @@ async function createAndReadSession(page, directory, timeoutMs) { * driveDialog must operate the real OS chooser and release its resources on abort. * initialProject, when provided, is the expected text of the initial home project button. */ -export async function verifyNativeProjectJourney({ page, directory, driveDialog, initialProject, timeoutMs = 45000 }) { +export async function verifyNativeProjectJourney({ page, directory, driveDialog, beforeChoose, initialProject, timeoutMs = 45000 }) { try { assert.ok(path.isAbsolute(directory), 'Expected an absolute test folder on the executing platform.'); const row = page.locator(projectButton); @@ -112,6 +116,7 @@ export async function verifyNativeProjectJourney({ page, directory, driveDialog, const label = directory.split(/[\\/]/u).filter(Boolean).at(-1) || directory; assert.notEqual(before, label, 'Choose a folder whose label differs from the initial workspace.'); for (const action of ['select', 'cancel']) { + await beforeChoose?.(); await chooseFromHome({ page, directory, action, driveDialog, timeoutMs }); await expect(row).toHaveText(label, { timeout: timeoutMs }); } diff --git a/scripts/lib/webui-native-project-launch.mjs b/scripts/lib/webui-native-project-launch.mjs index 74cf1fc4..8c203e28 100644 --- a/scripts/lib/webui-native-project-launch.mjs +++ b/scripts/lib/webui-native-project-launch.mjs @@ -1,7 +1,9 @@ -import { fork, spawnSync } from 'node:child_process'; +import { fork, spawn, spawnSync } from 'node:child_process'; import { existsSync, mkdtempSync } from 'node:fs'; +import { readFile, rm } from 'node:fs/promises'; import { createRequire } from 'node:module'; import path from 'node:path'; +import { createInterface } from 'node:readline'; import { setTimeout as delay } from 'node:timers/promises'; function powershell(script, env = {}) { @@ -85,20 +87,27 @@ if ((Get-ItemPropertyValue -LiteralPath $userKey -Name UserDataDir) -cne $env:WE } } -function startInstalledCommand(installed, work, port, miniappPort) { +function launcherEnvironment(installed, work, port, miniappPort) { const modules = path.resolve(installed, '..', '..'); const shimDirectory = [path.join(modules, '.bin'), path.dirname(modules)] .find((dir) => existsSync(path.join(dir, 'mcode-webui.cmd'))); if (!shimDirectory) throw new Error('npm did not install a Windows mcode-webui command shim.'); - // Windows keeps the driver's loaded native DLL mapped until this verifier exits. - // Use the checkout's test driver so the temporary npm installation can be removed. - const { spawn } = createRequire(new URL('../../packages/webui/package.json', import.meta.url))('node-pty'); const env = { ...process.env, MINIMAX_DATA_DIR: path.join(work, 'native-data'), WEBUI_HOST: '127.0.0.1', WEBUI_SERVER_PORT: String(port), WEBUI_MINIAPP_PORT: String(miniappPort), WEBUI_OPEN_BROWSER: '', }; + delete env.WEBUI_DESKTOP_HOST; + delete env.WEBUI_LAUNCH_URL_FILE; const pathKey = Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'Path'; env[pathKey] = shimDirectory + path.delimiter + (env[pathKey] ?? ''); + return env; +} + +function startInstalledCommand(installed, work, port, miniappPort) { + // Windows keeps the driver's loaded native DLL mapped until this verifier exits. + // Use the checkout's test driver so the temporary npm installation can be removed. + const { spawn } = createRequire(new URL('../../packages/webui/package.json', import.meta.url))('node-pty'); + const env = launcherEnvironment(installed, work, port, miniappPort); const term = spawn(path.join(process.env.SystemRoot, 'System32', 'cmd.exe'), ['/d', '/c', 'mcode-webui.cmd'], { cwd: work, env, cols: 120, rows: 30, }); @@ -221,20 +230,76 @@ function startTerminalDriver(installed, work, port, miniappPort) { }; } -export async function launchNativeProjectBrowser({ installed, work, port, miniappPort }) { +// A desktop host starts the installed command without a console and consumes its private file. +// A person starting the same command in the background manually opens the address it prints. +function startBackgroundCommand(installed, work, port, miniappPort, entry) { + const env = launcherEnvironment(installed, work, port, miniappPort); + env.MINIMAX_DATA_DIR = mkdtempSync(path.join(work, 'background-data-')); + const handoffFile = path.join(env.MINIMAX_DATA_DIR, 'launch-url'); + if (entry === 'desktop-handoff') { + env.WEBUI_DESKTOP_HOST = '1'; + env.WEBUI_LAUNCH_URL_FILE = handoffFile; + env.WEBUI_OPEN_BROWSER = '0'; + } + const child = spawn(path.join(process.env.SystemRoot, 'System32', 'cmd.exe'), ['/d', '/c', 'mcode-webui.cmd'], { + cwd: work, env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, + }); + const printed = Promise.withResolvers(); + const exited = new Promise((resolve) => child.once('close', resolve)); + child.once('error', () => printed.resolve(undefined)); + child.once('exit', () => printed.resolve(undefined)); + const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); + lines.on('line', (line) => { + const match = /^\[mcode-webui\] WebUI running at (\S+)$/u.exec(line); + if (match) printed.resolve(match[1]); + }); + return { + pid: child.pid, + async pageUrl() { + const address = await Promise.race([printed.promise, delay(60_000, undefined, { ref: false })]); + if (!address || !URL.canParse(address)) throw new Error('The background launcher did not print a valid access URL.'); + const url = new URL(address); + if (url.origin !== `http://127.0.0.1:${port}` || url.hash) throw new Error('Unexpected origin or private fragment in the printed access URL.'); + if (entry === 'manual') return address; + const handoff = await readFile(handoffFile, 'utf8'); + if (!URL.canParse(handoff)) throw new Error('The desktop host handoff did not contain a valid URL.'); + const privateUrl = new URL(handoff); + if (privateUrl.origin !== url.origin) throw new Error('The desktop host handoff does not identify its installed launcher.'); + return handoff; + }, + async close() { + try { + if (child.pid && child.exitCode === null && child.signalCode === null) { + // The npm shim owns the Node launcher and any modal worker beneath it. + spawnSync(path.join(process.env.SystemRoot, 'System32', 'taskkill.exe'), ['/T', '/F', '/PID', String(child.pid)], { + stdio: 'ignore', windowsHide: true, timeout: 5000, + }); + } + const closed = await Promise.race([exited.then(() => true), delay(5000, false, { ref: false })]); + if (!closed) throw new Error('The background launcher process tree did not close.'); + } finally { + lines.close(); + await rm(handoffFile, { force: true }); + } + }, + }; +} + +export async function launchNativeProjectBrowser({ installed, work, port, miniappPort, entry = 'terminal' }) { const hosted = process.env.GITHUB_ACTIONS === 'true' && process.env.RUNNER_ENVIRONMENT === 'github-hosted'; if (process.platform !== 'win32' || (!hosted && process.env.WEBUI_TEST_DISPOSABLE_DESKTOP !== '1')) { throw new Error('Run the Windows project-selection gate on a hosted Windows runner or set WEBUI_TEST_DISPOSABLE_DESKTOP=1 in a disposable Windows desktop account.'); } + if (!['terminal', 'desktop-handoff', 'manual'].includes(entry)) throw new Error('Unknown Windows project-selection entry.'); const { chromium } = await import('@playwright/test'); const { executable, policy, versionUrl } = defaultHttpBrowser(); const profile = mkdtempSync(path.join(work, 'native-browser-')); const restore = redirectRunnerBrowser(policy, profile); let context; - let terminal; + let launcher; async function close() { try { - await terminal?.close(); + await launcher?.close(); } finally { try { await context?.close(); } finally { restore(); } @@ -248,13 +313,24 @@ export async function launchNativeProjectBrowser({ installed, work, port, miniap if (path.relative(profile, path.dirname(actualProfile)) !== '') throw new Error('The browser did not open in the test profile.'); await version.close(); console.log(`Verified the isolated profile of the default HTTP browser (${path.basename(executable)}).`); - terminal = startTerminalDriver(installed, work, port, miniappPort); - const launcherPid = await terminal.launcherPid(); + if (entry !== 'terminal') { + launcher = startBackgroundCommand(installed, work, port, miniappPort, entry); + const address = await launcher.pageUrl(); + const page = await context.newPage(); + // A Playwright navigation error can contain the credential and handoff fragment. + try { await page.goto(address, { waitUntil: 'domcontentloaded', timeout: 30_000 }); } + catch { throw new Error(`Could not open the ${entry} page supplied by the background launcher.`); } + await page.bringToFront(); + console.log(`Opened the installed background launcher through the ${entry} entry in a fresh browser profile.`); + return { page, launcherPid: launcher.pid, close }; + } + launcher = startTerminalDriver(installed, work, port, miniappPort); + const launcherPid = await launcher.launcherPid(); console.log('Started the installed mcode-webui command in a Windows terminal.'); const origin = `http://127.0.0.1:${port}`; const deadline = Date.now() + 60_000; do { - terminal.assertRunning(); + launcher.assertRunning(); const page = context.pages().find((tab) => tab.url().startsWith(origin + '/')); if (page) { console.log('Observed the WebUI tab automatically opened by the launcher.'); diff --git a/scripts/lib/webui-windows-folder-dialog.ps1 b/scripts/lib/webui-windows-folder-dialog.ps1 index ae6de72b..56522a65 100644 --- a/scripts/lib/webui-windows-folder-dialog.ps1 +++ b/scripts/lib/webui-windows-folder-dialog.ps1 @@ -3,8 +3,8 @@ #requires -Version 5.1 param( [Parameter(Mandatory)][int]$LauncherPid, - [Parameter(Mandatory)][string]$PickerWorker, - [Parameter(Mandatory)][ValidateSet('select', 'cancel')][string]$Action, + [Parameter(Mandatory)][string]$LauncherEntry, + [Parameter(Mandatory)][ValidateSet('baseline', 'select', 'cancel')][string]$Action, [string]$Directory ) $ErrorActionPreference = 'Stop' @@ -42,10 +42,11 @@ public static class WebuiTestDesktop { } delegate bool EnumProc(IntPtr handle, IntPtr unused); [DllImport("user32.dll")] static extern bool GetGUIThreadInfo(uint thread, ref GuiThread info); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid); [DllImport("user32.dll")] static extern bool IsChild(IntPtr parent, IntPtr child); [DllImport("user32.dll")] static extern IntPtr GetParent(IntPtr child); - [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hwnd); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd); [DllImport("user32.dll")] static extern bool IsWindowEnabled(IntPtr hwnd); [DllImport("user32.dll")] static extern bool EnumChildWindows(IntPtr parent, EnumProc callback, IntPtr unused); [DllImport("user32.dll")] static extern int GetDlgCtrlID(IntPtr hwnd); @@ -65,6 +66,15 @@ public static class WebuiTestDesktop { uint pid; return hwnd != IntPtr.Zero && GetWindowThreadProcessId(hwnd, out pid) != 0 && pid == expected && Class(hwnd) == "#32770"; } + public static bool HasShellControls(IntPtr dialog) { + bool found = false; + EnumChildWindows(dialog, delegate(IntPtr child, IntPtr unused) { + var name = Class(child); + found = name == "SHELLDLL_DefView" || name == "Breadcrumb Parent"; + return !found; + }, IntPtr.Zero); + return found; + } static IntPtr Focus(IntPtr dialog) { uint pid; var info = new GuiThread { Size = Marshal.SizeOf(typeof(GuiThread)) }; @@ -166,7 +176,8 @@ $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 $PickerWorker).DirectoryName 'mcode-webui.mjs' +if (-not [IO.Path]::IsPathRooted($LauncherEntry)) { throw 'The installed launcher entry must be an absolute path.' } +$launcherPath = (Get-Item -LiteralPath $LauncherEntry -ErrorAction Stop).FullName # 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,45 +197,48 @@ $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 -# 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'" +# A common dialog can be owned by the launcher or by a helper at any depth. +# Resolve ancestry only for visible Win32 dialogs on this test desktop. +function Test-LauncherDescendant([int]$processId) { + $visited = @{} + while ($processId -gt 0 -and -not $visited.ContainsKey($processId)) { + if ($processId -eq $launcher.Id) { return $true } + $visited[$processId] = $true + $process = Get-CimInstance Win32_Process -Filter "ProcessId=$processId" -Property ParentProcessId + if (-not $process) { return $false } + $processId = $process.ParentProcessId + } + return $false +} $clock = [Diagnostics.Stopwatch]::StartNew() $picker = $null $dialog = $null $root = [System.Windows.Automation.AutomationElement]::RootElement $children = [System.Windows.Automation.TreeScope]::Children +$dialogClass = [System.Windows.Automation.PropertyCondition]::new( + [System.Windows.Automation.AutomationElement]::ClassNameProperty, '#32770') while ($clock.Elapsed.TotalSeconds -lt 20) { if ($launcher.HasExited) { throw "The WebUI launcher PID $LauncherPid exited before showing the chooser." } - if (-not $picker) { - $matchesWorker = @(Get-CimInstance Win32_Process -Filter $filter -Property $processFields | - Where-Object { $_.CommandLine -cmatch $expectedArgument }) - 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( - [System.Windows.Automation.AutomationElement]::ProcessIdProperty, [int]$picker.Id) - } - } + $visible = @($root.FindAll($children, $dialogClass) | Where-Object { + $current = $_.Current + -not $current.IsOffscreen -and (Test-LauncherDescendant $current.ProcessId) -and + [WebuiTestDesktop]::OwnsDialog([IntPtr]$current.NativeWindowHandle, $current.ProcessId) -and + ($Action -eq 'baseline' -or [WebuiTestDesktop]::HasShellControls([IntPtr]$current.NativeWindowHandle)) + }) + if ($Action -eq 'baseline') { + if ($visible.Count -gt 0) { throw 'The installed launcher already owns a visible dialog before the project selection.' } + return } - if ($picker) { - 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." } - if ($visible.Count -eq 1) { - $dialog = $visible[0] - break - } + if ($visible.Count -gt 1) { throw 'The installed launcher owns multiple visible Shell dialogs; the chooser is ambiguous.' } + if ($visible.Count -eq 1) { + $dialog = $visible[0] + $picker = Get-Process -Id $dialog.Current.ProcessId + [void]$picker.Handle + break } Start-Sleep -Milliseconds 120 } -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." } +if (-not $dialog) { throw "The installed launcher PID $($launcher.Id) did not display a visible Common Item 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 { @@ -249,8 +263,18 @@ function Save-DialogImage { [WebuiTestDesktop]::Capture($window, $file) } catch { Write-Warning 'Could not capture the native dialog window.' } } -$stage = 'wait for visible chooser controls' +$stage = 'wait for the chooser to take the foreground' try { + # A visible Shell dialog can still be behind the browser. Observe its exact HWND + # before the driver sends any input, which could itself activate the dialog. + $activation = [Diagnostics.Stopwatch]::StartNew() + while ([WebuiTestDesktop]::GetForegroundWindow() -ne $window) { + if ($picker.HasExited) { throw 'The chooser exited before taking the foreground.' } + if ($activation.ElapsedMilliseconds -ge 3000) { throw 'The visible chooser did not become the foreground window within 3 seconds.' } + Start-Sleep -Milliseconds 50 + } + Write-Output "Windows folder dialog PID $($picker.Id): observed foreground HWND $window before $Action." + $stage = 'wait for visible chooser controls' # Shell creates the top-level HWND before it finishes populating its controls. $ready = [Diagnostics.Stopwatch]::StartNew() while (-not [WebuiTestDesktop]::Controls($window) -and $ready.ElapsedMilliseconds -lt 3000) { @@ -286,8 +310,12 @@ try { if ($ready.ElapsedMilliseconds -gt 4000) { throw 'The common dialog did not expose its enabled button.' } Start-Sleep -Milliseconds 100 } - $stage = 'wait for the native chooser process to exit' - if (-not $picker.WaitForExit(5000)) { throw 'The chooser remained open after clicking the dialog button.' } + $stage = 'wait for the native chooser to close' + $ready.Restart() + while ([WebuiTestDesktop]::OwnsDialog($window, $picker.Id) -and [WebuiTestDesktop]::IsWindowVisible($window)) { + if ($ready.ElapsedMilliseconds -ge 5000) { throw 'The chooser remained open after clicking the dialog button.' } + Start-Sleep -Milliseconds 100 + } } catch { $controls = '(dialog closed)' if ([WebuiTestDesktop]::OwnsDialog($window, $picker.Id)) { diff --git a/scripts/verify-webui-package.mjs b/scripts/verify-webui-package.mjs index 4ecdde71..bec0e99f 100644 --- a/scripts/verify-webui-package.mjs +++ b/scripts/verify-webui-package.mjs @@ -237,31 +237,50 @@ async function availablePort() { } async function verifyWindowsProjectSelection(installed) { + // Each entry gets a fresh browser, launcher and project. A broken entry must + // neither borrow another entry's pairing nor prevent the others from running. + const failures = []; + for (const entry of ["terminal", "manual", "desktop-handoff"]) { + console.log(`Checking Windows project selection from ${entry}.`); + try { + await verifyWindowsProjectEntry(installed, entry); + } catch (error) { + failures.push(`${entry}: ${error.message}`); + console.error(`Windows ${entry} project selection failed: ${error.message}`); + } + } + if (failures.length) throw new Error(`Windows project selection failed:\n${failures.join("\n")}`); +} + +async function verifyWindowsProjectEntry(installed, entry) { const { launchNativeProjectBrowser } = await import("./lib/webui-native-project-launch.mjs"); const { verifyNativeProjectJourney } = await import("./lib/webui-native-project-journey.mjs"); const directory = mkdtempSync(path.join(work, "Project 示例 ")); - const browser = await launchNativeProjectBrowser({ installed, work, port: await availablePort(), miniappPort: await availablePort() }); + const browser = await launchNativeProjectBrowser({ installed, work, port: await availablePort(), miniappPort: await availablePort(), entry }); + const evidenceDir = process.env.WEBUI_BROWSER_OUTPUT_DIR && path.join(process.env.WEBUI_BROWSER_OUTPUT_DIR, entry); const driver = path.join(root, "scripts/lib/webui-windows-folder-dialog.ps1"); - const pickerWorker = path.join(installed, "bin/native-directory-picker-worker.cjs"); + const launcherEntry = path.join(installed, "bin/mcode-webui.mjs"); const driveDialog = async ({ action, signal }) => { const args = ["-NoProfile", "-NonInteractive", "-STA", "-ExecutionPolicy", "Bypass", "-File", driver, - "-LauncherPid", String(browser.launcherPid), "-PickerWorker", pickerWorker, "-Action", action]; + "-LauncherPid", String(browser.launcherPid), "-LauncherEntry", launcherEntry, "-Action", action]; if (action === "select") args.push("-Directory", directory); - const { stdout } = await promisify(execFile)("powershell.exe", args, { signal, timeout: 45_000, windowsHide: true }); + const { stdout } = await promisify(execFile)("powershell.exe", args, { + signal, timeout: 45_000, windowsHide: true, + env: { ...process.env, WEBUI_BROWSER_OUTPUT_DIR: evidenceDir ?? "" }, + }); console.log(stdout.trim()); }; await withCleanup(async () => { - console.log("Opened the installed launcher's home page in the Windows default browser."); try { - const result = await verifyNativeProjectJourney({ page: browser.page, directory, driveDialog }); - console.log(`Windows home project selection passed: native select and cancel, reloaded session ${result.sessionId} under ${result.directory}`); - if (process.env.WEBUI_BROWSER_OUTPUT_DIR) { - await browser.page.screenshot({ path: path.join(process.env.WEBUI_BROWSER_OUTPUT_DIR, "windows-project-session.png"), timeout: 5000 }) + const result = await verifyNativeProjectJourney({ + page: browser.page, directory, driveDialog, beforeChoose: () => driveDialog({ action: "baseline" }), + }); + console.log(`Windows ${entry} passed: foreground select and cancel; session ${result.sessionId} under ${result.directory} visible before and after reload.`); + if (evidenceDir) { + await browser.page.screenshot({ path: path.join(evidenceDir, "windows-project-session.png"), timeout: 5000 }) .catch(() => console.warn("Could not capture the verified project and session.")); } } catch (error) { - console.error(`Windows home project selection failed: ${error.message}`); - const evidenceDir = process.env.WEBUI_BROWSER_OUTPUT_DIR; if (evidenceDir) { // Playwright creates the parent directory when saving a screenshot. await browser.page.screenshot({ path: path.join(evidenceDir, "windows-project-picker.png"), timeout: 5000 }) diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index 1ec01e24..e397e897 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -28,7 +28,7 @@ import { acceptanceRecordFiles, restoreAcceptanceRecords } from '../scripts/lib/ 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', () => { +test('public WebUI CI verifies the source inventory and WebUI checks and cannot publish packages', () => { const activeWorkflows = readdirSync(new URL('../.github/workflows/', import.meta.url)) .filter(name => /\.ya?ml$/.test(name)).sort(); // The manual baseline refresh is a second active workflow: it records the @@ -83,7 +83,7 @@ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => assert.doesNotMatch(browserConfig, /process\.env\.WEBUI_BROWSER_OUTPUT_DIR/); // The steps that prepare the machine are not WebUI checks: they install the // dependencies, the browser and the media binary the Design paths run for - // real. Every other step has to be a WebUI command from this repository. + // real. The source inventory is shared with the repository release gates. const ffmpeg = job.steps.find(step => step.name === 'Install FFmpeg'); assert.ok(ffmpeg, 'the native Design media paths run FFmpeg for real'); assert.match(ffmpeg.run, /ffmpeg/); @@ -99,12 +99,13 @@ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => for (const command of commands) { if (provisioning.includes(command)) continue; const script = command === browserCommand ? 'pnpm test:webui-browser' : command; - assert.match(script, /^pnpm (?:typecheck|check|build|install|test):webui(?:-[a-z]+)?$/); + if (script !== 'pnpm check:source') assert.match(script, /^pnpm (?:typecheck|check|build|install|test):webui(?:-[a-z]+)?$/); assert.ok(Object.hasOwn(manifest.scripts, script.slice('pnpm '.length)), command); } const nativeTests = "matrix.lane.name == 'units' || matrix.lane.shard"; const checks = "matrix.lane.name == 'checks'"; const laneConditions = { + 'pnpm check:source': "runner.os == 'Linux' && matrix.lane.name == 'checks'", 'pnpm typecheck:webui': checks, 'pnpm check:webui-dependency': checks, 'pnpm check:webui-presentation': checks, @@ -125,6 +126,8 @@ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => assert.equal(step?.if, condition, `${command} must run in its assigned jobs`); assert.equal(step['continue-on-error'], undefined, `${command} must fail the job on a regression`); } + assert.ok(commands.indexOf('pnpm check:source') < commands.indexOf('pnpm install --frozen-lockfile'), + 'Verify the public inventory before package installation can create local files'); for (const prerequisite of ['pnpm build:webui', 'pnpm install:webui-browsers', ffmpeg.run, 'pnpm exec playwright install-deps chromium']) { for (const command of ['pnpm test:webui', browserCommand]) { assert.ok(commands.indexOf(prerequisite) < commands.indexOf(command), `Run ${prerequisite} before ${command}`); From c2c22b404ef26a20786c1a010a34673489e81c57 Mon Sep 17 00:00:00 2001 From: Jiaxiaoyuan Date: Fri, 27 Nov 2026 16:15:02 +0800 Subject: [PATCH 2/4] test(webui): verify foreground ownership on both sides of the picker click --- scripts/lib/webui-native-project-journey.mjs | 7 +++--- scripts/lib/webui-native-project-launch.mjs | 19 ++++++++++++++-- scripts/lib/webui-windows-folder-dialog.ps1 | 23 +++++++++++++++++--- scripts/verify-webui-package.mjs | 2 +- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/scripts/lib/webui-native-project-journey.mjs b/scripts/lib/webui-native-project-journey.mjs index de6196cd..b08661ae 100644 --- a/scripts/lib/webui-native-project-journey.mjs +++ b/scripts/lib/webui-native-project-journey.mjs @@ -12,7 +12,8 @@ function publicMessage(error) { .replace(/((?:token|nativeDirectoryGrant|browserKey)=)[^\s&"']+/giu, '$1[redacted]'); } -async function chooseFromHome({ page, directory, action, driveDialog, timeoutMs }) { +async function chooseFromHome({ page, directory, action, driveDialog, beforeChoose, timeoutMs }) { + await page.bringToFront(); await page.locator(projectButton).click({ timeout: timeoutMs }); const origin = new URL(page.url()).origin; const controller = new AbortController(); @@ -40,6 +41,7 @@ async function chooseFromHome({ page, directory, action, driveDialog, timeoutMs .filter({ hasText: /系统(?:文件夹选择器|目录选择)/u }).last(); const deadline = Date.now() + timeoutMs; try { + await beforeChoose?.(); await page.getByRole('option', { name: '选择新项目', exact: true }).click({ timeout: timeoutMs }); while (Date.now() < deadline) { if (duplicate) throw new Error('One project selection sent multiple chooser requests.'); @@ -116,8 +118,7 @@ export async function verifyNativeProjectJourney({ page, directory, driveDialog, const label = directory.split(/[\\/]/u).filter(Boolean).at(-1) || directory; assert.notEqual(before, label, 'Choose a folder whose label differs from the initial workspace.'); for (const action of ['select', 'cancel']) { - await beforeChoose?.(); - await chooseFromHome({ page, directory, action, driveDialog, timeoutMs }); + await chooseFromHome({ page, directory, action, driveDialog, beforeChoose, timeoutMs }); await expect(row).toHaveText(label, { timeout: timeoutMs }); } const sessionId = await createAndReadSession(page, directory, timeoutMs); diff --git a/scripts/lib/webui-native-project-launch.mjs b/scripts/lib/webui-native-project-launch.mjs index 8c203e28..0b2bd961 100644 --- a/scripts/lib/webui-native-project-launch.mjs +++ b/scripts/lib/webui-native-project-launch.mjs @@ -285,6 +285,20 @@ function startBackgroundCommand(installed, work, port, miniappPort, entry) { }; } +async function readBrowserPid(context) { + const session = await context.browser().newBrowserCDPSession(); + try { + const { processInfo } = await session.send('SystemInfo.getProcessInfo'); + const browsers = processInfo.filter(({ type }) => type === 'browser'); + if (browsers.length !== 1 || !Number.isSafeInteger(browsers[0].id) || browsers[0].id <= 0) { + throw new Error('The isolated browser did not report one browser process PID.'); + } + return browsers[0].id; + } finally { + await session.detach(); + } +} + export async function launchNativeProjectBrowser({ installed, work, port, miniappPort, entry = 'terminal' }) { const hosted = process.env.GITHUB_ACTIONS === 'true' && process.env.RUNNER_ENVIRONMENT === 'github-hosted'; if (process.platform !== 'win32' || (!hosted && process.env.WEBUI_TEST_DISPOSABLE_DESKTOP !== '1')) { @@ -312,6 +326,7 @@ export async function launchNativeProjectBrowser({ installed, work, port, miniap const actualProfile = await version.locator('#profile_path').innerText({ timeout: 10_000 }); if (path.relative(profile, path.dirname(actualProfile)) !== '') throw new Error('The browser did not open in the test profile.'); await version.close(); + const browserPid = await readBrowserPid(context); console.log(`Verified the isolated profile of the default HTTP browser (${path.basename(executable)}).`); if (entry !== 'terminal') { launcher = startBackgroundCommand(installed, work, port, miniappPort, entry); @@ -322,7 +337,7 @@ export async function launchNativeProjectBrowser({ installed, work, port, miniap catch { throw new Error(`Could not open the ${entry} page supplied by the background launcher.`); } await page.bringToFront(); console.log(`Opened the installed background launcher through the ${entry} entry in a fresh browser profile.`); - return { page, launcherPid: launcher.pid, close }; + return { page, launcherPid: launcher.pid, browserPid, close }; } launcher = startTerminalDriver(installed, work, port, miniappPort); const launcherPid = await launcher.launcherPid(); @@ -334,7 +349,7 @@ export async function launchNativeProjectBrowser({ installed, work, port, miniap const page = context.pages().find((tab) => tab.url().startsWith(origin + '/')); if (page) { console.log('Observed the WebUI tab automatically opened by the launcher.'); - return { page, launcherPid, close }; + return { page, launcherPid, browserPid, close }; } await delay(100); } while (Date.now() < deadline); diff --git a/scripts/lib/webui-windows-folder-dialog.ps1 b/scripts/lib/webui-windows-folder-dialog.ps1 index 56522a65..97f28abc 100644 --- a/scripts/lib/webui-windows-folder-dialog.ps1 +++ b/scripts/lib/webui-windows-folder-dialog.ps1 @@ -5,9 +5,13 @@ param( [Parameter(Mandatory)][int]$LauncherPid, [Parameter(Mandatory)][string]$LauncherEntry, [Parameter(Mandatory)][ValidateSet('baseline', 'select', 'cancel')][string]$Action, + [int]$BrowserPid, [string]$Directory ) $ErrorActionPreference = 'Stop' +if ($Action -eq 'baseline' -and $BrowserPid -le 0) { + throw 'Browser foreground precondition requires the PID of the tested browser.' +} if ($Action -eq 'select' -and ($Directory -notmatch '^(?:[A-Za-z]:[\\/]|\\\\)' -or -not [IO.Directory]::Exists($Directory))) { throw 'The selected test directory must be an existing absolute path.' } @@ -62,9 +66,12 @@ public static class WebuiTestDesktop { GetClassName(hwnd, name, name.Capacity); return name.ToString(); } - public static bool OwnsDialog(IntPtr hwnd, uint expected) { + public static uint WindowProcessId(IntPtr hwnd) { uint pid; - return hwnd != IntPtr.Zero && GetWindowThreadProcessId(hwnd, out pid) != 0 && pid == expected && Class(hwnd) == "#32770"; + return hwnd != IntPtr.Zero && GetWindowThreadProcessId(hwnd, out pid) != 0 ? pid : 0u; + } + public static bool OwnsDialog(IntPtr hwnd, uint expected) { + return WindowProcessId(hwnd) == expected && Class(hwnd) == "#32770"; } public static bool HasShellControls(IntPtr dialog) { bool found = false; @@ -227,7 +234,17 @@ while ($clock.Elapsed.TotalSeconds -lt 20) { }) if ($Action -eq 'baseline') { if ($visible.Count -gt 0) { throw 'The installed launcher already owns a visible dialog before the project selection.' } - return + $activation = [Diagnostics.Stopwatch]::StartNew() + do { + $foreground = [WebuiTestDesktop]::GetForegroundWindow() + $owner = [WebuiTestDesktop]::WindowProcessId($foreground) + if ($owner -eq $BrowserPid) { + Write-Output "Project selection precondition: browser PID $BrowserPid owns foreground HWND $foreground." + return + } + Start-Sleep -Milliseconds 50 + } while ($activation.ElapsedMilliseconds -lt 3000) + throw "Browser foreground precondition failed before the chooser click: expected PID $BrowserPid, last foreground HWND $foreground owned by PID $owner." } if ($visible.Count -gt 1) { throw 'The installed launcher owns multiple visible Shell dialogs; the chooser is ambiguous.' } if ($visible.Count -eq 1) { diff --git a/scripts/verify-webui-package.mjs b/scripts/verify-webui-package.mjs index bec0e99f..9794e85a 100644 --- a/scripts/verify-webui-package.mjs +++ b/scripts/verify-webui-package.mjs @@ -262,7 +262,7 @@ async function verifyWindowsProjectEntry(installed, entry) { const launcherEntry = path.join(installed, "bin/mcode-webui.mjs"); const driveDialog = async ({ action, signal }) => { const args = ["-NoProfile", "-NonInteractive", "-STA", "-ExecutionPolicy", "Bypass", "-File", driver, - "-LauncherPid", String(browser.launcherPid), "-LauncherEntry", launcherEntry, "-Action", action]; + "-LauncherPid", String(browser.launcherPid), "-LauncherEntry", launcherEntry, "-BrowserPid", String(browser.browserPid), "-Action", action]; if (action === "select") args.push("-Directory", directory); const { stdout } = await promisify(execFile)("powershell.exe", args, { signal, timeout: 45_000, windowsHide: true, From 022841783d42a3af24e9fd0aaa925efeee008244 Mon Sep 17 00:00:00 2001 From: Jiaxiaoyuan Date: Fri, 27 Nov 2026 16:26:40 +0800 Subject: [PATCH 3/4] test(webui): consume the installed background launcher output and host handoff --- scripts/lib/webui-native-project-launch.mjs | 70 ++++++++++++++------- 1 file changed, 47 insertions(+), 23 deletions(-) diff --git a/scripts/lib/webui-native-project-launch.mjs b/scripts/lib/webui-native-project-launch.mjs index 0b2bd961..c7175c8d 100644 --- a/scripts/lib/webui-native-project-launch.mjs +++ b/scripts/lib/webui-native-project-launch.mjs @@ -4,6 +4,7 @@ import { readFile, rm } from 'node:fs/promises'; import { createRequire } from 'node:module'; import path from 'node:path'; import { createInterface } from 'node:readline'; +import { stripVTControlCharacters } from 'node:util'; import { setTimeout as delay } from 'node:timers/promises'; function powershell(script, env = {}) { @@ -100,14 +101,14 @@ function launcherEnvironment(installed, work, port, miniappPort) { delete env.WEBUI_LAUNCH_URL_FILE; const pathKey = Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'Path'; env[pathKey] = shimDirectory + path.delimiter + (env[pathKey] ?? ''); - return env; + return { env, shim: path.join(shimDirectory, 'mcode-webui.cmd') }; } function startInstalledCommand(installed, work, port, miniappPort) { // Windows keeps the driver's loaded native DLL mapped until this verifier exits. // Use the checkout's test driver so the temporary npm installation can be removed. const { spawn } = createRequire(new URL('../../packages/webui/package.json', import.meta.url))('node-pty'); - const env = launcherEnvironment(installed, work, port, miniappPort); + const { env } = launcherEnvironment(installed, work, port, miniappPort); const term = spawn(path.join(process.env.SystemRoot, 'System32', 'cmd.exe'), ['/d', '/c', 'mcode-webui.cmd'], { cwd: work, env, cols: 120, rows: 30, }); @@ -233,7 +234,7 @@ function startTerminalDriver(installed, work, port, miniappPort) { // A desktop host starts the installed command without a console and consumes its private file. // A person starting the same command in the background manually opens the address it prints. function startBackgroundCommand(installed, work, port, miniappPort, entry) { - const env = launcherEnvironment(installed, work, port, miniappPort); + const { env, shim } = launcherEnvironment(installed, work, port, miniappPort); env.MINIMAX_DATA_DIR = mkdtempSync(path.join(work, 'background-data-')); const handoffFile = path.join(env.MINIMAX_DATA_DIR, 'launch-url'); if (entry === 'desktop-handoff') { @@ -241,31 +242,55 @@ function startBackgroundCommand(installed, work, port, miniappPort, entry) { env.WEBUI_LAUNCH_URL_FILE = handoffFile; env.WEBUI_OPEN_BROWSER = '0'; } - const child = spawn(path.join(process.env.SystemRoot, 'System32', 'cmd.exe'), ['/d', '/c', 'mcode-webui.cmd'], { - cwd: work, env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, + const origin = `http://127.0.0.1:${port}`; + // /s consumes the outer quotes, leaving a quoted npm shim even in a prefix with spaces. + const child = spawn(path.join(process.env.SystemRoot, 'System32', 'cmd.exe'), ['/d', '/s', '/c', '""%WEBUI_GATE_SHIM%""'], { + cwd: work, env: { ...env, WEBUI_GATE_SHIM: shim }, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, windowsVerbatimArguments: true, }); - const printed = Promise.withResolvers(); const exited = new Promise((resolve) => child.once('close', resolve)); - child.once('error', () => printed.resolve(undefined)); - child.once('exit', () => printed.resolve(undefined)); - const lines = createInterface({ input: child.stdout, crlfDelay: Infinity }); - lines.on('line', (line) => { - const match = /^\[mcode-webui\] WebUI running at (\S+)$/u.exec(line); - if (match) printed.resolve(match[1]); + let spawnError; + let address; + const categories = new Set(); + child.once('error', (error) => { spawnError = error.code ?? 'spawn-failed'; }); + const output = ['stdout', 'stderr'].map((name) => { + const stream = child[name]; + const stats = { name, bytes: 0, lines: 0 }; + stream.on('data', (chunk) => { stats.bytes += chunk.length; }); + const reader = createInterface({ input: stream, crlfDelay: Infinity }); + reader.on('line', (raw) => { + stats.lines++; + const line = stripVTControlCharacters(raw).trim(); + const errors = line.match(/\b(?:EADDRINUSE|EACCES|EPERM|ENOENT|MODULE_NOT_FOUND|ERR_MODULE_NOT_FOUND|SQLITE_BUSY|SQLITE_CANTOPEN)\b/g) ?? []; + for (const code of errors) categories.add(code); + if (line.includes('a native module this package needs was not built')) categories.add('native-binding'); + if (line.includes('could not write WEBUI_LAUNCH_URL_FILE')) categories.add('handoff-write'); + const match = /\[mcode-webui\] (?:WebUI running at|open) (https?:\/\/\S+)/u.exec(line); + if (match) address = match[1]; + }); + return stats; }); return { pid: child.pid, async pageUrl() { - const address = await Promise.race([printed.promise, delay(60_000, undefined, { ref: false })]); - if (!address || !URL.canParse(address)) throw new Error('The background launcher did not print a valid access URL.'); - const url = new URL(address); - if (url.origin !== `http://127.0.0.1:${port}` || url.hash) throw new Error('Unexpected origin or private fragment in the printed access URL.'); - if (entry === 'manual') return address; - const handoff = await readFile(handoffFile, 'utf8'); - if (!URL.canParse(handoff)) throw new Error('The desktop host handoff did not contain a valid URL.'); - const privateUrl = new URL(handoff); - if (privateUrl.origin !== url.origin) throw new Error('The desktop host handoff does not identify its installed launcher.'); - return handoff; + const deadline = Date.now() + 60_000; + while (Date.now() < deadline && !spawnError && child.exitCode === null && child.signalCode === null) { + if (address && (!URL.canParse(address) || new URL(address).origin !== origin || new URL(address).hash)) { + throw new Error('The printed access URL has an invalid origin or includes a private fragment.'); + } + if (entry === 'manual' && address) return address; + if (entry === 'desktop-handoff' && existsSync(handoffFile)) { + const handoff = await readFile(handoffFile, 'utf8'); + if (!URL.canParse(handoff) || new URL(handoff).origin !== origin) { + throw new Error('The desktop host handoff does not identify its installed launcher.'); + } + return handoff; + } + await delay(100); + } + const listener = await fetch(origin, { signal: AbortSignal.timeout(2000), redirect: 'manual' }) + .then(async (response) => { await response.body?.cancel(); return response.status; }, () => 'unreachable'); + const streams = output.map(({ name, bytes, lines }) => `${name}=${bytes}B/${lines}lines`).join(', '); + throw new Error(`No usable ${entry} launch URL (pid=${child.pid ?? 'none'}, process=${spawnError ?? child.exitCode ?? child.signalCode ?? 'running'}, listener=${listener}, handoffFile=${existsSync(handoffFile)}, ${streams}, codes=${[...categories].join(',') || 'none'}).`); }, async close() { try { @@ -278,7 +303,6 @@ function startBackgroundCommand(installed, work, port, miniappPort, entry) { const closed = await Promise.race([exited.then(() => true), delay(5000, false, { ref: false })]); if (!closed) throw new Error('The background launcher process tree did not close.'); } finally { - lines.close(); await rm(handoffFile, { force: true }); } }, From aaf790914710a965f1a76058d25fc42f1f475caa Mon Sep 17 00:00:00 2001 From: Jiaxiaoyuan Date: Fri, 27 Nov 2026 16:44:55 +0800 Subject: [PATCH 4/4] fix(webui): restore local project selection and refresh the session rail --- .gitignore | 1 + packages/webui/docs/client/composer.md | 12 +-- packages/webui/docs/client/ownership.md | 5 ++ packages/webui/docs/verification/gates.md | 3 +- .../application/task-session-workflows.ts | 9 --- .../sessions/application/session-workflows.ts | 46 ++++++------ .../platform/native-directory-picker.ts | 48 ++++++++++-- .../webui/src/server/http/native-directory.ts | 75 ++++++++++++++++++- .../test/unit/native-directory-picker.test.ts | 5 +- .../test/unit/task-session-workflows.test.ts | 27 ------- .../test/unit/webui-session-catalog.test.ts | 30 +++++++- release/public-source.json | 2 - release/webui-npm/README.md | 12 ++- release/webui-npm/bin/mcode-webui.mjs | 5 +- .../webui-npm/bin/native-directory-picker.mjs | 11 +-- scripts/source-inventory.mjs | 2 + test/source-sync.test.mjs | 6 +- 17 files changed, 201 insertions(+), 98 deletions(-) diff --git a/.gitignore b/.gitignore index 4d40bbd6..9a830844 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ dist-webui-npm/ !.env.example .DS_Store .idea/ +.openidea/ .codegraph/ dist-*.zip dist-store-*/ diff --git a/packages/webui/docs/client/composer.md b/packages/webui/docs/client/composer.md index 0c1ca6aa..9128de57 100644 --- a/packages/webui/docs/client/composer.md +++ b/packages/webui/docs/client/composer.md @@ -36,7 +36,7 @@ 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 opens the native +on the computer running `mcode-webui`. 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 @@ -48,14 +48,14 @@ Cancelling returns to the home page with the previous selection. The tab opened by the launcher exchanges its temporary grant for a browser key and a separate HttpOnly session cookie. Reloaded pages and other tabs on the -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. +same origin use that pairing. A manually opened local page can establish a +pairing through a temporary loopback listener. Remote pages 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` +The file is owner-only. The route checks loopback, Host, Origin, credentials and +browser pairing. `WEBUI_OPEN_BROWSER` still controls only the system browser. ## Where the pieces live diff --git a/packages/webui/docs/client/ownership.md b/packages/webui/docs/client/ownership.md index ec2730ca..4165814f 100644 --- a/packages/webui/docs/client/ownership.md +++ b/packages/webui/docs/client/ownership.md @@ -213,6 +213,11 @@ execution. Stop acknowledgements are fenced by the generation captured at invoca acknowledgement cannot settle a newer turn. Execution activity, delivery completion and persistence confirmation remain separate facts. +The sessions owner refreshes the rail's project records on a committed `session.created` +event, including sessions created by `/new` or another client. Multiple creations during a +pending read trigger one fresh lookup after it settles. Sending the first message can proceed +while that lookup is pending. + The selected session's metadata is read from the catalogue entity map, independently of the flat and tree pages' membership. Selection acquires missing metadata through the existing `getSession` operation; concurrent same-identity reads coalesce, and navigation does not redirect their result. diff --git a/packages/webui/docs/verification/gates.md b/packages/webui/docs/verification/gates.md index 4ddcf6a2..0dd28853 100644 --- a/packages/webui/docs/verification/gates.md +++ b/packages/webui/docs/verification/gates.md @@ -10,6 +10,7 @@ document: [`browser-suite.md`](browser-suite.md). | Gate | Proves | Fails on | | --- | --- | --- | +| `pnpm check:source` | The clean checkout matches the published source inventory. WebUI CI runs this in its Linux checks job before installing dependencies. | Missing declared files, undeclared source files or source integrity violations | | `pnpm typecheck:webui` | Every source file and every test file compiles under `strict`: the server/runtime/shared config, the client config, and one test program whose `include` is the whole `test/` and `src/` tree | A port member without its stub, a missing binding, a wrong DTO, a test fixture that no longer matches the signature it calls | | `pnpm check:webui-dependency` | Import direction and role ownership over the resolved source graph, including `import type` edges | A forbidden direction, a role violation, a business holding one role in two homes, a private cross-business import, or an unclassified source | | `pnpm check:webui-presentation` | Every client UI source module (`features/*/ui/`, `shell/`, the shared `ui/`) is classified in `scripts/lib/webui-presentation-inventory.json`, and the inventory agrees with the modules on disk | An unclassified module, an entry whose module is gone, an undefined disposition, kind or family, a business exception without a reason, a module classified as newly-adopted-contract that renders or calls nothing from the shared home | @@ -18,7 +19,7 @@ document: [`browser-suite.md`](browser-suite.md). | `pnpm check:webui-motion` | Every duration and every `@keyframes` in the client's stylesheets is inventoried per file in `docs/design/motion-inventory.json` against a named family (feedback, surface, disclosure, loading) or recorded as a distinct effect with its reason; and, in source, that motion belongs to a shared component — shared `ui/` components opt into the feedback family, and feature code owns no timing, rotation, interaction transform, smooth scroll or raw motion utility. The approved feature exceptions are `features/account/ui/account.css`, `features/transcript/ui/transcript.css`, the sign-in success effect, the transcript message entrance and turn-jump highlight, and the rose-loader Lottie asset | A new raw duration or keyframe, a recorded entry that has gone, a value that claims a family but is not that family's token, a distinct effect with no reason, a feature stylesheet declaring motion without an approved exception, a raw motion utility or inline motion style in a component, a hand-rolled `role="button"`, `data-webui-motion` outside the shared components, a native `
`, inline SVG animation, an animation-engine import outside `ui/feedback.tsx`, a `WebuiDialog` without an explicit `open` state, or a shared control that forgets to opt into the feedback family | | `pnpm build:webui` | The client and server bundles build, and prints input counts | A module that is written but not wired (counts do not move) | | `pnpm check:webui-boundary` | The combined client/server build graph contains required entries and inputs within declared package roots; direct WebUI workspace imports use exported subpaths; the artifact integrity record matches current inputs and outputs | A retired source path, the terminal renderer, a private direct workspace import, a forbidden internal reference, or a stale/modified build artifact | -| `pnpm test:webui-package` | Installs the candidate, verifies startup and the browser bridge, and on Windows selects a project from the launcher's home page | Packaging drift, native folder selection failure, a session using the wrong directory | +| `pnpm test:webui-package` | Installs the candidate and checks startup and the browser bridge. On Windows, tests the automatically opened page, the manually opened launcher URL and the desktop host's handoff URL in separate browser profiles. From each home page it selects and cancels a foreground system dialog, then finds the new session under its chosen project both before and after reloading. | A broken entry, a background-only dialog, a dropped selection, a stale project list or a session that fails to persist | | `pnpm test:webui` | The registered WebUI Vitest group (unit, integration and verification-gate tests) | Behaviour change, unregistered new test file | | `pnpm test:webui-browser` | Every Playwright spec collected under `packages/webui/test/browser/`: the built client and deterministic in-page transport, plus explicit real-browser bridge and production-host/native-PTY harnesses. The screenshot comparisons run against the font files committed under `packages/webui/test/browser/fonts/`, so their result does not depend on the fonts the machine has installed | Behaviour change in the built bundle, a real bridge path, or native lifecycle | | `pnpm check:source` | `release/public-source.json` lists exactly the delivered files | A new, moved or deleted file without inventory regeneration | diff --git a/packages/webui/src/client/application/task-session-workflows.ts b/packages/webui/src/client/application/task-session-workflows.ts index 3c44570a..8544e229 100644 --- a/packages/webui/src/client/application/task-session-workflows.ts +++ b/packages/webui/src/client/application/task-session-workflows.ts @@ -45,15 +45,12 @@ 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 { @@ -295,12 +292,6 @@ 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/src/client/features/sessions/application/session-workflows.ts b/packages/webui/src/client/features/sessions/application/session-workflows.ts index 4b510dd4..64a0ea1b 100644 --- a/packages/webui/src/client/features/sessions/application/session-workflows.ts +++ b/packages/webui/src/client/features/sessions/application/session-workflows.ts @@ -409,12 +409,32 @@ export function createWebuiSessionWorkflows(deps: { let archived: WebuiArchivedSessionsState = initialWebuiArchivedSessionsState; let projects: WebuiProjectsState = { loading: false }; let projectRequestVersion = 0; + let projectsInvalidated = false; let disposed = false; const projectListeners = new Set<() => void>(); const setProjects = (next: WebuiProjectsState): void => { projects = next; for (const listener of [...projectListeners]) listener(); }; + async function loadProjects(): Promise { + if (!port.loadProjects || disposed) return projects.projects ?? []; + const version = ++projectRequestVersion; + projectsInvalidated = false; + setProjects({ ...projects, loading: true, error: undefined }); + try { + const result = await port.loadProjects(); + if (!disposed && version === projectRequestVersion && !projectsInvalidated) + setProjects({ loading: false, projects: result }); + return result; + } catch (error) { + if (!disposed && version === projectRequestVersion && !projectsInvalidated) + setProjects({ ...projects, loading: false, error: message(error) }); + throw error; + } finally { + if (!disposed && version === projectRequestVersion && projectsInvalidated) + void loadProjects().catch(() => undefined); + } + } const archivedListeners = new Set<() => void>(); const setArchived = (next: WebuiArchivedSessionsState): void => { archived = next; @@ -766,6 +786,10 @@ export function createWebuiSessionWorkflows(deps: { if (disposed || removedSessionIds.has(fact.sessionId)) return; retireCatalogReads(); if (fact.kind === "created") { + // Creating from another client or /new changes the same rail as a home + // submission. A read started before the commit needs one trailing read. + if (projects.loading) projectsInvalidated = true; + else void loadProjects().catch(() => undefined); // A creation normally names an entity this client has never read. // Repair through the authoritative query before applying known-only patches. if (flatPending === undefined) void loadFlat(); @@ -946,27 +970,7 @@ export function createWebuiSessionWorkflows(deps: { projectListeners.add(listener); return () => projectListeners.delete(listener); }, - loadProjects: async () => { - if (!port.loadProjects) return []; - if (disposed) return projects.projects ?? []; - const version = ++projectRequestVersion; - setProjects({ ...projects, loading: true, error: undefined }); - try { - const result = await port.loadProjects(); - if (disposed || version !== projectRequestVersion) return result; - setProjects({ loading: false, projects: result }); - return result; - } catch (error) { - if (!disposed && version === projectRequestVersion) { - setProjects({ loading: false, ...(projects.projects ? { projects: projects.projects } : {}), error: message(error) }); - } - throw error; - } finally { - if (!disposed && version === projectRequestVersion && projects.loading) { - setProjects({ ...projects, loading: false }); - } - } - }, + loadProjects, retainedDeletionDrafts: () => retainedSnapshot, subscribeRetainedDrafts: (listener) => { retainedListeners.add(listener); diff --git a/packages/webui/src/client/platform/native-directory-picker.ts b/packages/webui/src/client/platform/native-directory-picker.ts index 09689c82..82e4206d 100644 --- a/packages/webui/src/client/platform/native-directory-picker.ts +++ b/packages/webui/src/client/platform/native-directory-picker.ts @@ -18,10 +18,10 @@ function localTarget() { target?.origin === url.origin && target.token) return target; } -async function pairBrowser(origin: string, token: string, grant: string): Promise { +async function pairBrowser(origin: string, token: string, headers: Record, signal?: AbortSignal): Promise { const response = await globalThis.fetch(`${origin}/native-directory-picker/authorize`, { method: "POST", mode: "same-origin", credentials: "same-origin", redirect: "error", - headers: { "X-Webui-Native-Grant": grant, "X-Webui-Token": token }, + headers: { ...headers, "X-Webui-Token": token }, ...(signal ? { signal } : {}), }); if (!response.ok) return; const result: unknown = await response.json(); @@ -33,6 +33,34 @@ async function pairBrowser(origin: string, token: string, grant: string): Promis return result.browserKey; } +async function pairLocalBrowser(origin: string, token: string, signal: AbortSignal): Promise { + // A forwarded WebUI can return the host's port number, but the new address + // resolves on the browser's own computer. Never send a credential to it. + try { + const challenge = await fetch(`${origin}/native-directory-picker/authorize`, { + method: "POST", mode: "same-origin", credentials: "same-origin", redirect: "error", signal, + headers: { "X-Webui-Native-Local": "1", "X-Webui-Token": token }, + }); + if (!challenge.ok) return; + const { localOrigin } = await challenge.json(); + if (typeof localOrigin !== "string") return; + const url = new URL(localOrigin); + if (url.origin !== localOrigin || url.protocol !== "http:" || url.hostname !== new URL(origin).hostname || + url.origin === origin || !url.port) return; + const receipt = await fetch(localOrigin + "/", { + method: "POST", mode: "cors", credentials: "omit", referrerPolicy: "no-referrer", redirect: "error", + signal: AbortSignal.any([signal, AbortSignal.timeout(5_000)]), + }); + if (!receipt.ok) return; + const { proof } = await receipt.json(); + if (typeof proof !== "string" || !uuid.test(proof)) return; + return await pairBrowser(origin, token, { "X-Webui-Native-Local": "1", "X-Webui-Native-Proof": proof }, signal); + } catch (error) { + if (signal.aborted) throw error; + return; + } +} + export function captureNativeDirectoryLaunchGrant(): void { launchPairing = undefined; const url = new URL(globalThis.location.href); @@ -45,7 +73,7 @@ export function captureNativeDirectoryLaunchGrant(): void { globalThis.history.replaceState(globalThis.history.state, "", url.href); const target = localTarget(); if (target && uuid.test(grant)) { - launchPairing = pairBrowser(target.origin, target.token, grant).catch(() => undefined); + launchPairing = pairBrowser(target.origin, target.token, { "X-Webui-Native-Grant": grant }).catch(() => undefined); } } export async function pickNativeWorkspaceDirectory(signal: AbortSignal): Promise { @@ -55,11 +83,19 @@ export async function pickNativeWorkspaceDirectory(signal: AbortSignal): Promise // A later launch may have paired another tab since this page loaded. try { browserKey = getWebuiBrowserStorage()?.getItem(pairingKey) ?? browserKey; } catch { /* Use this tab's key when browser storage cannot be read. */ } - if (!browserKey || !uuid.test(browserKey)) return { kind: "unavailable" }; - const response = await globalThis.fetch(`${target.origin}/native-directory-picker`, { + const choose = (key: string) => globalThis.fetch(`${target.origin}/native-directory-picker`, { method: "POST", mode: "same-origin", credentials: "same-origin", redirect: "error", signal, - headers: { "X-Webui-Native-Browser": browserKey, "X-Webui-Token": target.token }, + headers: { "X-Webui-Native-Browser": key, "X-Webui-Token": target.token }, }); + let response = browserKey && uuid.test(browserKey) ? await choose(browserKey) : undefined; + // A stale key from the previous server process is refused before the + // provider is invoked. Re-pair once; never repeat a submitted selection. + if (!response || (response.status === 403 && !launchPairing)) { + browserKey = await pairLocalBrowser(target.origin, target.token, signal); + if (!browserKey) return { kind: "unavailable" }; + launchPairing = Promise.resolve(browserKey); + response = await choose(browserKey); + } if ([401, 403, 404].includes(response.status)) return { kind: "unavailable" }; if (!response.ok) throw new Error(response.status === 409 ? "已有系统目录选择窗口,请先完成或取消。" : "系统目录选择失败,请重试。"); const result: unknown = await response.json(); diff --git a/packages/webui/src/server/http/native-directory.ts b/packages/webui/src/server/http/native-directory.ts index ce32c179..66655ee9 100644 --- a/packages/webui/src/server/http/native-directory.ts +++ b/packages/webui/src/server/http/native-directory.ts @@ -1,8 +1,9 @@ // Desktop capability supplied only by an interactive local launcher. General // WebUI credentials alone never authorize opening native desktop UI. -import type { IncomingMessage, ServerResponse } from "node:http"; +import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { once } from "node:events"; import { randomUUID, timingSafeEqual } from "node:crypto"; -import { credentialFromCookie, credentialPresented, type WebuiCredential } from "../credentials.js"; +import { credentialFromCookie, credentialMatches, credentialPresented, type WebuiCredential } from "../credentials.js"; import { stat } from "node:fs/promises"; import { isAbsolute } from "node:path"; import { rejectHttp } from "./responses.js"; @@ -20,6 +21,44 @@ interface Admission { readonly credential: WebuiCredential; } const loopback = (value: string | undefined) => value === "127.0.0.1" || value === "::1" || value === "::ffff:127.0.0.1"; +const forwarded = (request: IncomingMessage) => Object.keys(request.headers).some((key) => key === "forwarded" || key.startsWith("x-forwarded-")); + +// A browser that reached WebUI through a single forwarded port cannot reach +// this second listener on its own loopback interface. No bearer or cookie is +// sent there. The proof only pairs a browser at the original WebUI origin. +function startLocalPairing(host: string, origin: string) { + const proof = randomUUID(); + const controller = new AbortController(); + const server = createServer((req, res) => { + res.setHeader("Cache-Control", "no-store"); + const address = server.address(); + if (!address || typeof address === "string" || !loopback(req.socket.remoteAddress) || forwarded(req) || + req.method !== "POST" || req.url !== "/" || req.headers.origin !== origin || + req.headers.host !== `${new URL(origin).hostname}:${address.port}` || + req.headers["sec-fetch-site"] !== "same-site" || req.headers["sec-fetch-mode"] !== "cors" || + (req.headers["content-length"] !== undefined && req.headers["content-length"] !== "0") || req.headers["transfer-encoding"] !== undefined) { + rejectHttp(res, 403, "Native browser pairing unavailable"); return; + } + res.setHeader("Access-Control-Allow-Origin", origin); + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify({ proof })); + }); + server.maxConnections = 8; + server.unref(); + const ready = once(server, "listening", { signal: controller.signal }).then(() => { + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Local pairing listener unavailable"); + return `http://${new URL(origin).hostname}:${address.port}`; + }); + server.listen({ host, port: 0, signal: controller.signal }); + const timer = setTimeout(close, 10_000).unref(); + function close() { + clearTimeout(timer); + controller.abort(); + server.closeAllConnections(); + } + return { proof, ready, close, signal: controller.signal }; +} function equalSecret(value: string | string[] | undefined, expected: string): boolean { if (typeof value !== "string" || !expected) return false; const a = Buffer.from(value); const b = Buffer.from(expected); @@ -45,6 +84,7 @@ export async function validateNativeDirectory( export function createNativeDirectoryRoute(picker: WebuiNativeDirectoryPicker, timeoutMs = 120_000) { let active: { controller: AbortController; settled: Promise } | undefined; let pairing: { browserKey: string; cookieToken: string } | undefined; + let localPairing: ReturnType | undefined; let closed = false; return { async handle(request: IncomingMessage, response: ServerResponse, context: Admission, action: "choose" | "authorize" = "choose"): Promise { @@ -53,11 +93,18 @@ export function createNativeDirectoryRoute(picker: WebuiNativeDirectoryPicker, t if (closed || context.fullAccess || !loopback(context.host) || !loopback(request.socket.remoteAddress) || !context.port || request.headers.host !== authority || request.headers.origin !== `http://${authority}` || request.headers["sec-fetch-site"] !== "same-origin" || - Object.keys(request.headers).some((key) => key === "forwarded" || key.startsWith("x-forwarded-"))) { + forwarded(request)) { rejectHttp(response, 403, "Native directory selection unavailable"); return; } const cookieName = `webui_native_directory_${context.port}`; - if (!equalSecret(request.headers["x-webui-native-grant"], picker.grant)) { + const local = action === "authorize" && request.headers["x-webui-native-local"] === "1"; + if (local) { + const cookie = credentialFromCookie(request.headers.cookie); + if (cookie.kind !== "presented" || !credentialMatches(context.credential, cookie.token) || + !equalSecret(request.headers["x-webui-token"], context.credential.token)) { + rejectHttp(response, 401, "Unauthorized"); return; + } + } else if (!equalSecret(request.headers["x-webui-native-grant"], picker.grant)) { const cookie = credentialFromCookie(request.headers.cookie, cookieName); // Cookies follow a host across ports. The second proof belongs to the exact browser origin. if (action === "authorize" || !pairing || cookie.kind !== "presented" || @@ -76,6 +123,25 @@ export function createNativeDirectoryRoute(picker: WebuiNativeDirectoryPicker, t rejectHttp(response, 400, "Native directory selection accepts no body"); return; } if (action === "authorize") { + if (local) { + const proof = request.headers["x-webui-native-proof"]; + if (proof === undefined) { + try { + if (!localPairing || localPairing.signal.aborted) localPairing = startLocalPairing(context.host, `http://${authority}`); + const localOrigin = await localPairing.ready; + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify({ localOrigin })); + } catch { + localPairing?.close(); + rejectHttp(response, 503, "Native browser pairing unavailable"); + } + return; + } + if (!localPairing || localPairing.signal.aborted || !equalSecret(proof, localPairing.proof)) { + rejectHttp(response, 403, "Native browser pairing unavailable"); return; + } + localPairing.close(); + } pairing ??= { browserKey: randomUUID(), cookieToken: randomUUID() }; response.setHeader("Set-Cookie", `${cookieName}=${pairing.cookieToken}; Path=/native-directory-picker; SameSite=Strict; HttpOnly`); response.setHeader("Content-Type", "application/json"); @@ -115,6 +181,7 @@ export function createNativeDirectoryRoute(picker: WebuiNativeDirectoryPicker, t } }, async dispose(): Promise { + localPairing?.close(); closed = true; active?.controller.abort(); await picker.dispose(); await active?.settled.catch(() => undefined); diff --git a/packages/webui/test/unit/native-directory-picker.test.ts b/packages/webui/test/unit/native-directory-picker.test.ts index a9166728..a89463ef 100644 --- a/packages/webui/test/unit/native-directory-picker.test.ts +++ b/packages/webui/test/unit/native-directory-picker.test.ts @@ -206,12 +206,15 @@ describe("native directory launch grant transport", () => { expect(await pickNativeWorkspaceDirectory(signal)).toEqual({ kind: "unavailable" }); }); - it("does not contact a picker from an unpaired, remote, or mismatched-runtime page", async () => { + it("requests local pairing only from a same-origin loopback page", async () => { const fetch = vi.fn(); vi.stubGlobal("fetch", fetch); vi.stubGlobal("localStorage", undefined); browser(origin + "/"); expect(await pickNativeWorkspaceDirectory(signal)).toEqual({ kind: "unavailable" }); + expect(fetch).toHaveBeenCalledOnce(); + expect(fetch.mock.calls[0]?.[0]).toBe(origin + "/native-directory-picker/authorize"); + fetch.mockClear(); vi.stubGlobal("localStorage", { getItem: () => browserKey }); browser(`http://example.test/#nativeDirectoryGrant=${grant}`); expect(await pickNativeWorkspaceDirectory(signal)).toEqual({ kind: "unavailable" }); diff --git a/packages/webui/test/unit/task-session-workflows.test.ts b/packages/webui/test/unit/task-session-workflows.test.ts index b2822b0c..1f775b29 100644 --- a/packages/webui/test/unit/task-session-workflows.test.ts +++ b/packages/webui/test/unit/task-session-workflows.test.ts @@ -51,7 +51,6 @@ interface HarnessOptions { ) => Promise; readonly loadFlat?: () => Promise; readonly loadTree?: () => Promise; - readonly loadProjects?: () => Promise; readonly store?: WebuiSessionStore; readonly noProjectPersisted?: boolean; } @@ -81,10 +80,6 @@ function harness(options: HarnessOptions = {}) { catalogueCalls.push("tree"); await options.loadTree?.(); }, - loadProjects: async () => { - catalogueCalls.push("projects"); - await options.loadProjects?.(); - }, }, ...(options.createSession ? { @@ -276,28 +271,6 @@ 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" }), diff --git a/packages/webui/test/unit/webui-session-catalog.test.ts b/packages/webui/test/unit/webui-session-catalog.test.ts index a9d9ff60..0de44d18 100644 --- a/packages/webui/test/unit/webui-session-catalog.test.ts +++ b/packages/webui/test/unit/webui-session-catalog.test.ts @@ -14,7 +14,7 @@ import { createWebuiSessionStore } from "../../src/client/application/session-st import { createWebuiSessionWorkflows } from "../../src/client/features/sessions/application/session-workflows.js"; import { createWebuiSessionScopeManager } from "../../src/client/conversation/session-scope.js"; import { selectWebuiWorkspaceProgress } from "../../src/client/features/workspace/projection/workspace-progress.js"; -import type { WebuiClientSession } from "../../src/client/features/sessions/contracts/session-view.js"; +import type { WebuiClientProject, WebuiClientSession } from "../../src/client/features/sessions/contracts/session-view.js"; import type { WebuiSessionLookupResult } from "../../src/shared/contracts/session.js"; import { selectWebuiSessionAgentName, selectWebuiSessionLookups } from "../../src/client/features/sessions/projection/session-lookups.js"; @@ -411,6 +411,34 @@ describe("session workflows", () => { workflows.dispose(); }); + it("reads project membership after creation and reconciles creations during a pending read", async () => { + const reads: Array<(rows: readonly WebuiClientProject[]) => void> = []; + const workflows = createWebuiSessionWorkflows({ + store: createWebuiSessionStore(), composer: purger(), port: { + loadProjects: () => new Promise((resolve) => { reads.push(resolve); }), + } as Parameters[0]["port"], + }); + const expected: WebuiClientProject = { + projectId: 2, workspaceDir: "/later", projectKind: "workspace", hidden: false, pinned: false, + orderIndex: 0, recentAtMs: 1, latestActivityAtMs: 1, sessionCount: 1, + }; + const initial = workflows.loadProjects(); + reads[0]!([]); + await initial; + workflows.applyFact({ kind: "created", sessionId: "first" }); + workflows.applyFact({ kind: "created", sessionId: "second" }); + workflows.applyFact({ kind: "created", sessionId: "third" }); + expect(reads).toHaveLength(2); + reads[1]!([]); + await Promise.resolve(); + expect(reads).toHaveLength(3); + expect(workflows.getProjectsSnapshot().loading).toBe(true); + reads[2]!([expected]); + await Promise.resolve(); + expect(workflows.getProjectsSnapshot()).toEqual({ loading: false, projects: [expected] }); + workflows.dispose(); + }); + it("fences project answers that arrive after workflow disposal", async () => { let resolve: (projects: readonly { name: string; workspaceDir: string }[]) => void = () => {}; const workflows = createWebuiSessionWorkflows({ diff --git a/release/public-source.json b/release/public-source.json index 28f0aa2d..d216d307 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -61,8 +61,6 @@ ".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", diff --git a/release/webui-npm/README.md b/release/webui-npm/README.md index 20362b19..f7ed80dc 100644 --- a/release/webui-npm/README.md +++ b/release/webui-npm/README.md @@ -74,12 +74,10 @@ server is listening, the launcher writes the page URL with its 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. +Local desktop launches can open the native-directory picker without an +interactive TTY. A manually opened local page establishes browser pairing through +a short-lived loopback listener. `WEBUI_OPEN_BROWSER=0` controls automatic +browser opening. If the handoff file cannot be written, the host can use the +printed WebUI URL. The package requires a supported Node.js version shown in its `engines` field. diff --git a/release/webui-npm/bin/mcode-webui.mjs b/release/webui-npm/bin/mcode-webui.mjs index 3f3be7cf..c419df71 100644 --- a/release/webui-npm/bin/mcode-webui.mjs +++ b/release/webui-npm/bin/mcode-webui.mjs @@ -263,12 +263,11 @@ const terminal = new WebuiTerminalManager(); // The bridge's pairings follow the switches, so the persisted authorization has // to reach them before the service starts serving. await browser.initialize(); -// Kept out of help/version and disabled for unattended, remote and full-access runs. +// A desktop loopback launch offers the provider. The browser must still pair. const { nativeDirectoryPickerEligible, createNativeDirectoryPicker, nativeDirectoryLaunchUrl } = await import("./native-directory-picker.mjs"); const nativeDirectoryPicker = nativeDirectoryPickerEligible({ - platform: process.platform, tty: Boolean(process.stdout.isTTY), desktopHost, - bindHost, fullAccess: args["full-access"], + 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.mjs b/release/webui-npm/bin/native-directory-picker.mjs index c0733f43..184d02cb 100644 --- a/release/webui-npm/bin/native-directory-picker.mjs +++ b/release/webui-npm/bin/native-directory-picker.mjs @@ -7,15 +7,12 @@ import path from 'node:path'; import { createWin32DirectoryPicker } from './native-directory-picker-win32.mjs'; -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. +export function nativeDirectoryPickerEligible({ platform, bindHost, fullAccess, env = process.env }) { + // A background service can have an attended desktop. Browser pairing + // establishes local access when the user requests the chooser. const desktop = platform === 'win32' || platform === 'darwin' || (platform === 'linux' && Boolean(env.DISPLAY || env.WAYLAND_DISPLAY)); - const attended = desktopHost === true || tty === true; - return desktop && attended && !fullAccess && !env.SSH_CONNECTION && !env.SSH_TTY + return desktop && !fullAccess && !env.SSH_CONNECTION && !env.SSH_TTY && ['127.0.0.1', '::1'].includes(bindHost); } diff --git a/scripts/source-inventory.mjs b/scripts/source-inventory.mjs index bbd410cc..df8ca4d4 100644 --- a/scripts/source-inventory.mjs +++ b/scripts/source-inventory.mjs @@ -35,6 +35,8 @@ const skipped = new Set([ // but not to this scan, and without the entry any developer who happens to have // the tool installed fails `check:source` over a file they never wrote. ".codegraph", + // OpenIDEA's per-user changelists belong to the editor, not the source archive. + ".openidea", // The scratch directory of a working session, in the same category: git // ignores it, it is machine-local, and it holds screenshots and one-off // scripts rather than source. Without the entry any developer who has one diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index e397e897..c0ceafdf 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -1593,16 +1593,16 @@ 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 interactive or desktop-hosted local desktop loopback', () => { +test('a desktop loopback launch offers folder selection to paired browsers with or without a terminal', () => { 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' } }, { desktopHost: true, tty: false }]) { + { platform: 'linux', env: { WAYLAND_DISPLAY: 'wayland-0' } }, { desktopHost: true, tty: false }, { 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' }, - { tty: false }, { desktopHost: true, tty: false, env: { SSH_TTY: '/dev/pts/0' } }, + { 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); }