diff --git a/.github/workflows/webui-ci.yml b/.github/workflows/webui-ci.yml index b4c0dcc89..5fe5dcc5a 100644 --- a/.github/workflows/webui-ci.yml +++ b/.github/workflows/webui-ci.yml @@ -31,6 +31,9 @@ jobs: run: | echo "MCODE_WEBUI_VERIFY_DIR=$RUNNER_TEMP/webui-package-checks" >> "$GITHUB_ENV" echo "WEBUI_BROWSER_OUTPUT_DIR=$RUNNER_TEMP/webui-browser-results" >> "$GITHUB_ENV" + if [ "$RUNNER_OS" = "macOS" ]; then + echo "WEBUI_BROWSER_HEADED=1" >> "$GITHUB_ENV" + fi - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 with: version: 9.12.0 @@ -52,10 +55,12 @@ jobs: - name: Check WebUI feedback run: pnpm check:webui-feedback - name: Build WebUI + id: build run: pnpm build:webui - name: Check WebUI build boundaries run: pnpm check:webui-boundary - name: Install Chromium + id: browsers run: pnpm install:webui-browsers - name: Install Chromium system dependencies if: runner.os == 'Linux' @@ -63,11 +68,13 @@ jobs: - name: Test WebUI units and integrations run: pnpm test:webui - name: Test WebUI browser interactions + if: ${{ !cancelled() && steps.build.outcome == 'success' && steps.browsers.outcome == 'success' }} run: pnpm test:webui-browser - name: Verify WebUI package installation + if: ${{ !cancelled() && steps.build.outcome == 'success' }} run: pnpm test:webui-package - name: Upload WebUI browser diagnostics - if: ${{ failure() }} + if: ${{ !cancelled() }} uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: webui-browser-${{ matrix.os }}-${{ github.run_attempt }} diff --git a/docs/webui-ci.md b/docs/webui-ci.md index 546eacf7c..c1c7fa52e 100644 --- a/docs/webui-ci.md +++ b/docs/webui-ci.md @@ -15,12 +15,38 @@ repository-wide `pnpm verify` pipeline or publish packages. | npm package build, installation and launcher verification | Yes | Yes | Yes | Package verification uses an isolated installation and does not publish to npm. -Browser failure diagnostics are retained as Actions artifacts for seven days. -Only installation of Linux system dependencies is platform-gated. CI does not -skip the browser or package suites on macOS or Windows. This coverage declaration +Browser diagnostics and raw performance samples are retained as Actions artifacts +for seven days on successful and failed runs. Samples are written to the output +directory explicitly so the list reporter cannot discard in-memory attachments. +After a successful build and Chromium installation, browser checks still run if +unit tests fail. Package verification also runs after a successful build even if +an earlier test suite failed. Each failure still makes the job fail; this keeps +independent failures visible in one run instead of masking later suites. +Linux additionally installs Chromium system dependencies. Every platform runs +the browser and package suites. This coverage declaration does not establish a passing run; platform and visual-baseline failures remain visible and require diagnosis rather than relaxed assertions. +Hosted macOS sets `WEBUI_BROWSER_HEADED=1` for the browser suite and runs full +Chromium in a window. Native blank-page controls reproduced headless frame-source +stalls without the WebUI; windowed mode improves pacing but does not eliminate +hosted-runner pauses. Streaming frame p95 is compared diagnostically with the same +page's idle samples before and after streaming, recording whether it exceeds idle +p95 plus 50 ms. The frame gate requires main-thread CPU p95 between consecutive +animation callbacks to stay below 50 ms, capturing cumulative work across tasks. +Raw frame gaps, timers and tasks are retained for investigation. +Application execution retains the absolute 50 ms budget: lightweight Chromium tracing +measures main-thread task CPU time, adding browser-recorded Long Animation Frame +script pauses to their owning tasks to reject synchronous JavaScript waits as well. +Raw script and LongTask wall durations +remain diagnostic because they can include hosted-runner descheduling. Missing timing +capabilities or required task/frame CPU samples fail explicitly. Real idle, busy-script, +forced-layout and synchronous-wait controls verify attribution in the browser suite. +Other interaction budgets are unchanged. +Linux, Windows and local runs remain headless by default. To reproduce +the macOS CI browser mode locally, run `WEBUI_BROWSER_HEADED=1 pnpm test:webui-browser` +after building the client and installing Chromium. + ## Active and archived workflows Only `webui-ci.yml` remains in `.github/workflows/`. The following inherited @@ -37,8 +63,8 @@ Restoring a legacy YAML file to `.github/workflows/` would restore its triggers; the workflow-contract test rejects additional active YAML files. Dependabot can still create dependency-update PRs; those PRs run WebUI CI. -The local `pnpm verify`, its profiles, all existing gate scripts and package -commands are unchanged. Run them locally when broader runtime, CLI, release or +The CI scope does not remove steps from local `pnpm verify` profiles or retire +local package commands. Run them locally when broader runtime, CLI, release or security validation is needed. A green WebUI CI run does not establish those broader checks. The previously reported repository-history scan findings are outside this CI scope and have not been remediated by disabling Release audit. diff --git a/package.json b/package.json index 9c7572ad2..08b098b7e 100644 --- a/package.json +++ b/package.json @@ -55,6 +55,7 @@ "@typescript-eslint/parser": "7.18.0", "@typescript/native-preview": "7.0.0-dev.20260707.2", "axe-core": "4.14.0", + "cross-spawn": "7.0.6", "esbuild": "0.28.2", "eslint": "8.57.1", "eslint-config-airbnb-base": "15.0.0", diff --git a/packages/browser-extension/scripts/build.mjs b/packages/browser-extension/scripts/build.mjs index 8b679b938..0683c6c23 100644 --- a/packages/browser-extension/scripts/build.mjs +++ b/packages/browser-extension/scripts/build.mjs @@ -130,6 +130,11 @@ if (store) { // store, so the two artifacts cannot be confused for one another. const archive = join(packageRoot, `dist-${store}.zip`); await rm(archive, { force: true }); - await run("zip", ["-r", "-q", archive, "."], { cwd: outDir }); + if (process.platform === "win32") { + if (!process.env.SystemRoot) throw new Error("Windows SystemRoot is required to locate the ZIP archive tool."); + await run(join(process.env.SystemRoot, "System32", "tar.exe"), ["-a", "-c", "-f", archive, "."], { cwd: outDir }); + } else { + await run("zip", ["-r", "-q", archive, "."], { cwd: outDir }); + } process.stdout.write(`Packaged the ${store} build as ${archive}\n`); } diff --git a/packages/local-runtime-v2/src/service/miniapp/process/node-runtime/owner-lease.ts b/packages/local-runtime-v2/src/service/miniapp/process/node-runtime/owner-lease.ts index 0b4abdd0a..1fe83b5e8 100644 --- a/packages/local-runtime-v2/src/service/miniapp/process/node-runtime/owner-lease.ts +++ b/packages/local-runtime-v2/src/service/miniapp/process/node-runtime/owner-lease.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto'; -import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { lstat, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'; import net from 'node:net'; import path from 'node:path'; @@ -33,7 +33,7 @@ const SOCKET_FILE = 'owner.sock'; const RECORD_FILE = 'owner.json'; const WINDOWS_PIPE_PREFIX = '\\\\.\\pipe\\mcode-miniapp-owner-'; -/** A socket file on POSIX, a named pipe on Windows — named from the plugin id, never from the directory. */ +/** A directory-scoped socket on POSIX, a plugin-scoped named pipe on Windows. */ export function resolveMiniAppOwnerEndpoint( pluginDataDir: string, pluginId: string, @@ -43,7 +43,11 @@ export function resolveMiniAppOwnerEndpoint( const digest = createHash('sha256').update(pluginId).digest('hex').slice(0, 16); return `${WINDOWS_PIPE_PREFIX}${digest}`; } - return path.join(pluginDataDir, SOCKET_FILE); + const endpoint = path.join(pluginDataDir, SOCKET_FILE); + // macOS limits sockaddr_un.sun_path to 104 bytes, including its terminator. + if (Buffer.byteLength(endpoint) < 104) return endpoint; + const digest = createHash('sha256').update(path.resolve(pluginDataDir)).digest('hex').slice(0, 32); + return path.join('/tmp', `mcode-miniapp-owner-${process.getuid!()}`, `${digest}.sock`); } /** @@ -59,8 +63,17 @@ export async function acquireMiniAppOwner( ): Promise { const nowMs = input.nowMs ?? Date.now; const platform = input.platform ?? process.platform; - const endpoint = resolveMiniAppOwnerEndpoint(input.pluginDataDir, input.pluginId, platform); if (platform !== 'win32') await mkdir(input.pluginDataDir, { recursive: true }); + const dataDir = platform === 'win32' ? input.pluginDataDir : await realpath(input.pluginDataDir); + const endpoint = resolveMiniAppOwnerEndpoint(dataDir, input.pluginId, platform); + if (platform !== 'win32' && path.dirname(endpoint) !== dataDir) { + const socketDirectory = path.dirname(endpoint); + await mkdir(socketDirectory, { recursive: true, mode: 0o700 }); + const metadata = await lstat(socketDirectory); + if (!metadata.isDirectory() || metadata.uid !== process.getuid!() || (metadata.mode & 0o077) !== 0) { + throw new Error(`Mini App owner socket directory is not private: ${socketDirectory}`); + } + } for (let attempt = 0; attempt < 2; attempt += 1) { const server = net.createServer((socket) => socket.destroy()); diff --git a/packages/local-runtime-v2/test/unit/miniapp/owner-lease.test.ts b/packages/local-runtime-v2/test/unit/miniapp/owner-lease.test.ts index 93b7179fd..b0ca2fb24 100644 --- a/packages/local-runtime-v2/test/unit/miniapp/owner-lease.test.ts +++ b/packages/local-runtime-v2/test/unit/miniapp/owner-lease.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, rm } from 'node:fs/promises'; +import { mkdtemp, rm, symlink } from 'node:fs/promises'; import net from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -39,6 +39,19 @@ async function acquire(dir: string, client = 'webui'): Promise { + it.skipIf(process.platform === 'win32')('holds long data paths without truncating or sharing their sockets', async () => { + const root = await pluginDataDir(); + const first = join(root, 'a'.repeat(120)); + const second = join(root, 'b'.repeat(120)); + expect(Buffer.byteLength(resolveMiniAppOwnerEndpoint(first, 'fixture.miniapp'))).toBeLessThan(104); + expect((await acquire(first, 'desktop')).kind).toBe('acquired'); + expect(await acquire(first)).toMatchObject({ kind: 'held', owner: { client: 'desktop' } }); + const alias = join(root, 'alias'); + await symlink(first, alias); + expect(await acquire(alias)).toMatchObject({ kind: 'held', owner: { client: 'desktop' } }); + expect((await acquire(second)).kind).toBe('acquired'); + }); + it('acquires an unowned Mini App and can take it again after releasing', async () => { const dir = await pluginDataDir(); diff --git a/packages/webui/docs/architecture/module-map.md b/packages/webui/docs/architecture/module-map.md index 514193fa9..2e84c8254 100644 --- a/packages/webui/docs/architecture/module-map.md +++ b/packages/webui/docs/architecture/module-map.md @@ -49,6 +49,7 @@ host management, the projects rooted on a host and the remote terminal. | `runtime/auth-session.ts`, `runtime/auth-context.ts` | The one OAuth core with its lease and refresh timer, and the per-request auth context. | | `runtime/account-login.ts`, `runtime/check-in.ts`, `runtime/usage-quota.ts`, `runtime/usage-quota-projection.ts`, `runtime/reset-card-projection.ts`, `runtime/signing.ts` | Account login, daily check-in, the account-billing client (the quota, the credit fallback and the reset cards) and its two pure projections, request signing. | | `runtime/terminal.ts` | The terminal process manager. One per WebUI service, not a host-wide singleton. | +| `runtime/native-pty.ts` | Shared native PTY loading for local and SSH terminals. Restores the macOS spawn-helper execute bits missing from node-pty 1.1.0 prebuilds; a missing helper or failed permission change remains an explicit error. | | `runtime/remote-control/` | The phone pairing link: the vendored bridge, the pairing client and its credential source, the owner, the command router and the global-event source. See [`runtime/remote-control.md`](../runtime/remote-control.md). | | `runtime/mcode-tools.ts`, `runtime/mcode-tools-environment.ts`, `runtime/mcode-tools-entry.ts` | The mcode-tools broker, the child-process environment projection and the embedded entry loader. | | `runtime/workspace-archive.ts` + `runtime/workspace-archive/` | Archive listing and extraction: `zip-adapter.ts` and `tar-adapter.ts` over `archive-policy.ts`, `archive-listing.ts`, `archive-filesystem.ts`, `archive-types.ts`. | diff --git a/packages/webui/docs/verification/browser-suite.md b/packages/webui/docs/verification/browser-suite.md index 35b10ac14..82f13e458 100644 --- a/packages/webui/docs/verification/browser-suite.md +++ b/packages/webui/docs/verification/browser-suite.md @@ -59,6 +59,13 @@ and runs in the browser gate, after the client build and Chromium installation. Live and completed turn visibility is asserted from controlled stream frames while the indicator remains unmodified. +Live assistant Markdown coalesces arriving chunks at the next animation frame, retaining the latest +complete source without restarting a pending frame. Static content, replacements and completion +render immediately. The streaming responsiveness cases keep the existing 50 ms jank and long-task +budgets; a separate continuous-stream case verifies visible progress before completion and retains +the final chunk when `[DONE]` arrives in the same task. These are built-client fixture checks, not +measurements of a live model provider. + The composer spec selects `/compact` from the slash palette, adds an instruction, and asserts the `runCommand` request body at the fixture transport. This checks built-client behavior only; a production command-runner journey is not currently covered by `agent-transcript.test.ts` or another @@ -136,7 +143,7 @@ The shell case asserts that built image assets finish loading successfully. The tests also assert relevant DOM state and viewport geometry; screenshots are not the sole oracle. These are deterministic fixture renders with synthetic session content, not user workspace or account data. Review image diffs on the pinned -Linux Chromium revision before accepting baseline changes. +Chromium revision on the recorded platform before accepting baseline changes. `pnpm test:webui-browser` uses the already installed Playwright Chromium directly. It does not download a browser or install system packages. On a new machine, run `pnpm install:webui-browsers` @@ -154,15 +161,71 @@ pnpm build:webui pnpm test:webui-browser ``` -The screenshots are comparable across machines, because the gate does not read the host's fonts. -The font files under `packages/webui/test/browser/fonts/` are committed to this repository, and -`scripts/lib/webui-font-environment.mjs` writes a fontconfig that exposes only those files. The -browser is launched with `FONTCONFIG_FILE` pointing at it, so every name in the client's font -stack resolves to a committed face. The fontconfig also selects grayscale antialiasing, because -LCD subpixel rendering colours the glyph edges and that fringe depends on the display's subpixel -layout and on the host's fontconfig version. A machine with no CJK font installed and a machine -with a full set of them therefore render the same bytes: the recorded baseline is a property of -this repository, not of the runner. +The font files under `packages/webui/test/browser/fonts/` are committed to this repository. +The fixture server exposes those files as web fonts under the client's first sans and monospace +family names, and `openApp` waits for both faces and the initial layout observation before a test +measures geometry. This also pins macOS and Windows, whose font engines do not use fontconfig. +On Linux, `scripts/lib/webui-font-environment.mjs` additionally sets `FONTCONFIG_FILE` to expose +only the committed files and selects grayscale antialiasing. Native rasterization can still differ, +so screenshot baselines are platform-specific; review actual native captures before adding them. + +Chromium uses its normal frame scheduling and graphics path. Live Markdown coalescing +is measured at the browser's paint opportunities rather than an artificially unbounded frame rate. +Application work retains an absolute 50 ms budget. Frame pacing diagnostics compare active +p95 with the larger same-page idle p95 before/after streaming plus 50 ms. The comparison and +whether it exceeds that budget are saved in `frame-budget-comparison.json`; raw wall-clock +frame intervals do not decide application acceptance. The frame gate uses CPU timestamps on +consecutive animation-callback trace markers: main-thread CPU p95 per frame must stay below +50 ms. This includes cumulative work across small tasks without charging the application for +time descheduled by the runner. Raw maximum gaps, 50/100 ms outlier counts, +timer delays and every frame/long-task sample remain recorded in `stream-performance-raw.json`. +Raw task wall durations remain diagnostic. Lightweight CDP tracing (`toplevel,blink.user_timing`) +records root tasks intersecting measurement markers on the page's main thread; any task with +at least 50 ms of thread CPU time fails. Long Animation Frame `pauseDuration` is mapped +to the owning root task by the measurement marker's page/trace clock offset. Task CPU plus +its recorded synchronous pauses also fails at 50 ms, retaining coverage of JavaScript +blocking that uses little CPU. Script wall duration remains diagnostic because it also +includes time descheduled by the runner. Missing pause attribution or clock mapping fails. +This distinguishes actual execution from time descheduled by the runner without exempting +expensive layout or painting. Missing markers, CPU timings or observer support fail explicitly. +Tasks shorter than 50 ms without a CPU field use their wall duration as a conservative upper +bound; at least one real CPU sample is required, and an over-budget wall task with missing CPU +timing fails. The JSON evidence retains both task wall/CPU timings and script attribution. +Real browser controls require an idle page to pass, 80 ms busy-script/forced-layout work to fail, +and a synchronous request delayed by 120 ms to fail even when it uses little CPU. +An empty sample set fails. Both conversation sizes and rendered-content assertions remain intact. +Idle and active loops sample callback arrival with the same `performance.now()` clock. The active +window includes two paint opportunities after the final text reaches the DOM. +The plugin scroll case waits for populated rows and the hover action's layout stability before +recording its pre-wheel pinned geometry. + +Hosted macOS CI sets `WEBUI_BROWSER_HEADED=1` and selects full Chromium in a window; +Linux, Windows and local runs stay headless by default. Blank-page controls on native macOS +reproduced long headless frame intervals without any client work. On the same image and browser +build, windowed mode improved frame pacing, but repeated runs still exposed isolated scheduler +pauses. Windowed mode therefore complements the idle calibration rather than proving stability +on its own. Use the same environment flag locally to reproduce +the macOS CI mode; no frame-rate override or software-compositing override is used. + +Related launcher boxes are read in one DOM snapshot, and hover-dependent styles are polled for +their exact final values. The long-line diff case scrolls the contained viewport into view and +waits for real overflow before checking actual horizontal scrolling; DOM text alone is insufficient. + +Performance cases disable tracing during measurement and capture screenshots only on failure: +Chromium CPU profiles showed Playwright's injected snapshot walker inside the drag measurement, +and trace screenshots also occupy the renderer/compositor. The drag still runs through real pointer +input, waits two frames after pointer release, and retains the 50 ms long-task budget. Locator-based +geometry assertions run after the observer stops, so their injected queries are not charged to the +application. Raw task durations are attached as `workspace-drag-long-tasks.json`. +The review must paint its initial layout before the toolbar measurement begins. The panel's +`--webui-workspace-width` is a non-inherited registered property: it controls the panel's own +overlap margin, and inheriting each pointer sample into thousands of diff descendants caused +unnecessary style recalculation. The browser regression checks both actual panel resizing and +the child's independent default value. +Disclosure cases capture all coupled CSS transitions, +inspect their interpolated midpoint and +finish it before checking the final geometry, instead of racing a fixed delay against driver latency. +Tests that deliberately freeze the browser clock advance it explicitly for the initial layout frames. That also removes the trap the previous arrangement carried. The gate used to depend on the CJK fonts that `playwright install --with-deps chromium` pulled in, so the installed set changed with diff --git a/packages/webui/src/client/features/plugins/ui/PluginItemDialog.tsx b/packages/webui/src/client/features/plugins/ui/PluginItemDialog.tsx index 910b14c74..949a86886 100644 --- a/packages/webui/src/client/features/plugins/ui/PluginItemDialog.tsx +++ b/packages/webui/src/client/features/plugins/ui/PluginItemDialog.tsx @@ -56,6 +56,7 @@ export function PluginItemDialog({ : "配置 MiniMax Code 如何连接到该项"} onClose={onClose} dismissOnEscape + dismissOnBackdrop width="standard" portalTarget={portalTarget} > diff --git a/packages/webui/src/client/features/transcript/ui/AssistantBody.tsx b/packages/webui/src/client/features/transcript/ui/AssistantBody.tsx index f13f69319..d6e3a9d4d 100644 --- a/packages/webui/src/client/features/transcript/ui/AssistantBody.tsx +++ b/packages/webui/src/client/features/transcript/ui/AssistantBody.tsx @@ -90,7 +90,7 @@ function renderActivityParts( } index = cursor - 1; } else if (part.type === "text") { - rows.push({ messageId, element:
}); + rows.push({ messageId, element:
}); } else if (part.type === "cognitive" || part.type === "compaction") { rows.push({ messageId, element: }); } else if (part.type === "delegation") { @@ -345,7 +345,7 @@ export function WebuiAssistantBody({ children={renderProcessContent} collapsedContent={(expanded) => !expanded && (primaryAnswerPart || deliveredEntries.length > 0) ? - {primaryAnswerPart ?
: null} + {primaryAnswerPart ?
: null} {deliveredEntries.map((entry, index) => )}
: null} @@ -353,7 +353,7 @@ export function WebuiAssistantBody({ ) : null} {primaryAnswerPart && !hasExpandableProcessContent ? (
- +
) : processTextParts.length > 0 ? null : answers.map((answer, index) => (
- +
))} {/* The diff card sits after the assistant body so the diff --git a/packages/webui/src/client/features/transcript/ui/markdown.public.tsx b/packages/webui/src/client/features/transcript/ui/markdown.public.tsx index ae2ecd13e..3e4b6fa2d 100644 --- a/packages/webui/src/client/features/transcript/ui/markdown.public.tsx +++ b/packages/webui/src/client/features/transcript/ui/markdown.public.tsx @@ -524,6 +524,7 @@ interface WebuiMarkdownBlockCache { interface WebuiMarkdownViewProps { readonly source: string; + readonly streaming?: boolean; readonly onOpenFile?: (reference: NonNullable>) => void; readonly workspaceDir?: string; } @@ -555,10 +556,37 @@ function WebuiMarkdownView({ source, onOpenFile, workspaceDir }: WebuiMarkdownVi ); } -export const WebuiMarkdown = memo( +const WebuiMarkdownContent = memo( WebuiMarkdownView, (previous, next) => previous.source === next.source && previous.workspaceDir === next.workspaceDir && previous.onOpenFile === next.onOpenFile, ); + +export const WebuiMarkdown = memo(function WebuiMarkdown({ streaming = false, ...props }: WebuiMarkdownViewProps): ReactElement { + const [paintedSource, setPaintedSource] = useState(props.source); + const latestSource = useRef(props.source); + const pendingFrame = useRef(); + latestSource.current = props.source; + useEffect(() => { + if (!streaming) { + if (pendingFrame.current !== undefined) cancelAnimationFrame(pendingFrame.current); + pendingFrame.current = undefined; + setPaintedSource(props.source); + } else if (pendingFrame.current === undefined) { + // 同一绘制机会内合并网络分片;新分片不重置待执行帧,持续输出也不会饿死渲染。 + pendingFrame.current = requestAnimationFrame(() => { + pendingFrame.current = undefined; + setPaintedSource(latestSource.current); + }); + } + }, [props.source, streaming]); + useEffect(() => () => { + if (pendingFrame.current !== undefined) cancelAnimationFrame(pendingFrame.current); + pendingFrame.current = undefined; + }, []); + // 完成、替换和截断立即显示权威文本,不等待下一次绘制。 + const source = streaming && props.source.startsWith(paintedSource) ? paintedSource : props.source; + return ; +}); diff --git a/packages/webui/src/client/features/workspace/ui/WorkspaceDiffFileSection.tsx b/packages/webui/src/client/features/workspace/ui/WorkspaceDiffFileSection.tsx index 83f8a3b7c..ffc213777 100644 --- a/packages/webui/src/client/features/workspace/ui/WorkspaceDiffFileSection.tsx +++ b/packages/webui/src/client/features/workspace/ui/WorkspaceDiffFileSection.tsx @@ -44,7 +44,12 @@ function WebuiDiffFileSectionView({ file, selected, loading = false, error, onSe } return highlighted; }, [allLines, language]); - return
+ // Keep offscreen file headings and their intrinsic-width diff layout out of + // panel resize work. Preserve the estimated scroll extent until first paint. + const offscreenSize = expanded && lines.length > 0 && !loading && !error + ? { contentVisibility: "auto" as const, containIntrinsicSize: `auto ${40 + lines.length * 19.8}px` } + : undefined; + return
{ onSelect?.(file.file); setExpanded((value) => !value); }}> diff --git a/packages/webui/src/client/features/workspace/ui/workspace.css b/packages/webui/src/client/features/workspace/ui/workspace.css index 39e8e9202..d50f8a131 100644 --- a/packages/webui/src/client/features/workspace/ui/workspace.css +++ b/packages/webui/src/client/features/workspace/ui/workspace.css @@ -1,4 +1,11 @@ /* workspace — moved out of styles/shell.css; rules kept in their original relative order. */ +/* The panel owns this geometry; descendants must not recalculate styles on every drag sample. */ +@property --webui-workspace-width { + syntax: ""; + inherits: false; + initial-value: 50%; +} + @layer components { /* The project row under the composer. It is a LAYOUT element only — the @@ -307,7 +314,7 @@ .webui-turn-review-file-heading .webui-diff-file-icon { width: 18px; height: 18px; } .webui-turn-review-file-heading .webui-diff-file-icon .webui-workspace-filetype-badge { width: 18px; height: 18px; } .webui-turn-review-file-path { min-width: 0; flex: 1; overflow: hidden; font-size: var(--size_14); text-overflow: ellipsis; white-space: nowrap; } - .webui-turn-review-code { width: max-content; min-width: 100%; margin: 0; padding: 0; overflow: auto; background: var(--bg_default_primary); font-size: var(--size_12); line-height: 1.65; white-space: pre; overflow-wrap: normal; } + .webui-turn-review-code { width: 100%; min-width: 100%; margin: 0; padding: 0; overflow: auto; background: var(--bg_default_primary); font-size: var(--size_12); line-height: 1.65; white-space: pre; overflow-wrap: normal; } .webui-turn-review-code code { display: block; min-width: max-content; } .webui-turn-review-line { display: grid; min-width: max-content; grid-template-columns: 48px 48px 20px minmax(0, 1fr); } .webui-turn-review-code--split { width: 100%; } diff --git a/packages/webui/src/client/platform/browser-dom.ts b/packages/webui/src/client/platform/browser-dom.ts index c4c7bd3dc..d741be11c 100644 --- a/packages/webui/src/client/platform/browser-dom.ts +++ b/packages/webui/src/client/platform/browser-dom.ts @@ -60,7 +60,11 @@ function trackOutsideModalFocus(ownerDocument: Document): HTMLElement { ownerDocument.addEventListener("focusin", (event) => { const target = event.target; if (!(target instanceof HTMLElement)) return; - if (target.closest("[data-webui-dialog-mask], .webui-settings-mask, [data-overlay-layer]")) return; + // A dropdown's trigger wrapper is also an overlay layer. Its surviving + // trigger is a valid return target; only the popup itself is excluded. + if (target.closest("[data-webui-dialog-mask], .webui-dialog-mask, .webui-settings-mask, .webui-dropdown-popup")) return; + const layer = target.closest("[data-overlay-layer]"); + if (layer && !layer.hasAttribute("data-webui-dropdown")) return; if (target.closest(LIVE_SURFACE_SELECTOR)) return; recordOutsideModalFocus(ownerDocument, target); }, true); diff --git a/packages/webui/src/client/ui/Dropdown.tsx b/packages/webui/src/client/ui/Dropdown.tsx index 4726eeabc..4718062f0 100644 --- a/packages/webui/src/client/ui/Dropdown.tsx +++ b/packages/webui/src/client/ui/Dropdown.tsx @@ -531,7 +531,12 @@ export function WebuiDropdown({ const handleTriggerClick = useCallback(() => { if (open) onClose(); - else onOpen(); + else { + // Pointer activation does not focus buttons consistently across systems. + // Record the surviving trigger before a menu opens a modal and unmounts. + triggerRef.current?.focus(); + onOpen(); + } }, [onClose, onOpen, open]); const handleTriggerKeyDown = useCallback( diff --git a/packages/webui/src/client/ui/dialog.tsx b/packages/webui/src/client/ui/dialog.tsx index 3770cfb6a..f9d1ed5dd 100644 --- a/packages/webui/src/client/ui/dialog.tsx +++ b/packages/webui/src/client/ui/dialog.tsx @@ -9,7 +9,7 @@ import { useDialogLayer } from "./overlay-listeners.js"; import { ManagedOverlayBoundary } from "./overlay-listeners.js"; import { useOverlayCoordinator } from "./overlay-coordinator.js"; import { WebuiIconButton } from "./button.js"; -import { WebuiMotion, WebuiPage, WebuiSkeletonProjection } from "./page.js"; +import { isWebuiMotionExitAnimation, WebuiMotion, WebuiPage, WebuiSkeletonProjection } from "./page.js"; const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect; @@ -205,7 +205,7 @@ export function WebuiDialog({ if (!present || !portalTarget) return null; const finishExit = (event: React.AnimationEvent) => { - if (event.currentTarget !== event.target || motionState !== "exit" || open) return; + if (event.currentTarget !== event.target || !isWebuiMotionExitAnimation(event.animationName, "surface") || motionState !== "exit" || open) return; setPresent(false); onExitComplete?.(); }; diff --git a/packages/webui/src/client/ui/page.tsx b/packages/webui/src/client/ui/page.tsx index 132b2fe22..48031a088 100644 --- a/packages/webui/src/client/ui/page.tsx +++ b/packages/webui/src/client/ui/page.tsx @@ -120,7 +120,8 @@ export const WebuiPage = forwardRef( if ( event.target === event.currentTarget && exiting && - hasExitAnimation + hasExitAnimation && + isWebuiMotionExitAnimation(event.animationName, motion?.kind) ) { setMounted(false); onExitComplete?.(); @@ -268,6 +269,12 @@ export function WebuiMotionSlot({ }); } +/** Ignore a previous entrance finishing after a surface has begun leaving. */ +export function isWebuiMotionExitAnimation(animationName: string, kind: WebuiMotionKind | undefined): boolean { + if (kind === "panel") return animationName === "webui-motion-panel-exit"; + return (kind === "surface" || kind === "card") && animationName === "webui-motion-surface-exit"; +} + export interface WebuiMotionProps extends HTMLAttributes { readonly inert?: boolean; readonly as?: "article" | "aside" | "div" | "section" | "span"; diff --git a/packages/webui/src/runtime/native-pty.ts b/packages/webui/src/runtime/native-pty.ts new file mode 100644 index 000000000..68096a740 --- /dev/null +++ b/packages/webui/src/runtime/native-pty.ts @@ -0,0 +1,28 @@ +import { chmodSync, existsSync, statSync } from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; + +const require = createRequire(import.meta.url); + +/** node-pty 1.1.0 ships its macOS prebuilt spawn-helper without execute bits. */ +export function prepareWebuiPtyHelper( + moduleRoot: string, + platform: NodeJS.Platform = process.platform, + arch: string = process.arch, +): void { + if (platform !== "darwin") return; + const helpers = [ + path.join(moduleRoot, "build/Release/spawn-helper"), + path.join(moduleRoot, `prebuilds/darwin-${arch}/spawn-helper`), + ].filter((filename) => existsSync(filename)); + if (helpers.length === 0) throw new Error(`node-pty spawn-helper is missing: ${moduleRoot}`); + for (const filename of helpers) { + const mode = statSync(filename).mode; + if ((mode & 0o111) !== 0o111) chmodSync(filename, mode | 0o111); + } +} + +export function loadWebuiPty(): typeof import("node-pty") { + prepareWebuiPtyHelper(path.dirname(require.resolve("node-pty/package.json"))); + return require("node-pty") as typeof import("node-pty"); +} diff --git a/packages/webui/src/runtime/ssh/transport.ts b/packages/webui/src/runtime/ssh/transport.ts index e3e8a742f..231b1b97e 100644 --- a/packages/webui/src/runtime/ssh/transport.ts +++ b/packages/webui/src/runtime/ssh/transport.ts @@ -11,9 +11,7 @@ // window size to the remote pseudo-terminal it allocates. A remote pty whose size cannot be // changed is a terminal that is lying about its size, so the local side is a real pty too. import { spawn } from "node:child_process"; -import { createRequire } from "node:module"; - -const require = createRequire(import.meta.url); +import { loadWebuiPty } from "../native-pty.js"; type Pty = { readonly pid: number; @@ -106,7 +104,7 @@ function stopProcessTree(child: { pid?: number; kill(signal?: NodeJS.Signals): b * a build without it can still serve the command surface. */ export function createSystemSshTransport( - loadPty: () => PtyModule = () => require("node-pty") as PtyModule, + loadPty: () => PtyModule = loadWebuiPty, ): SshTransport { return { run(args, options = {}) { diff --git a/packages/webui/src/runtime/terminal.ts b/packages/webui/src/runtime/terminal.ts index 0135d0ddf..7470c2718 100644 --- a/packages/webui/src/runtime/terminal.ts +++ b/packages/webui/src/runtime/terminal.ts @@ -1,18 +1,17 @@ import os from "node:os"; import process from "node:process"; -import { createRequire } from "node:module"; +import { loadWebuiPty } from "./native-pty.js"; import type { WebuiTerminalProcessPort } from "./port.js"; type Pty = { readonly pid: number; write(data: string): void; resize(cols: number, rows: number): void; kill(): void; onData(listener: (data: string) => void): void; onExit(listener: () => void): void }; type PtyModule = { spawn(shell: string, args: string[], options: Record): Pty }; -const require = createRequire(import.meta.url); type Terminal = { readonly id: string; readonly workspaceTabId?: string; readonly pty: Pty; readonly output: string[]; readonly listeners: Set<(data: string) => void>; exited: boolean }; export class WebuiTerminalManager implements WebuiTerminalProcessPort { private readonly terminals = new Map(); - constructor(private readonly loadPty: () => PtyModule = () => require("node-pty") as PtyModule) {} + constructor(private readonly loadPty: () => PtyModule = loadWebuiPty) {} create(workspaceDir: string, cols = 80, rows = 24, workspaceTabId?: string) { if (this.terminals.size >= 5) throw new Error("最多可以打开 5 个终端"); const id = `terminal-${crypto.randomUUID()}`; diff --git a/packages/webui/src/server/browser-bridge/extension-package.ts b/packages/webui/src/server/browser-bridge/extension-package.ts index 26914c136..68f6ce345 100644 --- a/packages/webui/src/server/browser-bridge/extension-package.ts +++ b/packages/webui/src/server/browser-bridge/extension-package.ts @@ -59,7 +59,7 @@ export class WebuiBrowserExtensionPackage { const version = await readExtensionVersion(built); const fileName = `minimax-code-browser-extension-${version}.zip`; const bytes = await zipDirectory(built, fileName, this.options.scratchDir); - return bytes ? { fileName, bytes } : undefined; + return { fileName, bytes }; } /** The directory holding the built extension, after making sure it is current. */ @@ -118,7 +118,7 @@ async function zipDirectory( directory: string, fileName: string, scratchDir: string | undefined, -): Promise { +): Promise { // The scratch directory is the host's, and a host may hand us one it has not // created yet: a packaged host derives it from its data directory, which on a // fresh machine does not exist until something writes there. Creating it here @@ -128,8 +128,17 @@ async function zipDirectory( const scratch = await mkdtemp(path.join(scratchParent, "webui-extension-")); const archivePath = path.join(scratch, fileName); try { - const code = await run("zip", ["-r", "-q", archivePath, "."], directory); - if (code !== 0) return undefined; + // Windows ships libarchive's bsdtar, including ZIP creation; POSIX hosts + // use their existing zip tool. Both archive the built directory's contents. + let code: number; + if (process.platform === "win32") { + const systemRoot = process.env.SystemRoot; + if (!systemRoot) throw new Error("Windows SystemRoot is required to locate the ZIP archive tool."); + code = await run(path.join(systemRoot, "System32", "tar.exe"), ["-a", "-c", "-f", archivePath, "."], directory); + } else { + code = await run("zip", ["-r", "-q", archivePath, "."], directory); + } + if (code !== 0) throw new Error(`The browser extension archive failed (exit ${code}).`); return await readFile(archivePath); } finally { await rm(scratch, { recursive: true, force: true }); diff --git a/packages/webui/test/browser/acceptance-record.ts b/packages/webui/test/browser/acceptance-record.ts index 54a41ee95..f91eb94e7 100644 --- a/packages/webui/test/browser/acceptance-record.ts +++ b/packages/webui/test/browser/acceptance-record.ts @@ -21,6 +21,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { release } from "node:os"; import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; /** What one acceptance case observed. */ export interface AcceptanceObservation { @@ -153,7 +154,7 @@ export interface AcceptanceRecords { * about the process. */ export function acceptanceRecordsFor(plan: WebuiAcceptancePlan): AcceptanceRecords { - const recordDir = resolve(new URL(PLAN_DIRECTORIES[plan], import.meta.url).pathname); + const recordDir = fileURLToPath(new URL(PLAN_DIRECTORIES[plan], import.meta.url)); /** The suites of this plan that have written a record in this process. */ const started = new Set(); diff --git a/packages/webui/test/browser/account-login.spec.mjs b/packages/webui/test/browser/account-login.spec.mjs index 27d1b0d57..868fba1f9 100644 --- a/packages/webui/test/browser/account-login.spec.mjs +++ b/packages/webui/test/browser/account-login.spec.mjs @@ -156,9 +156,17 @@ test("usage loading applies the shared pulse animation to each skeleton shape", await page.evaluate(() => window.__fixture.resolveAllPending("getUsageQuota", {}, { signedIn: false })); await expect(page.locator('[data-testid="usage-sign-in-button"]')).toBeVisible(); + await popover.evaluate((element) => { + window.__usageExitAnimation = undefined; + const observer = new MutationObserver(() => { + if (element.getAttribute("data-webui-motion-state") !== "exit") return; + window.__usageExitAnimation = getComputedStyle(element).animationName; + observer.disconnect(); + }); + observer.observe(element, { attributes: true, attributeFilter: ["data-webui-motion-state"] }); + }); await page.mouse.move(1, 1); - await expect(popover).toHaveAttribute("data-webui-motion-state", "exit"); - expect(await popover.evaluate((element) => getComputedStyle(element).animationName)).toBe("webui-motion-surface-exit"); + await expect.poll(() => page.evaluate(() => window.__usageExitAnimation)).toBe("webui-motion-surface-exit"); await expect(popover).toHaveCount(0, { timeout: 500 }); }); diff --git a/packages/webui/test/browser/application-performance.mjs b/packages/webui/test/browser/application-performance.mjs new file mode 100644 index 000000000..dbcb78ae6 --- /dev/null +++ b/packages/webui/test/browser/application-performance.mjs @@ -0,0 +1,108 @@ +export const APPLICATION_BLOCK_MS = 50; +export const MEASURE_START = "webui-application-measure-start"; +export const MEASURE_END = "webui-application-measure-end"; +export const FRAME_MARK = "webui-application-frame"; + +export function attributeFrameWork(events) { + const start = events.find((event) => event.name === MEASURE_START); + const end = events.find((event) => event.name === MEASURE_END); + if (!start || !end) throw new Error("application frame markers are missing"); + const marks = events.filter( + (event) => + event.name === FRAME_MARK && + event.pid === start.pid && + event.tid === start.tid && + event.ts >= start.ts && + event.ts <= end.ts, + ); + if (marks.length < 2 || marks.some((mark) => !Number.isFinite(mark.tts))) { + throw new Error("application frame CPU timing is unavailable"); + } + return marks.slice(1).map((mark, index) => { + const previous = marks[index]; + if (mark.tts < previous.tts || mark.ts < previous.ts) throw new Error("application frame clock is inconsistent"); + return { wallMs: (mark.ts - previous.ts) / 1000, cpuMs: (mark.tts - previous.tts) / 1000 }; + }); +} + +export function attributeApplicationWork(events, frames) { + const start = events.find((event) => event.name === MEASURE_START); + const end = events.find((event) => event.name === MEASURE_END); + if (!start || !end || end.ts <= start.ts || start.pid !== end.pid || start.tid !== end.tid) { + throw new Error("application measurement markers are missing or inconsistent"); + } + // 只计算该页面主线程中与实际测量窗口相交的根任务,不累加嵌套事件。 + const tasks = events.filter( + (event) => + event.name === "ThreadControllerImpl::RunTask" && + event.ph === "X" && + event.pid === start.pid && + event.tid === start.tid && + event.ts < end.ts && + event.ts + event.dur > start.ts, + ); + // Chromium 的部分微小合成任务没有线程时钟。墙钟已低于预算时用它作保守上界; + // 必须存在真实 CPU 样本,任何达到预算却缺少 CPU 时钟的任务仍明确失败。 + if ( + !tasks.some((task) => Number.isFinite(task.tdur)) || + tasks.some((task) => task.tdur < 0 || (!Number.isFinite(task.tdur) && task.dur >= APPLICATION_BLOCK_MS * 1000)) + ) { + throw new Error("application main-thread CPU timing is unavailable"); + } + const scripts = frames.flatMap((frame) => frame.scripts); + if ( + scripts.some( + (script) => + !Number.isFinite(script.duration) || !Number.isFinite(script.pauseDuration) || script.pauseDuration < 0, + ) + ) { + throw new Error("application script timing is unavailable"); + } + const pauses = new Map(); + for (const script of scripts.filter((script) => script.pauseDuration > 0)) { + if (!Number.isFinite(start.args?.data?.startTime) || !Number.isFinite(script.startTime)) { + throw new Error("application script clock mapping is unavailable"); + } + const scriptStart = start.ts + (script.startTime - start.args.data.startTime) * 1000; + const scriptEnd = scriptStart + script.duration * 1000; + // LoAF 的毫秒精度比 trace 低,允许边界最多 0.2ms 的量化误差。 + const owner = tasks.find((task) => task.ts <= scriptStart + 200 && task.ts + task.dur >= scriptEnd - 200); + if (!owner) throw new Error("application synchronous pause has no owning main-thread task"); + pauses.set(owner, (pauses.get(owner) ?? 0) + script.pauseDuration); + } + const blockedTasks = tasks.map((task) => { + const cpuMs = (Number.isFinite(task.tdur) ? task.tdur : task.dur) / 1000; + const pauseMs = pauses.get(task) ?? 0; + return { task, cpuMs, pauseMs, applicationMs: cpuMs + pauseMs }; + }); + return { + tasks, + scripts, + blockedTasks, + // CPU 覆盖脚本、布局与绘制;浏览器记录的同步暂停另外计入,系统调度停顿保留诊断。 + cpuOverBudget: tasks.filter( + (task) => (Number.isFinite(task.tdur) ? task.tdur : task.dur) / 1000 >= APPLICATION_BLOCK_MS, + ), + blockingOverBudget: blockedTasks.filter((task) => task.applicationMs >= APPLICATION_BLOCK_MS), + }; +} + +export async function startApplicationTrace(page) { + const cdp = await page.context().newCDPSession(page); + const events = []; + cdp.on("Tracing.dataCollected", ({ value }) => events.push(...value)); + await cdp.send("Tracing.start", { + categories: "toplevel,blink.user_timing", + transferMode: "ReportEvents", + }); + return async () => { + try { + const completed = new Promise((resolve) => cdp.once("Tracing.tracingComplete", resolve)); + await cdp.send("Tracing.end"); + await completed; + return events; + } finally { + await cdp.detach(); + } + }; +} diff --git a/packages/webui/test/browser/architecture-acceptance.spec.mjs b/packages/webui/test/browser/architecture-acceptance.spec.mjs index 3b10e73c4..6e7b641e9 100644 --- a/packages/webui/test/browser/architecture-acceptance.spec.mjs +++ b/packages/webui/test/browser/architecture-acceptance.spec.mjs @@ -75,7 +75,7 @@ test("V29 protocol incompatibility is a startup failure before business ingress" test("V28 search-only changes issue zero probes after the initial read", async ({ page }) => { await pausedClock(page); - await openApp(page); + await openApp(page, "#session=A", { advanceClockForLayout: true }); await expect.poll(() => requestCount(page, "getActiveTurn")).toBeGreaterThan(0); await expect(page.locator('[data-webui-session-link="B"]')).toBeVisible(); const before = await requestCount(page, "getActiveTurn"); @@ -100,7 +100,7 @@ test("V31/V34 inspection and authorization progress through a saturated activity window.__fixture.setResponse("getAccountStatus", { email: "before@example.invalid" }); window.__fixture.setModels([{ providerId: "p", modelId: "before", displayName: "Before" }]); }); - await openApp(page); + await openApp(page, "#session=A", { advanceClockForLayout: true }); await expect.poll(() => page.evaluate(() => window.__fixture.pending.filter(r => r.operation === "getActiveTurn").length)).toBe(8); await expect(page.locator("[data-webui-model-selector]").getByRole("button").first()).toBeEnabled(); await expect.poll(() => requestCount(page, "getAccountStatus")).toBeGreaterThan(0); diff --git a/packages/webui/test/browser/browser-bridge-real-external.spec.ts b/packages/webui/test/browser/browser-bridge-real-external.spec.ts index d8cc3129a..8415e00d0 100644 --- a/packages/webui/test/browser/browser-bridge-real-external.spec.ts +++ b/packages/webui/test/browser/browser-bridge-real-external.spec.ts @@ -149,7 +149,11 @@ test.describe("the external bridge, against a real browser and a real page", () await waitForConnected(started.bridge, surface, true); // And the bridge works again: a command against the live tab answers. - const title = await evaluate(provider!, target, "document.title"); + // A restarted worker announces a fresh target generation. + const reconnectedProvider = started.bridge.createProvider(surface); + expect(reconnectedProvider).toBeDefined(); + const reconnectedTarget = await waitForTarget(reconnectedProvider!); + const title = await evaluate(reconnectedProvider!, reconnectedTarget, "document.title"); expect(typeof title).toBe("string"); }, ); diff --git a/packages/webui/test/browser/browser-bridge-real-packaged.spec.ts b/packages/webui/test/browser/browser-bridge-real-packaged.spec.ts index c36dcb99f..cfa531822 100644 --- a/packages/webui/test/browser/browser-bridge-real-packaged.spec.ts +++ b/packages/webui/test/browser/browser-bridge-real-packaged.spec.ts @@ -28,6 +28,7 @@ import { createHash, generateKeyPairSync } from "node:crypto"; import { readFile } from "node:fs/promises"; import { rm } from "node:fs/promises"; import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; import { expect, test } from "@playwright/test"; @@ -48,7 +49,7 @@ const SUITE = "real-packaged"; /** The development build's manifest, for the build comparison. */ const developmentDist = resolve( - new URL("../../../browser-extension/dist/manifest.json", import.meta.url).pathname, + fileURLToPath(new URL("../../../browser-extension/dist/manifest.json", import.meta.url)), ); /** @@ -66,7 +67,7 @@ const STORES = [ /** Where a store build is built. It is not `dist/`: the two cannot share. */ function storeDistOf(store: "chrome" | "edge"): string { return resolve( - new URL(`../../../browser-extension/dist-store-${store}`, import.meta.url).pathname, + fileURLToPath(new URL(`../../../browser-extension/dist-store-${store}`, import.meta.url)), ); } diff --git a/packages/webui/test/browser/browser-workspace.spec.mjs b/packages/webui/test/browser/browser-workspace.spec.mjs index 13ddb62c7..627f84bcc 100644 --- a/packages/webui/test/browser/browser-workspace.spec.mjs +++ b/packages/webui/test/browser/browser-workspace.spec.mjs @@ -133,14 +133,22 @@ test("the browser page fills the workspace body and the workspace edge resizes h await openLauncher(page); const brand = page.getByTestId("workspace-launcher-brand"); - const omnibox = page.locator(".webui-workspace-launcher-omnibox"); - const launcher = page.getByTestId("workspace-launcher"); - const tiles = page.locator(".webui-workspace-launcher-tiles"); await expect(brand).toBeVisible(); - const brandBox = await brand.boundingBox(); - const omniboxBox = await omnibox.boundingBox(); - const launcherBox = await launcher.boundingBox(); - const tilesBox = await tiles.boundingBox(); + // Compare related boxes in one layout snapshot while the panel can resize. + const { brandBox, omniboxBox, launcherBox, tilesBox, contentOffset } = await page.evaluate(() => { + const rect = (selector) => { + const { x, y, width, height } = document.querySelector(selector).getBoundingClientRect(); + return { x, y, width, height }; + }; + const transform = getComputedStyle(document.querySelector(".webui-workspace-launcher-content")).transform; + return { + brandBox: rect(".webui-workspace-launcher-brand"), + omniboxBox: rect(".webui-workspace-launcher-omnibox"), + launcherBox: rect(".webui-workspace-launcher"), + tilesBox: rect(".webui-workspace-launcher-tiles"), + contentOffset: transform === "none" ? 0 : new DOMMatrixReadOnly(transform).m42, + }; + }); expect(Math.abs(brandBox.x + brandBox.width / 2 - (omniboxBox.x + omniboxBox.width / 2))).toBeLessThanOrEqual(1); expect(brandBox.y + brandBox.height).toBeLessThan(omniboxBox.y); // The launcher's content is centred in the panel body and then nudged up by @@ -150,12 +158,6 @@ test("the browser page fills the workspace body and the workspace edge resizes h // first and last children, so the midpoint between them is the content's own // centre -- and the nudge is the content's own transform, so the group is // measured against the line the layout put it on rather than a copy of it. - const contentOffset = await page - .locator(".webui-workspace-launcher-content") - .evaluate((element) => { - const transform = getComputedStyle(element).transform; - return transform === "none" ? 0 : new DOMMatrixReadOnly(transform).m42; - }); const groupCentre = (brandBox.y + tilesBox.y + tilesBox.height) / 2; const launcherCentre = launcherBox.y + launcherBox.height / 2; expect(Math.abs(groupCentre - (launcherCentre + contentOffset))).toBeLessThanOrEqual(1); @@ -169,12 +171,20 @@ test("the browser page fills the workspace body and the workspace edge resizes h // panel: a gesture started before it finished is lost with the old tree. await expect(page.getByTestId("browser-toolbar")).toBeVisible(); - const stage = page.locator(".webui-browser-stage"); - const frame = page.getByTestId("browser-panel-frame"); - const stageBox = await stage.boundingBox(); - const frameBox = await frame.boundingBox(); + await expect(page.getByTestId("browser-panel-frame")).toBeVisible(); + const { stageBox, frameBox } = await page.evaluate(() => { + const rect = (selector) => { + const { width, height } = document.querySelector(selector).getBoundingClientRect(); + return { width, height }; + }; + return { stageBox: rect(".webui-browser-stage"), frameBox: rect('[data-testid="browser-panel-frame"]') }; + }); expect(stageBox).not.toBeNull(); expect(frameBox).not.toBeNull(); + expect(stageBox.width).toBeGreaterThan(0); + expect(stageBox.height).toBeGreaterThan(0); + expect(frameBox.width).toBeGreaterThan(0); + expect(frameBox.height).toBeGreaterThan(0); expect(Math.abs(frameBox.width - stageBox.width)).toBeLessThanOrEqual(1); expect(Math.abs(frameBox.height - stageBox.height)).toBeLessThanOrEqual(1); @@ -192,6 +202,12 @@ test("the browser page fills the workspace body and the workspace edge resizes h .poll(async () => (await panel.boundingBox()).width) .toBeGreaterThan(before.width + 40); const after = await panel.boundingBox(); + const widthScopes = await panel.evaluate((element) => ({ + panel: getComputedStyle(element).getPropertyValue("--webui-workspace-width").trim(), + frame: getComputedStyle(element.querySelector('[data-testid="browser-panel-frame"]')).getPropertyValue("--webui-workspace-width").trim(), + })); + expect(widthScopes.panel).toMatch(/px$/u); + expect(widthScopes.frame).toBe("50%"); await expect(handle).toBeVisible(); await handle.focus(); await page.keyboard.press("ArrowLeft"); diff --git a/packages/webui/test/browser/harness.mjs b/packages/webui/test/browser/harness.mjs index 9c0abbcc1..129142eb3 100644 --- a/packages/webui/test/browser/harness.mjs +++ b/packages/webui/test/browser/harness.mjs @@ -13,10 +13,20 @@ // process happens to answer on the harness port. import { expect, test as base } from "@playwright/test"; +import { mkdir, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; /** The suite's `test`, carrying the harness-server guard for every test. */ export const test = base; +export async function attachJsonEvidence(name, value) { + // list reporter 不落盘 body 附件;显式写入 outputDir 供 CI artifact 保留。 + const path = test.info().outputPath(name); + await mkdir(dirname(path), { recursive: true }); + await writeFile(path, JSON.stringify(value, null, 2)); + await test.info().attach(name, { path, contentType: "application/json" }); +} + /** * The pixel budget for a screenshot comparison, shared by every spec that * compares a baseline. @@ -75,11 +85,63 @@ test.afterEach(async ({ page }) => { expect(await page.evaluate(() => window.__WEBUI_TEST_SERVER_ID__)).toBe(expectedServerId()); }); -export async function openApp(page, hash = "#session=A") { +export async function openApp(page, hash = "#session=A", options = {}) { await page.goto(`/${hash}`); await assertHarnessServer(page); await expect(page.locator("#webui-root")).toBeVisible(); await expect.poll(() => page.evaluate(() => window.__fixture.requests.some((request) => request.operation === "listSessions"))).toBe(true); + const loadedFonts = await page.evaluate(async () => { + const faces = await Promise.all([ + document.fonts.load('14px "HarmonyOS Sans"'), + document.fonts.load('14px "Hack"'), + ]); + await document.fonts.ready; + return faces.map((fonts) => fonts.length); + }); + expect(loadedFonts, "both pinned browser fonts must load before measuring the client").toEqual([1, 1]); + // Register the frame wait before advancing a deliberately frozen test clock. + await page.evaluate(() => { + window.__webuiInitialLayoutReady = new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + }); + if (options.advanceClockForLayout) await page.clock.runFor(34); + await page.evaluate(() => window.__webuiInitialLayoutReady); +} + +/** Capture real CSS interpolation before driver round trips can consume it. */ +export async function pauseNextTransition(locator, property) { + await locator.evaluate((element, property) => { + element.__webuiTestTransition = undefined; + const capture = (event) => { + if (event.target !== element || event.propertyName !== property) return; + element.removeEventListener("transitionrun", capture); + const transitions = element.getAnimations().filter((animation) => animation instanceof CSSTransition); + if (!transitions.some((animation) => animation.transitionProperty === property)) throw new Error(`The ${property} transition did not start`); + // Width and flex-basis jointly determine the used size. Sample every + // coupled property at the same progress instead of freezing only width. + for (const transition of transitions) { + const duration = transition.effect.getTiming().duration; + if (typeof duration !== "number" || duration <= 0) throw new Error("The transition must have a finite positive duration"); + transition.pause(); + transition.currentTime = duration / 2; + } + element.__webuiTestTransition = transitions; + }; + element.addEventListener("transitionrun", capture); + }, property); +} + +export async function transitionMidpointSize(locator, dimension) { + await expect.poll(() => locator.evaluate((element) => Boolean(element.__webuiTestTransition))).toBe(true); + return locator.evaluate((element, dimension) => element.getBoundingClientRect()[dimension], dimension); +} + +export async function finishCapturedTransition(locator) { + await locator.evaluate(async (element) => { + const transition = element.__webuiTestTransition; + if (!transition) throw new Error("No captured transition to finish"); + for (const animation of transition) animation.finish(); + await Promise.all(transition.map((animation) => animation.finished)); + }); } export async function switchSession(page, sessionId) { diff --git a/packages/webui/test/browser/miniapp-panel.spec.mjs b/packages/webui/test/browser/miniapp-panel.spec.mjs index b76787de6..4b7af09fa 100644 --- a/packages/webui/test/browser/miniapp-panel.spec.mjs +++ b/packages/webui/test/browser/miniapp-panel.spec.mjs @@ -245,9 +245,22 @@ test("the left rail 应用 entry opens a frosted task-card panel with loaded ico await expect.poll(() => icon.evaluate((image) => image.getBoundingClientRect().width)).toBeGreaterThan(iconWidthBeforeHover * 1.05); expect(previewBox.width).toBeGreaterThan(105); expect(previewBox.width).toBeLessThan(130); + await launcher.evaluate((element) => { + window.__miniappLauncherExit = undefined; + const observer = new MutationObserver(() => { + if (element.getAttribute("data-webui-motion-state") !== "exit") return; + window.__miniappLauncherExit = { + state: element.getAttribute("data-webui-motion-state"), + animation: getComputedStyle(element).animationName, + }; + observer.disconnect(); + }); + observer.observe(element, { attributes: true, attributeFilter: ["data-webui-motion-state"] }); + }); await launcher.getByRole("button", { name: "关闭应用面板" }).click(); - await expect(launcher).toHaveAttribute("data-webui-motion-state", "exit"); - await expect(launcher).toHaveCSS("animation-name", "webui-motion-surface-exit"); + await expect.poll(() => page.evaluate(() => window.__miniappLauncherExit)).toEqual({ + state: "exit", animation: "webui-motion-surface-exit", + }); await expect(launcher).toHaveCount(0); }); @@ -363,6 +376,8 @@ async function loadedMiniAppFrame(page) { .toBe(MINI_APP_VIEW_URL); const frame = await handle.contentFrame(); if (!frame) throw new Error("the Mini App frame is not attached"); + await frame.waitForLoadState("domcontentloaded"); + await frame.locator("body").waitFor({ state: "attached" }); return frame; } diff --git a/packages/webui/test/browser/native-runtime.spec.mjs b/packages/webui/test/browser/native-runtime.spec.mjs index 0a671bea4..5be9f1513 100644 --- a/packages/webui/test/browser/native-runtime.spec.mjs +++ b/packages/webui/test/browser/native-runtime.spec.mjs @@ -1,7 +1,7 @@ import { fork } from "node:child_process"; import { once } from "node:events"; import path from "node:path"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { expect } from "@playwright/test"; import { test } from "./harness.mjs"; @@ -11,8 +11,8 @@ let ready; let logs = ""; test.beforeAll(async () => { child = fork(path.join(root, "packages/webui/test/browser/support/native-browser-host.ts"), [], { - execArgv: ["--import", path.join(root, "packages/webui/node_modules/tsx/dist/loader.mjs")], - env: { ...process.env, TSX_TSCONFIG_PATH: path.join(root, "tsconfig.standalone.json"), SHELL: "/bin/sh" }, + execArgv: ["--import", pathToFileURL(path.join(root, "packages/webui/node_modules/tsx/dist/loader.mjs")).href], + env: { ...process.env, TSX_TSCONFIG_PATH: path.join(root, "tsconfig.standalone.json"), SHELL: process.platform === "win32" ? "powershell.exe" : "/bin/sh" }, stdio: ["ignore", "pipe", "pipe", "ipc"], }); child.stdout.on("data", (data) => { logs += data; }); @@ -83,7 +83,7 @@ test("V04/V06: native PTYs survive another page, reload and a full five-slot ros await expect(second.locator(".webui-xterm-host")).toBeVisible(); await second.getByRole("button", { name: "关闭面板" }).click(); await second.close(); - await rpc(page, "writeTerminal", { terminalId: terminal.terminalId, data: "printf 'WEBUI_NATIVE_%s\\n' ALIVE\r" }); + await rpc(page, "writeTerminal", { terminalId: terminal.terminalId, data: process.platform === "win32" ? "Write-Output ('WEBUI_NATIVE_' + 'ALIVE')\r" : "printf 'WEBUI_NATIVE_%s\\n' ALIVE\r" }); await expect.poll(async () => (await rpc(page, "listTerminals"))[0].output).toContain("WEBUI_NATIVE_ALIVE"); for (let index = 1; index < 5; index += 1) await rpc(page, "createTerminal", { workspaceDir: ready.workspaceDir }); await page.reload(); @@ -113,7 +113,7 @@ test("V04/V06: native PTYs survive another page, reload and a full five-slot ros const survivors = await rpc(page, "listTerminals"); expect(survivors).toHaveLength(5); const latest = survivors.at(-1); - await rpc(page, "writeTerminal", { terminalId: latest.terminalId, data: "printf 'WEBUI_LATE_%s\\n' ALIVE\r" }); + await rpc(page, "writeTerminal", { terminalId: latest.terminalId, data: process.platform === "win32" ? "Write-Output ('WEBUI_LATE_' + 'ALIVE')\r" : "printf 'WEBUI_LATE_%s\\n' ALIVE\r" }); await expect.poll(async () => (await rpc(page, "listTerminals")).find((entry) => entry.terminalId === latest.terminalId).output) .toContain("WEBUI_LATE_ALIVE"); await rpc(page, "disposeTerminal", { terminalId: latest.terminalId }); diff --git a/packages/webui/test/browser/overlay-coordination.spec.mjs b/packages/webui/test/browser/overlay-coordination.spec.mjs index a42b98825..23f3e7d4c 100644 --- a/packages/webui/test/browser/overlay-coordination.spec.mjs +++ b/packages/webui/test/browser/overlay-coordination.spec.mjs @@ -330,16 +330,18 @@ test("the shared modal frame keeps its header and actions fixed around a scrolli test("closing a modal returns focus to the control that opened it, never the body", async ({ page }) => { // The settings sheet is opened from an entry inside the user menu. Focus has - // to come back to that entry — a keyboard user who closes the sheet resumes - // where they were, not at the top of the document. The platform keeps a short + // to come back to the surviving menu trigger once that entry unmounts — a + // keyboard user resumes where they were. The platform keeps a short // history of what was focused outside a modal precisely because an opener that // lives in a popup is not guaranteed to survive the modal it opened. await page.getByTestId("sidebar-user-menu-trigger").click(); await page.getByTestId("user-menu-settings").click(); await expect(page.getByRole("dialog", { name: "设置" })).toBeVisible(); + await expect(page.getByTestId("user-menu-settings")).toHaveCount(0); await page.keyboard.press("Escape"); await expect(page.getByRole("dialog", { name: "设置" })).toHaveCount(0); + await expect(page.getByTestId("sidebar-user-menu-trigger")).toBeFocused(); const focused = await page.evaluate(() => { const element = document.activeElement; @@ -353,5 +355,5 @@ test("closing a modal returns focus to the control that opened it, never the bod expect(focused.isBody).toBe(false); expect(focused.connected).toBe(true); expect(focused.tag).toBe("BUTTON"); - expect(focused.testId).toBe("user-menu-settings"); + expect(focused.testId).toBe("sidebar-user-menu-trigger"); }); diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs index 6664bfb6f..736787e2a 100644 --- a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs +++ b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs @@ -69,6 +69,10 @@ test("marketplace and management keep vertical categories pinned on the left", a }); expect(managementGeometry.searchWidth).toBeLessThanOrEqual(768); const scrollRegion = layout.locator(".webui-plugin-page-scroll"); + await expect(layout.locator(".webui-plugin-row")).toHaveCount(30); + // Hover waits for the viewport to become stable and may scroll its ancestors + // into view. Capture the pinned position after that preparation, before wheel. + await scrollRegion.hover(); const pinnedGeometry = await layout.evaluate((element) => ({ searchTop: element.querySelector(".webui-plugin-page-controls").getBoundingClientRect().top, scrollHeight: element.querySelector(".webui-plugin-page-scroll").scrollHeight, @@ -78,7 +82,6 @@ test("marketplace and management keep vertical categories pinned on the left", a })); expect(pinnedGeometry.mainHeight).toBe(pinnedGeometry.layoutHeight); expect(pinnedGeometry.scrollHeight).toBeGreaterThan(pinnedGeometry.clientHeight); - await scrollRegion.hover(); await page.mouse.wheel(0, 500); await expect.poll(() => scrollRegion.evaluate((element) => element.scrollTop)).toBeGreaterThan(0); // The controls stay where they were while the list scrolls under them. diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-darwin.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-darwin.png new file mode 100644 index 000000000..35e29586c Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-darwin.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-linux.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-linux.png index 422696fee..12c7f0dc4 100644 Binary files a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-linux.png and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-linux.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-win32.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-win32.png new file mode 100644 index 000000000..12ae65b28 Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-win32.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-darwin.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-darwin.png new file mode 100644 index 000000000..8e68dc911 Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-darwin.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-linux.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-linux.png index fdad26b8a..dd9c2a1b4 100644 Binary files a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-linux.png and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-linux.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-win32.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-win32.png new file mode 100644 index 000000000..18a3517dd Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-win32.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-darwin.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-darwin.png new file mode 100644 index 000000000..6b08e454e Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-darwin.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-linux.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-linux.png index ecbc71934..286e968a5 100644 Binary files a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-linux.png and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-linux.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-win32.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-win32.png new file mode 100644 index 000000000..cde2daa13 Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-win32.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-darwin.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-darwin.png new file mode 100644 index 000000000..6b671ec64 Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-darwin.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-linux.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-linux.png index 3890c53cd..a4dd9709c 100644 Binary files a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-linux.png and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-linux.png differ diff --git a/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-win32.png b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-win32.png new file mode 100644 index 000000000..2c9911910 Binary files /dev/null and b/packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-win32.png differ diff --git a/packages/webui/test/browser/rail-pin.spec.mjs b/packages/webui/test/browser/rail-pin.spec.mjs index 419f1a3bb..95fe68119 100644 --- a/packages/webui/test/browser/rail-pin.spec.mjs +++ b/packages/webui/test/browser/rail-pin.spec.mjs @@ -121,12 +121,17 @@ test("hovering a child session keeps its avatar and clips only the title for the const avatar = child.locator(".webui-agent-avatar"); const title = child.locator(".webui-project-child-session-title"); const action = childRow.locator(".webui-session-row-actions"); - const titleBounds = await title.boundingBox(); - const actionBounds = await action.boundingBox(); await expect(avatar).toBeVisible(); await expect(action.getByRole("button", { name: "子任务 C 更多操作" })).toBeVisible(); expect(await avatar.evaluate((element) => getComputedStyle(element).clipPath)).toBe("none"); - expect(await title.evaluate((element) => getComputedStyle(element).clipPath)).toBe("inset(0px 28px 0px 0px)"); + await expect.poll(() => title.evaluate((element) => getComputedStyle(element).clipPath)).toBe("inset(0px 28px 0px 0px)"); + const { titleBounds, actionBounds } = await childRow.evaluate((row) => { + const rect = (selector) => { + const { x, width } = row.querySelector(selector).getBoundingClientRect(); + return { x, width }; + }; + return { titleBounds: rect(".webui-project-child-session-title"), actionBounds: rect(".webui-session-row-actions") }; + }); expect(titleBounds).not.toBeNull(); expect(actionBounds).not.toBeNull(); expect(titleBounds.x + titleBounds.width - 28).toBeLessThanOrEqual(actionBounds.x); diff --git a/packages/webui/test/browser/real-browser-bridge.ts b/packages/webui/test/browser/real-browser-bridge.ts index 68956f808..3b1518889 100644 --- a/packages/webui/test/browser/real-browser-bridge.ts +++ b/packages/webui/test/browser/real-browser-bridge.ts @@ -10,7 +10,8 @@ import { execFile } from "node:child_process"; import { createServer, type IncomingMessage } from "node:http"; import { mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import type { Duplex } from "node:stream"; @@ -25,7 +26,7 @@ const run = promisify(execFile); // The spec lives at packages/webui/test/browser/, so the repository root is // four levels up from the file's directory. -const repoRoot = resolve(new URL("../../../..", import.meta.url).pathname); +const repoRoot = fileURLToPath(new URL("../../../..", import.meta.url)); const extensionDist = join(repoRoot, "packages/browser-extension/dist"); /** The storage keys the extension keeps its configuration under. */ @@ -77,11 +78,11 @@ export async function buildExtension( readonly publicKey?: string; } = {}, ): Promise { - const args = ["--filter", "@mavis/browser-extension", "build"]; + const args = [join(repoRoot, "packages/browser-extension/scripts/build.mjs")]; if (options.store) args.push("--store", options.store); if (options.out) args.push("--out", options.out); - await run("pnpm", args, { - cwd: repoRoot, + await run(process.execPath, args, { + cwd: join(repoRoot, "packages/browser-extension"), timeout: 120_000, env: options.store && options.publicKey ? { diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-darwin.png new file mode 100644 index 000000000..f18809a64 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-linux.png index 21bd43da2..e21c2d538 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-win32.png new file mode 100644 index 000000000..f1b08da4d Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-darwin.png new file mode 100644 index 000000000..0e2539030 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-linux.png index 0191d0342..5acb97c9d 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-win32.png new file mode 100644 index 000000000..cfbb8a516 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-darwin.png new file mode 100644 index 000000000..3a133df8b Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-linux.png index 357bf4bd3..002952982 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-win32.png new file mode 100644 index 000000000..783ff465f Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-darwin.png new file mode 100644 index 000000000..0b82b709a Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-linux.png index a5f9d682d..27b3d4aee 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-win32.png new file mode 100644 index 000000000..092a79d89 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-darwin.png new file mode 100644 index 000000000..cb3389ed8 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-linux.png index 3a7a021fd..f25f82f15 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-win32.png new file mode 100644 index 000000000..5be273337 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-darwin.png new file mode 100644 index 000000000..01127db76 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-linux.png index a5fbbae41..88335c233 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-win32.png new file mode 100644 index 000000000..07896a895 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-darwin.png new file mode 100644 index 000000000..2b8d5f882 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-linux.png index ab9cb9fc1..84468765e 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-win32.png new file mode 100644 index 000000000..f28cbfacc Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png new file mode 100644 index 000000000..8c5baa675 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-linux.png index 6cb0d1a34..454129de3 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-win32.png new file mode 100644 index 000000000..70f6acbf5 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png new file mode 100644 index 000000000..7d2a1ee46 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-linux.png index a1c87d560..b726c3536 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-win32.png new file mode 100644 index 000000000..57a3c34c6 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-win32.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png new file mode 100644 index 000000000..9d8bd90e6 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-linux.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-linux.png index d95e53b5a..f755a5532 100644 Binary files a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-linux.png and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-linux.png differ diff --git a/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-win32.png b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-win32.png new file mode 100644 index 000000000..34472a2f5 Binary files /dev/null and b/packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-win32.png differ diff --git a/packages/webui/test/browser/responsive-layout.spec.mjs b/packages/webui/test/browser/responsive-layout.spec.mjs index 0d7358bc2..14edeefdd 100644 --- a/packages/webui/test/browser/responsive-layout.spec.mjs +++ b/packages/webui/test/browser/responsive-layout.spec.mjs @@ -13,7 +13,7 @@ import { expect } from "@playwright/test"; -import { configureFixture, openApp, test } from "./harness.mjs"; +import { configureFixture, finishCapturedTransition, openApp, pauseNextTransition, test, transitionMidpointSize } from "./harness.mjs"; /** The widths the contract's matrix covers. */ const VIEWPORTS = [ @@ -116,6 +116,7 @@ test.describe("the layout adapts to the width it has", () => { expect(await rail.evaluate((element) => getComputedStyle(element).transitionProperty)).toContain("transform"); expect(await rail.evaluate((element) => getComputedStyle(element).transitionDuration)).toBe("0.18s"); expect(await rail.evaluate((element) => getComputedStyle(element).transform)).not.toBe("none"); + await pauseNextTransition(rail, "transform"); await page.getByRole("button", { name: "展开导航栏" }).click(); const scrim = page.getByRole("button", { name: "关闭导航栏" }); await expect(scrim).toHaveAttribute("data-webui-motion", "surface"); @@ -123,13 +124,13 @@ test.describe("the layout adapts to the width it has", () => { await expect(rail).toHaveAttribute("data-webui-page-visible", "true"); await expect(rail).not.toHaveAttribute("aria-hidden", "true"); expect(await rail.evaluate((element) => element.hasAttribute("inert"))).toBe(false); - await page.waitForTimeout(70); + await transitionMidpointSize(rail, "width"); const openTransform = await rail.evaluate((element) => getComputedStyle(element).transform); const openX = Number(openTransform.match(/^matrix\([^,]+,[^,]+,[^,]+,[^,]+,([^,]+)/u)?.[1] ?? NaN); expect(openX).toBeGreaterThan(-drawerWidth); expect(openX).toBeLessThan(0); - await page.waitForTimeout(140); - expect(await rail.evaluate((element) => getComputedStyle(element).transform)).toBe("matrix(1, 0, 0, 1, 0, 0)"); + await finishCapturedTransition(rail); + await expect.poll(() => rail.evaluate((element) => getComputedStyle(element).transform)).toBe("matrix(1, 0, 0, 1, 0, 0)"); await page.evaluate(() => { window.__railScrimExitAnimation = undefined; @@ -142,19 +143,20 @@ test.describe("the layout adapts to the width it has", () => { } }, { capture: true }); }); + await pauseNextTransition(rail, "transform"); await page.mouse.click(400, 400); await expect(rail).toHaveAttribute("data-webui-page-visible", "false"); await expect(rail).toHaveAttribute("aria-hidden", "true"); expect(await rail.evaluate((element) => element.hasAttribute("inert"))).toBe(true); - await page.waitForTimeout(70); + await transitionMidpointSize(rail, "width"); const closeTransform = await rail.evaluate((element) => getComputedStyle(element).transform); const closeX = Number(closeTransform.match(/^matrix\([^,]+,[^,]+,[^,]+,[^,]+,([^,]+)/u)?.[1] ?? NaN); expect(closeX).toBeLessThan(0); expect(closeX).toBeGreaterThan(-drawerWidth); await expect.poll(() => page.evaluate(() => window.__railScrimExitAnimation)).toBe("webui-motion-surface-exit"); await expect(scrim).toHaveCount(0); - await page.waitForTimeout(140); - expect(await rail.evaluate((element) => getComputedStyle(element).transform)).toBe(`matrix(1, 0, 0, 1, ${-drawerWidth}, 0)`); + await finishCapturedTransition(rail); + await expect.poll(() => rail.evaluate((element) => getComputedStyle(element).transform)).toBe(`matrix(1, 0, 0, 1, ${-drawerWidth}, 0)`); }); test("the wide navigation rail uses the shared disclosure transition when collapsed", async ({ page }) => { @@ -167,14 +169,14 @@ test.describe("the layout adapts to the width it has", () => { expect(await rail.evaluate((element) => getComputedStyle(element).transitionProperty)).toContain("width"); expect(await rail.evaluate((element) => getComputedStyle(element).transitionDuration)).toBe("0.16s"); const expandedWidth = await rail.evaluate((element) => element.getBoundingClientRect().width); + await pauseNextTransition(rail, "width"); await page.getByRole("button", { name: "收起导航栏" }).click(); await expect(rail).toHaveAttribute("data-webui-rail-width", "64"); - await page.waitForTimeout(70); - const widthDuringCollapse = await rail.evaluate((element) => element.getBoundingClientRect().width); + const widthDuringCollapse = await transitionMidpointSize(rail, "width"); expect(widthDuringCollapse).toBeLessThan(expandedWidth); expect(widthDuringCollapse).toBeGreaterThan(64); - await page.waitForTimeout(130); - expect(await rail.evaluate((element) => element.getBoundingClientRect().width)).toBe(64); + await finishCapturedTransition(rail); + await expect.poll(() => rail.evaluate((element) => element.getBoundingClientRect().width)).toBe(64); }); test("the header row's parts do not overlap each other", async ({ page }) => { diff --git a/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-darwin.png b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-darwin.png new file mode 100644 index 000000000..92bbba548 Binary files /dev/null and b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-darwin.png differ diff --git a/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-win32.png b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-win32.png new file mode 100644 index 000000000..a2b8e69ab Binary files /dev/null and b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-win32.png differ diff --git a/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-darwin.png b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-darwin.png new file mode 100644 index 000000000..f0fb74d69 Binary files /dev/null and b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-darwin.png differ diff --git a/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-darwin.png b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-darwin.png new file mode 100644 index 000000000..9630f5ab6 Binary files /dev/null and b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-darwin.png differ diff --git a/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-win32.png b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-win32.png new file mode 100644 index 000000000..3c1384c2c Binary files /dev/null and b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-win32.png differ diff --git a/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-win32.png b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-win32.png new file mode 100644 index 000000000..4204e98df Binary files /dev/null and b/packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-win32.png differ diff --git a/packages/webui/test/browser/server.mjs b/packages/webui/test/browser/server.mjs index 3f3efa446..fa66cdea0 100644 --- a/packages/webui/test/browser/server.mjs +++ b/packages/webui/test/browser/server.mjs @@ -4,12 +4,27 @@ import path from "node:path"; import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; import { installFixtureTransport } from "./fixture.mjs"; +import { WEBUI_FONT_DIRECTORY, WEBUI_MONO_FONT, WEBUI_SANS_FONT } from "../../../../scripts/lib/webui-font-environment.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../dist-webui/client"); const port = 4179; const serverId = process.env.WEBUI_BROWSER_SERVER_ID ?? randomUUID(); +const fontRoot = fileURLToPath(new URL(`../../../../${WEBUI_FONT_DIRECTORY}/`, import.meta.url)); +const fontCss = ` +@font-face { font-family: "HarmonyOS Sans"; src: url("/__webui-test-fonts/${WEBUI_SANS_FONT}") format("opentype"); } +@font-face { font-family: "Hack"; src: url("/__webui-test-fonts/${WEBUI_MONO_FONT}") format("opentype"); } +`; const server = createServer(async (request, response) => { const pathname = new URL(request.url ?? "/", `http://127.0.0.1:${port}`).pathname; + if (pathname.startsWith("/__webui-test-fonts/")) { + const name = pathname.slice("/__webui-test-fonts/".length); + if (![WEBUI_SANS_FONT, WEBUI_MONO_FONT].includes(name)) { + response.writeHead(404).end("unknown test font"); + return; + } + response.writeHead(200, { "content-type": "font/otf" }).end(await readFile(path.join(fontRoot, name))); + return; + } if (pathname === "/health") { response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ status: "ok", serverId })); return; @@ -36,7 +51,7 @@ const server = createServer(async (request, response) => { if (name === "index.html") { const html = body.toString().replace( "", - ``, + ``, ); body = Buffer.from(html); } diff --git a/packages/webui/test/browser/streaming-performance.spec.mjs b/packages/webui/test/browser/streaming-performance.spec.mjs index bcc2dfb9c..842ca5af6 100644 --- a/packages/webui/test/browser/streaming-performance.spec.mjs +++ b/packages/webui/test/browser/streaming-performance.spec.mjs @@ -5,11 +5,8 @@ // turn that delivers a few hundred frames gives a few hundred renders. This // spec measures what that costs the reader. // -// The metric that matters is the FRAME GAP: how long the main thread stays -// busy between two animation frames. A gap is what the reader sees — a gap of -// 50 ms is one dropped frame at 60 Hz, a gap of 100 ms is a visible stutter. -// So this measures the gap distribution during a streamed reply and asserts -// that the page never drops a frame and never runs a long task. +// 帧间隔包含 runner 的调度延迟,不能直接当成应用阻塞时间。 +// 同页空闲基线校准帧间隔,应用长任务仍使用绝对 50ms 预算。 // // Two scenarios, because they fail differently: // - a short reply in a short conversation (the everyday case); @@ -21,7 +18,20 @@ import { expect } from "@playwright/test"; -import { openApp, startTurn, test } from "./harness.mjs"; +import { attachJsonEvidence, openApp, startTurn, test } from "./harness.mjs"; +import { + APPLICATION_BLOCK_MS, + FRAME_MARK, + MEASURE_END, + MEASURE_START, + attributeApplicationWork, + attributeFrameWork, + startApplicationTrace, +} from "./application-performance.mjs"; + +// Keep trace snapshots and screenshot capture outside the measured interval; +// a failure screenshot is taken only after the performance assertions. +test.use({ trace: "off", screenshot: "only-on-failure" }); /** A reply body that exercises the markdown path: prose, a list and a fence. */ function replyChunk(index) { @@ -61,6 +71,36 @@ const JANK_FRAME_MS = 50; /** A frame longer than this is more than one dropped frame. */ const DROPPED_FRAME_MS = 100; +function percentile(values, fraction) { + if (!values.length) throw new Error("performance measurement collected no frame samples"); + const sorted = [...values].sort((left, right) => left - right); + return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))]; +} + +function frameBudget(idleBefore, idleAfter) { + // 显示器与 runner 的空闲帧周期不占用应用的 50ms 额外开销预算。 + return Math.max(percentile(idleBefore, 0.95), percentile(idleAfter, 0.95)) + APPLICATION_BLOCK_MS; +} + +async function measureIdleFrames(page, durationMs) { + return page.evaluate(async (duration) => { + const gaps = []; + let previous; + const deadline = performance.now() + duration; + await new Promise((resolve) => { + const sample = () => { + const now = performance.now(); + if (previous !== undefined) gaps.push(now - previous); + previous = now; + if (now < deadline) requestAnimationFrame(sample); + else resolve(); + }; + requestAnimationFrame(sample); + }); + return gaps; + }, durationMs); +} + /** * The streaming measurement, run inside the page. * @@ -75,9 +115,7 @@ async function measureStreamedReply(page, options) { // so it is staged through the fixture's boot-time setup hook. await page.addInitScript((messages) => { window.__WEBUI_FIXTURE_SETUP__ ??= []; - window.__WEBUI_FIXTURE_SETUP__.push(() => - window.__fixture.setPage("A", { messages, hasMore: false }), - ); + window.__WEBUI_FIXTURE_SETUP__.push(() => window.__fixture.setPage("A", { messages, hasMore: false })); }, historyMessages(historyTurns)); await openApp(page); await startTurn(page, "A", "Stream a long answer"); @@ -89,12 +127,16 @@ async function measureStreamedReply(page, options) { window.__fixture.emitStream("A", { dataJson: JSON.stringify({ type: "agent_message", - agent_message: { msg_id: "msg-user-1", msg_content: "Stream a long answer" }, + agent_message: { + msg_id: "msg-user-1", + msg_content: "Stream a long answer", + }, }), }); }); const chunkTexts = Array.from({ length: chunks }, (_value, index) => replyChunk(index)); + const idleBefore = await measureIdleFrames(page, 2000); // Optional CPU profile of the streaming window, so the cost of one frame can // be attributed to functions instead of guessed at. @@ -105,83 +147,143 @@ async function measureStreamedReply(page, options) { await cdp.send("Profiler.start"); } - const metrics = await page.evaluate(async (chunkTextsIn) => { - const count = chunkTextsIn.length; - const longTasks = []; - const observer = new PerformanceObserver((entries) => { - for (const entry of entries.getEntries()) longTasks.push(entry.duration); - }); - observer.observe({ type: "longtask" }); + const finishTrace = await startApplicationTrace(page); + let traceEvents; + let metrics; + try { + metrics = await page.evaluate( + async ({ chunkTextsIn, measureStart, measureEnd, frameMark }) => { + if ( + !["longtask", "long-animation-frame"].every((type) => PerformanceObserver.supportedEntryTypes.includes(type)) + ) { + throw new Error("application performance observers are unavailable"); + } + const count = chunkTextsIn.length; + const longTasks = []; + const longTaskDetails = []; + const observer = new PerformanceObserver((entries) => { + for (const entry of entries.getEntries()) { + longTasks.push(entry.duration); + longTaskDetails.push(entry.toJSON()); + } + }); + observer.observe({ type: "longtask" }); + const longAnimationFrames = []; + const frameObserver = new PerformanceObserver((entries) => { + longAnimationFrames.push(...entries.getEntries().map((entry) => entry.toJSON())); + }); + frameObserver.observe({ type: "long-animation-frame" }); - // A rAF loop records the frame pacing the reader actually sees. - const frameGaps = []; - let previousFrame = performance.now(); - let running = true; - const sample = () => { - if (!running) return; - const now = performance.now(); - frameGaps.push(now - previousFrame); - previousFrame = now; - requestAnimationFrame(sample); - }; - requestAnimationFrame(sample); + // A rAF loop records the frame pacing the reader actually sees. + const frameGaps = []; + let previousFrame = performance.now(); + let running = true; + const sample = () => { + if (!running) return; + performance.mark(frameMark); + const now = performance.now(); + frameGaps.push(now - previousFrame); + previousFrame = now; + requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); - // A zero-delay timer is the cheapest honest probe of "can the main thread - // still answer me": a busy renderer pushes it late. - const timerDelays = []; - let timerRunning = true; - const probe = () => { - if (!timerRunning) return; - const requested = performance.now(); - setTimeout(() => { - timerDelays.push(performance.now() - requested); + // A zero-delay timer is the cheapest honest probe of "can the main thread + // still answer me": a busy renderer pushes it late. + const timerDelays = []; + let timerRunning = true; + const probe = () => { + if (!timerRunning) return; + const requested = performance.now(); + setTimeout(() => { + timerDelays.push(performance.now() - requested); + probe(); + }, 0); + }; probe(); - }, 0); - }; - probe(); - const started = performance.now(); - for (let index = 0; index < count; index += 1) { - window.__fixture.emitStream("A", { - cursor: `cursor-${index}`, - dataJson: JSON.stringify({ - type: "agent_message_chunk", - agent_message_chunk: { - msg_id: "a-turn-1", - msg_content: `${chunkTextsIn[index]}\n\n`, - }, - }), - }); - // Each frame is its own browser task in production, so the render - // opportunity is per frame. A macrotask boundary reproduces that. - await new Promise((resolve) => setTimeout(resolve, 0)); - } - const emitted = performance.now(); + performance.mark(measureStart); + const started = performance.now(); + for (let index = 0; index < count; index += 1) { + window.__fixture.emitStream("A", { + cursor: `cursor-${index}`, + dataJson: JSON.stringify({ + type: "agent_message_chunk", + agent_message_chunk: { + msg_id: "a-turn-1", + msg_content: `${chunkTextsIn[index]}\n\n`, + }, + }), + }); + // Each frame is its own browser task in production, so the render + // opportunity is per frame. A macrotask boundary reproduces that. + await new Promise((resolve) => setTimeout(resolve, 0)); + } + const emitted = performance.now(); - await new Promise((resolve) => { - const deadline = performance.now() + 20_000; - const check = () => { - const text = document.querySelector('[data-webui-assistant-body="a-turn-1"]')?.textContent ?? ""; - if (text.includes(`Paragraph ${count - 1} of the streamed answer`)) return resolve(); - if (performance.now() > deadline) return resolve(); - requestAnimationFrame(check); - }; - check(); - }); - const settled = performance.now(); - running = false; - timerRunning = false; - observer.disconnect(); - const records = observer.takeRecords().map((entry) => entry.duration); - return { - emitted: emitted - started, - settled: settled - started, - longTasks: [...longTasks, ...records], - frameGaps: frameGaps.slice(1), - timerDelays, - liveBodyFound: Boolean(document.querySelector('[data-webui-assistant-body="a-turn-1"]')), - }; - }, chunkTexts); + await new Promise((resolve) => { + const deadline = performance.now() + 20_000; + const check = () => { + const text = document.querySelector('[data-webui-assistant-body="a-turn-1"]')?.textContent ?? ""; + if (text.includes(`Paragraph ${count - 1} of the streamed answer`)) return resolve(); + if (performance.now() > deadline) return resolve(); + requestAnimationFrame(check); + }; + check(); + }); + // 最终文本进入 DOM 后仍需完成绘制;与拖拽一样覆盖提交后的两帧。 + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + const settled = performance.now(); + performance.mark(measureEnd); + running = false; + timerRunning = false; + const records = observer.takeRecords(); + longTaskDetails.push(...records.map((entry) => entry.toJSON())); + observer.disconnect(); + longAnimationFrames.push(...frameObserver.takeRecords().map((entry) => entry.toJSON())); + frameObserver.disconnect(); + return { + emitted: emitted - started, + settled: settled - started, + longTasks: [...longTasks, ...records.map((entry) => entry.duration)], + longTaskDetails, + longAnimationFrames, + frameGaps: frameGaps.slice(1), + timerDelays, + liveBodyFound: Boolean(document.querySelector('[data-webui-assistant-body="a-turn-1"]')), + }; + }, + { + chunkTextsIn: chunkTexts, + measureStart: MEASURE_START, + measureEnd: MEASURE_END, + frameMark: FRAME_MARK, + }, + ); + } finally { + traceEvents = await finishTrace(); + } + await attachJsonEvidence("application-task-trace.json", traceEvents); + const idleAfter = await measureIdleFrames(page, Math.max(2000, metrics.settled)); + // 即使归因数据不完整也先保留原始样本,便于定位采样失败。 + await attachJsonEvidence("stream-performance-samples.json", { + historyTurns, + chunks, + idleBefore, + active: metrics, + idleAfter, + }); + const applicationWork = attributeApplicationWork(traceEvents, metrics.longAnimationFrames); + const frameWork = attributeFrameWork(traceEvents); + await attachJsonEvidence("stream-performance-raw.json", { + historyTurns, + chunks, + idleBefore, + active: metrics, + idleAfter, + applicationWork, + frameWork, + }); if (cdp) { const { profile } = await cdp.send("Profiler.stop"); @@ -202,29 +304,47 @@ async function measureStreamedReply(page, options) { } const gaps = [...metrics.frameGaps].sort((left, right) => left - right); - const percentile = (fraction) => - gaps.length === 0 ? 0 : (gaps[Math.min(gaps.length - 1, Math.floor(gaps.length * fraction))] ?? 0); const summary = { ...metrics, worstFrameGap: gaps.at(-1) ?? 0, - p95FrameGap: percentile(0.95), - medianFrameGap: percentile(0.5), + p95FrameGap: percentile(gaps, 0.95), + medianFrameGap: percentile(gaps, 0.5), + allowedP95FrameGap: frameBudget(idleBefore, idleAfter), jankFrames: gaps.filter((gap) => gap >= JANK_FRAME_MS).length, droppedFrames: gaps.filter((gap) => gap >= DROPPED_FRAME_MS).length, worstTimerDelay: Math.max(0, ...metrics.timerDelays), - longTaskCount: metrics.longTasks.filter((duration) => duration >= 50).length, + longTaskCount: metrics.longTasks.filter((duration) => duration >= APPLICATION_BLOCK_MS).length, + applicationOverBudget: applicationWork.blockingOverBudget.length, + p95FrameCpu: percentile( + frameWork.map((frame) => frame.cpuMs), + 0.95, + ), }; + await attachJsonEvidence("frame-budget-comparison.json", { + idleBeforeP95: percentile(idleBefore, 0.95), + idleAfterP95: percentile(idleAfter, 0.95), + rawActiveP95: summary.p95FrameGap, + rawAllowedP95: summary.allowedP95FrameGap, + rawBudgetExceeded: summary.p95FrameGap >= summary.allowedP95FrameGap, + applicationFrameCpuP95: summary.p95FrameCpu, + applicationBudget: APPLICATION_BLOCK_MS, + }); console.info( [ `streamed reply: ${chunks} frames over ${summary.emitted.toFixed(0)} ms`, `settled after ${summary.settled.toFixed(0)} ms`, `frame gap: median ${summary.medianFrameGap.toFixed(1)} ms`, `p95 ${summary.p95FrameGap.toFixed(1)} ms`, + `idle-calibrated p95 budget ${summary.allowedP95FrameGap.toFixed(1)} ms`, `worst ${summary.worstFrameGap.toFixed(1)} ms`, `jank frames(>=${JANK_FRAME_MS}ms): ${summary.jankFrames}`, `dropped frames(>=${DROPPED_FRAME_MS}ms): ${summary.droppedFrames}`, `worst timer delay: ${summary.worstTimerDelay.toFixed(1)} ms`, `long tasks: ${summary.longTaskCount}`, + `application tasks/scripts over budget: ${summary.applicationOverBudget}`, + `p95 frame CPU: ${summary.p95FrameCpu.toFixed(1)} ms`, + `max task CPU: ${(Math.max(...applicationWork.tasks.map((task) => (Number.isFinite(task.tdur) ? task.tdur : task.dur))) / 1000).toFixed(1)} ms`, + `max script: ${Math.max(0, ...applicationWork.scripts.map((script) => script.duration)).toFixed(1)} ms`, ].join(" | "), ); return summary; @@ -242,9 +362,7 @@ async function expectRenderedAnswer(page, chunks) { const answer = body.locator(".webui-markdown"); await expect(answer).toHaveCount(1); // The oldest block, the one every later frame reused. - await expect(answer.locator("p").first()).toContainText( - "Paragraph 0 of the streamed answer", - ); + await expect(answer.locator("p").first()).toContainText("Paragraph 0 of the streamed answer"); // Every block that arrived: one list of two items and one fenced code block // per chunk, all of them rendered. await expect(answer.locator(".webui-code-block")).toHaveCount(chunks); @@ -264,15 +382,14 @@ test("a streamed reply keeps the page responsive", async ({ page }) => { // The reply must reach the screen, in its own turn block. expect(summary.liveBodyFound, "the live reply did not render its own assistant body").toBe(true); await expectRenderedAnswer(page, Number(process.env.WEBUI_PERF_CHUNKS ?? 120)); - // The reader must never lose a frame to the reply. expect( - summary.jankFrames, - `the streamed reply dropped ${summary.jankFrames} frames (worst gap ${summary.worstFrameGap.toFixed(1)} ms)`, - ).toBe(0); - // No single frame may block the main thread long enough to be a stutter. + summary.p95FrameCpu, + `stream frame CPU p95 ${summary.p95FrameCpu} ms exceeds application budget ${APPLICATION_BLOCK_MS} ms`, + ).toBeLessThan(APPLICATION_BLOCK_MS); + // 原始停顿保留诊断;实际主线程执行与脚本阻塞分别执行 50ms 预算。 expect( - summary.longTaskCount, - `the streamed reply produced ${summary.longTaskCount} long tasks`, + summary.applicationOverBudget, + `the streamed reply produced ${summary.applicationOverBudget} application tasks/scripts over budget`, ).toBe(0); }); @@ -288,15 +405,211 @@ test("a long reply in a long conversation does not drop frames", async ({ page } expect(summary.liveBodyFound, "the live reply did not render its own assistant body").toBe(true); await expectRenderedAnswer(page, Number(process.env.WEBUI_PERF_HEAVY_CHUNKS ?? 400)); expect( - summary.droppedFrames, - `the streamed reply dropped ${summary.droppedFrames} frames (worst gap ${summary.worstFrameGap.toFixed(1)} ms)`, - ).toBe(0); - expect( - summary.jankFrames, - `the streamed reply dropped ${summary.jankFrames} frames (worst gap ${summary.worstFrameGap.toFixed(1)} ms)`, - ).toBe(0); + summary.p95FrameCpu, + `stream frame CPU p95 ${summary.p95FrameCpu} ms exceeds application budget ${APPLICATION_BLOCK_MS} ms`, + ).toBeLessThan(APPLICATION_BLOCK_MS); expect( - summary.longTaskCount, - `the streamed reply produced ${summary.longTaskCount} long tasks`, + summary.applicationOverBudget, + `the streamed reply produced ${summary.applicationOverBudget} application tasks/scripts over budget`, ).toBe(0); -}); \ No newline at end of file +}); + +for (const scenario of ["idle", "javascript", "layout", "synchronous-wait"]) { + test(`application attribution detects real blocking: ${scenario}`, async ({ page }) => { + await openApp(page); + await page.route("**/__application_wait", async (route) => { + await new Promise((resolve) => setTimeout(resolve, 120)); + await route.fulfill({ status: 200, body: "ok" }); + }); + const finishTrace = await startApplicationTrace(page); + let events; + let frames; + try { + frames = await page.evaluate( + async ({ scenario, start, end }) => { + if (!PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")) { + throw new Error("application performance observers are unavailable"); + } + const frames = []; + const observer = new PerformanceObserver((list) => + frames.push(...list.getEntries().map((entry) => entry.toJSON())), + ); + observer.observe({ type: "long-animation-frame" }); + const content = document.createElement("div"); + document.body.append(content); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + performance.mark(start); + await new Promise((resolve) => + setTimeout(() => { + const started = performance.now(); + if (scenario === "synchronous-wait") { + const request = new XMLHttpRequest(); + request.open("GET", "/__application_wait", false); + request.send(); + if (request.status !== 200) throw new Error("synchronous wait control failed"); + } + if (scenario === "layout") content.innerHTML = '
layout control
'.repeat(3000); + let iteration = 0; + while (scenario !== "idle" && performance.now() - started < 80) { + if (scenario === "layout") { + content.style.width = `${600 + (iteration % 2)}px`; + content.getBoundingClientRect(); + } + iteration += 1; + } + resolve(); + }, 0), + ); + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + performance.mark(end); + await new Promise((resolve) => setTimeout(resolve, 100)); + frames.push(...observer.takeRecords().map((entry) => entry.toJSON())); + observer.disconnect(); + content.remove(); + return frames; + }, + { scenario, start: MEASURE_START, end: MEASURE_END }, + ); + } finally { + events = await finishTrace(); + } + const work = attributeApplicationWork(events, frames); + await attachJsonEvidence("application-attribution-control.json", { + scenario, + work, + frames, + }); + expect(work.blockingOverBudget.length > 0).toBe(scenario !== "idle"); + if (scenario === "synchronous-wait") expect(work.blockedTasks.some((task) => task.pauseMs >= 50)).toBe(true); + }); +} + +test("missing application timing fails instead of passing with zero work", async ({ page }) => { + await openApp(page); + expect(() => attributeApplicationWork([], [])).toThrow("markers are missing"); + expect(() => attributeFrameWork([])).toThrow("frame markers are missing"); + const markers = [ + { name: MEASURE_START, ts: 1, pid: 1, tid: 1 }, + { name: MEASURE_END, ts: 100, pid: 1, tid: 1 }, + ]; + expect(() => attributeFrameWork(markers)).toThrow("frame CPU timing is unavailable"); + const frameEvents = [ + { name: MEASURE_START, ts: 0, pid: 1, tid: 1 }, + { name: MEASURE_END, ts: 100_000, pid: 1, tid: 1 }, + { name: FRAME_MARK, ts: 100, tts: 10, pid: 1, tid: 1 }, + { name: FRAME_MARK, ts: 90_000, tts: 60_010, pid: 1, tid: 1 }, + ]; + expect(attributeFrameWork(frameEvents)).toEqual([{ wallMs: 89.9, cpuMs: 60 }]); + expect(() => attributeFrameWork(frameEvents.map((event) => ({ ...event, tts: undefined })))).toThrow( + "frame CPU timing is unavailable", + ); + expect(() => attributeApplicationWork(markers, [])).toThrow("CPU timing is unavailable"); + expect(() => + attributeApplicationWork( + [ + ...markers, + { + name: "ThreadControllerImpl::RunTask", + ph: "X", + pid: 1, + tid: 1, + ts: 2, + dur: 70, + }, + ], + [], + ), + ).toThrow("CPU timing is unavailable"); + const measured = { + name: "ThreadControllerImpl::RunTask", + ph: "X", + pid: 1, + tid: 1, + ts: 2, + dur: 10, + tdur: 10, + }; + expect(() => + attributeApplicationWork( + [ + ...markers, + measured, + { + ...measured, + ts: 3, + dur: 70_000, + tdur: undefined, + }, + ], + [], + ), + ).toThrow("CPU timing is unavailable"); + const shortSynthetic = { ...measured, ts: 3, dur: 1, tdur: undefined }; + expect(attributeApplicationWork([...markers, measured, shortSynthetic], []).cpuOverBudget).toEqual([]); + const wallGap = [ + { name: MEASURE_START, ts: 0, pid: 1, tid: 1, args: { data: { startTime: 0 } } }, + { name: MEASURE_END, ts: 500_000, pid: 1, tid: 1 }, + { ...measured, ts: 0, dur: 400_000, tdur: 20_000 }, + ]; + const script = { startTime: 0, duration: 400, pauseDuration: 0 }; + expect(attributeApplicationWork(wallGap, [{ scripts: [script] }]).blockingOverBudget).toEqual([]); + const blocked = attributeApplicationWork(wallGap, [{ scripts: [{ ...script, pauseDuration: 60 }] }]); + expect(blocked.blockingOverBudget).toHaveLength(1); + expect(blocked.blockingOverBudget[0].applicationMs).toBe(80); +}); + +test("frame calibration distinguishes scheduler outliers from sustained application delay", async ({ page }) => { + await openApp(page); + const smooth = Array(120).fill(1000 / 60); + const outlier = [...smooth, 100]; + expect(percentile(outlier, 0.95)).toBeLessThan(frameBudget(smooth, smooth)); + const delayed = Array(120).fill(70); + expect(percentile(delayed, 0.95)).toBeGreaterThan(frameBudget(smooth, smooth)); + const slowRunner = Array(120).fill(40); + expect(percentile(slowRunner, 0.95)).toBeLessThan(frameBudget(slowRunner, slowRunner)); + expect(percentile(Array(120).fill(70), 0.95)).toBeLessThan(frameBudget(slowRunner, slowRunner)); + expect(percentile(Array(120).fill(100), 0.95)).toBeGreaterThan(frameBudget(slowRunner, slowRunner)); + expect(() => frameBudget([], smooth)).toThrow("no frame samples"); +}); + +test("continuous chunks remain visible before the stream ends and the final chunk is retained", async ({ page }) => { + await openApp(page); + await startTurn(page, "A", "Stream a progressively visible answer"); + const progress = await page.evaluate(async () => { + const snapshots = []; + for (let index = 0; index < 80; index += 1) { + window.__fixture.emitStream("A", { + dataJson: JSON.stringify({ + type: "agent_message_chunk", + agent_message_chunk: { + msg_id: "progressive-answer", + msg_content: `Visible chunk ${index}.\n\n`, + }, + }), + }); + await new Promise((resolve) => setTimeout(resolve, 4)); + if (index === 20 || index === 40 || index === 60) { + const text = document.querySelector('[data-webui-assistant-body="progressive-answer"]')?.textContent ?? ""; + snapshots.push(text.includes(`Visible chunk ${index - 10}.`)); + } + } + return snapshots; + }); + expect(progress).toEqual([true, true, true]); + await expect(page.locator('[data-webui-assistant-body="progressive-answer"]')).toContainText("Visible chunk 79."); + await page.evaluate(() => { + window.__fixture.emitStream("A", { + dataJson: JSON.stringify({ + type: "agent_message_chunk", + agent_message_chunk: { + msg_id: "progressive-answer", + msg_content: "Final chunk before DONE.", + }, + }), + }); + window.__fixture.emitStream("A", { dataJson: "[DONE]" }); + }); + await expect(page.locator('[data-webui-assistant-body="progressive-answer"]')).toContainText( + "Final chunk before DONE.", + ); +}); diff --git a/packages/webui/test/browser/support/native-browser-host.ts b/packages/webui/test/browser/support/native-browser-host.ts index e534af791..a609f8f7a 100644 --- a/packages/webui/test/browser/support/native-browser-host.ts +++ b/packages/webui/test/browser/support/native-browser-host.ts @@ -3,7 +3,7 @@ import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { createRequire } from "node:module"; +import { loadWebuiPty } from "../../../src/runtime/native-pty.js"; import { createWebuiRuntimeHost } from "../../../src/runtime/assembly.js"; import { createHarnessPortFromHost } from "../../../src/runtime/harness/adapter.js"; import { WebuiTerminalManager } from "../../../src/runtime/terminal.js"; @@ -41,7 +41,7 @@ const initialSession = await port.createSession({ name: "main", workspaceDir }); const sessionId = initialSession.session?.sessionId; if (!sessionId) throw new Error("Native acceptance session was not created"); type NativePtyModule = ReturnType[0]>>; -const native = createRequire(import.meta.url)("node-pty") as NativePtyModule; +const native: NativePtyModule = loadWebuiPty(); const exits: Promise[] = []; const terminal = new WebuiTerminalManager(() => ({ spawn: (shell, args, options) => { const pty = native.spawn(shell, args, options); diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-darwin.png new file mode 100644 index 000000000..47318f8ec Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-win32.png new file mode 100644 index 000000000..5a7263589 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png new file mode 100644 index 000000000..74ff52556 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-linux.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-linux.png index 775e6d686..f59892fdc 100644 Binary files a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-linux.png and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-linux.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-win32.png new file mode 100644 index 000000000..c9ba0835d Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-darwin.png new file mode 100644 index 000000000..f091f3e5d Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-win32.png new file mode 100644 index 000000000..ba78a5919 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-darwin.png new file mode 100644 index 000000000..e054a072d Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-linux.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-linux.png index 009fddaab..63dd9fd2f 100644 Binary files a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-linux.png and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-linux.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-win32.png new file mode 100644 index 000000000..75df7d156 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-darwin.png new file mode 100644 index 000000000..a38bbcaf4 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-win32.png new file mode 100644 index 000000000..4b98ed1c3 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-darwin.png new file mode 100644 index 000000000..fefbf2305 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-linux.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-linux.png index b13bc19ae..cc2a14768 100644 Binary files a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-linux.png and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-linux.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-win32.png new file mode 100644 index 000000000..bfe2b2e2b Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-darwin.png new file mode 100644 index 000000000..3a133df8b Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-linux.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-linux.png index 357bf4bd3..002952982 100644 Binary files a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-linux.png and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-linux.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-win32.png new file mode 100644 index 000000000..783ff465f Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-darwin.png new file mode 100644 index 000000000..e65d34d64 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-win32.png new file mode 100644 index 000000000..6962d24ea Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-darwin.png new file mode 100644 index 000000000..e21d28ef2 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-win32.png new file mode 100644 index 000000000..27e3110cf Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-win32.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-darwin.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-darwin.png new file mode 100644 index 000000000..f3bb46461 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-darwin.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-linux.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-linux.png index 6824b005e..e7dc84c07 100644 Binary files a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-linux.png and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-linux.png differ diff --git a/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-win32.png b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-win32.png new file mode 100644 index 000000000..a6f85fbe6 Binary files /dev/null and b/packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-win32.png differ diff --git a/packages/webui/test/browser/workspace-panel-actions.spec.mjs b/packages/webui/test/browser/workspace-panel-actions.spec.mjs index d10c4a78a..87cc05d14 100644 --- a/packages/webui/test/browser/workspace-panel-actions.spec.mjs +++ b/packages/webui/test/browser/workspace-panel-actions.spec.mjs @@ -15,7 +15,11 @@ import { expect } from "@playwright/test"; import AxeBuilder from "@axe-core/playwright"; -import { configureFixture, openApp, openLauncherTile, switchSession, test } from "./harness.mjs"; +import { attachJsonEvidence, configureFixture, finishCapturedTransition, openApp, openLauncherTile, pauseNextTransition, switchSession, test, transitionMidpointSize } from "./harness.mjs"; + +// Neither injected DOM snapshots nor trace screenshots belong to the client's +// performance budget. Capture failure screenshots after the measurement. +test.use({ trace: "off", screenshot: "only-on-failure" }); /** Open the browser panel, choose 查看文件, and wait for the tree it loads. */ async function openFilePanel(page) { @@ -172,6 +176,9 @@ test("the workspace review stays responsive with 70 expanded diff files", async const review = page.getByTestId("workspace-review"); await expect(review.locator('[data-testid="turn-review-diff-file"]')).toHaveCount(70); await expect(review.locator(".webui-turn-review-code")).toHaveCount(70); + await expect(review.locator(".webui-turn-review-code").first()).toBeVisible(); + // DOM 数量不代表初始布局已绘制;用户能看到 review 后再测工具栏交互。 + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); const elapsed = await page.evaluate(async () => { const button = document.querySelector('[data-testid="workspace-review-toolbar-context"]'); @@ -184,6 +191,13 @@ test("the workspace review stays responsive with 70 expanded diff files", async console.info(`70-file review interaction: ${elapsed.toFixed(1)} ms`); expect(elapsed, `70-file review interaction took ${elapsed.toFixed(1)} ms`).toBeLessThan(100); + const handle = page.getByRole("separator", { name: "调整工作区面板宽度" }); + const bounds = await handle.boundingBox(); + if (!bounds) throw new Error("workspace panel resize handle is not laid out"); + const panelWidthBefore = await page.getByTestId("workspace-panel").evaluate((element) => element.getBoundingClientRect().width); + await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); + // Resolve the handle before observing the drag: selector discovery is not a + // pointer gesture, and can walk the whole expanded accessibility tree. await page.evaluate(() => { window.__reviewLongTasks = []; window.__reviewLongTaskObserver = new PerformanceObserver((entries) => { @@ -191,19 +205,18 @@ test("the workspace review stays responsive with 70 expanded diff files", async }); window.__reviewLongTaskObserver.observe({ type: "longtask" }); }); - const handle = page.getByRole("separator", { name: "调整工作区面板宽度" }); - const bounds = await handle.boundingBox(); - if (!bounds) throw new Error("workspace panel resize handle is not laid out"); - const panelWidthBefore = await page.getByTestId("workspace-panel").evaluate((element) => element.getBoundingClientRect().width); - await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); await page.mouse.down(); await page.mouse.move(bounds.x + bounds.width / 2 + 96, bounds.y + bounds.height / 2, { steps: 12 }); await page.mouse.up(); - await expect.poll(() => page.getByTestId("workspace-panel").evaluate((element) => element.getBoundingClientRect().width)).not.toBe(panelWidthBefore); - const dragLongTasks = await page.evaluate(() => { + const dragLongTasks = await page.evaluate(async () => { + // 等待 pointerup 的提交和布局;定位器查找及断言在性能窗口外执行。 + await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); + const tasks = [...window.__reviewLongTasks, ...window.__reviewLongTaskObserver.takeRecords().map((entry) => entry.duration)]; window.__reviewLongTaskObserver.disconnect(); - return [...window.__reviewLongTasks, ...window.__reviewLongTaskObserver.takeRecords().map((entry) => entry.duration)]; + return tasks; }); + await attachJsonEvidence("workspace-drag-long-tasks.json", dragLongTasks); + await expect.poll(() => page.getByTestId("workspace-panel").evaluate((element) => element.getBoundingClientRect().width)).not.toBe(panelWidthBefore); expect(dragLongTasks.filter((duration) => duration >= 50), `workspace panel drag produced ${dragLongTasks} ms long tasks`).toEqual([]); const lastFile = review.locator('[data-testid="turn-review-diff-file"]').last(); await lastFile.scrollIntoViewIfNeeded(); @@ -211,6 +224,30 @@ test("the workspace review stays responsive with 70 expanded diff files", async expect(await lastFile.locator(".webui-turn-review-code").evaluate((element) => element.getBoundingClientRect().height)).toBeGreaterThan(1000); }); +test("a contained unified diff keeps long lines horizontally scrollable", async ({ page }) => { + await configureFixture(page, () => { + const file = { fileId: "src/long.ts", path: "src/long.ts", additions: 1, deletions: 0, status: "modified" }; + window.__fixture.setWorkspaceReview({ + repositoryId: "repo-1", reviewSnapshotId: "long-line-snapshot", files: [file], + totals: { files: 1, additions: 1, deletions: 0 }, + }, [{ fileId: file.fileId, diff: { type: "text", diff: `diff --git a/src/long.ts b/src/long.ts\n--- a/src/long.ts\n+++ b/src/long.ts\n@@ -0,0 +1 @@\n+${"x".repeat(800)}` } }]); + }); + await openApp(page); + await page.getByTestId("workspace-panel-controls").getByRole("button", { name: "浏览器" }).click(); + await openLauncherTile(page, "review"); + const code = page.getByTestId("workspace-review").locator(".webui-turn-review-code"); + await expect(code).toBeVisible(); + await expect(code).toContainText("x".repeat(800)); + await code.scrollIntoViewIfNeeded(); + await expect.poll(() => code.evaluate((element) => element.scrollWidth > element.clientWidth)).toBe(true); + const geometry = await code.evaluate((element) => { + element.scrollLeft = 200; + return { clientWidth: element.clientWidth, scrollWidth: element.scrollWidth, scrollLeft: element.scrollLeft }; + }); + expect(geometry.scrollWidth).toBeGreaterThan(geometry.clientWidth); + expect(geometry.scrollLeft).toBe(200); +}); + test("the workspace file tree uses the shared disclosure transition when a directory opens and closes", async ({ page }) => { await configureFixture(page, () => undefined); await openApp(page); @@ -228,22 +265,26 @@ test("the workspace file tree uses the shared disclosure transition when a direc expect(await disclosure.getAttribute("aria-hidden")).toBe("true"); expect(await disclosure.evaluate((element) => getComputedStyle(element).transitionDuration)).toBe("0.16s"); + await pauseNextTransition(disclosure, "grid-template-rows"); await directory.click(); await expect(chevron).toHaveClass(/is-rotated-90/u); expect(await chevron.evaluate((element) => getComputedStyle(element).transform)).not.toBe("none"); await expect(disclosure).toHaveAttribute("data-webui-motion-state", "expand"); await expect(disclosure).not.toHaveAttribute("aria-hidden", "true"); - await page.waitForTimeout(70); - expect(await disclosure.evaluate((element) => element.getBoundingClientRect().height)).toBeGreaterThan(0); + expect(await transitionMidpointSize(disclosure, "height")).toBeGreaterThan(0); + await finishCapturedTransition(disclosure); + const expandedHeight = await disclosure.evaluate((element) => element.getBoundingClientRect().height); + await pauseNextTransition(disclosure, "grid-template-rows"); await directory.click(); await expect(chevron).not.toHaveClass(/is-rotated-90/u); expect(await chevron.evaluate((element) => getComputedStyle(element).transitionDuration)).toBe("0.16s"); await expect(disclosure).toHaveAttribute("data-webui-motion-state", "collapse"); await expect(disclosure).toHaveAttribute("aria-hidden", "true"); - await page.waitForTimeout(70); - expect(await disclosure.evaluate((element) => element.getBoundingClientRect().height)).toBeGreaterThan(0); - await page.waitForTimeout(130); + const collapsingHeight = await transitionMidpointSize(disclosure, "height"); + expect(collapsingHeight).toBeGreaterThan(0); + expect(collapsingHeight).toBeLessThan(expandedHeight); + await finishCapturedTransition(disclosure); expect(await disclosure.evaluate((element) => element.getBoundingClientRect().height)).toBe(0); }); @@ -319,20 +360,24 @@ test("the file tree uses the shared horizontal disclosure while its workspace pa expect(await fileTreePanel.evaluate((element) => getComputedStyle(element).transitionDuration)).toBe("0.16s"); const fileTreeWidth = await fileTreePanel.evaluate((element) => element.getBoundingClientRect().width); + await pauseNextTransition(fileTreePanel, "width"); await page.getByRole("button", { name: "隐藏文件树" }).click(); await expect(fileTreePanel).toHaveAttribute("data-webui-motion-state", "collapse"); await expect(fileTreePanel).toHaveAttribute("aria-hidden", "true"); - await page.waitForTimeout(70); - const fileTreeWidthDuringCollapse = await fileTreePanel.evaluate((element) => element.getBoundingClientRect().width); + const fileTreeWidthDuringCollapse = await transitionMidpointSize(fileTreePanel, "width"); expect(fileTreeWidthDuringCollapse).toBeGreaterThan(0); expect(fileTreeWidthDuringCollapse).toBeLessThan(fileTreeWidth); - await page.waitForTimeout(130); - expect(await fileTreePanel.evaluate((element) => element.getBoundingClientRect().width)).toBe(0); + await finishCapturedTransition(fileTreePanel); + await expect.poll(() => fileTreePanel.evaluate((element) => element.getBoundingClientRect().width)).toBe(0); + await pauseNextTransition(fileTreePanel, "width"); await page.getByRole("button", { name: "显示文件树" }).click(); await expect(fileTreePanel).toHaveAttribute("data-webui-motion-state", "expand"); - await page.waitForTimeout(200); - expect(await fileTreePanel.evaluate((element) => element.getBoundingClientRect().width)).toBe(fileTreeWidth); + const expandingWidth = await transitionMidpointSize(fileTreePanel, "width"); + expect(expandingWidth).toBeGreaterThan(0); + expect(expandingWidth).toBeLessThan(fileTreeWidth); + await finishCapturedTransition(fileTreePanel); + await expect.poll(() => fileTreePanel.evaluate((element) => element.getBoundingClientRect().width)).toBe(fileTreeWidth); await page.getByRole("button", { name: "关闭面板" }).click(); await expect(workspacePanel).toHaveAttribute("data-webui-motion-state", "exit"); diff --git a/packages/webui/test/gates/fixtures/path-metadata-f00.json b/packages/webui/test/gates/fixtures/path-metadata-f00.json index 337cfd62c..ed872a53c 100644 --- a/packages/webui/test/gates/fixtures/path-metadata-f00.json +++ b/packages/webui/test/gates/fixtures/path-metadata-f00.json @@ -1,8 +1,36 @@ { "baseline": "f00b1268c28ad15054a8882620c3fb08beb86d58", "sourceSha256": "46b86b658adc1611f3531d8dc9844612f7e9ee3de0eec4a532aeec44b5de0a12", - "declaredDelta": "Public marker preserves the original layer and adds only the published- role prefix; publication legality has separate positive/negative fixtures.", + "declaredDelta": "Public marker preserves the original layer and adds only the published- role prefix; publication legality has separate positive/negative fixtures. Post-baseline additions: conversation/pagination remains a mechanism, platform/transport-origin remains infrastructure, and runtime/ssh/authentication remains outside the client.", "cases": [ + { + "path": "runtime/native-pty.ts", + "layers": ["runtime"], + "role": "outside", + "business": null, + "home": "outside" + }, + { + "path": "client/conversation/pagination.ts", + "layers": ["mechanisms"], + "role": "conversation", + "business": null, + "home": "target" + }, + { + "path": "client/platform/transport-origin.ts", + "layers": ["infrastructure"], + "role": "platform", + "business": null, + "home": "target" + }, + { + "path": "runtime/ssh/authentication.ts", + "layers": ["runtime"], + "role": "outside", + "business": null, + "home": "outside" + }, { "path": "client/application/create-application.ts", "layers": [ diff --git a/packages/webui/test/gates/webui-motion.test.ts b/packages/webui/test/gates/webui-motion.test.ts index f168fef5c..e9286be01 100644 --- a/packages/webui/test/gates/webui-motion.test.ts +++ b/packages/webui/test/gates/webui-motion.test.ts @@ -6,6 +6,7 @@ // to run on every change. import { readFileSync } from "node:fs"; +import { checkMotionOwnership } from "../../../../scripts/check-webui-motion.mjs"; import { describe, expect, it } from "vitest"; import { compareMotion, disabledTransitionOwnershipProblems, featureInteractionTransformOwnershipProblems, featureRotationOwnershipProblems, featureSmoothScrollOwnershipProblems, scanStylesheet, sharedFeedbackControlProblems, sourceMotionOwnershipProblems } from "../../../../scripts/check-webui-motion.mjs"; @@ -25,6 +26,26 @@ const inventory = { }; describe("the motion inventory", () => { + it("recognizes shared owners and asset imports with Windows glob paths", async () => { + const approved = JSON.parse(readFileSync(new URL("../../docs/design/motion-inventory.json", import.meta.url), "utf8")); + async function* windowsPaths(pattern: string) { + // Exercise the scanner with real shared implementations, approved + // feature styles and the asset owner, without parsing the whole client + // a second time inside a unit test. + for (const entry of [ + "styles/motion.css", "features/account/ui/account.css", "features/transcript/ui/transcript.css", + "ui/page.tsx", "ui/feedback.tsx", "features/transcript/ui/ActivityIndicator.tsx", + ]) { + if (pattern.endsWith(".css") ? entry.endsWith(".css") : /\.(?:ts|tsx)$/u.test(entry)) { + yield entry.replaceAll("/", "\\"); + } + } + } + const result = await checkMotionOwnership(approved, windowsPaths); + expect(result.problems).toEqual([]); + expect(result.approvedStylesheets).toBeGreaterThan(0); + }); + it("names the four families and the popup exit in tokens", () => { for (const family of ["feedback", "surface", "disclosure", "loading"]) { expect(motionCss).toMatch(new RegExp(`--webui-motion-duration-${family}:\\s*\\d`, "u")); diff --git a/packages/webui/test/integration/agent-transcript.test.ts b/packages/webui/test/integration/agent-transcript.test.ts index 599499f95..bcbd98339 100644 --- a/packages/webui/test/integration/agent-transcript.test.ts +++ b/packages/webui/test/integration/agent-transcript.test.ts @@ -171,6 +171,9 @@ it.each(["transcript", "cross-client", "external-active-mutation", "external-act const crossClientHoldGate = new Promise((resolve) => { releaseCrossClientHold = resolve; }); let releaseImmediateAnswer: () => void = () => undefined; const immediateAnswerGate = new Promise((resolve) => { releaseImmediateAnswer = resolve; }); + let releaseGoalFollowUp: () => void = () => undefined; + const goalFollowUpGate = new Promise((resolve) => { releaseGoalFollowUp = resolve; }); + let goalAnswers = 0; let retryModelAttempts = 0; let allowModelRetryRecovery = false; const modelRequests: { url: string | undefined; authorization: string | undefined; body: string }[] = []; @@ -223,6 +226,10 @@ it.each(["transcript", "cross-client", "external-active-mutation", "external-act // This branch has to precede the Ask User one below: both read the whole // history, and the earlier Ask User turn stays in it, so whichever comes // first answers every later kickoff turn. + // Keep subsequent automatic turns behind the active-goal assertions. + // Otherwise identical follow-up answers race the unique text locator + // and the runaway guard can pause the goal before it is inspected. + if (goalAnswers++ > 0) await goalFollowUpGate; response.write(frame({ role: "assistant", content: "Synthetic goal progress acknowledged." })); } else if (serializedMessages.includes("Ask User continuation.")) { const askUserCompleted = serializedMessages.includes("call-ask-user-e2e"); @@ -1291,6 +1298,7 @@ it.each(["transcript", "cross-client", "external-active-mutation", "external-act }); const goalCreate = requests.find((request) => request.operation === "createGoal"); expect(goalCreate?.body).toMatchObject({ objective: "Keep this synthetic goal active." }); + releaseGoalFollowUp(); const goalBanner = page.getByTestId("thread-goal-banner"); await browserExpect.poll(() => goalBanner.getAttribute("data-goal-status"), { timeout: 30_000 }) @@ -1884,6 +1892,7 @@ it.each(["transcript", "cross-client", "external-active-mutation", "external-act releaseStoppedAnswer(); releaseCrossClientHold(); releaseImmediateAnswer(); + releaseGoalFollowUp(); await browser?.close(); await service?.close().catch(() => undefined); await browserAdapter?.close().catch(() => undefined); diff --git a/packages/webui/test/integration/cron-desktop-and-webui.test.ts b/packages/webui/test/integration/cron-desktop-and-webui.test.ts index 04f669b99..3b425c53d 100644 --- a/packages/webui/test/integration/cron-desktop-and-webui.test.ts +++ b/packages/webui/test/integration/cron-desktop-and-webui.test.ts @@ -10,7 +10,7 @@ * `packages/webui/test/integration/real-host-cron-runs.test.ts` (one run, one delivery). Stating the * split is what keeps each claim reviewable instead of a single test that gestures at everything. */ -import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { mkdir, mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -18,6 +18,7 @@ import type { CreatedLocalRuntimeHost, LocalRuntimeConfig } from "@mavis/local-r import { afterEach, describe, expect, it } from "vitest"; import { createLocalRuntimeHostV2ForTest } from "../../../local-runtime-v2/src/runtime.js"; +import { removeRealHostDataDir } from "./remove-real-host-data-dir.js"; type HostWithCron = CreatedLocalRuntimeHost & { readonly cliService?: { @@ -37,8 +38,8 @@ const hosts: HostWithCron[] = []; const dataDirs: string[] = []; afterEach(async () => { - for (const host of hosts.splice(0)) await host.apiHost.close().catch(() => undefined); - for (const dir of dataDirs.splice(0)) await rm(dir, { recursive: true, force: true }); + for (const host of hosts.splice(0)) await host.apiHost.close(); + for (const dir of dataDirs.splice(0)) await removeRealHostDataDir(dir); }); async function boot(dataDir: string, runtimeOwnerKind: "webui" | "electron"): Promise { @@ -164,7 +165,7 @@ describe("two scheduler hosts on one data directory", () => { expect(paused?.nextRunAtMs).toBeUndefined(); expect((await cron(webui).listCronTasks({})).items[0]).toMatchObject({ enabled: false, armed: false }); - await peer.apiHost.close().catch(() => undefined); + await peer.apiHost.close(); hosts.splice(hosts.indexOf(peer), 1); const restartedPeer = await boot(dataDir, "electron"); diff --git a/packages/webui/test/integration/real-host-capability-surface.test.ts b/packages/webui/test/integration/real-host-capability-surface.test.ts index 60d85e9ff..0f8463f3b 100644 --- a/packages/webui/test/integration/real-host-capability-surface.test.ts +++ b/packages/webui/test/integration/real-host-capability-surface.test.ts @@ -286,9 +286,13 @@ describe("the real host, the capability surface a turn offers", () => { content: "what can you do?", }); expect(sent.ok).toBe(true); - - await expect.poll(() => stub.requests.length, { timeout: 120_000 }).toBeGreaterThan(0); - const request = JSON.parse(stub.requests[0]?.body ?? "{}") as ModelRequest; + if (sent.ok) for await (const _frame of sent.source) void _frame; + // 后台标题请求也使用该端点,不能把先到的请求当成用户 turn。 + const turnRequests = stub.requests + .map((request) => JSON.parse(request.body) as ModelRequest) + .filter((request) => !extractToolNames(request).includes("submit_session_title")); + expect(turnRequests).toHaveLength(1); + const request = turnRequests[0]!; const skills = extractSkillIds(request).sort(); const tools = extractToolNames(request).sort(); diff --git a/packages/webui/test/integration/real-host-cron-runs.test.ts b/packages/webui/test/integration/real-host-cron-runs.test.ts index 613aec4a3..74ec87a74 100644 --- a/packages/webui/test/integration/real-host-cron-runs.test.ts +++ b/packages/webui/test/integration/real-host-cron-runs.test.ts @@ -12,12 +12,12 @@ * are counted, and a real host would try to deliver a turn to a model. */ import { randomUUID } from "node:crypto"; -import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { eq } from "drizzle-orm"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { DatabaseClient } from "../../../local-runtime-v2/src/infra/db/client.js"; import { initializeDatabase } from "../../../local-runtime-v2/src/infra/db/initialize.js"; @@ -26,16 +26,22 @@ import { Scheduler } from "../../../local-runtime-v2/src/infra/scheduler/index.j import { composeCronService } from "../../../local-runtime-v2/src/service/cron/composition.js"; import { createWebuiRuntimeHost } from "../../src/runtime/assembly.js"; import { createOperationRegistry } from "../../src/server/operation/operations.js"; +import { removeRealHostDataDir } from "./remove-real-host-data-dir.js"; const disposers: Array<() => Promise | void> = []; afterEach(async () => { - for (const dispose of disposers.splice(0).reverse()) await dispose(); + try { + for (const dispose of disposers.splice(0).reverse()) await dispose(); + } finally { + vi.unstubAllEnvs(); + (await import("@mavis/config")).resetConfig(); + } }); async function temporaryDataDir(prefix: string): Promise { const dataDir = await mkdtemp(join(tmpdir(), prefix)); - disposers.push(() => rm(dataDir, { recursive: true, force: true })); + disposers.push(() => removeRealHostDataDir(dataDir)); await mkdir(join(dataDir, "workspace"), { recursive: true }); return dataDir; } @@ -43,8 +49,13 @@ async function temporaryDataDir(prefix: string): Promise { describe("run now and run history over the real host", () => { it("runs a task immediately and shows the run in its history", async () => { const dataDir = await temporaryDataDir("webui-cron-runs-"); + await writeFile(join(dataDir, "config.yaml"), "{}\n", { mode: 0o600 }); + vi.stubEnv("MINIMAX_DATA_DIR", dataDir); + const config = await import("@mavis/config"); + config.resetConfig(); + expect(config.getConfig().dataDir).toBe(dataDir); const assembled = await createWebuiRuntimeHost({ dataDir, appVersion: "cron-runs" }); - disposers.push(() => assembled.host.apiHost.close().catch(() => undefined)); + disposers.push(() => assembled.host.apiHost.close()); const registry = createOperationRegistry(assembled.harnessPort); const call = async (name: string, body: unknown): Promise => { const entry = registry.get(name); diff --git a/packages/webui/test/integration/real-host-cron-task-mutations.test.ts b/packages/webui/test/integration/real-host-cron-task-mutations.test.ts index 7b5ef9578..f45db9cc5 100644 --- a/packages/webui/test/integration/real-host-cron-task-mutations.test.ts +++ b/packages/webui/test/integration/real-host-cron-task-mutations.test.ts @@ -9,7 +9,7 @@ * definition's schedule generation and next fire time belong to the shared row, and an operation * that answered with its own request would pass this test while the task ran on the wrong schedule. */ -import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { once } from "node:events"; @@ -22,21 +22,39 @@ import { createOperationRegistry } from "../../src/server/operation/operations.j import { WebuiService } from "../../src/server/service.js"; import { webuiCronDraftFromTask, webuiCronUpdateRequest } from "../../src/client/features/scheduling/projection/scheduling-panel.js"; import type { WebuiCronTask } from "../../src/shared/contracts/cron.js"; +import { removeRealHostDataDir } from "./remove-real-host-data-dir.js"; const disposers: Array<() => Promise | void> = []; afterEach(async () => { - for (const dispose of disposers.splice(0).reverse()) await dispose(); - vi.unstubAllEnvs(); + try { + for (const dispose of disposers.splice(0).reverse()) await dispose(); + } finally { + vi.unstubAllEnvs(); + (await import("@mavis/config")).resetConfig(); + } }); async function boot() { const dataDir = await mkdtemp(join(tmpdir(), "webui-cron-mutations-")); vi.stubEnv("MINIMAX_DATA_DIR", dataDir); - disposers.push(() => rm(dataDir, { recursive: true, force: true })); + disposers.push(() => removeRealHostDataDir(dataDir)); await mkdir(join(dataDir, "workspace"), { recursive: true }); + await writeFile(join(dataDir, "config.yaml"), JSON.stringify({ + defaultModel: "custom_provider:synthetic/stub-model", + custom_provider: { + synthetic: { + name: "Synthetic", api: "openai-completions", + options: { baseURL: "http://127.0.0.1:1/v1", apiKey: "synthetic-test-key" }, + models: { "stub-model": { id: "stub-model", name: "Synthetic Model" } }, + }, + }, + }), { mode: 0o600 }); + const config = await import("@mavis/config"); + config.resetConfig(); + expect(config.getConfig().dataDir).toBe(dataDir); const assembled = await createWebuiRuntimeHost({ dataDir, appVersion: "cron-mutations" }); - disposers.push(() => assembled.host.apiHost.close().catch(() => undefined)); + disposers.push(() => assembled.host.apiHost.close()); const registry = createOperationRegistry(assembled.harnessPort); const call = async (name: string, body: unknown): Promise => { const entry = registry.get(name); @@ -67,7 +85,7 @@ describe("scheduled-task mutations over the real service and the real host", () }; const created = await callWire("createCronTask", { name: "synthetic edit", agentName: "agent-one", prompt: "Do nothing.", - project: "/synthetic/project", model: "minimax/MiniMax-M3", + project: "/synthetic/project", model: "custom_provider:synthetic/stub-model", schedule: { kind: "recurring", expression: "0 9 * * *", timezone: "Asia/Shanghai", maxRuns: 7 }, sessionTarget: { mode: "new" }, }) as WebuiCronTask; diff --git a/packages/webui/test/integration/real-host-list-cron-tasks.test.ts b/packages/webui/test/integration/real-host-list-cron-tasks.test.ts index b6a44d285..cf712a46d 100644 --- a/packages/webui/test/integration/real-host-list-cron-tasks.test.ts +++ b/packages/webui/test/integration/real-host-list-cron-tasks.test.ts @@ -12,27 +12,38 @@ * own DTO, and the validator accepting the envelope the panel actually sends. Each of those rots * independently, so the assertion runs through all of them. */ -import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { createWebuiRuntimeHost } from "../../src/runtime/assembly.js"; import { createOperationRegistry } from "../../src/server/operation/operations.js"; +import { removeRealHostDataDir } from "./remove-real-host-data-dir.js"; const disposers: Array<() => Promise | void> = []; afterEach(async () => { - for (const dispose of disposers.splice(0).reverse()) await dispose(); + try { + for (const dispose of disposers.splice(0).reverse()) await dispose(); + } finally { + vi.unstubAllEnvs(); + (await import("@mavis/config")).resetConfig(); + } }); async function bootWebuiHost() { const dataDir = await mkdtemp(join(tmpdir(), "webui-list-cron-tasks-")); - disposers.push(() => rm(dataDir, { recursive: true, force: true })); + disposers.push(() => removeRealHostDataDir(dataDir)); await mkdir(join(dataDir, "workspace"), { recursive: true }); + await writeFile(join(dataDir, "config.yaml"), "{}\n", { mode: 0o600 }); + vi.stubEnv("MINIMAX_DATA_DIR", dataDir); + const config = await import("@mavis/config"); + config.resetConfig(); + expect(config.getConfig().dataDir).toBe(dataDir); const assembled = await createWebuiRuntimeHost({ dataDir, appVersion: "list-cron-tasks" }); - disposers.push(() => assembled.host.apiHost.close().catch(() => undefined)); + disposers.push(() => assembled.host.apiHost.close()); return assembled; } diff --git a/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts b/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts index bf29f1888..d05ca7757 100644 --- a/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts +++ b/packages/webui/test/integration/real-host-mcode-tools-bash-environment.test.ts @@ -282,7 +282,8 @@ describe("the real host, what the Agent's Bash inherits", () => { ) .toBeGreaterThan(0); const withResult = stub.requests.find((request) => carriesToolResult(request.body)); - const toolOutput = withResult?.body ?? ""; + const messages = JSON.parse(withResult!.body).messages as { role: string; content: string }[]; + const toolOutput = messages.filter((message) => message.role === "tool").map((message) => message.content).join("\n"); // The Bash subprocess saw the host keys — the endpoint and the // capability file that authenticate an mcode-tools run. diff --git a/packages/webui/test/integration/real-host-miniapp-tool.test.ts b/packages/webui/test/integration/real-host-miniapp-tool.test.ts index 8add76439..049e013e4 100644 --- a/packages/webui/test/integration/real-host-miniapp-tool.test.ts +++ b/packages/webui/test/integration/real-host-miniapp-tool.test.ts @@ -208,9 +208,12 @@ describe("the real WebUI host", () => { // The stub served a real turn, so the request body it recorded is the // tool table this client's agent actually works with. expect(stub.requests.length).toBeGreaterThan(0); - const body = JSON.parse(stub.requests[0]?.body ?? "{}") as { + // Title generation shares the endpoint and may arrive before the turn. + const turnRequests = stub.requests.map((request) => JSON.parse(request.body) as { readonly tools?: ReadonlyArray<{ readonly function?: { readonly name?: string } }>; - }; + }).filter((request) => !request.tools?.some((tool) => tool.function?.name === "submit_session_title")); + expect(turnRequests).toHaveLength(1); + const body = turnRequests[0]!; const toolNames = (body.tools ?? []).map((tool) => tool.function?.name); expect(toolNames).toContain("miniapp"); }, diff --git a/packages/webui/test/integration/real-host-skill-catalog.test.ts b/packages/webui/test/integration/real-host-skill-catalog.test.ts index abe518492..26f21dbf4 100644 --- a/packages/webui/test/integration/real-host-skill-catalog.test.ts +++ b/packages/webui/test/integration/real-host-skill-catalog.test.ts @@ -246,9 +246,16 @@ async function runTurnAndReadCatalog(betaMcodeTools: boolean | undefined): Promi const sent = await port.sendMessage({ id: sessionId as string, content: "hello stub" }); expect(sent.ok).toBe(true); - - await expect.poll(() => stub.requests.length, { timeout: 60_000 }).toBeGreaterThan(0); - const body = stub.requests[0]?.body ?? ""; + if (sent.ok) for await (const _frame of sent.source) void _frame; + // The background title request can win the race to the same model endpoint. + const turnRequests = stub.requests.filter((request) => { + const body = JSON.parse(request.body) as { + readonly tools?: ReadonlyArray<{ readonly function?: { readonly name?: string } }>; + }; + return !body.tools?.some((tool) => tool.function?.name === "submit_session_title"); + }); + expect(turnRequests).toHaveLength(1); + const body = turnRequests[0]!.body; const catalog = extractSkillCatalog(body); return { catalog, requested, ready: false }; } diff --git a/packages/webui/test/integration/remote-resource-lifetime.test.ts b/packages/webui/test/integration/remote-resource-lifetime.test.ts index 359ebba0d..9742cede5 100644 --- a/packages/webui/test/integration/remote-resource-lifetime.test.ts +++ b/packages/webui/test/integration/remote-resource-lifetime.test.ts @@ -2,7 +2,7 @@ import { once } from "node:events"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import * as pty from "node-pty"; +import { loadWebuiPty } from "../../src/runtime/native-pty.js"; import { afterEach, describe, expect, it, vi } from "vitest"; import { WebSocket } from "ws"; @@ -164,7 +164,7 @@ describe("remote resource lifetime through the production seams", () => { const transport: SshTransport = { run: async () => ({ stdout: SSH_PROBE_MARKER, stderr: "", code: 0, timedOut: false }), spawnTerminal: (_args, dimensions) => { - const child = pty.spawn("/bin/sh", ["-c", "printf READY; cat"], { ...dimensions, name: "xterm", env: process.env }); + const child = loadWebuiPty().spawn(process.execPath, ["-e", "process.stdin.on('data', data => process.stdout.write(data))"], { ...dimensions, name: "xterm", env: process.env }); terminalAlive = true; child.onExit(() => { terminalAlive = false; }); return { write: (value) => child.write(value), resize: (cols, rows) => child.resize(cols, rows), kill: () => child.kill(), onData: (listener) => { child.onData(listener); }, onExit: (listener) => { child.onExit(({ exitCode }) => listener({ code: exitCode })); } }; @@ -173,7 +173,9 @@ describe("remote resource lifetime through the production seams", () => { const runtime = await createSshRuntime({ dataDir: dataDir(), transport }); cleanup.push(() => runtime.dispose()); await runtime.connections.save({ alias: "local", endpoint: { kind: "manual", host: "synthetic.invalid" } }); - terminalId = (await runtime.terminals.open({ alias: "local" })).session.terminalId; + const opened = await runtime.terminals.open({ alias: "local" }); + expect(opened.session.error).toBeUndefined(); + terminalId = opened.session.terminalId; const watch = runtime.terminals.watch.bind(runtime.terminals); runtime.terminals.watch = async function* (id, signal) { subscribed.resolve(); @@ -193,6 +195,9 @@ describe("remote resource lifetime through the production seams", () => { })); socket.send(JSON.stringify({ kind: "request", protocolVersion: info.protocolVersion, requestId: "quiet", operation: kind === "ssh" ? "watchSshTerminal" : "watchRemoteControlStatus", body: kind === "ssh" ? { terminalId } : {} })); await subscribed.promise; + // Send through the real PTY after its watcher is attached, rather than + // depending on shell startup output arriving after subscription. + if (kind === "ssh") expect(await port.writeSshTerminal({ terminalId, data: "READY\r" })).toEqual({ accepted: true }); await initial; socket.close(); await once(socket, "close"); diff --git a/packages/webui/test/integration/remove-real-host-data-dir.ts b/packages/webui/test/integration/remove-real-host-data-dir.ts index f1468c1e4..02f051064 100644 --- a/packages/webui/test/integration/remove-real-host-data-dir.ts +++ b/packages/webui/test/integration/remove-real-host-data-dir.ts @@ -1,11 +1,18 @@ import { rm } from "node:fs/promises"; +import { setTimeout } from "node:timers/promises"; /** Remove an isolated host data directory after asynchronous host shutdown. */ -export function removeRealHostDataDir(dataDir: string): Promise { - return rm(dataDir, { - recursive: true, - force: true, - maxRetries: 10, - retryDelay: 100, - }); +export async function removeRealHostDataDir(dataDir: string): Promise { + // Retry the operation as a whole: recursive rm otherwise retries at every + // ancestor and can hide a permanently held handle behind a hook timeout. + for (let attempt = 0; ; attempt += 1) { + try { + await rm(dataDir, { recursive: true, force: true, maxRetries: 0 }); + return; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (attempt >= 10 || !["EBUSY", "EMFILE", "ENFILE", "ENOTEMPTY", "EPERM"].includes(code ?? "")) throw error; + await setTimeout(100); + } + } } diff --git a/packages/webui/test/unit/browser-bridge-trusted-extensions.test.ts b/packages/webui/test/unit/browser-bridge-trusted-extensions.test.ts index 8d8080f71..eac3907a6 100644 --- a/packages/webui/test/unit/browser-bridge-trusted-extensions.test.ts +++ b/packages/webui/test/unit/browser-bridge-trusted-extensions.test.ts @@ -78,7 +78,8 @@ describe("the trusted extension identities on disk", () => { expect(written.edge).toEqual([EDGE_ID]); // The file says which extensions this machine authorised. It is not a // secret, but it is not everybody's business either. - expect(statSync(file).mode & 0o077).toBe(0); + // Windows uses ACLs rather than the POSIX group/other mode bits. + if (process.platform !== "win32") expect(statSync(file).mode & 0o077).toBe(0); }); it("treats a file it cannot read as no identities at all", () => { diff --git a/packages/webui/test/unit/browser-workspace-panel.test.tsx b/packages/webui/test/unit/browser-workspace-panel.test.tsx index 5f085e451..0cb7c1f97 100644 --- a/packages/webui/test/unit/browser-workspace-panel.test.tsx +++ b/packages/webui/test/unit/browser-workspace-panel.test.tsx @@ -77,16 +77,16 @@ describe("the web tab kind", () => { } }); - it("is exactly the five tool views, in the ADR's order", () => { + it("is exactly the five tool views, with Mini Apps first", () => { // The new tab page is a launcher over the tool views, and the browser tool - // view is not one of them: the tiles are 变更, 终端, 画布, 应用 and 查看文件. + // view is not one of them: the tiles are 应用, 变更, 终端, 画布 and 查看文件. // 应用 opens the Mini App tool page, because which Mini App a tab shows is // chosen from the runtime's listing rather than from the tile. expect(webuiWorkspaceLauncherTiles().map((tile) => tile.kind)).toEqual([ + "miniapp-picker", "review", "terminal", "canvas", - "miniapp-picker", "files", ]); }); diff --git a/packages/webui/test/unit/ssh-endpoint.test.ts b/packages/webui/test/unit/ssh-endpoint.test.ts index b55858935..9a074247b 100644 --- a/packages/webui/test/unit/ssh-endpoint.test.ts +++ b/packages/webui/test/unit/ssh-endpoint.test.ts @@ -25,7 +25,7 @@ import { createSshRuntime } from "../../src/runtime/ssh/index.js"; import type { SshTransport } from "../../src/runtime/ssh/transport.js"; import { normalizeSshIdentityFile } from "../../src/runtime/ssh/validators.js"; -const HOME = "/home/tester"; +const HOME = process.platform === "win32" ? "C:\\Users\\tester" : "/home/tester"; const directories: string[] = []; function temporaryDataDir(): string { @@ -65,8 +65,8 @@ afterEach(() => { describe("a key path", () => { it("expands the tilde the way OpenSSH writes it", () => { - expect(normalizeSshIdentityFile("~/.ssh/id_ed25519", HOME)).toBe("/home/tester/.ssh/id_ed25519"); - expect(normalizeSshIdentityFile("~", HOME)).toBe("/home/tester"); + expect(normalizeSshIdentityFile("~/.ssh/id_ed25519", HOME)).toBe(path.join(HOME, ".ssh", "id_ed25519")); + expect(normalizeSshIdentityFile("~", HOME)).toBe(HOME); }); it("keeps a path that is already absolute", () => { @@ -147,7 +147,7 @@ describe("a saved host", () => { }); expect(saved.success).toBe(true); - expect(saved.connection?.endpoint.identityFile).toBe("/home/tester/.ssh/id_ed25519"); + expect(saved.connection?.endpoint.identityFile).toBe(path.join(HOME, ".ssh", "id_ed25519")); }); it("refuses a key path that is not a path at all", async () => { diff --git a/packages/webui/test/unit/ssh-remote-command.test.ts b/packages/webui/test/unit/ssh-remote-command.test.ts index 3f3690256..792874e9c 100644 --- a/packages/webui/test/unit/ssh-remote-command.test.ts +++ b/packages/webui/test/unit/ssh-remote-command.test.ts @@ -10,7 +10,7 @@ * answer is pinned and not only its syntax. */ import { spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -102,7 +102,8 @@ describe("the remote commands", () => { .split(String.fromCharCode(0)) .filter((field) => field.length > 0); expect(fields[0]).toBe("status=ready"); - expect(fields[1]).toBe(`path=${root}`); + const canonicalRoot = realpathSync(root); + expect(fields[1]).toBe(`path=${canonicalRoot}`); // The entries follow as a kind and a path, one pair each — the reader walks them two at // a time. const entries = fields.slice(2); @@ -111,7 +112,7 @@ describe("the remote commands", () => { for (let index = 0; index + 1 < entries.length; index += 2) { pairs.push(`${entries[index]} ${entries[index + 1]}`); } - expect(pairs).toContain(`directory ${path.join(root, "src")}`); - expect(pairs).toContain(`file ${path.join(root, "readme.md")}`); + expect(pairs).toContain(`directory ${path.join(canonicalRoot, "src")}`); + expect(pairs).toContain(`file ${path.join(canonicalRoot, "readme.md")}`); }); }); diff --git a/packages/webui/test/unit/ssh-store-transaction.test.ts b/packages/webui/test/unit/ssh-store-transaction.test.ts index 8de99ab35..afcf73988 100644 --- a/packages/webui/test/unit/ssh-store-transaction.test.ts +++ b/packages/webui/test/unit/ssh-store-transaction.test.ts @@ -20,6 +20,7 @@ import { createRequire } from "node:module"; import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { pathToFileURL } from "node:url"; import { rename } from "node:fs/promises"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -65,7 +66,7 @@ function host(alias: string) { afterEach(() => { while (directories.length > 0) { const directory = directories.pop(); - if (directory) rmSync(directory, { recursive: true, force: true }); + if (directory) rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } }); @@ -89,7 +90,7 @@ describe("the SSH connection store", () => { await entered; // 旧租约被抢走时,最终 rename 仍然挂起;新锁必须覆盖这个窗口。 rmSync(`${file}.lock`, { recursive: true, force: true }); - const loader = createRequire(import.meta.url).resolve("tsx"); + const loader = pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href; const child = spawn(process.execPath, ["--import", loader, "--input-type=module", "-e", ` const { createRequire } = await import('node:module'); const require = createRequire(process.cwd() + '/package.json'); @@ -192,7 +193,7 @@ describe("the SSH connection store", () => { await hosts.save(host("switch")); await hosts.save(host("doomed")); await projects.save({ id: "old", alias: "doomed", path: "/old", displayName: "Old" }); - const loader = createRequire(import.meta.url).resolve("tsx"); + const loader = pathToFileURL(createRequire(import.meta.url).resolve("tsx")).href; const script = ` const { createSshConnectionRepository } = await import(${JSON.stringify(new URL("../../src/runtime/ssh/connection-repository.ts", import.meta.url).href)}); const { createSshProjectRepository } = await import(${JSON.stringify(new URL("../../src/runtime/ssh/project-repository.ts", import.meta.url).href)}); diff --git a/packages/webui/test/unit/terminal-process-manager.test.ts b/packages/webui/test/unit/terminal-process-manager.test.ts index 7275d1920..ac124d21d 100644 --- a/packages/webui/test/unit/terminal-process-manager.test.ts +++ b/packages/webui/test/unit/terminal-process-manager.test.ts @@ -9,8 +9,39 @@ // for) instead of asserting that nothing seemed to happen. import { describe, expect, it } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; import { WebuiTerminalManager } from "../../src/runtime/terminal.js"; +import { prepareWebuiPtyHelper } from "../../src/runtime/native-pty.js"; + +describe("native PTY helper permissions", () => { + it.skipIf(process.platform === "win32")("repairs the packaged macOS helper and preserves its existing permissions", () => { + const root = mkdtempSync(path.join(tmpdir(), "webui-pty-")); + try { + for (const relative of ["build/Release/spawn-helper", "prebuilds/darwin-arm64/spawn-helper"]) { + const helper = path.join(root, relative); + mkdirSync(path.dirname(helper), { recursive: true }); + writeFileSync(helper, "synthetic helper permission fixture", { mode: 0o640 }); + } + prepareWebuiPtyHelper(root, "darwin", "arm64"); + for (const relative of ["build/Release/spawn-helper", "prebuilds/darwin-arm64/spawn-helper"]) { + expect(statSync(path.join(root, relative)).mode & 0o777).toBe(0o751); + } + prepareWebuiPtyHelper(root, "darwin", "arm64"); + expect(statSync(path.join(root, "prebuilds/darwin-arm64/spawn-helper")).mode & 0o777).toBe(0o751); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("requires a macOS helper and leaves other platforms alone", () => { + expect(() => prepareWebuiPtyHelper("missing-native-module", "darwin", "arm64")).toThrow("spawn-helper is missing"); + expect(() => prepareWebuiPtyHelper("missing-native-module", "win32")).not.toThrow(); + expect(() => prepareWebuiPtyHelper("missing-native-module", "linux")).not.toThrow(); + }); +}); interface FakePty { readonly pid: number; diff --git a/packages/webui/test/unit/token-plan-model.test.ts b/packages/webui/test/unit/token-plan-model.test.ts index 0dfd61a55..8b93f6c47 100644 --- a/packages/webui/test/unit/token-plan-model.test.ts +++ b/packages/webui/test/unit/token-plan-model.test.ts @@ -227,7 +227,7 @@ describe("context panel — hover names it, click opens it", () => { expect(indicator).toContain("onOpen={() => {"); expect(indicator).toContain("onClose={() => setOpen(false)}"); expect(dropdown).toContain("if (open) onClose();"); - expect(dropdown).toContain("else onOpen();"); + expect(dropdown).toMatch(/else\s*\{[\s\S]*?triggerRef\.current\?\.focus\(\);\s*onOpen\(\);/u); }); it("carries a hover label naming the ring, hidden from assistive tech", () => { diff --git a/packages/webui/test/unit/webui-application-lifecycle.test.ts b/packages/webui/test/unit/webui-application-lifecycle.test.ts index a80411af7..4664936ff 100644 --- a/packages/webui/test/unit/webui-application-lifecycle.test.ts +++ b/packages/webui/test/unit/webui-application-lifecycle.test.ts @@ -537,7 +537,10 @@ describe("V02 · independent owners' pending IO cannot commit after disposal", ( const pending = Promise.all([ application.modelsWorkflows.loadModels(SESSION), application.settingsWorkflows.loadInstructions(), - application.composerPluginCatalogue.installedPlugins(), + application.composerPluginCatalogue.installedPlugins().then( + () => { throw new Error("A disposed catalogue must refuse its late answer"); }, + (error: unknown) => { expect(error).toEqual(new Error("插件目录读取已失效,请重试。")); }, + ), application.turnReview.load({ sessionId: SESSION, turnId: "turn-1" }), application.transcriptHistory.loadPage(SESSION), Promise.resolve(application.workspaceQueries.files.loadFileTree("/repo")), diff --git a/packages/webui/test/unit/workspace-tab-registry.test.ts b/packages/webui/test/unit/workspace-tab-registry.test.ts index 471d98546..840f1be09 100644 --- a/packages/webui/test/unit/workspace-tab-registry.test.ts +++ b/packages/webui/test/unit/workspace-tab-registry.test.ts @@ -108,27 +108,24 @@ describe("the registry answers for the whole closed set", () => { it("offers the launcher's tiles in one order, and only where a tile exists", () => { const tiles = webuiWorkspaceLauncherTiles(); expect(tiles.map((tile) => tile.kind)).toEqual([ + "miniapp-picker", "review", "terminal", "canvas", - "miniapp-picker", "files", ]); expect(tiles.map((tile) => tile.label)).toEqual([ + "应用", "变更", "终端", "画布", - "应用", "查看文件", ]); expect(tiles.map((tile) => tile.opens)).toEqual([ + { type: "open-tab", kind: "miniapp-picker" }, { type: "open-workspace-review" }, { type: "open-tab", kind: "terminal" }, { type: "open-tab", kind: "canvas" }, - // The Mini App tile opens the Mini App tool page: which Mini App a tab - // shows is chosen from the runtime's listing, so this tile carries no - // plugin id and the page it opens is the one the choice is made in. - { type: "open-tab", kind: "miniapp-picker" }, { type: "open-tab", kind: "files" }, ]); // Every tile names a declared kind, and the order names each one once. diff --git a/packages/webui/test/unit/workspace-tab-strip.test.tsx b/packages/webui/test/unit/workspace-tab-strip.test.tsx index 21fd77c52..3d33973fb 100644 --- a/packages/webui/test/unit/workspace-tab-strip.test.tsx +++ b/packages/webui/test/unit/workspace-tab-strip.test.tsx @@ -387,7 +387,7 @@ describe("the new tab page", () => { } expect( webuiWorkspaceLauncherTileCommand( - webuiWorkspaceLauncherTiles()[0]!, + webuiWorkspaceLauncherTiles().find((tile) => tile.kind === "review")!, "tab-3", { sessionId: "session-1", workspaceDir: "/work" }, ), @@ -404,7 +404,7 @@ describe("the new tab page", () => { // it has nothing to open, so it is not rendered rather than rendered dead. expect( webuiWorkspaceLauncherTileCommand( - webuiWorkspaceLauncherTiles()[0]!, + webuiWorkspaceLauncherTiles().find((tile) => tile.kind === "review")!, "tab-3", { sessionId: "session-1" }, ), diff --git a/playwright.config.mjs b/playwright.config.mjs index 74c9fd816..5a4c8abc1 100644 --- a/playwright.config.mjs +++ b/playwright.config.mjs @@ -31,6 +31,7 @@ const fontEnvironment = prepareFontEnvironment(root, { // explicitly and anything else fails loudly on a busy port instead. CI never // reuses: it is a fresh machine per run and has nothing to reuse. const reuseExistingServer = !process.env.CI && process.env.WEBUI_BROWSER_REUSE === "1"; +const headedBrowser = process.env.WEBUI_BROWSER_HEADED === "1"; export default defineConfig({ testDir: "./packages/webui/test/browser", @@ -48,7 +49,8 @@ export default defineConfig({ colorScheme: "light", reducedMotion: "reduce", browserName: "chromium", - headless: true, + channel: headedBrowser ? "chromium" : undefined, + headless: !headedBrowser, trace: "retain-on-failure", launchOptions: { env: { ...process.env, ...fontEnvironment.env }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e08e17a58..c990793ae 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -41,6 +41,9 @@ importers: axe-core: specifier: 4.14.0 version: 4.14.0 + cross-spawn: + specifier: 7.0.6 + version: 7.0.6 esbuild: specifier: 0.28.2 version: 0.28.2 @@ -957,6 +960,9 @@ importers: '@xterm/xterm': specifier: 6.0.0 version: 6.0.0 + better-sqlite3: + specifier: 12.11.1 + version: 12.11.1 highlight.js: specifier: 10.7.3 version: 10.7.3 @@ -975,9 +981,6 @@ importers: node-pty: specifier: 1.1.0 version: 1.1.0 - better-sqlite3: - specifier: 12.11.1 - version: 12.11.1 qrcode.react: specifier: 4.2.0 version: 4.2.0(react@18.3.1) @@ -6772,7 +6775,7 @@ snapshots: obug: 2.2.1 std-env: 4.2.0 tinyrainbow: 3.1.1 - vitest: 4.1.11(@opentelemetry/api@1.9.0)(@types/node@20.19.43)(@vitest/coverage-v8@4.1.11)(vite@7.3.6(@types/node@20.19.43)(jiti@2.7.0)(tsx@4.23.13)(yaml@2.9.1)) + vitest: 4.1.11(@opentelemetry/api@1.9.0)(@types/node@20.19.43)(@vitest/coverage-v8@4.1.11)(vite@7.3.6(@types/node@20.19.43)(jiti@2.7.0)(tsx@4.23.15)(yaml@2.9.1)) '@vitest/expect@4.1.11': dependencies: diff --git a/release/public-source.json b/release/public-source.json index 8a3e92027..c1be1bbd5 100644 --- a/release/public-source.json +++ b/release/public-source.json @@ -4473,6 +4473,7 @@ "packages/webui/src/runtime/mcode-tools-entry.ts", "packages/webui/src/runtime/mcode-tools-environment.ts", "packages/webui/src/runtime/mcode-tools.ts", + "packages/webui/src/runtime/native-pty.ts", "packages/webui/src/runtime/port.ts", "packages/webui/src/runtime/profile-files.ts", "packages/webui/src/runtime/remote-control/bridge/attachment-fetch.ts", @@ -4652,6 +4653,7 @@ "packages/webui/test/browser/account-login.spec.mjs", "packages/webui/test/browser/api-key-feedback.spec.mjs", "packages/webui/test/browser/application-observation.spec.mjs", + "packages/webui/test/browser/application-performance.mjs", "packages/webui/test/browser/architecture-acceptance.spec.mjs", "packages/webui/test/browser/browser-bridge-real-browser.spec.ts", "packages/webui/test/browser/browser-bridge-real-external.spec.ts", @@ -4679,10 +4681,18 @@ "packages/webui/test/browser/native-runtime.spec.mjs", "packages/webui/test/browser/overlay-coordination.spec.mjs", "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-darwin.png", "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-linux.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Agent-add-form-is-centered-fields-are-aligned-and-backdrop-dismissal-works-1-win32.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-darwin.png", "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-linux.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Git-plugin-import-form-is-an-accessible-viewport-overlay-and-previews-local-fixture-data-1-win32.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-darwin.png", "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-linux.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/MCP-add-form-validates-inputs-switches-transport-and-sends-advanced-HTTP-config-1-win32.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-darwin.png", "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-linux.png", + "packages/webui/test/browser/plugin-catalogue-layout.spec.mjs-snapshots/Skill-add-form-is-centered-usable-and-submits-through-plugin-management-1-win32.png", "packages/webui/test/browser/plugin-mcp-status.spec.mjs", "packages/webui/test/browser/provider-form.spec.mjs", "packages/webui/test/browser/questionnaire.spec.mjs", @@ -4694,23 +4704,49 @@ "packages/webui/test/browser/recovered-surfaces.spec.mjs", "packages/webui/test/browser/rendering-integrity.spec.mjs", "packages/webui/test/browser/responsive-baselines.spec.mjs", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1024-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1280-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-1440-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-480-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-640-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-768-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/shell-at-900-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1024-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-1440-win32.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-darwin.png", "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-linux.png", + "packages/webui/test/browser/responsive-baselines.spec.mjs-snapshots/workspace-panel-at-768-win32.png", "packages/webui/test/browser/responsive-layout.spec.mjs", "packages/webui/test/browser/review-consumers.spec.mjs", "packages/webui/test/browser/review-diff-colors.spec.mjs", "packages/webui/test/browser/scheduling-panel.spec.mjs", + "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-darwin.png", "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-linux.png", + "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-editor-win32.png", + "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-darwin.png", "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-linux.png", + "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-darwin.png", "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-linux.png", + "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-runs-win32.png", + "packages/webui/test/browser/scheduling-panel.spec.mjs-snapshots/scheduling-panel-win32.png", "packages/webui/test/browser/select-dynamic-options.spec.mjs", "packages/webui/test/browser/select-keyboard.spec.mjs", "packages/webui/test/browser/server.mjs", @@ -4737,16 +4773,36 @@ "packages/webui/test/browser/transcript.spec.mjs", "packages/webui/test/browser/turn-lifecycle.spec.mjs", "packages/webui/test/browser/visual-baselines.spec.mjs", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/composer-command-overlay-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/embedded-browser-panel-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/mcp-management-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/plugin-marketplace-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/progress-panel-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/settings-dialog-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/shell-and-rail-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-management-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/skill-marketplace-win32.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-darwin.png", "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-linux.png", + "packages/webui/test/browser/visual-baselines.spec.mjs-snapshots/transcript-and-composer-win32.png", "packages/webui/test/browser/workspace-canvas.spec.mjs", "packages/webui/test/browser/workspace-panel-actions.spec.mjs", "packages/webui/test/browser/workspace-panel-robustness.spec.mjs", diff --git a/release/webui-npm/bin/mcode-webui.mjs b/release/webui-npm/bin/mcode-webui.mjs index 555b2de3e..c47c1543f 100644 --- a/release/webui-npm/bin/mcode-webui.mjs +++ b/release/webui-npm/bin/mcode-webui.mjs @@ -315,6 +315,16 @@ try { console.log("Press Ctrl+C to stop the server."); process.once("SIGINT", () => void close().finally(() => process.exit(0))); process.once("SIGTERM", () => void close().finally(() => process.exit(0))); + // Windows process.kill cannot deliver a catchable POSIX signal. A Node + // parent can request the same graceful teardown over its private IPC pipe. + if (process.send) process.on("message", (message) => { + if (message?.type === "mcode-webui:shutdown") { + void close().then(() => process.exit(0), (error) => { + console.error(error); + process.exit(1); + }); + } + }); } catch (error) { await close(); throw error; diff --git a/scripts/check-webui-motion.d.mts b/scripts/check-webui-motion.d.mts index 9e4da4b10..01399e13f 100644 --- a/scripts/check-webui-motion.d.mts +++ b/scripts/check-webui-motion.d.mts @@ -41,3 +41,7 @@ export function featureRotationOwnershipProblems(file: string, text: string): st export function featureSmoothScrollOwnershipProblems(file: string, text: string): string[]; export function featureInteractionTransformOwnershipProblems(file: string, text: string): string[]; export function scanClient(root?: string): Promise>; +export function checkMotionOwnership( + inventory: MotionInventory, + enumerate?: (pattern: string, options: { cwd: string }) => AsyncIterable, +): Promise<{ problems: string[]; approvedStylesheets: number; rawUtilityClasses: number }>; diff --git a/scripts/check-webui-motion.mjs b/scripts/check-webui-motion.mjs index 30b7438fe..db481abd4 100644 --- a/scripts/check-webui-motion.mjs +++ b/scripts/check-webui-motion.mjs @@ -420,12 +420,13 @@ function animationAssetImports(file, text) { return assets; } -async function checkMotionOwnership(inventory) { +export async function checkMotionOwnership(inventory, enumerate = glob) { const problems = []; let approvedStylesheets = 0; let rawUtilityClasses = 0; const importedAnimationAssets = new Map(); - for await (const file of glob("**/*.css", { cwd: clientRoot })) { + for await (const entry of enumerate("**/*.css", { cwd: clientRoot })) { + const file = entry.replaceAll("\\", "/"); const text = readFileSync(path.join(clientRoot, file), "utf8"); const stylesheet = text.replace(/\/\*[\s\S]*?\*\//gu, ""); if (file !== "styles/motion.css" && /[^{}]*\.webui-skeleton(?:[\s.#:[>+~]|$)[^{}]*\{/u.test(stylesheet)) { @@ -458,7 +459,8 @@ async function checkMotionOwnership(inventory) { } } - for await (const file of glob("**/*.{ts,tsx}", { cwd: clientRoot })) { + for await (const entry of enumerate("**/*.{ts,tsx}", { cwd: clientRoot })) { + const file = entry.replaceAll("\\", "/"); const text = readFileSync(path.join(clientRoot, file), "utf8"); const fileProblems = sourceMotionOwnershipProblems(file, text); rawUtilityClasses += fileProblems.filter((problem) => problem.includes("raw source motion utility")).length; diff --git a/scripts/lib/webui-presentation-inventory.json b/scripts/lib/webui-presentation-inventory.json index e24116263..d78690b27 100644 --- a/scripts/lib/webui-presentation-inventory.json +++ b/scripts/lib/webui-presentation-inventory.json @@ -229,7 +229,7 @@ "features/settings/ui/SettingsModal.tsx": "85efc7db47572b26", "features/settings/ui/ShortcutsSettings.tsx": "ee297c77956443b8", "features/settings/ui/UsageHeatmap.tsx": "3effdfb9671baf89", - "features/settings/ui/UsageModelSettings.tsx": "965255c8cd5e0f22", + "features/settings/ui/UsageModelSettings.tsx": "82ca29b07f2ddfcc", "features/settings/ui/UsageResetCards.tsx": "ea83782db7f6af63", "features/settings/ui/UserProfileSection.tsx": "06a06ab9ab227da3", "features/settings/ui/account-usage-glyphs.tsx": "42d9ecdccaae8b0f", @@ -257,7 +257,7 @@ "features/transcript/ui/TranscriptPrimitives.tsx": "710f935727950fee", "features/transcript/ui/TranscriptSkeletons.tsx": "cd9ed7922014279d", "features/transcript/ui/TurnNavigator.tsx": "3e3dbee1a59deed8", - "features/transcript/ui/markdown.public.tsx": "0b67429c899771d5", + "features/transcript/ui/markdown.public.tsx": "08cb6f9e3ea1e719", "features/transcript/ui/webui-mermaid.tsx": "fc1aab96c48f3a3d", "features/workspace/ui/WebuiWorkspaceDirectoryBrowser.public.tsx": "25ae2bc524e495b7", "features/workspace/ui/WebuiWorkspaceTabStrip.public.tsx": "70a32a14d51fa43a", @@ -303,7 +303,7 @@ "ui/menu-item.tsx": "086f3bf5bbd0e8da", "ui/overlay-coordinator.tsx": "ed3d94391cdde3a7", "ui/overlay-listeners.tsx": "86696d33c0fe4f73", - "ui/page.tsx": "0ee0c0ef9dd3dea5", + "ui/page.tsx": "912debc12201cce4", "ui/segmented-control.tsx": "1e44618d2ebb0b74", "ui/settings-glyphs.tsx": "e5b21c9f9bb243c5", "ui/settings-layout.tsx": "452bc0adcd989304", diff --git a/scripts/verify-webui-package.mjs b/scripts/verify-webui-package.mjs index e384b5661..528878b26 100644 --- a/scripts/verify-webui-package.mjs +++ b/scripts/verify-webui-package.mjs @@ -1,4 +1,5 @@ -import { spawn, spawnSync } from "node:child_process"; +import { spawn } from "node:child_process"; +import spawnCommand from "cross-spawn"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { createServer } from "node:net"; import path from "node:path"; @@ -38,7 +39,7 @@ mkdirSync(scratch, { recursive: true }); const work = mkdtempSync(path.join(scratch, "installed-")); const npm = process.platform === "win32" ? "npm.cmd" : "npm"; function run(command, args, options = {}) { - const result = spawnSync(command, args, { cwd: root, encoding: "utf8", timeout: 300_000, maxBuffer: 4 * 1024 * 1024, ...options }); + const result = spawnCommand.sync(command, args, { cwd: root, encoding: "utf8", timeout: 300_000, maxBuffer: 4 * 1024 * 1024, ...options }); if (result.error || result.status !== 0) throw new Error(`${path.basename(command)} failed: ${result.error?.message ?? result.stderr ?? result.signal}`); return result.stdout; } @@ -108,7 +109,7 @@ try { MAVIS_BROWSER_STORE_CHROME_EXTENSION_IDS: SELF_HOSTED_EXTENSION_ID, MAVIS_BROWSER_CHROME_EXTENSION_IDS: DEVELOPMENT_EXTENSION_ID, }, - stdio: ["ignore", "pipe", "pipe"], + stdio: ["ignore", "pipe", "pipe", "ipc"], }); let output = ""; child.stdout.on("data", (chunk) => { output = (output + chunk).slice(-32_768); }); @@ -176,7 +177,8 @@ try { const refused = await bridgeUpgrade(port, DEVELOPMENT_EXTENSION_ID); if (refused) throw new Error("The installed WebUI accepted a development extension identity"); const exited = once(child, "exit"); - child.kill("SIGTERM"); + if (process.platform === "win32") child.send({ type: "mcode-webui:shutdown" }); + else child.kill("SIGTERM"); const [code, signal] = await Promise.race([exited, new Promise((_, reject) => setTimeout(() => reject(new Error("Installed WebUI shutdown timed out")), 10_000).unref())]); if (code !== 0 || signal !== null) throw new Error(`Installed WebUI shutdown failed: ${code ?? signal}`); child = undefined; diff --git a/test/source-sync.test.mjs b/test/source-sync.test.mjs index e92203ae3..4bad41e30 100644 --- a/test/source-sync.test.mjs +++ b/test/source-sync.test.mjs @@ -54,9 +54,22 @@ test('public WebUI CI runs only WebUI checks and cannot publish packages', () => assert.ok(commands.includes(command), `Missing ${command}`); } assert.ok(commands.indexOf('pnpm build:webui') < commands.indexOf('pnpm test:webui-browser')); - for (const command of ['pnpm test:webui', 'pnpm test:webui-browser', 'pnpm test:webui-package']) { - assert.equal(job.steps.find(step => step.run === command).if, undefined, `${command} must run on every platform`); + assert.equal(job.steps.find(step => step.run === 'pnpm build:webui').id, 'build'); + assert.equal(job.steps.find(step => step.run === 'pnpm install:webui-browsers').id, 'browsers'); + const testConditions = { + 'pnpm test:webui': undefined, + 'pnpm test:webui-browser': "${{ !cancelled() && steps.build.outcome == 'success' && steps.browsers.outcome == 'success' }}", + 'pnpm test:webui-package': "${{ !cancelled() && steps.build.outcome == 'success' }}", + }; + for (const [command, condition] of Object.entries(testConditions)) { + const step = job.steps.find(step => step.run === command); + assert.equal(step.if, condition, `${command} must run on every platform and preserve independent failures`); + assert.equal(step['continue-on-error'], undefined, `${command} must fail the job on a regression`); } + assert.equal(job['continue-on-error'], undefined); + const diagnostics = job.steps.find(step => step.name === 'Upload WebUI browser diagnostics'); + assert.equal(diagnostics.if, '${{ !cancelled() }}', 'Successful runs must retain raw performance samples too'); + assert.equal(diagnostics.with['retention-days'], 7); }); test('coverage review distinguishes declared browser scenarios from executed evidence', () => {