diff --git a/.github/workflows/desktop-e2e.yml b/.github/workflows/desktop-e2e.yml index bbf18bb6d15..9999764568b 100644 --- a/.github/workflows/desktop-e2e.yml +++ b/.github/workflows/desktop-e2e.yml @@ -157,15 +157,15 @@ jobs: # The terminal-cancel suite drives a real tmux server; without tmux its tmux scenarios skip. - name: Install tmux run: brew install tmux + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' - name: Run Playwright _electron smoke suite working-directory: apps/desktop run: bun run ../../scripts/desktop-e2e.ts ${{ matrix.shard }}/${{ strategy.job-total }} env: PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/desktop-smoke.json - BACKGROUND_EXECUTOR_REPORT_PATH: test-results/background-executor-report.json - TERMINAL_CANCEL_REPORT_PATH: test-results/terminal-cancel-report.json - CONTINUE_SIGN_IN_REPORT_PATH: test-results/continue-sign-in-report.json - name: Upload test results if: failure() @@ -244,14 +244,13 @@ jobs: # The terminal-cancel suite drives a real tmux server; without tmux its tmux scenarios skip. - name: Install tmux run: brew install tmux + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' - name: Run Playwright _electron smoke suite working-directory: apps/desktop run: bunx playwright test - env: - BACKGROUND_EXECUTOR_REPORT_PATH: test-results/background-executor-report.json - TERMINAL_CANCEL_REPORT_PATH: test-results/terminal-cancel-report.json - CONTINUE_SIGN_IN_REPORT_PATH: test-results/continue-sign-in-report.json - name: Upload test results if: failure() diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 836f2a2644d..32ff85e3945 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -221,15 +221,15 @@ jobs: - name: Install tmux run: brew install tmux + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' - name: Run Electron smoke partition working-directory: apps/desktop env: SIM_DESKTOP_DEFAULT_ORIGIN: ${{ needs.source.outputs.origin }} PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/desktop-smoke.json - BACKGROUND_EXECUTOR_REPORT_PATH: test-results/background-executor-report.json - TERMINAL_CANCEL_REPORT_PATH: test-results/terminal-cancel-report.json - CONTINUE_SIGN_IN_REPORT_PATH: test-results/continue-sign-in-report.json run: bun run ../../scripts/desktop-e2e.ts ${{ matrix.shard }}/${{ strategy.job-total }} - name: Upload smoke coverage and timings diff --git a/apps/desktop/README.md b/apps/desktop/README.md index f6c2caafc8f..5a73dee13c5 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -205,7 +205,7 @@ Approved native reads can return bounded text, directory listings, images, or PD - `electron-updater` reads the deployment's `/api/desktop/update` feed; production resolves stable releases from `simstudioai/sim`, while dev/staging resolve prereleases from `simstudioai/sim-desktop-releases`. Artifact downloads go directly to GitHub and deltas use `.zip.blockmap`. Sim validates every candidate before starting its download. Developer ID builds installed under `/Applications` use a prompt (Restart and update / Later; Later installs on quit); other packaged builds offer a validated installer download — never forced mid-session. A staged or offered update keeps being re-checked on the normal cadence, and a newer release replaces it, so a shell left running across several releases installs the latest build in one restart instead of the stale one followed by another prompt. - Streams: production follows stable `X.Y.Z` releases, dev follows `-dev.N`, and staging follows `-staging.N`. The feed still recognizes legacy `-alpha.N`/`-beta.N` releases during migration. - Restart becomes available only after Squirrel confirms native staging. Replacing a staged update returns the UI to downloading; a failed transfer can retain the previous staged build, but a failure after the native feed is replaced requires a retry. Diagnostics record `update_downloaded` after native staging, `update_install` when an explicit restart is committed, and `update_install_result` on the next launch with the expected and installed versions. The staging checkpoint also covers updates installed on a normal quit. -- `bun run test:e2e e2e/updater.spec.ts` exercises the real Electron process, MacUpdater, downloads, retries, and installation checkpoints. Native verification and bundle replacement are simulated. Set `DESKTOP_UPDATER_REPORT_PATH` to choose the JSON report path; by default it is included in Playwright's test results and uploaded by CI on failure. +- `bun run test:e2e e2e/updater.spec.ts` exercises the real Electron process, MacUpdater, downloads, retries, and installation checkpoints. Native verification and bundle replacement are simulated. Each check is a Playwright step, so it appears in the run's JSON report and in the results CI uploads on failure. - Staged rollout: after publishing, edit `stagingPercentage: 10` into the release's `latest-mac.yml`, then raise as crash metrics stay clean. - Rollback: a pulled release must be superseded by a **higher** version — users on the broken build will not reinstall an equal one. (A blocked-versions kill-switch was removed as unwired dead code; reintroduce it in `updater.ts` if a remote config source ever exists to feed it.) - Ship the DMG and tell users to install to `/Applications` — App Translocation breaks Squirrel.Mac updates from quarantined paths. diff --git a/apps/desktop/e2e-durations.json b/apps/desktop/e2e-durations.json index 7d184cc16b2..f839f479f5f 100644 --- a/apps/desktop/e2e-durations.json +++ b/apps/desktop/e2e-durations.json @@ -7,7 +7,6 @@ "browser-sign-in-prompts.spec.ts": 29.02, "browser-tools.spec.ts": 136.49, "chat-panel.spec.ts": 19.81, - "check-report.spec.ts": 2.48, "computer-use.spec.ts": 3.62, "continue-sign-in.spec.ts": 10.93, "desktop-tools-live-sim.spec.ts": 0.0, diff --git a/apps/desktop/e2e/background-executor.spec.ts b/apps/desktop/e2e/background-executor.spec.ts index 5849198fbc5..79cb4d83a6a 100644 --- a/apps/desktop/e2e/background-executor.spec.ts +++ b/apps/desktop/e2e/background-executor.spec.ts @@ -1,26 +1,13 @@ -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - renameSync, - rmSync, - writeFileSync, -} from 'node:fs' -import { tmpdir } from 'node:os' +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { type ElectronApplication, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' +import type { ElectronApplication, Page } from '@playwright/test' import { sleep } from '@sim/utils/helpers' -import { recordCheck } from './check-report' import { answerShellDialog, - type FixtureCall, FixtureSim, - launch, + journalState, + launchAgainst, processRunning, - RECONCILE_MS, readFileSafe, refFor, registeredDevice, @@ -28,18 +15,24 @@ import { sha256, WORKSPACE, } from './executor-sim' +import { type DesktopBridge, expect, test } from './harness' /** * The Sim desktop app's background executor against a fixture Sim that speaks the executor's * device protocol (register, inbox, doorbell, claim, lease, complete, import) the way Sim's * routes do. * The window navigates, reloads and leaves the chats while their calls run: nothing in this - * suite depends on a chat view, which is the point. Each check lands in a JSON report at - * BACKGROUND_EXECUTOR_REPORT_PATH as it finishes. + * suite depends on a chat view, which is the point. */ /** Sim's window for a device to claim an offered call (DESKTOP_TOOL_PICKUP_GRACE_MS in Sim). */ const SIM_PICKUP_GRACE_MS = 15_000 +/** + * Long enough that only the doorbell can explain a prompt reaction: with jitter, the device's own + * inbox reads come at least 24s apart. + */ +const SLOW_RECONCILE_MS = 30_000 +const DOORBELL_REACTION_MS = 10_000 const CHAT_A = 'chat-browser-a' const CHAT_B = 'chat-terminal-b' @@ -47,36 +40,78 @@ const CHAT_C = 'chat-idle-c' const sim = new FixtureSim() -/** Runs one check and adds its outcome to the report as soon as it is known. */ -async function check(name: string, body: () => Promise): Promise { - const startedAt = Date.now() - const record = (status: 'passed' | 'failed', error?: unknown) => - recordCheck(process.env.BACKGROUND_EXECUTOR_REPORT_PATH, 'background-executor', { - name, - status, - durationMs: Date.now() - startedAt, - retry: test.info().retry, - ...(error === undefined ? {} : { error: getErrorMessage(error) }), - }) - try { - await body() - record('passed') - } catch (error) { - record('failed', error) - throw error - } +type SleepBlockerProbe = typeof globalThis & { __heldSleepBlockers?: Map } + +/** Replaces the power blocker with one that records what is held, before any work arrives. */ +async function stubSleepBlockers(app: ElectronApplication): Promise { + await app.evaluate(({ powerSaveBlocker }) => { + const held = new Map() + let next = 1 + ;(globalThis as SleepBlockerProbe).__heldSleepBlockers = held + powerSaveBlocker.start = (type) => { + held.set(next, type) + return next++ + } + powerSaveBlocker.stop = (id) => held.delete(id) + powerSaveBlocker.isStarted = (id) => held.has(id) + }) +} + +function heldSleepBlockers(app: ElectronApplication): Promise { + return app.evaluate(() => [ + ...((globalThis as SleepBlockerProbe).__heldSleepBlockers?.values() ?? []), + ]) } -test.describe('background executor', () => { - let app: ElectronApplication | null = null +function offeredDevice(window: Page) { + return window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.desktopExecutor?.getDevice() + ) +} + +/** + * The user presses Tab in the agent's page. Resolves once Chromium has delivered the key to the + * page, which is when the app records the input; `sendInputEvent` itself returns before that. + */ +async function userTypesInPage(app: ElectronApplication, pageUrl: string): Promise { + await app.evaluate(async ({ webContents }, pageUrl) => { + const page = webContents.getAllWebContents().find((contents) => contents.getURL() === pageUrl) + if (!page) throw new Error(`No page at ${pageUrl}`) + const delivered = new Promise((resolve) => { + const onInput = (_event: unknown, input: { type: string }) => { + if (input.type !== 'keyDown' && input.type !== 'rawKeyDown') return + page.removeListener('input-event', onInput) + resolve() + } + page.on('input-event', onInput) + }) + page.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) + page.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) + await delivered + }, pageUrl) +} +/** Inbox reads, without the doorbell stream. */ +function inboxReads(): number { + return sim.requests.filter((request) => request === 'GET /api/desktop/inbox').length +} + +/** + * Rings the doorbell and waits for the inbox read it causes. Reads never overlap, so once it + * starts, every read before it, and whatever that read made the device do, has finished. + */ +async function nextInboxRead(deviceId: string): Promise { + const before = inboxReads() + sim.ring(deviceId, 'approval') + await expect.poll(inboxReads).toBeGreaterThan(before) +} + +test.describe('background executor', () => { test.beforeAll(async () => { await sim.start() }) - test.afterEach(async () => { - await app?.close().catch(() => {}) - app = null + test.afterEach(() => { sim.reset() }) @@ -84,29 +119,31 @@ test.describe('background executor', () => { await sim.stop() }) - test('A: two chats run browser and terminal work while the user is elsewhere and reloads', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-a-')) - const launched = await launch(sim, userData) - app = launched.app - const window = launched.window + test('A: two chats run browser and terminal work while the user is elsewhere and reloads', async ({ + desktop, + }) => { + const { app, window, userData } = await launchAgainst(desktop, sim) + await stubSleepBlockers(app) const deviceId = await registeredDevice(sim) await window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) + await test.step('an enabled device offers itself for binding', async () => { + expect(await offeredDevice(window)).toEqual({ deviceId, protocolVersion: 1 }) + }) + const marker = join(userData, 'terminal-marker.txt') const releaseCommands = join(userData, 'release-commands') const readable = join(userData, 'notes.txt') writeFileSync(readable, 'background read fixture') - await check('A: chat A opens its page in the background', async () => { + const button = await test.step('chat A opens its page in the background', async () => { const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { url: `${sim.origin}/counter?chat=A`, }) const completion = await settled(sim, opened) expect(completion.status, completion.message).toBe('success') + return refFor((completion.data?.snapshot as { outline: string }).outline, 'Count visit') }) - const opened = [...sim.calls.values()][0] as FixtureCall - const outline = (opened.completions[0]?.data?.snapshot as { outline: string }).outline - const button = refFor(outline, 'Count visit') const clicks = Array.from({ length: 10 }, () => sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) @@ -120,7 +157,7 @@ test.describe('background executor', () => { }, }) ) - const readConsent = launched.app.waitForEvent('window') + const readConsent = app.waitForEvent('window') const localRead = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) try { await answerShellDialog(await readConsent, 'Allow folder') @@ -131,7 +168,7 @@ test.describe('background executor', () => { // Chat B's first command holds its queue until released, so a claim that waited for the // calls ahead of it to run could never happen in time. - await check("A: every call is claimed while chat B's first command still runs", async () => { + await test.step("every call is claimed while chat B's first command still runs", async () => { await expect .poll( () => @@ -149,16 +186,20 @@ test.describe('background executor', () => { } }) - await check('A: the lease is renewed while calls wait and run', async () => { + await test.step('the lease is renewed while calls wait and run', async () => { await expect .poll(() => terminalRuns.filter((id) => sim.requireCall(id).renewals === 0)) .toEqual([]) }) + + await test.step('the machine is kept awake while the commands run', async () => { + await expect.poll(() => heldSleepBlockers(app)).toEqual(['prevent-app-suspension']) + }) } finally { writeFileSync(releaseCommands, '') } - await check('A: every call completes exactly once with its own token', async () => { + await test.step('every call completes exactly once with its own token', async () => { for (const id of [...clicks, ...terminalRuns, localRead]) { const completion = await settled(sim, id, 90_000) const call = sim.requireCall(id) @@ -169,40 +210,43 @@ test.describe('background executor', () => { } }) - await check('A: the page saw each click exactly once', async () => { + await test.step('the machine may sleep again once every result is delivered', async () => { + await expect.poll(() => heldSleepBlockers(app)).toEqual([]) + }) + + await test.step('the page saw each click exactly once', async () => { await expect.poll(() => sim.hits.get('A')).toBe(10) }) - await check('A: chat B ran each command once, in order, in its own terminal', async () => { + await test.step('chat B ran each command once, in order, in its own terminal', async () => { expect(readFileSync(marker, 'utf8').trim().split('\n')).toEqual(['B-1', 'B-2', 'B-3']) const read = sim.requireCall(localRead).completions[0] expect(JSON.stringify(read?.data)).toContain('background read fixture') }) - await check("A: chat B cannot see chat A's tabs", async () => { + await test.step("chat B cannot see chat A's tabs", async () => { const listed = sim.issue(deviceId, CHAT_B, 'browser_list_tabs', {}) const completion = await settled(sim, listed) expect(JSON.stringify(completion.data)).not.toContain('/counter') }) - await check('A: no chat view executed or reported a call', async () => { - expect(sim.requests.filter((request) => request.includes('/api/copilot/confirm'))).toEqual([]) + await test.step('no chat view authorized a call', async () => { expect( sim.requests.filter((request) => request.includes('/api/desktop/tool/authorize')) ).toEqual([]) }) }) - test('background file reads require consent and Stop cancels pending permission', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-consent-')) - const launched = await launch(sim, userData) - app = launched.app + test('background file reads require consent and Stop cancels pending permission', async ({ + desktop, + }) => { + const { app, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'background consent fixture') - await check('background read stays pending until folder consent', async () => { - const shown = launched.app.waitForEvent('window', { timeout: 10_000 }) + await test.step('background read stays pending until folder consent', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) const prompt = await shown await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() @@ -213,8 +257,8 @@ test.describe('background executor', () => { expect(JSON.stringify(completion)).not.toContain('background consent fixture') }) - await check('Stop dismisses background consent without granting access', async () => { - const shown = launched.app.waitForEvent('window', { timeout: 10_000 }) + await test.step('Stop dismisses background consent without granting access', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) const prompt = await shown await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() @@ -224,8 +268,8 @@ test.describe('background executor', () => { expect(sim.requireCall(call).completions[0]?.outcome).toBe('superseded') }) - await check('approved background reads reuse the shared folder grant', async () => { - const shown = launched.app.waitForEvent('window', { timeout: 10_000 }) + await test.step('approved background reads reuse the shared folder grant', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) const prompt = await shown await answerShellDialog(prompt, 'Allow folder') @@ -237,130 +281,113 @@ test.describe('background executor', () => { }) }) - test('background consent cannot grant access when Sim cannot verify the call', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-offline-consent-')) - const launched = await launch(sim, userData) - app = launched.app + test('background consent cannot grant access when Sim cannot verify the call', async ({ + desktop, + }) => { + const { app, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'offline consent fixture') - await check('offline approval returns an error without remembering a grant', async () => { - const shown = launched.app.waitForEvent('window') - const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) - const prompt = await shown - await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() - sim.disconnect() - await answerShellDialog(prompt, 'Allow folder') - await expect - .poll(() => - launched.app.evaluate(({ safeStorage }, toolCallId) => { - const fs = process.getBuiltinModule('node:fs') - const path = `${process.env.SIM_DESKTOP_USER_DATA}/desktop-executor-journal.json` - const envelope = JSON.parse(fs.readFileSync(path, 'utf8')) - const journal = JSON.parse( - safeStorage.decryptString(Buffer.from(envelope.ciphertext, 'base64')) - ) as { entries: { toolCallId: string; state: string }[] } - return journal.entries.find((entry) => entry.toolCallId === toolCallId)?.state - }, call) - ) - .toBe('result') + const shown = app.waitForEvent('window') + const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) + const prompt = await shown + await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() + sim.disconnect() + await answerShellDialog(prompt, 'Allow folder') + + await test.step('offline approval returns an error', async () => { + await expect.poll(() => journalState(app, call)).toBe('result') sim.reconnect() const completion = await settled(sim, call) expect(completion.status).toBe('error') expect(JSON.stringify(completion)).not.toContain('offline consent fixture') - const nextPrompt = launched.app.waitForEvent('window') + }) + + await test.step('the approval left no grant behind', async () => { + const nextPrompt = app.waitForEvent('window') const next = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) await answerShellDialog(await nextPrompt, "Don't allow") expect((await settled(sim, next)).status).toBe('error') }) }) - test('background consent does not reopen the main app after its windows are closed', async () => { + test('background consent does not reopen the main app after its windows are closed', async ({ + desktop, + }) => { test.skip(process.platform !== 'darwin', 'The macOS app remains running without a window.') - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-windowless-consent-')) - const launched = await launch(sim, userData) - app = launched.app + const { app, window, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'windowless consent fixture') - await launched.window.close() + await window.close() - await check('only the standalone consent window opens for a background read', async () => { - const shown = launched.app.waitForEvent('window') - const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) - const prompt = await shown - await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() - expect( - await launched.app.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().map((window) => window.getParentWindow() === null) - ) - ).toEqual([true]) - await answerShellDialog(prompt, "Don't allow") - expect((await settled(sim, call)).status).toBe('error') - }) + const shown = app.waitForEvent('window') + const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) + const prompt = await shown + await expect(prompt.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() + expect( + await app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().map((window) => window.getParentWindow() === null) + ) + ).toEqual([true]) + await answerShellDialog(prompt, "Don't allow") + expect((await settled(sim, call)).status).toBe('error') }) - test('sign-out clears folder grants even when desktop settings cannot be saved', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-grant-cleanup-')) - const launched = await launch(sim, userData) - app = launched.app + test('sign-out clears folder grants even when desktop settings cannot be saved', async ({ + desktop, + }) => { + const { app, window, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const readable = join(userData, 'private.txt') writeFileSync(readable, 'cleanup consent fixture') - const shown = launched.app.waitForEvent('window') + const shown = app.waitForEvent('window') const call = sim.issue(deviceId, CHAT_B, 'read_local_file', { path: readable }) await answerShellDialog(await shown, 'Allow folder') expect((await settled(sim, call)).status).toBe('success') const grants = join(userData, 'local-filesystem-grants.json') expect(existsSync(grants)).toBe(true) - await launched.window.evaluate(() => { + await window.evaluate(() => { const button = document.createElement('button') button.textContent = 'Enable full file access' button.onclick = async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.settings.setFullFileAccess?.(true) + await (globalThis as DesktopBridge).simDesktop.settings.setFullFileAccess?.(true) button.textContent = 'Full file access enabled' } document.body.append(button) }) - await launched.window - .getByRole('button', { name: 'Enable full file access', exact: true }) - .click() + await window.getByRole('button', { name: 'Enable full file access', exact: true }).click() await expect( - launched.window.getByRole('button', { name: 'Full file access enabled', exact: true }) + window.getByRole('button', { name: 'Full file access enabled', exact: true }) ).toBeVisible() const settings = join(userData, 'settings.json') if (existsSync(settings)) renameSync(settings, `${settings}.backup`) mkdirSync(settings) try { - await check( - 'failed settings persistence does not skip independent grant cleanup', - async () => { - const failedSignOut = launched.app.waitForEvent('window') - await launched.app.evaluate(({ Menu }) => { - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Sign Out') - if (!item) throw new Error('Missing Sign Out menu item') - item.click() - }) - const failure = await failedSignOut - await answerShellDialog(failure, 'OK') - expect(existsSync(join(userData, 'account-data-teardown-required.json'))).toBe(true) - await expect.poll(() => existsSync(grants)).toBe(false) - } - ) + const failedSignOut = app.waitForEvent('window') + await app.evaluate(({ Menu }) => { + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Sign Out') + if (!item) throw new Error('Missing Sign Out menu item') + item.click() + }) + await answerShellDialog(await failedSignOut, 'OK') + expect(existsSync(join(userData, 'account-data-teardown-required.json'))).toBe(true) + await expect.poll(() => existsSync(grants)).toBe(false) } finally { + // The app saves its settings again as it quits. rmSync(settings, { recursive: true, force: true }) if (existsSync(`${settings}.backup`)) renameSync(`${settings}.backup`, settings) } }) - test('B: a result produced while the network is cut is delivered once after reconnecting', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-b-')) - app = (await launch(sim, userData)).app + test('B: a result produced while the network is cut is delivered once after reconnecting', async ({ + desktop, + }) => { + const { app } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const run = sim.issue(deviceId, CHAT_B, 'terminal', { @@ -370,27 +397,25 @@ test.describe('background executor', () => { await expect.poll(() => sim.requireCall(run).claims).toBe(1) sim.disconnect() - await check( - 'B: the cut drops the doorbell and nothing reaches Sim while it lasts', - async () => { - await expect.poll(() => sim.streams.get(deviceId)?.size ?? 0).toBe(0) - await expect.poll(() => sim.droppedWhileOffline, { timeout: 15_000 }).toBeGreaterThan(0) - await sleep(4_000) - expect(sim.requireCall(run).completions).toHaveLength(0) - } - ) + await test.step('the cut drops the doorbell, and the result waits on the machine', async () => { + await expect.poll(() => sim.streams.get(deviceId)?.size ?? 0).toBe(0) + await expect.poll(() => journalState(app, run), { timeout: 30_000 }).toBe('result') + await expect.poll(() => sim.droppedWhileOffline, { timeout: 15_000 }).toBeGreaterThan(0) + expect(sim.requireCall(run).completions).toHaveLength(0) + }) sim.reconnect() - await check('B: the result arrives once after reconnecting', async () => { + await test.step('the result arrives once after reconnecting', async () => { const completion = await settled(sim, run, 60_000) expect(completion.status, completion.message).toBe('success') expect(JSON.stringify(completion.data)).toContain('offline-done') - await sleep(3_000) + // Forgotten only once Sim acknowledged it, so nothing is left to send again. + await expect.poll(() => journalState(app, run)).toBeUndefined() expect(sim.requireCall(run).completions).toHaveLength(1) expect(sim.requireCall(run).claims).toBe(1) }) - await check('B: the device reopens its doorbell and picks up new work', async () => { + await test.step('the device reopens its doorbell and picks up new work', async () => { await expect.poll(() => sim.streams.get(deviceId)?.size ?? 0, { timeout: 45_000 }).toBe(1) const after = sim.issue(deviceId, CHAT_B, 'browser_list_tabs', {}) const completion = await settled(sim, after) @@ -398,10 +423,11 @@ test.describe('background executor', () => { }) }) - test('C: a crash mid-command reports the outcome as unknown and never reruns it', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-c-')) - const marker = join(userData, 'crash-marker.txt') - const first = await launch(sim, userData) + test('C: a crash mid-command reports the outcome as unknown and never reruns it', async ({ + desktop, + }) => { + const first = await launchAgainst(desktop, sim) + const marker = join(first.userData, 'crash-marker.txt') const deviceId = await registeredDevice(sim) const run = sim.issue(deviceId, CHAT_B, 'terminal', { @@ -409,26 +435,24 @@ test.describe('background executor', () => { args: { command: `echo started >> '${marker}'; sleep 40`, waitSeconds: 60 }, }) await expect.poll(() => readFileSafe(marker), { timeout: 30_000 }).toContain('started') - first.app.process().kill('SIGKILL') + first.child.kill('SIGKILL') sim.streams.get(deviceId)?.clear() - app = (await launch(sim, userData)).app + await launchAgainst(desktop, sim, { userData: first.userData }) - await check('C: the restarted app reports the lost result as outcome unknown', async () => { + await test.step('the restarted app reports the lost result as outcome unknown', async () => { const completion = await settled(sim, run, 60_000) expect(completion.data).toMatchObject({ outcomeUnknown: true, doNotRetry: true }) }) - await check('C: the command ran exactly once', async () => { + await test.step('the command ran exactly once', async () => { expect(sim.requireCall(run).claims).toBe(1) expect(readFileSafe(marker).trim().split('\n')).toEqual(['started']) }) }) - test('D: a folder import lands in Sim while the user is in another chat', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-d-')) - const launched = await launch(sim, userData) - app = launched.app + test('D: a folder import lands in Sim while the user is in another chat', async ({ desktop }) => { + const { app, window, userData } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const source = join(userData, 'Reports') mkdirSync(join(source, 'q3'), { recursive: true }) @@ -436,9 +460,9 @@ test.describe('background executor', () => { // Larger than one 8 MB read, so the file crosses Electron in several chunks. const large = Buffer.alloc(9 * 1024 * 1024, 7) writeFileSync(join(source, 'q3', 'export.bin'), large) - await launched.window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) + await window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) - const importConsent = launched.app.waitForEvent('window') + const importConsent = app.waitForEvent('window') const call = sim.issue(deviceId, CHAT_B, 'import_local_files', { path: source, targetWorkspaceId: WORKSPACE, @@ -447,7 +471,7 @@ test.describe('background executor', () => { await answerShellDialog(await importConsent, 'Allow folder') - await check('D: the import completes with every entry it stored', async () => { + await test.step('the import completes with every entry it stored', async () => { const completion = await settled(sim, call, 60_000) expect(completion.status).toBe('success') expect(completion.data).toMatchObject({ @@ -464,7 +488,7 @@ test.describe('background executor', () => { }) }) - await check('D: Sim received the tree with the bytes on disk, once', async () => { + await test.step('Sim received the tree with the bytes on disk, once', async () => { expect(sim.imported).toEqual([ { toolCallId: call, kind: 'directory', sourceName: 'Reports', relativePath: '' }, { @@ -489,9 +513,11 @@ test.describe('background executor', () => { }) }) - test('E: Stop from another chat stops a running browser wait and terminal command', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-e-')) - app = (await launch(sim, userData)).app + test('E: Stop from another chat stops a running browser wait and terminal command', async ({ + desktop, + }) => { + sim.reconcileMs = SLOW_RECONCILE_MS + await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { @@ -514,266 +540,152 @@ test.describe('background executor', () => { sim.stopCall(wait) sim.stopCall(run) - await check('E: both stopped calls are acknowledged within seconds', async () => { - await settled(sim, wait, 10_000) - await settled(sim, run, 15_000) - expect(sim.requireCall(wait).completions[0]?.outcome).toBe('superseded') - expect(sim.requireCall(run).completions[0]?.outcome).toBe('superseded') - expect((sim.requireCall(wait).completions[0]?.at ?? 0) - stoppedAt).toBeLessThan(5_000) + await test.step('both stopped calls are acknowledged through the doorbell', async () => { + for (const call of [wait, run]) { + const completion = await settled(sim, call, DOORBELL_REACTION_MS) + expect(completion.outcome).toBe('superseded') + expect(completion.at - stoppedAt).toBeLessThan(DOORBELL_REACTION_MS) + } }) - await check('E: the stopped command no longer runs on the machine', async () => { + await test.step('the stopped command no longer runs on the machine', async () => { await expect.poll(() => processRunning(command), { timeout: 10_000 }).toBe(false) }) }) - test('F: a call waiting for approval in a background chat notifies, then runs once approved', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-f-')) - app = (await launch(sim, userData)).app + test('F: a call held for approval in a background chat notifies, runs only once approved, and never once declined', async ({ + desktop, + }) => { + sim.reconcileMs = SLOW_RECONCILE_MS + const { app, userData } = await launchAgainst(desktop, sim) await app.evaluate(({ Notification }) => { const shown: Array<{ title: string; body: string }> = [] - const target = globalThis as typeof globalThis & { __shownNotifications?: typeof shown } - target.__shownNotifications = shown + ;( + globalThis as typeof globalThis & { __shownNotifications?: typeof shown } + ).__shownNotifications = shown Notification.prototype.show = function show(this: { title: string; body: string }) { shown.push({ title: this.title, body: this.body }) } }) + const shownNotifications = () => + app.evaluate( + () => + (globalThis as { __shownNotifications?: Array<{ title: string; body: string }> }) + .__shownNotifications ?? [] + ) const deviceId = await registeredDevice(sim) + const marker = join(userData, 'declined-marker.txt') - const gated = sim.issue( + const approved = sim.issue( deviceId, CHAT_B, 'terminal', { operation: 'run', args: { command: 'echo approved-run', waitSeconds: 30 } }, 'awaiting_approval' ) - - await check('F: the user is notified, without the command in the notification', async () => { - await expect - .poll( - () => - app?.evaluate( - () => - (globalThis as { __shownNotifications?: Array<{ body: string }> }) - .__shownNotifications ?? [] - ), - { timeout: 15_000 } - ) - .toHaveLength(1) - const shown = await app?.evaluate( - () => - (globalThis as { __shownNotifications?: Array<{ body: string }> }).__shownNotifications - ) - expect(JSON.stringify(shown)).not.toContain('approved-run') - }) - - await check('F: nothing runs before approval', async () => { - await sleep(RECONCILE_MS * 2) - expect(sim.requireCall(gated).claims).toBe(0) - }) - - sim.approve(gated) - const approvedAt = Date.now() - await check('F: the approved call is claimed promptly and runs once', async () => { - const completion = await settled(sim, gated) - expect((sim.requireCall(gated).claimedAt ?? 0) - approvedAt).toBeLessThan(1_500) - expect(JSON.stringify(completion.data)).toContain('approved-run') - }) - }) - - test('F: a call the user declines in a background chat never runs', async () => { - const userData = mkdtempSync(join(tmpdir(), 'sim-executor-f-declined-')) - const marker = join(userData, 'declined-marker.txt') - app = (await launch(sim, userData)).app - const deviceId = await registeredDevice(sim) - const pulls = () => - sim.requests.filter((request) => request.startsWith('GET /api/desktop/inbox')).length - const claimAttempts = () => - sim.requests.filter((request) => request === 'POST /api/desktop/tool/claim').length - const pullsBefore = pulls() - const claimAttemptsBefore = claimAttempts() - - const gated = sim.issue( + const declined = sim.issue( deviceId, CHAT_B, 'terminal', { operation: 'run', args: { command: `echo ran >> '${marker}'`, waitSeconds: 30 } }, 'awaiting_approval' ) - // The device has pulled its inbox and seen the call waiting for approval. - await expect.poll(pulls).toBeGreaterThan(pullsBefore) - sim.decline(gated) - await check('F: the declined call is never claimed, and its command never runs', async () => { - await sleep(RECONCILE_MS * 2) - // Attempts, not successful claims: the fixture refuses a declined call's claim itself. - expect(claimAttempts() - claimAttemptsBefore).toBe(0) - expect(sim.requireCall(gated).completions).toEqual([]) - expect(readFileSafe(marker)).toBe('') + await test.step('the user is notified of each call, without its command', async () => { + await expect.poll(shownNotifications, { timeout: 15_000 }).toHaveLength(2) + const shown = JSON.stringify(await shownNotifications()) + expect(shown).not.toContain('approved-run') + expect(shown).not.toContain('declined-marker') }) - }) - test('G: only the device a turn is bound to claims its calls', async () => { - const first = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-g1-'))) - const firstDevice = await registeredDevice(sim) - const second = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-g2-'))) - const secondDevice = await registeredDevice(sim, new Set([firstDevice])) - app = first.app + await test.step('nothing is claimed while the calls wait for approval', async () => { + await nextInboxRead(deviceId) + expect(sim.requireCall(approved).claimAttempts).toBe(0) + expect(sim.requireCall(declined).claimAttempts).toBe(0) + }) - const call = sim.issue(firstDevice, CHAT_A, 'browser_list_tabs', {}) - await check('G: the bound device runs it and the other never claims it', async () => { - await settled(sim, call) - expect(sim.requireCall(call).claims).toBe(1) - expect( - sim.requests.filter((request) => request === 'POST /api/desktop/tool/claim').length - ).toBe(1) - expect(secondDevice).not.toBe(firstDevice) + sim.decline(declined) + sim.approve(approved) + const decidedAt = Date.now() + + await test.step('the approved call is claimed through the doorbell and runs once', async () => { + const completion = await settled(sim, approved) + expect((sim.requireCall(approved).claimedAt ?? 0) - decidedAt).toBeLessThan( + DOORBELL_REACTION_MS + ) + expect(sim.requireCall(approved).claims).toBe(1) + expect(JSON.stringify(completion.data)).toContain('approved-run') + }) + + await test.step('the declined call is never claimed, and its command never runs', async () => { + await nextInboxRead(deviceId) + // Attempts, not successful claims: the fixture refuses a declined call's claim itself. + expect(sim.requireCall(declined).claimAttempts).toBe(0) + expect(sim.requireCall(declined).completions).toEqual([]) + expect(readFileSafe(marker)).toBe('') }) - await second.app.close() }) - test('H: a device Sim has not enabled offers no binding', async () => { + test('H: a device Sim has not enabled offers no binding', async ({ desktop }) => { sim.enabled = false - const launched = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-h-'))) - app = launched.app - await launched.window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) - await expect.poll(() => sim.requests.includes('POST /api/desktop/devices')).toBe(true) - - await check( - 'H: the composer gets no device, so its turns stay with the chat view', - async () => { - const device = await launched.window.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.desktopExecutor?.getDevice() - ) - expect(device).toBeNull() - } - ) + const { window, output } = await launchAgainst(desktop, sim, { env: { LOG_LEVEL: 'INFO' } }) + await window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) + // Logged once the app has acted on Sim's answer, so the device read below is the settled one. + await expect.poll(output, { timeout: 30_000 }).toContain('Desktop executor registered') - sim.enabled = true - await launched.app.close() - const enabled = await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-h2-'))) - app = enabled.app - const deviceId = await registeredDevice(sim) - await enabled.window.goto(`${sim.origin}/workspace/${WORKSPACE}/chat/${CHAT_C}`) - await check('H: an enabled device offers itself for binding', async () => { - const device = await enabled.window.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.desktopExecutor?.getDevice() - ) - expect(device).toEqual({ deviceId, protocolVersion: 1 }) - }) + expect(await offeredDevice(window)).toBeNull() }) - test('I: the agent yields its page while the user works in it, then takes it back', async () => { - app = (await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-i-')))).app + test('I: the agent yields its page while the user works in it, then takes it back', async ({ + desktop, + }) => { + const { app } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) - const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { - url: `${sim.origin}/counter?chat=I`, - }) + const pageUrl = `${sim.origin}/counter?chat=I` + const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { url: pageUrl }) const outline = ((await settled(sim, opened)).data?.snapshot as { outline: string }).outline const button = refFor(outline, 'Count visit') - const typeInAgentPage = () => - app?.evaluate(({ webContents }) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().includes('/counter?chat=I')) - page?.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) - page?.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) - }) - await typeInAgentPage() - const click = sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) - for (let i = 0; i < 4; i++) { - await sleep(500) - await typeInAgentPage() - } + await userTypesInPage(app, pageUrl) const lastUserInputAt = Date.now() + const click = sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) - await check('I: the click waits until the user stops, then runs once', async () => { - const completion = await settled(sim, click, 30_000) - expect(completion.status, completion.message).toBe('success') - expect(completion.at - lastUserInputAt).toBeGreaterThanOrEqual(3_000) - await expect.poll(() => sim.hits.get('I')).toBe(1) - }) + const completion = await settled(sim, click, 30_000) + expect(completion.status, completion.message).toBe('success') + expect(completion.at - lastUserInputAt).toBeGreaterThanOrEqual(3_000) + await expect.poll(() => sim.hits.get('I')).toBe(1) }) - test('I: an action the user never stops working long enough for does not run', async () => { - app = (await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-i2-')))).app + test('I: an action the user never stops working long enough for does not run', async ({ + desktop, + }) => { + const { app } = await launchAgainst(desktop, sim) const deviceId = await registeredDevice(sim) - const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { - url: `${sim.origin}/counter?chat=I2`, - }) + const pageUrl = `${sim.origin}/counter?chat=I2` + const opened = sim.issue(deviceId, CHAT_A, 'browser_open_url', { url: pageUrl }) const outline = ((await settled(sim, opened)).data?.snapshot as { outline: string }).outline const button = refFor(outline, 'Count visit') - const typeInAgentPage = () => - app?.evaluate(({ webContents }) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().includes('/counter?chat=I2')) - page?.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) - page?.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) - }) - await typeInAgentPage() + await userTypesInPage(app, pageUrl) const click = sim.issue(deviceId, CHAT_A, 'browser_click', { elementId: button }) let typing = true + // A keypress a second, well inside the quiet the agent waits for before it acts. const keepTyping = (async () => { while (typing) { - await typeInAgentPage() + await userTypesInPage(app, pageUrl) await sleep(1_000) } })() - await check('I: the click reports it never ran, instead of timing out', async () => { + try { const completion = await settled(sim, click, 60_000) - typing = false - await keepTyping expect(completion.status).toBe('error') expect(completion.message).toContain('Not run: the user kept working in this page') expect(completion.data).not.toMatchObject({ outcomeUnknown: true }) expect(sim.hits.get('I2') ?? 0).toBe(0) - }) - }) - - test('J: the machine stays awake only while a chat has work running', async () => { - app = (await launch(sim, mkdtempSync(join(tmpdir(), 'sim-executor-j-')))).app - await app.evaluate(({ powerSaveBlocker }) => { - const log: string[] = [] - const active = new Set() - let next = 1 - const target = globalThis as typeof globalThis & { __sleepBlocks?: string[] } - target.__sleepBlocks = log - powerSaveBlocker.start = (type) => { - log.push(`start:${type}`) - active.add(next) - return next++ - } - powerSaveBlocker.stop = (id) => { - log.push('stop') - active.delete(id) - return true - } - powerSaveBlocker.isStarted = (id) => active.has(id) - }) - const deviceId = await registeredDevice(sim) - const sleepLog = () => - app?.evaluate(() => (globalThis as { __sleepBlocks?: string[] }).__sleepBlocks ?? []) - - const run = sim.issue(deviceId, CHAT_B, 'terminal', { - operation: 'run', - args: { command: 'sleep 3; echo awake', waitSeconds: 30 }, - }) - await check('J: a blocker is held while the command runs', async () => { - await expect.poll(sleepLog, { timeout: 15_000 }).toEqual(['start:prevent-app-suspension']) - }) - await check('J: it is released once the result is delivered', async () => { - await settled(sim, run) - await expect - .poll(sleepLog, { timeout: 10_000 }) - .toEqual(['start:prevent-app-suspension', 'stop']) - }) + } finally { + typing = false + await keepTyping + } }) }) diff --git a/apps/desktop/e2e/browser-chrome.spec.ts b/apps/desktop/e2e/browser-chrome.spec.ts index c5857f80ea0..b0f703c7442 100644 --- a/apps/desktop/e2e/browser-chrome.spec.ts +++ b/apps/desktop/e2e/browser-chrome.spec.ts @@ -1,107 +1,73 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import type { Page } from '@playwright/test' +import { + bundleSimFixture, + type DesktopBridge, + expect, + focusFirstWindow, + SIM_DIR, + serve, + test, +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath(new URL('./fixtures/browser-chrome.tsx', import.meta.url)) const SCOPE = 'browser-chrome-fixture' -test('crowded tabs and renderer overlays work with a real native browser page', async () => { - const testInfo = test.info() - let server: Server | undefined - let userData: string | undefined - let app: Awaited> | undefined - try { - const config = await loadPostcssConfig({}, SIM_DIR) - const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(stylesheet, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: stylesheet } - ) - const hook = join( - SIM_DIR, - 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-panel-occlusion.ts' - ) - const bundle = await build({ - stdin: { - contents: `import { mountBrowserChromeFixture } from ${JSON.stringify(FIXTURE)}; +test('crowded tabs and renderer overlays work with a real native browser page', async ({ + desktop, +}, testInfo) => { + const hook = join( + SIM_DIR, + 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session/browser-panel-occlusion.ts' + ) + const bundle = await bundleSimFixture( + { + source: `import { mountBrowserChromeFixture } from ${JSON.stringify(FIXTURE)}; import { useBrowserPanelOcclusion } from ${JSON.stringify(hook)}; mountBrowserChromeFixture(useBrowserPanelOcclusion);`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: testInfo.outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end( - path.endsWith('.js') - ? bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text - : `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - ) - return - } - if (path.startsWith('/api/')) { - response.setHeader('Content-Type', 'application/json') - response.end( - path === '/api/auth/get-session' - ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - : '{}' - ) - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) + }, + { sources: [FIXTURE] } + ) + const server = await serve((_request, response, url) => { + const path = url.pathname + if (path === '/fixture.js' || path === '/fixture.css') { + response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') + response.end(path.endsWith('.js') ? bundle.js : bundle.css) + return + } + if (path.startsWith('/api/')) { + response.setHeader('Content-Type', 'application/json') response.end( - path === '/page' - ? '

Browser fixture

A live page behind the application chrome.

' - : '
' + path === '/api/auth/get-session' + ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) + : '{}' ) + return + } + response.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', }) - await new Promise((resolve) => server?.listen(0, resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - userData = mkdtempSync(join(tmpdir(), 'sim-browser-chrome-e2e-')) - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: userData, - }, - }) - const shell = app - const page = await shell.firstWindow() - await shell.evaluate(({ app, BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - window.setContentSize(1100, 750) - window.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - window.focus() + response.end( + path === '/page' + ? '

Browser fixture

A live page behind the application chrome.

' + : '
' + ) + }) + let shellPage: Page | undefined + try { + const { app } = await desktop.launch({ + origin: server.origin, }) + const page = await app.firstWindow() + shellPage = page + await app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0].setContentSize(1100, 750) + ) + await focusFirstWindow(app) const nativeVisible = () => - shell.evaluate(({ BrowserWindow, WebContentsView }) => + app.evaluate(({ BrowserWindow, WebContentsView }) => BrowserWindow.getAllWindows()[0] .contentView.children.find( (view) => view instanceof WebContentsView && view.webContents.getURL().endsWith('/page') @@ -118,7 +84,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, ) expect(geometry.every((tab) => tab.width < 160)).toBe(true) expect(geometry.at(-1)?.right).toBeLessThan(1070) - await page.screenshot({ path: testInfo.outputPath('tabs.png') }) }) await test.step('Crowded tabs keep readable labels when selected, hovered, and focused', async () => { await page.locator('#many-tabs').click() @@ -165,17 +130,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect .poll(() => label.evaluate((element) => element.getBoundingClientRect().width)) .toBeGreaterThanOrEqual(48) - await page.mouse.move(200, 180) - await page.screenshot({ - path: testInfo.outputPath('crowded-tabs.png'), - animations: 'disabled', - }) - await page.evaluate(() => document.documentElement.classList.remove('dark')) - await page.screenshot({ - path: testInfo.outputPath('crowded-tabs-light.png'), - animations: 'disabled', - }) - await page.evaluate(() => document.documentElement.classList.add('dark')) await page.keyboard.press('Home') await expect(page.getByRole('tab').first()).toBeInViewport({ ratio: 1 }) await page.locator('#eight-tabs').click() @@ -218,7 +172,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, ) }) ).toBe(true) - await page.screenshot({ path: testInfo.outputPath('crowded-tabs-touch.png') }) const beforeSelection = await attention.evaluate( (element: HTMLElement) => element.offsetWidth ) @@ -228,11 +181,15 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, beforeSelection ) await page.locator('#toggle-activity').click() + await expect(indicator).toHaveCount(0) expect(await attention.evaluate((element: HTMLElement) => element.offsetWidth)).toBe( beforeSelection ) await page.locator('#toggle-activity').click() await page.locator('#medium-tabs').click() + await expect(page.locator('[data-tab-strip-item] [data-overflow-text]')).toHaveText( + Array(4).fill('Medium title') + ) await page.getByRole('tab').first().click() const intrinsicWidth = await attention.evaluate( (element: HTMLElement) => element.offsetWidth @@ -244,6 +201,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, intrinsicWidth ) await page.locator('#toggle-activity').click() + await expect(indicator).toHaveCount(0) expect(await attention.evaluate((element: HTMLElement) => element.offsetWidth)).toBe( intrinsicWidth ) @@ -256,6 +214,9 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, }) await test.step('Short labels stay below the maximum tab width', async () => { await page.locator('#short-tabs').click() + await expect(page.locator('[data-tab-strip-item] [data-overflow-text]')).toHaveText( + Array(8).fill('A') + ) const widths = await page .locator('[data-tab-strip-item]') .evaluateAll((tabs) => tabs.map((tab) => tab.getBoundingClientRect().width)) @@ -268,9 +229,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, expect( await page.evaluate( (scope) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.capturePanelSnapshot(scope), + (globalThis as DesktopBridge).simDesktop.browserAgent.capturePanelSnapshot(scope), SCOPE ) ).toBeNull() @@ -289,7 +248,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect(page.getByRole('tooltip')).toBeVisible() await expect.poll(nativeVisible).toBe(false) await expect(page.locator('#snapshot')).toBeVisible() - await page.screenshot({ path: testInfo.outputPath('tooltip.png') }) }) await test.step('Leaving the tooltip restores the native browser', async () => { await page.mouse.move(200, 180) @@ -309,7 +267,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect(page.locator('#snapshot')).toBeVisible() }) await test.step('Resizing with an open menu refreshes the captured viewport', async () => { - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(1000, 750) ) await expect @@ -318,7 +276,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, ) .toBe(450) await expect.poll(nativeVisible).toBe(false) - await page.screenshot({ path: testInfo.outputPath('menu.png') }) }) await test.step('Escape dismisses the menu and restores the native browser', async () => { await page.keyboard.press('Escape') @@ -327,7 +284,7 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, await expect(page.locator('#snapshot')).toHaveCount(0) }) } catch (error) { - const page = app?.windows()[0] + const page = shellPage if (page && !page.isClosed()) { await page.screenshot({ path: testInfo.outputPath('failure.png') }) const overlays = await page.locator('[data-native-surface-overlay]').evaluateAll((elements) => @@ -345,13 +302,6 @@ mountBrowserChromeFixture(useBrowserPanelOcclusion);`, } throw error } finally { - await app?.close() - if (server?.listening) { - const listener = server - await new Promise((resolve, reject) => - listener.close((error) => (error ? reject(error) : resolve())) - ) - } - if (userData) rmSync(userData, { recursive: true, force: true }) + await server.close() } }) diff --git a/apps/desktop/e2e/browser-focus.spec.ts b/apps/desktop/e2e/browser-focus.spec.ts index 86e13ee3726..d6a5de1ebee 100644 --- a/apps/desktop/e2e/browser-focus.spec.ts +++ b/apps/desktop/e2e/browser-focus.spec.ts @@ -1,196 +1,158 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { BrowserPanelAction, BrowserToolName } from '@sim/browser-protocol' +import { refFor } from './executor-sim' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + type DesktopBridge, expect, - type Page, + focusFirstWindow, + hideBrowserPanel, + serve, + ToolAuthorizer, test, -} from '@playwright/test' -import type { BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-focus-e2e' const PRIMARY = process.platform === 'darwin' ? 'meta' : 'control' +const PANEL_TOP = 120 const SHELL_FIXTURE = 'Sim fixture

Browser focus fixture

' const page = (name: string) => `${name}Open popup` -type Bridge = typeof globalThis & { simDesktop: SimDesktopApi; shellMarker?: string } +type Bridge = DesktopBridge & { shellMarker?: string } +/** What the test installs in the main process. */ +type MainFixture = typeof globalThis & { pageLoads?: Map; countedPage?: number } /** * The browser shares one window with Sim, so focus and shortcuts decide whether - * a keystroke lands in chat, in the page, or reloads all of Sim. These checks + * a keystroke lands in chat, in the page, or reloads all of Sim. These steps * drive the real shell and native tab views. */ -test('browser focus and shortcuts stay with the surface the user is using', async () => { - const reportPath = - process.env.DESKTOP_BROWSER_FOCUS_REPORT_PATH ?? test.info().outputPath('browser-focus.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const calls = new Map() - const server: Server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } +test('browser focus and shortcuts stay with the surface the user is using', async ({ desktop }) => { + const authorizer = new ToolAuthorizer('browser-focus') + const server = await serve(async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return // The app origin serves the shell; the same server on localhost is the web. const isSite = request.headers.host?.startsWith('localhost') === true response.writeHead(200, { 'Content-Type': 'text/html', ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), }) - response.end(isSite ? page(path.slice(1)) : SHELL_FIXTURE) + response.end(isSite ? page(url.pathname.slice(1)) : SHELL_FIXTURE) }) - const userData = mkdtempSync(join(tmpdir(), 'sim-browser-focus-e2e-')) - let app: ElectronApplication | undefined - let passed = false try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const origin = `http://127.0.0.1:${address.port}` - /** Pages outside the app origin browse in the agent partition, like any third-party site. */ - const site = origin.replace('127.0.0.1', 'localhost') - const shellApp = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - app = shellApp - const shell: Page = await shellApp.firstWindow() - await shellApp.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() + const { site } = server + const { app } = await desktop.launch({ + origin: server.origin, }) + const shell = await app.firstWindow() + await focusFirstWindow(app) await expect(shell.getByRole('heading')).toHaveText('Browser focus fixture') - await shell.evaluate(async (scope) => { - const api = (globalThis as Bridge).simDesktop.browserAgent - await api.activateScope(scope) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 120, width: innerWidth, height: innerHeight - 120 }, - null, - scope - ) - updateBounds() - ;(globalThis as Bridge & { boundsTimer?: number }).boundsTimer = window.setInterval( - updateBounds, - 200 - ) + await attachBrowserPanel(shell, SCOPE, PANEL_TOP) + await shell.evaluate(() => { ;(globalThis as Bridge).shellMarker = 'alive' - }, SCOPE) + }) - let callCount = 0 - const execute = async (tool: BrowserToolName, args: Record) => { - const callId = `browser-focus-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - const result = await shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) - return result.ok ? result.result : undefined - } - const panelAction = (action: Record) => + const execute = (tool: BrowserToolName, args: Record = {}) => + authorizer.execute(shell, SCOPE, tool, args) + /** + * Fire-and-forget browser IPC, followed by an invoke round trip from the same renderer so the + * main process has handled the sends before the test acts. + */ + const send = (message: { panelAction: BrowserPanelAction } | { panelFocused: boolean }) => shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), - { action, scope: SCOPE } - ) - const setPanelFocused = (focused: boolean) => - shell.evaluate( - ({ focused, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.setPanelFocused(focused, scope), - { focused, scope: SCOPE } + async ({ message, scope }) => { + const api = (globalThis as Bridge).simDesktop.browserAgent + if ('panelAction' in message) api.panelAction(message.panelAction, scope) + else api.setPanelFocused(message.panelFocused, scope) + await api.activateScope(scope) + }, + { message, scope: SCOPE } ) - const tabCount = () => + const tabs = () => shell.evaluate( async (scope) => - (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs.length, + (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, SCOPE ) + const tabCount = async () => (await tabs()).length const shellAlive = () => shell.evaluate(() => (globalThis as Bridge).shellMarker === 'alive').catch(() => false) const composerFocused = () => shell.evaluate(() => document.hasFocus() && document.activeElement?.id === 'composer') const focusedPageUrls = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => + app.evaluate(({ BrowserWindow, WebContentsView }) => BrowserWindow.getAllWindows()[0] .contentView.children.filter( (view) => view instanceof WebContentsView && view.webContents.isFocused() ) .map((view) => (view as Electron.WebContentsView).webContents.getURL()) ) - const visiblePageUrl = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => { + const visiblePage = () => + app.evaluate(({ BrowserWindow, WebContentsView }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() ) as Electron.WebContentsView | undefined - return view?.webContents.getURL() ?? null + return view + ? { url: view.webContents.getURL(), loading: view.webContents.isLoading() } + : null }) - /** Counts main-frame loads of the visible page from now on. */ + const visiblePageUrl = async () => (await visiblePage())?.url ?? null + /** Whether a page at exactly `url` finished loading, visible or not. */ + const pageLoaded = (url: string) => + app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .some((contents) => contents.getURL() === url && !contents.isLoading()), + url + ) + /** How many popup pages have finished loading, wherever they are in the strip. */ + const loadedPopups = () => + app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .filter((contents) => contents.getURL() === url && !contents.isLoading()).length, + `${site}/popup` + ) + /** Counts main-frame loads of the page on screen from now on, keyed to its contents. */ const countVisiblePageLoads = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => { + app.evaluate(({ BrowserWindow, WebContentsView }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() ) as Electron.WebContentsView - const counter = globalThis as typeof globalThis & { pageLoads?: number; counted?: boolean } - counter.pageLoads = 0 - if (!counter.counted) { - counter.counted = true - view.webContents.on('did-finish-load', () => { - counter.pageLoads = (counter.pageLoads ?? 0) + 1 - }) + const fixture = globalThis as MainFixture + const loads = (fixture.pageLoads ??= new Map()) + const contents = view.webContents + if (!loads.has(contents.id)) { + contents.on('did-finish-load', () => + loads.set(contents.id, (loads.get(contents.id) ?? 0) + 1) + ) } + loads.set(contents.id, 0) + fixture.countedPage = contents.id }) const pageLoads = () => - shellApp.evaluate(() => (globalThis as typeof globalThis & { pageLoads?: number }).pageLoads) - const focusVisiblePage = () => - shellApp.evaluate(({ BrowserWindow, WebContentsView }) => { + app.evaluate(() => { + const fixture = globalThis as MainFixture + return fixture.countedPage === undefined + ? undefined + : fixture.pageLoads?.get(fixture.countedPage) + }) + /** Focuses the page on screen and waits until it holds keyboard focus. */ + const focusVisiblePage = async () => { + const url = await app.evaluate(({ BrowserWindow, WebContentsView }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() ) as Electron.WebContentsView view.webContents.focus() + return view.webContents.getURL() }) + await expect.poll(focusedPageUrls).toEqual([url]) + } const pressInPage = (keyCode: string, modifiers: string[]) => - shellApp.evaluate( + app.evaluate( ({ BrowserWindow, WebContentsView }, { keyCode, modifiers }) => { const view = BrowserWindow.getAllWindows()[0].contentView.children.find( (child) => child instanceof WebContentsView && child.getVisible() @@ -203,7 +165,7 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn ) /** Clicks an application-menu item the way its accelerator would. */ const clickMenu = (label: string) => - shellApp.evaluate(({ BrowserWindow, Menu }, label) => { + app.evaluate(({ BrowserWindow, Menu }, label) => { const win = BrowserWindow.getAllWindows()[0] const find = (items: Electron.MenuItem[]): Electron.MenuItem | null => { for (const item of items) { @@ -217,53 +179,50 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn if (!item) throw new Error(`No menu item ${label}`) item.click(undefined, win, win.webContents) }, label) + const clickPopupLink = async () => { + const before = await loadedPopups() + const snapshot = (await execute('browser_snapshot')) as { outline: string } + await execute('browser_click', { elementId: refFor(snapshot.outline, 'Open popup') }) + await expect.poll(loadedPopups).toBe(before + 1) + } - await check('the agent working never takes the caret from the composer', async () => { + await test.step('the agent working never takes the caret from the composer', async () => { await shell.locator('#composer').click() await shell.keyboard.type('draft') - for (const [tool, args] of [ - ['browser_open_url', { url: `${site}/one` }], - ['browser_navigate', { url: `${site}/two` }], - ['browser_open_tab', { url: `${site}/three` }], + for (const [tool, path] of [ + ['browser_open_url', '/one'], + ['browser_navigate', '/two'], + ['browser_open_tab', '/three'], ] as const) { - await execute(tool, args) - await expect.poll(visiblePageUrl).not.toBeNull() + await execute(tool, { url: `${site}${path}` }) + // browser_open_tab works in a background tab, so the page need not be the visible one. + await expect.poll(() => pageLoaded(`${site}${path}`)).toBe(true) expect(await composerFocused()).toBe(true) expect(await focusedPageUrls()).toEqual([]) } // A link without an opener is focused by Chromium itself as it is created. - const snapshot = await execute('browser_snapshot', {}) - const ref = /"Open popup" \[ref=(\d+)\]/.exec( - String((snapshot as { outline?: string }).outline) - )?.[1] - expect(ref, 'snapshot lists the popup link').toBeTruthy() - await execute('browser_click', { elementId: Number(ref) }) - await expect.poll(tabCount).toBe(3) - await expect.poll(focusedPageUrls).toEqual([]) + await clickPopupLink() + expect(await tabCount()).toBe(3) + expect(await focusedPageUrls()).toEqual([]) expect(await composerFocused()).toBe(true) await shell.keyboard.type(' continues') await expect(shell.locator('#composer')).toHaveValue('draft continues') }) - await check('an omnibox navigation hands focus to the page it loads', async () => { - await panelAction({ action: 'switch-tab', tabId: '1' }) - await panelAction({ action: 'navigate', url: `${site}/four` }) + await test.step('an omnibox navigation hands focus to the page it loads', async () => { + await send({ panelAction: { action: 'switch-tab', tabId: '1' } }) + await send({ panelAction: { action: 'navigate', url: `${site}/four` } }) await expect.poll(focusedPageUrls).toEqual([`${site}/four`]) }) - await check('a popup the agent opens hands focus back to the page the user is in', async () => { + await test.step('a popup the agent opens hands focus back to the page the user is in', async () => { const before = await tabCount() - const snapshot = await execute('browser_snapshot', {}) - const ref = /"Open popup" \[ref=(\d+)\]/.exec( - String((snapshot as { outline?: string }).outline) - )?.[1] - expect(ref, 'snapshot lists the popup link').toBeTruthy() - await execute('browser_click', { elementId: Number(ref) }) - await expect.poll(tabCount).toBe(before + 1) + await clickPopupLink() + expect(await tabCount()).toBe(before + 1) await expect.poll(focusedPageUrls).toEqual([`${site}/four`]) }) - await check('reload keys typed in the page reload only that page', async () => { + await test.step('reload keys typed in the page reload only that page', async () => { for (const [keyCode, modifiers] of [ ['R', [PRIMARY]], ['R', [PRIMARY, 'shift']], @@ -276,19 +235,19 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn } }) - await check('the page keeps its shortcut claim after the chrome reports blur', async () => { - await setPanelFocused(true) + await test.step('the page keeps its shortcut claim after the chrome reports blur', async () => { + await send({ panelFocused: true }) await focusVisiblePage() - await setPanelFocused(false) + await send({ panelFocused: false }) await countVisiblePageLoads() await clickMenu('Reload') await expect.poll(pageLoads).toBe(1) expect(await shellAlive()).toBe(true) }) - await check('Back and Forward move through the focused page history', async () => { - await panelAction({ action: 'navigate', url: `${site}/five` }) - await expect.poll(visiblePageUrl).toBe(`${site}/five`) + await test.step('Back and Forward move through the focused page history', async () => { + await send({ panelAction: { action: 'navigate', url: `${site}/five` } }) + await expect.poll(visiblePage).toEqual({ url: `${site}/five`, loading: false }) await focusVisiblePage() await clickMenu('Back') await expect.poll(visiblePageUrl).toBe(`${site}/four`) @@ -297,50 +256,42 @@ test('browser focus and shortcuts stay with the surface the user is using', asyn await expect.poll(visiblePageUrl).toBe(`${site}/five`) }) - await check('browser shortcuts work while renderer chrome hides the page', async () => { + await test.step('browser shortcuts work while renderer chrome hides the page', async () => { const before = await tabCount() - await shell.evaluate((scope) => { - const bridge = globalThis as Bridge & { boundsTimer?: number } - window.clearInterval(bridge.boundsTimer) - bridge.simDesktop.browserAgent.setPanelBounds(null, null, scope) - }, SCOPE) - await setPanelFocused(true) + await hideBrowserPanel(shell, SCOPE) + await send({ panelFocused: true }) await clickMenu('New Tab') await expect.poll(tabCount).toBe(before + 1) }) - await check( - 'a revealed page resumes throttling in its own chat after switching chats', - async () => { - await panelAction({ action: 'switch-tab', tabId: '1' }) - await shell.evaluate(async (scope) => { + + await test.step('a revealed page resumes throttling in its own chat after switching chats', async () => { + await send({ panelAction: { action: 'switch-tab', tabId: '1' } }) + await shell.evaluate( + async ({ scope, top }) => { const api = (globalThis as Bridge).simDesktop.browserAgent api.setPanelBounds( - { x: 0, y: 120, width: innerWidth, height: innerHeight - 120 }, + { x: 0, y: top, width: innerWidth, height: innerHeight - top }, null, scope ) await api.activateScope('browser-focus-other-chat') - }, SCOPE) - await expect - .poll(() => - shellApp.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - ?.getBackgroundThrottling(), - `${site}/five` - ) + }, + { scope: SCOPE, top: PANEL_TOP } + ) + await expect + .poll(() => + app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .find((contents) => contents.getURL() === url) + ?.getBackgroundThrottling(), + `${site}/five` ) - .toBe(true) - } - ) - passed = true + ) + .toBe(true) + }) } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await server.close() } }) diff --git a/apps/desktop/e2e/browser-page-dialogs.spec.ts b/apps/desktop/e2e/browser-page-dialogs.spec.ts index 89a75935ebc..58582581496 100644 --- a/apps/desktop/e2e/browser-page-dialogs.spec.ts +++ b/apps/desktop/e2e/browser-page-dialogs.spec.ts @@ -1,28 +1,28 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Dialog, Page } from '@playwright/test' +import type { BrowserPageDialog, BrowserPanelAction, BrowserToolName } from '@sim/browser-protocol' import { - type Dialog, - type ElectronApplication, - _electron as electron, + BROWSER_SESSION_COMPONENTS, + focusedPageUrl, + inPage, + openShell, + panelAction, + serveShellAndSite, + titleAt, + userInput, +} from './browser-page' +import { + bundleSimFixture, + type DesktopBridge, expect, - type Page, + hideBrowserPanel, + SIM_DIR, + ToolAuthorizer, test, -} from '@playwright/test' -import type { BrowserPageDialog, BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-page-dialogs-e2e' -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) -const SHELL_FIXTURE = - 'Sim fixture

Browser dialogs fixture

' +const SHELL = { heading: 'Browser dialogs fixture', top: 80 } const FORM_FIXTURE = `form @@ -31,11 +31,9 @@ const FORM_FIXTURE = `form if (document.getElementById('draft').value) { event.preventDefault(); event.returnValue = '' } })` -type Bridge = typeof globalThis & { - simDesktop: SimDesktopApi +type FixtureGlobals = DesktopBridge & { pageDialog?: BrowserPageDialog | null pageIssue?: string | null - boundsTimer?: number } /** @@ -43,42 +41,15 @@ type Bridge = typeof globalThis & { * the page: the user on the tab they are looking at, the agent during its own * action. These checks drive the real shell and native tab views. */ -test('page dialogs wait for the user on their page and stay automatic for the agent', async () => { - const reportPath = - process.env.DESKTOP_BROWSER_DIALOGS_REPORT_PATH ?? - test.info().outputPath('browser-page-dialogs.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const browserComponents = join( - SIM_DIR, - 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session' - ) - const bundle = await build({ - stdin: { - contents: `import { createElement } from 'react'; +test('page dialogs wait for the user on their page and stay automatic for the agent', async ({ + desktop, +}) => { + const bundle = await bundleSimFixture({ + source: `import { createElement } from 'react'; import { createRoot } from 'react-dom/client'; import { useBrowserSessionStore as store } from ${JSON.stringify(join(SIM_DIR, 'stores/browser-session/store.ts'))}; -import { BrowserPageDialogModal } from ${JSON.stringify(join(browserComponents, 'browser-page-dialog.tsx'))}; -import { useBrowserPanelOcclusion } from ${JSON.stringify(join(browserComponents, 'browser-panel-occlusion.ts'))}; +import { BrowserPageDialogModal } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-page-dialog.tsx'))}; +import { useBrowserPanelOcclusion } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-panel-occlusion.ts'))}; const scope = ${JSON.stringify(SCOPE)}; const api = globalThis.simDesktop.browserAgent; api.onPageState(state => store.getState().setPageState(state)); @@ -96,128 +67,47 @@ function Fixture() { }); } createRoot(document.getElementById('root')).render(createElement(Fixture));`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, }) - const config = await loadPostcssConfig({}, SIM_DIR) - const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process(readFileSync(stylesheet, 'utf8'), { - from: stylesheet, - }) - const calls = new Map() - const server: Server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') + const authorizer = new ToolAuthorizer('browser-dialogs') + const server = await serveShellAndSite({ + ...SHELL, + bundle, + authorizer, + site: (_request, response, url) => { + if (url.pathname === '/broken') { + response.destroy() + return + } + response.writeHead(200, { 'Content-Type': 'text/html' }) response.end( - path.endsWith('.js') - ? bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text - : css.css - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - if (path === '/broken') { - response.destroy() - return - } - // The app origin serves the shell; the same server on localhost is the web. - const isSite = request.headers.host?.startsWith('localhost') === true - response.writeHead(200, { - 'Content-Type': 'text/html', - ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), - }) - response.end( - !isSite - ? SHELL_FIXTURE - : path === '/form' || path === '/agent' + url.pathname === '/form' || url.pathname === '/agent' ? FORM_FIXTURE : 'next' - ) + ) + }, }) - const userData = mkdtempSync(join(tmpdir(), 'sim-browser-dialogs-e2e-')) - let app: ElectronApplication | undefined - let passed = false try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const origin = `http://127.0.0.1:${address.port}` - const site = origin.replace('127.0.0.1', 'localhost') - const shellApp = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - app = shellApp + const { site } = server + const form = `${site}/form` + const { app } = await desktop.launch({ origin: server.origin }) // A dialog listener stops Playwright auto-dismissing page dialogs, so the desktop's own // handling decides their outcome exactly as it does in production. const nativeDialogs: Dialog[] = [] - const leaveDialogsToDesktop = (page: Page) => - page.on('dialog', (dialog) => nativeDialogs.push(dialog)) + const captureDialogs = (page: Page) => page.on('dialog', (dialog) => nativeDialogs.push(dialog)) + app.context().pages().forEach(captureDialogs) + app.context().on('page', captureDialogs) const nextNativeDialog = async () => { await expect.poll(() => nativeDialogs.length).toBeGreaterThan(0) const dialog = nativeDialogs.shift() if (!dialog) throw new Error('Missing native dialog') return dialog } - shellApp.context().pages().forEach(leaveDialogsToDesktop) - shellApp.context().on('page', leaveDialogsToDesktop) - const shell = await shellApp.firstWindow() - await shellApp.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - if (!host) throw new Error('Missing host window') - app.focus({ steal: true }) - host.focus() - }) - await expect(shell.getByRole('heading')).toHaveText('Browser dialogs fixture') - await shell.evaluate(async (scope) => { - const bridge = globalThis as Bridge - const api = bridge.simDesktop.browserAgent - await api.activateScope(scope) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - bridge.boundsTimer = window.setInterval(updateBounds, 200) - bridge.pageDialog = null - }, SCOPE) + const shell = await openShell(app, SCOPE, SHELL) - let callCount = 0 - const execute = async (tool: BrowserToolName, args: Record) => { - const callId = `browser-dialogs-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - const result = await shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) - return result.ok ? result.result : undefined - } - const pageDialog = () => shell.evaluate(() => (globalThis as Bridge).pageDialog ?? null) - /** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ - const panelAction = async (action: Record) => { + const execute = (tool: BrowserToolName, args: Record = {}) => + authorizer.execute(shell, SCOPE, tool, args) + const pageDialog = () => shell.evaluate(() => (globalThis as FixtureGlobals).pageDialog ?? null) + const act = async (action: BrowserPanelAction) => { // The store holds a dialog before its modal finishes the native-surface handshake and // renders, so a live dialog is answered through the modal once it appears. if ( @@ -225,113 +115,75 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, (await pageDialog())?.requestId === action.requestId ) { await shell - .getByRole('button', { - name: action.allowed ? 'Leave' : 'Stay', - exact: true, - }) + .getByRole('button', { name: action.allowed ? 'Leave' : 'Stay', exact: true }) .click() return } - await shell.getByRole('heading').click() - await shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), - { action, scope: SCOPE } - ) + await panelAction(shell, SCOPE, action) } - const inPage = (script: string) => - shellApp.evaluate( - async ({ webContents }, { script, url }) => - (await webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(url)) - ?.executeJavaScript(script)) as T, - { script, url: site } - ) - /** Read from the shell: a script cannot run in a page while its dialog is open. */ - const pageTitle = () => - shellApp.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(url)) - ?.getTitle() ?? null, - site - ) + const formTitle = () => titleAt(app, form) + const draft = (url = form) => inPage(app, url, "document.getElementById('draft').value") + /** Types into the draft field and waits until the queued keys have landed. */ + const typeDraft = async (text: string) => { + const before = await draft() + await userInput(app, form, '#draft', text) + await expect.poll(() => draft()).toBe(before + text) + } + /** The URL of the one tab on the fixture site, whichever page it is showing. */ const pageUrl = () => - shellApp.evaluate( - ({ webContents }, url) => + app.evaluate( + ({ webContents }, site) => webContents .getAllWebContents() - .find((contents) => contents.getURL().startsWith(url)) + .find((contents) => contents.getURL().startsWith(site)) ?.getURL() ?? null, site ) - const focusedContentsUrl = () => - shellApp.evaluate(({ webContents }) => webContents.getFocusedWebContents()?.getURL()) - /** Trusted input into the page, the way the user's own mouse and keys arrive. */ - const userInput = (selector: string, text = '') => - shellApp.evaluate( - async ({ webContents }, { selector, text, url }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => candidate.getURL().startsWith(url)) - if (!contents) throw new Error('No page') - const rect: { x: number; y: number } = await contents.executeJavaScript( - `(() => { const { x, y } = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x, y } })()` - ) - const point = { x: Math.round(rect.x + 5), y: Math.round(rect.y + 5) } - contents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 }) - contents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 }) - for (const character of text) - contents.sendInputEvent({ type: 'char', keyCode: character }) - }, - { selector, text, url: site } - ) + const answerLeave = async (allowed: boolean) => { + await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) + const dialog = await pageDialog() + await act({ action: 'respond-dialog', requestId: dialog?.requestId, allowed }) + } - await check('without a renderer that shows dialogs, the shell still answers them', async () => { - await execute('browser_open_url', { url: `${site}/form` }) - await panelAction({ action: 'switch-tab', tabId: '1' }) - await userInput('#delete') - await expect.poll(() => pageTitle()).toBe('confirm:false') + await test.step('without a renderer that shows dialogs, the shell still answers them', async () => { + await execute('browser_open_url', { url: form }) + await act({ action: 'switch-tab', tabId: '1' }) + await userInput(app, form, '#delete') + await expect.poll(formTitle).toBe('confirm:false') expect(await pageDialog()).toBeNull() }) - await panelAction({ action: 'enable-page-dialogs' }) - await inPage("document.title = 'form'") - + await act({ action: 'enable-page-dialogs' }) + await inPage(app, form, "document.title = 'form'") nativeDialogs.length = 0 - await check("the user's confirm waits for their answer without a duplicate modal", async () => { - await userInput('#delete') + + await test.step("the user's confirm waits for their answer without a duplicate modal", async () => { + await userInput(app, form, '#delete') const dialog = await nextNativeDialog() expect(dialog.type()).toBe('confirm') expect(dialog.message()).toBe('Delete the report?') - expect(await pageTitle()).toBe('form') + expect(await formTitle()).toBe('form') expect(await pageDialog()).toBeNull() await expect(shell.getByRole('dialog')).toHaveCount(0) await dialog.accept() - await expect.poll(() => pageTitle()).toBe('confirm:true') + await expect.poll(formTitle).toBe('confirm:true') }) - await check('a user sees the complete decision text beyond the diagnostic limit', async () => { - await userInput('#long-message') + await test.step('a user sees the complete decision text beyond the diagnostic limit', async () => { + await userInput(app, form, '#long-message') const dialog = await nextNativeDialog() expect(dialog.message()).toBe(`${'Details '.repeat(150)}Final decision detail`) await dialog.accept() }) - await check('automation leaves a user-owned confirmation unanswered', async () => { - await inPage("document.title = 'form'") - await userInput('#delete') + await test.step('automation leaves a user-owned confirmation unanswered', async () => { + await inPage(app, form, "document.title = 'form'") + await userInput(app, form, '#delete') const dialog = await nextNativeDialog() - const callId = `browser-dialogs-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: 'browser_snapshot', args: {} }) + const callId = authorizer.issue(SCOPE, 'browser_snapshot', {}) const result = await shell.evaluate( ({ callId, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool( + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( callId, 'browser_snapshot', {}, @@ -342,112 +194,105 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, expect(result.ok).toBe(false) await shell.evaluate( ({ callId, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.cancelTool?.(callId, scope), + (globalThis as DesktopBridge).simDesktop.browserAgent.cancelTool?.(callId, scope), { callId, scope: SCOPE } ) - expect(await pageTitle()).toBe('form') + expect(await formTitle()).toBe('form') await dialog.accept() - await expect.poll(() => pageTitle()).toBe('confirm:true') + await expect.poll(formTitle).toBe('confirm:true') }) - await check("the agent's dialogs never wait on the user", async () => { - await inPage("document.title = 'form'") - const snapshot = await execute('browser_snapshot', {}) + await test.step("the agent's dialogs never wait on the user", async () => { + await inPage(app, form, "document.title = 'form'") + const snapshot = await execute('browser_snapshot') const ref = /button "Delete" \[ref=(\d+)\]/.exec( String((snapshot as { outline?: string }).outline) )?.[1] expect(ref, 'snapshot lists the Delete button').toBeTruthy() await execute('browser_click', { elementId: Number(ref) }) - await expect.poll(() => pageTitle()).toBe('confirm:false') + await expect.poll(formTitle).toBe('confirm:false') expect(await pageDialog()).toBeNull() - await inPage("document.title = 'form'") + await inPage(app, form, "document.title = 'form'") await execute('browser_click', { elementId: Number(ref), dialog: { accept: true } }) - await expect.poll(() => pageTitle()).toBe('confirm:true') + await expect.poll(formTitle).toBe('confirm:true') expect(await pageDialog()).toBeNull() }) // CDP answers the JavaScript call but Electron owns its native sheet. Reload // ends the native dialogs before testing the renderer's leave-site modal. - await panelAction({ action: 'reload' }) - await expect.poll(() => pageTitle()).toBe('form') + await act({ action: 'reload' }) + await expect.poll(formTitle).toBe('form') - await check('clean reloads and navigation never ask to discard changes', async () => { - await inPage("document.documentElement.dataset.reloadProbe = 'before'") - await panelAction({ action: 'reload' }) + await test.step('clean reloads and navigation never ask to discard changes', async () => { + await inPage(app, form, "document.documentElement.dataset.reloadProbe = 'before'") + await act({ action: 'reload' }) await expect - .poll(() => inPage('document.documentElement.dataset.reloadProbe')) + .poll(() => + inPage(app, form, 'document.documentElement.dataset.reloadProbe') + ) .toBeUndefined() - await expect.poll(() => pageTitle()).toBe('form') + await expect.poll(formTitle).toBe('form') expect(await pageDialog()).toBeNull() - await panelAction({ action: 'navigate', url: `${site}/next` }) + await act({ action: 'navigate', url: `${site}/next` }) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() - await panelAction({ action: 'back' }) - await expect.poll(pageUrl).toBe(`${site}/form`) + await act({ action: 'back' }) + await expect.poll(pageUrl).toBe(form) expect(await pageDialog()).toBeNull() }) - await check('clearing a draft removes the leave warning', async () => { - await userInput('#draft', 'temporary draft') - await inPage("document.getElementById('draft').value = ''") - await panelAction({ action: 'navigate', url: `${site}/next` }) + await test.step('clearing a draft removes the leave warning', async () => { + await typeDraft('temporary draft') + await inPage(app, form, "document.getElementById('draft').value = ''") + await act({ action: 'navigate', url: `${site}/next` }) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() - await panelAction({ action: 'navigate', url: `${site}/form` }) - await expect.poll(pageUrl).toBe(`${site}/form`) + await act({ action: 'navigate', url: form }) + await expect.poll(pageUrl).toBe(form) }) - await check('same-page navigation preserves a draft without a leave warning', async () => { - await userInput('#draft', 'same-page draft') - await panelAction({ action: 'navigate', url: `${site}/form#section` }) - await expect.poll(pageUrl).toBe(`${site}/form#section`) + await test.step('same-page navigation preserves a draft without a leave warning', async () => { + await typeDraft('same-page draft') + await act({ action: 'navigate', url: `${form}#section` }) + await expect.poll(pageUrl).toBe(`${form}#section`) expect(await pageDialog()).toBeNull() - expect(await inPage("document.getElementById('draft').value")).toBe('same-page draft') - await panelAction({ action: 'back' }) - await expect.poll(pageUrl).toBe(`${site}/form`) + expect(await draft(`${form}#section`)).toBe('same-page draft') + await act({ action: 'back' }) + await expect.poll(pageUrl).toBe(form) expect(await pageDialog()).toBeNull() - await inPage(`setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })`) + await inPage( + app, + form, + `setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })` + ) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() - await panelAction({ action: 'navigate', url: `${site}/form` }) - await expect.poll(pageUrl).toBe(`${site}/form`) + await act({ action: 'navigate', url: form }) + await expect.poll(pageUrl).toBe(form) }) - await check('leaving a draft from the URL bar asks, and Stay keeps it', async () => { - await userInput('#draft', 'draft') - await expect - .poll(() => inPage("document.getElementById('draft').value")) - .toBe('draft') - await panelAction({ action: 'navigate', url: `${site}/next` }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: false }) + await test.step('leaving a draft from the URL bar asks, and Stay keeps it', async () => { + await typeDraft('draft') + await act({ action: 'navigate', url: `${site}/next` }) + await answerLeave(false) await expect.poll(pageDialog).toBeNull() - expect(await pageUrl()).toBe(`${site}/form`) - expect(await inPage("document.getElementById('draft').value")).toBe('draft') + expect(await pageUrl()).toBe(form) + expect(await draft()).toBe('draft') }) - await check('Reload of a draft asks too, and Stay keeps it', async () => { - await panelAction({ action: 'reload' }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: false }) + await test.step('Reload of a draft asks too, and Stay keeps it', async () => { + await act({ action: 'reload' }) + await answerLeave(false) await expect.poll(pageDialog).toBeNull() - expect(await inPage("document.getElementById('draft').value")).toBe('draft') + expect(await draft()).toBe('draft') }) - await check('Escape keeps the draft and returns typing to the page', async () => { - await userInput('#draft') + await test.step('Escape keeps the draft and returns typing to the page', async () => { + await userInput(app, form, '#draft') // The click is queued input: reloading before the page takes focus lets that focus land // after the modal's, leaving the Sim window without keyboard focus. - await expect.poll(focusedContentsUrl).toBe(`${site}/form`) - await panelAction({ action: 'reload' }) - await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() - await shell.getByRole('dialog').screenshot({ - path: test.info().outputPath('leave-page-modal.png'), - animations: 'allow', - caret: 'initial', - }) + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await act({ action: 'reload' }) await expect(shell.getByRole('button', { name: 'Stay', exact: true })).toBeFocused() const shown = await pageDialog() await shell.keyboard.press('Escape') @@ -456,119 +301,97 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, message: `dialog ${shown?.requestId} was showing when Escape was pressed`, }) .toBeNull() - await expect.poll(focusedContentsUrl).toBe(`${site}/form`) - await shellApp.evaluate(({ webContents }) => { + await expect.poll(() => focusedPageUrl(app)).toBe(form) + await app.evaluate(({ webContents }) => { const contents = webContents.getFocusedWebContents() if (!contents) throw new Error('Missing focused page') contents.sendInputEvent({ type: 'char', keyCode: 'x' }) }) - expect(await inPage("document.getElementById('draft').value")).toBe('xdraft') + await expect.poll(() => draft()).toBe('xdraft') }) - await check('Leave lets the navigation through without asking again', async () => { - await panelAction({ action: 'navigate', url: `${site}/next` }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: true }) + await test.step('Leave lets the navigation through without asking again', async () => { + await act({ action: 'navigate', url: `${site}/next` }) + await answerLeave(true) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() }) - await check('a crashed page drops its pending Leave decision', async () => { - await panelAction({ action: 'navigate', url: `${site}/form` }) - await expect.poll(pageUrl).toBe(`${site}/form`) - await userInput('#draft', 'draft') - await panelAction({ action: 'reload' }) + + await test.step('a crashed page drops its pending Leave decision', async () => { + await act({ action: 'navigate', url: form }) + await expect.poll(pageUrl).toBe(form) + await typeDraft('draft') + await act({ action: 'reload' }) await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) const stale = await pageDialog() - await shellApp.evaluate(({ webContents }, url) => { + await app.evaluate(({ webContents }, url) => { webContents .getAllWebContents() .find((contents) => contents.getURL() === url) ?.forcefullyCrashRenderer() - }, `${site}/form`) + }, form) await expect.poll(pageDialog).toBeNull() - await panelAction({ action: 'respond-dialog', requestId: stale?.requestId, allowed: true }) - await panelAction({ action: 'reload' }) - await expect.poll(() => pageTitle()).toBe('form') + await act({ action: 'respond-dialog', requestId: stale?.requestId, allowed: true }) + await act({ action: 'reload' }) + await expect.poll(formTitle).toBe('form') await expect.poll(pageDialog).toBeNull() }) - await check('Back from a failed load does not capture a later page navigation', async () => { - await userInput('#draft', 'draft') - await panelAction({ action: 'navigate', url: `${site}/broken` }) - await expect.poll(pageDialog).toMatchObject({ kind: 'beforeunload' }) - const dialog = await pageDialog() - await panelAction({ action: 'respond-dialog', requestId: dialog?.requestId, allowed: true }) + await test.step('Back from a failed load does not capture a later page navigation', async () => { + await typeDraft('draft') + await act({ action: 'navigate', url: `${site}/broken` }) + await answerLeave(true) await expect - .poll(() => shell.evaluate(() => (globalThis as Bridge).pageIssue)) + .poll(() => shell.evaluate(() => (globalThis as FixtureGlobals).pageIssue)) .toBe('load-error') - await panelAction({ action: 'back' }) - await inPage(`setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })`) + await act({ action: 'back' }) + // The page navigates itself from whatever document Back left in the tab. + const current = await pageUrl() + if (!current) throw new Error('No page on the fixture site after Back') + await inPage( + app, + current, + `setTimeout(() => { location.href = ${JSON.stringify(`${site}/next`)} })` + ) await expect.poll(pageUrl).toBe(`${site}/next`) expect(await pageDialog()).toBeNull() }) - /** Opens a page-initiated confirm (no user gesture) on the tab at `path`. */ - const confirmFromPage = (path: string) => - shellApp.evaluate(({ webContents }, url) => { - const contents = webContents.getAllWebContents().find((c) => c.getURL() === url) - if (!contents) throw new Error(`No page at ${url}`) - void contents.executeJavaScript( - "setTimeout(() => { document.title = 'confirm:' + confirm('Continue?') })" - ) - }, `${site}${path}`) - const titleAt = (path: string) => - shellApp.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((c) => c.getURL() === url) - ?.getTitle() ?? null, - `${site}${path}` + /** Opens a page-initiated confirm (no user gesture) on the tab at `url`. */ + const confirmFromPage = (url: string) => + inPage( + app, + url, + "setTimeout(() => { document.title = 'confirm:' + confirm('Continue?') }); 'scheduled'" ) - - await check( - "a dialog on the agent's page stays automatic until the user takes it", - async () => { - await execute('browser_open_tab', { url: `${site}/agent` }) - const tabs = await shell.evaluate( - async (scope) => - (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, - SCOPE - ) - const agentTabId = tabs.find((tab) => tab.url === `${site}/agent`)?.tabId - // The resource strip mirrors the agent's tab on screen without the user claiming it. - await panelAction({ action: 'switch-tab', tabId: agentTabId, claim: false }) - await confirmFromPage('/agent') - await expect.poll(() => titleAt('/agent')).toBe('confirm:false') - expect(await pageDialog()).toBeNull() - } - ) - - await check('a dialog while the browser is off screen stays automatic', async () => { - const tabs = await shell.evaluate( - async (scope) => - (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, + const agentTabId = async () => { + const { tabs } = await shell.evaluate( + (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.activateScope(scope), SCOPE ) const tabId = tabs.find((tab) => tab.url === `${site}/agent`)?.tabId - expect(tabId).toBeTruthy() - await panelAction({ action: 'switch-tab', tabId }) - await shell.evaluate((scope) => { - const bridge = globalThis as Bridge - window.clearInterval(bridge.boundsTimer) - bridge.simDesktop.browserAgent.setPanelBounds(null, null, scope) - }, SCOPE) - await confirmFromPage('/agent') - await expect.poll(() => titleAt('/agent')).toBe('confirm:false') + expect(tabId, 'the agent tab is listed').toBeTruthy() + return tabId + } + + await test.step("a dialog on the agent's page stays automatic until the user takes it", async () => { + await execute('browser_open_tab', { url: `${site}/agent` }) + // The resource strip mirrors the agent's tab on screen without the user claiming it. + await act({ action: 'switch-tab', tabId: await agentTabId(), claim: false }) + await confirmFromPage(`${site}/agent`) + await expect.poll(() => titleAt(app, `${site}/agent`)).toBe('confirm:false') + expect(await pageDialog()).toBeNull() + }) + + await test.step('a dialog while the browser is off screen stays automatic', async () => { + await act({ action: 'switch-tab', tabId: await agentTabId() }) + await hideBrowserPanel(shell, SCOPE) + await inPage(app, `${site}/agent`, "document.title = 'agent'") + await confirmFromPage(`${site}/agent`) + await expect.poll(() => titleAt(app, `${site}/agent`)).toBe('confirm:false') expect(await pageDialog()).toBeNull() }) - passed = true } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await server.close() } }) diff --git a/apps/desktop/e2e/browser-page-parity.spec.ts b/apps/desktop/e2e/browser-page-parity.spec.ts index ec1c1256536..ec59c5f70d5 100644 --- a/apps/desktop/e2e/browser-page-parity.spec.ts +++ b/apps/desktop/e2e/browser-page-parity.spec.ts @@ -1,29 +1,25 @@ -import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs' -import { createServer, type ServerResponse } from 'node:http' -import { tmpdir } from 'node:os' +import { readdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { ElectronApplication, Page } from '@playwright/test' +import type { BrowserPageDialog, BrowserPanelAction } from '@sim/browser-protocol' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + type DesktopBridge, expect, - type Page, + type FixtureServer, + focusFirstWindow, + serve, + ToolAuthorizer, test, -} from '@playwright/test' -import type { BrowserPageDialog, BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { recordCheck } from './check-report' +} from './harness' /** * The embedded browser against what a user expects of Chrome: the page menu, * history and tab keys, Escape on a slow load, and a video's fullscreen * button. Each test drives the real shell and native tab views with trusted - * input, and lands in a JSON report at BROWSER_PAGE_PARITY_REPORT_PATH - * (test-results/browser-page-parity-report.json by default) as it finishes. + * input. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-page-parity-e2e' const IS_MAC = process.platform === 'darwin' const SHELL_FIXTURE = 'Sim fixture

Browser parity fixture

' @@ -51,127 +47,79 @@ document.onfullscreenchange = () => { if (!document.fullscreenElement) document. `, } -type Bridge = typeof globalThis & { - simDesktop: SimDesktopApi - pageDialog?: BrowserPageDialog | null - boundsTimer?: number -} +type Bridge = DesktopBridge & { pageDialog?: BrowserPageDialog | null } /** What the suite installs in the main process. */ type MainFixture = typeof globalThis & { agentMenus?: (Electron.MenuItemConstructorOptions | Electron.MenuItem)[][] visibleView?: () => Electron.WebContentsView | undefined } -const reportPath = () => - process.env.BROWSER_PAGE_PARITY_REPORT_PATH ?? - join(test.info().project.outputDir, 'browser-page-parity-report.json') - -/** Runs one check and adds its outcome to the report as soon as it is known. */ -async function check(name: string, body: () => Promise): Promise { - const startedAt = Date.now() - const record = (status: 'passed' | 'failed', error?: unknown) => - recordCheck(reportPath(), 'browser-page-parity', { - name, - status, - durationMs: Date.now() - startedAt, - retry: test.info().retry, - ...(error === undefined ? {} : { error: getErrorMessage(error) }), - }) - try { - await body() - record('passed') - } catch (error) { - record('failed', error) - throw error - } -} - -/** A test whose outcome is also one check in the suite's report. */ -function checkedTest(name: string, body: () => Promise): void { - test(name, () => check(name, body)) -} - test.describe('browser page parity with Chrome', () => { - let app: ElectronApplication | undefined - let shell: Page + let server: FixtureServer let site = '' - let userData = '' + let app: ElectronApplication + let shell: Page let downloads = '' - /** Held responses for the slow page, released when the suite ends. */ - const held = new Set() /** The Referer each load of the link target arrived with. */ const referrers: (string | undefined)[] = [] /** The Referer each request for the image arrived with. */ const imageReferrers: (string | undefined)[] = [] - const calls = new Map() - const server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - if (path === '/pixel.png') { - imageReferrers.push(request.headers.referer) - // Hotlink-protected, like many image hosts: a request without the page as referrer fails. - if (!request.headers.referer) { - response.writeHead(403) - response.end() + const authorizer = new ToolAuthorizer('browser-parity') + + test.beforeAll(async () => { + server = await serve(async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return + const path = url.pathname + if (path === '/pixel.png') { + imageReferrers.push(request.headers.referer) + // Hotlink-protected, like many image hosts: a request without the page as referrer fails. + if (!request.headers.referer) { + response.writeHead(403) + response.end() + return + } + response.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' }) + response.end(PNG) return } - response.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-store' }) - response.end(PNG) - return - } - if (path === '/landing') referrers.push(request.headers.referer) - if (path === '/slow') { - held.add(response) - return - } - // The app origin serves the shell; the same server on localhost is the web. - const isSite = request.headers.host?.startsWith('localhost') === true - response.writeHead(200, { - 'Content-Type': 'text/html', - ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), + if (path === '/landing') referrers.push(request.headers.referer) + // Never answered; closing the server drops it. + if (path === '/slow') return + // The app origin serves the shell; the same server on localhost is the web. + const isSite = request.headers.host?.startsWith('localhost') === true + response.writeHead(200, { + 'Content-Type': 'text/html', + ...(isSite ? {} : { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/' }), + }) + response.end( + isSite + ? (PAGES[path] ?? `${path.slice(1)}

${path}

`) + : SHELL_FIXTURE + ) }) - response.end( - isSite - ? (PAGES[path] ?? `${path.slice(1)}

${path}

`) - : SHELL_FIXTURE - ) + site = server.site }) - test.beforeAll(async () => { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const origin = `http://127.0.0.1:${address.port}` - site = origin.replace('127.0.0.1', 'localhost') - userData = mkdtempSync(join(tmpdir(), 'sim-browser-parity-e2e-')) - downloads = mkdtempSync(join(tmpdir(), 'sim-browser-parity-downloads-')) - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, + test.afterAll(async () => { + await server?.close() + }) + + test.beforeEach(async ({ desktop }) => { + referrers.length = 0 + imageReferrers.length = 0 + downloads = desktop.tempDir('sim-browser-parity-downloads-') + const launched = await desktop.launch({ + origin: server.origin, + // The desktop's own handling decides a page's leave-site question, as in production. + leaveDialogsToDesktop: true, }) - // A dialog listener stops Playwright auto-dismissing a page's leave-site - // question, so the desktop's own handling decides it as in production. - const leaveDialogsToDesktop = (page: Page) => page.on('dialog', () => {}) - app.context().pages().forEach(leaveDialogsToDesktop) - app.context().on('page', leaveDialogsToDesktop) + app = launched.app shell = await app.firstWindow() await app.evaluate(({ app, BrowserWindow, Menu, WebContentsView }, downloads) => { // Downloads default to the OS folder; keep the suite's files out of the user's. app.setPath('downloads', downloads) - const host = BrowserWindow.getAllWindows()[0] - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() // A native menu blocks the main process while it is open; keep each page - // menu's items so a check can choose one the way a click would. + // menu's items so a test can choose one the way a click would. const capture = globalThis as MainFixture capture.visibleView = () => BrowserWindow.getAllWindows()[0].contentView.children.find( @@ -187,65 +135,38 @@ test.describe('browser page parity with Chrome', () => { return menu } }, downloads) + await focusFirstWindow(app) await expect(shell.getByRole('heading')).toHaveText('Browser parity fixture') - await shell.evaluate(async (scope) => { + await shell.evaluate(() => { const bridge = globalThis as Bridge - const api = bridge.simDesktop.browserAgent - await api.activateScope(scope) - api.onPageState((state) => { + bridge.simDesktop.browserAgent.onPageState((state) => { bridge.pageDialog = state.dialog ?? null }) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - bridge.boundsTimer = window.setInterval(updateBounds, 200) - }, SCOPE) - await execute('browser_open_url', { url: `${site}/start` }) + }) + await attachBrowserPanel(shell, SCOPE) + await authorizer.execute(shell, SCOPE, 'browser_open_url', { url: `${site}/start` }) await panelAction({ action: 'switch-tab', tabId: '1' }) await panelAction({ action: 'enable-page-dialogs' }) }) - test.afterAll(async () => { - for (const response of held) response.destroy() - await app?.close() - server.closeAllConnections() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) - rmSync(downloads, { recursive: true, force: true }) - }) - - let callCount = 0 - async function execute(tool: BrowserToolName, args: Record) { - const callId = `browser-parity-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - const result = await shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) - } - - /** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ - async function panelAction(action: Record) { + /** + * Browser-chrome actions are user gestures, so each follows a real click in Sim. The action is a + * send; the invoke after it from the same renderer returns once main has handled it. + */ + async function panelAction(action: BrowserPanelAction) { await shell.getByRole('heading').click() await shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), + async ({ action, scope }) => { + const api = (globalThis as Bridge).simDesktop.browserAgent + api.panelAction(action, scope) + await api.activateScope(scope) + }, { action, scope: SCOPE } ) } /** Reads one property of the page on screen from the main process. */ function visiblePage(read: string): Promise { - if (!app) throw new Error('App not launched') return app.evaluate(({ BrowserWindow }, read) => { const view = (globalThis as MainFixture).visibleView?.() if (!view) return null @@ -254,7 +175,7 @@ test.describe('browser page parity with Chrome', () => { url: contents.getURL(), title: contents.getTitle(), loading: contents.isLoadingMainFrame(), - zoom: contents.getZoomFactor(), + focused: contents.isFocused(), bounds: view.getBounds(), windowFullScreen: BrowserWindow.getAllWindows()[0].isFullScreen(), } @@ -266,6 +187,16 @@ test.describe('browser page parity with Chrome', () => { const pageTitle = () => visiblePage('title') const pageDialog = () => shell.evaluate(() => (globalThis as Bridge).pageDialog ?? null) + /** Gives the page on screen keyboard focus, as the user's click into it would. */ + async function focusPage(): Promise { + await app.evaluate(() => { + const view = (globalThis as MainFixture).visibleView?.() + if (!view) throw new Error('No visible page') + view.webContents.focus() + }) + await expect.poll(() => visiblePage('focused')).toBe(true) + } + /** Trusted input into the page on screen, the way the user's own mouse and keys arrive. */ async function inPage( action: @@ -274,7 +205,7 @@ test.describe('browser page parity with Chrome', () => { | { kind: 'key'; keyCode: string; modifiers?: string[] } | { kind: 'script'; script: string } ): Promise { - if (!app) throw new Error('App not launched') + if (action.kind === 'type' || action.kind === 'key') await focusPage() return app.evaluate(async (_electron, action) => { const view = (globalThis as MainFixture).visibleView?.() if (!view) throw new Error('No visible page') @@ -291,7 +222,6 @@ test.describe('browser page parity with Chrome', () => { keyCode: action.keyCode, modifiers: action.modifiers ?? [], } as Electron.KeyboardInputEvent - contents.focus() contents.sendInputEvent({ ...input, type: 'keyDown' }) contents.sendInputEvent({ ...input, type: 'keyUp' }) return null @@ -312,9 +242,7 @@ test.describe('browser page parity with Chrome', () => { /** Right-clicks `selector` and returns the page menu's item labels. */ async function openPageMenu(selector: string, offsetX?: number): Promise { - if (!app) throw new Error('App not launched') - const menus = () => - app?.evaluate(() => (globalThis as MainFixture).agentMenus?.length ?? 0) ?? 0 + const menus = () => app.evaluate(() => (globalThis as MainFixture).agentMenus?.length ?? 0) const before = await menus() await inPage({ kind: 'right-click', selector, offsetX }) await expect.poll(menus).toBeGreaterThan(before) @@ -327,7 +255,6 @@ test.describe('browser page parity with Chrome', () => { /** Chooses an item from the page menu opened last. */ async function choosePageMenuItem(label: string): Promise { - if (!app) throw new Error('App not launched') await app.evaluate((_electron, label) => { const item = (globalThis as MainFixture).agentMenus ?.at(-1) @@ -343,7 +270,7 @@ test.describe('browser page parity with Chrome', () => { await expect.poll(() => visiblePage('loading')).toBe(false) } - checkedTest("the page menu's Back asks before leaving unsaved changes", async () => { + test("the page menu's Back asks before leaving unsaved changes", async () => { await navigate('/next') await navigate('/form') await inPage({ kind: 'click', selector: '#draft' }) @@ -367,50 +294,45 @@ test.describe('browser page parity with Chrome', () => { await expect.poll(pageUrl).toBe(`${site}/next`) }) - checkedTest( - "the page menu's Save Image lands through the browser's downloads, with the page as referrer", - async () => { - for (const file of readdirSync(downloads)) rmSync(join(downloads, file), { force: true }) - await navigate('/image') - await expect - .poll(() => inPage({ kind: 'script', script: 'document.getElementById("pic").complete' })) - .toBe(true) - const labels = await openPageMenu('#pic') - expect(labels).toEqual( - expect.arrayContaining(['Open Image in New Tab', 'Copy Image', 'Copy Image Address']) - ) - imageReferrers.length = 0 - await choosePageMenuItem('Save Image') - await expect.poll(() => readdirSync(downloads)).toEqual(['pixel.png']) - expect(readFileSync(join(downloads, 'pixel.png')).equals(PNG)).toBe(true) - expect(imageReferrers).toEqual([`${site}/image`]) - } - ) + test("the page menu's Save Image lands through the browser's downloads, with the page as referrer", async () => { + await navigate('/image') + await expect + .poll(() => inPage({ kind: 'script', script: 'document.getElementById("pic").complete' })) + .toBe(true) + const labels = await openPageMenu('#pic') + expect(labels).toEqual( + expect.arrayContaining(['Open Image in New Tab', 'Copy Image', 'Copy Image Address']) + ) + imageReferrers.length = 0 + await choosePageMenuItem('Save Image') + await expect.poll(() => readdirSync(downloads)).toEqual(['pixel.png']) + expect(readFileSync(join(downloads, 'pixel.png')).equals(PNG)).toBe(true) + expect(imageReferrers).toEqual([`${site}/image`]) + }) - checkedTest("the page menu's Open Link in New Tab sends the page as referrer", async () => { - referrers.length = 0 + test("the page menu's Open Link in New Tab sends the page as referrer", async () => { await navigate('/links') await openPageMenu('#link') await choosePageMenuItem('Open Link in New Tab') await expect.poll(() => referrers).toEqual([`${site}/links`]) }) - checkedTest('tab keys, and history keys off macOS, typed in the page follow Chrome', async () => { + test('tab keys, and history keys off macOS, typed in the page follow Chrome', async () => { await navigate('/one') - await execute('browser_open_tab', { url: `${site}/two` }) - await execute('browser_open_tab', { url: `${site}/three` }) + await authorizer.execute(shell, SCOPE, 'browser_open_tab', { url: `${site}/two` }) + await authorizer.execute(shell, SCOPE, 'browser_open_tab', { url: `${site}/three` }) const tabs = await shell.evaluate( async (scope) => (await (globalThis as Bridge).simDesktop.browserAgent.activateScope(scope)).tabs, SCOPE ) - // Earlier checks may have left tabs open; the keys move to the neighbours in strip order. + // The keys move to the strip neighbours, in whatever order the strip placed the new tabs. const urls = tabs.map((tab) => tab.url) + expect([...urls].sort()).toEqual([`${site}/one`, `${site}/three`, `${site}/two`]) const index = urls.indexOf(`${site}/one`) const next = urls[(index + 1) % urls.length] const previous = urls[(index - 1 + urls.length) % urls.length] - expect(urls.length).toBeGreaterThan(2) - await panelAction({ action: 'switch-tab', tabId: tabs[index]?.tabId }) + await panelAction({ action: 'switch-tab', tabId: tabs[index].tabId }) await expect.poll(pageUrl).toBe(`${site}/one`) if (IS_MAC) { @@ -437,7 +359,7 @@ test.describe('browser page parity with Chrome', () => { } }) - checkedTest('Escape stops a page that is still loading', async () => { + test('Escape stops a page that is still loading', async () => { await navigate('/before-slow') await panelAction({ action: 'navigate', url: `${site}/slow` }) await expect.poll(() => visiblePage('loading')).toBe(true) @@ -445,7 +367,7 @@ test.describe('browser page parity with Chrome', () => { await expect.poll(() => visiblePage('loading'), { timeout: 3_000 }).toBe(false) }) - checkedTest("a page's fullscreen fills the browser panel and Escape leaves it", async () => { + test("a page's fullscreen fills the browser panel and Escape leaves it", async () => { await navigate('/fullscreen') const bounds = await visiblePage('bounds') await inPage({ kind: 'click', selector: '#go' }) diff --git a/apps/desktop/e2e/browser-page.ts b/apps/desktop/e2e/browser-page.ts new file mode 100644 index 00000000000..98dc2b65748 --- /dev/null +++ b/apps/desktop/e2e/browser-page.ts @@ -0,0 +1,157 @@ +/** + * Shared pieces for specs that drive a page in the desktop's native browser panel from a Sim shell + * fixture: the fixture server, the shell bring-up, browser-chrome actions, and reads and trusted + * input aimed at the page with an exact URL. + */ +import { join } from 'node:path' +import type { ElectronApplication, Page } from '@playwright/test' +import type { BrowserPanelAction } from '@sim/browser-protocol' +import { + attachBrowserPanel, + type DesktopBridge, + expect, + type FixtureHandler, + type FixtureServer, + focusFirstWindow, + SIM_DIR, + type SimFixtureBundle, + serve, + type ToolAuthorizer, +} from './harness' + +export const BROWSER_SESSION_COMPONENTS = join( + SIM_DIR, + 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session' +) + +interface ShellFixtureOptions { + heading: string + /** Where the native browser panel starts below the shell's own UI. */ + top: number +} + +/** + * Serves the shell on the app origin (with a session cookie) and hands requests to the `site` + * alias, which the browser panel treats as the web, to `site`. + */ +export function serveShellAndSite( + options: ShellFixtureOptions & { + bundle: SimFixtureBundle + authorizer: ToolAuthorizer + site: FixtureHandler + } +): Promise { + const html = `Sim fixture

${options.heading}

` + return serve(async (request, response, url) => { + if (url.pathname === '/fixture.js' || url.pathname === '/fixture.css') { + const js = url.pathname.endsWith('.js') + response.setHeader('Content-Type', js ? 'text/javascript' : 'text/css') + response.end(js ? options.bundle.js : options.bundle.css) + return + } + if (await options.authorizer.handle(request, response, url)) return + if (request.headers.host?.startsWith('localhost')) { + await options.site(request, response, url) + return + } + response.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/', + }) + response.end(html) + }) +} + +/** Focuses the shell window, waits for its fixture UI, and puts the browser panel below it. */ +export async function openShell( + app: ElectronApplication, + scope: string, + options: ShellFixtureOptions +): Promise { + const shell = await app.firstWindow() + await focusFirstWindow(app) + await expect(shell.getByRole('heading')).toHaveText(options.heading) + await attachBrowserPanel(shell, scope, options.top) + return shell +} + +/** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ +export async function panelAction( + shell: Page, + scope: string, + action: BrowserPanelAction +): Promise { + await shell.getByRole('heading').click() + await shell.evaluate( + async ({ action, scope }) => { + const api = (globalThis as DesktopBridge).simDesktop.browserAgent + api.panelAction(action, scope) + // panelAction is a send; this invoke from the same renderer returns after main handled it. + await api.activateScope(scope) + }, + { action, scope } + ) +} + +/** Runs a script in the page at exactly `url`; throws while no page is there, so polls retry. */ +export function inPage( + app: ElectronApplication, + url: string, + script: string, + { userGesture = false } = {} +): Promise { + return app.evaluate( + async ({ webContents }, { url, script, userGesture }) => { + const contents = webContents + .getAllWebContents() + .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + return (await contents.executeJavaScript(script, userGesture)) as T + }, + { url, script, userGesture } + ) +} + +/** Read from the main process: a script cannot run in a page while its dialog is open. */ +export function titleAt(app: ElectronApplication, url: string): Promise { + return app.evaluate( + ({ webContents }, url) => + webContents + .getAllWebContents() + .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) + ?.getTitle() ?? null, + url + ) +} + +export function focusedPageUrl(app: ElectronApplication): Promise { + return app.evaluate(({ webContents }) => webContents.getFocusedWebContents()?.getURL()) +} + +/** + * Trusted input into the page at `url`, the way the user's own mouse and keys arrive: a click on + * `selector`, then `text` typed. The events are queued, so callers wait for their effect. + */ +export function userInput( + app: ElectronApplication, + url: string, + selector: string, + text = '' +): Promise { + return app.evaluate( + async ({ webContents }, { url, selector, text }) => { + const contents = webContents + .getAllWebContents() + .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + const rect: { x: number; y: number } = await contents.executeJavaScript( + `(() => { const { x, y } = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x, y } })()` + ) + const point = { x: Math.round(rect.x + 3), y: Math.round(rect.y + 3) } + contents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 }) + contents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 }) + for (const character of text) contents.sendInputEvent({ type: 'char', keyCode: character }) + }, + { url, selector, text } + ) +} diff --git a/apps/desktop/e2e/browser-sign-in-prompts.spec.ts b/apps/desktop/e2e/browser-sign-in-prompts.spec.ts index d52d13cd97d..6a077dd4ea1 100644 --- a/apps/desktop/e2e/browser-sign-in-prompts.spec.ts +++ b/apps/desktop/e2e/browser-sign-in-prompts.spec.ts @@ -1,82 +1,56 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' +import { join } from 'node:path' +import type { ElectronApplication, Page } from '@playwright/test' import type { BrowserAppLaunchNotice, BrowserPagePrompt, + BrowserPanelAction, BrowserToolName, } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { + BROWSER_SESSION_COMPONENTS, + focusedPageUrl, + inPage, + openShell, + panelAction, + serveShellAndSite, + titleAt, + userInput, +} from './browser-page' +import { + test as base, + bundleSimFixture, + type DesktopBridge, + expect, + type FixtureHandler, + SIM_DIR, + type SimFixtureBundle, + serve, + ToolAuthorizer, +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-sign-in-prompts-e2e' -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) -const SHELL_FIXTURE = - 'Sim fixture

Browser sign-in fixture

' +const SHELL = { heading: 'Browser sign-in fixture', top: 120 } const CREDENTIALS = `Basic ${Buffer.from('alice:s3cret').toString('base64')}` /** Long enough for a refused request to have surfaced if it were going to. */ const QUIET_MS = 1_500 -type Bridge = typeof globalThis & { - simDesktop: SimDesktopApi +type FixtureGlobals = DesktopBridge & { pagePrompt?: BrowserPagePrompt | null launchNotice?: BrowserAppLaunchNotice | null - boundsTimer?: number } type MainGlobals = typeof globalThis & { openedExternal?: string[] } -/** - * A browser tab's sign-in challenges and links to other apps belong to the - * user: Sim shows the question for the tab that asked, only a click in Sim - * answers it, and nothing is asked of an older renderer that cannot show it. - * These checks drive the real shell, native tab views, and Sim's prompt UI. - */ -test('sign-in and app-launch prompts wait for the user on the page that asked', async () => { - test.setTimeout(180_000) - const reportPath = - process.env.DESKTOP_BROWSER_SIGNIN_REPORT_PATH ?? - test.info().outputPath('browser-sign-in-prompts.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const browserComponents = join( - SIM_DIR, - 'app/workspace/[workspaceId]/home/components/mothership-view/components/resource-content/components/browser-session' - ) - const bundle = await build({ - stdin: { - contents: `import { createElement } from 'react'; +let fixtureBundle: Promise | undefined +function shellBundle(): Promise { + if (!fixtureBundle) { + fixtureBundle = bundleSimFixture({ + source: `import { createElement } from 'react'; import { createRoot } from 'react-dom/client'; import { useBrowserSessionStore as store } from ${JSON.stringify(join(SIM_DIR, 'stores/browser-session/store.ts'))}; -import { BrowserAppLaunchNoticeBar, BrowserPagePromptModal } from ${JSON.stringify(join(browserComponents, 'browser-page-prompt.tsx'))}; -import { useBrowserPanelOcclusion } from ${JSON.stringify(join(browserComponents, 'browser-panel-occlusion.ts'))}; +import { BrowserAppLaunchNoticeBar, BrowserPagePromptModal } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-page-prompt.tsx'))}; +import { useBrowserPanelOcclusion } from ${JSON.stringify(join(BROWSER_SESSION_COMPONENTS, 'browser-panel-occlusion.ts'))}; const scope = ${JSON.stringify(SCOPE)}; const api = globalThis.simDesktop.browserAgent; api.onPageState(state => store.getState().setPageState(state)); @@ -93,409 +67,283 @@ function Fixture() { createElement(BrowserPagePromptModal, { prompt: page?.prompt, open: Boolean(page?.prompt), onRespond: respond })); } createRoot(document.getElementById('root')).render(createElement(Fixture));`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - const config = await loadPostcssConfig({}, SIM_DIR) - const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process(readFileSync(stylesheet, 'utf8'), { - from: stylesheet, - }) - const calls = new Map() - const challenges: string[] = [] - let otherPort = 0 - const handleSite = (request: IncomingMessage, response: ServerResponse, port: number) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/basic') { - challenges.push(`${port}${path}`) - if (request.headers.authorization === CREDENTIALS) { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end('secret') - return - } - response.writeHead(401, { - 'Content-Type': 'text/html', - 'WWW-Authenticate': 'Basic realm="Fixture realm"', - }) - response.end('denied') - return - } - response.writeHead(200, { 'Content-Type': 'text/html' }) - if (path === '/subresource') { - response.end( - `sub` - ) - return - } - if (path === '/links') { - response.end(`links + }) + } + return fixtureBundle +} + +/** Every link records trusted and agent clicks, so a test can tell a click landed. */ +const LINKS_FIXTURE = `links +

Join meeting

Diagnostics

Unhandled

-

Mail

-`) - return - } - if (path === '/auto') { - response.end( - `auto` - ) - return - } - response.end('next') - } - const server: Server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end( - path.endsWith('.js') - ? bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text - : css.css - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const authorization = calls.get(JSON.parse(body).toolCallId) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - // The app origin serves the shell; the same server on localhost is the web. - if (request.headers.host?.startsWith('localhost')) { - const address = server.address() - handleSite(request, response, typeof address === 'object' && address ? address.port : 0) - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/', - }) - response.end(SHELL_FIXTURE) - }) - const otherSite: Server = createServer((request, response) => - handleSite(request, response, otherPort) - ) - const userData = mkdtempSync(join(tmpdir(), 'sim-browser-signin-e2e-')) - let app: ElectronApplication | undefined - let passed = false - try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - await new Promise((resolve) => otherSite.listen(0, '127.0.0.1', resolve)) - const address = server.address() - const otherAddress = otherSite.address() - if ( - !address || - typeof address === 'string' || - !otherAddress || - typeof otherAddress === 'string' - ) - throw new Error('Missing fixture address') - otherPort = otherAddress.port - const origin = `http://127.0.0.1:${address.port}` - const site = `http://localhost:${address.port}` - const crossSite = `http://localhost:${otherPort}` - const shellApp = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - app = shellApp - // Launching real apps is out of scope: record what the shell would hand the OS, - // and register a fixture handler for the schemes the page links to. - await shellApp.evaluate(({ app, shell }) => { - const main = globalThis as MainGlobals - main.openedExternal = [] - shell.openExternal = async (url: string) => { - main.openedExternal?.push(url) +

Mail

` + +interface SignInBrowser { + app: ElectronApplication + shell: Page + /** The web, on the shell's own server. */ + site: string + /** A second web origin, for cross-origin challenges. */ + crossSite: string + /** `site/basic` or `cross-site/basic`, per challenge served. */ + challenges: string[] + act(action: BrowserPanelAction): Promise + startTool( + tool: BrowserToolName, + args: Record + ): Promise<{ ok: boolean; error?: string }> + execute(tool: BrowserToolName, args: Record): Promise + pagePrompt(): Promise + launchNotice(): Promise + openedExternal(): Promise + /** Navigates from the URL bar and waits for the page to finish loading with `title`. */ + navigate(url: string, title: string): Promise + /** A trusted click on a link, waited on until the page saw it. */ + clickLink(url: string, selector: string): Promise + /** Signs in through the visible sign-in prompt the way the user does. */ + signInAs(username: string, password: string): Promise + /** Nothing asks and nothing opens, after a click that landed. */ + expectQuiet(openedBefore: string[]): Promise +} + +/** + * A browser tab's sign-in challenges and links to other apps belong to the + * user: Sim shows the question for the tab that asked, only a click in Sim + * answers it, and nothing is asked of an older renderer that cannot show it. + * These checks drive the real shell, native tab views, and Sim's prompt UI. + */ +const test = base.extend<{ signIn: SignInBrowser }>({ + signIn: async ({ desktop }, use) => { + const challenges: string[] = [] + const siteHandler = + (label: string): FixtureHandler => + (request, response, url) => { + if (url.pathname === '/basic') { + challenges.push(`${label}/basic`) + if (request.headers.authorization === CREDENTIALS) { + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('secret') + return + } + response.writeHead(401, { + 'Content-Type': 'text/html', + 'WWW-Authenticate': 'Basic realm="Fixture realm"', + }) + response.end('denied') + return + } + response.writeHead(200, { 'Content-Type': 'text/html' }) + if (url.pathname === '/subresource') { + response.end( + `sub` + ) + } else if (url.pathname === '/links') { + response.end(LINKS_FIXTURE) + } else if (url.pathname === '/auto') { + response.end( + `auto` + ) + } else { + response.end('next') + } } - app.getApplicationNameForProtocol = (url: string) => - /^(simfixture|ms-msdt|mailto):/i.test(url) ? 'Fixture Meetings' : '' - }) - const openedExternal = () => - shellApp.evaluate(() => [...((globalThis as MainGlobals).openedExternal ?? [])]) - const shell = await shellApp.firstWindow() - await shellApp.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - if (!host) throw new Error('Missing host window') - app.focus({ steal: true }) - host.focus() + const crossSite = await serve(siteHandler('cross-site')) + const authorizer = new ToolAuthorizer('browser-signin') + const server = await serveShellAndSite({ + ...SHELL, + bundle: await shellBundle(), + authorizer, + site: siteHandler('site'), }) - await expect(shell.getByRole('heading')).toHaveText('Browser sign-in fixture') - await shell.evaluate(async (scope) => { - const bridge = globalThis as Bridge - const api = bridge.simDesktop.browserAgent - await api.activateScope(scope) - const updateBounds = () => - api.setPanelBounds( - { x: 0, y: 120, width: innerWidth, height: innerHeight - 120 }, - null, - scope + try { + const { app } = await desktop.launch({ origin: server.origin }) + // Launching real apps is out of scope: record what the shell would hand the OS, + // and register a fixture handler for the schemes the page links to. + await app.evaluate(({ app, shell }) => { + const main = globalThis as MainGlobals + main.openedExternal = [] + shell.openExternal = async (url: string) => { + main.openedExternal?.push(url) + } + app.getApplicationNameForProtocol = (url: string) => + /^(simfixture|ms-msdt|mailto):/i.test(url) ? 'Fixture Meetings' : '' + }) + const shell = await openShell(app, SCOPE, SHELL) + const site = server.site + const act = (action: BrowserPanelAction) => panelAction(shell, SCOPE, action) + const startTool = (tool: BrowserToolName, args: Record) => { + const callId = authorizer.issue(SCOPE, tool, args) + return shell.evaluate( + ({ callId, tool, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + callId, + tool, + args, + scope + ), + { callId, tool, args, scope: SCOPE } ) - updateBounds() - bridge.boundsTimer = window.setInterval(updateBounds, 200) - }, SCOPE) + } + const pagePrompt = () => + shell.evaluate(() => (globalThis as FixtureGlobals).pagePrompt ?? null) + const launchNotice = () => + shell.evaluate(() => (globalThis as FixtureGlobals).launchNotice ?? null) + const openedExternal = () => + app.evaluate(() => [...((globalThis as MainGlobals).openedExternal ?? [])]) - let callCount = 0 - const startTool = (tool: BrowserToolName, args: Record) => { - const callId = `browser-signin-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - return shell.evaluate( - ({ callId, tool, args, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.executeTool(callId, tool, args, scope), - { callId, tool, args, scope: SCOPE } - ) - } - const execute = async (tool: BrowserToolName, args: Record) => { - const result = await startTool(tool, args) - expect(result.ok, result.error).toBe(true) - return result.result - } - /** Browser-chrome actions are user gestures, so each follows a real click in Sim. */ - const panelAction = async (action: Record) => { - await shell.getByRole('heading').click() - await shell.evaluate( - ({ action, scope }) => - (globalThis as Bridge).simDesktop.browserAgent.panelAction( - action as unknown as Parameters[0], - scope - ), - { action, scope: SCOPE } - ) - } - const pagePrompt = () => shell.evaluate(() => (globalThis as Bridge).pagePrompt ?? null) - const launchNotice = () => shell.evaluate(() => (globalThis as Bridge).launchNotice ?? null) - /** The page currently at `url`; `read` is `title` or a script evaluated in it. */ - const pageAt = (url: string, read: string) => - shellApp.evaluate( - async ({ webContents }, { url, read }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) - if (!contents) return null - if (read === 'title') return contents.getTitle() as T - return (await contents.executeJavaScript(read, true)) as T + await authorizer.execute(shell, SCOPE, 'browser_open_url', { url: `${site}/next` }) + await act({ action: 'switch-tab', tabId: '1' }) + await expect.poll(() => titleAt(app, `${site}/next`)).toBe('next') + + await use({ + app, + shell, + site, + crossSite: crossSite.site, + challenges, + act, + startTool, + execute: (tool, args) => authorizer.execute(shell, SCOPE, tool, args), + pagePrompt, + launchNotice, + openedExternal, + async navigate(url, title) { + await act({ action: 'navigate', url }) + await expect.poll(() => titleAt(app, url)).toBe(title) + await expect.poll(() => inPage(app, url, 'document.readyState')).toBe('complete') }, - { url, read } - ) - const titleAt = (url: string) => () => pageAt(url, 'title') - const navigate = async (url: string) => { - await panelAction({ action: 'navigate', url }) - await expect.poll(() => pageAt(url, 'title')).not.toBeNull() - } - /** Trusted input into the page, the way the user's own click arrives and focuses it. */ - const userClick = (url: string, selector: string) => - shellApp.evaluate( - async ({ webContents }, { url, selector }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => !candidate.isDestroyed() && candidate.getURL() === url) - if (!contents) throw new Error(`No page at ${url}`) - const rect: { x: number; y: number } = await contents.executeJavaScript( - `(() => { const { x, y } = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x, y } })()` - ) - const point = { x: Math.round(rect.x + 3), y: Math.round(rect.y + 3) } - contents.focus() - contents.sendInputEvent({ type: 'mouseDown', ...point, button: 'left', clickCount: 1 }) - contents.sendInputEvent({ type: 'mouseUp', ...point, button: 'left', clickCount: 1 }) + async clickLink(url, selector) { + const clicks = () => + inPage( + app, + url, + `Number(document.querySelector(${JSON.stringify(selector)}).dataset.clicks ?? 0)` + ) + const before = await clicks() + await userInput(app, url, selector) + await expect.poll(clicks).toBe(before + 1) }, - { url, selector } - ) - /** Types into the visible sign-in prompt the way the user does: the password field unlocks on focus. */ - const signInAs = async (username: string, password: string) => { - const dialog = shell.getByRole('dialog') - await expect(dialog).toHaveCount(1) - await expect(async () => { - await dialog.getByRole('textbox', { name: 'Username' }).fill(username) - await dialog.getByRole('textbox', { name: 'Password' }).click() - await shell.keyboard.press('ControlOrMeta+A') - await shell.keyboard.type(password) - await expect(dialog.getByRole('textbox', { name: 'Username' })).toHaveValue(username, { - timeout: 1_000, - }) - await expect(dialog.getByRole('textbox', { name: 'Password' })).toHaveValue(password, { - timeout: 1_000, - }) - }).toPass({ timeout: 10_000 }) - } - const expectQuiet = async (openedBefore: string[]) => { - await sleep(QUIET_MS) - expect(await pagePrompt()).toBeNull() - expect(await launchNotice()).toBeNull() - expect(await openedExternal()).toEqual(openedBefore) + async signInAs(username, password) { + const dialog = shell.getByRole('dialog') + await expect(dialog).toHaveCount(1) + const usernameField = dialog.getByRole('textbox', { name: 'Username' }) + const passwordField = dialog.getByRole('textbox', { name: 'Password' }) + // Kept from the original suite: the Username field can come back empty right after the + // prompt appears (seen in CI, cause not yet found), so the entry repeats until both hold. + await expect(async () => { + await usernameField.fill(username) + // The password field stays read-only until it takes focus, which keeps autofill out. + await passwordField.click() + await expect(passwordField).toBeEditable({ timeout: 1_000 }) + await passwordField.fill(password) + await expect(usernameField).toHaveValue(username, { timeout: 1_000 }) + await expect(passwordField).toHaveValue(password, { timeout: 1_000 }) + }).toPass({ timeout: 10_000 }) + }, + async expectQuiet(openedBefore) { + await sleep(QUIET_MS) + expect(await pagePrompt()).toBeNull() + expect(await launchNotice()).toBeNull() + expect(await openedExternal()).toEqual(openedBefore) + }, + }) + } finally { + await server.close() + await crossSite.close() } + }, +}) - await execute('browser_open_url', { url: `${site}/next` }) - await panelAction({ action: 'switch-tab', tabId: '1' }) - await expect.poll(titleAt(`${site}/next`)).toBe('next') - - await check('an older renderer leaves sign-in challenges and app links refused', async () => { - await panelAction({ action: 'enable-page-dialogs' }) - await navigate(`${site}/basic`) - await expect.poll(titleAt(`${site}/basic`)).toBe('denied') - expect(await pagePrompt()).toBeNull() - await navigate(`${site}/links`) - await expect.poll(titleAt(`${site}/links`)).toBe('links') - await userClick(`${site}/links`, '#app') - await expectQuiet([]) - }) - - await panelAction({ action: 'enable-page-dialogs', pagePrompts: true }) - - await check( - 'basic auth asks for the page, re-asks after a wrong password, then signs in', - async () => { - await panelAction({ action: 'navigate', url: `${site}/basic` }) - await expect.poll(pagePrompt).toMatchObject({ - kind: 'http-auth', - origin: site, - proxy: false, - insecure: true, - retry: false, - }) - await expect(shell.getByText('Your connection to this site is not private.')).toBeVisible() - await signInAs('alice', 'wrong') - await shell.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect.poll(pagePrompt).toMatchObject({ kind: 'http-auth', retry: true }) - await expect(shell.getByText('Incorrect username or password.')).toBeVisible() - await signInAs('alice', 's3cret') - await shell.getByRole('button', { name: 'Sign in', exact: true }).click() - await expect.poll(titleAt(`${site}/basic`)).toBe('secret') - expect(await pagePrompt()).toBeNull() - } - ) - - await check('a cross-origin subresource challenge never asks', async () => { - const before = challenges.length - await navigate(`${site}/subresource`) - await expect.poll(titleAt(`${site}/subresource`)).toBe('img-failed') - expect(challenges.slice(before)).toContain(`${otherPort}/basic`) - expect(await pagePrompt()).toBeNull() - }) - - await check( - "the agent's sign-in challenge waits for the user instead of being answered", - async () => { - const navigation = startTool('browser_navigate', { url: `${crossSite}/basic` }) - await expect.poll(pagePrompt).toMatchObject({ kind: 'http-auth', origin: crossSite }) - await sleep(QUIET_MS) - expect(await pagePrompt()).toMatchObject({ kind: 'http-auth', retry: false }) - await signInAs('alice', 's3cret') - await shell.getByRole('button', { name: 'Sign in', exact: true }).click() - const result = await navigation - expect(result.ok, result.error).toBe(true) - await expect.poll(titleAt(`${crossSite}/basic`)).toBe('secret') - } - ) +test('sign-in challenges and passkeys wait for the user on the page that asked', async ({ + signIn, +}) => { + const { app, shell, site, crossSite } = signIn + const titleOf = (url: string) => () => titleAt(app, url) + const signInButton = shell.getByRole('button', { name: 'Sign in', exact: true }) - await check("the agent's clicks never open another app", async () => { - await navigate(`${site}/links`) - const opened = await openedExternal() - const snapshot = await execute('browser_snapshot', {}) - const ref = /link "Join meeting" \[ref=(\d+)\]/.exec( - String((snapshot as { outline?: string }).outline) - )?.[1] - expect(ref, 'snapshot lists the Join meeting link').toBeTruthy() - const result = await execute('browser_click', { elementId: Number(ref) }) - await expectQuiet(opened) - const notices = [ - ...((result as { notices?: string[] }).notices ?? []), - ...(((await execute('browser_snapshot', {})) as { notices?: string[] }).notices ?? []), - ] - expect(notices.join('\n')).toContain('never open from agent actions') - }) + await test.step('an older renderer leaves sign-in challenges refused', async () => { + await signIn.act({ action: 'enable-page-dialogs' }) + await signIn.navigate(`${site}/basic`, 'denied') + expect(await signIn.pagePrompt()).toBeNull() + }) - await check('a link to another app asks after a click and opens only on Open', async () => { - await userClick(`${site}/links`, '#app') - await expect.poll(pagePrompt).toMatchObject({ - kind: 'external-app', - origin: site, - appName: 'Fixture Meetings', - canAlwaysAllow: false, - }) - const open = shell.getByRole('button', { name: 'Open', exact: true }) - await expect(open).toBeVisible() - expect(await openedExternal()).toEqual([]) - await expect(open).toBeEnabled() - await open.click() - await expect.poll(openedExternal).toEqual(['simfixture://join?id=7']) - expect(await pagePrompt()).toBeNull() - }) + await signIn.act({ action: 'enable-page-dialogs', pagePrompts: true }) - await check('without a click, a page only offers to open the app', async () => { - await navigate(`${site}/auto`) - await expect.poll(launchNotice).toMatchObject({ appName: 'Fixture Meetings', origin: site }) - expect(await pagePrompt()).toBeNull() - expect(await openedExternal()).toEqual(['simfixture://join?id=7']) - await shell.getByRole('button', { name: 'Open', exact: true }).click() - await expect.poll(openedExternal).toEqual(['simfixture://join?id=7', 'simfixture://auto']) - await expect.poll(launchNotice).toBeNull() + await test.step('basic auth asks for the page, re-asks after a wrong password, then signs in', async () => { + await signIn.act({ action: 'navigate', url: `${site}/basic` }) + await expect.poll(signIn.pagePrompt).toMatchObject({ + kind: 'http-auth', + origin: site, + proxy: false, + insecure: true, + retry: false, }) + await expect(shell.getByText('Your connection to this site is not private.')).toBeVisible() + await signIn.signInAs('alice', 'wrong') + await signInButton.click() + await expect.poll(signIn.pagePrompt).toMatchObject({ kind: 'http-auth', retry: true }) + await expect(shell.getByText('Incorrect username or password.')).toBeVisible() + await signIn.signInAs('alice', 's3cret') + await signInButton.click() + await expect.poll(titleOf(`${site}/basic`)).toBe('secret') + expect(await signIn.pagePrompt()).toBeNull() + }) - await check('a page cannot keep asking to open apps', async () => { - await navigate(`${site}/links`) - await userClick(`${site}/links`, '#app') - await expectQuiet(['simfixture://join?id=7', 'simfixture://auto']) - }) + await test.step('a cross-origin subresource challenge never asks', async () => { + const before = signIn.challenges.length + await signIn.navigate(`${site}/subresource`, 'img-failed') + expect(signIn.challenges.slice(before)).toContain('cross-site/basic') + expect(await signIn.pagePrompt()).toBeNull() + }) - await check( - 'denied and unhandled schemes never open, mail links open after a click', - async () => { - await shell.evaluate( - (scope) => (globalThis as Bridge).simDesktop.browserAgent.openTab?.(scope), - SCOPE - ) - const opened = await openedExternal() - // A fresh document per link: one page's refused launch must not mask the next. - let links = '' - for (const [index, selector] of ['#denied', '#unhandled'].entries()) { - links = `${site}/links?tab=2&link=${index}` - await navigate(links) - await userClick(links, selector) - await expectQuiet(opened) - } - await userClick(links, '#mail') - await expect.poll(openedExternal).toEqual([...opened, 'mailto:a@example.com?subject=Hi']) - expect(await pagePrompt()).toBeNull() - } - ) + await test.step("the agent's sign-in challenge waits for the user instead of being answered", async () => { + const navigation = signIn.startTool('browser_navigate', { url: `${crossSite}/basic` }) + await expect.poll(signIn.pagePrompt).toMatchObject({ kind: 'http-auth', origin: crossSite }) + await sleep(QUIET_MS) + expect(await signIn.pagePrompt()).toMatchObject({ kind: 'http-auth', retry: false }) + await signIn.signInAs('alice', 's3cret') + await signInButton.click() + const result = await navigation + expect(result.ok, result.error).toBe(true) + await expect.poll(titleOf(`${crossSite}/basic`)).toBe('secret') + }) - await check('a passkey sign-in lets the user choose the account', async () => { - const passkeyPage = `${site}/next?passkey` - await navigate(passkeyPage) - await shellApp.evaluate(async ({ webContents }) => { - const contents = webContents - .getAllWebContents() - .find((candidate) => candidate.getURL().includes('/next?passkey')) - if (!contents) throw new Error('No passkey page') - if (!contents.debugger.isAttached()) contents.debugger.attach('1.3') - await contents.debugger.sendCommand('WebAuthn.enable', { enableUI: false }) - await contents.debugger.sendCommand('WebAuthn.addVirtualAuthenticator', { - options: { - protocol: 'ctap2', - transport: 'internal', - hasResidentKey: true, - hasUserVerification: true, - isUserVerified: true, - automaticPresenceSimulation: true, - }, - }) + await test.step('a passkey sign-in lets the user choose the account', async () => { + const passkeyPage = `${site}/next?passkey` + await signIn.navigate(passkeyPage, 'next') + // WebAuthn only answers a focused document, and the user's click is what focuses it. + await userInput(app, passkeyPage, 'html') + await expect.poll(() => focusedPageUrl(app)).toBe(passkeyPage) + await app.evaluate(async ({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((c) => c.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + if (!contents.debugger.isAttached()) contents.debugger.attach('1.3') + await contents.debugger.sendCommand('WebAuthn.enable', { enableUI: false }) + await contents.debugger.sendCommand('WebAuthn.addVirtualAuthenticator', { + options: { + protocol: 'ctap2', + transport: 'internal', + hasResidentKey: true, + hasUserVerification: true, + isUserVerified: true, + automaticPresenceSimulation: true, + }, }) - const created = await pageAt( - passkeyPage, - `(async () => { + }, passkeyPage) + const askForPasskey = `globalThis.passkeyOutcome = 'pending' + navigator.credentials.get({ publicKey: { + challenge: new Uint8Array(16), rpId: 'localhost', userVerification: 'preferred', + } }).then((credential) => new TextDecoder().decode(credential.response.userHandle), + (error) => 'error:' + error.name).then((outcome) => { globalThis.passkeyOutcome = outcome })` + const created = await inPage( + app, + passkeyPage, + `(async () => { const make = (id, name) => navigator.credentials.create({ publicKey: { challenge: new Uint8Array(16), rp: { id: 'localhost', name: 'Fixture' }, user: { id: new TextEncoder().encode(id), name, displayName: name }, @@ -504,57 +352,128 @@ createRoot(document.getElementById('root')).render(createElement(Fixture));`, } }) await make('user-ada', 'ada@example.com') await make('user-grace', 'grace@example.com') - globalThis.passkeyOutcome = 'pending' - navigator.credentials.get({ publicKey: { - challenge: new Uint8Array(16), rpId: 'localhost', userVerification: 'preferred', - } }).then((credential) => new TextDecoder().decode(credential.response.userHandle), - (error) => 'error:' + error.name).then((outcome) => { globalThis.passkeyOutcome = outcome }) + ${askForPasskey} return 'created' - })()` - ) - expect(created).toBe('created') - await expect.poll(pagePrompt).toMatchObject({ - kind: 'passkey-account', - relyingPartyId: 'localhost', - }) - const prompt = await pagePrompt() - expect( - prompt?.kind === 'passkey-account' && prompt.accounts.map((account) => account.name).sort() - ).toEqual(['ada@example.com', 'grace@example.com']) - // A stray Enter must never send an identity: nothing is preselected and Enter does not - // continue. It dismisses when the prompt has keyboard focus and is ignored when it does - // not (as on a CI runner without window focus); either way, refuse and ask again. - const passkeyOutcome = () => pageAt(passkeyPage, 'globalThis.passkeyOutcome') - await shell.keyboard.press('Enter') - await sleep(QUIET_MS) - expect(['pending', 'error:NotAllowedError']).toContain(await passkeyOutcome()) - if ((await passkeyOutcome()) === 'pending') { - await shell.getByRole('button', { name: 'Cancel', exact: true }).click() - } - await expect.poll(passkeyOutcome).toBe('error:NotAllowedError') - await pageAt( - passkeyPage, - `globalThis.passkeyOutcome = 'pending' - navigator.credentials.get({ publicKey: { - challenge: new Uint8Array(16), rpId: 'localhost', userVerification: 'preferred', - } }).then((credential) => new TextDecoder().decode(credential.response.userHandle), - (error) => 'error:' + error.name).then((outcome) => { globalThis.passkeyOutcome = outcome }); 'asked'` - ) - await expect.poll(pagePrompt).toMatchObject({ kind: 'passkey-account' }) - const dialog = shell.getByRole('dialog') - await dialog.getByRole('button').filter({ hasText: 'Choose an account' }).click() - await shell.getByRole('menuitemradio', { name: 'grace@example.com' }).click() - await shell.getByRole('button', { name: 'Continue', exact: true }).click() - await expect.poll(passkeyOutcome).toBe('user-grace') - expect(await pagePrompt()).toBeNull() + })()`, + { userGesture: true } + ) + expect(created).toBe('created') + await expect.poll(signIn.pagePrompt).toMatchObject({ + kind: 'passkey-account', + relyingPartyId: 'localhost', }) - passed = true - } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - await new Promise((resolve) => otherSite.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) - } + const prompt = await signIn.pagePrompt() + expect( + prompt?.kind === 'passkey-account' && prompt.accounts.map((account) => account.name).sort() + ).toEqual(['ada@example.com', 'grace@example.com']) + + // A stray Enter in the prompt must never send an identity: nothing is preselected and + // Enter does not continue. + const passkeyOutcome = () => inPage(app, passkeyPage, 'globalThis.passkeyOutcome') + const dialog = shell.getByRole('dialog') + await dialog.focus() + await expect(dialog).toBeFocused() + await shell.keyboard.press('Enter') + await sleep(QUIET_MS) + expect(await passkeyOutcome()).toBe('pending') + expect(await signIn.pagePrompt()).toMatchObject({ kind: 'passkey-account' }) + await shell.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect.poll(passkeyOutcome).toBe('error:NotAllowedError') + + await inPage(app, passkeyPage, `${askForPasskey}; 'asked'`, { userGesture: true }) + await expect.poll(signIn.pagePrompt).toMatchObject({ kind: 'passkey-account' }) + await dialog.getByRole('button').filter({ hasText: 'Choose an account' }).click() + await shell.getByRole('menuitemradio', { name: 'grace@example.com' }).click() + await shell.getByRole('button', { name: 'Continue', exact: true }).click() + await expect.poll(passkeyOutcome).toBe('user-grace') + expect(await signIn.pagePrompt()).toBeNull() + }) +}) + +test("links to other apps open only after the user's click and their answer", async ({ + signIn, +}) => { + const { shell, site } = signIn + const links = `${site}/links` + const open = shell.getByRole('button', { name: 'Open', exact: true }) + + await test.step('an older renderer leaves app links refused', async () => { + await signIn.act({ action: 'enable-page-dialogs' }) + await signIn.navigate(links, 'links') + await signIn.clickLink(links, '#app') + await signIn.expectQuiet([]) + }) + + await signIn.act({ action: 'enable-page-dialogs', pagePrompts: true }) + + await test.step("the agent's clicks never open another app", async () => { + await signIn.navigate(links, 'links') + const snapshot = await signIn.execute('browser_snapshot', {}) + const ref = /link "Join meeting" \[ref=(\d+)\]/.exec( + String((snapshot as { outline?: string }).outline) + )?.[1] + expect(ref, 'snapshot lists the Join meeting link').toBeTruthy() + const result = await signIn.execute('browser_click', { elementId: Number(ref) }) + await signIn.expectQuiet([]) + const notices = [ + ...((result as { notices?: string[] }).notices ?? []), + ...(((await signIn.execute('browser_snapshot', {})) as { notices?: string[] }).notices ?? []), + ] + expect(notices.join('\n')).toContain('never open from agent actions') + }) + + await test.step('a link to another app asks after a click and opens only on Open', async () => { + await signIn.clickLink(links, '#app') + await expect.poll(signIn.pagePrompt).toMatchObject({ + kind: 'external-app', + origin: site, + appName: 'Fixture Meetings', + canAlwaysAllow: false, + }) + await expect(open).toBeVisible() + expect(await signIn.openedExternal()).toEqual([]) + await expect(open).toBeEnabled() + await open.click() + await expect.poll(signIn.openedExternal).toEqual(['simfixture://join?id=7']) + expect(await signIn.pagePrompt()).toBeNull() + }) + + await test.step('without a click, a page only offers to open the app', async () => { + await signIn.navigate(`${site}/auto`, 'auto') + await expect + .poll(signIn.launchNotice) + .toMatchObject({ appName: 'Fixture Meetings', origin: site }) + expect(await signIn.pagePrompt()).toBeNull() + expect(await signIn.openedExternal()).toEqual(['simfixture://join?id=7']) + await open.click() + await expect + .poll(signIn.openedExternal) + .toEqual(['simfixture://join?id=7', 'simfixture://auto']) + await expect.poll(signIn.launchNotice).toBeNull() + }) + + await test.step('a page cannot keep asking to open apps', async () => { + await signIn.navigate(links, 'links') + await signIn.clickLink(links, '#app') + await signIn.expectQuiet(['simfixture://join?id=7', 'simfixture://auto']) + }) + + await test.step('denied and unhandled schemes never open, mail links open after a click', async () => { + await shell.evaluate( + (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.openTab?.(scope), + SCOPE + ) + const opened = await signIn.openedExternal() + // A fresh document per link: one page's refused launch must not mask the next. + let page = '' + for (const [index, selector] of ['#denied', '#unhandled'].entries()) { + page = `${site}/links?tab=2&link=${index}` + await signIn.navigate(page, 'links') + await signIn.clickLink(page, selector) + await signIn.expectQuiet(opened) + } + await signIn.clickLink(page, '#mail') + await expect.poll(signIn.openedExternal).toEqual([...opened, 'mailto:a@example.com?subject=Hi']) + expect(await signIn.pagePrompt()).toBeNull() + }) }) diff --git a/apps/desktop/e2e/browser-tools.spec.ts b/apps/desktop/e2e/browser-tools.spec.ts index bf3d323751f..5df89210c67 100644 --- a/apps/desktop/e2e/browser-tools.spec.ts +++ b/apps/desktop/e2e/browser-tools.spec.ts @@ -1,20 +1,24 @@ -import { mkdtempSync } from 'node:fs' -import { createServer, type IncomingMessage, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { ElectronApplication, Page } from '@playwright/test' +import type { BrowserTabsState, BrowserToolName, BrowserToolResponse } from '@sim/browser-protocol' +import { refFor } from './executor-sim' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + test as base, + type DesktopBridge, expect, - type Page, - test, -} from '@playwright/test' -import type { BrowserToolName } from '@sim/browser-protocol' -import type { SimDesktopApi } from '@sim/desktop-bridge' + focusFirstWindow, + serve, + ToolAuthorizer, +} from './harness' + +/** + * Browser tools against the real desktop, one app per test. Sharing an app would need a scope per + * test that can be disposed afterwards, and only provisional scopes can be, while tool calls are + * authorized only for real chat ids. + */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'browser-tools-e2e' + const FORM = `Form fixture @@ -53,7 +57,6 @@ const CLICK_FIXTURE = `Click fixture ` const CAPABILITIES_FIXTURE = `Capabilities fixture -
Report row
Drop a receipt
@@ -83,12 +86,6 @@ const popupsFixture = ( }); ` -async function readBody(request: IncomingMessage): Promise { - let body = '' - for await (const chunk of request) body += chunk.toString() - return body -} - const echoPage = (method: string | undefined, body: string) => `${method} ${body}` @@ -120,385 +117,498 @@ const UPLOAD_TARGET_FIXTURE = `Upload target fixture</titl } </script>` -test.describe('browser tools', () => { - const calls = new Map< - string, - { chatId: string; toolName: BrowserToolName | 'terminal'; args: Record<string, unknown> } - >() - const claimed = new Map<string, { args: Record<string, unknown> }>() - let server: Server - let popupServer: Server - let origin: string - let site: string - let popupOrigin: string - let app: ElectronApplication - let window: Page - let callCount = 0 - let beforeUploadResponse: (() => Promise<void>) | undefined - const appEchoes: string[] = [] - - test.beforeAll(async () => { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - if (path === '/redirect') { - response.writeHead(302, { Location: `${origin.replace('127.0.0.1', 'localhost')}/landing` }) - response.end() - return - } - if (path === '/enter-sim') { - response.writeHead(302, { Location: `${origin}/private-chat` }) - response.end() - return - } - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify( - request.headers.cookie?.includes('better-auth.session_token=fixture') - ? { user: { id: 'browser-auth-fixture' }, session: { id: 'fixture-session' } } - : null - ) - ) - return +const UPLOADED = { + original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], + decoy: [], + currentCount: 1, +} +const NOT_UPLOADED = { original: [], decoy: [], currentCount: 0 } + +const PDF = + '%PDF-1.4\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n' + +const PRIVATE_CHAT = + '<!doctype html><title>Private deployed chat

Authenticated deployed chat

' +const PRIVATE_PREVIEW = `Private HTML preview

Authenticated HTML preview

` + +const SESSION_COOKIE = 'better-auth.session_token=fixture' + +/** The fixture servers every test in the file shares. */ +interface ToolsSite { + origin: string + /** The app server as localhost: outside the app origin, so it browses in the agent partition. */ + site: string + popupOrigin: string + authorizer: ToolAuthorizer + /** Requests that reached the app origin's `/echo`. */ + appEchoes: string[] + /** Runs once before the next upload file is served, to change the page mid-staging. */ + beforeUploadResponse: (() => Promise) | undefined +} + +interface Shell { + app: ElectronApplication + shell: Page +} + +interface BrowserTools extends Shell { + scope: string + /** Runs a tool and returns its outcome, failed or not. */ + call(tool: BrowserToolName, args?: Record): Promise + /** Runs a tool and returns its result, failing the test on a tool error. */ + run(tool: BrowserToolName, args?: Record): Promise + /** Opens `url` and returns its snapshot outline. */ + open(url: string): Promise + tabs(): Promise + /** + * Runs script with a user gesture in the page at `url` (or its query-string variants) once it + * finished loading. Throws when no page has that URL. + */ + inPage(url: string, code: string): Promise + /** `inPage` for polling: undefined while no page has that URL. */ + pollPage(url: string, code: string): Promise +} + +async function openShell(app: ElectronApplication): Promise { + const shell = await app.firstWindow() + await focusFirstWindow(app) + await expect(shell.getByRole('heading')).toHaveText('Browser tools fixture') + return shell +} + +function browserTools( + { app, shell }: Shell, + scope: string, + authorizer: ToolAuthorizer +): BrowserTools { + const call = (tool: BrowserToolName, args: Record = {}) => { + const callId = authorizer.issue(scope, tool, args) + return shell.evaluate( + ({ callId, tool, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + callId, + tool, + args, + scope + ), + { callId, tool, args, scope } + ) + } + const run = (tool: BrowserToolName, args: Record = {}) => + authorizer.execute(shell, scope, tool, args) + const pageScript = (url: string, code: string, required: boolean) => + app.evaluate( + async ({ webContents }, { url, code, required }) => { + const contents = webContents + .getAllWebContents() + .find((page) => page.getURL() === url || page.getURL().startsWith(`${url}?`)) + if (!contents) { + if (required) throw new Error(`No page at ${url}`) + return undefined + } + if (contents.isLoading()) { + await new Promise((resolve) => contents.once('did-stop-loading', () => resolve())) + } + return contents.executeJavaScript(code, true) + }, + { url, code, required } + ) + return { + app, + shell, + scope, + call, + run, + async open(url) { + const result = (await run('browser_open_url', { url })) as { snapshot: { outline: string } } + return result.snapshot.outline + }, + tabs: () => + shell.evaluate( + (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.activateScope(scope), + scope + ), + inPage: (url, code) => pageScript(url, code, true), + pollPage: (url, code) => pageScript(url, code, false), + } +} + +const test = base.extend<{ tools: BrowserTools }, { toolsSite: ToolsSite }>({ + toolsSite: [ + // biome-ignore lint/correctness/noEmptyPattern: Playwright reads a fixture's dependencies from this destructuring, and this one has none. + async ({}, use) => { + const fixture: ToolsSite = { + origin: '', + site: '', + popupOrigin: '', + authorizer: new ToolAuthorizer('browser-fixture'), + appEchoes: [], + beforeUploadResponse: undefined, } - if (path === '/api/auth/sign-out') { - response.writeHead(200, { - 'Content-Type': 'application/json', - 'Set-Cookie': 'better-auth.session_token=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0', - }) - response.end('{}') - return + const readBody = async (request: AsyncIterable) => { + let body = '' + for await (const chunk of request) body += chunk.toString() + return body } - if (path === '/private-chat' || path === '/private-preview') { - if (!request.headers.cookie?.includes('better-auth.session_token=fixture')) { - response.writeHead(302, { Location: '/login' }) - response.end() - return + const appServer = await serve(async (request, response, url) => { + if (await fixture.authorizer.handle(request, response, url)) return + const path = url.pathname + const signedIn = request.headers.cookie?.includes(SESSION_COOKIE) === true + const reply = ( + status: number, + headers: Record, + body: string | Buffer = '' + ) => { + response.writeHead(status, headers) + response.end(body) } - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end( - path === '/private-chat' - ? 'Private deployed chat

Authenticated deployed chat

' - : `Private HTML preview

Authenticated HTML preview

` - ) - return - } - if (path === '/api/desktop/tool/file') { - const body = await readBody(request) - const { toolCallId, index } = JSON.parse(body) - const reference = claimed.get(toolCallId)?.args.paths - const found = Array.isArray(reference) && reference[index] === 'files/receipt.txt' - const beforeResponse = beforeUploadResponse - beforeUploadResponse = undefined - try { - await beforeResponse?.() - } catch (error) { - response.writeHead(500, { 'Content-Type': 'text/plain' }) - response.end(String(error)) - return + switch (path) { + case '/redirect': + return reply(302, { Location: `${fixture.site}/landing` }) + case '/enter-sim': + return reply(302, { Location: `${fixture.origin}/private-chat` }) + case '/api/auth/get-session': + return reply( + 200, + { 'Content-Type': 'application/json' }, + JSON.stringify( + signedIn + ? { user: { id: 'browser-auth-fixture' }, session: { id: 'fixture-session' } } + : null + ) + ) + case '/api/auth/sign-out': + return reply( + 200, + { + 'Content-Type': 'application/json', + 'Set-Cookie': + 'better-auth.session_token=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0', + }, + '{}' + ) + case '/private-chat': + case '/private-preview': + if (!signedIn) return reply(302, { Location: '/login' }) + return reply( + 200, + { 'Content-Type': 'text/html' }, + path === '/private-chat' ? PRIVATE_CHAT : PRIVATE_PREVIEW + ) + case '/api/desktop/tool/file': { + const { toolCallId, index } = JSON.parse(await readBody(request)) + const args = fixture.authorizer.calls.get(toolCallId)?.args as + | { paths?: unknown } + | undefined + const found = Array.isArray(args?.paths) && args.paths[index] === 'files/receipt.txt' + const beforeResponse = fixture.beforeUploadResponse + fixture.beforeUploadResponse = undefined + try { + await beforeResponse?.() + } catch (error) { + return reply(500, { 'Content-Type': 'text/plain' }, String(error)) + } + return found + ? reply( + 200, + { + 'Content-Type': 'application/octet-stream', + 'Content-Disposition': 'attachment; filename="receipt.txt"', + }, + 'receipt-bytes' + ) + : reply( + 404, + { 'Content-Type': 'application/json' }, + JSON.stringify({ error: 'File not found' }) + ) + } + case '/upload-target': + return reply(200, { 'Content-Type': 'text/html' }, UPLOAD_TARGET_FIXTURE) + case '/upload-host': { + const frameOrigin = + url.searchParams.get('kind') === 'oopif' ? fixture.origin : fixture.site + return reply( + 200, + { 'Content-Type': 'text/html' }, + `Upload frame fixture` + ) + } + case '/doc.pdf': + return reply(200, { 'Content-Type': 'application/pdf' }, PDF) + case '/echo': { + const body = await readBody(request) + fixture.appEchoes.push(`${request.method} ${body}`) + return reply(200, { 'Content-Type': 'text/html' }, echoPage(request.method, body)) + } + case '/authorize': + return reply(200, { 'Content-Type': 'text/html' }, POPUP_FIXTURE) + case '/popups': + return reply( + 200, + { 'Content-Type': 'text/html' }, + popupsFixture(fixture.origin, fixture.popupOrigin) + ) } - response.writeHead(found ? 200 : 404, { - 'Content-Type': found ? 'application/octet-stream' : 'application/json', - ...(found ? { 'Content-Disposition': 'attachment; filename="receipt.txt"' } : {}), - }) - response.end(found ? 'receipt-bytes' : JSON.stringify({ error: 'File not found' })) - return - } - if (path === '/upload-target' || path === '/upload-host') { - const params = new URL(request.url ?? '/', 'http://127.0.0.1').searchParams - const frameOrigin = params.get('kind') === 'oopif' ? origin : site - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end( - path === '/upload-target' - ? UPLOAD_TARGET_FIXTURE - : `Upload frame fixture` + const page = + path === '/click' + ? CLICK_FIXTURE + : path === '/capabilities' + ? CAPABILITIES_FIXTURE + : path === '/form' + ? FORM + : 'Sim fixture

Browser tools fixture

' + reply( + 200, + { + 'Content-Type': 'text/html', + ...(path === '/workspace' || path === '/home' || path === '/' + ? { 'Set-Cookie': `${SESSION_COOKIE}; HttpOnly; SameSite=Lax; Path=/` } + : {}), + }, + page ) - return - } - if (path === '/doc.pdf') { - response.writeHead(200, { 'Content-Type': 'application/pdf' }) + }) + const popupServer = await serve(async (request, response, url) => { + response.writeHead(200, { 'Content-Type': 'text/html' }) response.end( - '%PDF-1.4\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF\n' + url.pathname === '/echo' + ? echoPage(request.method, await readBody(request)) + : POPUP_FIXTURE ) - return - } - if (path === '/echo') { - const body = await readBody(request) - appEchoes.push(`${request.method} ${body}`) - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end(echoPage(request.method, body)) - return - } - if (path === '/authorize') { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end(POPUP_FIXTURE) - return - } - if (path === '/popups') { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end(popupsFixture(origin, popupOrigin)) - return - } - if (path === '/api/desktop/tool/authorize') { - const body = await readBody(request) - const authorization = calls.get(JSON.parse(body).toolCallId) - calls.delete(JSON.parse(body).toolCallId) - if (authorization) claimed.set(JSON.parse(body).toolCallId, authorization) - response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(authorization ?? {})) - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - ...(path === '/workspace' || path === '/home' || path === '/' - ? { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/' } - : {}), }) - response.end( - path === '/click' - ? CLICK_FIXTURE - : path === '/capabilities' - ? CAPABILITIES_FIXTURE - : path === '/form' - ? FORM - : 'Sim fixture

Browser tools fixture

' - ) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - /** Pages outside the app origin browse in the agent partition, like any third-party site. */ - site = origin.replace('127.0.0.1', 'localhost') - popupServer = createServer(async (request, response) => { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end( - request.url === '/echo' ? echoPage(request.method, await readBody(request)) : POPUP_FIXTURE - ) + fixture.origin = appServer.origin + fixture.site = appServer.site + fixture.popupOrigin = popupServer.site + await use(fixture) + await appServer.close() + await popupServer.close() + }, + { scope: 'worker' }, + ], + + tools: async ({ toolsSite, desktop }, use) => { + const { app } = await desktop.launch({ + origin: toolsSite.origin, + leaveDialogsToDesktop: true, }) - await new Promise((resolve) => popupServer.listen(0, '127.0.0.1', resolve)) - const popupAddress = popupServer.address() - if (!popupAddress || typeof popupAddress === 'string') throw new Error('Missing popup address') - popupOrigin = `http://localhost:${popupAddress.port}` - }) + const shell = await openShell(app) + await attachBrowserPanel(shell, SCOPE) + await use(browserTools({ app, shell }, SCOPE, toolsSite.authorizer)) + toolsSite.appEchoes.length = 0 + toolsSite.beforeUploadResponse = undefined + }, +}) - test.beforeEach(async () => { - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: origin, - SIM_DESKTOP_USER_DATA: mkdtempSync(join(tmpdir(), 'sim-browser-tools-e2e-')), - }, - }) - // A dialog listener stops Playwright auto-dismissing page dialogs, so the desktop's own CDP - // dialog handling decides their outcome exactly as it does in production. - const leaveDialogsToDesktop = (page: Page) => page.on('dialog', () => {}) - app.context().pages().forEach(leaveDialogsToDesktop) - app.context().on('page', leaveDialogsToDesktop) - window = await app.firstWindow() - await app.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() - }) - await expect - .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused())) - .toBe(true) - await expect(window.getByRole('heading')).toHaveText('Browser tools fixture') - await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.browserAgent.activateScope(scope) - const updateBounds = () => - api.browserAgent.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - setInterval(updateBounds, 200) - }, SCOPE) - }) +async function openForm(tools: BrowserTools, origin: string) { + const outline = await tools.open(`${origin}/form`) + expect(outline).toContain('Name') + return (name: string) => refFor(outline, name) +} - test.afterEach(async () => { - beforeUploadResponse = undefined - appEchoes.length = 0 - await app?.close() - calls.clear() - claimed.clear() - }) +function formState(tools: BrowserTools, origin: string) { + return tools.inPage<{ + name: string + plan: string + updates: boolean + password: string + route: string + scrollLeft: number + }>( + `${origin}/form`, + `({ + name: document.getElementById('name').value, + plan: document.getElementById('plan').value, + updates: document.getElementById('updates').checked, + password: document.getElementById('password').value, + route: document.getElementById('route').value, + scrollLeft: document.getElementById('horizontal').scrollLeft + })` + ) +} - test.afterAll(async () => { - for (const listener of [server, popupServer]) { - await new Promise((resolve, reject) => - listener.close((error) => (error ? reject(error) : resolve())) - ) - } - }) +async function openCapabilities(tools: BrowserTools, site: ToolsSite) { + const url = `${site.site}/capabilities?popup=${encodeURIComponent(`${site.popupOrigin}/authorize`)}` + const outline = await tools.open(url) + return { + ref: (name: string) => refFor(outline, name), + dataset: () => tools.pollPage>(url, '({ ...document.body.dataset })'), + } +} - async function execute(tool: BrowserToolName, args: Record) { - const callId = `browser-fixture-${++callCount}` - calls.set(callId, { chatId: SCOPE, toolName: tool, args }) - return window.evaluate( - async ({ callId, tool, args, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.browserAgent.executeTool(callId, tool, args, scope) +async function openUploadTarget( + tools: BrowserTools, + site: string, + kind: 'root' | 'same-origin' | 'oopif' | 'shadow', + steal = false +) { + const framed = kind === 'same-origin' || kind === 'oopif' + const url = framed + ? `${site}/upload-host?kind=${kind}` + : `${site}/upload-target?shadow=${kind === 'shadow' ? '1' : '0'}&steal=${steal ? '1' : '0'}` + await tools.run('browser_open_url', { url }) + /** Runs script in the upload frame, or the top page; undefined while that frame is missing. */ + const evaluate = (expression: string, inTopFrame = false) => + tools.app.evaluate( + ({ webContents }, { url, framed, expression }) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) + if (!contents) throw new Error(`No page at ${url}`) + const frame = framed ? contents.mainFrame.frames[0] : contents.mainFrame + return frame?.executeJavaScript(expression) }, - { callId, tool, args, scope: SCOPE } + { url, framed: framed && !inTopFrame, expression } ) + await expect.poll(() => evaluate('typeof window.uploadTestState')).toBe('function') + if (kind === 'oopif') { + expect( + await tools.app.evaluate(({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) + const child = contents?.mainFrame.frames[0] + return child && child.processId !== contents?.mainFrame.processId + }, url) + ).toBe(true) } + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + return { elementId: refFor(outline, 'Upload original'), evaluate } +} - async function openForm() { - const response = await execute('browser_open_url', { url: `${origin}/form` }) - expect(response.ok, response.error).toBe(true) - const result = response.result as { snapshot: { outline: string } } - expect(result.snapshot.outline).toContain('Name') - return (name: string) => { - const line = result.snapshot.outline - .split('\n') - .find((line) => line.includes(`"${name}"`) && /\[ref=\d+\]/.test(line)) - const match = line?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error(`No reference for ${name}: ${result.snapshot.outline}`) - return Number(match[1]) - } - } +/** The first pixel of a screenshot, as [red, green, blue]. */ +function firstPixel(app: ElectronApplication, dataUrl: string) { + return app.evaluate(({ nativeImage }, dataUrl) => { + const bitmap = nativeImage.createFromDataURL(dataUrl).toBitmap() + return [bitmap[2], bitmap[1], bitmap[0]] + }, dataUrl) +} - async function openCapabilities() { - const url = `${site}/capabilities?popup=${encodeURIComponent(`${popupOrigin}/authorize`)}` - const response = await execute('browser_open_url', { url }) - expect(response.ok, response.error).toBe(true) - const outline = (response.result as { snapshot: { outline: string } }).snapshot.outline - const ref = (name: string) => { - const match = outline - .split('\n') - .find((line) => line.includes(`"${name}"`) && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error(`No reference for ${name}: ${outline}`) - return Number(match[1]) +/** Paints the form page `color` and checks that a screenshot shows it. */ +async function expectCapturedColor( + tools: BrowserTools, + origin: string, + color: string, + dominantChannel: number +) { + await tools.inPage( + `${origin}/form`, + `document.body.style.background = ${JSON.stringify(color)}; + new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))` + ) + const shot = (await tools.run('browser_screenshot')) as { dataUrl: string } + const pixel = await firstPixel(tools.app, shot.dataUrl) + expect(pixel[dominantChannel], `${color}: ${pixel}`).toBeGreaterThan(180) + for (let channel = 0; channel < 3; channel++) { + if (channel !== dominantChannel) { + expect(pixel[dominantChannel] - pixel[channel], `${color}: ${pixel}`).toBeGreaterThan(80) } - const dataset = () => - app.evaluate( - ({ webContents }, url) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - ?.executeJavaScript('({ ...document.body.dataset })'), - url - ) - return { ref, dataset } } +} - test('answers confirm dialogs only when the action asks and right-clicks reach the page', async () => { - const { ref, dataset } = await openCapabilities() - - const dismissed = await execute('browser_click', { elementId: ref('Delete report') }) - expect(JSON.stringify(dismissed.result)).toContain('which was dismissed') - expect(await dataset()).toMatchObject({ deleted: 'false' }) +/** The window and form page state a screenshot must leave as it was. */ +function windowState(tools: BrowserTools, origin: string) { + return tools.app.evaluate(async ({ BrowserWindow, webContents }, origin) => { + const win = BrowserWindow.getAllWindows()[0] + const contents = webContents + .getAllWebContents() + .find((page) => page.getURL() === `${origin}/form`) + if (!contents) throw new Error('Missing screenshot fixture') + return { + id: contents.id, + visible: win.isVisible(), + minimized: win.isMinimized(), + bounds: win.getBounds(), + focused: BrowserWindow.getFocusedWindow()?.id ?? null, + page: await contents.executeJavaScript( + "({width:innerWidth,height:innerHeight,scrollX,scrollY,html:document.body.innerHTML,focus:document.activeElement?.id,value:document.getElementById('name').value})" + ), + } + }, origin) +} - const accepted = await execute('browser_click', { - elementId: ref('Delete report'), - dialog: { accept: true }, +/** Takes screenshots of the form page, checking each image and that nothing else changed. */ +async function expectCapturesLeaveStateUnchanged(tools: BrowserTools, origin: string) { + const before = await windowState(tools, origin) + for (let i = 0; i < 3; i++) { + const shot = (await tools.run('browser_screenshot')) as { + dataUrl: string + scale: number + viewport: { width: number; height: number } + } + expect(shot.viewport.width).toBeGreaterThan(0) + expect(shot.viewport.height).toBeGreaterThan(0) + const image = await tools.app.evaluate(({ nativeImage }, dataUrl) => { + const image = nativeImage.createFromDataURL(dataUrl) + return { empty: image.isEmpty(), ...image.getSize() } + }, shot.dataUrl) + expect(image).toEqual({ + empty: false, + width: Math.round(shot.viewport.width * shot.scale), + height: Math.round(shot.viewport.height * shot.scale), }) - expect(JSON.stringify(accepted.result)).toContain('accepted as requested') - expect(await dataset()).toMatchObject({ deleted: 'true' }) + expect(await windowState(tools, origin)).toEqual(before) + } + return before +} - const menu = await execute('browser_click', { +/** Blurs the window and waits until no window has focus. */ +async function blurWindow(tools: BrowserTools) { + await tools.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].blur()) + await expect + .poll(() => + tools.app.evaluate(({ BrowserWindow }) => BrowserWindow.getFocusedWindow()?.id ?? null) + ) + .toBeNull() +} + +test.describe('browser tools', () => { + test('right-clicks with modifiers reach the page', async ({ tools, toolsSite }) => { + const { ref, dataset } = await openCapabilities(tools, toolsSite) + await tools.run('browser_click', { elementId: ref('Report row'), button: 'right', modifiers: ['Shift'], }) - expect(menu.ok, menu.error).toBe(true) expect(await dataset()).toMatchObject({ menu: '2:true' }) }) - test('uploads a workspace file into the hidden input behind a drop zone', async () => { - const { ref, dataset } = await openCapabilities() - - const upload = await execute('browser_upload_file', { + test('uploads a workspace file into the hidden input behind a drop zone', async ({ + tools, + toolsSite, + }) => { + const { ref, dataset } = await openCapabilities(tools, toolsSite) + const upload = await tools.run('browser_upload_file', { elementId: ref('Attach receipt'), paths: ['files/receipt.txt'], }) - - expect(upload.ok, upload.error).toBe(true) - expect(upload.result).toMatchObject({ + expect(upload).toMatchObject({ uploaded: [{ name: 'receipt.txt', size: 13 }], effectObserved: true, }) await expect.poll(dataset).toMatchObject({ upload: 'receipt.txt:receipt-bytes' }) }) - async function openUploadTarget( - kind: 'root' | 'same-origin' | 'oopif' | 'shadow', - steal = false - ) { - const framed = kind === 'same-origin' || kind === 'oopif' - const url = framed - ? `${site}/upload-host?kind=${kind}` - : `${site}/upload-target?shadow=${kind === 'shadow' ? '1' : '0'}&steal=${steal ? '1' : '0'}` - const response = await execute('browser_open_url', { url }) - expect(response.ok, response.error).toBe(true) - const evaluate = (expression: string, inTopFrame = false) => - app.evaluate( - ({ webContents }, { url, framed, expression }) => { - const contents = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - const frame = framed ? contents?.mainFrame.frames[0] : contents?.mainFrame - if (!frame) throw new Error('Missing upload fixture frame') - return frame.executeJavaScript(expression) - }, - { url, framed: framed && !inTopFrame, expression } - ) - await expect.poll(() => evaluate('typeof window.uploadTestState')).toBe('function') - if (kind === 'oopif') { - expect( - await app.evaluate(({ webContents }, url) => { - const contents = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - const child = contents?.mainFrame.frames[0] - return child && child.processId !== contents?.mainFrame.processId - }, url) - ).toBe(true) - } - const snapshot = await execute('browser_snapshot', {}) - expect(snapshot.ok, snapshot.error).toBe(true) - const outline = (snapshot.result as { outline: string }).outline - const match = outline - .split('\n') - .find((line) => line.includes('"Upload original"')) - ?.match(/\[ref=(\d+)\]/) - expect(match, outline).toBeTruthy() - return { elementId: Number(match?.[1]), evaluate } - } - - test('pins uploads to the original input when page code steals a DOM marker', async () => { - const { elementId, evaluate } = await openUploadTarget('root', true) - const upload = await execute('browser_upload_file', { elementId, paths: ['files/receipt.txt'] }) - - expect(upload.ok, upload.error).toBe(true) - expect(await evaluate('window.uploadTestState()')).toEqual({ - original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], - decoy: [], - currentCount: 1, - }) + test('pins uploads to the original input when page code steals a DOM marker', async ({ + tools, + toolsSite, + }) => { + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, 'root', true) + await tools.run('browser_upload_file', { elementId, paths: ['files/receipt.txt'] }) + expect(await evaluate('window.uploadTestState()')).toEqual(UPLOADED) }) - test('reports an unconfirmed upload when cancelled before Chromium acknowledgement arrives', async () => { - const { elementId, evaluate } = await openUploadTarget('root') - await app.evaluate(({ webContents }, site) => { - const contents = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === `${site}/upload-target?shadow=0&steal=0`) + test('reports an unconfirmed upload when cancelled before Chromium acknowledgement arrives', async ({ + tools, + toolsSite, + }) => { + type Held = { count: number; applied: boolean; release: () => void; restore: () => void } + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, 'root') + await tools.app.evaluate(({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) if (!contents) throw new Error('Missing upload acknowledgement fixture') const original = contents.debugger.sendCommand let release = () => {} const acknowledgement = new Promise((resolve) => { release = resolve }) - const state = { + const state: Held = { count: 0, applied: false, release, @@ -506,8 +616,9 @@ test.describe('browser tools', () => { contents.debugger.sendCommand = original }, } - const globals = globalThis as typeof globalThis & { heldUploadAcknowledgement?: typeof state } - globals.heldUploadAcknowledgement = state + ;( + globalThis as typeof globalThis & { heldUploadAcknowledgement?: Held } + ).heldUploadAcknowledgement = state contents.debugger.sendCommand = async (method, params, sessionId) => { if (method !== 'DOM.setFileInputFiles') { return original.call(contents.debugger, method, params, sessionId) @@ -518,36 +629,35 @@ test.describe('browser tools', () => { await acknowledgement return result } - }, site) - const pending = execute('browser_upload_file', { elementId, paths: ['files/receipt.txt'] }) - const toolCallId = `browser-fixture-${callCount}` + }, `${toolsSite.site}/upload-target?shadow=0&steal=0`) + const held = () => + tools.app.evaluate(() => { + const state = (globalThis as typeof globalThis & { heldUploadAcknowledgement?: Held }) + .heldUploadAcknowledgement + return state && { count: state.count, applied: state.applied } + }) + const args = { elementId, paths: ['files/receipt.txt'] } + const toolCallId = toolsSite.authorizer.issue(tools.scope, 'browser_upload_file', args) + const pending = tools.shell.evaluate( + ({ toolCallId, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + toolCallId, + 'browser_upload_file', + args, + scope + ), + { toolCallId, args, scope: tools.scope } + ) try { - await expect - .poll(() => evaluate('window.uploadTestState()')) - .toEqual({ - original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], - decoy: [], - currentCount: 1, - }) - await expect - .poll(() => - app.evaluate( - () => - ( - globalThis as typeof globalThis & { - heldUploadAcknowledgement?: { applied: boolean } - } - ).heldUploadAcknowledgement?.applied - ) - ) - .toBe(true) - await window.evaluate( + await expect.poll(() => evaluate('window.uploadTestState()')).toEqual(UPLOADED) + await expect.poll(held).toMatchObject({ applied: true }) + await tools.shell.evaluate( async ({ toolCallId, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - if (!api.browserAgent.cancelTool) throw new Error('Browser cancellation is unavailable') - await api.browserAgent.cancelTool(toolCallId, scope) + const api = (globalThis as DesktopBridge).simDesktop.browserAgent + if (!api.cancelTool) throw new Error('Browser cancellation is unavailable') + await api.cancelTool(toolCallId, scope) }, - { toolCallId, scope: SCOPE } + { toolCallId, scope: tools.scope } ) const upload = await pending @@ -558,22 +668,11 @@ test.describe('browser tools', () => { note: expect.stringContaining('Inspect the page'), }) expect(upload.result).not.toHaveProperty('dispatched', true) - expect((await execute('browser_list_tabs', {})).ok).toBe(true) - expect( - await app.evaluate( - () => - ( - globalThis as typeof globalThis & { - heldUploadAcknowledgement?: { count: number } - } - ).heldUploadAcknowledgement?.count - ) - ).toBe(1) + await tools.run('browser_list_tabs') + expect(await held()).toMatchObject({ count: 1 }) } finally { - await app.evaluate(() => { - const globals = globalThis as typeof globalThis & { - heldUploadAcknowledgement?: { release: () => void; restore: () => void } - } + await tools.app.evaluate(() => { + const globals = globalThis as typeof globalThis & { heldUploadAcknowledgement?: Held } globals.heldUploadAcknowledgement?.release() globals.heldUploadAcknowledgement?.restore() globals.heldUploadAcknowledgement = undefined @@ -583,12 +682,17 @@ test.describe('browser tools', () => { }) for (const mutation of ['replace', 'disable', 'navigate-frame'] as const) { - test(`refuses uploads when the target changes during staging: ${mutation}`, async () => { + test(`refuses uploads when the target changes during staging: ${mutation}`, async ({ + tools, + toolsSite, + }) => { const { elementId, evaluate } = await openUploadTarget( + tools, + toolsSite.site, mutation === 'navigate-frame' ? 'same-origin' : 'root' ) let mutated = false - beforeUploadResponse = async () => { + toolsSite.beforeUploadResponse = async () => { if (mutation === 'navigate-frame') { await evaluate('parent.previousUploadInput = document.querySelector("#original")') await evaluate('location.replace("/upload-target?after=1")') @@ -599,35 +703,34 @@ test.describe('browser tools', () => { } mutated = true } - const upload = await execute('browser_upload_file', { + const upload = await tools.call('browser_upload_file', { elementId, paths: ['files/receipt.txt'], }) expect(mutated).toBe(true) expect(upload.ok, JSON.stringify(upload)).toBe(false) - expect(await evaluate('window.uploadTestState()')).toEqual({ - original: [], - decoy: [], - currentCount: 0, - }) + expect(await evaluate('window.uploadTestState()')).toEqual(NOT_UPLOADED) if (mutation === 'navigate-frame') { expect(await evaluate('parent.previousUploadInput.files.length')).toBe(0) } }) } - test('refuses uploads after their same-origin frame is removed during staging', async () => { - const { elementId, evaluate } = await openUploadTarget('same-origin') + test('refuses uploads after their same-origin frame is removed during staging', async ({ + tools, + toolsSite, + }) => { + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, 'same-origin') let removed = false - beforeUploadResponse = async () => { + toolsSite.beforeUploadResponse = async () => { await evaluate( 'window.removedUploadInput = document.querySelector("iframe").contentDocument.querySelector("#original"); document.querySelector("iframe").remove()', true ) removed = true } - const upload = await execute('browser_upload_file', { + const upload = await tools.call('browser_upload_file', { elementId, paths: ['files/receipt.txt'], }) @@ -638,155 +741,159 @@ test.describe('browser tools', () => { }) for (const kind of ['same-origin', 'oopif', 'shadow'] as const) { - test(`uploads through a pinned input in a ${kind} context`, async () => { - const { elementId, evaluate } = await openUploadTarget(kind) - const upload = await execute('browser_upload_file', { + test(`uploads through a pinned input in a ${kind} context`, async ({ tools, toolsSite }) => { + const { elementId, evaluate } = await openUploadTarget(tools, toolsSite.site, kind) + const upload = await tools.run('browser_upload_file', { elementId, paths: ['files/receipt.txt'], }) - - expect(upload.ok, upload.error).toBe(true) - expect(upload.result).toMatchObject({ uploaded: [{ name: 'receipt.txt', size: 13 }] }) - expect(await evaluate('window.uploadTestState()')).toEqual({ - original: [{ name: 'receipt.txt', text: 'receipt-bytes' }], - decoy: [], - currentCount: 1, - }) + expect(upload).toMatchObject({ uploaded: [{ name: 'receipt.txt', size: 13 }] }) + expect(await evaluate('window.uploadTestState()')).toEqual(UPLOADED) }) } - test('keeps window.opener for page popups and returns to the opener when they close', async () => { - const { ref, dataset } = await openCapabilities() + test('keeps window.opener for page popups and returns to the opener when they close', async ({ + tools, + toolsSite, + }) => { + const { ref, dataset } = await openCapabilities(tools, toolsSite) + const popupUrl = `${toolsSite.popupOrigin}/authorize` - expect((await execute('browser_click', { elementId: ref('Connect') })).ok).toBe(true) - const popup = await execute('browser_snapshot', {}) - const allow = (popup.result as { outline: string }).outline.match( - /button "Allow" \[ref=(\d+)\]/ - )?.[1] - expect(allow, JSON.stringify(popup.result)).toBeTruthy() - const allowed = await execute('browser_click', { elementId: Number(allow) }) - expect(allowed.ok, allowed.error).toBe(true) + await tools.run('browser_click', { elementId: ref('Connect') }) + await expect.poll(() => tools.pollPage(popupUrl, 'true')).toBe(true) + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + await tools.run('browser_click', { elementId: refFor(outline, 'Allow') }) await expect.poll(dataset).toMatchObject({ connected: 'granted' }) await expect - .poll( - async () => ((await execute('browser_list_tabs', {})).result as { tabs: unknown[] }).tabs - ) + .poll(async () => ((await tools.run('browser_list_tabs')) as { tabs: unknown[] }).tabs) .toHaveLength(1) }) - const tabsState = () => - window.evaluate( - (scope) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.activateScope(scope), - SCOPE - ) - const tabUrls = async () => (await tabsState()).tabs.map((tab) => tab.url) - /** Runs script in a page with a user gesture, as the user's own click would. */ - const inPage = (url: string, code: string) => - app.evaluate( - ({ webContents }, { url, code }) => - webContents - .getAllWebContents() - .find((contents) => contents.getURL() === url) - ?.executeJavaScript(code, true), - { url, code } - ) - const pageDataset = (url: string) => inPage(url, '({ ...document.body.dataset })') - - test('adopts a blank popup that keeps its opener and returns there when it closes', async () => { + test('adopts a blank popup that keeps its opener and returns there when it closes', async ({ + tools, + toolsSite, + }) => { + const { site, popupOrigin } = toolsSite const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) + const tabUrls = async () => (await tools.tabs()).tabs.map((tab) => tab.url) + await tools.run('browser_open_url', { url: openerUrl }) // A second tab makes the strip neighbour differ from the opener. - expect((await execute('browser_open_tab', { url: `${site}/other` })).ok).toBe(true) - const openerTabId = (await tabsState()).tabs.find((tab) => tab.url === openerUrl)?.tabId + await tools.run('browser_open_tab', { url: `${site}/other` }) + const openerTabId = (await tools.tabs()).tabs.find((tab) => tab.url === openerUrl)?.tabId expect(openerTabId).toBeTruthy() - await inPage(openerUrl, 'signIn()') + await tools.inPage(openerUrl, 'signIn()') await expect - .poll(() => pageDataset(openerUrl)) + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) .toMatchObject({ handle: 'true', blank: 'ready' }) await expect.poll(tabUrls).toContain(`${popupOrigin}/authorize`) - const popupTab = (await tabsState()).tabs.find((tab) => tab.url === `${popupOrigin}/authorize`) + const popupTab = (await tools.tabs()).tabs.find((tab) => tab.url === `${popupOrigin}/authorize`) expect(popupTab?.active).toBe(true) - await inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") - await expect.poll(() => pageDataset(openerUrl)).toMatchObject({ connected: 'granted' }) - await expect.poll(async () => (await tabsState()).tabs.length).toBe(2) - expect((await tabsState()).activeTabId).toBe(openerTabId) + await tools.inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") + await expect + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) + .toMatchObject({ connected: 'granted' }) + await expect.poll(async () => (await tools.tabs()).tabs.length).toBe(2) + expect((await tools.tabs()).activeTabId).toBe(openerTabId) }) - test('forgets the opener once the user switches tabs, closing the popup to its neighbour', async () => { + test('forgets the opener once the user switches tabs, closing the popup to its neighbour', async ({ + tools, + toolsSite, + }) => { + const { site, popupOrigin } = toolsSite const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - expect((await execute('browser_open_tab', { url: `${site}/other` })).ok).toBe(true) - const otherTabId = (await tabsState()).tabs.find((tab) => tab.url === `${site}/other`)?.tabId - await inPage(openerUrl, 'signIn()') - await expect.poll(tabUrls).toContain(`${popupOrigin}/authorize`) - const popupTabId = (await tabsState()).tabs.find( + await tools.run('browser_open_url', { url: openerUrl }) + await tools.run('browser_open_tab', { url: `${site}/other` }) + const otherTabId = (await tools.tabs()).tabs.find((tab) => tab.url === `${site}/other`)?.tabId + await tools.inPage(openerUrl, 'signIn()') + await expect + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${popupOrigin}/authorize`) + const popupTabId = (await tools.tabs()).tabs.find( (tab) => tab.url === `${popupOrigin}/authorize` )?.tabId for (const tabId of [otherTabId, popupTabId]) { - await window.evaluate( + await tools.shell.evaluate( ({ tabId, scope }) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.panelAction({ action: 'switch-tab', tabId }, scope), - { tabId, scope: SCOPE } + (globalThis as DesktopBridge).simDesktop.browserAgent.panelAction( + { action: 'switch-tab', tabId }, + scope + ), + { tabId, scope: tools.scope } ) - await expect.poll(async () => (await tabsState()).activeTabId).toBe(tabId) + await expect.poll(async () => (await tools.tabs()).activeTabId).toBe(tabId) } - await inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") - await expect.poll(() => pageDataset(openerUrl)).toMatchObject({ connected: 'granted' }) - await expect.poll(async () => (await tabsState()).tabs.length).toBe(2) - expect((await tabsState()).activeTabId).toBe(otherTabId) + await tools.inPage(`${popupOrigin}/authorize`, "document.querySelector('button').click()") + await expect + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) + .toMatchObject({ connected: 'granted' }) + await expect.poll(async () => (await tools.tabs()).tabs.length).toBe(2) + expect((await tools.tabs()).activeTabId).toBe(otherTabId) }) - test('keeps data: popups denied', async () => { - const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - expect(await inPage(openerUrl, "String(window.open('data:text/html,x') !== null)")).toBe( + test('keeps data: popups denied', async ({ tools, toolsSite }) => { + const openerUrl = `${toolsSite.site}/popups` + await tools.run('browser_open_url', { url: openerUrl }) + expect(await tools.inPage(openerUrl, "String(window.open('data:text/html,x') !== null)")).toBe( 'false' ) - expect((await tabsState()).tabs).toHaveLength(1) + // The handler decides popups in order, so once this one is listed the data: popup was decided. + await tools.inPage(openerUrl, `void window.open('${toolsSite.site}/sentinel')`) + await expect + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${toolsSite.site}/sentinel`) + expect((await tools.tabs()).tabs).toHaveLength(2) }) - test('posts a same-session form popup and refuses to reissue a cross-session one', async () => { + test('posts a same-session form popup and refuses to reissue a cross-session one', async ({ + tools, + toolsSite, + }) => { + const { site, popupOrigin } = toolsSite const openerUrl = `${site}/popups` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - await inPage(openerUrl, "document.getElementById('same-session').requestSubmit()") - await expect.poll(() => inPage(`${popupOrigin}/echo`, 'document.title')).toBe('POST note=hello') + await tools.run('browser_open_url', { url: openerUrl }) + await tools.inPage(openerUrl, "document.getElementById('same-session').requestSubmit()") + await expect + .poll(() => tools.pollPage(`${popupOrigin}/echo`, 'document.title')) + .toBe('POST note=hello') - const before = (await tabsState()).tabs.length - await inPage(openerUrl, "document.getElementById('cross-session').requestSubmit()") + const before = (await tools.tabs()).tabs.length + await tools.inPage(openerUrl, "document.getElementById('cross-session').requestSubmit()") // The handler decides popups in order, so once this one is listed the post was decided. - await inPage(openerUrl, `void window.open('${site}/sentinel')`) - await expect.poll(tabUrls).toContain(`${site}/sentinel`) - expect((await tabsState()).tabs).toHaveLength(before + 1) - expect(appEchoes).toEqual([]) + await tools.inPage(openerUrl, `void window.open('${site}/sentinel')`) + await expect + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${site}/sentinel`) + expect((await tools.tabs()).tabs).toHaveLength(before + 1) + expect(toolsSite.appEchoes).toEqual([]) }) - test('keeps the opener of a Sim page blank popup that navigates within Sim', async () => { + test('keeps the opener of a Sim page blank popup that navigates within Sim', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite const openerUrl = `${origin}/popups?next=${encodeURIComponent(`${origin}/authorize`)}` - expect((await execute('browser_open_url', { url: openerUrl })).ok).toBe(true) - await inPage(openerUrl, 'signIn()') - await expect.poll(tabUrls).toContain(`${origin}/authorize`) - await inPage(`${origin}/authorize`, "document.querySelector('button').click()") + await tools.run('browser_open_url', { url: openerUrl }) + await tools.inPage(openerUrl, 'signIn()') await expect - .poll(() => pageDataset(openerUrl)) + .poll(async () => (await tools.tabs()).tabs.map((tab) => tab.url)) + .toContain(`${origin}/authorize`) + await tools.inPage(`${origin}/authorize`, "document.querySelector('button').click()") + await expect + .poll(() => tools.pollPage(openerUrl, '({ ...document.body.dataset })')) .toMatchObject({ handle: 'true', connected: 'granted' }) }) - test('renders PDFs in the built-in viewer', async () => { - const response = await execute('browser_open_url', { url: `${site}/doc.pdf` }) - expect(response.ok, response.error).toBe(true) - + test('renders PDFs in the built-in viewer', async ({ tools, toolsSite }) => { + await tools.run('browser_open_url', { url: `${toolsSite.site}/doc.pdf` }) await expect .poll(() => - app.evaluate( + tools.app.evaluate( ({ webContents }, url) => webContents .getAllWebContents() @@ -794,18 +901,24 @@ test.describe('browser tools', () => { ?.mainFrame.framesInSubtree.some((frame) => frame.url.startsWith('chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/') ), - `${site}/doc.pdf` + `${toolsSite.site}/doc.pdf` ) ) .toBe(true) }) - test('shares desktop authentication for private HTML previews and deployed chats', async () => { + test('shares desktop authentication for private HTML previews and deployed chats', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite for (const path of ['/private-preview', '/private-chat']) { - const result = await execute('browser_open_url', { url: `${origin}${path}` }) - expect(result.ok, result.error).toBe(true) - expect(result.result).toMatchObject({ url: `${origin}${path}` }) - const state = await app.evaluate(async ({ webContents, BrowserWindow }, url) => { + const result = (await tools.run('browser_open_url', { url: `${origin}${path}` })) as { + url: string + snapshot: { outline: string } + } + expect(result.url).toBe(`${origin}${path}`) + const state = await tools.app.evaluate(async ({ webContents, BrowserWindow }, url) => { const host = BrowserWindow.getAllWindows()[0].webContents const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) if (!page) throw new Error('Missing protected page') @@ -818,20 +931,13 @@ test.describe('browser tools', () => { escaped: await page.executeJavaScript('document.body.dataset.escaped === "true"'), } }, `${origin}${path}`) - expect(state.sharedSession).toBe(true) - expect(state.hasDesktopBridge).toBe(false) + expect(state).toMatchObject({ sharedSession: true, hasDesktopBridge: false, escaped: false }) expect(state.heading).toContain('Authenticated') - expect(state.escaped).toBe(false) if (path === '/private-preview') { - const outline = (result.result as { snapshot: { outline: string } }).snapshot.outline - const button = outline - .split('\n') - .find((line) => line.includes('"Test quiz"') && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/)?.[1] - expect(button, JSON.stringify(result.result)).toBeTruthy() - const click = await execute('browser_click', { elementId: Number(button) }) - expect(click.ok, click.error).toBe(true) - const frameState = await app.evaluate(async ({ webContents }, url) => { + await tools.run('browser_click', { + elementId: refFor(result.snapshot.outline, 'Test quiz'), + }) + const frameState = await tools.app.evaluate(async ({ webContents }, url) => { const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) const frame = page?.mainFrame.frames.find((frame) => frame.url === 'about:srcdoc') if (!frame) throw new Error('Missing sandboxed preview') @@ -842,119 +948,97 @@ test.describe('browser tools', () => { expect(frameState).toEqual({ clicked: 'true', isolated: 'true', bridge: 'undefined' }) } } - const typed = await execute('browser_open_url', { url: `${origin}/private-chat` }) - expect(typed.ok, typed.error).toBe(true) - const result = typed.result as { snapshot: { outline: string } } - const message = result.snapshot.outline - .split('\n') - .find((line) => line.includes('"Message"') && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/)?.[1] - const send = result.snapshot.outline - .split('\n') - .find((line) => line.includes('"Send"') && /\[ref=\d+\]/.test(line)) - ?.match(/\[ref=(\d+)\]/)?.[1] - expect(message, result.snapshot.outline).toBeTruthy() - expect(send, result.snapshot.outline).toBeTruthy() - expect( - (await execute('browser_type', { elementId: Number(message), text: 'Session works' })).ok - ).toBe(true) - expect((await execute('browser_click', { elementId: Number(send) })).ok).toBe(true) - expect(JSON.stringify(await execute('browser_snapshot', {}))).toContain('Session works') + const outline = await tools.open(`${origin}/private-chat`) + await tools.run('browser_type', { + elementId: refFor(outline, 'Message'), + text: 'Session works', + }) + await tools.run('browser_click', { elementId: refFor(outline, 'Send') }) + await expect + .poll(() => + tools.pollPage(`${origin}/private-chat`, "document.getElementById('reply').textContent") + ) + .toBe('Session works') }) - test('keeps external navigation isolated and authenticates redirects back into Sim', async () => { - expect((await execute('browser_open_url', { url: `${origin}/private-chat` })).ok).toBe(true) - const external = origin.replace('127.0.0.1', 'localhost') - const result = await execute('browser_open_url', { url: `${origin}/redirect` }) - expect(result.ok, result.error).toBe(true) - expect(result.result).toMatchObject({ url: `${external}/landing` }) + test('keeps external navigation isolated and authenticates redirects back into Sim', async ({ + tools, + toolsSite, + }) => { + const { origin, site } = toolsSite + await tools.run('browser_open_url', { url: `${origin}/private-chat` }) + const result = await tools.run('browser_open_url', { url: `${origin}/redirect` }) + expect(result).toMatchObject({ url: `${site}/landing` }) expect( - await app.evaluate(({ webContents, BrowserWindow }, url) => { + await tools.app.evaluate(({ webContents, BrowserWindow }, url) => { const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) - return page?.session === BrowserWindow.getAllWindows()[0].webContents.session - }, `${external}/landing`) + if (!page) throw new Error(`No page at ${url}`) + return page.session === BrowserWindow.getAllWindows()[0].webContents.session + }, `${site}/landing`) ).toBe(false) - const back = await execute('browser_open_url', { url: `${external}/enter-sim` }) - expect(back.ok, back.error).toBe(true) - expect(back.result).toMatchObject({ url: `${origin}/private-chat` }) + const back = await tools.run('browser_open_url', { url: `${site}/enter-sim` }) + expect(back).toMatchObject({ url: `${origin}/private-chat` }) }) - test('sign-out clears authenticated browser pages with the desktop session', async () => { - const opened = await execute('browser_open_url', { url: `${origin}/private-chat` }) - expect(opened.ok, opened.error).toBe(true) - expect(opened.result).toMatchObject({ url: `${origin}/private-chat` }) - await window.evaluate(async () => { + test('sign-out clears authenticated browser pages with the desktop session', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const opened = await tools.run('browser_open_url', { url: `${origin}/private-chat` }) + expect(opened).toMatchObject({ url: `${origin}/private-chat` }) + await tools.shell.evaluate(async () => { await fetch('/api/auth/sign-out', { method: 'POST' }) }) await expect .poll(() => - app.evaluate( + tools.app.evaluate( ({ webContents }, url) => webContents.getAllWebContents().some((contents) => contents.getURL() === url), `${origin}/private-chat` ) ) .toBe(false) - await expect(window).toHaveURL(`${origin}/login`) + await expect(tools.shell).toHaveURL(`${origin}/login`) }) - async function formState() { - return app.evaluate(async ({ webContents }, origin) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${origin}/form`)) - if (!page) throw new Error('Missing browser fixture') - return page.executeJavaScript(`({ - name: document.getElementById('name').value, - plan: document.getElementById('plan').value, - updates: document.getElementById('updates').checked, - password: document.getElementById('password').value, - route: document.getElementById('route').value, - scrollLeft: document.getElementById('horizontal').scrollLeft - })`) - }, origin) - } - - test('sets and clears multiple selections without partial writes for invalid options', async () => { - const ref = await openForm() - const selected = await execute('browser_select_option', { + test('sets and clears multiple selections without partial writes for invalid options', async ({ + tools, + toolsSite, + }) => { + const ref = await openForm(tools, toolsSite.origin) + const selected = await tools.run('browser_select_option', { elementId: ref('Regions'), values: ['A', 'B'], }) - expect(selected.ok, selected.error).toBe(true) - expect(selected.result).toMatchObject({ + expect(selected).toMatchObject({ values: ['a', 'b'], effectObserved: true, readback: { values: ['a', 'b'] }, }) - const invalid = await execute('browser_select_option', { + const invalid = await tools.call('browser_select_option', { elementId: ref('Regions'), values: ['B', 'C'], }) expect(invalid.ok).toBe(false) - const values = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing form fixture') - return contents.executeJavaScript( + expect( + await tools.inPage( + `${toolsSite.origin}/form`, 'Array.from(document.getElementById("regions").selectedOptions, option => option.value)' ) - }, origin) - expect(values).toEqual(['a', 'b']) - const cleared = await execute('browser_select_option', { + ).toEqual(['a', 'b']) + const cleared = await tools.run('browser_select_option', { elementId: ref('Regions'), values: [], }) - expect(cleared.result).toMatchObject({ - values: [], - effectObserved: true, - readback: { values: [] }, - }) + expect(cleared).toMatchObject({ values: [], effectObserved: true, readback: { values: [] } }) }) - test('fills structured native fields and leaves invalid dates unchanged', async () => { - const ref = await openForm() + test('fills structured native fields and leaves invalid dates unchanged', async ({ + tools, + toolsSite, + }) => { + const ref = await openForm(tools, toolsSite.origin) for (const [name, text] of [ ['Date', '2026-09-15'], ['Time', '15:48'], @@ -964,27 +1048,18 @@ test.describe('browser tools', () => { ['Color', '#AABBCC'], ['Range', '75'], ]) { - const response = await execute('browser_type', { elementId: ref(name), text }) - expect(response.ok, response.error).toBe(true) - expect(response.result).toMatchObject({ - trusted: false, - dispatched: true, - effectObserved: true, - }) + const typed = await tools.run('browser_type', { elementId: ref(name), text }) + expect(typed).toMatchObject({ trusted: false, dispatched: true, effectObserved: true }) } - const invalid = await execute('browser_type', { elementId: ref('Date'), text: '2026-02-30' }) + const invalid = await tools.call('browser_type', { elementId: ref('Date'), text: '2026-02-30' }) expect(invalid.ok).toBe(false) expect(invalid.error).toContain('Invalid value') - const state = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing form fixture') - return contents.executeJavaScript( + expect( + await tools.inPage( + `${toolsSite.origin}/form`, '({date:document.getElementById("date").value,time:document.getElementById("time").value,appointment:document.getElementById("appointment").value,month:document.getElementById("month").value,week:document.getElementById("week").value,color:document.getElementById("color").value,range:document.getElementById("range").value,events:document.getElementById("date").dataset.events})' ) - }, origin) - expect(state).toEqual({ + ).toEqual({ date: '2026-09-15', time: '15:48', appointment: '2026-09-15T15:48', @@ -997,55 +1072,47 @@ test.describe('browser tools', () => { }) for (const mode of ['menu', 'sticky']) { - test(`clicks a ${mode} target without losing its identity`, async () => { - const opened = await execute('browser_open_url', { url: `${origin}/click?mode=${mode}` }) - expect(opened.ok, opened.error).toBe(true) - await app.evaluate( - async ({ webContents }, { origin, mode }) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL().startsWith(`${origin}/click`)) - if (!contents) throw new Error('Missing click fixture') - await contents.executeJavaScript(` - history.scrollRestoration = 'manual'; - document.getElementById('target').style.top = ${mode === 'sticky' ? '1010' : 'innerHeight - 100'} + 'px'; - scrollTo(0, ${mode === 'sticky' ? '1000' : '0'}); - new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => { - document.body.dataset.scrolls = '0'; document.body.dataset.armed = 'true'; resolve(); - }))) - `) - }, - { origin, mode } + test(`clicks a ${mode} target without losing its identity`, async ({ tools, toolsSite }) => { + const url = `${toolsSite.origin}/click?mode=${mode}` + await tools.run('browser_open_url', { url }) + await tools.inPage( + url, + `history.scrollRestoration = 'manual'; + document.getElementById('target').style.top = ${mode === 'sticky' ? '1010' : 'innerHeight - 100'} + 'px'; + scrollTo(0, ${mode === 'sticky' ? '1000' : '0'}); + new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => { + document.body.dataset.scrolls = '0'; document.body.dataset.armed = 'true'; resolve(); + })))` + ) + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + await tools.run('browser_click', { elementId: refFor(outline, 'Choose option') }) + const state = await tools.inPage<{ clicks: string; scrolls: string; scrollY: number }>( + url, + '({clicks:document.body.dataset.clicks,scrolls:document.body.dataset.scrolls,scrollY})' ) - const snapshot = await execute('browser_snapshot', {}) - expect(snapshot.ok, snapshot.error).toBe(true) - const outline = (snapshot.result as { outline: string }).outline - const line = outline.split('\n').find((line) => line.includes('"Choose option"')) - const match = line?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error(`Missing target: ${outline}`) - const result = await execute('browser_click', { elementId: Number(match[1]) }) - expect(result.ok, result.error).toBe(true) - const state = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL().startsWith(`${origin}/click`)) - if (!contents) throw new Error('Missing click fixture') - return contents.executeJavaScript( - '({clicks:document.body.dataset.clicks,scrolls:document.body.dataset.scrolls,scrollY})' - ) - }, origin) expect(state.clicks).toBe('1') if (mode === 'menu') expect(state).toMatchObject({ scrolls: '0', scrollY: 0 }) else expect(state.scrollY).toBeLessThan(1000) }) } - test('recovers a permanently pending native capture without losing the page', async () => { - await openForm() - const before = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) + test('captures fresh pixels after a resize and recovers a permanently pending native capture without losing the page', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + await openForm(tools, origin) + const viewportWidth = () => tools.inPage(`${origin}/form`, 'innerWidth') + const beforeWidth = await viewportWidth() + await tools.app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0].setSize(1280, 900) + ) + await expect.poll(viewportWidth).not.toBe(beforeWidth) + await expectCapturedColor(tools, origin, 'rgb(240, 20, 30)', 0) + await expectCapturedColor(tools, origin, 'rgb(30, 40, 230)', 2) + + const before = await tools.app.evaluate(async ({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) if (!contents) throw new Error('Missing capture fixture') await contents.executeJavaScript(` document.getElementById('name').value = 'Unsaved work'; @@ -1053,37 +1120,15 @@ test.describe('browser tools', () => { `) contents.capturePage = () => new Promise(() => {}) return { id: contents.id, url: contents.getURL() } - }, origin) + }, `${origin}/form`) for (const [color, dominantChannel] of [ ['rgb(240, 20, 30)', 0], ['rgb(30, 40, 230)', 2], ['rgb(20, 220, 50)', 1], ] as const) { - await app.evaluate( - async ({ webContents }, { id, color }) => { - const contents = webContents.fromId(id) - if (!contents) throw new Error('Capture fixture was replaced') - await contents.executeJavaScript(` - document.body.style.background = ${JSON.stringify(color)}; - new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))) - `) - }, - { id: before.id, color } - ) - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { dataUrl: string } - const pixel = await app.evaluate(({ nativeImage }, dataUrl) => { - const bitmap = nativeImage.createFromDataURL(dataUrl).toBitmap() - return [bitmap[2], bitmap[1], bitmap[0]] - }, shot.dataUrl) - expect(pixel[dominantChannel]).toBeGreaterThan(180) - for (let channel = 0; channel < 3; channel++) { - if (channel !== dominantChannel) - expect(pixel[dominantChannel] - pixel[channel]).toBeGreaterThan(80) - } + await expectCapturedColor(tools, origin, color, dominantChannel) } - const after = await app.evaluate(async ({ webContents }, id) => { + const after = await tools.app.evaluate(async ({ webContents }, id) => { const contents = webContents.fromId(id) if (!contents) throw new Error('Capture fixture was replaced') return { @@ -1097,39 +1142,32 @@ test.describe('browser tools', () => { expect(after).toEqual({ ...before, page: { value: 'Unsaved work', focus: 'name' } }) }) - test('maps a fractional narrow crop back to its actual viewport position', async () => { - await openForm() - const target = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing crop fixture') - return contents.executeJavaScript(` - const button = document.createElement('button'); - button.textContent = 'Narrow target'; - button.style.cssText = 'position:absolute;left:20.1px;top:60.1px;width:1.1px;height:100px;padding:0;border:0;overflow:hidden'; - button.onclick = () => { document.body.dataset.cropClicks = Number(document.body.dataset.cropClicks || 0) + 1 }; - document.body.append(button); - const rect = button.getBoundingClientRect(); - ({x:rect.x,y:rect.y,width:rect.width,height:rect.height,devicePixelRatio}); - `) as Promise<{ - x: number - y: number - width: number - height: number - devicePixelRatio: number - }> - }, origin) - const snapshot = await execute('browser_snapshot', {}) - expect(snapshot.ok, snapshot.error).toBe(true) - const line = (snapshot.result as { outline: string }).outline - .split('\n') - .find((line) => line.includes('"Narrow target"')) - const match = line?.match(/\[ref=(\d+)\]/) - if (!match) throw new Error('Missing narrow target reference') - const response = await execute('browser_screenshot', { elementId: Number(match[1]) }) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { + test('maps a fractional narrow crop back to its actual viewport position', async ({ + tools, + toolsSite, + }) => { + const formUrl = `${toolsSite.origin}/form` + await openForm(tools, toolsSite.origin) + const target = await tools.inPage<{ + x: number + y: number + width: number + height: number + devicePixelRatio: number + }>( + formUrl, + `const button = document.createElement('button'); + button.textContent = 'Narrow target'; + button.style.cssText = 'position:absolute;left:20.1px;top:60.1px;width:1.1px;height:100px;padding:0;border:0;overflow:hidden'; + button.onclick = () => { document.body.dataset.cropClicks = Number(document.body.dataset.cropClicks || 0) + 1 }; + document.body.append(button); + const rect = button.getBoundingClientRect(); + ({x:rect.x,y:rect.y,width:rect.width,height:rect.height,devicePixelRatio});` + ) + const { outline } = (await tools.run('browser_snapshot')) as { outline: string } + const shot = (await tools.run('browser_screenshot', { + elementId: refFor(outline, 'Narrow target'), + })) as { imageSize: { width: number; height: number } clip: { x: number; y: number; width: number; height: number } scale: number @@ -1141,305 +1179,191 @@ test.describe('browser tools', () => { expect(target.x - shot.clip.x).toBeLessThan(1 / target.devicePixelRatio) expect(target.y - shot.clip.y).toBeLessThan(1 / target.devicePixelRatio) expect(shot.scale).toBeCloseTo(shot.imageSize.width / shot.clip.width) - const clicked = await execute('browser_click_at', { + await tools.run('browser_click_at', { x: shot.clip.x + shot.clip.width / 2, y: shot.clip.y + shot.clip.height / 2, }) - expect(clicked.ok, clicked.error).toBe(true) - const count = await app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - return contents?.executeJavaScript('document.body.dataset.cropClicks') - }, origin) - expect(count).toBe('1') + expect(await tools.inPage(formUrl, 'document.body.dataset.cropClicks')).toBe('1') }) - for (const mode of ['hidden', 'minimized']) { - test(`recovers a stalled capture after restoring a ${mode} window`, async () => { - test.skip(mode === 'minimized' && process.platform !== 'darwin', 'Requires minimize events') - await openForm() - await app.evaluate( - async ({ BrowserWindow, webContents }, { origin, mode }) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing capture fixture') - contents.capturePage = () => new Promise(() => {}) - await contents.executeJavaScript("document.getElementById('name').value = 'Unsaved work'") - const win = BrowserWindow.getAllWindows()[0] - win.blur() - if (mode === 'hidden') win.hide() - else { - const minimized = new Promise((resolve) => win.once('minimize', resolve)) - win.minimize() - await minimized - } - }, - { origin, mode } - ) - const state = () => - app.evaluate(async ({ BrowserWindow, webContents }, origin) => { - const win = BrowserWindow.getAllWindows()[0] - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing capture fixture') - return { - id: contents.id, - visible: win.isVisible(), - minimized: win.isMinimized(), - focused: BrowserWindow.getFocusedWindow()?.id ?? null, - bounds: win.getBounds(), - value: await contents.executeJavaScript("document.getElementById('name').value"), - } - }, origin) - const before = await state() - const start = Date.now() - const hiddenCapture = await execute('browser_screenshot', {}) - expect(Date.now() - start).toBeLessThan(12_000) - if (!hiddenCapture.ok) - expect(hiddenCapture.error).toContain('Screenshot frame capture timed out') - expect(await state()).toEqual(before) - await app.evaluate(({ BrowserWindow }, mode) => { - const win = BrowserWindow.getAllWindows()[0] - if (mode === 'minimized') win.restore() - else win.showInactive() - }, mode) - for (let attempt = 0; attempt < 2; attempt++) { - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - } - expect(await state()).toMatchObject({ id: before.id, value: 'Unsaved work' }) - }) - } - - for (const mode of ['visible', 'hidden', 'minimized']) { - test(`captures a ${mode} window without changing its state`, async () => { - test.skip( - mode === 'minimized' && process.platform !== 'darwin', - 'Requires a window manager with minimize events' - ) - await openForm() - await app.evaluate(async ({ BrowserWindow }, mode) => { + for (const mode of ['hidden', 'minimized'] as const) { + test(`captures a ${mode} window without changing its state, and recovers a stalled capture after restoring it`, async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + await openForm(tools, origin) + await tools.inPage(`${origin}/form`, "document.getElementById('name').value = 'Unsaved work'") + await blurWindow(tools) + await tools.app.evaluate(async ({ BrowserWindow }, mode) => { const win = BrowserWindow.getAllWindows()[0] - win.blur() if (mode === 'hidden') win.hide() - if (mode === 'minimized') { - const minimized = new Promise((resolve) => win.once('minimize', () => resolve())) + else { + const minimized = new Promise((resolve) => win.once('minimize', resolve)) win.minimize() await minimized } }, mode) - const state = () => - app.evaluate(async ({ BrowserWindow, webContents }, origin) => { - const win = BrowserWindow.getAllWindows()[0] - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing screenshot fixture') - return { - visible: win.isVisible(), - minimized: win.isMinimized(), - bounds: win.getBounds(), - focused: BrowserWindow.getFocusedWindow()?.id ?? null, - page: await contents.executeJavaScript( - '({width:innerWidth,height:innerHeight,scrollX,scrollY,html:document.body.innerHTML,focus:document.activeElement?.id})' - ), - } - }, origin) - const before = await state() - for (let i = 0; i < 3; i++) { - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { - dataUrl: string - scale: number - viewport: { width: number; height: number } - } - expect(shot.dataUrl.length).toBeGreaterThan(1000) - expect(shot.viewport.width).toBeGreaterThan(0) - expect(shot.viewport.height).toBeGreaterThan(0) - const image = await app.evaluate(({ nativeImage }, dataUrl) => { - const image = nativeImage.createFromDataURL(dataUrl) - return { empty: image.isEmpty(), ...image.getSize() } - }, shot.dataUrl) - expect(image).toEqual({ - empty: false, - width: Math.round(shot.viewport.width * shot.scale), - height: Math.round(shot.viewport.height * shot.scale), - }) - expect(await state()).toEqual(before) - } + + const before = await expectCapturesLeaveStateUnchanged(tools, origin) + + await tools.app.evaluate(({ webContents }, url) => { + const contents = webContents.getAllWebContents().find((page) => page.getURL() === url) + if (!contents) throw new Error('Missing capture fixture') + contents.capturePage = () => new Promise(() => {}) + }, `${origin}/form`) + const start = Date.now() + const stalled = await tools.call('browser_screenshot') + expect(Date.now() - start).toBeLessThan(12_000) + if (!stalled.ok) expect(stalled.error).toContain('Screenshot frame capture timed out') + expect(await windowState(tools, origin)).toEqual(before) + + await tools.app.evaluate(({ BrowserWindow }, mode) => { + const win = BrowserWindow.getAllWindows()[0] + if (mode === 'minimized') win.restore() + else win.showInactive() + }, mode) + await expect + .poll(() => + tools.app.evaluate(({ BrowserWindow }) => { + const win = BrowserWindow.getAllWindows()[0] + return !win.isMinimized() && win.isVisible() + }) + ) + .toBe(true) + for (let attempt = 0; attempt < 2; attempt++) await tools.run('browser_screenshot') + expect(await windowState(tools, origin)).toMatchObject({ + id: before.id, + page: { value: 'Unsaved work' }, + }) }) } - test('captures fresh pixels after resizing and repainting the viewport', async () => { - await openForm() - const viewportWidth = () => - app.evaluate(async ({ webContents }, origin) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - return contents?.executeJavaScript('innerWidth') - }, origin) - const beforeWidth = await viewportWidth() - await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setSize(1280, 900)) - await expect.poll(viewportWidth).not.toBe(beforeWidth) - for (const color of ['red', 'blue']) { - await app.evaluate( - async ({ webContents }, { origin, color }) => { - const contents = webContents - .getAllWebContents() - .find((wc) => wc.getURL() === `${origin}/form`) - if (!contents) throw new Error('Missing screenshot fixture') - await contents.executeJavaScript( - `document.body.style.background = ${JSON.stringify(color)}; - new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))` - ) - }, - { origin, color } - ) - const response = await execute('browser_screenshot', {}) - expect(response.ok, response.error).toBe(true) - const shot = response.result as { dataUrl: string } - const pixel = await app.evaluate(({ nativeImage }, dataUrl) => { - const image = nativeImage.createFromDataURL(dataUrl) - return Array.from(image.toBitmap().subarray(0, 4)) - }, shot.dataUrl) - const dominant = pixel[color === 'red' ? 2 : 0] - const other = pixel[color === 'red' ? 0 : 2] - expect(dominant - other, `${color}: ${pixel}`).toBeGreaterThan(150) - } + test('captures a visible window without changing its state', async ({ tools, toolsSite }) => { + await openForm(tools, toolsSite.origin) + await blurWindow(tools) + await expectCapturesLeaveStateUnchanged(tools, toolsSite.origin) }) - test('opens with references, fills in order, and scrolls a horizontal pane', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('opens with references, fills in order, and scrolls a horizontal pane', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = await tools.run('browser_fill_form', { fields: [ { elementId: ref('Name'), kind: 'text', text: 'Example User' }, { elementId: ref('Plan'), kind: 'select', value: 'pro' }, { elementId: ref('Updates'), kind: 'checked', checked: true }, ], }) - expect(fill.ok, fill.error).toBe(true) - expect(fill.result, JSON.stringify(fill.result)).toMatchObject({ - completed: true, - completedCount: 3, + expect(fill, JSON.stringify(fill)).toMatchObject({ completed: true, completedCount: 3 }) + expect(await formState(tools, origin)).toMatchObject({ + name: 'Example User', + plan: 'pro', + updates: true, }) - expect(await formState()).toMatchObject({ name: 'Example User', plan: 'pro', updates: true }) - const cleared = await execute('browser_fill_form', { + const cleared = await tools.run('browser_fill_form', { fields: [{ elementId: ref('Name'), kind: 'text', text: '' }], }) - expect(cleared.result, JSON.stringify(cleared.result)).toMatchObject({ completed: true }) - expect(await formState()).toMatchObject({ name: '' }) + expect(cleared, JSON.stringify(cleared)).toMatchObject({ completed: true }) + expect(await formState(tools, origin)).toMatchObject({ name: '' }) - const scroll = await execute('browser_scroll', { + const scroll = await tools.run('browser_scroll', { direction: 'right', amount: 240, elementId: ref('Wide table'), }) - expect(scroll.ok, scroll.error).toBe(true) - expect(scroll.result).toMatchObject({ movedBy: 240 }) - expect(Math.round((await formState()).scrollLeft)).toBe(240) - await execute('browser_scroll', { + expect(scroll).toMatchObject({ movedBy: 240 }) + expect(Math.round((await formState(tools, origin)).scrollLeft)).toBe(240) + await tools.run('browser_scroll', { direction: 'left', amount: 240, elementId: ref('Wide table'), }) - expect(await formState()).toMatchObject({ scrollLeft: 0 }) + expect(await formState(tools, origin)).toMatchObject({ scrollLeft: 0 }) }) - test('batches an action with a fresh observation without replaying form fields', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('batches an action with a fresh observation without replaying form fields', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = (await tools.run('browser_fill_form', { fields: [{ elementId: ref('Name'), kind: 'text', text: 'Observed value' }], observe: { query: 'Name' }, - }) - expect(fill.ok, fill.error).toBe(true) - expect(fill.result).toMatchObject({ + })) as { observation: { result: { matches: { elementId: number }[] } } } + expect(fill).toMatchObject({ completed: true, completedCount: 1, observation: { ok: true, result: { totalMatches: 1 } }, }) - expect(await formState()).toMatchObject({ name: 'Observed value' }) - const result = fill.result as { observation: { result: { matches: { elementId: number }[] } } } - const freshId = result.observation.result.matches[0].elementId + expect(await formState(tools, origin)).toMatchObject({ name: 'Observed value' }) + const freshId = fill.observation.result.matches[0].elementId expect(freshId).toBe(ref('Name')) - const clear = await execute('browser_type', { elementId: freshId, text: '', observe: {} }) - expect(clear.ok, clear.error).toBe(true) - expect(clear.result).toMatchObject({ observation: { ok: true } }) - expect(await formState()).toMatchObject({ name: '' }) + const clear = await tools.run('browser_type', { elementId: freshId, text: '', observe: {} }) + expect(clear).toMatchObject({ observation: { ok: true } }) + expect(await formState(tools, origin)).toMatchObject({ name: '' }) }) - test('stops after a route change without writing the next field', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('stops after a route change without writing the next field', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = await tools.call('browser_fill_form', { fields: [ { elementId: ref('Route'), kind: 'text', text: 'change route' }, { elementId: ref('Name'), kind: 'text', text: 'Must not be written' }, ], }) - expect(fill.result, JSON.stringify(fill.result)).toMatchObject({ - completed: false, - doNotRetry: true, - }) - expect(await formState()).toMatchObject({ name: '', route: 'change route' }) + expect(fill.result, JSON.stringify(fill)).toMatchObject({ completed: false, doNotRetry: true }) + expect(await formState(tools, origin)).toMatchObject({ name: '', route: 'change route' }) }) - test('follows a link and cross-origin redirect without a website approval prompt', async () => { - await openForm() - await app.evaluate(async ({ webContents }, url) => { - const page = webContents.getAllWebContents().find((contents) => contents.getURL() === url) - if (!page) throw new Error('Missing browser fixture') - await page.executeJavaScript("document.querySelector('a').click()") - }, `${origin}/form`) - - const destination = `${origin.replace('127.0.0.1', 'localhost')}/landing` - await expect - .poll(() => - app.evaluate( - ({ webContents }, url) => - webContents.getAllWebContents().some((contents) => contents.getURL() === url), - destination - ) - ) - .toBe(true) - expect(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().length)).toBe(1) - await expect(window.getByRole('heading')).toHaveText('Browser tools fixture') + test('follows a link and cross-origin redirect without a website approval prompt', async ({ + tools, + toolsSite, + }) => { + const { origin, site } = toolsSite + await openForm(tools, origin) + await tools.inPage(`${origin}/form`, "document.querySelector('a').click()") + await expect.poll(() => tools.pollPage(`${site}/landing`, 'true')).toBe(true) + expect( + await tools.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().length) + ).toBe(1) + await expect(tools.shell.getByRole('heading')).toHaveText('Browser tools fixture') }) - test('stops when a new popup exceeds the page summary limit', async () => { - const ref = await openForm() - await app.evaluate(async ({ webContents }, origin) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${origin}/form`)) - if (!page) throw new Error('Missing browser fixture') - await page.executeJavaScript(` - for (let index = 0; index < 10; index++) { - const toolbar = document.createElement('div') - toolbar.setAttribute('role', 'toolbar') - toolbar.textContent = 'Toolbar ' + index - document.body.append(toolbar) - } - document.getElementById('name').addEventListener('input', () => { - const popup = document.createElement('div') - popup.setAttribute('role', 'listbox') - popup.textContent = 'Suggestions' - document.body.append(popup) - }, { once: true }) - `) - }, origin) + test('stops when a new popup exceeds the page summary limit', async ({ tools, toolsSite }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + await tools.inPage( + `${origin}/form`, + `for (let index = 0; index < 10; index++) { + const toolbar = document.createElement('div') + toolbar.setAttribute('role', 'toolbar') + toolbar.textContent = 'Toolbar ' + index + document.body.append(toolbar) + } + document.getElementById('name').addEventListener('input', () => { + const popup = document.createElement('div') + popup.setAttribute('role', 'listbox') + popup.textContent = 'Suggestions' + document.body.append(popup) + }, { once: true })` + ) - const fill = await execute('browser_fill_form', { + const fill = await tools.run('browser_fill_form', { fields: [ { elementId: ref('Name'), kind: 'text', text: 'Example User' }, { elementId: ref('Plan'), kind: 'select', value: 'pro' }, ], }) - expect(fill.ok, fill.error).toBe(true) - expect(fill.result, JSON.stringify(fill.result)).toMatchObject({ + expect(fill, JSON.stringify(fill)).toMatchObject({ completed: false, completedCount: 1, stoppedIndex: 0, @@ -1447,51 +1371,22 @@ test.describe('browser tools', () => { doNotRetry: true, error: expect.stringContaining('could not be fully verified'), }) - expect(await formState()).toMatchObject({ name: 'Example User', plan: 'basic' }) + expect(await formState(tools, origin)).toMatchObject({ name: 'Example User', plan: 'basic' }) }) - test('refuses credential fields and leaves subsequent fields untouched', async () => { - const ref = await openForm() - const fill = await execute('browser_fill_form', { + test('refuses credential fields and leaves subsequent fields untouched', async ({ + tools, + toolsSite, + }) => { + const { origin } = toolsSite + const ref = await openForm(tools, origin) + const fill = await tools.call('browser_fill_form', { fields: [ { elementId: ref('Password'), kind: 'text', text: 'must-not-be-entered' }, { elementId: ref('Name'), kind: 'text', text: 'Must not be written' }, ], }) expect(fill.result).toMatchObject({ completed: false, completedCount: 0 }) - expect(await formState()).toMatchObject({ name: '', password: '' }) - }) - test('local terminal executes through its native PTY and refuses repeated authorization', async () => { - await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.terminal.activateScope(scope) - await api.terminal.openTerminal(undefined, scope) - }, SCOPE) - calls.set('local-cwd', { - chatId: SCOPE, - toolName: 'terminal', - args: { operation: 'cwd', args: {} }, - }) - const cwd = await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.terminal.executeTool('local-cwd', 'cwd', {}, scope) - }, SCOPE) - expect(cwd.ok).toBe(true) - calls.set('local-run', { - chatId: SCOPE, - toolName: 'terminal', - args: { operation: 'run', args: { command: "printf 'SIM_NATIVE_TERMINAL_VERIFIED\\n'" } }, - }) - const result = await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.terminal.executeTool('local-run', 'run', {}, scope) - }, SCOPE) - expect(result.ok).toBe(true) - expect(JSON.stringify(result)).toContain('SIM_NATIVE_TERMINAL_VERIFIED') - const replay = await window.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.terminal.executeTool('local-run', 'run', {}, scope) - }, SCOPE) - expect(replay.ok).toBe(false) + expect(await formState(tools, origin)).toMatchObject({ name: '', password: '' }) }) }) diff --git a/apps/desktop/e2e/chat-panel.spec.ts b/apps/desktop/e2e/chat-panel.spec.ts index 9731e6011d2..090c31f66a9 100644 --- a/apps/desktop/e2e/chat-panel.spec.ts +++ b/apps/desktop/e2e/chat-panel.spec.ts @@ -1,146 +1,64 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { bundleSimFixture, type DesktopBridge, expect, test } from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath(new URL('../../sim/scripts/fixtures/chat-panel.tsx', import.meta.url)) -test('chat panel sizes survive navigation, chat switches, collapse, and layout constraints', async () => { - const reportPath = process.env.CHAT_PANEL_REPORT_PATH ?? test.info().outputPath('chat-panel.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const userData = mkdtempSync(join(tmpdir(), 'sim-chat-panel-e2e-')) - let app: Awaited> | undefined - const errors: string[] = [] - let desktopExit: { code: number | null; signal: string | null } | null = null - let rendererCrashed = false - let passed = false - let javascript = '' - let stylesheet = '' - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/page') { - response.setHeader('Content-Type', 'text/html') - response.end('Native browser resize fixture') - } else if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end(path.endsWith('.js') ? javascript : stylesheet) - } else if (path.startsWith('/api/')) { - response.setHeader('Content-Type', 'application/json') - response.end( - path === '/api/auth/get-session' - ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - : '{}' - ) - } else { - response.setHeader('Content-Type', 'text/html') - response.setHeader( - 'Set-Cookie', - 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/' - ) - response.end( - '
' - ) - } +test('chat panel sizes survive navigation, chat switches, collapse, and layout constraints', async ({ + desktop, +}) => { + const { js, css } = await bundleSimFixture({ file: FIXTURE }) + const fixture = await serveSignedIn({ + page: '
', + handle: (_request, response, url) => { + if (url.pathname === '/page') { + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Native browser resize fixture') + return true + } + if (url.pathname === '/fixture.js' || url.pathname === '/fixture.css') { + const script = url.pathname.endsWith('.js') + response.writeHead(200, { 'Content-Type': script ? 'text/javascript' : 'text/css' }) + response.end(script ? js : css) + return true + } + return false + }, }) - try { - await check('load the production resource panel resize hook in Electron', async () => { - const config = await loadPostcssConfig({}, SIM_DIR) - const cssPath = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(cssPath, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: cssPath } - ) - const bundle = await build({ - entryPoints: [FIXTURE], - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - javascript = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text ?? '' - stylesheet = `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - await new Promise((resolve) => server.listen(0, resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: userData, - }, - }) + const { app } = await desktop.launch({ + origin: fixture.origin, }) - if (!app) throw new Error('Electron did not launch') - app.process().once('exit', (code, signal) => { - desktopExit = { code, signal } - }) - const shell = app - const page = await shell.firstWindow() - const inputSession = await page.context().newCDPSession(page) + const page = await app.firstWindow() + const errors: string[] = [] page.on('pageerror', (error) => errors.push(error.message)) - page.on('crash', () => { - rendererCrashed = true - }) - await shell.evaluate(({ app, BrowserWindow }) => { + const inputSession = await page.context().newCDPSession(page) + const focusShell = async () => { + await app.evaluate(({ app, BrowserWindow }) => { + app.focus({ steal: true }) + BrowserWindow.getAllWindows()[0].focus() + }) + await expect + .poll(() => + app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) + ) + .toBe(true) + } + await app.evaluate(({ BrowserWindow }) => { const window = BrowserWindow.getAllWindows()[0] // Keep the physical window inside the small displays used by macOS CI. window.setMinimumSize(0, 0) window.setContentSize(720, 400) window.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - window.focus() }) await page.reload() - await shell.evaluate(({ app, BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - window.webContents.setZoomFactor(0.5) - app.focus({ steal: true }) - window.focus() - }) + await app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows()[0].webContents.setZoomFactor(0.5) + ) expect(errors).toEqual([]) - await expect - .poll(() => - shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) - ) - .toBe(true) + await focusShell() await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(1440) + const storage = () => page.evaluate(() => JSON.stringify(localStorage)) const panel = page.locator('[data-mothership-panel]') const divider = page.getByRole('separator', { name: 'Resize resource view' }) const width = () => panel.evaluate((element) => element.getBoundingClientRect().width) @@ -148,15 +66,7 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expect.poll(width).toBeCloseTo(expected, 0) } const beginDrag = async () => { - await shell.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - await expect - .poll(() => - shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) - ) - .toBe(true) + await focusShell() await divider.hover({ position: { x: 4, y: 100 } }) const rect = await panel.boundingBox() if (!rect) throw new Error('Missing panel bounds') @@ -173,7 +83,7 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expectWidth(target) } - await check('a chosen width survives a settings round trip and reload', async () => { + await test.step('a chosen width survives a settings round trip and reload', async () => { await expectWidth(720) await dragTo(620) await page.getByRole('button', { name: 'Settings', exact: true }).click() @@ -184,67 +94,61 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expectWidth(620) }) - await check( - 'workspace and organization chats restore independent widths without remounting', - async () => { - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - await expectWidth(720) - await dragTo(830) - await page.getByRole('button', { name: 'organization-chat-a', exact: true }).click() - await expectWidth(720) - await dragTo(560) - await page.getByRole('button', { name: 'Settings', exact: true }).click() - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expectWidth(560) - await page.getByRole('button', { name: 'workspace-chat-a', exact: true }).click() - await expectWidth(620) - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - await expectWidth(830) - } - ) + await test.step('workspace and organization chats restore independent widths without remounting', async () => { + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + await expectWidth(720) + await dragTo(830) + await page.getByRole('button', { name: 'organization-chat-a', exact: true }).click() + await expectWidth(720) + await dragTo(560) + await page.getByRole('button', { name: 'Settings', exact: true }).click() + await page.getByRole('button', { name: 'Back', exact: true }).click() + await expectWidth(560) + await page.getByRole('button', { name: 'workspace-chat-a', exact: true }).click() + await expectWidth(620) + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + await expectWidth(830) + }) - await check( - 'collapse preserves the expanded preference, including keyboard changes', - async () => { - await page.getByRole('button', { name: 'Collapse resource view' }).click() - await expectWidth(0) - await page.getByRole('button', { name: 'Expand resource view' }).click() - await expectWidth(830) - await divider.focus() - await page.keyboard.press('ArrowRight') - await expectWidth(798) - await page.getByRole('button', { name: 'Settings', exact: true }).click() - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expectWidth(798) - } - ) + await test.step('collapse preserves the expanded preference, including keyboard changes', async () => { + await page.getByRole('button', { name: 'Collapse resource view' }).click() + await expectWidth(0) + await page.getByRole('button', { name: 'Expand resource view' }).click() + await expectWidth(830) + await divider.focus() + await page.keyboard.press('ArrowRight') + await expectWidth(798) + await page.getByRole('button', { name: 'Settings', exact: true }).click() + await page.getByRole('button', { name: 'Back', exact: true }).click() + await expectWidth(798) + }) - await check('container and window clamps do not overwrite the preferred width', async () => { + await test.step('container and window clamps do not overwrite the preferred width', async () => { await page.getByRole('button', { name: 'Resize container' }).click() await expectWidth(520) await page.getByRole('button', { name: 'Resize container' }).click() await expectWidth(798) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(525, 400) ) await expectWidth(570) await page.getByRole('button', { name: 'Settings', exact: true }).click() await page.getByRole('button', { name: 'Back', exact: true }).click() await expectWidth(570) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(720, 400) ) await expectWidth(798) }) - await check('resizing writes storage only when the gesture ends', async () => { - const before = await page.evaluate(() => JSON.stringify(localStorage)) + await test.step('resizing writes storage only when the gesture ends', async () => { + const before = await storage() const rect = await beginDrag() await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) await expectWidth(698) - expect(await page.evaluate(() => JSON.stringify(localStorage))).toBe(before) + expect(await storage()).toBe(before) await page.mouse.up() - expect(await page.evaluate(() => JSON.stringify(localStorage))).not.toBe(before) + await expect.poll(storage).not.toBe(before) }) for (const interruption of [ @@ -255,69 +159,66 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c 'chat switch', ] as const) { const keepsDraggedWidth = interruption === 'capture loss' || interruption === 'blur' - await check( - `${interruption} keeps the ${keepsDraggedWidth ? 'dragged' : 'previous saved'} width`, - async () => { - const before = await page.evaluate(() => JSON.stringify(localStorage)) - const rect = await beginDrag() - await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) + await test.step(`${interruption} keeps the ${keepsDraggedWidth ? 'dragged' : 'previous saved'} width`, async () => { + const before = await storage() + const rect = await beginDrag() + await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) + await expectWidth(598) + if (interruption === 'pointercancel') { + await divider.dispatchEvent('pointercancel', { pointerId: 1 }) + } else if (interruption === 'capture loss') { + await divider.evaluate((element) => element.releasePointerCapture(1)) + await page.mouse.move(rect.x + 100, rect.y + 100) + } else if (interruption === 'blur') { + // Reloads restore Playwright's focus emulation; native blur must reach the document. + await inputSession.send('Emulation.setFocusEmulationEnabled', { enabled: false }) + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].blur()) + await expect.poll(() => page.evaluate(() => document.hasFocus())).toBe(false) + } else if (interruption === 'chat switch') { + await page + .getByRole('button', { name: 'organization-chat-a', exact: true }) + .evaluate((element: HTMLButtonElement) => element.click()) + await expectWidth(560) + } else { + await page + .getByRole('button', { name: 'Settings', exact: true }) + .evaluate((element: HTMLButtonElement) => element.click()) + await expect(panel).toHaveCount(0) + } + if (keepsDraggedWidth) { await expectWidth(598) - if (interruption === 'pointercancel') { - await divider.dispatchEvent('pointercancel', { pointerId: 1 }) - } else if (interruption === 'capture loss') { - await divider.evaluate((element) => element.releasePointerCapture(1)) - await page.mouse.move(rect.x + 100, rect.y + 100) - } else if (interruption === 'blur') { - // Reloads restore Playwright's focus emulation; native blur must reach the document. - await inputSession.send('Emulation.setFocusEmulationEnabled', { enabled: false }) - await shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].blur()) - await expect.poll(() => page.evaluate(() => document.hasFocus())).toBe(false) - } else if (interruption === 'chat switch') { - await page - .getByRole('button', { name: 'organization-chat-a', exact: true }) - .evaluate((element: HTMLButtonElement) => element.click()) - await expectWidth(560) - } else { - await page - .getByRole('button', { name: 'Settings', exact: true }) - .evaluate((element: HTMLButtonElement) => element.click()) - await expect(panel).toHaveCount(0) - } - if (keepsDraggedWidth) { - await expectWidth(598) - expect(await page.evaluate(() => JSON.stringify(localStorage))).not.toBe(before) - if (interruption === 'blur') { - await shell.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - } - await page.mouse.move(rect.x + 150, rect.y + 100) - await expectWidth(598) - } - await page.mouse.up() - if (interruption === 'chat switch') { - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - } - if (interruption === 'detach') { - await page.getByRole('button', { name: 'Back', exact: true }).click() - } - await expectWidth(keepsDraggedWidth ? 598 : 698) - if (keepsDraggedWidth) { - await page.reload() - await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() - await expectWidth(598) - await dragTo(698) - } else { - expect(await page.evaluate(() => JSON.stringify(localStorage))).toBe(before) + await expect.poll(storage).not.toBe(before) + if (interruption === 'blur') { + await app.evaluate(({ app, BrowserWindow }) => { + app.focus({ steal: true }) + BrowserWindow.getAllWindows()[0].focus() + }) } + await page.mouse.move(rect.x + 150, rect.y + 100) + await expectWidth(598) } - ) + await page.mouse.up() + if (interruption === 'chat switch') { + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + } + if (interruption === 'detach') { + await page.getByRole('button', { name: 'Back', exact: true }).click() + } + await expectWidth(keepsDraggedWidth ? 598 : 698) + if (keepsDraggedWidth) { + await page.reload() + await page.getByRole('button', { name: 'workspace-chat-b', exact: true }).click() + await expectWidth(598) + await dragTo(698) + } else { + expect(await storage()).toBe(before) + } + }) } for (const button of ['middle', 'right'] as const) { - await check(`${button}-button drags leave the panel width unchanged`, async () => { - const before = await page.evaluate(() => JSON.stringify(localStorage)) + await test.step(`${button}-button drags leave the panel width unchanged`, async () => { + const before = await storage() await divider.hover({ position: { x: 4, y: 100 } }) const rect = await panel.boundingBox() if (!rect) throw new Error('Missing panel bounds') @@ -325,11 +226,11 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await page.mouse.move(rect.x + 100, rect.y + 100, { steps: 12 }) await page.mouse.up({ button }) await expectWidth(698) - expect(await page.evaluate(() => JSON.stringify(localStorage))).toBe(before) + expect(await storage()).toBe(before) }) } - await check('a touch drag resizes the panel without becoming a scroll gesture', async () => { + await test.step('a touch drag resizes the panel without becoming a scroll gesture', async () => { const rect = await panel.boundingBox() if (!rect) throw new Error('Missing panel bounds') await inputSession.send('Emulation.setTouchEmulationEnabled', { enabled: true }) @@ -352,32 +253,32 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await dragTo(698) }) - await check('a viewport change during a drag clamps the committed display width', async () => { + await test.step('a viewport change during a drag clamps the committed display width', async () => { await expectWidth(698) const rect = await beginDrag() await page.mouse.move(rect.x + 20, rect.y + 100, { steps: 12 }) await expectWidth(678) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(500, 400) ) await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(1000) await page.mouse.up() await expectWidth(520) - await shell.evaluate(({ BrowserWindow }) => + await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setContentSize(720, 400) ) await expectWidth(678) await dragTo(698) }) - await check('another account cannot inherit the current chat width', async () => { + await test.step('another account cannot inherit the current chat width', async () => { await page.getByRole('button', { name: 'Switch account' }).click() await expectWidth(720) await dragTo(580) await page.getByRole('button', { name: 'Switch account' }).click() await expectWidth(698) }) - await check('assigning a permanent chat ID lets an active drag finish', async () => { + await test.step('assigning a permanent chat ID lets an active drag finish', async () => { await page.getByRole('button', { name: 'pending:chat', exact: true }).click() await expectWidth(720) await dragTo(620) @@ -399,32 +300,32 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c await expectWidth(698) }) - await check( - 'cancelling before the first animation frame restores native browser bounds', - async () => { + const nativeBounds = () => + app.evaluate(({ BrowserWindow, WebContentsView }) => { + const view = BrowserWindow.getAllWindows()[0].contentView.children.find( + (child) => + child instanceof WebContentsView && child.webContents.getURL().endsWith('/page') + ) + return view?.getVisible() ? view.getBounds() : null + }) + // The bridge round trip observes main-process geometry after the queued bounds messages. + const settleBounds = (scope: string) => + page.evaluate( + (scope) => + (globalThis as DesktopBridge).simDesktop.browserAgent.capturePanelSnapshot(scope), + scope + ) + + const before = + await test.step('cancelling before the first animation frame restores native browser bounds', async () => { await page.getByRole('button', { name: 'pending:native', exact: true }).click() await expectWidth(720) await dragTo(698) - await shell.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - await expect - .poll(() => - shell.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused()) - ) - .toBe(true) + await focusShell() await page.getByRole('button', { name: 'Start browser', exact: true }).click() - const nativeBounds = () => - shell.evaluate(({ BrowserWindow, WebContentsView }) => { - const view = BrowserWindow.getAllWindows()[0].contentView.children.find( - (child) => - child instanceof WebContentsView && child.webContents.getURL().endsWith('/page') - ) - return view?.getVisible() ? view.getBounds() : null - }) await expect.poll(nativeBounds).not.toBeNull() - const before = await nativeBounds() + const bounds = await nativeBounds() + if (!bounds) throw new Error('Missing native browser bounds') await beginDrag() await divider.evaluate((element) => { const rect = element.getBoundingClientRect() @@ -433,61 +334,37 @@ test('chat panel sizes survive navigation, chat switches, collapse, and layout c ) element.dispatchEvent(new PointerEvent('pointercancel', { pointerId: 1, bubbles: true })) }) - // The bridge round trip observes main-process geometry after the queued bounds messages. - await page.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.capturePanelSnapshot('pending:native') - ) + await settleBounds('pending:native') await page.mouse.up() await expectWidth(698) - expect(await nativeBounds()).toEqual(before) + expect(await nativeBounds()).toEqual(bounds) + return bounds + }) - await check('native predictions follow a chat ID assigned during a drag', async () => { - if (!before) throw new Error('Missing native browser bounds') - await beginDrag() - await page - .getByRole('button', { name: 'Assign chat ID', exact: true }) - .evaluate((element: HTMLButtonElement) => element.click()) - await expect( - page.getByRole('button', { name: 'Assign chat ID', exact: true }) - ).toBeDisabled() - expect(await divider.evaluate((element) => element.hasPointerCapture(1))).toBe(true) - await divider.evaluate((element) => { - const rect = element.getBoundingClientRect() - element.dispatchEvent( - new PointerEvent('pointermove', { - pointerId: 1, - clientX: rect.x + 104, - bubbles: true, - }) - ) - }) - await page.evaluate(() => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.capturePanelSnapshot('assigned-chat') - ) - expect(await nativeBounds()).toEqual({ - ...before, - x: before.x + 50, - width: before.width - 50, - }) - await page.mouse.up() - await expectWidth(598) - }) - } - ) + await test.step('native predictions follow a chat ID assigned during a drag', async () => { + await beginDrag() + await page + .getByRole('button', { name: 'Assign chat ID', exact: true }) + .evaluate((element: HTMLButtonElement) => element.click()) + await expect(page.getByRole('button', { name: 'Assign chat ID', exact: true })).toBeDisabled() + expect(await divider.evaluate((element) => element.hasPointerCapture(1))).toBe(true) + await divider.evaluate((element) => { + const rect = element.getBoundingClientRect() + element.dispatchEvent( + new PointerEvent('pointermove', { pointerId: 1, clientX: rect.x + 104, bubbles: true }) + ) + }) + await settleBounds('assigned-chat') + expect(await nativeBounds()).toEqual({ + ...before, + x: before.x + 50, + width: before.width - 50, + }) + await page.mouse.up() + await expectWidth(598) + }) expect(errors).toEqual([]) - passed = true } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync( - reportPath, - JSON.stringify({ passed, checks, errors, desktopExit, rendererCrashed }, null, 2) - ) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/e2e/check-report.spec.ts b/apps/desktop/e2e/check-report.spec.ts deleted file mode 100644 index dc2a6378255..00000000000 --- a/apps/desktop/e2e/check-report.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { createRequire } from 'node:module' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { expect, test } from '@playwright/test' -import { omit } from '@sim/utils/object' -import type { ReportCheck } from './check-report' - -/** - * The suites' JSON reports against a real worker restart: a nested Playwright run of a fixture - * whose first test fails, so the second runs in a fresh worker with fresh module state. The report - * must keep the failure, and must not carry checks from an earlier run. - */ -const CLI = createRequire(import.meta.url).resolve('@playwright/test/cli') -const CONFIG = fileURLToPath(new URL('./fixtures/worker-restart.config.ts', import.meta.url)) - -test('a check that failed before the worker restarted stays in the report', () => { - const reportPath = join(mkdtempSync(join(tmpdir(), 'sim-check-report-')), 'report.json') - writeFileSync( - reportPath, - JSON.stringify({ - suite: 'worker-restart', - run: -1, - checks: [{ name: 'left by an earlier run', status: 'passed', durationMs: 0 }], - }) - ) - // The outer run's worker variables would make the nested runner think it is a worker. - const env = omit( - process.env, - Object.keys(process.env).filter((key) => /^(TEST_|PW_)/.test(key)) - ) - - const run = spawnSync(process.execPath, [CLI, 'test', '--config', CONFIG], { - env: { ...env, WORKER_RESTART_REPORT_PATH: reportPath }, - encoding: 'utf8', - timeout: 60_000, - }) - - expect(run.status, run.stdout + run.stderr).toBe(1) - const checks = (JSON.parse(readFileSync(reportPath, 'utf8')) as { checks: ReportCheck[] }).checks - expect(checks.map(({ name, status }) => ({ name, status }))).toEqual([ - { name: 'fails first', status: 'failed' }, - { name: 'passes after the worker restarts', status: 'passed' }, - ]) - // Proof the second check ran in a replacement worker, not the one that failed. - expect(checks[0]?.error).not.toBe(checks[1]?.error) -}) diff --git a/apps/desktop/e2e/check-report.ts b/apps/desktop/e2e/check-report.ts deleted file mode 100644 index 5fd3692f70c..00000000000 --- a/apps/desktop/e2e/check-report.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { readFileSync, writeFileSync } from 'node:fs' - -/** One check's outcome in a suite's JSON report. */ -export interface ReportCheck { - name: string - status: string - durationMs: number - error?: string - retry?: number -} - -interface Report { - suite: string - /** The Playwright run that wrote it: its workers' parent process. */ - run: number - checks: ReportCheck[] -} - -/** - * Adds a check to the suite's report at `reportPath` as soon as its outcome is known, keeping the - * checks already there from the same run. - * - * Playwright replaces a worker after a failure, and the new one starts with empty module state, so - * a report kept in memory and written at the end would drop everything before the failure, the - * failure included, and could read green. The file holds it instead. Every worker of one run is a - * child of the same runner, so a report left by an earlier run is replaced rather than added to. - */ -export function recordCheck( - reportPath: string | undefined, - suite: string, - check: ReportCheck -): void { - if (!reportPath) return - const run = process.ppid - let checks: ReportCheck[] = [] - try { - const existing = JSON.parse(readFileSync(reportPath, 'utf8')) as Report - if (existing.suite === suite && existing.run === run) checks = existing.checks - } catch { - // No report yet from this run. - } - const report: Report = { suite, run, checks: [...checks, check] } - writeFileSync(reportPath, JSON.stringify(report, null, 2)) -} diff --git a/apps/desktop/e2e/computer-use.spec.ts b/apps/desktop/e2e/computer-use.spec.ts index d171febdf3d..4c68e863b36 100644 --- a/apps/desktop/e2e/computer-use.spec.ts +++ b/apps/desktop/e2e/computer-use.spec.ts @@ -1,20 +1,27 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +import type { Page } from '@playwright/test' +import { type DesktopBridge, expect, test } from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) +/** Runs a computer tool call from the page; resolves 'rejected' when the desktop refuses it. */ +function runTool(window: Page, toolCallId: string): Promise { + return window.evaluate(async (toolCallId) => { + const api = (globalThis as DesktopBridge).simDesktop + try { + await api.computerUse?.executeTool(toolCallId, { action: 'status' }) + return 'unexpected success' + } catch { + return 'rejected' + } + }, toolCallId) +} -test('computer use reaches the actual helper only with canonical one-shot authorization', async () => { +test('computer use reaches the actual helper only with canonical one-shot authorization', async ({ + desktop, +}) => { test.skip(process.platform !== 'darwin', 'The native helper is macOS-only.') - const root = mkdtempSync(join(tmpdir(), 'sim-computer-use-e2e-')) - let server: Server | undefined - let app: ElectronApplication | undefined let claimed = false - let authorizationCount = 0 + /** The body of every authorization request, checked in the test rather than the handler. */ + const authorizationBodies: unknown[] = [] let releaseAuthorization: () => void = () => {} let markAuthorizationStarted: () => void = () => {} const authorizationStarted = new Promise((resolve) => { @@ -23,128 +30,82 @@ test('computer use reaches the actual helper only with canonical one-shot author const authorizationReleased = new Promise((resolve) => { releaseAuthorization = resolve }) - try { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }).end( - JSON.stringify({ - user: { id: 'computer-test' }, - session: { id: 'computer-test-session' }, - }) - ) - return + const fixture = await serveSignedIn({ + page: `Computer Use fixture

Computer Use

`, + handle: async (request, response, url) => { + if (url.pathname !== '/api/desktop/computer/authorize') return false + let body = '' + for await (const chunk of request) body += chunk.toString() + const input = JSON.parse(body) + authorizationBodies.push(input) + if (Object.keys(input).join() !== 'toolCallId') { + response.writeHead(400, { 'Content-Type': 'application/json' }).end('{}') + return true } - if (path === '/api/desktop/computer/authorize') { - authorizationCount += 1 - let body = '' - for await (const chunk of request) body += chunk.toString() - const input = JSON.parse(body) - expect(Object.keys(input)).toEqual(['toolCallId']) - if (input.toolCallId === 'delayed') { - markAuthorizationStarted() - await authorizationReleased - } else if (input.toolCallId !== 'status-once' || claimed) { - response.writeHead(403, { 'Content-Type': 'application/json' }).end('{}') - return - } - claimed = true - response.writeHead(200, { 'Content-Type': 'application/json' }).end( - JSON.stringify({ - chatId: 'computer-chat', - toolName: 'computer', - args: { action: 'status' }, - }) - ) - return + if (input.toolCallId === 'delayed') { + markAuthorizationStarted() + await authorizationReleased + } else if (input.toolCallId !== 'status-once' || claimed) { + response.writeHead(403, { 'Content-Type': 'application/json' }).end('{}') + return true } - response - .writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', + claimed = true + response.writeHead(200, { 'Content-Type': 'application/json' }).end( + JSON.stringify({ + chatId: 'computer-chat', + toolName: 'computer', + args: { action: 'status' }, }) - .end( - `Computer Use fixture

Computer Use

` - ) - }) - await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing local fixture port') - const profile = join(root, 'profile') - mkdirSync(profile) - writeFileSync( - join(profile, 'settings.json'), - JSON.stringify({ origin: `http://127.0.0.1:${address.port}`, computerUseEnabled: true }) - ) - app = await electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: profile, - }, + ) + return true + }, + }) + try { + const { app } = await desktop.launch({ + origin: fixture.origin, + settings: { origin: fixture.origin, computerUseEnabled: true }, }) const window = await app.firstWindow() await expect(window.getByRole('heading')).toHaveText('Computer Use') - const status = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.computerUse?.getStatus() - }) - expect(status).toMatchObject({ supported: true, enabled: true, activeAction: null }) - const result = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.computerUse?.executeTool('status-once', { - action: 'get_app_state', - bundleId: 'com.apple.systempreferences', - }) - }) - expect(result).toMatchObject({ kind: 'status', platform: 'darwin' }) - const replay = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - try { - await api.computerUse?.executeTool('status-once', { action: 'status' }) - return 'unexpected success' - } catch { - return 'rejected' - } - }) - expect(replay).toBe('rejected') - expect(authorizationCount).toBe(2) - const delayed = window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - try { - await api.computerUse?.executeTool('delayed', { action: 'status' }) - return 'unexpected success' - } catch { - return 'stopped' - } + + await test.step('an authorized call reaches the helper once and a replay is refused', async () => { + const status = await window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.computerUse?.getStatus() + ) + expect(status).toMatchObject({ supported: true, enabled: true, activeAction: null }) + const result = await window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.computerUse?.executeTool('status-once', { + action: 'get_app_state', + bundleId: 'com.apple.systempreferences', + }) + ) + expect(result).toMatchObject({ kind: 'status', platform: 'darwin' }) + expect(await runTool(window, 'status-once')).toBe('rejected') + expect(authorizationBodies).toEqual([ + { toolCallId: 'status-once' }, + { toolCallId: 'status-once' }, + ]) }) - await authorizationStarted - await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.computerUse?.cancel('delayed') + + await test.step('cancelling while authorization is pending stops the call', async () => { + const delayed = runTool(window, 'delayed') + await authorizationStarted + await window.evaluate(() => + (globalThis as DesktopBridge).simDesktop.computerUse?.cancel('delayed') + ) + releaseAuthorization() + expect(await delayed).toBe('rejected') + expect(authorizationBodies).toHaveLength(3) }) - releaseAuthorization() - expect(await delayed).toBe('stopped') - expect(authorizationCount).toBe(3) - await window.getByRole('button', { name: 'Disable Computer Use' }).click() - await expect(window.locator('#status')).toHaveText('false') - const disabled = await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - try { - await api.computerUse?.executeTool('disabled', { action: 'status' }) - return 'unexpected success' - } catch { - return 'rejected' - } + + await test.step('turning computer use off refuses calls before asking Sim', async () => { + await window.getByRole('button', { name: 'Disable Computer Use' }).click() + await expect(window.locator('#status')).toHaveText('false') + expect(await runTool(window, 'disabled')).toBe('rejected') + expect(authorizationBodies).toHaveLength(3) }) - expect(disabled).toBe('rejected') - expect(authorizationCount).toBe(3) } finally { releaseAuthorization() - await app?.close() - await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())) - rmSync(root, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/e2e/continue-sign-in.spec.ts b/apps/desktop/e2e/continue-sign-in.spec.ts index c1954da5736..0a157a8535d 100644 --- a/apps/desktop/e2e/continue-sign-in.spec.ts +++ b/apps/desktop/e2e/continue-sign-in.spec.ts @@ -1,13 +1,7 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { recordCheck } from './check-report' +import type { ElectronApplication, Page } from '@playwright/test' +import { type DesktopBridge, expect, type FixtureServer, test } from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'continue-sign-in-fixture' /** @@ -20,38 +14,13 @@ const SCOPE = 'continue-sign-in-fixture' * covered by the importer's fixture-database tests instead. */ test.describe('continue a sign-in in another browser', () => { - let server: Server - let origin: string - let site: string - let home: string - let userData: string - let app: ElectronApplication | undefined + let fixture: FixtureServer + let app: ElectronApplication + let page: Page test.beforeAll(async () => { - server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - ) - return - } - if (path.startsWith('/api/')) { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end('{}') - return - } - if (request.headers.host?.startsWith('localhost')) { - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end('Sign in

Sign in

') - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) - response.end(`Sim fixture

Continue fixture

+ fixture = await serveSignedIn({ + page: `Sim fixture

Continue fixture

`) +`, + handle: (request, response, url) => { + if (url.pathname.startsWith('/api/') || !request.headers.host?.startsWith('localhost')) { + return false + } + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Sign in

Sign in

') + return true + }, }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - site = `http://localhost:${address.port}` }) - test.beforeEach(async () => { - home = mkdtempSync(join(tmpdir(), 'sim-continue-home-')) - userData = mkdtempSync(join(tmpdir(), 'sim-continue-e2e-')) - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - HOME: home, - SIM_DESKTOP_ORIGIN: origin, - SIM_DESKTOP_USER_DATA: userData, - }, - }) - const page = await app.firstWindow() + test.afterAll(async () => { + await fixture.close() + }) + + test.beforeEach(async ({ desktop }) => { + ;({ app } = await desktop.launch({ + origin: fixture.origin, + env: { HOME: desktop.tempDir('sim-continue-home-') }, + })) + page = await app.firstWindow() await expect(page.getByRole('heading')).toHaveText('Continue fixture') await page.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + const api = (globalThis as DesktopBridge).simDesktop await api.browserAgent.activateScope(scope) api.browserAgent.setPanelBounds({ x: 0, y: 120, width: 800, height: 400 }, null, scope) }, SCOPE) }) - test.afterEach(async () => { - const testInfo = test.info() - recordCheck(process.env.CONTINUE_SIGN_IN_REPORT_PATH, 'continue-sign-in', { - name: testInfo.title, - status: testInfo.status ?? 'unknown', - durationMs: testInfo.duration, - retry: testInfo.retry, - }) - await app?.close() - app = undefined - rmSync(userData, { recursive: true, force: true }) - rmSync(home, { recursive: true, force: true }) - }) - - test.afterAll(async () => { - await new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) - }) - - test('advertises the capability, but offers no browser when none is installed', async () => { - const page = await app?.firstWindow() - const surface = await page?.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + test('advertises the capability without a browser to offer, and refuses calls without the user', async () => { + const surface = await page.evaluate(async (scope) => { + const api = (globalThis as DesktopBridge).simDesktop return { continueSignIn: typeof api.browserImport?.continueSignIn, bringSignInBack: typeof api.browserImport?.bringSignInBack, - pending: await api.browserImport?.getPendingSignIn?.('continue-sign-in-fixture'), + pending: await api.browserImport?.getPendingSignIn?.(scope), profiles: await api.browserImport?.listChromeProfiles(), + // Page script calling straight in, with no user gesture behind it. + continued: await api.browserImport?.continueSignIn?.('chrome:Default', scope), + broughtBack: await api.browserImport?.bringSignInBack?.(scope), } - }) + }, SCOPE) expect(surface).toEqual({ continueSignIn: 'function', bringSignInBack: 'function', pending: null, profiles: [], - }) - }) - - test('refuses page script that acts without the user', async () => { - const page = await app?.firstWindow() - const results = await page?.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return { - continued: await api.browserImport?.continueSignIn?.('chrome:Default', scope), - broughtBack: await api.browserImport?.bringSignInBack?.(scope), - } - }, SCOPE) - - expect(results).toEqual({ continued: { error: 'unknown' }, broughtBack: { cookiesImported: 0, cookiesSkipped: 0, error: 'unknown' }, }) }) test('reads the page from the tab itself and hands over only https', async () => { - const page = await app?.firstWindow() - if (!page || !app) throw new Error('App did not launch') const read = (key: string) => page.evaluate((name) => Reflect.get(globalThis, name), key) await page.locator('#open').click() await expect.poll(() => read('opened')).toMatchObject({ activeTabId: expect.any(String) }) await expect .poll(() => - app?.evaluate( + app.evaluate( ({ webContents }, target) => webContents.getAllWebContents().some((contents) => contents.getURL() === target), - `${site}/login` + `${fixture.site}/login` ) ) .toBe(true) diff --git a/apps/desktop/e2e/desktop-tools-live-sim.spec.ts b/apps/desktop/e2e/desktop-tools-live-sim.spec.ts index c396d8104a4..01cf40f3098 100644 --- a/apps/desktop/e2e/desktop-tools-live-sim.spec.ts +++ b/apps/desktop/e2e/desktop-tools-live-sim.spec.ts @@ -1,18 +1,9 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { mkdirSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { - type ElectronApplication, - _electron as electron, - expect, - type Locator, - type Page, - test, -} from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +import type { Locator, Page } from '@playwright/test' import { sleep } from '@sim/utils/helpers' import { generateId } from '@sim/utils/id' +import { answerShellDialog } from './executor-sim' import { type LiveSimConfig, liveSimConfig, @@ -22,6 +13,7 @@ import { SimDatabase, SimProxy, } from './fixtures/live-sim' +import { type DesktopApp, type DesktopBridge, type DesktopFixture, expect, test } from './harness' /** * Desktop tools in the real Electron app against a real local Sim: the renderer is Sim's own chat @@ -37,7 +29,6 @@ import { * The tests marked as running in the background let Sim's own answer through. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const config = liveSimConfig() const PICKUP_GRACE_MS = 15_000 /** Longer than the default tool budget (60 s) plus the resume grace (30 s). */ @@ -48,15 +39,17 @@ const LEASE_MS = 60_000 const ARRIVAL_MS = 60_000 /** First requests to a route compile it, which takes minutes on a cold dev app. */ const COMPILE_MS = 300_000 +/** The warm-up's budget: every route it reaches may compile from cold. */ +const WARM_UP_MS = 1_500_000 const REGISTRATION_PATH = '/api/desktop/devices' const DESKTOP_COMPLETION_PATH = '/api/desktop/tool/complete' +/** The title of the shell dialog asking to allow a folder. */ +const FOLDER_CONSENT_TITLE = 'Allow access to this folder?' /** Sim's answer to registration on an install that cannot run the background executor. */ const executorUnavailable = (answer: Record) => { answer.enabled = false } -type DesktopWindow = typeof globalThis & { simDesktop: SimDesktopApi } - test.describe('desktop tools against a live Sim', () => { test.skip(typeof config === 'string', typeof config === 'string' ? config : '') test.describe.configure({ timeout: 360_000 }) @@ -65,14 +58,14 @@ test.describe('desktop tools against a live Sim', () => { let proxy: SimProxy let agent: ScriptedAgent let db: SimDatabase - let app: ElectronApplication | undefined + let launched: DesktopApp | undefined + let warmedUp = process.env.SIM_DESKTOP_E2E_APP_SERVER === 'start' let scratch: string /** Errors the current window reported, shown when a click is blocked. */ let pageErrors: string[] = [] let testStartedAt = 0 test.beforeAll(async () => { - test.setTimeout(1_500_000) if (typeof config === 'string') throw new Error(config) sim = config proxy = new SimProxy(sim) @@ -80,23 +73,29 @@ test.describe('desktop tools against a live Sim', () => { db = new SimDatabase(sim) await Promise.all([proxy.start(), agent.start()]) proxy.rewriteAnswer(REGISTRATION_PATH, executorUnavailable) - if (process.env.SIM_DESKTOP_E2E_APP_SERVER !== 'start') - await test.step('warm up the routes the tests use', warmUp) }) test.afterAll(async () => { await Promise.all([proxy?.stop(), agent?.stop(), db?.close()]) }) - test.beforeEach(() => { + // The warm-up launches the app, which only a test's fixtures can do, so the first test runs it + // with the time it takes added to its own. + test.beforeEach(async ({ desktop }) => { + if (!warmedUp) { + // Once per worker even if it fails: the failure is this test's, not every test's. + warmedUp = true + test.setTimeout(test.info().timeout + WARM_UP_MS) + await test.step('warm up the routes the tests use', () => warmUp(desktop)) + } testStartedAt = Date.now() - scratch = mkdtempSync(join(tmpdir(), 'sim-desktop-tools-live-')) + scratch = desktop.tempDir('sim-desktop-tools-live-') }) test.afterEach(async () => { const testInfo = test.info() if (testInfo.status !== testInfo.expectedStatus) { - const page = app?.windows()[0] + const page = launched?.app.windows()[0] await page?.screenshot({ path: testInfo.outputPath('failure.png') }).catch(() => {}) writeFileSync( testInfo.outputPath('diagnostics.json'), @@ -120,11 +119,9 @@ test.describe('desktop tools against a live Sim', () => { } proxy.clearHolds() proxy.restoreNetwork() - await app?.close().catch(() => {}) - app = undefined + launched = undefined proxy.rewriteAnswer(REGISTRATION_PATH, executorUnavailable) proxy.rewriteAnswer(DESKTOP_COMPLETION_PATH, undefined) - rmSync(scratch, { recursive: true, force: true }) }) /** @@ -135,8 +132,8 @@ test.describe('desktop tools against a live Sim', () => { * so no route the tests reach is left to compile. It ends with a marker request * (`/api/health?e2e=warm-up-done`) so the dev server's log shows anything compiled after it. */ - async function warmUp(): Promise { - scratch = mkdtempSync(join(tmpdir(), 'sim-desktop-tools-warm-')) + async function warmUp(desktop: DesktopFixture): Promise { + scratch = desktop.tempDir('sim-desktop-tools-warm-') try { const user = await db.seedUser(['Warm chat', 'Warm other chat']) const headers = { @@ -208,7 +205,7 @@ test.describe('desktop tools against a live Sim', () => { // The leg stays open until Stop ends it. await turn.closed }) - const page = await openApp(user, 'Warm chat', COMPILE_MS) + const page = await openApp(desktop, user, 'Warm chat', COMPILE_MS) await send(page, '[warm-up] read and import', COMPILE_MS) await expect(page.getByText('Warming up.')).toBeVisible({ timeout: COMPILE_MS }) // Leaving and reopening a chat while its turn runs re-attaches to the turn's stream. @@ -225,33 +222,45 @@ test.describe('desktop tools against a live Sim', () => { await proxy.settled(COMPILE_MS) await compile('/api/health?e2e=warm-up-done') } finally { - await app?.close().catch(() => {}) - app = undefined - rmSync(scratch, { recursive: true, force: true }) + if (launched) await desktop.close(launched) + launched = undefined } } const chatPath = (user: SeededUser, title: string) => `/workspace/${user.workspaceId}/chat/${user.chats[title]}` + /** + * Allows the folder when `window` is the folder consent dialog, as the user would; any other + * window is left alone. + */ + async function allowFolderConsent(window: Page): Promise { + await window.waitForLoadState('domcontentloaded') + if (!window.url().endsWith('/dialog.html')) return + // The dialog takes its title before it renders. + await window.getByRole('dialog').waitFor() + if ((await window.title()) !== FOLDER_CONSENT_TITLE) return + await answerShellDialog(window, 'Allow folder') + } + /** Launches the app signed in as `user`, showing the chat titled `title`. */ - async function openApp(user: SeededUser, title: string, timeout = 120_000): Promise { - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: proxy.origin, - SIM_DESKTOP_USER_DATA: join(scratch, 'profile'), - }, + async function openApp( + desktop: DesktopFixture, + user: SeededUser, + title: string, + timeout = 120_000 + ): Promise { + launched = await desktop.launch({ + origin: proxy.origin, }) + const { app } = launched const page = await app.firstWindow({ timeout }) pageErrors = [] - app.on('window', (permission) => { - void permission - .getByRole('button', { name: 'Allow folder', exact: true }) - .click({ timeout: 10_000 }) - .catch((error) => pageErrors.push(`Folder approval failed: ${String(error)}`)) + app.on('window', (window) => { + void allowFolderConsent(window).catch((error: unknown) => { + // A dialog the app closes itself, such as on Stop, is not a failed approval. + if (!window.isClosed()) pageErrors.push(`Folder approval failed: ${String(error)}`) + }) }) page.on('pageerror', (error) => pageErrors.push(error.message)) page.on('console', (message) => { @@ -392,7 +401,9 @@ test.describe('desktop tools against a live Sim', () => { const isToolReport = (method: string, path: string) => method === 'POST' && path === '/api/copilot/confirm' - test('a browser call issued after the user switched chats fails as not started after the pickup grace', async () => { + test('a browser call issued after the user switched chats fails as not started after the pickup grace', async ({ + desktop, + }) => { const user = await db.seedUser(['Browser chat', 'Other chat']) let issue!: () => void const issued = new Promise((resolve) => { @@ -407,7 +418,7 @@ test.describe('desktop tools against a live Sim', () => { issuedAt = Date.now() turn.pause() }) - const page = await openApp(user, 'Browser chat') + const page = await openApp(desktop, user, 'Browser chat') await send(page, '[pickup-grace] which tabs are open?') await expect(page.getByText('Checking your browser tabs.')).toBeVisible({ timeout: 60_000 }) await openChat(page, user, 'Other chat') @@ -424,7 +435,7 @@ test.describe('desktop tools against a live Sim', () => { expect(call).toMatchObject({ toolName: 'browser_list_tabs', status: 'failed', claimedBy: null }) }) - test('leaving the chat does not end a local file read already under way', async () => { + test('leaving the chat does not end a local file read already under way', async ({ desktop }) => { const user = await db.seedUser(['Read chat', 'Other chat']) const marker = generateId() const file = writeFile(join(scratch, 'notes.txt'), `notes from disk ${marker}`) @@ -433,7 +444,7 @@ test.describe('desktop tools against a live Sim', () => { callId = turn.toolCall({ toolName: 'read_local_file', args: { path: file } }) turn.pause() }) - const page = await openApp(user, 'Read chat') + const page = await openApp(desktop, user, 'Read chat') // Visit the other chat once, so leaving for it later is a quick client-side switch. await openChat(page, user, 'Other chat') await openChat(page, user, 'Read chat') @@ -458,7 +469,9 @@ test.describe('desktop tools against a live Sim', () => { expect(call).toMatchObject({ toolName: 'read_local_file', status: 'completed' }) }) - test('an import keeps running across chat switches, and Stop from the reopened chat ends it', async () => { + test('an import keeps running across chat switches, and Stop from the reopened chat ends it', async ({ + desktop, + }) => { const user = await db.seedUser(['Import chat', 'Other chat']) const chatId = user.chats['Import chat'] const source = importSource() @@ -469,7 +482,7 @@ test.describe('desktop tools against a live Sim', () => { }) turn.pause() }) - const page = await openApp(user, 'Import chat') + const page = await openApp(desktop, user, 'Import chat') const firstUpload = proxy.hold(isUploadStart) await send(page, '[stop-import] import my reports') await firstUpload.arrival(ARRIVAL_MS, 'The first upload') @@ -505,7 +518,12 @@ test.describe('desktop tools against a live Sim', () => { }) /** An import whose first upload the proxy holds until released, as a large file's would take. */ - async function slowImport(user: SeededUser, title: string, marker: string) { + async function slowImport( + desktop: DesktopFixture, + user: SeededUser, + title: string, + marker: string + ) { const source = importSource() let callId = '' agent.script(marker, (turn) => { @@ -515,18 +533,21 @@ test.describe('desktop tools against a live Sim', () => { }) turn.pause() }) - const page = await openApp(user, title) + const page = await openApp(desktop, user, title) const firstUpload = proxy.hold(isUploadStart) await send(page, `${marker} import my reports`) await firstUpload.arrival(ARRIVAL_MS, 'The first upload') return { page, firstUpload, callId: () => callId } } - test('an import that runs longer than the default tool budget still completes', async () => { + test('an import that runs longer than the default tool budget still completes', async ({ + desktop, + }) => { test.setTimeout(420_000) const user = await db.seedUser(['Long import chat', 'Other chat']) const chatId = user.chats['Long import chat'] const { page, firstUpload, callId } = await slowImport( + desktop, user, 'Long import chat', '[long-import]' @@ -548,16 +569,18 @@ test.describe('desktop tools against a live Sim', () => { expect(await callState(chatId)).toMatch(/^completed/) }) - test('a long import whose window crashed settles as outcome unknown about one lease later @lease-lapse', async () => { + test('a long import whose window crashed settles as outcome unknown about one lease later @lease-lapse', async ({ + desktop, + }) => { test.setTimeout(420_000) const user = await db.seedUser(['Crashing import chat']) - const { callId } = await slowImport(user, 'Crashing import chat', '[crash-import]') + const { callId } = await slowImport(desktop, user, 'Crashing import chat', '[crash-import]') await sleep(LONG_IMPORT_MS) expect(agent.resultFor(callId())).toBeUndefined() // A crash reports nothing on its way out, unlike a closed window: only the lapse of the // lease the page was renewing tells Sim the import is gone. const crashedAt = Date.now() - await app?.evaluate(({ webContents }) => { + await launched?.app.evaluate(({ webContents }) => { for (const contents of webContents.getAllWebContents()) if (contents.getURL().includes('/workspace/')) contents.forcefullyCrashRenderer() }) @@ -567,7 +590,7 @@ test.describe('desktop tools against a live Sim', () => { expect((result?.at ?? 0) - crashedAt).toBeLessThan(LEASE_MS + 20_000) }) - test('signing out ends a desktop tool still running', async () => { + test('signing out ends a desktop tool still running', async ({ desktop }) => { const user = await db.seedUser(['Import chat']) const chatId = user.chats['Import chat'] const source = importSource() @@ -578,7 +601,7 @@ test.describe('desktop tools against a live Sim', () => { }) turn.pause() }) - const page = await openApp(user, 'Import chat') + const page = await openApp(desktop, user, 'Import chat') const firstUpload = proxy.hold(isUploadStart) await send(page, '[sign-out-import] import my reports') await firstUpload.arrival(ARRIVAL_MS, 'The first upload') @@ -625,73 +648,75 @@ test.describe('desktop tools against a live Sim', () => { return call } - test("a local read awaiting the user's approval cannot be claimed", async () => { - const user = await db.seedUser(['Approval chat']) - const secret = generateId() - const file = writeFile(join(scratch, 'secret.txt'), `private ${secret}`) - agent.script('[unapproved-read]', (turn) => { - turn.toolCall({ - toolName: 'read_local_file', - args: { path: file }, - status: 'awaiting_approval', + test("a local read or terminal command awaiting the user's approval cannot be claimed", async ({ + desktop, + }) => { + const user = await db.seedUser(['Read approval chat', 'Run approval chat']) + const page = await openApp(desktop, user, 'Read approval chat') + + await test.step('a local read', async () => { + const secret = generateId() + const file = writeFile(join(scratch, 'secret.txt'), `private ${secret}`) + agent.script('[unapproved-read]', (turn) => { + turn.toolCall({ + toolName: 'read_local_file', + args: { path: file }, + status: 'awaiting_approval', + }) + turn.pause() }) - turn.pause() + const chatId = user.chats['Read approval chat'] + const read = await gatedCall( + page, + chatId, + '[unapproved-read] read my secret', + 'read_local_file' + ) + // A renderer acting on a call the user has not allowed (a replayed event) is refused. + const response = await page.evaluate( + (toolCallId) => + (globalThis as DesktopBridge).simDesktop.localFiles?.({ operation: 'read', toolCallId }), + read.toolCallId + ) + expect(response?.ok).toBe(false) + expect(JSON.stringify(response)).not.toContain(secret) + const [after] = await db.toolCalls(chatId) + expect(after).toMatchObject({ status: 'pending', claimedBy: null }) }) - const page = await openApp(user, 'Approval chat') - const chatId = user.chats['Approval chat'] - const read = await gatedCall( - page, - chatId, - '[unapproved-read] read my secret', - 'read_local_file' - ) - - // A renderer acting on a call the user has not allowed (a replayed event) is refused. - const response = await page.evaluate( - (toolCallId) => - (globalThis as DesktopWindow).simDesktop.localFiles?.({ operation: 'read', toolCallId }), - read.toolCallId - ) - expect(response?.ok).toBe(false) - expect(JSON.stringify(response)).not.toContain(secret) - const [after] = await db.toolCalls(chatId) - expect(after).toMatchObject({ status: 'pending', claimedBy: null }) - }) - test("a terminal command awaiting the user's approval cannot be claimed", async () => { - const user = await db.seedUser(['Approval chat']) - const command = `touch '${join(scratch, 'terminal-ran')}'` - agent.script('[unapproved-run]', (turn) => { - turn.toolCall({ toolName: 'terminal', args: { operation: 'run', command } }) - turn.pause() + await test.step('a terminal command', async () => { + const command = `touch '${join(scratch, 'terminal-ran')}'` + agent.script('[unapproved-run]', (turn) => { + turn.toolCall({ toolName: 'terminal', args: { operation: 'run', command } }) + turn.pause() + }) + await openChat(page, user, 'Run approval chat') + const chatId = user.chats['Run approval chat'] + const run = await gatedCall(page, chatId, '[unapproved-run] run a command', 'terminal') + // The guard is the claim: Sim must not hand an unapproved command to the desktop, so the + // call stays pending and unclaimed. Whether a handed-over command then runs depends on a + // terminal being open for the chat, which this test does not set up, so it checks the claim. + const response = await page.evaluate( + ({ toolCallId, command }) => + (globalThis as DesktopBridge).simDesktop.terminal + .executeTool(toolCallId, 'run', { command }, 'unapproved-e2e') + .catch((error: unknown) => ({ ok: false, error: String(error) })), + { toolCallId: run.toolCallId, command } + ) + expect(response).toMatchObject({ ok: false }) + const [after] = await db.toolCalls(chatId) + expect(after).toMatchObject({ status: 'pending', claimedBy: null }) }) - const page = await openApp(user, 'Approval chat') - const chatId = user.chats['Approval chat'] - const run = await gatedCall(page, chatId, '[unapproved-run] run a command', 'terminal') - - // The guard is the claim: Sim must not hand an unapproved command to the desktop, so the call - // stays pending and unclaimed. Whether a handed-over command then runs depends on a terminal - // being open for the chat, which this test does not set up, so it checks the claim only. - const response = await page.evaluate( - ({ toolCallId, command }) => - (globalThis as DesktopWindow).simDesktop.terminal - .executeTool(toolCallId, 'run', { command }, 'unapproved-e2e') - .catch((error: unknown) => ({ ok: false, error: String(error) })), - { toolCallId: run.toolCallId, command } - ) - expect(response).toMatchObject({ ok: false }) - const [after] = await db.toolCalls(chatId) - expect(after).toMatchObject({ status: 'pending', claimedBy: null }) }) - test('a claim that reaches Sim after the user pressed Stop is refused', async () => { + test('a claim that reaches Sim after the user pressed Stop is refused', async ({ desktop }) => { const user = await db.seedUser(['Stop chat']) const file = writeFile(join(scratch, 'notes.txt'), 'notes') agent.script('[stopped-claim]', (turn) => { turn.toolCall({ toolName: 'read_local_file', args: { path: file } }) turn.pause() }) - const page = await openApp(user, 'Stop chat') + const page = await openApp(desktop, user, 'Stop chat') const chatId = user.chats['Stop chat'] // Delivered to Sim on release even should Electron have given up on it meanwhile. const lateClaim = proxy.hold(isDesktopClaim, { deliverIfAbandoned: true }) @@ -706,7 +731,7 @@ test.describe('desktop tools against a live Sim', () => { const [call] = await db.toolCalls(chatId) const replay = await page.evaluate( (toolCallId) => - (globalThis as DesktopWindow).simDesktop.localFiles?.({ operation: 'read', toolCallId }), + (globalThis as DesktopBridge).simDesktop.localFiles?.({ operation: 'read', toolCallId }), call.toolCallId ) expect(replay?.ok).toBe(false) @@ -718,7 +743,9 @@ test.describe('desktop tools against a live Sim', () => { expect(after).toMatchObject({ status: 'cancelled', claimedBy: null }) }) - test('where Sim cannot run the background executor, the app stays dormant and a desktop round trip runs in the chat view', async () => { + test('where Sim cannot run the background executor, the app stays dormant and a desktop round trip runs in the chat view', async ({ + desktop, + }) => { const user = await db.seedUser(['Round trip']) const marker = generateId() const file = writeFile(join(scratch, 'plan.txt'), `plan ${marker}`) @@ -741,7 +768,7 @@ test.describe('desktop tools against a live Sim', () => { } ) const since = Date.now() - const page = await openApp(user, 'Round trip') + const page = await openApp(desktop, user, 'Round trip') await send(page, '[round-trip] what does my plan say?') // Each layer is checked on its own (soft), so a regression shows every layer it reaches: // the round trip, the turn's binding, the routes the app calls, and the doorbell. @@ -787,7 +814,9 @@ test.describe('desktop tools against a live Sim', () => { } }) - test('in the background, a call issued after the user switched chats runs on the desktop', async () => { + test('in the background, a call issued after the user switched chats runs on the desktop', async ({ + desktop, + }) => { proxy.rewriteAnswer(REGISTRATION_PATH, undefined) const user = await db.seedUser(['Background chat', 'Other chat']) const marker = generateId() @@ -805,7 +834,7 @@ test.describe('desktop tools against a live Sim', () => { issuedAt = Date.now() turn.pause() }) - const page = await openApp(user, 'Background chat') + const page = await openApp(desktop, user, 'Background chat') await send(page, '[background-read] read my notes') await expect(page.getByText('Reading your notes.')).toBeVisible({ timeout: 60_000 }) await openChat(page, user, 'Other chat') @@ -825,7 +854,9 @@ test.describe('desktop tools against a live Sim', () => { expect(proxy.seen(issuedAt, '/api/desktop/tool/authorize')).toEqual([]) }) - test('in the background, a result reported across a network cut reaches the agent exactly once', async () => { + test('in the background, a result reported across a network cut reaches the agent exactly once', async ({ + desktop, + }) => { proxy.rewriteAnswer(REGISTRATION_PATH, undefined) const user = await db.seedUser(['Cut chat']) const chatId = user.chats['Cut chat'] @@ -836,7 +867,7 @@ test.describe('desktop tools against a live Sim', () => { callId = turn.toolCall({ toolName: 'read_local_file', args: { path: file } }) turn.pause() }) - const page = await openApp(user, 'Cut chat') + const page = await openApp(desktop, user, 'Cut chat') // Reaches Sim on release although the cut made the app give up on it, as a report already on // the wire would: the app cannot know it landed, so it reports again once back online. const completion = proxy.hold(isDesktopCompletion, { deliverIfAbandoned: true }) diff --git a/apps/desktop/e2e/executor-sim.ts b/apps/desktop/e2e/executor-sim.ts index fbb462b98aa..92b78d8790c 100644 --- a/apps/desktop/e2e/executor-sim.ts +++ b/apps/desktop/e2e/executor-sim.ts @@ -1,18 +1,11 @@ import { execFileSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { mkdtempSync, readFileSync } from 'node:fs' +import { readFileSync } from 'node:fs' import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' import type { Socket } from 'node:net' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { - type ElectronApplication, - _electron as electron, - expect, - type Page, -} from '@playwright/test' +import type { ElectronApplication, Page } from '@playwright/test' import { getErrorMessage } from '@sim/utils/errors' +import { type DesktopApp, type DesktopFixture, expect } from './harness' /** * A fixture Sim that speaks the background executor's device protocol (register, inbox, @@ -20,10 +13,9 @@ import { getErrorMessage } from '@sim/utils/errors' * executor's Electron suites share. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) export const WORKSPACE = 'ws-e2e' const LEASE_RENEW_MS = 1_000 -export const RECONCILE_MS = 2_000 +const RECONCILE_MS = 2_000 type CallStatus = 'pending' | 'awaiting_approval' | 'running' | 'completed' | 'failed' | 'cancelled' @@ -45,7 +37,10 @@ export interface FixtureCall { issuedAt: number claimedAt?: number token?: string + /** Successful claims. */ claims: number + /** Every claim request for this call, refused ones included. */ + claimAttempts: number renewals: number completions: Completion[] acknowledged: boolean @@ -72,6 +67,8 @@ export class FixtureSim { readonly streams = new Map>() readonly imported: ImportedEntry[] = [] enabled = true + /** How often a registered device reads its inbox without a ring. */ + reconcileMs = RECONCILE_MS /** Connections reset while the network was cut. */ droppedWhileOffline = 0 private offline = false @@ -125,6 +122,7 @@ export class FixtureSim { this.hits.clear() this.imported.length = 0 this.enabled = true + this.reconcileMs = RECONCILE_MS this.offline = false this.droppedWhileOffline = 0 } @@ -147,6 +145,7 @@ export class FixtureSim { status, issuedAt: Date.now(), claims: 0, + claimAttempts: 0, renewals: 0, completions: [], acknowledged: false, @@ -279,7 +278,7 @@ export class FixtureSim { protocolVersion: 1, leaseMs: 60_000, leaseRenewMs: LEASE_RENEW_MS, - reconcileMs: RECONCILE_MS, + reconcileMs: this.reconcileMs, }) return } @@ -347,6 +346,7 @@ export class FixtureSim { return } if (path === '/api/desktop/tool/claim') { + call.claimAttempts += 1 if (call.status !== 'pending' || call.token) { this.json(response, 404, { error: 'This call is no longer waiting for this device' }) return @@ -434,37 +434,47 @@ export class FixtureSim { } } +export interface ExecutorApp extends DesktopApp { + window: Page +} + /** - * Launches the app against the fixture Sim. Its shells are zsh with an empty config directory, so - * what they do is the app's and not this machine's: a developer's `.zshrc` can stop at a question - * (oh-my-zsh asks before updating) and hold the first prompt for as long as nobody answers it. - * The terminal's handling of slow and stalled startup files has its own tests. + * Launches the app against the fixture Sim and waits for its window to load Sim. Its shells are + * zsh with an empty config directory, so what they do is the app's and not this machine's: a + * developer's `.zshrc` can stop at a question (oh-my-zsh asks before updating) and hold the first + * prompt for as long as nobody answers it. Pass `userData` to relaunch on an earlier profile. */ -export async function launch( +export async function launchAgainst( + desktop: DesktopFixture, sim: FixtureSim, - userData: string, - env: Record = {} -): Promise<{ app: ElectronApplication; window: Page }> { - const app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SHELL: '/bin/zsh', - ZDOTDIR: mkdtempSync(join(tmpdir(), 'sim-e2e-zdotdir-')), - SIM_DESKTOP_ORIGIN: sim.origin, - SIM_DESKTOP_USER_DATA: userData, - ...env, - }, + options: { userData?: string; env?: Record } = {} +): Promise { + const launched = await desktop.launch({ + origin: sim.origin, + userData: options.userData, + leaveDialogsToDesktop: true, + env: { SHELL: '/bin/zsh', ZDOTDIR: desktop.tempDir('sim-e2e-zdotdir-'), ...options.env }, }) - // A dialog listener stops Playwright auto-dismissing page dialogs, so the desktop's own handling - // decides their outcome exactly as it does in production. - const leaveDialogsToDesktop = (page: Page) => page.on('dialog', () => {}) - app.context().pages().forEach(leaveDialogsToDesktop) - app.context().on('page', leaveDialogsToDesktop) - const window = await app.firstWindow() + const window = await launched.app.firstWindow() await window.waitForURL((url) => url.origin === sim.origin, { waitUntil: 'load' }) - return { app, window } + return { ...launched, window } +} + +/** + * Where the executor's encrypted journal has a call: `started`, `result` once its result is kept + * for delivery, undefined once the call is forgotten (or before it was recorded). + */ +export function journalState(app: ElectronApplication, toolCallId: string): Promise { + return app.evaluate(({ safeStorage }, toolCallId) => { + const fs = process.getBuiltinModule('node:fs') + const path = `${process.env.SIM_DESKTOP_USER_DATA}/desktop-executor-journal.json` + if (!fs.existsSync(path)) return undefined + const envelope = JSON.parse(fs.readFileSync(path, 'utf8')) + const journal = JSON.parse( + safeStorage.decryptString(Buffer.from(envelope.ciphertext, 'base64')) + ) as { entries: { toolCallId: string; state: string }[] } + return journal.entries.find((entry) => entry.toolCallId === toolCallId)?.state + }, toolCallId) } /** The device this app registered, once it has opened its doorbell. */ diff --git a/apps/desktop/e2e/fixtures/worker-restart.config.ts b/apps/desktop/e2e/fixtures/worker-restart.config.ts deleted file mode 100644 index d0f0e3a8b2d..00000000000 --- a/apps/desktop/e2e/fixtures/worker-restart.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from '@playwright/test' - -/** Runs only the worker-restart fixture, for `check-report.spec.ts`. */ -export default defineConfig({ - testDir: '.', - testMatch: 'worker-restart.ts', - workers: 1, - retries: 0, - reporter: [['line']], -}) diff --git a/apps/desktop/e2e/fixtures/worker-restart.ts b/apps/desktop/e2e/fixtures/worker-restart.ts deleted file mode 100644 index 8a8c3921787..00000000000 --- a/apps/desktop/e2e/fixtures/worker-restart.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { expect, test } from '@playwright/test' -import { recordCheck } from '../check-report' - -/** - * Two checks in one file, the first failing, run by `check-report.spec.ts` in a Playwright run of - * its own. The failure makes Playwright start a new worker for the second, as it does mid-suite. - */ -const reportPath = process.env.WORKER_RESTART_REPORT_PATH - -function record(name: string, status: string): void { - recordCheck(reportPath, 'worker-restart', { - name, - status, - durationMs: 0, - error: `worker ${test.info().workerIndex}`, - }) -} - -test('fails first', () => { - record('fails first', 'failed') - expect('failed').toBe('passed') -}) - -test('passes after the worker restarts', () => { - record('passes after the worker restarts', 'passed') -}) diff --git a/apps/desktop/e2e/harness.ts b/apps/desktop/e2e/harness.ts new file mode 100644 index 00000000000..03d366a8c59 --- /dev/null +++ b/apps/desktop/e2e/harness.ts @@ -0,0 +1,515 @@ +/** + * Shared launch and teardown for the Electron E2E suite. + * + * Every spec launches the app through the `desktop` fixture, which tracks each app and temp + * directory a test creates and tears all of them down, even when the test fails midway. Closing is + * bounded: `ElectronApplication.close()` asks the app to quit and then waits for the process with + * no deadline, so a quit that a dialog or a cancelled `before-quit` blocks used to hang a test to + * its timeout and then hang the worker's own teardown. A quit that misses its deadline is a real + * bug (it is the same path as Cmd+Q), so the fixture records what the app was doing, kills it, and + * fails the test rather than hiding the stall. + */ +import { type ChildProcess, execFileSync } from 'node:child_process' +import { once } from 'node:events' +import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { + test as base, + type ElectronApplication, + _electron as electron, + expect, + type Page, + type TestInfo, +} from '@playwright/test' +import type { BrowserToolName } from '@sim/browser-protocol' +import type { SimDesktopApi } from '@sim/desktop-bridge' +import { type BuildOptions, build } from 'esbuild' +import postcss from 'postcss' +import loadPostcssConfig from 'postcss-load-config' + +export { expect } + +export const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) +export const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) + +/** Above the 5s an account teardown may legitimately hold `before-quit`. */ +const QUIT_DEADLINE_MS = 15_000 +const OUTPUT_TAIL_BYTES = 64 * 1024 + +export type DesktopBridge = typeof globalThis & { simDesktop: SimDesktopApi } + +type PanelHeartbeats = typeof globalThis & { simE2ePanelHeartbeats?: Record } + +/** Below the main process's 2.5s panel-bounds lease, which hides the panel once it lapses. */ +const PANEL_HEARTBEAT_MS = 500 + +export interface LaunchOptions { + origin: string + /** A profile to reuse, e.g. to relaunch on the same one. Defaults to a fresh temp profile. */ + userData?: string + /** Written to the profile's `settings.json` before launch; a string is written verbatim. */ + settings?: unknown + env?: Record + /** The app directory or main script. */ + main?: string + args?: string[] + /** + * Keeps Playwright from auto-dismissing page dialogs, so the desktop's own dialog handling + * decides them as it does in production. + */ + leaveDialogsToDesktop?: boolean +} + +export interface DesktopApp { + app: ElectronApplication + /** Captured at launch: `app.process()` throws once the app has quit or crashed. */ + child: ChildProcess + userData: string + /** The tail of the main process's stdout and stderr. */ + output(): string +} + +export interface DesktopFixture { + launch(options: LaunchOptions): Promise + /** Quits an app mid-test, under the same deadline as teardown. */ + close(desktop: DesktopApp): Promise + /** A temp directory removed after the test. */ + tempDir(prefix: string): string +} + +function hasExited(child: ChildProcess): boolean { + return child.exitCode !== null || child.signalCode !== null +} + +function captureOutput(child: ChildProcess): () => string { + let tail = '' + const append = (chunk: Buffer) => { + tail = (tail + chunk.toString('utf8')).slice(-OUTPUT_TAIL_BYTES) + } + child.stdout?.on('data', append) + child.stderr?.on('data', append) + return () => tail +} + +/** Everything that says why an app did not quit, gathered before it is killed. */ +async function quitStallDiagnostics(desktop: DesktopApp): Promise { + const pid = desktop.child.pid + const sections: string[] = [] + const windows = await Promise.race([ + desktop.app + .evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().map((win) => ({ + title: win.getTitle(), + url: win.webContents.getURL(), + visible: win.isVisible(), + })) + ) + .then((list) => JSON.stringify(list, null, 2)), + new Promise((resolve) => + setTimeout( + () => resolve('main process did not answer within 2s (its thread is blocked)'), + 2_000 + ) + ), + ]).catch((error: unknown) => `could not list windows: ${String(error)}`) + sections.push(`## Windows\n${windows}`) + if (process.platform === 'darwin' && pid !== undefined) { + try { + const stack = execFileSync('sample', [String(pid), '2'], { + encoding: 'utf8', + timeout: 15_000, + }) + sections.push(`## Main process sample\n${stack}`) + } catch (error) { + sections.push(`## Main process sample\nunavailable: ${String(error)}`) + } + } + sections.push(`## Main process output (tail)\n${desktop.output()}`) + try { + const log = readFileSync(join(desktop.userData, 'logs', 'desktop-events.log'), 'utf8') + sections.push(`## desktop-events.log (tail)\n${log.slice(-OUTPUT_TAIL_BYTES)}`) + } catch { + sections.push('## desktop-events.log\nnone') + } + return sections.join('\n\n') +} + +/** + * The processes that can still write a profile: Chromium's helpers stay in the app's process group + * (Playwright spawns it detached, so the group is its own), while Crashpad's handler starts its own + * session but names the profile on its command line. + */ +function profileWriters(appGroup: number, profilePaths: readonly string[]): number[] { + return execFileSync('ps', ['-axww', '-o', 'pid=,pgid=,command='], { encoding: 'utf8' }) + .split('\n') + .flatMap((line) => { + const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line) + if (!match) return [] + const [, pid, group, command] = match + return Number(group) === appGroup || profilePaths.some((path) => command.includes(path)) + ? [Number(pid)] + : [] + }) +} + +/** + * Kills whatever is left of an app and removes its profile once nothing can write to it: a helper + * or Crashpad's handler creating a file mid-removal fails it with ENOTEMPTY. + */ +export async function stopAndRemoveProfile(child: ChildProcess, userData: string): Promise { + if (!hasExited(child)) { + const exited = once(child, 'exit') + child.kill('SIGKILL') + await exited + } + if (child.pid !== undefined) { + const appGroup = child.pid + let profilePaths = [userData] + try { + profilePaths = [userData, realpathSync(userData)] + } catch {} + await expect + .poll(() => { + const writers = profileWriters(appGroup, profilePaths) + for (const pid of writers) { + try { + process.kill(pid, 'SIGKILL') + } catch {} + } + return writers + }) + .toEqual([]) + } + rmSync(userData, { recursive: true, force: true }) +} + +/** Launches the app against `options.origin` on `userData`, capturing its output. */ +async function launchDesktop(options: LaunchOptions & { userData: string }): Promise { + if (options.settings !== undefined) { + writeFileSync( + join(options.userData, 'settings.json'), + typeof options.settings === 'string' ? options.settings : JSON.stringify(options.settings) + ) + } + const app = await electron.launch({ + args: [options.main ?? '.', ...(options.args ?? [])], + cwd: DESKTOP_DIR, + env: { + ...process.env, + SIM_DESKTOP_ORIGIN: options.origin, + SIM_DESKTOP_USER_DATA: options.userData, + ...options.env, + }, + }) + const child = app.process() + const desktop: DesktopApp = { + app, + child, + userData: options.userData, + output: captureOutput(child), + } + if (options.leaveDialogsToDesktop) { + const leave = (page: Page) => page.on('dialog', () => {}) + app.context().pages().forEach(leave) + app.context().on('page', leave) + } + return desktop +} + +/** + * Quits an app through Playwright (the same `app.quit()` path as Cmd+Q). If it has not exited by + * the deadline, hands what it was doing to `report`, kills it, and throws. + */ +async function quitDesktop( + desktop: DesktopApp, + report: (diagnostics: string) => Promise | void +): Promise { + const { child } = desktop + if (hasExited(child)) return + const exited = once(child, 'exit') + // The exit event is the outcome; close() itself rejects once the process is gone. + void desktop.app.close().catch(() => {}) + let timer: NodeJS.Timeout | undefined + const quit = await Promise.race([ + exited.then(() => true), + new Promise((resolve) => { + timer = setTimeout(() => resolve(false), QUIT_DEADLINE_MS) + }), + ]) + clearTimeout(timer) + if (quit) return + try { + await report(await quitStallDiagnostics(desktop)) + } finally { + if (!hasExited(child) && child.pid !== undefined) { + try { + process.kill(-child.pid, 'SIGKILL') + } catch { + child.kill('SIGKILL') + } + await exited + } + } + throw new Error( + `Electron did not quit within ${QUIT_DEADLINE_MS / 1_000}s; see the electron-quit-stall diagnostics` + ) +} + +function closeDesktop(desktop: DesktopApp, testInfo: TestInfo): Promise { + return quitDesktop(desktop, (diagnostics) => + testInfo.attach('electron-quit-stall', { body: diagnostics, contentType: 'text/plain' }) + ) +} + +export const test = base.extend<{ desktop: DesktopFixture }>({ + desktop: [ + // biome-ignore lint/correctness/noEmptyPattern: Playwright reads a fixture's dependencies from this destructuring, and this one has none. + async ({}, use, testInfo) => { + const launched: DesktopApp[] = [] + const tempDirs: string[] = [] + const tempDir = (prefix: string) => { + const dir = mkdtempSync(join(tmpdir(), prefix)) + tempDirs.push(dir) + return dir + } + await use({ + tempDir, + async launch(options) { + const desktop = await launchDesktop({ + ...options, + userData: options.userData ?? tempDir('sim-desktop-e2e-profile-'), + }) + launched.push(desktop) + return desktop + }, + close: (desktop) => closeDesktop(desktop, testInfo), + }) + // Every app is closed and every directory removed even if an earlier one fails; the first + // failure is reported once the rest are cleaned up. + // Quit in parallel so several stalled apps still fit the teardown budget. + const failures: unknown[] = [] + for (const outcome of await Promise.allSettled( + launched.map((desktop) => closeDesktop(desktop, testInfo)) + )) { + if (outcome.status === 'rejected') failures.push(outcome.reason) + } + for (const desktop of launched) { + try { + await stopAndRemoveProfile(desktop.child, desktop.userData) + } catch (error) { + failures.push(error) + } + } + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }) + if (failures.length > 0) throw failures[0] + }, + // Teardown has its own budget, so a test that used up its time still gets cleaned up. + { timeout: 2 * QUIT_DEADLINE_MS + 30_000 }, + ], +}) + +export type FixtureHandler = ( + request: IncomingMessage, + response: ServerResponse, + url: URL +) => void | Promise + +export interface FixtureServer { + server: Server + /** `http://127.0.0.1:`. */ + origin: string + /** The same server as `http://localhost:`, a different site for cross-site checks. */ + site: string + close(): Promise +} + +/** An HTTP fixture on loopback only, closed with its open connections. */ +export async function serve(handler: FixtureHandler): Promise { + const server = createServer((request, response) => { + const url = new URL(request.url ?? '/', 'http://127.0.0.1') + // Through then(), so a handler that throws synchronously also answers 500. + Promise.resolve() + .then(() => handler(request, response, url)) + .catch((error: unknown) => { + if (!response.headersSent) response.writeHead(500) + response.end(String(error)) + }) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + const port = typeof address === 'object' && address ? address.port : 0 + return { + server, + origin: `http://127.0.0.1:${port}`, + site: `http://localhost:${port}`, + close: () => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + server.closeAllConnections() + }), + } +} + +/** Brings the app's first window to the front and waits until the OS reports it focused. */ +export async function focusFirstWindow(app: ElectronApplication): Promise { + await app.evaluate(({ app, BrowserWindow }) => { + const host = BrowserWindow.getAllWindows()[0] + host.webContents.setBackgroundThrottling(false) + app.focus({ steal: true }) + host.focus() + }) + await expect + .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused())) + .toBe(true) +} + +/** + * Activates a browser scope in the shell page and keeps the native browser panel below a `top` + * inset. The main process treats panel bounds as a lease that lapses after 2.5s, so the bounds are + * renewed on a heartbeat, the way Sim's panel renews them. Resolves once they reached main. + */ +export async function attachBrowserPanel(shell: Page, scope: string, top = 80): Promise { + await shell.evaluate( + async ({ scope, top, heartbeatMs }) => { + const api = (globalThis as DesktopBridge).simDesktop + const heartbeats = ((globalThis as PanelHeartbeats).simE2ePanelHeartbeats ??= {}) + clearInterval(heartbeats[scope]) + await api.browserAgent.activateScope(scope) + const updateBounds = () => + api.browserAgent.setPanelBounds( + { x: 0, y: top, width: innerWidth, height: innerHeight - top }, + null, + scope + ) + updateBounds() + heartbeats[scope] = window.setInterval(updateBounds, heartbeatMs) + // One renderer's IPC is handled in order, so this round trip lands after the bounds. + await api.browserAgent.activateScope(scope) + }, + { scope, top, heartbeatMs: PANEL_HEARTBEAT_MS } + ) +} + +/** Stops renewing a scope's panel bounds and takes the panel off screen, as Sim does on hide. */ +export async function hideBrowserPanel(shell: Page, scope: string): Promise { + await shell.evaluate(async (scope) => { + const api = (globalThis as DesktopBridge).simDesktop + clearInterval((globalThis as PanelHeartbeats).simE2ePanelHeartbeats?.[scope]) + api.browserAgent.setPanelBounds(null, null, scope) + await api.browserAgent.activateScope(scope) + }, scope) +} + +export interface SimFixtureBundle { + js: string + css: string +} + +/** + * Bundles a browser fixture built from apps/sim source, with apps/sim's stylesheet, so a spec can + * serve real Sim UI from its fixture server. `entry` is either a file or inline TSX resolved from + * apps/sim. + */ +export async function bundleSimFixture( + entry: { file: string } | { source: string }, + options: Pick & { + /** More files whose utility classes the stylesheet must include; a `file` entry is added. */ + sources?: string[] + } = {} +): Promise { + const bundle = await build({ + ...('file' in entry + ? { entryPoints: [entry.file] } + : { stdin: { contents: entry.source, resolveDir: SIM_DIR, loader: 'tsx' } }), + bundle: true, + write: false, + outdir: 'out', + jsx: 'automatic', + external: ['node:async_hooks', ...(options.external ?? [])], + inject: options.inject, + banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, + format: 'iife', + platform: 'browser', + tsconfig: join(SIM_DIR, 'tsconfig.json'), + define: { 'process.env.NODE_ENV': '"development"' }, + }) + const js = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text + if (js === undefined) throw new Error('The fixture bundle produced no JavaScript') + // Stylesheets the fixture imports (e.g. a package's own CSS) come out of esbuild separately. + const importedCss = bundle.outputFiles + .filter((file) => file.path.endsWith('.css')) + .map((file) => file.text) + .join('\n') + const config = await loadPostcssConfig({}, SIM_DIR) + const stylesheet = join(SIM_DIR, 'app/_styles/globals.css') + // A fixture's own utility classes are generated too, not only the ones Sim's sources use. + const scanFixture = [...('file' in entry ? [entry.file] : []), ...(options.sources ?? [])] + .map((source) => `\n@source ${JSON.stringify(source)};`) + .join('') + const css = await postcss(config.plugins).process( + `${readFileSync(stylesheet, 'utf8')}${scanFixture}`, + { from: stylesheet } + ) + return { js, css: `${css.css}\n${importedCss}` } +} + +export interface ToolCallAuthorization { + chatId: string + toolName: string + args: unknown +} + +/** + * Stands in for Sim's `/api/desktop/tool/authorize`: the desktop asks it before running a tool + * call, and it authorizes exactly the calls a test issued. + */ +export class ToolAuthorizer { + readonly calls = new Map() + private count = 0 + + constructor(private readonly prefix: string) {} + + /** Handles the authorize route; returns false for any other path. */ + async handle(request: IncomingMessage, response: ServerResponse, url: URL): Promise { + if (url.pathname !== '/api/desktop/tool/authorize') return false + let body = '' + for await (const chunk of request) body += chunk.toString() + const authorization = this.calls.get(JSON.parse(body).toolCallId) + response.writeHead(authorization ? 200 : 403, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify(authorization ?? {})) + return true + } + + /** Authorizes a new browser tool call and returns its id. */ + issue(scope: string, toolName: BrowserToolName, args: unknown): string { + const callId = `${this.prefix}-${++this.count}` + this.calls.set(callId, { chatId: scope, toolName, args }) + return callId + } + + /** Runs a browser tool from the shell page and returns its result, failing on a tool error. */ + async execute( + shell: Page, + scope: string, + toolName: BrowserToolName, + args: Record + ): Promise { + const callId = this.issue(scope, toolName, args) + const result = await shell.evaluate( + ({ callId, toolName, args, scope }) => + (globalThis as DesktopBridge).simDesktop.browserAgent.executeTool( + callId, + toolName, + args, + scope + ), + { callId, toolName, args, scope } + ) + expect(result.ok, result.error).toBe(true) + return result.result + } +} diff --git a/apps/desktop/e2e/local-files.spec.ts b/apps/desktop/e2e/local-files.spec.ts index ec2d10d6912..43e9a3e4fc9 100644 --- a/apps/desktop/e2e/local-files.spec.ts +++ b/apps/desktop/e2e/local-files.spec.ts @@ -1,6 +1,5 @@ import { mkdirSync, - mkdtempSync, readFileSync, realpathSync, renameSync, @@ -8,122 +7,156 @@ import { symlinkSync, writeFileSync, } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { DesktopLocalFileRequest, SimDesktopApi } from '@sim/desktop-bridge' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import type { ElectronApplication, Locator, Page } from '@playwright/test' +import type { + DesktopLocalFileRequest, + DesktopPreferences, + SimDesktopApi, +} from '@sim/desktop-bridge' import { answerShellDialog } from './executor-sim' +import { + test as base, + type DesktopApp, + type DesktopBridge, + expect, + focusFirstWindow, + serve, +} from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) - -test('native file tools remember folder consent across chats and restarts until revoked', async () => { - test.setTimeout(180_000) - const root = mkdtempSync(join(tmpdir(), 'sim-native-files-e2e-')) - const source = join(root, 'Reports') - const outside = join(root, 'Reports-other') - mkdirSync(outside) - writeFileSync(join(outside, 'private.txt'), 'outside contents') - mkdirSync(join(source, 'empty'), { recursive: true }) - writeFileSync(join(source, 'report.txt'), 'native file contents') - const png = - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Zl1sAAAAASUVORK5CYII=' - writeFileSync(join(source, 'image.png'), Buffer.from(png, 'base64')) - const claimed = new Set() - const expireAfterAuthorization = new Set() - let signedIn = true - const calls: Record< - string, - { toolName: string; args: Record; chatId?: string } | undefined - > = { - directory: { toolName: 'read_local_file', args: { path: source } }, - text: { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } }, - otherChat: { - toolName: 'read_local_file', - args: { path: join(source, 'report.txt') }, - chatId: 'other-chat', - }, - image: { toolName: 'read_local_file', args: { path: join(source, 'image.png') } }, - import: { - toolName: 'import_local_files', - args: { path: source, targetWorkspaceId: 'target-workspace' }, - }, +const PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9Zl1sAAAAASUVORK5CYII=' + +/** + * The app's own page stands in for Sim: a Forget button and a Full file access switch that drive + * the same bridge calls Sim's Desktop settings make (a real click supplies the user activation the + * setter requires), and the switch shows whatever the desktop last reported. + */ +const FIXTURE_PAGE = `Local file fixture

Local files

+ + + +` + +type LocalFileResponse = Awaited>> + +interface ToolCall { + toolName: 'read_local_file' | 'import_local_files' + args: Record + chatId?: string +} + +interface Session { + desktop: DesktopApp + app: ElectronApplication + window: Page + fullAccess: Locator + invoke(request: DesktopLocalFileRequest): Promise + /** Starts a request and resolves once its folder prompt is up. */ + requestPermission( + request: DesktopLocalFileRequest + ): Promise<{ prompt: Page; result: Promise }> + preferences(): Promise +} + +interface LocalFilesFixture { + root: string + /** `Reports`: report.txt, image.png, and an empty subfolder. */ + source: string + /** `Reports-other`, a sibling holding private.txt that no call is meant to reach. */ + outside: string + /** The calls the fixture Sim authorizes, by tool call id; any other id is refused. */ + calls: Record + /** Calls Sim refuses after their first authorization, as it does once a call has ended. */ + expireAfterAuthorization: Set + origin: string + signIn(): void + /** Launches the app, on `userData` when relaunching the same profile. */ + open(userData?: string): Promise + close(session: Session): Promise +} + +type FsPatchRuntime = typeof globalThis & { + e2eFsPatch?: { fired: string[]; restore(): void | Promise } +} + +/** Undoes a step's fs/promises patch in the main process and returns the race actions that ran. */ +async function restoreFsPatch(app: ElectronApplication): Promise { + return app.evaluate(async () => { + const runtime = globalThis as FsPatchRuntime + const patch = runtime.e2eFsPatch + runtime.e2eFsPatch = undefined + await patch?.restore() + return patch?.fired ?? [] + }) +} + +const test = base.extend<{ localFiles: LocalFilesFixture }>({ + localFiles: async ({ desktop }, use) => { + const root = desktop.tempDir('sim-native-files-e2e-') + const source = join(root, 'Reports') + const outside = join(root, 'Reports-other') + mkdirSync(outside) + writeFileSync(join(outside, 'private.txt'), 'outside contents') + mkdirSync(join(source, 'empty'), { recursive: true }) + writeFileSync(join(source, 'report.txt'), 'native file contents') + writeFileSync(join(source, 'image.png'), Buffer.from(PNG, 'base64')) + const claimed = new Set() + const expireAfterAuthorization = new Set() + let signedIn = true + const calls: Record = { + directory: { toolName: 'read_local_file', args: { path: source } }, + text: { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } }, + otherChat: { + toolName: 'read_local_file', + args: { path: join(source, 'report.txt') }, + chatId: 'other-chat', + }, + image: { toolName: 'read_local_file', args: { path: join(source, 'image.png') } }, + import: { + toolName: 'import_local_files', + args: { path: source, targetWorkspaceId: 'target-workspace' }, + }, + } + const server = await serve(async (request, response, url) => { + if (url.pathname === '/api/auth/get-session') { + response + .writeHead(200, { 'Content-Type': 'application/json' }) + .end( + JSON.stringify( + signedIn + ? { user: { id: 'local-file-user' }, session: { id: 'local-file-session' } } + : null + ) ) - ) return } - if (path === '/api/auth/sign-out') { + if (url.pathname === '/api/auth/sign-out') { signedIn = false response .writeHead(200, { @@ -133,7 +166,7 @@ createRoot(document.getElementById('settings')).render( .end('{}') return } - if (path === '/api/desktop/tool/authorize') { + if (url.pathname === '/api/desktop/tool/authorize') { let body = '' for await (const chunk of request) body += chunk.toString() const input = JSON.parse(body) @@ -159,827 +192,833 @@ createRoot(document.getElementById('settings')).render( ? { 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/' } : {}), }) - .end(`Local file fixture

Local files

- -
`) + .end(FIXTURE_PAGE) }) - await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - const launch = () => - electron.launch({ - args: ['.', '--use-mock-keychain'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: join(root, 'profile'), - }, + const sessions: Session[] = [] + + const open = async (userData?: string): Promise => { + const launched = await desktop.launch({ + origin: server.origin, + userData, + args: ['--use-mock-keychain'], }) - app = await launch() - let window = await app.firstWindow() - await app.evaluate(({ app, BrowserWindow }) => { - const host = BrowserWindow.getAllWindows()[0] - if (!host) throw new Error('Missing host window') - host.webContents.setBackgroundThrottling(false) - app.focus({ steal: true }) - host.focus() - }) - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - const invoke = (input: DesktopLocalFileRequest) => - window.evaluate(async (request) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - if (!api.localFiles) throw new Error('Native file bridge missing') - return api.localFiles(request) - }, input) - await expect - .poll(() => - window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return (await api.localFilesystem?.({ operation: 'list_mounts' }))?.ok + const { app } = launched + const window = await app.firstWindow() + await focusFirstWindow(app) + await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toBeVisible() + const invoke = (request: DesktopLocalFileRequest) => + window.evaluate(async (input) => { + const api = (globalThis as DesktopBridge).simDesktop + if (!api.localFiles) throw new Error('Native file bridge missing') + return api.localFiles(input) + }, request) + await expect + .poll(() => + window.evaluate( + async () => + ( + await (globalThis as DesktopBridge).simDesktop.localFilesystem?.({ + operation: 'list_mounts', + }) + )?.ok + ) + ) + .toBe(true) + if (userData === undefined) { + await window.evaluate(async () => { + const settings = (globalThis as DesktopBridge).simDesktop.settings + await settings.setPreference('browserEnabled', false) + await settings.setPreference('terminalEnabled', false) }) - ) - .toBe(true) - await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.settings.setPreference('browserEnabled', false) - await api.settings.setPreference('terminalEnabled', false) + } + const session: Session = { + desktop: launched, + app, + window, + fullAccess: window.getByRole('switch', { name: 'Full file access', exact: true }), + invoke, + async requestPermission(request) { + const shown = app.waitForEvent('window', { timeout: 10_000 }) + const result = invoke(request) + void result.catch(() => {}) + const prompt = await shown + await expect( + prompt.getByRole('button', { name: "Don't allow", exact: true }) + ).toBeVisible() + return { prompt, result } + }, + preferences: () => + window.evaluate(() => (globalThis as DesktopBridge).simDesktop.settings.getPreferences()), + } + sessions.push(session) + return session + } + + await use({ + root, + source, + outside, + calls, + expireAfterAuthorization, + origin: server.origin, + signIn: () => { + signedIn = true + }, + open, + close: (session) => desktop.close(session.desktop), }) - const deniedPrompt = app.waitForEvent('window', { timeout: 10_000 }) - const deniedReads = ['text', 'otherChat'].map((toolCallId) => + // The apps quit while their server still answers, as they would against a live Sim. + try { + for (const session of sessions) await desktop.close(session.desktop) + } finally { + await server.close() + } + }, +}) + +test('folder consent is asked once per folder, shared across chats, and bound to the authorized call', async ({ + localFiles, +}) => { + const { root, source, outside, calls, expireAfterAuthorization } = localFiles + const { app, window, invoke, requestPermission } = await localFiles.open() + + await test.step('declining consent fails every read waiting on that folder', async () => { + const shown = app.waitForEvent('window', { timeout: 10_000 }) + const reads = ['text', 'otherChat'].map((toolCallId) => invoke({ operation: 'read', toolCallId }) ) - const deniedResults: unknown[] = [] - for (const read of deniedReads) - void read.then((result) => deniedResults.push(result)).catch(() => {}) - const denial = await deniedPrompt + for (const read of reads) void read.catch(() => {}) + const denial = await shown await expect(denial.getByRole('button', { name: "Don't allow", exact: true })).toBeFocused() - await denial.screenshot({ - path: - process.env.DESKTOP_LOCAL_FILES_REPORT_PATH ?? - test.info().outputPath('local-file-consent.png'), - }) await answerShellDialog(denial, "Don't allow") - await expect.poll(() => deniedResults.length).toBe(2) - expect(deniedResults).toEqual([ + expect(await Promise.all(reads)).toEqual([ { ok: false, error: expect.any(String) }, { ok: false, error: expect.any(String) }, ]) + }) - const folderPrompt = app.waitForEvent('window') + await test.step('an allowed folder serves the queued read, the authorized path, and images', async () => { + const shown = app.waitForEvent('window') const folderRead = invoke({ operation: 'read', toolCallId: 'directory' }) void folderRead.catch(() => {}) - const folderConsent = await folderPrompt + const consent = await shown const queuedRead = invoke({ operation: 'read', toolCallId: 'text' }) void queuedRead.catch(() => {}) - await expect( - folderConsent.getByRole('button', { name: 'Allow folder', exact: true }) - ).toBeVisible() + await expect(consent.getByRole('button', { name: 'Allow folder', exact: true })).toBeVisible() expect( - await folderConsent.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop) + await consent.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop) ).toBe('undefined') - await answerShellDialog(folderConsent, 'Allow folder') + await answerShellDialog(consent, 'Allow folder') expect(await folderRead).toMatchObject({ ok: true, data: { representation: 'directory' } }) expect(await queuedRead).toMatchObject({ ok: true, data: { text: 'native file contents' } }) - const canonicalRequest = { + // The renderer's path is ignored: Sim's authorized arguments decide what is read. + const redirected = { operation: 'read' as const, toolCallId: 'text', path: join(outside, 'private.txt'), } - expect(await invoke(canonicalRequest)).toMatchObject({ + expect(await invoke(redirected)).toMatchObject({ ok: true, data: { representation: 'text', text: 'native file contents' }, }) expect(await invoke({ operation: 'read', toolCallId: 'image' })).toMatchObject({ ok: true, - data: { observations: [{ mediaType: 'image/png', data: png }] }, + data: { observations: [{ mediaType: 'image/png', data: PNG }] }, }) - const requestPermission = async (request: DesktopLocalFileRequest) => { - if (!app) throw new Error('Desktop app is not running') - const shown = app.waitForEvent('window', { timeout: 10_000 }) - const result = invoke(request) - void result.catch(() => {}) - const prompt = await shown - await expect(prompt.getByRole('button', { name: "Don't allow", exact: true })).toBeVisible() - return { prompt, result } + }) + + await test.step('a folder grant works in another chat but does not permit symlink escapes', async () => { + expect(await invoke({ operation: 'read', toolCallId: 'otherChat' })).toMatchObject({ + ok: true, + data: { text: 'native file contents' }, + }) + writeFileSync(join(source, 'empty', 'new.txt'), 'new file in a subfolder') + calls.nested = { + toolName: 'read_local_file', + args: { path: join(source, 'empty', 'new.txt') }, + chatId: 'another-chat', } - await test.step('File → Folder Access opens over a focused utility window', async () => { - if (!app) throw new Error('Desktop app is not running') - const serverShown = app.waitForEvent('window', { timeout: 10_000 }) - await app.evaluate(({ Menu }) => { - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Server…') - if (!item) throw new Error('Server menu item missing') - item.click() - }) - await expect(await serverShown).toHaveTitle('Sim - Server') - await expect - .poll(() => - app?.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some( - (win) => win.webContents.getURL().endsWith('server.html') && win.isVisible() - ) - ) - ) - .toBe(true) - const accessMenu = await app.evaluate(({ BrowserWindow, Menu }) => { - const utility = BrowserWindow.getAllWindows().find((win) => - win.webContents.getURL().endsWith('server.html') - ) - if (!utility) throw new Error('Server window missing') - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Folder Access…') - if (!item) throw new Error('Folder Access menu item missing') - const popup = Menu.prototype.popup - let shown: { anchoredToUtility: boolean; items: string[] } | undefined - Menu.prototype.popup = function (this: Electron.Menu, options) { - shown = { - anchoredToUtility: options?.window === utility, - items: this.items.map((entry) => entry.label), - } - } - try { - item.click(undefined, utility) - } finally { - Menu.prototype.popup = popup - } - utility.close() - return shown - }) - expect(accessMenu?.anchoredToUtility).toBe(true) - expect(accessMenu?.items).toContain('Add Folder…') + expect(await invoke({ operation: 'read', toolCallId: 'nested' })).toMatchObject({ + ok: true, + data: { text: 'new file in a subfolder' }, }) + rmSync(join(source, 'empty', 'new.txt')) + symlinkSync(join(outside, 'private.txt'), join(source, 'linked.txt')) + calls.escape = { toolName: 'read_local_file', args: { path: join(source, 'linked.txt') } } + const escaped = await requestPermission({ operation: 'read', toolCallId: 'escape' }) + await expect(escaped.prompt.getByRole('dialog')).toContainText( + JSON.stringify(realpathSync(outside)) + ) + await answerShellDialog(escaped.prompt, "Don't allow") + expect(await escaped.result).toMatchObject({ ok: false }) + rmSync(join(source, 'linked.txt')) + }) - await test.step('Stop cancels only its own request while chats share a folder prompt', async () => { - const sharedFolder = join(root, 'Shared') - mkdirSync(sharedFolder) - writeFileSync(join(sharedFolder, 'shared.txt'), 'shared contents') - for (const toolCallId of ['sharedLeader', 'sharedFollower', 'sharedSurvivor']) { - calls[toolCallId] = { - toolName: 'read_local_file', - args: { path: join(sharedFolder, 'shared.txt') }, - chatId: toolCallId, - } + await test.step('cancelled calls and changed arguments cannot acquire a grant', async () => { + for (const changed of [false, true]) { + calls.stale = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } + const stale = await requestPermission({ operation: 'read', toolCallId: 'stale' }) + if (changed) calls.stale.args.path = join(source, 'report.txt') + else calls.stale = undefined + await answerShellDialog(stale.prompt, 'Allow folder') + expect(await stale.result).toMatchObject({ ok: false }) + } + }) + + await test.step('Stop cancels only its own request while chats share a folder prompt', async () => { + const sharedFolder = join(root, 'Shared') + mkdirSync(sharedFolder) + writeFileSync(join(sharedFolder, 'shared.txt'), 'shared contents') + for (const toolCallId of ['sharedLeader', 'sharedFollower', 'sharedSurvivor']) { + calls[toolCallId] = { + toolName: 'read_local_file', + args: { path: join(sharedFolder, 'shared.txt') }, + chatId: toolCallId, } - const leader = await requestPermission({ operation: 'read', toolCallId: 'sharedLeader' }) - let followerResult: unknown - const follower = invoke({ operation: 'read', toolCallId: 'sharedFollower' }).then( - (result) => { - followerResult = result + } + // A request joins the pending prompt in the same turn its stat of the file settles, so the + // count of those stats says how many requests share the prompt. Sim's authorization lands + // before that, which is why it cannot stand in for the join. + await app.evaluate( + (_electron, file) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const original = fs.stat + const fired: string[] = [] + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.stat = original + }, } - ) + fs.stat = (async (...args: Parameters) => { + const result = await original(...args) + if (args[0] === file) fired.push('joined') + return result + }) as typeof fs.stat + }, + realpathSync(join(sharedFolder, 'shared.txt')) + ) + const joined = () => + app.evaluate(() => (globalThis as FsPatchRuntime).e2eFsPatch?.fired.length ?? 0) + try { + const leader = await requestPermission({ operation: 'read', toolCallId: 'sharedLeader' }) + expect(await joined()).toBe(1) + const follower = invoke({ operation: 'read', toolCallId: 'sharedFollower' }) void follower.catch(() => {}) - await expect.poll(() => claimed.has('sharedFollower')).toBe(true) - await leader.prompt.getByRole('dialog').hover() + await expect.poll(joined).toBe(2) await invoke({ operation: 'cancel', toolCallId: 'sharedFollower' }) - await expect.poll(() => followerResult).toMatchObject({ ok: false }) - await follower - await expect(leader.prompt.getByRole('dialog')).toBeVisible() + expect(await follower).toMatchObject({ ok: false }) const survivor = invoke({ operation: 'read', toolCallId: 'sharedSurvivor' }) void survivor.catch(() => {}) - await expect.poll(() => claimed.has('sharedSurvivor')).toBe(true) - await leader.prompt.getByRole('dialog').hover() + await expect.poll(joined).toBe(3) await invoke({ operation: 'cancel', toolCallId: 'sharedLeader' }) expect(await leader.result).toMatchObject({ ok: false }) - await expect(leader.prompt.getByRole('dialog')).toBeVisible() + // The leader's own prompt is still the one to answer: neither cancel closed it. await answerShellDialog(leader.prompt, 'Allow folder') expect(await survivor).toMatchObject({ ok: true, data: { text: 'shared contents' } }) + } finally { + await restoreFsPatch(app) + } + }) + + await test.step('cancelling in the renderer closes consent without remembering access', async () => { + calls.cancelled = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } + const cancelled = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) + const closed = cancelled.prompt.waitForEvent('close') + await invoke({ operation: 'cancel', toolCallId: 'cancelled' }) + await closed + expect(await cancelled.result).toMatchObject({ ok: false }) + const again = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) + await answerShellDialog(again.prompt, "Don't allow") + expect(await again.result).toMatchObject({ ok: false }) + }) + + await test.step('consent escapes direction controls in folder names', async () => { + const folder = join(root, 'Bidi؜‎‏') + mkdirSync(folder) + calls.bidi = { toolName: 'read_local_file', args: { path: folder } } + const bidi = await requestPermission({ operation: 'read', toolCallId: 'bidi' }) + await expect(bidi.prompt.getByRole('dialog')).toContainText('Bidi\\u061c\\u200e\\u200f') + await answerShellDialog(bidi.prompt, "Don't allow") + expect(await bidi.result).toMatchObject({ ok: false }) + }) + + await test.step('an unanswered prompt does not block approved folders', async () => { + calls.blocker = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } + const blocker = await requestPermission({ operation: 'read', toolCallId: 'blocker' }) + expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: true }) + await answerShellDialog(blocker.prompt, "Don't allow") + expect(await blocker.result).toMatchObject({ ok: false }) + }) + + await test.step('a call that ended after authorization cannot use an approved folder', async () => { + calls.expired = { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } } + expireAfterAuthorization.add('expired') + expect(await invoke({ operation: 'read', toolCallId: 'expired' })).toMatchObject({ ok: false }) + }) + + await test.step('replacing the proposed folder during consent does not expose its new target', async () => { + const proposed = join(root, 'Proposed') + mkdirSync(proposed) + calls.retargeted = { toolName: 'read_local_file', args: { path: proposed } } + const retargeted = await requestPermission({ operation: 'read', toolCallId: 'retargeted' }) + renameSync(proposed, join(root, 'Original')) + mkdirSync(proposed) + writeFileSync(join(proposed, 'unapproved.txt'), 'replacement folder contents') + await answerShellDialog(retargeted.prompt, 'Allow folder') + expect(await retargeted.result).toMatchObject({ ok: false }) + }) + + await test.step('an approved folder imports once per call and to any destination without prompting', async () => { + const manifest = await invoke({ operation: 'manifest', toolCallId: 'import' }) + if (!manifest.ok || manifest.data.kind !== 'manifest') throw new Error(JSON.stringify(manifest)) + expect(manifest.data.targetWorkspaceId).toBe('target-workspace') + expect(manifest.data.entries.map((entry) => entry.relativePath)).toEqual([ + '', + 'empty', + 'image.png', + 'report.txt', + ]) + const file = manifest.data.entries.find((entry) => entry.relativePath === 'report.txt') + if (!file) throw new Error('Missing import file') + const chunkRequest = { + operation: 'chunk' as const, + toolCallId: 'import', + relativePath: file.relativePath, + revision: file.revision, + offset: 0, + } + const chunk = await invoke(chunkRequest) + if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error(JSON.stringify(chunk)) + expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('native file contents')]) + expect(chunk.data.eof).toBe(true) + // The bytes cross the bridge in a form the renderer can upload as a File. + expect( + await window.evaluate(async (input) => { + const response = await (globalThis as DesktopBridge).simDesktop.localFiles?.(input) + if (!response?.ok || response.data.kind !== 'chunk') throw new Error('Missing native chunk') + return new File([new Uint8Array(response.data.bytes)], 'report.txt').text() + }, chunkRequest) + ).toBe('native file contents') + expect(await invoke({ operation: 'manifest', toolCallId: 'import' })).toMatchObject({ + ok: false, + code: 'ALREADY_STARTED', }) - await test.step('expired requests cannot enable Full file access from a confirmation', async () => { - if (!app) throw new Error('Desktop app is not running') - calls.expiringFullAccess = { - toolName: 'read_local_file', - args: { path: join(outside, 'private.txt') }, - } - const permission = await requestPermission({ - operation: 'read', - toolCallId: 'expiringFullAccess', - }) - const shown = app.waitForEvent('window') - await answerShellDialog(permission.prompt, 'Full file access') - const confirmation = await shown - calls.expiringFullAccess = undefined - await answerShellDialog(confirmation, 'Enable') - expect(await permission.result).toMatchObject({ ok: false }) - expect( - await window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ).toMatchObject({ fullFileAccess: false }) + calls.otherImport = { + toolName: 'import_local_files', + args: { path: source, targetWorkspaceId: 'other-workspace' }, + } + expect(await invoke({ operation: 'manifest', toolCallId: 'otherImport' })).toMatchObject({ + ok: true, }) - await test.step('Full file access is opt-in, survives restart, and stops granting access when disabled', async () => { - if (!app) throw new Error('Desktop app is not running') - const fullFolder = join(root, 'Full access') - mkdirSync(fullFolder) - writeFileSync(join(fullFolder, 'file.txt'), 'full access contents') - calls.fullAccess = { - toolName: 'read_local_file', - args: { path: join(fullFolder, 'file.txt') }, - } - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).not.toBeChecked() - const permission = await requestPermission({ operation: 'read', toolCallId: 'fullAccess' }) - const confirmationShown = app.waitForEvent('window') - await answerShellDialog(permission.prompt, 'Full file access') - const confirmation = await confirmationShown - await expect(confirmation.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused() - const returnedPrompt = app.waitForEvent('window') - await answerShellDialog(confirmation, 'Cancel') - const folderPrompt = await returnedPrompt - expect( - await window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ).toMatchObject({ fullFileAccess: false }) - const acceptedConfirmation = app.waitForEvent('window') - await answerShellDialog(folderPrompt, 'Full file access') - const allowAll = await acceptedConfirmation - await allowAll.screenshot({ - path: test.info().outputPath('full-file-access-confirmation.png'), - }) - await answerShellDialog(allowAll, 'Enable') - expect(await permission.result).toMatchObject({ - ok: true, - data: { text: 'full access contents' }, - }) - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeChecked() - expect(await invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ - ok: true, - data: { text: 'full access contents' }, - }) - calls.fullImport = { - toolName: 'import_local_files', - args: { path: fullFolder, targetWorkspaceId: 'target-workspace' }, - } - const manifest = await invoke({ operation: 'manifest', toolCallId: 'fullImport' }) - if (!manifest.ok || manifest.data.kind !== 'manifest') - throw new Error('Missing full-access manifest') - const imported = manifest.data.entries.find((entry) => entry.relativePath === 'file.txt') - if (!imported) throw new Error('Missing full-access file') - const chunk = await invoke({ - operation: 'chunk', - toolCallId: 'fullImport', - relativePath: imported.relativePath, - revision: imported.revision, - offset: 0, - }) - if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error('Missing full-access contents') - expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('full access contents')]) - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeChecked() - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeEnabled() - await window.screenshot({ - path: test.info().outputPath('desktop-settings-full-access.png'), - animations: 'disabled', - }) - await window.evaluate(() => document.documentElement.classList.add('dark')) - await window.screenshot({ - path: test.info().outputPath('desktop-settings-full-access-dark.png'), - animations: 'disabled', - }) - await window.evaluate(() => document.documentElement.classList.remove('dark')) - expect(await invoke({ operation: 'read', toolCallId: 'notAuthorized' })).toMatchObject({ - ok: false, - }) - await app?.close() - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - await expect - .poll(() => - window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() + }) + + await test.step('File → Folder Access opens over a focused utility window', async () => { + const serverShown = app.waitForEvent('window', { timeout: 10_000 }) + await app.evaluate(({ Menu }) => { + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Server…') + if (!item) throw new Error('Server menu item missing') + item.click() + }) + await expect(await serverShown).toHaveTitle('Sim - Server') + await expect + .poll(() => + app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some( + (win) => win.webContents.getURL().endsWith('server.html') && win.isVisible() ) ) - .toMatchObject({ fullFileAccess: true }) - expect(await invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ - ok: true, - data: { text: 'full access contents' }, - }) - await window.getByRole('switch', { name: 'Full file access', exact: true }).click() - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).not.toBeChecked() - const revoked = await requestPermission({ operation: 'read', toolCallId: 'fullAccess' }) - await answerShellDialog(revoked.prompt, "Don't allow") - expect(await revoked.result).toMatchObject({ ok: false }) - }) - await test.step('a folder grant works in another chat but does not permit symlink escapes', async () => { - expect(await invoke({ operation: 'read', toolCallId: 'otherChat' })).toMatchObject({ - ok: true, - data: { text: 'native file contents' }, - }) - writeFileSync(join(source, 'empty', 'new.txt'), 'new file in a subfolder') - calls.nested = { - toolName: 'read_local_file', - args: { path: join(source, 'empty', 'new.txt') }, - chatId: 'another-chat', - } - expect(await invoke({ operation: 'read', toolCallId: 'nested' })).toMatchObject({ - ok: true, - data: { text: 'new file in a subfolder' }, - }) - rmSync(join(source, 'empty', 'new.txt')) - symlinkSync(join(outside, 'private.txt'), join(source, 'linked.txt')) - calls.escape = { toolName: 'read_local_file', args: { path: join(source, 'linked.txt') } } - const escapedRead = await requestPermission({ operation: 'read', toolCallId: 'escape' }) - await expect(escapedRead.prompt.getByRole('dialog')).toContainText( - JSON.stringify(realpathSync(outside)) ) - await answerShellDialog(escapedRead.prompt, "Don't allow") - expect(await escapedRead.result).toMatchObject({ ok: false }) - rmSync(join(source, 'linked.txt')) - }) - await test.step('cancelled calls and changed arguments cannot acquire a grant', async () => { - for (const changed of [false, true]) { - calls.stale = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } - const stale = await requestPermission({ operation: 'read', toolCallId: 'stale' }) - if (changed) calls.stale.args.path = join(source, 'report.txt') - else calls.stale = undefined - await answerShellDialog(stale.prompt, 'Allow folder') - expect(await stale.result).toMatchObject({ ok: false }) + .toBe(true) + const accessMenu = await app.evaluate(({ BrowserWindow, Menu }) => { + const utility = BrowserWindow.getAllWindows().find((win) => + win.webContents.getURL().endsWith('server.html') + ) + if (!utility) throw new Error('Server window missing') + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Folder Access…') + if (!item) throw new Error('Folder Access menu item missing') + const popup = Menu.prototype.popup + let shown: { anchoredToUtility: boolean; items: string[] } | undefined + Menu.prototype.popup = function (this: Electron.Menu, options) { + shown = { + anchoredToUtility: options?.window === utility, + items: this.items.map((entry) => entry.label), + } } - }) - await test.step('native traversal rejects redirected ancestors and replaced grant identities', async () => { - const parent = join(realpathSync(source), 'native-parent') - mkdirSync(parent) - writeFileSync(join(parent, 'inside.txt'), 'inside') - const linked = join(realpathSync(source), 'native-link') - symlinkSync(outside, linked) try { - const result = await app?.evaluate( - async ({ app }, paths) => { - const { createRequire } = process.getBuiltinModule('node:module') - const { stat } = process.getBuiltinModule('node:fs/promises') - const fs = process.getBuiltinModule('node:fs') - const native = createRequire(`${app.getAppPath()}/package.json`)( - './dist/native/directory.node' - ) as { - openApproved( - root: string, - relative: string, - dev: bigint, - ino: bigint, - directory: boolean - ): Promise - } - const root = await stat(paths.source, { bigint: true }) - const denied = async (path: string, ino = root.ino) => { - try { - const fd = await native.openApproved(paths.source, path, root.dev, ino, false) - fs.closeSync(fd) - return false - } catch { - return true - } - } - const valid = await native.openApproved( - paths.source, - 'native-parent/inside.txt', - root.dev, - root.ino, - false - ) - const text = fs.readFileSync(valid, 'utf8') - fs.closeSync(valid) - return { - text, - ancestor: await denied('native-link/private.txt'), - traversal: await denied('../Reports-other/private.txt'), - replaced: await denied('native-parent/inside.txt', root.ino + 1n), - overflow: await denied('native-parent/inside.txt', root.ino + (1n << 64n)), - } - }, - { source: realpathSync(source) } - ) - expect(result).toEqual({ - text: 'inside', - ancestor: true, - traversal: true, - replaced: true, - overflow: true, - }) + item.click(undefined, utility) } finally { - rmSync(linked) - rmSync(parent, { recursive: true }) + Menu.prototype.popup = popup } + utility.close() + return shown }) - await test.step('a symlink replacement cannot redirect an inspected file', async () => { - const file = realpathSync(join(source, 'report.txt')) - const backup = join(source, 'original-report.txt') - const other = join(source, 'other.txt') - writeFileSync(other, 'different file contents') - await app?.evaluate( - (_electron, paths) => { - const fs = process.getBuiltinModule( - 'node:fs/promises' - ) as typeof import('node:fs/promises') - const original = fs.stat - fs.stat = (async (...args: Parameters) => { - const result = await original(...args) - if (args[0] === paths.file) { - fs.stat = original - await fs.rename(paths.file, paths.backup) - await fs.symlink(paths.other, paths.file) - } - return result - }) as typeof fs.stat - }, - { file, backup, other } - ) - try { - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: false }) - } finally { - rmSync(file) - renameSync(backup, file) - rmSync(other) - } + expect(accessMenu?.anchoredToUtility).toBe(true) + expect(accessMenu?.items).toContain('Add Folder…') + }) +}) + +test('Full file access is opt-in, survives restart, turns off cleanly, and fails closed when it cannot be saved', async ({ + localFiles, +}) => { + const { root, outside, calls } = localFiles + let session = await localFiles.open() + const fullFolder = join(root, 'Full access') + mkdirSync(fullFolder) + writeFileSync(join(fullFolder, 'file.txt'), 'full access contents') + calls.fullAccess = { toolName: 'read_local_file', args: { path: join(fullFolder, 'file.txt') } } + + await test.step('a request that ended cannot enable Full file access from its confirmation', async () => { + calls.expiringFullAccess = { + toolName: 'read_local_file', + args: { path: join(outside, 'private.txt') }, + } + const permission = await session.requestPermission({ + operation: 'read', + toolCallId: 'expiringFullAccess', }) - await test.step('swapping an ancestor cannot redirect directory enumeration', async () => { - const parent = join(realpathSync(source), 'parent') - const child = join(parent, 'child') - const backup = join(realpathSync(source), 'parent-backup') - const otherParent = join(outside, 'parent') - mkdirSync(child, { recursive: true }) - mkdirSync(join(otherParent, 'child'), { recursive: true }) - writeFileSync(join(child, 'allowed.txt'), 'allowed') - writeFileSync(join(otherParent, 'child', 'private.txt'), 'outside') - calls.ancestorRace = { toolName: 'read_local_file', args: { path: child } } - await app?.evaluate( - (_electron, paths) => { - const fs = process.getBuiltinModule( - 'node:fs/promises' - ) as typeof import('node:fs/promises') - const originalStat = fs.lstat - const originalRealpath = fs.realpath - let swapped = false - const restore = async () => { - fs.lstat = originalStat - fs.realpath = originalRealpath - if (swapped) { - await fs.rm(paths.parent) - await fs.rename(paths.backup, paths.parent) - swapped = false - } - } - ;( - globalThis as typeof globalThis & { restoreLocalFileRace?: () => Promise } - ).restoreLocalFileRace = restore - fs.lstat = (async (...args: Parameters) => { - const result = await originalStat(...args) - if (args[0] === paths.child) { - fs.lstat = originalStat - await fs.rename(paths.parent, paths.backup) - await fs.symlink(paths.otherParent, paths.parent) - swapped = true - } - return result - }) as typeof fs.lstat - fs.realpath = (async (...args: Parameters) => { - if (swapped && args[0] === paths.child) await restore() - return originalRealpath(...args) - }) as typeof fs.realpath - }, - { parent, child, backup, otherParent } - ) - try { - expect(await invoke({ operation: 'read', toolCallId: 'ancestorRace' })).toMatchObject({ - ok: true, - data: { entries: [{ name: 'allowed.txt', kind: 'file' }] }, - }) - } finally { - await app?.evaluate(async () => { - const runtime = globalThis as typeof globalThis & { - restoreLocalFileRace?: () => Promise - } - await runtime.restoreLocalFileRace?.() - runtime.restoreLocalFileRace = undefined - }) - rmSync(parent, { recursive: true, force: true }) - rmSync(otherParent, { recursive: true, force: true }) - } + const shown = session.app.waitForEvent('window') + await answerShellDialog(permission.prompt, 'Full file access') + const confirmation = await shown + calls.expiringFullAccess = undefined + await answerShellDialog(confirmation, 'Enable') + expect(await permission.result).toMatchObject({ ok: false }) + expect(await session.preferences()).toMatchObject({ fullFileAccess: false }) + }) + + await test.step('Cancel on the confirmation returns to the folder prompt, and Enable reaches every folder', async () => { + const { app, invoke, fullAccess } = session + await expect(fullAccess).not.toBeChecked() + const permission = await session.requestPermission({ + operation: 'read', + toolCallId: 'fullAccess', }) - await test.step('a replaced directory cannot return a listing for its old contents', async () => { - const directory = join(realpathSync(source), 'replace-during-read') - const backup = join(realpathSync(source), 'previous-directory') - mkdirSync(directory) - writeFileSync(join(directory, 'old.txt'), 'old contents') - calls.directoryReplaced = { toolName: 'read_local_file', args: { path: directory } } - await app?.evaluate( - (_electron, paths) => { - const fs = process.getBuiltinModule( - 'node:fs/promises' - ) as typeof import('node:fs/promises') - const original = fs.lstat - fs.lstat = (async (...args: Parameters) => { - if (args[0] === paths.directory) { - fs.lstat = original - await fs.rename(paths.directory, paths.backup) - await fs.mkdir(paths.directory) - await fs.writeFile(`${paths.directory}/new.txt`, 'new contents') - } - return original(...args) - }) as typeof fs.lstat - }, - { directory, backup } - ) + const confirmationShown = app.waitForEvent('window') + await answerShellDialog(permission.prompt, 'Full file access') + const confirmation = await confirmationShown + await expect(confirmation.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused() + const returnedPrompt = app.waitForEvent('window') + await answerShellDialog(confirmation, 'Cancel') + const folderPrompt = await returnedPrompt + expect(await session.preferences()).toMatchObject({ fullFileAccess: false }) + const acceptedConfirmation = app.waitForEvent('window') + await answerShellDialog(folderPrompt, 'Full file access') + await answerShellDialog(await acceptedConfirmation, 'Enable') + expect(await permission.result).toMatchObject({ + ok: true, + data: { text: 'full access contents' }, + }) + // The desktop pushes the change to open settings pages. + await expect(fullAccess).toBeChecked() + expect(await invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ + ok: true, + data: { text: 'full access contents' }, + }) + calls.fullImport = { + toolName: 'import_local_files', + args: { path: fullFolder, targetWorkspaceId: 'target-workspace' }, + } + const manifest = await invoke({ operation: 'manifest', toolCallId: 'fullImport' }) + if (!manifest.ok || manifest.data.kind !== 'manifest') + throw new Error('Missing full-access manifest') + const imported = manifest.data.entries.find((entry) => entry.relativePath === 'file.txt') + if (!imported) throw new Error('Missing full-access file') + const chunk = await invoke({ + operation: 'chunk', + toolCallId: 'fullImport', + relativePath: imported.relativePath, + revision: imported.revision, + offset: 0, + }) + if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error('Missing full-access contents') + expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('full access contents')]) + expect(await invoke({ operation: 'read', toolCallId: 'notAuthorized' })).toMatchObject({ + ok: false, + }) + }) + + await test.step('Full file access survives restart, and turning it off brings folder prompts back', async () => { + await localFiles.close(session) + session = await localFiles.open(session.desktop.userData) + expect(await session.preferences()).toMatchObject({ fullFileAccess: true }) + expect(await session.invoke({ operation: 'read', toolCallId: 'fullAccess' })).toMatchObject({ + ok: true, + data: { text: 'full access contents' }, + }) + await expect(session.fullAccess).toBeChecked() + await session.fullAccess.click() + await expect(session.fullAccess).not.toBeChecked() + const revoked = await session.requestPermission({ operation: 'read', toolCallId: 'fullAccess' }) + await answerShellDialog(revoked.prompt, "Don't allow") + expect(await revoked.result).toMatchObject({ ok: false }) + }) + + await test.step('a failed settings write leaves Full file access off and local files denied', async () => { + const userData = session.desktop.userData + const settingsPath = join(userData, 'settings.json') + const backupPath = `${settingsPath}.backup` + const saved = JSON.parse(readFileSync(settingsPath, 'utf8')) + for (const previous of [false, true]) { + await localFiles.close(session) + writeFileSync(settingsPath, JSON.stringify({ ...saved, fullFileAccess: previous })) + session = await localFiles.open(userData) + await expect(session.fullAccess).toBeChecked({ checked: previous }) + // A directory where the settings file belongs makes the next write fail. + renameSync(settingsPath, backupPath) + mkdirSync(settingsPath) try { - expect(await invoke({ operation: 'read', toolCallId: 'directoryReplaced' })).toMatchObject({ + await session.fullAccess.click() + await expect(session.window.getByRole('status')).toHaveText('Not saved') + await expect(session.fullAccess).not.toBeChecked() + expect(await session.preferences()).toMatchObject({ fullFileAccess: false }) + expect(await session.invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: false, }) } finally { - rmSync(directory, { recursive: true, force: true }) - rmSync(backup, { recursive: true, force: true }) + await localFiles.close(session) + rmSync(settingsPath, { recursive: true, force: true }) + renameSync(backupPath, settingsPath) } + } + }) +}) + +test('native file access refuses paths swapped or replaced while it reads them', async ({ + localFiles, +}) => { + const { source, outside, calls } = localFiles + const { app, invoke, requestPermission } = await localFiles.open() + const granted = await requestPermission({ operation: 'read', toolCallId: 'directory' }) + await answerShellDialog(granted.prompt, 'Allow folder') + expect(await granted.result).toMatchObject({ ok: true }) + + await test.step('native traversal rejects redirected ancestors and replaced grant identities', async () => { + const parent = join(realpathSync(source), 'native-parent') + mkdirSync(parent) + writeFileSync(join(parent, 'inside.txt'), 'inside') + symlinkSync(outside, join(realpathSync(source), 'native-link')) + const result = await app.evaluate( + async ({ app }, paths) => { + const { createRequire } = process.getBuiltinModule('node:module') + const { stat } = process.getBuiltinModule('node:fs/promises') + const fs = process.getBuiltinModule('node:fs') + const native = createRequire(`${app.getAppPath()}/package.json`)( + './dist/native/directory.node' + ) as { + openApproved( + root: string, + relative: string, + dev: bigint, + ino: bigint, + directory: boolean + ): Promise + } + const root = await stat(paths.source, { bigint: true }) + const denied = async (path: string, ino = root.ino) => { + try { + const fd = await native.openApproved(paths.source, path, root.dev, ino, false) + fs.closeSync(fd) + return false + } catch { + return true + } + } + const valid = await native.openApproved( + paths.source, + 'native-parent/inside.txt', + root.dev, + root.ino, + false + ) + const text = fs.readFileSync(valid, 'utf8') + fs.closeSync(valid) + return { + text, + ancestor: await denied('native-link/private.txt'), + traversal: await denied('../Reports-other/private.txt'), + replaced: await denied('native-parent/inside.txt', root.ino + 1n), + overflow: await denied('native-parent/inside.txt', root.ino + (1n << 64n)), + } + }, + { source: realpathSync(source) } + ) + expect(result).toEqual({ + text: 'inside', + ancestor: true, + traversal: true, + replaced: true, + overflow: true, }) - await test.step('cancelling a directory read prevents its contents from returning', async () => { - const path = realpathSync(join(source, 'empty')) - calls.directoryCancel = { toolName: 'read_local_file', args: { path } } - await app?.evaluate((_electron, path) => { + }) + + await test.step('a symlink swapped in after inspection cannot redirect a file read', async () => { + const file = realpathSync(join(source, 'report.txt')) + const backup = join(source, 'original-report.txt') + const other = join(source, 'other.txt') + writeFileSync(other, 'different file contents') + await app.evaluate( + (_electron, paths) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const original = fs.stat + const fired: string[] = [] + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.stat = original + }, + } + fs.stat = (async (...args: Parameters) => { + const result = await original(...args) + if (args[0] === paths.file) { + fs.stat = original + await fs.rename(paths.file, paths.backup) + await fs.symlink(paths.other, paths.file) + fired.push('swapped') + } + return result + }) as typeof fs.stat + }, + { file, backup, other } + ) + let fired: string[] = [] + try { + expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: false }) + } finally { + fired = await restoreFsPatch(app) + if (fired.includes('swapped')) { + rmSync(file) + renameSync(backup, file) + } + rmSync(other) + } + expect(fired).toEqual(['swapped']) + }) + + await test.step('swapping an ancestor cannot redirect directory enumeration', async () => { + const parent = join(realpathSync(source), 'parent') + const child = join(parent, 'child') + const backup = join(realpathSync(source), 'parent-backup') + const otherParent = join(outside, 'parent') + mkdirSync(child, { recursive: true }) + mkdirSync(join(otherParent, 'child'), { recursive: true }) + writeFileSync(join(child, 'allowed.txt'), 'allowed') + writeFileSync(join(otherParent, 'child', 'private.txt'), 'outside') + calls.ancestorRace = { toolName: 'read_local_file', args: { path: child } } + await app.evaluate( + (_electron, paths) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const originalLstat = fs.lstat + const originalRealpath = fs.realpath + const fired: string[] = [] + let swapped = false + const unswap = async () => { + if (!swapped) return + swapped = false + await fs.rm(paths.parent) + await fs.rename(paths.backup, paths.parent) + } + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: async () => { + fs.lstat = originalLstat + fs.realpath = originalRealpath + await unswap() + }, + } + fs.lstat = (async (...args: Parameters) => { + const result = await originalLstat(...args) + if (args[0] === paths.child) { + fs.lstat = originalLstat + await fs.rename(paths.parent, paths.backup) + await fs.symlink(paths.otherParent, paths.parent) + swapped = true + fired.push('swapped') + } + return result + }) as typeof fs.lstat + fs.realpath = (async (...args: Parameters) => { + if (args[0] === paths.child) await unswap() + return originalRealpath(...args) + }) as typeof fs.realpath + }, + { parent, child, backup, otherParent } + ) + let fired: string[] = [] + try { + expect(await invoke({ operation: 'read', toolCallId: 'ancestorRace' })).toMatchObject({ + ok: true, + data: { entries: [{ name: 'allowed.txt', kind: 'file' }] }, + }) + } finally { + fired = await restoreFsPatch(app) + rmSync(parent, { recursive: true, force: true }) + rmSync(otherParent, { recursive: true, force: true }) + } + expect(fired).toEqual(['swapped']) + }) + + await test.step('a replaced directory cannot return a listing for its old contents', async () => { + const directory = join(realpathSync(source), 'replace-during-read') + const backup = join(realpathSync(source), 'previous-directory') + mkdirSync(directory) + writeFileSync(join(directory, 'old.txt'), 'old contents') + calls.directoryReplaced = { toolName: 'read_local_file', args: { path: directory } } + await app.evaluate( + (_electron, paths) => { const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') const original = fs.lstat + const fired: string[] = [] + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.lstat = original + }, + } fs.lstat = (async (...args: Parameters) => { - const handle = await original(...args) - if (args[0] === path) { + if (args[0] === paths.directory) { fs.lstat = original - await new Promise((resolve) => { - ;( - globalThis as typeof globalThis & { releaseLocalFileRead?: () => void } - ).releaseLocalFileRead = resolve - }) + await fs.rename(paths.directory, paths.backup) + await fs.mkdir(paths.directory) + await fs.writeFile(`${paths.directory}/new.txt`, 'new contents') + fired.push('replaced') } - return handle + return original(...args) }) as typeof fs.lstat - }, path) - const reading = invoke({ operation: 'read', toolCallId: 'directoryCancel' }) - void reading.catch(() => {}) - try { - await expect - .poll(() => - app?.evaluate( - () => - typeof (globalThis as typeof globalThis & { releaseLocalFileRead?: () => void }) - .releaseLocalFileRead === 'function' - ) - ) - .toBe(true) - await invoke({ operation: 'cancel', toolCallId: 'directoryCancel' }) - } finally { - await app?.evaluate(() => { - const runtime = globalThis as typeof globalThis & { releaseLocalFileRead?: () => void } - runtime.releaseLocalFileRead?.() - runtime.releaseLocalFileRead = undefined - }) - } - expect(await reading).toMatchObject({ ok: false }) - }) - await test.step('cancelling in the renderer closes consent without remembering access', async () => { - calls.cancelled = { - toolName: 'read_local_file', - args: { path: join(outside, 'private.txt') }, - } - const cancelled = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) - const closed = cancelled.prompt.waitForEvent('close', { timeout: 5000 }) - await window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.localFiles?.({ operation: 'cancel', toolCallId: 'cancelled' }) - }) - await closed - expect(await cancelled.result).toMatchObject({ ok: false }) - const again = await requestPermission({ operation: 'read', toolCallId: 'cancelled' }) - await answerShellDialog(again.prompt, "Don't allow") - expect(await again.result).toMatchObject({ ok: false }) - }) - await test.step('consent escapes direction controls in folder names', async () => { - const folder = join(root, 'Bidi\u061c\u200e\u200f') - mkdirSync(folder) - calls.bidi = { toolName: 'read_local_file', args: { path: folder } } - const bidi = await requestPermission({ operation: 'read', toolCallId: 'bidi' }) - await expect(bidi.prompt.getByRole('dialog')).toContainText('Bidi\\u061c\\u200e\\u200f') - await answerShellDialog(bidi.prompt, "Don't allow") - expect(await bidi.result).toMatchObject({ ok: false }) - }) - await test.step('an unanswered prompt does not block approved folders', async () => { - calls.blocker = { toolName: 'read_local_file', args: { path: join(outside, 'private.txt') } } - const blocker = await requestPermission({ operation: 'read', toolCallId: 'blocker' }) - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: true }) - await answerShellDialog(blocker.prompt, "Don't allow") - expect(await blocker.result).toMatchObject({ ok: false }) - }) - await test.step('cancelled calls cannot reuse an approved folder', async () => { - calls.expired = { toolName: 'read_local_file', args: { path: join(source, 'report.txt') } } - expireAfterAuthorization.add('expired') - expect(await invoke({ operation: 'read', toolCallId: 'expired' })).toMatchObject({ + }, + { directory, backup } + ) + let fired: string[] = [] + try { + expect(await invoke({ operation: 'read', toolCallId: 'directoryReplaced' })).toMatchObject({ ok: false, }) - }) - await test.step('replacing the proposed folder during consent does not expose its new target', async () => { - const proposed = join(root, 'Proposed') - mkdirSync(proposed) - calls.retargeted = { toolName: 'read_local_file', args: { path: proposed } } - const retargeted = await requestPermission({ operation: 'read', toolCallId: 'retargeted' }) - renameSync(proposed, join(root, 'Original')) - mkdirSync(proposed) - writeFileSync(join(proposed, 'unapproved.txt'), 'replacement folder contents') - await answerShellDialog(retargeted.prompt, 'Allow folder') - expect(await retargeted.result).toMatchObject({ ok: false }) - }) - const result = await invoke({ operation: 'manifest', toolCallId: 'import' }) - if (!result.ok || result.data.kind !== 'manifest') throw new Error(JSON.stringify(result)) - expect(result.data.targetWorkspaceId).toBe('target-workspace') - expect(result.data.entries.map((entry) => entry.relativePath)).toEqual([ - '', - 'empty', - 'image.png', - 'report.txt', - ]) - const file = result.data.entries.find((entry) => entry.relativePath === 'report.txt') - if (!file) throw new Error('Missing import file') - const chunk = await invoke({ - operation: 'chunk', - toolCallId: 'import', - relativePath: file.relativePath, - revision: file.revision, - offset: 0, - }) - if (!chunk.ok || chunk.data.kind !== 'chunk') throw new Error(JSON.stringify(chunk)) - expect(Object.values(chunk.data.bytes)).toEqual([...Buffer.from('native file contents')]) - expect(chunk.data.eof).toBe(true) - expect( - await window.evaluate( - async (input) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - const response = await api.localFiles?.(input) - if (!response?.ok || response.data.kind !== 'chunk') - throw new Error('Missing native chunk') - const file = new File([new Uint8Array(response.data.bytes)], 'report.txt') - return file.text() - }, - { - operation: 'chunk' as const, - toolCallId: 'import', - relativePath: file.relativePath, - revision: file.revision, - offset: 0, - } - ) - ).toBe('native file contents') - expect(await invoke({ operation: 'manifest', toolCallId: 'import' })).toMatchObject({ - ok: false, - code: 'ALREADY_STARTED', - }) - await test.step('an approved folder permits imports without repeated destination prompts', async () => { - calls.otherImport = { - toolName: 'import_local_files', - args: { path: source, targetWorkspaceId: 'other-workspace' }, - } - expect(await invoke({ operation: 'manifest', toolCallId: 'otherImport' })).toMatchObject({ - ok: true, - }) - }) - await test.step('folder permissions survive restarting the desktop app', async () => { - await app?.close() - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ ok: true }) - }) - await test.step('forgetting a folder revokes native reads and survives restart', async () => { - await window.getByRole('button', { name: 'Forget folders', exact: true }).click() - await expect(window.getByRole('button', { name: 'Forgotten', exact: true })).toBeVisible() - await app?.close() - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - const revoked = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await answerShellDialog(revoked.prompt, 'Allow folder') - expect(await revoked.result).toMatchObject({ ok: true }) - }) - - await test.step('a remembered grant does not follow a replaced folder after restart', async () => { - await app?.close() - renameSync(source, join(root, 'Original-reports')) - mkdirSync(source) - writeFileSync(join(source, 'report.txt'), 'replacement contents') - app = await launch() - window = await app.firstWindow() - await expect(window.getByRole('heading', { name: 'Local files', exact: true })).toHaveText( - 'Local files' - ) - const replaced = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await answerShellDialog(replaced.prompt, "Don't allow") - expect(await replaced.result).toMatchObject({ ok: false }) - rmSync(source, { recursive: true }) - renameSync(join(root, 'Original-reports'), source) - const restored = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await answerShellDialog(restored.prompt, 'Allow folder') - expect(await restored.result).toMatchObject({ ok: true }) - }) + } finally { + fired = await restoreFsPatch(app) + rmSync(directory, { recursive: true, force: true }) + rmSync(backup, { recursive: true, force: true }) + } + expect(fired).toEqual(['replaced']) + }) - await test.step('sign-out revokes remembered grants and Full file access before the next account session', async () => { - await window.getByRole('switch', { name: 'Full file access', exact: true }).click() - await expect( - window.getByRole('switch', { name: 'Full file access', exact: true }) - ).toBeChecked() - await app?.evaluate(({ Menu }) => { - const item = Menu.getApplicationMenu() - ?.items.flatMap((entry) => entry.submenu?.items ?? []) - .find((entry) => entry.label === 'Sign Out') - if (!item) throw new Error('Sign Out menu item missing') - item.click() + await test.step('cancelling a directory read prevents its contents from returning', async () => { + const path = realpathSync(join(source, 'empty')) + calls.directoryCancel = { toolName: 'read_local_file', args: { path } } + await app.evaluate((_electron, path) => { + const fs = process.getBuiltinModule('node:fs/promises') as typeof import('node:fs/promises') + const original = fs.lstat + const fired: string[] = [] + let release = () => {} + const held = new Promise((resolve) => { + release = resolve }) - await expect(window).toHaveURL(`http://127.0.0.1:${address.port}/login`) - signedIn = true - await window.goto(`http://127.0.0.1:${address.port}/`) + ;(globalThis as FsPatchRuntime).e2eFsPatch = { + fired, + restore: () => { + fs.lstat = original + release() + }, + } + fs.lstat = (async (...args: Parameters) => { + const result = await original(...args) + if (args[0] === path) { + fs.lstat = original + fired.push('held') + await held + } + return result + }) as typeof fs.lstat + }, path) + const reading = invoke({ operation: 'read', toolCallId: 'directoryCancel' }) + void reading.catch(() => {}) + try { await expect .poll(() => - window.evaluate(async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return (await api.localFilesystem?.({ operation: 'list_mounts' }))?.ok - }) + app.evaluate(() => (globalThis as FsPatchRuntime).e2eFsPatch?.fired.includes('held')) ) .toBe(true) - await expect - .poll(() => - window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ) - .toMatchObject({ fullFileAccess: false }) - const revoked = await requestPermission({ operation: 'read', toolCallId: 'text' }) - await answerShellDialog(revoked.prompt, "Don't allow") - expect(await revoked.result).toMatchObject({ ok: false }) + await invoke({ operation: 'cancel', toolCallId: 'directoryCancel' }) + } finally { + await restoreFsPatch(app) + } + expect(await reading).toMatchObject({ ok: false }) + }) +}) + +test('remembered folder grants survive restart until forgotten, replaced, or signed out', async ({ + localFiles, +}) => { + const { root, source } = localFiles + let session = await localFiles.open() + const restart = async () => { + await localFiles.close(session) + session = await localFiles.open(session.desktop.userData) + } + const answerTextRead = async (button: 'Allow folder' | "Don't allow") => { + const permission = await session.requestPermission({ operation: 'read', toolCallId: 'text' }) + await answerShellDialog(permission.prompt, button) + return permission.result + } + expect(await answerTextRead('Allow folder')).toMatchObject({ ok: true }) + + await test.step('a folder grant survives restarting the app', async () => { + await restart() + expect(await session.invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ + ok: true, }) - await test.step('a failed settings write reports the error and leaves Full file access disabled', async () => { - const settingsPath = join(root, 'profile', 'settings.json') - const saved = JSON.parse(readFileSync(settingsPath, 'utf8')) - for (const previous of [false, true]) { - await app?.close() - rmSync(settingsPath, { recursive: true, force: true }) - writeFileSync(settingsPath, JSON.stringify({ ...saved, fullFileAccess: previous })) - app = await launch() - window = await app.firstWindow() - const toggle = window.getByRole('switch', { name: 'Full file access', exact: true }) - await expect(toggle).toBeChecked({ checked: previous }) - renameSync(settingsPath, `${settingsPath}.backup`) - mkdirSync(settingsPath) - try { - await toggle.click() - await expect( - window.getByText( - 'Could not save file access settings. Your previous setting may return after restarting Sim.', - { exact: true } - ) - ).toBeVisible() - await expect(toggle).not.toBeChecked() - expect( - await window.evaluate(async () => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.getPreferences() - ) - ).toMatchObject({ fullFileAccess: false }) - expect(await invoke({ operation: 'read', toolCallId: 'text' })).toMatchObject({ - ok: false, - }) - } finally { - await app.close() - app = undefined - rmSync(settingsPath, { recursive: true, force: true }) - renameSync(`${settingsPath}.backup`, settingsPath) - } - } + }) + + await test.step('forgetting a folder revokes native reads and survives restart', async () => { + await session.window.getByRole('button', { name: 'Forget folders', exact: true }).click() + await expect( + session.window.getByRole('button', { name: 'Forgotten', exact: true }) + ).toBeVisible() + await restart() + expect(await answerTextRead('Allow folder')).toMatchObject({ ok: true }) + }) + + await test.step('a remembered grant does not follow a replaced folder after restart', async () => { + await localFiles.close(session) + renameSync(source, join(root, 'Original-reports')) + mkdirSync(source) + writeFileSync(join(source, 'report.txt'), 'replacement contents') + session = await localFiles.open(session.desktop.userData) + expect(await answerTextRead("Don't allow")).toMatchObject({ ok: false }) + rmSync(source, { recursive: true }) + renameSync(join(root, 'Original-reports'), source) + expect(await answerTextRead('Allow folder')).toMatchObject({ ok: true }) + }) + + await test.step('sign-out revokes remembered grants and Full file access before the next account session', async () => { + const { app, window, fullAccess } = session + await fullAccess.click() + await expect(fullAccess).toBeChecked() + await app.evaluate(({ Menu }) => { + const item = Menu.getApplicationMenu() + ?.items.flatMap((entry) => entry.submenu?.items ?? []) + .find((entry) => entry.label === 'Sign Out') + if (!item) throw new Error('Sign Out menu item missing') + item.click() }) - } finally { - await app?.close() - server?.close() - rmSync(root, { recursive: true, force: true }) - } + await expect(window).toHaveURL(`${localFiles.origin}/login`) + localFiles.signIn() + await window.goto(`${localFiles.origin}/`) + await expect + .poll(() => + window.evaluate( + async () => + ( + await (globalThis as DesktopBridge).simDesktop.localFilesystem?.({ + operation: 'list_mounts', + }) + )?.ok + ) + ) + .toBe(true) + await expect.poll(() => session.preferences()).toMatchObject({ fullFileAccess: false }) + expect(await answerTextRead("Don't allow")).toMatchObject({ ok: false }) + }) }) diff --git a/apps/desktop/e2e/packaged-smoke.spec.ts b/apps/desktop/e2e/packaged-smoke.spec.ts index 559db75d3ea..c2be201f8d7 100644 --- a/apps/desktop/e2e/packaged-smoke.spec.ts +++ b/apps/desktop/e2e/packaged-smoke.spec.ts @@ -1,10 +1,10 @@ -import { type ChildProcess, execFileSync, spawn } from 'node:child_process' -import { once } from 'node:events' -import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' +import { spawn } from 'node:child_process' +import { existsSync, mkdtempSync, readFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { FuseV1Options, FuseVersion, getCurrentFuseWire } from '@electron/fuses' -import { type Browser, chromium, expect, test } from '@playwright/test' +import { type Browser, chromium } from '@playwright/test' +import { expect, stopAndRemoveProfile, test } from './harness' const FUSE_DISABLED = '0'.charCodeAt(0) const FUSE_ENABLED = '1'.charCodeAt(0) @@ -27,53 +27,6 @@ test.skip( 'Packaged smoke runs only after the desktop executable has been built' ) -/** - * The processes of a packaged run that can still write its profile. Chromium's helpers stay in the - * app's process group (it is spawned detached, so the group is its own), while Crashpad's handler - * starts its own session but names the profile's Crashpad database on its command line. - */ -function profileWriters(appGroup: number, profilePaths: readonly string[]): number[] { - return execFileSync('ps', ['-axww', '-o', 'pid=,pgid=,command='], { encoding: 'utf8' }) - .split('\n') - .flatMap((line) => { - const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line) - if (!match) return [] - const [, pid, group, command] = match - return Number(group) === appGroup || profilePaths.some((path) => command.includes(path)) - ? [Number(pid)] - : [] - }) -} - -/** - * Removes a profile only once nothing can write into it. Killing the main process leaves its - * helpers and Crashpad's handler running for a moment, and a file one of them creates while the - * directory is being removed fails the removal with ENOTEMPTY. - */ -async function stopAndRemoveProfile(child: ChildProcess, userDataPath: string): Promise { - if (child.exitCode === null && child.signalCode === null) { - const exited = once(child, 'exit') - child.kill('SIGKILL') - await exited - } - const appGroup = child.pid - if (appGroup !== undefined) { - const profilePaths = [userDataPath, realpathSync(userDataPath)] - await expect - .poll(() => { - const writers = profileWriters(appGroup, profilePaths) - for (const pid of writers) { - try { - process.kill(pid, 'SIGKILL') - } catch {} - } - return writers - }) - .toEqual([]) - } - rmSync(userDataPath, { recursive: true, force: true }) -} - test('packaged Electron binary has the production fuse policy', async () => { const executablePath = process.env.SIM_DESKTOP_EXECUTABLE if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') @@ -90,48 +43,12 @@ test('packaged Electron binary has the production fuse policy', async () => { } }) -test('packaged main process starts and records launch telemetry', async () => { - const executablePath = process.env.SIM_DESKTOP_EXECUTABLE - if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') - const userDataPath = mkdtempSync(join(tmpdir(), 'sim-desktop-packaged-e2e-')) - const child = spawn(executablePath, [], { - detached: true, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: 'http://127.0.0.1:1', - SIM_DESKTOP_USER_DATA: userDataPath, - }, - stdio: 'ignore', - }) - const eventLogPath = join(userDataPath, 'logs', 'desktop-events.log') - - try { - await expect - .poll( - () => { - if (child.exitCode !== null || child.signalCode !== null) { - throw new Error( - `Packaged app exited with ${child.exitCode ?? child.signalCode ?? 'unknown status'}` - ) - } - return ( - existsSync(eventLogPath) && readFileSync(eventLogPath, 'utf8').includes('app_launch') - ) - }, - { timeout: 10_000 } - ) - .toBe(true) - } finally { - await stopAndRemoveProfile(child, userDataPath) - } -}) - // The unpackaged suite cannot see this: the bundled pages live inside app.asar // only once packaged, and the file-protocol fuse is only off once packaged. // v0.8.13 through v0.8.19 shipped both pages blank because nothing loaded them // in that configuration. Chromium's remote-debugging switch is honoured by the // fused binary, which is what lets the test read the rendered page. -test('packaged shell renders the bundled offline page', async () => { +test('packaged shell records its launch and renders the bundled offline page', async () => { const executablePath = process.env.SIM_DESKTOP_EXECUTABLE if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required') const userDataPath = mkdtempSync(join(tmpdir(), 'sim-desktop-packaged-e2e-')) @@ -179,6 +96,10 @@ test('packaged shell renders the bundled offline page', async () => { if (!offline) throw new Error('offline page disappeared') await expect(offline.locator('#title')).toHaveText('Can’t connect to Sim') await expect(offline.locator('#server')).toBeVisible() + const eventLog = join(userDataPath, 'logs', 'desktop-events.log') + await expect + .poll(() => existsSync(eventLog) && readFileSync(eventLog, 'utf8').includes('app_launch')) + .toBe(true) // The picker is the recovery path from here. Opening it and reading the // pre-filled value crosses the local-page IPC gate twice, which packaged diff --git a/apps/desktop/e2e/password-autofill.spec.ts b/apps/desktop/e2e/password-autofill.spec.ts index 8a00ba9bbd3..a2a796dd177 100644 --- a/apps/desktop/e2e/password-autofill.spec.ts +++ b/apps/desktop/e2e/password-autofill.spec.ts @@ -1,125 +1,57 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' +import { writeFileSync } from 'node:fs' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' +import type { ElectronApplication, Locator, Page } from '@playwright/test' +import { getErrorMessage } from '@sim/utils/errors' import { - type ElectronApplication, - _electron as electron, + attachBrowserPanel, + type DesktopBridge, expect, - type Page, + type FixtureServer, + focusFirstWindow, + hideBrowserPanel, + ToolAuthorizer, test, -} from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +} from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'password-fixture' -const SCREENSHOTS = process.env.SIM_PASSWORD_SCREENSHOTS +const PICKER_PAGE = 'credential-picker.html' const LOGIN = `Account sign in

Sign in to your account

` test.describe('saved password autofill', () => { - let server: Server - let origin: string - let site: string + let fixture: FixtureServer let app: ElectronApplication let host: Page let userData: string - const calls = new Map< - string, - { chatId: string; toolName: string; args: Record } - >() - let serial = 0 + const authorizer = new ToolAuthorizer('fixture') test.beforeAll(async () => { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const call = calls.get(JSON.parse(body).toolCallId) - response.writeHead(call ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(call ?? {})) - return - } - if (path.startsWith('/api/')) { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end('{}') - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) - response.end( - path === '/login' - ? LOGIN - : 'Sim fixture

Password fixture

' - ) + fixture = await serveSignedIn({ + page: 'Sim fixture

Password fixture

', + handle: async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return true + if (url.pathname !== '/login') return false + response.writeHead(200, { 'Content-Type': 'text/html' }).end(LOGIN) + return true + }, }) - await new Promise((resolve) => server.listen(0, resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - site = `http://localhost:${address.port}` }) - test.beforeEach(async () => { - userData = mkdtempSync(join(tmpdir(), 'sim-password-e2e-')) - app = await electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) + test.afterAll(async () => { + await fixture.close() + }) + + test.beforeEach(async ({ desktop }) => { + ;({ app, userData } = await desktop.launch({ origin: fixture.origin })) host = await app.firstWindow() await expect(host.getByRole('heading')).toHaveText('Password fixture') - await app.evaluate(({ app, BrowserWindow }) => { - app.focus({ steal: true }) - BrowserWindow.getAllWindows()[0].focus() - }) - await expect - .poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isFocused())) - .toBe(true) - await host.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.browserAgent.activateScope(scope) - api.browserAgent.setPanelBounds( - { x: 0, y: 130, width: innerWidth, height: innerHeight - 130 }, - null, - scope - ) - setInterval( - () => - api.browserAgent.setPanelBounds( - { x: 0, y: 130, width: innerWidth, height: innerHeight - 130 }, - null, - scope - ), - 200 - ) - }, SCOPE) + await focusFirstWindow(app) + await attachBrowserPanel(host, SCOPE, 130) await seed(3) - await navigate(`${site}/login`) - }) - - test.afterEach(async () => { - await app?.close() - rmSync(userData, { recursive: true, force: true }) - calls.clear() - }) - test.afterAll(async () => { - await new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) + await navigate(`${fixture.site}/login`) }) async function seed(count: number, prefix = 'account') { @@ -136,7 +68,7 @@ test.describe('saved password autofill', () => { })) return safeStorage.encryptString(JSON.stringify(records)).toString('base64') }, - { site, count, prefix } + { site: fixture.site, count, prefix } ) writeFileSync( join(userData, 'browser-credentials.json'), @@ -146,16 +78,7 @@ test.describe('saved password autofill', () => { } async function navigate(url: string) { - const id = `fixture-${++serial}` - calls.set(id, { chatId: SCOPE, toolName: 'browser_open_url', args: { url } }) - const result = await host.evaluate( - async ({ id, url, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.browserAgent.executeTool(id, 'browser_open_url', { url }, scope) - }, - { id, url, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) + await authorizer.execute(host, SCOPE, 'browser_open_url', { url }) } async function pageScript(script: string): Promise { @@ -167,16 +90,18 @@ test.describe('saved password autofill', () => { if (!page) throw new Error('Missing fixture page') return page.executeJavaScript(script) }, - { site, script } + { site: fixture.site, script } ) } + /** Clicks a login field with native input, as a user would. */ async function clickField(id = 'user') { await app.evaluate( async ({ webContents }, { site, id }) => { const page = webContents .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! + .find((contents) => contents.getURL().startsWith(`${site}/login`)) + if (!page) throw new Error('Missing fixture page') const point = await page.executeJavaScript( `(() => {const r=document.getElementById(${JSON.stringify(id)}).getBoundingClientRect();return {x:Math.round(r.x+12),y:Math.round(r.y+12)}})()` ) @@ -184,29 +109,98 @@ test.describe('saved password autofill', () => { page.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point }) page.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point }) }, - { site, id } + { site: fixture.site, id } ) } - async function picker() { - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(true) - const page = app.windows().find((page) => page.url().includes('credential-picker.html'))! + /** Sends a key to the login page with native input. */ + async function loginKey(keyCode: string) { + await app.evaluate( + ({ webContents }, { site, keyCode }) => { + const page = webContents + .getAllWebContents() + .find((contents) => contents.getURL().startsWith(`${site}/login`)) + if (!page) throw new Error('Missing fixture page') + page.sendInputEvent({ type: 'keyDown', keyCode }) + page.sendInputEvent({ type: 'keyUp', keyCode }) + }, + { site: fixture.site, keyCode } + ) + } + + const pickerPage = () => app.windows().find((page) => page.url().includes(PICKER_PAGE)) + const pickerOpen = () => pickerPage() !== undefined + + async function picker(): Promise { + await expect.poll(pickerOpen).toBe(true) + const page = pickerPage() + if (!page) throw new Error('The picker closed before it could be read') await expect(page.getByRole('menu')).toBeVisible() return page } + const pickerFocused = () => + app.evaluate( + ({ BrowserWindow }, pickerUrl) => + BrowserWindow.getFocusedWindow()?.webContents.getURL().includes(pickerUrl), + PICKER_PAGE + ) + async function pickerKey(keyCode: string) { - await app.evaluate(({ BrowserWindow }, keyCode) => { - const contents = BrowserWindow.getAllWindows().find((window) => - window.webContents.getURL().includes('credential-picker.html') - )!.webContents - contents.sendInputEvent({ type: 'keyDown', keyCode }) - contents.sendInputEvent({ type: 'keyUp', keyCode }) - }, keyCode) + await app.evaluate( + ({ BrowserWindow }, { keyCode, pickerUrl }) => { + const picker = BrowserWindow.getAllWindows().find((window) => + window.webContents.getURL().includes(pickerUrl) + ) + if (!picker) throw new Error('The picker is not open') + picker.webContents.sendInputEvent({ type: 'keyDown', keyCode }) + picker.webContents.sendInputEvent({ type: 'keyUp', keyCode }) + }, + { keyCode, pickerUrl: PICKER_PAGE } + ) + } + + /** Chooses an account; the picker closes under the click, the only error tolerated. */ + async function choose(menu: Page, item: Locator) { + const closed = menu.waitForEvent('close') + await item.click().catch((error: unknown) => { + if (!getErrorMessage(error).includes('Target page, context or browser has been closed')) { + throw error + } + }) + await closed } + /** Whether the picker sits flush with the username field, below it or above it. */ + const placement = () => + app.evaluate(async ({ BrowserWindow, WebContentsView }, pickerUrl) => { + const picker = BrowserWindow.getAllWindows().find((window) => + window.webContents.getURL().includes(pickerUrl) + ) + const parent = picker?.getParentWindow() + const view = parent?.contentView.children.find( + (child): child is InstanceType => + child instanceof WebContentsView && child.webContents.getURL().includes('/login') + ) + if (!picker || !parent || !view) return null + const field = await view.webContents.executeJavaScript( + '(() => { const r=document.getElementById("user").getBoundingClientRect(); return {x:r.x,y:r.y,height:r.height} })()' + ) + const bounds = picker.getBounds() + const zoom = view.webContents.getZoomFactor() + const fieldX = parent.getContentBounds().x + view.getBounds().x + field.x * zoom + const fieldY = parent.getContentBounds().y + view.getBounds().y + field.y * zoom + const fieldHeight = field.height * zoom + return { + alignedX: Math.abs(bounds.x - fieldX) <= 1, + adjacentY: + Math.min( + Math.abs(bounds.y - fieldY - fieldHeight - 4), + Math.abs(bounds.y + bounds.height + 4 - fieldY) + ) <= 1, + } + }, PICKER_PAGE) + test('uses shared emcn styling, fills a selected account, and never submits', async () => { await clickField() const menu = await picker() @@ -219,35 +213,7 @@ test.describe('saved password autofill', () => { }) expect(denied).toBe('failed') expect(await pageScript('document.getElementById("pass").value')).toBe('') - const placement = await app.evaluate(async ({ BrowserWindow, WebContentsView }) => { - const picker = BrowserWindow.getAllWindows().find((window) => - window.webContents.getURL().includes('credential-picker.html') - )! - const parent = picker.getParentWindow()! - const view = parent.contentView.children.find( - (view) => view instanceof WebContentsView && view.webContents.getURL().includes('/login') - ) as InstanceType - const field = await view.webContents.executeJavaScript( - '(() => { const r=document.getElementById("user").getBoundingClientRect(); return {x:r.x,y:r.y,height:r.height} })()' - ) - const bounds = picker.getBounds() - const zoom = view.webContents.getZoomFactor() - return { - x: bounds.x, - y: bounds.y, - height: bounds.height, - fieldX: parent.getContentBounds().x + view.getBounds().x + field.x * zoom, - fieldY: parent.getContentBounds().y + view.getBounds().y + field.y * zoom, - fieldHeight: field.height * zoom, - } - }) - expect(Math.abs(placement.x - placement.fieldX)).toBeLessThanOrEqual(1) - expect( - Math.min( - Math.abs(placement.y - placement.fieldY - placement.fieldHeight - 4), - Math.abs(placement.y + placement.height + 4 - placement.fieldY) - ) - ).toBeLessThanOrEqual(1) + await expect.poll(placement).toEqual({ alignedX: true, adjacentY: true }) await menu.evaluate(async () => { await document.fonts.ready await new Promise(requestAnimationFrame) @@ -262,18 +228,7 @@ test.describe('saved password autofill', () => { })) expect(geometry).toMatchObject({ x: 0, width: 320, overflow: false, weight: '400' }) expect(geometry.font).toContain('Season Sans') - if (SCREENSHOTS) { - mkdirSync(SCREENSHOTS, { recursive: true }) - for (const theme of ['light', 'dark']) { - await host.evaluate((theme) => { - document.documentElement.className = theme - document.documentElement.style.colorScheme = theme - }, theme) - await expect(menu.locator('html')).toHaveClass(theme) - await menu.screenshot({ path: join(SCREENSHOTS, `password-picker-${theme}.png`) }) - } - } - await menu.getByRole('menuitem', { name: 'account2@example.test', exact: true }).click() + await choose(menu, menu.getByRole('menuitem', { name: 'account2@example.test', exact: true })) await expect .poll(() => pageScript( @@ -281,29 +236,14 @@ test.describe('saved password autofill', () => { ) ) .toEqual({ user: 'account2@example.test', pass: 'fixture-secret-1', submitted: null }) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) }) test('supports keyboard selection and dismissal without unnecessary scrolling', async () => { await seed(15) await clickField() const menu = await picker() - await app.evaluate(({ webContents }, site) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! - page.sendInputEvent({ type: 'keyDown', keyCode: 'Down' }) - page.sendInputEvent({ type: 'keyUp', keyCode: 'Down' }) - }, site) - await expect - .poll(() => - app.evaluate(({ BrowserWindow }) => - BrowserWindow.getFocusedWindow()?.webContents.getURL().includes('credential-picker.html') - ) - ) - .toBe(true) + await loginKey('Down') + await expect.poll(pickerFocused).toBe(true) await expect(menu.getByRole('menuitem')).toHaveCount(15) await pickerKey('End') await expect(menu.getByRole('menuitem').last()).toBeFocused() @@ -311,15 +251,11 @@ test.describe('saved password autofill', () => { await expect .poll(() => pageScript('document.getElementById("user").value')) .toBe('account9@example.test') - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) await clickField() await picker() await pickerKey('Escape') - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) }) for (const count of [1, 3]) { @@ -345,14 +281,11 @@ test.describe('saved password autofill', () => { }) ) .toBe(true) - if (SCREENSHOTS) { - await menu.screenshot({ path: join(SCREENSHOTS, `password-picker-long-${count}.png`) }) - } - await app.evaluate(({ BrowserWindow }) => { + await app.evaluate(({ BrowserWindow }, pickerUrl) => { BrowserWindow.getAllWindows() - .find((window) => window.webContents.getURL().includes('credential-picker.html'))! - .setContentSize(800, 600) - }) + .find((window) => window.webContents.getURL().includes(pickerUrl)) + ?.setContentSize(800, 600) + }, PICKER_PAGE) await menu .getByRole('menuitem') .first() @@ -377,40 +310,20 @@ test.describe('saved password autofill', () => { await clickField() await picker() await host.getByRole('button', { name: 'Outside the browser' }).click() - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) await expect(host.getByRole('button', { name: 'Outside the browser' })).toBeFocused() await clickField() await picker() - await host.evaluate((scope) => { - ;( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.browserAgent.setPanelBounds(null, null, scope) - }, SCOPE) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await hideBrowserPanel(host, SCOPE) + await expect.poll(pickerOpen).toBe(false) expect(await pageScript('document.getElementById("pass").value')).toBe('') }) test('returns keyboard focus to the login after dismissal and selection', async () => { await clickField() await picker() - await app.evaluate(({ webContents }, site) => { - const page = webContents - .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! - page.sendInputEvent({ type: 'keyDown', keyCode: 'Down' }) - page.sendInputEvent({ type: 'keyUp', keyCode: 'Down' }) - }, site) - await expect - .poll(() => - app.evaluate(({ BrowserWindow }) => - BrowserWindow.getFocusedWindow()?.webContents.getURL().includes('credential-picker.html') - ) - ) - .toBe(true) + await loginKey('Down') + await expect.poll(pickerFocused).toBe(true) await pickerKey('Escape') await expect .poll(() => @@ -419,18 +332,19 @@ test.describe('saved password autofill', () => { page: webContents.getFocusedWebContents()?.getURL(), })) ) - .toEqual({ window: host.url(), page: `${site}/login` }) + .toEqual({ window: host.url(), page: `${fixture.site}/login` }) await app.evaluate(({ webContents }) => { - const page = webContents.getFocusedWebContents()! + const page = webContents.getFocusedWebContents() + if (!page) throw new Error('No focused page') page.sendInputEvent({ type: 'keyDown', keyCode: 'Tab' }) page.sendInputEvent({ type: 'keyUp', keyCode: 'Tab' }) }) await expect.poll(() => pageScript('document.activeElement.id')).toBe('pass') const menu = await picker() - await menu.getByRole('menuitem').first().click() + await choose(menu, menu.getByRole('menuitem').first()) await expect .poll(() => app.evaluate(({ webContents }) => webContents.getFocusedWebContents()?.getURL())) - .toBe(`${site}/login`) + .toBe(`${fixture.site}/login`) }) test('rejects replaced fields and excludes account creation', async () => { @@ -439,25 +353,28 @@ test.describe('saved password autofill', () => { await pageScript( 'document.querySelector("form").innerHTML = \'\'' ) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await expect.poll(pickerOpen).toBe(false) await clickField('pass') + // The click must have landed, or the checks below would pass without exercising anything. + await expect.poll(() => pageScript('document.activeElement.id')).toBe('pass') expect(await pageScript('document.getElementById("pass").value')).toBe('') - expect(app.windows().some((page) => page.url().includes('credential-picker.html'))).toBe(false) + expect(pickerOpen()).toBe(false) }) + test('offers a focused manual chooser with one account', async () => { await seed(1) await host.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + const api = (globalThis as DesktopBridge).simDesktop await api.browserAgent.capturePanelSnapshot(scope) if (!(await api.browserAgent.setPanelOccluded(true, scope))) { throw new Error('Could not open the toolbar overlay') } }, SCOPE) await host.evaluate((scope) => { - document.getElementById('outside')!.onclick = async () => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop + const outside = document.getElementById('outside') + if (!outside) throw new Error('Missing outside button') + outside.onclick = async () => { + const api = (globalThis as DesktopBridge).simDesktop await api.browserAgent.setPanelOccluded(false, scope) await api.browserCredentials.showChooser({ x: 20, y: 80 }, scope) } @@ -465,14 +382,8 @@ test.describe('saved password autofill', () => { await host.getByRole('button', { name: 'Outside the browser' }).click() const menu = await picker() await expect(menu.getByRole('menuitem')).toHaveCount(1) - await expect - .poll(() => - app.evaluate(({ BrowserWindow }) => - BrowserWindow.getFocusedWindow()?.webContents.getURL().includes('credential-picker.html') - ) - ) - .toBe(true) - await menu.getByRole('menuitem').click() + await expect.poll(pickerFocused).toBe(true) + await choose(menu, menu.getByRole('menuitem')) await expect .poll(() => pageScript('document.getElementById("pass").value')) .toBe('fixture-secret-0') @@ -484,21 +395,19 @@ test.describe('saved password autofill', () => { ) await clickField() const menu = await picker() + // A failed fill keeps the picker open to show why. await menu.getByRole('menuitem').first().click() await expect(menu.getByRole('alert')).toHaveText( 'Could not fill this form. Select the field again.' ) expect(await pageScript('document.getElementById("pass").value')).toBe('') - if (SCREENSHOTS) await menu.screenshot({ path: join(SCREENSHOTS, 'password-picker-error.png') }) }) test('closes on navigation and never fills the destination', async () => { await clickField() await picker() - await navigate(`${site}/login?next=1`) - await expect - .poll(() => app.windows().some((page) => page.url().includes('credential-picker.html'))) - .toBe(false) + await navigate(`${fixture.site}/login?next=1`) + await expect.poll(pickerOpen).toBe(false) expect(await pageScript('document.getElementById("pass").value')).toBe('') }) @@ -510,16 +419,17 @@ test.describe('saved password autofill', () => { await app.evaluate(async ({ webContents }, site) => { const page = webContents .getAllWebContents() - .find((contents) => contents.getURL().startsWith(`${site}/login`))! + .find((contents) => contents.getURL().startsWith(`${site}/login`)) + if (!page) throw new Error('Missing fixture page') const point = await page.executeJavaScript( '(() => {const r=document.getElementById("shadow").shadowRoot.getElementById("pass").getBoundingClientRect();return {x:Math.round(r.x+4),y:Math.round(r.y+4)}})()' ) page.focus() page.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point }) page.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point }) - }, site) + }, fixture.site) const menu = await picker() - await menu.getByRole('menuitem').first().click() + await choose(menu, menu.getByRole('menuitem').first()) await expect .poll(() => pageScript('document.getElementById("shadow").shadowRoot.getElementById("pass").value') diff --git a/apps/desktop/e2e/quick-chat.spec.ts b/apps/desktop/e2e/quick-chat.spec.ts index 95d94ef3f4d..37e6e56f275 100644 --- a/apps/desktop/e2e/quick-chat.spec.ts +++ b/apps/desktop/e2e/quick-chat.spec.ts @@ -1,30 +1,21 @@ -import { mkdtempSync, writeFileSync } from 'node:fs' -import type { Server } from 'node:http' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' import type { ElectronApplication, Page } from '@playwright/test' -import { _electron as electron, expect, test } from '@playwright/test' import type { DesktopPreferences, QuickChatShortcut } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { recordCheck } from './check-report' +import { type DesktopBridge, expect, type FixtureServer, serve, test } from './harness' /** * Drives the quick chat window in the real shell against a fixture origin: where it opens, that * it floats with no desktop bridge, that it resizes within its bounds, that "Open in Sim" hands * the chat to a full window, that the toggle hides and restores the same page, that sign-out - * destroys it, and how its shortcut setting and load failures behave. Each check lands in a JSON - * report at QUICK_CHAT_REPORT_PATH as it finishes. + * destroys it, and how its shortcut setting and load failures behave. */ -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const WORKSPACE_ROUTE = '/workspace/ws1/home' +const QUICK_ROUTE = '/extension/ws1' const DEFAULT_SHORTCUT: QuickChatShortcut = 'Alt+Space' const PAGES: Record = { [WORKSPACE_ROUTE]: '

workspace

', - '/extension/ws1': `

quick-chat

+ [QUICK_ROUTE]: `

quick-chat

Open in Sim `, '/workspace/ws1/chat/c1': @@ -32,63 +23,6 @@ const PAGES: Record = { '/login': '

fixture-login

', } -interface FixtureServer { - server: Server - origin: string - /** Drops every connection for `path`, so its loads fail, until `failing` is turned off again. */ - setFailing: (path: string, failing: boolean) => void -} - -function startFixtureServer(): Promise { - const failing = new Set() - return new Promise((resolvePromise) => { - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - if (failing.has(path)) { - request.socket.destroy() - return - } - if (path === '/api/auth/sign-out') { - response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') - return - } - const body = PAGES[path] - if (!body) { - response.writeHead(404, { 'Content-Type': 'text/html' }).end('

not found

') - return - } - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(body) - }) - server.listen(0, '127.0.0.1', () => { - const address = server.address() - const port = typeof address === 'object' && address ? address.port : 0 - resolvePromise({ - server, - origin: `http://127.0.0.1:${port}`, - setFailing: (path, on) => { - if (on) failing.add(path) - else failing.delete(path) - }, - }) - }) - }) -} - -function launchApp(origin: string, settings: string | Record = {}) { - const userData = mkdtempSync(join(tmpdir(), 'sim-desktop-quick-chat-')) - writeFileSync( - join(userData, 'settings.json'), - typeof settings === 'string' - ? settings - : JSON.stringify({ origin, lastRoute: WORKSPACE_ROUTE, ...settings }) - ) - return electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) -} - /** Clicks an application-menu item by label, the way a user choosing it from the menu bar would. */ function clickMenu(app: ElectronApplication, label: string): Promise { return app.evaluate(({ Menu }, label) => { @@ -123,6 +57,13 @@ function windowState(app: ElectronApplication, url: string) { }, url) } +/** Whether a floating (always-on-top) window exists; full windows never float. */ +function hasFloatingWindow(app: ElectronApplication): Promise { + return app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isAlwaysOnTop()) + ) +} + /** Resizes the window showing `url` the way dragging its edge would. */ function resizeWindow(app: ElectronApplication, url: string, width: number, height: number) { return app.evaluate( @@ -142,235 +83,214 @@ const hasBridge = (page: Page) => const setShortcut = (page: Page, shortcut: string | null) => page.evaluate( (value) => - ( - globalThis as unknown as { - simDesktop: { - settings: { setQuickChatShortcut(v: unknown): Promise } - } - } - ).simDesktop.settings.setQuickChatShortcut(value), + (globalThis as DesktopBridge).simDesktop.settings.setQuickChatShortcut?.( + value as QuickChatShortcut | null + ), shortcut ) const isRegistered = (app: ElectronApplication, shortcut: string) => app.evaluate(({ globalShortcut }, value) => globalShortcut.isRegistered(value), shortcut) -/** Runs one named check and records its outcome as soon as it is known. */ -async function check(name: string, body: () => Promise) { - const reportPath = process.env.QUICK_CHAT_REPORT_PATH ?? test.info().outputPath('quick-chat.json') - const started = Date.now() - const record = (status: 'passed' | 'failed', error?: unknown) => - recordCheck(reportPath, 'quick-chat', { - name, - status, - durationMs: Date.now() - started, - retry: test.info().retry, - ...(error === undefined ? {} : { error: getErrorMessage(error) }), - }) - try { - await body() - record('passed') - } catch (error) { - record('failed', error) - throw error - } -} - test.describe('quick chat window', () => { let fixture: FixtureServer - let app: ElectronApplication | undefined + /** Paths whose connections are dropped, so their loads fail. */ + const failing = new Set() test.beforeAll(async () => { - fixture = await startFixtureServer() + fixture = await serve((request, response, url) => { + if (failing.has(url.pathname)) { + request.socket.destroy() + return + } + if (url.pathname === '/api/auth/sign-out') { + response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') + return + } + const body = PAGES[url.pathname] + if (!body) { + response.writeHead(404, { 'Content-Type': 'text/html' }).end('

not found

') + return + } + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(body) + }) }) - test.afterAll(() => { - fixture.server.close() + test.afterAll(async () => { + await fixture.close() }) - test.afterEach(async () => { - await app?.close().catch(() => {}) + test.afterEach(() => { + failing.clear() }) - test('opens, resizes, hands off, toggles, and closes on sign-out', async () => { - const launched = await launchApp(fixture.origin) - app = launched - const main = await launched.firstWindow() + const settings = (extra: Record = {}) => ({ + origin: fixture.origin, + lastRoute: WORKSPACE_ROUTE, + ...extra, + }) + + test('opens, resizes, hands off, toggles, and closes on sign-out', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: fixture.origin, settings: settings() }) + const main = await app.firstWindow() await expect(main.locator('#app')).toHaveText('workspace') - const quickUrl = `${fixture.origin}/extension/ws1` - let quick: Page | undefined + const quickUrl = `${fixture.origin}${QUICK_ROUTE}` - await check('opens the compact chat for the last workspace as a floating window', async () => { - const opened = launched.waitForEvent('window') - await clickMenu(launched, 'Quick Chat') - quick = await opened - await expect(quick.locator('#quick')).toHaveText('quick-chat') - expect(quick.url()).toBe(quickUrl) - await expect - .poll(() => windowState(launched, quickUrl)) - .toMatchObject({ visible: true, alwaysOnTop: true }) - }) + const quick = + await test.step('opens the compact chat for the last workspace as a floating window', async () => { + const opened = app.waitForEvent('window') + await clickMenu(app, 'Quick Chat') + const page = await opened + await expect(page.locator('#quick')).toHaveText('quick-chat') + expect(page.url()).toBe(quickUrl) + await expect + .poll(() => windowState(app, quickUrl)) + .toMatchObject({ visible: true, alwaysOnTop: true }) + return page + }) - await check('the floating page gets no desktop bridge while full windows keep it', async () => { - if (!quick) throw new Error('Quick chat did not open') + await test.step('the floating page gets no desktop bridge while full windows keep it', async () => { expect(await hasBridge(quick)).toBe(false) expect(await hasBridge(main)).toBe(true) }) - await check('resizing holds the minimum size and the page follows the window', async () => { - if (!quick) throw new Error('Quick chat did not open') - const page = quick - await resizeWindow(launched, quickUrl, 200, 200) - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ size: [360, 420] }) + await test.step('resizing holds the minimum size and the page follows the window', async () => { + await resizeWindow(app, quickUrl, 200, 200) + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ size: [360, 420] }) // Small enough for any runner display; macOS clamps a window to the screen it is on. - await resizeWindow(launched, quickUrl, 600, 560) - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ size: [600, 560] }) - await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(600) + await resizeWindow(app, quickUrl, 600, 560) + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ size: [600, 560] }) + await expect.poll(() => quick.evaluate(() => window.innerWidth)).toBe(600) }) - await check( - 'Open in Sim hands the chat to a full window and leaves the panel open', - async () => { - if (!quick) throw new Error('Quick chat did not open') - const handedOff = launched.waitForEvent('window') - await quick.locator('#open-in-sim').click() - const full = await handedOff - await expect(full.locator('#chat')).toHaveText('handed-off') - expect(await hasBridge(full)).toBe(true) - expect(await windowState(launched, quickUrl)).toMatchObject({ - visible: true, - alwaysOnTop: true, - }) - } - ) + await test.step('Open in Sim hands the chat to a full window and leaves the panel open', async () => { + const handedOff = app.waitForEvent('window') + await quick.locator('#open-in-sim').click() + const full = await handedOff + await expect(full.locator('#chat')).toHaveText('handed-off') + expect(await hasBridge(full)).toBe(true) + expect(await windowState(app, quickUrl)).toMatchObject({ visible: true, alwaysOnTop: true }) + }) - await check( - 'the toggle brings a background panel forward, then hides it, keeping the page', - async () => { - if (!quick) throw new Error('Quick chat did not open') - await quick.evaluate(() => { - ;(globalThis as { quickChatMarker?: string }).quickChatMarker = 'kept' - }) - // The hand-off focused the full window; the app must be active for window focus to land. - await launched.evaluate(({ app }) => app.focus({ steal: true })) - await clickMenu(launched, 'Quick Chat') - await expect - .poll(() => windowState(launched, quickUrl)) - .toMatchObject({ visible: true, focused: true }) - await clickMenu(launched, 'Quick Chat') - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ visible: false }) - await clickMenu(launched, 'Quick Chat') - await expect.poll(() => windowState(launched, quickUrl)).toMatchObject({ visible: true }) - expect( - await quick.evaluate(() => (globalThis as { quickChatMarker?: string }).quickChatMarker) - ).toBe('kept') - } - ) + await test.step('the toggle brings a background panel forward, then hides it, keeping the page', async () => { + await quick.evaluate(() => { + ;(globalThis as { quickChatMarker?: string }).quickChatMarker = 'kept' + }) + // The hand-off focused the full window; the app must be active for window focus to land. + await app.evaluate(({ app }) => app.focus({ steal: true })) + await clickMenu(app, 'Quick Chat') + await expect + .poll(() => windowState(app, quickUrl)) + .toMatchObject({ visible: true, focused: true }) + await clickMenu(app, 'Quick Chat') + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ visible: false }) + await clickMenu(app, 'Quick Chat') + await expect.poll(() => windowState(app, quickUrl)).toMatchObject({ visible: true }) + expect( + await quick.evaluate(() => (globalThis as { quickChatMarker?: string }).quickChatMarker) + ).toBe('kept') + }) - await check('signing out destroys the panel with the account it belonged to', async () => { - await clickMenu(launched, 'Sign Out') + await test.step('signing out destroys the panel with the account it belonged to', async () => { + await clickMenu(app, 'Sign Out') // Found as the only always-on-top window, not by URL: sign-out sends full windows to /login. - await expect - .poll( - () => - launched.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isAlwaysOnTop()) - ), - { timeout: 30_000 } - ) - .toBe(false) + await expect.poll(() => hasFloatingWindow(app), { timeout: 30_000 }).toBe(false) + // Windows go to /login only once the whole account teardown has finished. + await expect(main.locator('#login')).toHaveText('fixture-login', { timeout: 30_000 }) }) }) - test('the shortcut setting and a failed first load', async () => { + test('the shortcut setting and a failed first load', async ({ desktop }) => { test.skip(process.platform !== 'darwin', 'Only macOS binds a shortcut by default') - const launched = await launchApp(fixture.origin, { quickChatShortcut: 'CommandOrControl+Q' }) - app = launched - const main = await launched.firstWindow() + const { app } = await desktop.launch({ + origin: fixture.origin, + settings: settings({ quickChatShortcut: 'CommandOrControl+Q' }), + }) + const main = await app.firstWindow() await expect(main.locator('#app')).toHaveText('workspace') - await check('a stored shortcut outside the presets falls back to the default', async () => { - const preferences = await main.evaluate(() => - ( - globalThis as unknown as { - simDesktop: { settings: { getPreferences(): Promise } } - } - ).simDesktop.settings.getPreferences() + await test.step('a stored shortcut outside the presets falls back to the default', async () => { + const preferences: DesktopPreferences = await main.evaluate(() => + (globalThis as DesktopBridge).simDesktop.settings.getPreferences() ) expect(preferences).toMatchObject({ quickChatShortcut: DEFAULT_SHORTCUT, quickChatShortcutAvailable: true, }) - expect(await isRegistered(launched, DEFAULT_SHORTCUT)).toBe(true) - expect(await isRegistered(launched, 'CommandOrControl+Q')).toBe(false) + expect(await isRegistered(app, DEFAULT_SHORTCUT)).toBe(true) + expect(await isRegistered(app, 'CommandOrControl+Q')).toBe(false) }) - await check('choosing another shortcut releases the old one and binds the new', async () => { + await test.step('choosing another shortcut releases the old one and binds the new', async () => { const next: QuickChatShortcut = 'CommandOrControl+Shift+Space' expect(await setShortcut(main, next)).toMatchObject({ quickChatShortcut: next, quickChatShortcutAvailable: true, }) - expect(await isRegistered(launched, next)).toBe(true) - expect(await isRegistered(launched, DEFAULT_SHORTCUT)).toBe(false) + expect(await isRegistered(app, next)).toBe(true) + expect(await isRegistered(app, DEFAULT_SHORTCUT)).toBe(false) }) - await check( - 'turning it off releases the shortcut and refuses values off the list', - async () => { - expect(await setShortcut(main, null)).toMatchObject({ - quickChatShortcut: null, - quickChatShortcutAvailable: true, - }) - expect(await isRegistered(launched, 'CommandOrControl+Shift+Space')).toBe(false) - expect(await setShortcut(main, 'CommandOrControl+Q')).toMatchObject({ - quickChatShortcut: null, - }) - expect(await isRegistered(launched, 'CommandOrControl+Q')).toBe(false) - } - ) + await test.step('turning it off releases the shortcut and refuses values off the list', async () => { + expect(await setShortcut(main, null)).toMatchObject({ + quickChatShortcut: null, + quickChatShortcutAvailable: true, + }) + expect(await isRegistered(app, 'CommandOrControl+Shift+Space')).toBe(false) + expect(await setShortcut(main, 'CommandOrControl+Q')).toMatchObject({ + quickChatShortcut: null, + }) + expect(await isRegistered(app, 'CommandOrControl+Q')).toBe(false) + }) - await check('a failed first load reloads when the panel is shown again', async () => { - fixture.setFailing('/extension/ws1', true) - const opened = launched.waitForEvent('window') - await clickMenu(launched, 'Quick Chat') + await test.step('a failed first load reloads when the panel is shown again', async () => { + failing.add(QUICK_ROUTE) + // Listens before the panel exists: its first load can fail before Playwright sees the page. + await app.evaluate(({ app }) => { + const state = globalThis as { quickChatLoadFailed?: boolean } + app.once('browser-window-created', (_event, win) => { + win.webContents.on( + 'did-fail-load', + (_failure, _code, _description, _url, isMainFrame) => { + if (isMainFrame) state.quickChatLoadFailed = true + } + ) + }) + }) + const opened = app.waitForEvent('window') + await clickMenu(app, 'Quick Chat') const quick = await opened - await quick.waitForLoadState().catch(() => {}) - expect(await quick.locator('#quick').count()).toBe(0) - fixture.setFailing('/extension/ws1', false) - await launched.evaluate(({ app }) => app.focus({ steal: true })) - // Pressing the shortcut either hides a focused panel or shows it again; each show after the - // failure reloads, so a few presses must land on the loaded page. await expect - .poll( - async () => { - if ((await quick.locator('#quick').count()) > 0) return true - await clickMenu(launched, 'Quick Chat') - return false - }, - { intervals: [1_000], timeout: 15_000 } + .poll(() => + app.evaluate(() => (globalThis as { quickChatLoadFailed?: boolean }).quickChatLoadFailed) ) .toBe(true) + await expect(quick.locator('#quick')).toHaveCount(0) + failing.delete(QUICK_ROUTE) + + // Focus the main window so the toggle reveals the panel rather than hiding a focused one. + await app.evaluate(({ app, BrowserWindow }, route) => { + const win = BrowserWindow.getAllWindows().find((candidate) => + candidate.webContents.getURL().endsWith(route) + ) + if (!win) throw new Error('Main window is missing') + app.focus({ steal: true }) + win.focus() + }, WORKSPACE_ROUTE) + await expect + .poll(() => windowState(app, `${fixture.origin}${WORKSPACE_ROUTE}`)) + .toMatchObject({ focused: true }) + await clickMenu(app, 'Quick Chat') await expect(quick.locator('#quick')).toHaveText('quick-chat') }) }) - test('stays closed while account data cannot be stored', async () => { + test('the toggle opens nothing while account data cannot be stored', async ({ desktop }) => { // An unreadable settings file blocks persistence, which makes account data unavailable. - const launched = await launchApp(fixture.origin, '[]') - app = launched - await launched.firstWindow() - await check( - 'the shortcut opens nothing while the window could not hold an account', - async () => { - await clickMenu(launched, 'Quick Chat') - await new Promise((resolveDelay) => setTimeout(resolveDelay, 1_500)) - expect( - await launched.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((win) => !win.isDestroyed() && win.isAlwaysOnTop()) - ) - ).toBe(false) - } - ) + const { app } = await desktop.launch({ origin: fixture.origin, settings: '[]' }) + await app.firstWindow() + // The toggle builds the window synchronously inside the menu click. + await clickMenu(app, 'Quick Chat') + expect(await hasFloatingWindow(app)).toBe(false) }) }) diff --git a/apps/desktop/e2e/session-cookies.spec.ts b/apps/desktop/e2e/session-cookies.spec.ts index 7c85b99e63f..ac55b5c5ec9 100644 --- a/apps/desktop/e2e/session-cookies.spec.ts +++ b/apps/desktop/e2e/session-cookies.spec.ts @@ -1,12 +1,14 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { type ElectronApplication, _electron as electron, expect, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' +import type { ElectronApplication, Page } from '@playwright/test' +import { + attachBrowserPanel, + expect, + type FixtureServer, + type LaunchOptions, + ToolAuthorizer, + test, +} from './harness' +import { serveSignedIn } from './session-fixture' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) const SCOPE = 'session-cookies-fixture' /** @@ -15,145 +17,68 @@ const SCOPE = 'session-cookies-fixture' * every restart. This drives a real quit and relaunch against one profile. */ test.describe('built-in browser session cookies', () => { - let server: Server - let origin: string - let site: string - let userData: string - let app: ElectronApplication | undefined - let serial = 0 + let fixture: FixtureServer let lastCookieHeader: string | undefined - const calls = new Map< - string, - { chatId: string; toolName: string; args: Record } - >() + const authorizer = new ToolAuthorizer('fixture') test.beforeAll(async () => { - server = createServer(async (request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/api/auth/get-session') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end( - JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) - ) - return - } - if (path === '/api/desktop/tool/authorize') { - let body = '' - for await (const chunk of request) body += chunk.toString() - const call = calls.get(JSON.parse(body).toolCallId) - response.writeHead(call ? 200 : 403, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(call ?? {})) - return - } - if (path.startsWith('/api/')) { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end('{}') - return - } - if (path === '/sign-in') { - // A login redirect that sets a short-lived cookie the next hop deletes. - response.writeHead(302, { - 'Set-Cookie': 'oauth_state=pending; HttpOnly; Path=/', - Location: '/signed-in', - }) - response.end() - return - } - if (path === '/signed-in') { - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': [ - 'oauth_state=; Path=/; Max-Age=0', - 'login=fixture; HttpOnly; SameSite=Lax; Path=/', - 'remember=1; Path=/; Max-Age=3600', - ], - }) - response.end('Signed in') - return - } - if (path === '/account') { - lastCookieHeader = request.headers.cookie ?? '' - response.writeHead(200, { 'Content-Type': 'text/html' }) - response.end('Account') - return - } - if (request.headers.host?.startsWith('localhost')) { - // Favicon and other stray site requests must not set the app session cookie on the site. - response.writeHead(404) - response.end() - return - } - response.writeHead(200, { - 'Content-Type': 'text/html', - 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', - }) - response.end('Sim fixture

Session cookie fixture

') + fixture = await serveSignedIn({ + page: 'Sim fixture

Session cookie fixture

', + handle: async (request, response, url) => { + if (await authorizer.handle(request, response, url)) return true + if (url.pathname === '/sign-in') { + // A login redirect that sets a short-lived cookie the next hop deletes. + response.writeHead(302, { + 'Set-Cookie': 'oauth_state=pending; HttpOnly; Path=/', + Location: '/signed-in', + }) + response.end() + return true + } + if (url.pathname === '/signed-in') { + response.writeHead(200, { + 'Content-Type': 'text/html', + 'Set-Cookie': [ + 'oauth_state=; Path=/; Max-Age=0', + 'login=fixture; HttpOnly; SameSite=Lax; Path=/', + 'remember=1; Path=/; Max-Age=3600', + ], + }) + response.end('Signed in') + return true + } + if (url.pathname === '/account') { + lastCookieHeader = request.headers.cookie ?? '' + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Account') + return true + } + if (request.headers.host?.startsWith('localhost')) { + // Favicon and other stray site requests must not set the app session cookie on the site. + response.writeHead(404) + response.end() + return true + } + return false + }, }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - /** Pages outside the app origin browse in the built-in browser's own partition. */ - site = `http://localhost:${address.port}` - }) - - test.beforeEach(() => { - userData = mkdtempSync(join(tmpdir(), 'sim-session-cookies-e2e-')) - }) - - test.afterEach(async () => { - await app?.close() - app = undefined - rmSync(userData, { recursive: true, force: true }) - calls.clear() }) test.afterAll(async () => { - await new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) + await fixture.close() }) - async function launch(): Promise { - const launched = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - const host = await launched.firstWindow() + async function openShell(app: ElectronApplication) { + const host = await app.firstWindow() await expect(host.getByRole('heading')).toHaveText('Session cookie fixture') - await host.evaluate(async (scope) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - await api.browserAgent.activateScope(scope) - const updateBounds = () => - api.browserAgent.setPanelBounds( - { x: 0, y: 80, width: innerWidth, height: innerHeight - 80 }, - null, - scope - ) - updateBounds() - setInterval(updateBounds, 200) - }, SCOPE) - return launched - } - - async function navigate(target: ElectronApplication, url: string) { - const id = `fixture-${++serial}` - calls.set(id, { chatId: SCOPE, toolName: 'browser_open_url', args: { url } }) - const host = await target.firstWindow() - const result = await host.evaluate( - async ({ id, url, scope }) => { - const api = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }).simDesktop - return api.browserAgent.executeTool(id, 'browser_open_url', { url }, scope) - }, - { id, url, scope: SCOPE } - ) - expect(result.ok, result.error).toBe(true) + await attachBrowserPanel(host, SCOPE) + return host } - async function cookiesSentToSite(target: ElectronApplication): Promise { + /** The cookies the built-in browser sends to the site (`fixture.site`, its own partition). */ + async function cookiesSentToSite(host: Page): Promise { lastCookieHeader = undefined - await navigate(target, `${site}/account`) + await authorizer.execute(host, SCOPE, 'browser_open_url', { url: `${fixture.site}/account` }) await expect.poll(() => lastCookieHeader).not.toBeUndefined() return (lastCookieHeader ?? '') .split(';') @@ -162,17 +87,26 @@ test.describe('built-in browser session cookies', () => { .sort() } - test('keeps a session-cookie login across a restart without reviving deleted cookies', async () => { - app = await launch() - await navigate(app, `${site}/sign-in`) - expect(await cookiesSentToSite(app)).toEqual(['login=fixture', 'remember=1']) + test('keeps a session-cookie login across a restart without reviving deleted cookies', async ({ + desktop, + }) => { + const options: LaunchOptions = { + origin: fixture.origin, + } + const first = await desktop.launch(options) + const host = await openShell(first.app) + await authorizer.execute(host, SCOPE, 'browser_open_url', { url: `${fixture.site}/sign-in` }) + expect(await cookiesSentToSite(host)).toEqual(['login=fixture', 'remember=1']) - await app.evaluate(({ session }) => + await first.app.evaluate(({ session }) => session.fromPartition('persist:sim-browser-agent').cookies.flushStore() ) - await app.close() + await desktop.close(first) - app = await launch() - expect(await cookiesSentToSite(app)).toEqual(['login=fixture', 'remember=1']) + const relaunched = await desktop.launch({ ...options, userData: first.userData }) + expect(await cookiesSentToSite(await openShell(relaunched.app))).toEqual([ + 'login=fixture', + 'remember=1', + ]) }) }) diff --git a/apps/desktop/e2e/session-fixture.ts b/apps/desktop/e2e/session-fixture.ts new file mode 100644 index 00000000000..71b29c4caed --- /dev/null +++ b/apps/desktop/e2e/session-fixture.ts @@ -0,0 +1,33 @@ +import { type FixtureHandler, type FixtureServer, serve } from './harness' + +export interface SignedInOriginOptions { + /** The HTML of every app page, served with the session cookie. */ + page: string + /** Sees each request first; returns true when it answered it. */ + handle?: (...args: Parameters) => boolean | Promise +} + +/** + * A fixture Sim origin with a signed-in user: the shell treats the window as signed in only when + * the session cookie is set and `/api/auth/get-session` returns a user. Every other `/api/` route + * answers `{}`. + */ +export function serveSignedIn({ page, handle }: SignedInOriginOptions): Promise { + return serve(async (request, response, url) => { + if (handle && (await handle(request, response, url))) return + if (url.pathname.startsWith('/api/')) { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end( + url.pathname === '/api/auth/get-session' + ? JSON.stringify({ user: { id: 'fixture-user' }, session: { id: 'fixture-session' } }) + : '{}' + ) + return + } + response.writeHead(200, { + 'Content-Type': 'text/html; charset=utf-8', + 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; SameSite=Lax; Path=/', + }) + response.end(page) + }) +} diff --git a/apps/desktop/e2e/smoke.spec.ts b/apps/desktop/e2e/smoke.spec.ts index 3d2f6e5bdb7..aca424f1d9d 100644 --- a/apps/desktop/e2e/smoke.spec.ts +++ b/apps/desktop/e2e/smoke.spec.ts @@ -1,13 +1,8 @@ -import { mkdtempSync } from 'node:fs' -import type { Server } from 'node:http' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import type { ElectronApplication } from '@playwright/test' -import { _electron as electron, expect, test } from '@playwright/test' +import type { ElectronApplication, Page } from '@playwright/test' +import { getErrorMessage } from '@sim/utils/errors' +import { expect, type FixtureServer, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) +const OFFLINE_ORIGIN = 'http://127.0.0.1:1' const PAGES: Record = { '/home': `Sim Fixture @@ -24,76 +19,74 @@ const PAGES: Record = { /** `User-Agent` of every request the fixture origin has served, in arrival order. */ const requestUserAgents: string[] = [] -function startFixtureServer(): Promise<{ server: Server; origin: string }> { - return new Promise((resolvePromise) => { - const server = createServer((request, response) => { +/** Runs an action that closes `page`, tolerating only the error from the page closing under it. */ +async function closeWith(page: Page, action: () => Promise): Promise { + const closed = page.waitForEvent('close') + await action().catch((error: unknown) => { + if (!getErrorMessage(error).includes('Target page, context or browser has been closed')) { + throw error + } + }) + await closed +} + +/** Replaces `shell.openExternal` with a recorder, read back by `openedExternally`. */ +async function recordExternalOpens(app: ElectronApplication): Promise { + await app.evaluate(({ shell }) => { + const opened: string[] = [] + ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened + shell.openExternal = async (url: string) => { + opened.push(url) + } + }) +} + +function openedExternally(app: ElectronApplication): Promise { + return app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) +} + +function dialogFits(page: Page): Promise { + return page + .getByRole('dialog') + .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) +} + +test.describe('desktop shell smoke', () => { + let fixture: FixtureServer + + test.beforeAll(async () => { + fixture = await serve((request, response, url) => { requestUserAgents.push(request.headers['user-agent'] ?? '') - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname const sessionCookie = request.headers.cookie ?.split(';') .map((cookie) => cookie.trim()) .includes('sim-e2e-session=shared') const body = - path === '/mcp' + url.pathname === '/mcp' ? sessionCookie ? '

oauth-popup

' : '

sign-in-required

' - : PAGES[path] + : PAGES[url.pathname] if (!body) { response.writeHead(404, { 'Content-Type': 'text/html' }).end('

not found

') return } response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }).end(body) }) - server.listen(0, '127.0.0.1', () => { - const address = server.address() - const port = typeof address === 'object' && address ? address.port : 0 - resolvePromise({ server, origin: `http://127.0.0.1:${port}` }) - }) - }) -} - -async function launchApp(origin: string): Promise { - return electron.launch({ - args: ['.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: origin, - SIM_DESKTOP_USER_DATA: mkdtempSync(join(tmpdir(), 'sim-desktop-e2e-')), - }, - }) -} - -test.describe('desktop shell smoke', () => { - let server: Server - let origin: string - let app: ElectronApplication - - test.beforeAll(async () => { - ;({ server, origin } = await startFixtureServer()) }) test.afterAll(async () => { - server.close() - }) - - test.afterEach(async () => { - await app?.close().catch(() => {}) - }) - - test('loads the configured origin top-level', async () => { - app = await launchApp(origin) - const window = await app.firstWindow() - await expect(window.locator('#app')).toHaveText('fixture-app') - expect(window.url()).toBe(`${origin}/home`) + await fixture.close() }) - test('presents one stock Chrome user agent on every request from the first load', async () => { + test('loads the configured origin top-level with one stock Chrome user agent on every request', async ({ + desktop, + }) => { requestUserAgents.length = 0 - app = await launchApp(origin) + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() await expect(window.locator('#app')).toHaveText('fixture-app') + expect(window.url()).toBe(`${fixture.origin}/home`) await window.evaluate(() => fetch('/home').then((response) => response.text())) const pageUserAgent = await window.evaluate(() => navigator.userAgent) @@ -104,8 +97,8 @@ test.describe('desktop shell smoke', () => { expect(new Set(requestUserAgents)).toEqual(new Set([pageUserAgent])) }) - test('internal window.open creates an independent full Sim window', async () => { - app = await launchApp(origin) + test('internal window.open creates an independent full Sim window', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() const newWindowPromise = app.waitForEvent('window') await window.locator('#internal-blank').click() @@ -115,30 +108,36 @@ test.describe('desktop shell smoke', () => { expect(app.windows()).toHaveLength(2) }) - test('external window.open goes to the system browser, never a new app window', async () => { - app = await launchApp(origin) + test('other origins open in the system browser, never in an app window or the app document', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() - await app.evaluate(({ shell }) => { - const opened: string[] = [] - ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened - shell.openExternal = async (url: string) => { - opened.push(url) - } - }) - await window.locator('#external-blank').click() - await expect - .poll(() => - app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) - ) - .toEqual(['https://docs.sim.ai/x']) - expect(app.windows()).toHaveLength(1) await expect(window.locator('#app')).toHaveText('fixture-app') + await recordExternalOpens(app) + + await test.step('window.open to another origin', async () => { + await window.locator('#external-blank').click() + await expect.poll(() => openedExternally(app)).toEqual(['https://docs.sim.ai/x']) + expect(app.windows()).toHaveLength(1) + await expect(window.locator('#app')).toHaveText('fixture-app') + }) + + await test.step('same-window navigation to another origin', async () => { + await window.locator('#external-navigate').click({ noWaitAfter: true }) + await expect + .poll(() => openedExternally(app)) + .toEqual(['https://docs.sim.ai/x', 'https://docs.sim.ai/navigation']) + expect(window.url()).toBe(`${fixture.origin}/home`) + }) }) - test('OAuth popups share the session without inheriting the privileged preload', async () => { - app = await launchApp(origin) + test('OAuth popups share the session without inheriting the privileged preload', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() - await window.waitForURL(`${origin}/home`, { waitUntil: 'load' }) + await window.waitForURL(`${fixture.origin}/home`, { waitUntil: 'load' }) await window.evaluate(() => { document.cookie = 'sim-e2e-session=shared; Path=/; SameSite=Lax' }) @@ -152,31 +151,10 @@ test.describe('desktop shell smoke', () => { .toBe('undefined') }) - test('cross-origin same-window navigation opens externally and preserves the app document', async () => { - app = await launchApp(origin) + test('unreachable origin shows the bundled offline page', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: OFFLINE_ORIGIN }) const window = await app.firstWindow() - await app.evaluate(({ shell }) => { - const opened: string[] = [] - ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened - shell.openExternal = async (url: string) => { - opened.push(url) - } - }) - - await window.locator('#external-navigate').click({ noWaitAfter: true }) - - await expect - .poll(() => - app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) - ) - .toEqual(['https://docs.sim.ai/navigation']) - expect(window.url()).toBe(`${origin}/home`) - }) - - test('unreachable origin shows the bundled offline page', async () => { - app = await launchApp('http://127.0.0.1:1') - const window = await app.firstWindow() - await window.waitForSelector('#retry', { timeout: 30_000 }) + await expect(window.locator('#retry')).toBeVisible({ timeout: 30_000 }) expect(window.url()).toMatch(/^sim-shell:\/\/pages\/offline\.html\?/) const home = window.getByRole('link', { name: 'Home', exact: true }) await expect(home).toBeVisible() @@ -196,9 +174,11 @@ test.describe('desktop shell smoke', () => { await expect(window.locator('#detail')).toHaveAttribute('role', 'status') }) - test('offline title-bar geometry follows native fullscreen state across reloads', async () => { + test('offline title-bar geometry follows native fullscreen state across reloads', async ({ + desktop, + }) => { test.skip(process.platform !== 'darwin', 'The traffic-light lane is macOS-specific') - app = await launchApp('http://127.0.0.1:1') + const { app } = await desktop.launch({ origin: OFFLINE_ORIGIN }) const window = await app.firstWindow() await expect(window.locator('#server')).toBeVisible() await expect(window.locator('html')).toHaveAttribute('data-sim-desktop-title-bar', 'inset') @@ -223,8 +203,10 @@ test.describe('desktop shell smoke', () => { .toBeGreaterThanOrEqual(38) }) - test('bundled dialogs follow the app theme independently of the system theme', async () => { - app = await launchApp(origin) + test('the hang recovery dialog is an isolated, app-themed EMCN dialog that defaults to Wait', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) const window = await app.firstWindow() await expect(window.locator('#app')).toBeVisible() await app.evaluate(({ nativeTheme }) => { @@ -232,143 +214,114 @@ test.describe('desktop shell smoke', () => { }) await window.evaluate(() => { document.documentElement.className = 'dark' + ;(globalThis as { __sameDocument?: boolean }).__sameDocument = true }) const dialogPromise = app.waitForEvent('window') await app.evaluate(({ BrowserWindow }) => { BrowserWindow.getAllWindows()[0].webContents.emit('unresponsive') }) const prompt = await dialogPromise - await expect(prompt.getByRole('dialog')).toBeVisible() - await expect(prompt.locator('html')).toHaveClass('dark') - await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'dark') - await expect(prompt.locator('#dialog-message')).toHaveCSS('-webkit-font-smoothing', 'auto') - await expect(prompt.locator('#dialog-message')).toHaveCSS('font-weight', '400') - await expect(prompt.locator('#dialog-message')).toHaveCSS('font-size', '14px') - await window.evaluate(() => { - document.documentElement.className = 'light' + + await test.step('isolated dialog with Wait focused', async () => { + await expect( + prompt.getByRole('dialog', { name: 'Sim isn’t responding', exact: true }) + ).toBeVisible() + await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() + await expect.poll(() => dialogFits(prompt)).toBe(true) + await expect + .poll(() => + prompt.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop) + ) + .toBe('undefined') }) - await expect(prompt.locator('html')).toHaveClass('light') - await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'light') - await prompt.getByRole('button', { name: 'Wait', exact: true }).click() - }) - test('recovery messages use an isolated EMCN dialog with a safe keyboard default', async () => { - app = await launchApp('http://127.0.0.1:1') - const window = await app.firstWindow() - await expect(window.locator('#server')).toBeVisible() - const dialogPromise = app.waitForEvent('window') - await app.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0].webContents.emit('unresponsive') + await test.step('follows the app theme, not the system theme', async () => { + await expect(prompt.locator('html')).toHaveClass('dark') + await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'dark') + await expect(prompt.locator('#dialog-message')).toHaveCSS('-webkit-font-smoothing', 'auto') + await expect(prompt.locator('#dialog-message')).toHaveCSS('font-weight', '400') + await expect(prompt.locator('#dialog-message')).toHaveCSS('font-size', '14px') + await window.evaluate(() => { + document.documentElement.className = 'light' + }) + await expect(prompt.locator('html')).toHaveClass('light') + await expect(prompt.locator('html')).toHaveCSS('color-scheme', 'light') }) - const prompt = await dialogPromise - await expect( - prompt.getByRole('dialog', { name: 'Sim isn’t responding', exact: true }) - ).toBeVisible() - await expect(prompt.getByText('Sim isn’t responding')).toBeVisible() - await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() - await expect - .poll(() => - prompt - .getByRole('dialog') - .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) - ) - .toBe(true) - await expect - .poll(() => prompt.evaluate(() => typeof (globalThis as { simDesktop?: unknown }).simDesktop)) - .toBe('undefined') - await prompt.screenshot({ - path: test.info().outputPath('recovery-dialog.png'), - animations: 'disabled', + + await test.step('a long message keeps every button reachable', async () => { + await app.evaluate(({ BrowserWindow }) => { + const win = BrowserWindow.getAllWindows().find( + (entry) => entry.webContents.getURL() === 'sim-shell://pages/dialog.html' + ) + if (!win) throw new Error('Recovery dialog is missing') + win.webContents.ipc.removeHandler('shell:configuration') + win.webContents.ipc.handle('shell:configuration', () => ({ + title: 'Long recovery message', + text: Array.from({ length: 80 }, (_, index) => `Diagnostic detail ${index + 1}`).join( + '\n' + ), + type: 'warning', + buttons: ['Wait', 'Reload'], + defaultId: 0, + cancelId: 0, + })) + win.webContents.reload() + }) + await expect( + prompt.getByRole('dialog', { name: 'Long recovery message', exact: true }) + ).toBeVisible() + await expect(prompt.getByRole('button', { name: 'Reload', exact: true })).toBeInViewport() + await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() }) - await app.evaluate(({ BrowserWindow }) => { - const win = BrowserWindow.getAllWindows().find( - (entry) => entry.webContents.getURL() === 'sim-shell://pages/dialog.html' + + await test.step('Enter waits instead of reloading', async () => { + await closeWith(prompt, () => + prompt.getByRole('button', { name: 'Wait', exact: true }).press('Enter') ) - if (!win) throw new Error('Recovery dialog is missing') - win.webContents.ipc.removeHandler('shell:configuration') - win.webContents.ipc.handle('shell:configuration', () => ({ - title: 'Long recovery message', - text: Array.from({ length: 80 }, (_, index) => `Diagnostic detail ${index + 1}`).join('\n'), - type: 'warning', - buttons: ['Wait', 'Reload'], - defaultId: 0, - cancelId: 0, - })) - win.webContents.reload() + await expect(window.locator('#app')).toBeVisible() + expect( + await window.evaluate(() => (globalThis as { __sameDocument?: boolean }).__sameDocument) + ).toBe(true) }) - await expect( - prompt.getByRole('dialog', { name: 'Long recovery message', exact: true }) - ).toBeVisible() - await expect(prompt.getByRole('button', { name: 'Reload', exact: true })).toBeInViewport() - await expect(prompt.getByRole('button', { name: 'Wait', exact: true })).toBeFocused() - const closed = prompt.waitForEvent('close') - await prompt - .getByRole('button', { name: 'Wait', exact: true }) - .press('Enter') - .catch(() => {}) - await closed - await expect(window.locator('#server')).toBeVisible() }) // The picker is the only way to repoint a shell whose server is unreachable. // Its page, the pre-filled value (which crosses the local-page IPC gate) and // Escape are asserted together because the packaged build once opened it as // a blank sheet with no way out. - test('the offline server picker handles validation and dismissal', async () => { - const testInfo = test.info() - app = await launchApp('http://127.0.0.1:1') + test('the offline server picker handles validation and dismissal', async ({ desktop }) => { + const { app } = await desktop.launch({ origin: OFFLINE_ORIGIN }) const window = await app.firstWindow() - await window.waitForSelector('#server', { timeout: 30_000 }) + await expect(window.locator('#server')).toBeVisible({ timeout: 30_000 }) const pickerPromise = app.waitForEvent('window') await window.locator('#server').click() const picker = await pickerPromise + const serverUrl = picker.getByLabel('Server URL') await expect(picker).toHaveURL('sim-shell://pages/server.html') await expect(picker.getByRole('dialog', { name: 'Sim server', exact: true })).toBeVisible() - await expect(picker.getByLabel('Server URL')).toHaveValue('http://127.0.0.1:1') - await expect(picker.getByLabel('Server URL')).toBeFocused() - await expect - .poll(() => - picker - .getByRole('dialog') - .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) - ) - .toBe(true) - await picker.getByLabel('Server URL').fill('http://example.com') - await picker.getByLabel('Server URL').press('Enter') + await expect(serverUrl).toHaveValue(OFFLINE_ORIGIN) + await expect(serverUrl).toBeFocused() + await expect.poll(() => dialogFits(picker)).toBe(true) + + await serverUrl.fill('http://example.com') + await serverUrl.press('Enter') await expect(picker.locator('#server-origin-errors')).toBeVisible() - await expect(picker.getByLabel('Server URL')).toHaveAccessibleDescription( - /Server URL must use HTTPS/ - ) - await expect(picker.getByLabel('Server URL')).toHaveAttribute('aria-invalid', 'true') - await picker.getByLabel('Server URL').fill('http://127.0.0.1:1') + await expect(serverUrl).toHaveAccessibleDescription(/Server URL must use HTTPS/) + await expect(serverUrl).toHaveAttribute('aria-invalid', 'true') + await serverUrl.fill(OFFLINE_ORIGIN) await expect(picker.locator('#server-origin-errors')).toHaveCount(0) - await expect(picker.getByLabel('Server URL')).not.toHaveAttribute('aria-invalid', 'true') + await expect(serverUrl).not.toHaveAttribute('aria-invalid', 'true') await picker.getByRole('button', { name: 'Connect', exact: true }).click() await expect(picker.getByRole('status')).toHaveText('Already connected to this server.') - await expect - .poll(() => - picker - .getByRole('dialog') - .evaluate((element) => element.scrollHeight <= globalThis.innerHeight) - ) - .toBe(true) - await picker.emulateMedia({ colorScheme: 'light' }) - await picker.screenshot({ - path: testInfo.outputPath('server-modal-light.png'), - animations: 'disabled', - }) + await expect.poll(() => dialogFits(picker)).toBe(true) + + // The picker follows the app's theme, not the system's. await picker.emulateMedia({ colorScheme: 'dark' }) await expect(picker.locator('[data-auth-root]')).toHaveCSS('color-scheme', 'light') - await picker.screenshot({ - path: testInfo.outputPath('server-modal-dark.png'), - animations: 'disabled', - }) - const closed = picker.waitForEvent('close') - await picker.keyboard.press('Escape').catch(() => {}) - await closed + await closeWith(picker, () => picker.keyboard.press('Escape')) expect(app.windows()).toHaveLength(1) }) }) diff --git a/apps/desktop/e2e/source-connect.spec.ts b/apps/desktop/e2e/source-connect.spec.ts index 6f5925bb3c9..d7c844fa32b 100644 --- a/apps/desktop/e2e/source-connect.spec.ts +++ b/apps/desktop/e2e/source-connect.spec.ts @@ -1,47 +1,18 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { chromium, _electron as electron, expect, test } from '@playwright/test' -import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' import { generateShortId } from '@sim/utils/id' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { bundleSimFixture, expect, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath( new URL('../../sim/scripts/fixtures/desktop-source-connect.tsx', import.meta.url) ) +const BROWSER_BUFFER = fileURLToPath(new URL('./fixtures/browser-buffer.ts', import.meta.url)) /** Real renderer, preload, main process, loopback, and a separate browser cookie jar. */ -test('source authorization returns to its desktop screen and refreshes live', async () => { - const reportPath = - process.env.DESKTOP_SOURCE_CONNECT_REPORT_PATH ?? test.info().outputPath('source-connect.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, action: () => Promise) => { - const started = Date.now() - try { - await test.step(name, action) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } +test('source authorization returns to its desktop screen and refreshes live', async ({ + desktop, + context, +}) => { const tickets = new Map() const attempts = new Map() const accountAttempts = new Map() @@ -60,14 +31,11 @@ test('source authorization returns to its desktop screen and refreshes live', as const personalAttempts = new Map() let personalInventoryFailed = false let personalInventoryFailures = 0 - let javascript = '' - let stylesheet = '' + /** The desktop state of each `/desktop/connect/complete` handoff the browser made. */ + const completedStates: string[] = [] + const bundle = await bundleSimFixture({ file: FIXTURE }, { inject: [BROWSER_BUFFER] }) let origin = '' - let app: Awaited> | undefined - let browser: Awaited> | undefined - const userData = mkdtempSync(join(tmpdir(), 'sim-source-connect-e2e-')) - const server = createServer(async (request, response) => { - const url = new URL(request.url ?? '/', origin || 'http://localhost') + const server = await serve(async (request, response, url) => { const path = url.pathname const session = request.headers.cookie?.includes('browser-fixture') ? 'browser-fixture' @@ -87,7 +55,7 @@ test('source authorization returns to its desktop screen and refreshes live', as } if (path === '/fixture.js' || path === '/fixture.css') { response.setHeader('content-type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end(path.endsWith('.js') ? javascript : stylesheet) + response.end(path.endsWith('.js') ? bundle.js : bundle.css) return } if (path === '/api/organizations/fixture-organization/connected-accounts') { @@ -165,6 +133,7 @@ test('source authorization returns to its desktop screen and refreshes live', as } if (path === '/api/desktop/source-connect') { const { requestId, request: sourceRequest } = await body() + // Outlives Chromium's ~5s transient user activation: opening the browser must not need it. if (startSessions.length === 0) await sleep(5_500) tickets.set(requestId, sourceRequest) json({ requestId }) @@ -361,6 +330,7 @@ test('source authorization returns to its desktop screen and refreshes live', as return } if (path === '/desktop/connect/complete') { + completedStates.push(url.searchParams.get('state') ?? '') const params = new URLSearchParams({ state: url.searchParams.get('state') ?? '' }) if (url.searchParams.has('error')) params.set('error', url.searchParams.get('error')!) if (url.searchParams.has('credentialId')) @@ -413,55 +383,22 @@ test('source authorization returns to its desktop screen and refreshes live', as '
' ) }) + origin = server.origin try { - await check('launch the production source hook and native bridge', async () => { - const config = await loadPostcssConfig({}, SIM_DIR) - const cssPath = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(cssPath, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: cssPath } - ) - const bundle = await build({ - entryPoints: [FIXTURE], - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - external: ['node:async_hooks'], - inject: [fileURLToPath(new URL('./fixtures/browser-buffer.ts', import.meta.url))], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - define: { 'process.env.NODE_ENV': '"development"' }, - }) - javascript = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text ?? '' - stylesheet = `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - origin = `http://127.0.0.1:${address.port}` - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { ...process.env, SIM_DESKTOP_ORIGIN: origin, SIM_DESKTOP_USER_DATA: userData }, - }) - await app.evaluate(({ shell }) => { - const global = globalThis as typeof globalThis & { openedUrls: string[] } - global.openedUrls = [] - shell.openExternal = async (url) => { - global.openedUrls.push(url) - } - }) - browser = await chromium.launch() + const { app: shell } = await desktop.launch({ origin }) + await shell.evaluate(({ shell }) => { + const global = globalThis as typeof globalThis & { openedUrls: string[] } + global.openedUrls = [] + shell.openExternal = async (url) => { + global.openedUrls.push(url) + } }) - if (!app || !browser) throw new Error('Missing apps') - const shell = app - const page = await app.firstWindow() + const page = await shell.firstWindow() const pageErrors: string[] = [] page.on('pageerror', (error) => pageErrors.push(error.message)) + // Reloads so errors from the first render, before the listener existed, are caught too. await page.reload() - await expect.poll(() => pageErrors).toEqual([]) - const context = await browser.newContext() + await expect(page.getByLabel('Source draft')).toBeVisible() await context.addCookies([ { name: 'better-auth.session_token', @@ -474,103 +411,97 @@ test('source authorization returns to its desktop screen and refreshes live', as const external = await context.newPage() const opened = () => shell.evaluate(() => (globalThis as typeof globalThis & { openedUrls: string[] }).openedUrls) - await check( - 'separate browser consent completes under its initiating session and refreshes desktop', - async () => { - await page.getByLabel('Source draft').fill('Preserved while connecting') - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(1) - expect(page.url()).toBe(`${origin}/home`) - await expect(page.getByLabel('Connection')).toHaveText('pending') - await external.goto((await opened())[0]) - await external.getByRole('link', { name: 'Authorize', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('success') - await expect(page.getByLabel('Accounts')).toHaveText('1') - await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') - expect(startSessions).toEqual(['browser-fixture']) - expect(callbackSessions).toEqual(['browser-fixture']) - await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) - } - ) - await check( - 'denied authorization returns an actionable error without navigating desktop', - async () => { - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(2) - await external.goto((await opened())[1]) - await external.getByRole('link', { name: 'Cancel', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('error') - await expect(page.getByRole('alert')).toContainText('Try connecting again') - expect(page.url()).toBe(`${origin}/home`) - await expect(page.getByLabel('Accounts')).toHaveText('1') - } - ) - await check( - 'native cancellation rejects a stale callback without disrupting the next request', - async () => { - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(3) - await external.goto((await opened())[2]) - await external.getByRole('link', { name: 'Authorize', exact: true }).waitFor() - const staleCallback = await external - .getByRole('link', { name: 'Authorize', exact: true }) - .getAttribute('href') - await expect(page.getByRole('button', { name: 'Cancel', exact: true })).toHaveCount(1) - await page.getByRole('button', { name: 'Cancel', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('error') - const canceled = new URL((await opened())[2]) - const probe = `http://127.0.0.1:${canceled.searchParams.get('port')}/connect/callback?state=${'x'.repeat(32)}` - await expect - .poll(() => - fetch(probe).then( - () => false, - () => true - ) + await test.step('separate browser consent completes under its initiating session and refreshes desktop', async () => { + await page.getByLabel('Source draft').fill('Preserved while connecting') + await page.getByRole('button', { name: 'Connect Slack' }).click() + // The first start outlives the default timeout on purpose (see /api/desktop/source-connect). + await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(1) + expect(page.url()).toBe(`${origin}/home`) + await expect(page.getByLabel('Connection')).toHaveText('pending') + await external.goto((await opened())[0]) + await external.getByRole('link', { name: 'Authorize', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('success') + await expect(page.getByLabel('Accounts')).toHaveText('1') + await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') + expect(startSessions).toEqual(['browser-fixture']) + expect(callbackSessions).toEqual(['browser-fixture']) + await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) + }) + await test.step('denied authorization returns an actionable error without navigating desktop', async () => { + await page.getByRole('button', { name: 'Connect Slack' }).click() + await expect.poll(async () => (await opened()).length).toBe(2) + await external.goto((await opened())[1]) + await external.getByRole('link', { name: 'Cancel', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('error') + await expect(page.getByRole('alert')).toContainText('Try connecting again') + expect(page.url()).toBe(`${origin}/home`) + await expect(page.getByLabel('Accounts')).toHaveText('1') + }) + await test.step('native cancellation rejects a stale callback without disrupting the next request', async () => { + await page.getByRole('button', { name: 'Connect Slack' }).click() + await expect.poll(async () => (await opened()).length).toBe(3) + await external.goto((await opened())[2]) + await external.getByRole('link', { name: 'Authorize', exact: true }).waitFor() + const staleCallback = await external + .getByRole('link', { name: 'Authorize', exact: true }) + .getAttribute('href') + await expect(page.getByRole('button', { name: 'Cancel', exact: true })).toHaveCount(1) + await page.getByRole('button', { name: 'Cancel', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('error') + const canceled = new URL((await opened())[2]) + const probe = `http://127.0.0.1:${canceled.searchParams.get('port')}/connect/callback?state=${'x'.repeat(32)}` + await expect + .poll(() => + fetch(probe).then( + () => false, + () => true ) - .toBe(true) - await page.getByRole('button', { name: 'Connect Slack' }).click() - await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(4) - await external.goto(`${origin}${staleCallback}`) - await expect(page.getByLabel('Connection')).toHaveText('pending') - await external.goto((await opened())[3]) - await external.getByRole('link', { name: 'Authorize', exact: true }).click() - await expect(page.getByLabel('Connection')).toHaveText('success') - await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') - } - ) - await check( - 'GitHub setup stays in the browser session and verifies the returned credential in desktop', - async () => { + ) + .toBe(true) + await page.getByRole('button', { name: 'Connect Slack' }).click() + await expect.poll(async () => (await opened()).length).toBe(4) + const handoffs = completedStates.length + await external.goto(`${origin}${staleCallback}`) + // The browser page hands the stale result back toward the canceled attempt's loopback. + await expect + .poll(() => completedStates.slice(handoffs)) + .toEqual([canceled.searchParams.get('state')]) + await expect(page.getByLabel('Connection')).toHaveText('pending') + await external.goto((await opened())[3]) + await external.getByRole('link', { name: 'Authorize', exact: true }).click() + await expect(page.getByLabel('Connection')).toHaveText('success') + await expect(page.getByLabel('Source draft')).toHaveValue('Preserved while connecting') + }) + await test.step('GitHub setup stays in the browser session and verifies the returned credential in desktop', async () => { + await page.getByRole('button', { name: 'Connect GitHub' }).click() + await expect.poll(async () => (await opened()).length).toBe(5) + await external.goto((await opened())[4]) + await external.getByRole('link', { name: 'Authorize GitHub' }).click() + await expect(page.getByLabel('GitHub error')).toContainText('not available') + await expect(page.getByLabel('GitHub credential')).toHaveText('') + nativeCredentialVisible = true + let releaseGithubInventory = () => {} + githubInventoryHold = new Promise((resolve) => { + releaseGithubInventory = resolve + }) + try { await page.getByRole('button', { name: 'Connect GitHub' }).click() - await expect.poll(async () => (await opened()).length).toBe(5) - await external.goto((await opened())[4]) + await expect.poll(async () => (await opened()).length).toBe(6) + await external.goto((await opened())[5]) await external.getByRole('link', { name: 'Authorize GitHub' }).click() - await expect(page.getByLabel('GitHub error')).toContainText('not available') - await expect(page.getByLabel('GitHub credential')).toHaveText('') - nativeCredentialVisible = true - let releaseGithubInventory = () => {} - githubInventoryHold = new Promise((resolve) => { - releaseGithubInventory = resolve - }) - try { - await page.getByRole('button', { name: 'Connect GitHub' }).click() - await expect.poll(async () => (await opened()).length).toBe(6) - await external.goto((await opened())[5]) - await external.getByRole('link', { name: 'Authorize GitHub' }).click() - await expect.poll(() => githubInventorySessions.length).toBe(2) - await expect(page.getByLabel('GitHub pending')).toHaveText('true') - } finally { - githubInventoryHold = undefined - releaseGithubInventory() - } - await expect(page.getByLabel('GitHub credential')).toHaveText('fixture-github-credential') - expect(githubStartSessions).toEqual(['browser-fixture', 'browser-fixture']) - expect(githubInventorySessions).toEqual(['desktop-fixture', 'desktop-fixture']) - await expect(page.getByLabel('GitHub pending')).toHaveText('false') - expect(page.url()).toBe(`${origin}/home`) + await expect.poll(() => githubInventorySessions.length).toBe(2) + await expect(page.getByLabel('GitHub pending')).toHaveText('true') + } finally { + githubInventoryHold = undefined + releaseGithubInventory() } - ) - await check('ordinary knowledge-base enrollment preserves its invitation step', async () => { + await expect(page.getByLabel('GitHub credential')).toHaveText('fixture-github-credential') + expect(githubStartSessions).toEqual(['browser-fixture', 'browser-fixture']) + expect(githubInventorySessions).toEqual(['desktop-fixture', 'desktop-fixture']) + await expect(page.getByLabel('GitHub pending')).toHaveText('false') + expect(page.url()).toBe(`${origin}/home`) + }) + await test.step('ordinary knowledge-base enrollment preserves its invitation step', async () => { await page.getByRole('button', { name: 'Connect invited source' }).click() await expect.poll(async () => (await opened()).length).toBe(7) await external.goto((await opened())[6]) @@ -579,7 +510,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(page.getByLabel('Enrollment error')).toHaveText('') expect(page.url()).toBe(`${origin}/home`) }) - await check('browser sign-in failures retain recovery guidance on desktop', async () => { + await test.step('browser sign-in failures retain recovery guidance on desktop', async () => { await page.getByRole('button', { name: 'Connect Slack' }).click() await expect.poll(async () => (await opened()).length).toBe(8) await external.goto((await opened())[7]) @@ -588,7 +519,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(page.getByRole('alert')).toContainText('Sign in to Sim in your browser') expect(page.url()).toBe(`${origin}/home`) }) - await check('managed accounts return through the desktop completion handoff', async () => { + await test.step('managed accounts return through the desktop completion handoff', async () => { await page.getByRole('button', { name: 'Connect MCP account', exact: true }).click() await expect.poll(async () => (await opened()).length).toBe(9) await external.goto((await opened())[8]) @@ -601,25 +532,22 @@ test('source authorization returns to its desktop screen and refreshes live', as const web = await context.newPage() web.on('pageerror', (error) => pageErrors.push(error.message)) await web.goto(`${origin}/o/fixture-organization/integrations?search=fixture`) - await check( - 'web authorization preserves the origin and refreshes after an isolated provider window', - async () => { - accountConnected = false - mcpAccountConnected = false - await web.reload() - await web.getByLabel('Source draft').fill('Web draft retained') - await expect(web.getByLabel('Account count')).toHaveText('0') - const popupReady = context.waitForEvent('page') - await web.getByRole('button', { name: 'Connect account', exact: true }).click() - const popup = await popupReady - await popup.getByRole('link', { name: 'Authorize account' }).click() - await expect(web.getByLabel('Account count')).toHaveText('1') - await expect(web.getByLabel('Account authorization', { exact: true })).toHaveText('success') - await expect(web.getByLabel('Source draft')).toHaveValue('Web draft retained') - expect(web.url()).toBe(`${origin}/o/fixture-organization/integrations?search=fixture`) - } - ) - await check('overlapping connect and reconnect preserve the active authorization', async () => { + await test.step('web authorization preserves the origin and refreshes after an isolated provider window', async () => { + accountConnected = false + mcpAccountConnected = false + await web.reload() + await web.getByLabel('Source draft').fill('Web draft retained') + await expect(web.getByLabel('Account count')).toHaveText('0') + const popupReady = context.waitForEvent('page') + await web.getByRole('button', { name: 'Connect account', exact: true }).click() + const popup = await popupReady + await popup.getByRole('link', { name: 'Authorize account' }).click() + await expect(web.getByLabel('Account count')).toHaveText('1') + await expect(web.getByLabel('Account authorization', { exact: true })).toHaveText('success') + await expect(web.getByLabel('Source draft')).toHaveValue('Web draft retained') + expect(web.url()).toBe(`${origin}/o/fixture-organization/integrations?search=fixture`) + }) + await test.step('overlapping connect and reconnect preserve the active authorization', async () => { const popupReady = context.waitForEvent('page') await web.getByRole('button', { name: 'Connect account', exact: true }).click() const popup = await popupReady @@ -632,7 +560,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await popup.getByRole('link', { name: 'Authorize account' }).click() await expect(web.getByLabel('Account authorization', { exact: true })).toHaveText('success') }) - await check('web denial and cancellation leave the initiating page usable', async () => { + await test.step('web denial and cancellation leave the initiating page usable', async () => { const popupReady = context.waitForEvent('page') await web.getByRole('button', { name: 'Connect account', exact: true }).click() const popup = await popupReady @@ -651,7 +579,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(web.getByRole('button', { name: 'Connect account', exact: true })).toBeEnabled() await expect(web.getByLabel('Account count')).toHaveText('1') }) - await check('reconnect uses the same completion lifecycle', async () => { + await test.step('reconnect uses the same completion lifecycle', async () => { const popupReady = context.waitForEvent('page') await web.getByRole('button', { name: 'Reconnect account', exact: true }).click() const popup = await popupReady @@ -659,7 +587,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(web.getByLabel('Reconnect status')).toHaveText('success') await expect(web.getByLabel('Source draft')).toHaveValue('Web draft retained') }) - await check('blocked popups complete in the same tab and return to Integrations', async () => { + await test.step('blocked popups complete in the same tab and return to Integrations', async () => { await web.evaluate(() => { window.open = () => null }) @@ -668,7 +596,7 @@ test('source authorization returns to its desktop screen and refreshes live', as await expect(web).toHaveURL(`${origin}/o/fixture-organization/integrations`) await expect(web.getByLabel('Account count')).toHaveText('1') }) - await check('canceling Slack setup aborts the pending web HTTP request', async () => { + await test.step('canceling Slack setup aborts the pending web HTTP request', async () => { holdSlackStart = true const starts = startSessions.length try { @@ -681,65 +609,59 @@ test('source authorization returns to its desktop screen and refreshes live', as holdSlackStart = false } }) - await check( - 'desktop Search preserves pending receipts after inventory failure and allows cancellation/retry', - async () => { - const previousOpens = (await opened()).length - await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() - await expect.poll(async () => (await opened()).length).toBe(previousOpens + 1) - await external.goto((await opened())[previousOpens]) - await external.getByRole('link', { name: 'Authorize personal Search' }).waitFor() - personalInventoryFailed = true - await external.getByRole('link', { name: 'Authorize personal Search' }).click() - await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) - await expect.poll(() => personalInventoryFailures).toBeGreaterThan(0) - await expect( - page.getByRole('button', { name: 'Connect personal Search', exact: true }) - ).toBeEnabled() - const receipt = () => - page.evaluate(() => { - const entry = Object.entries(localStorage).find(([key]) => - key.startsWith('sim.search-connection.') - ) - if (!entry) return null - const attempt: { completionId: string; status: string; credentialId?: string } = - JSON.parse(entry[1]) - return attempt - }) - const pendingReceipt = await receipt() - expect(pendingReceipt).toMatchObject({ status: 'pending' }) - await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() - expect(await receipt()).toEqual(pendingReceipt) - await page.getByRole('button', { name: 'Cancel personal Search', exact: true }).click() - await expect - .poll(receipt) - .toMatchObject({ completionId: pendingReceipt?.completionId, status: 'failed' }) - personalInventoryFailed = false - await page.getByRole('button', { name: 'Retry personal inventory', exact: true }).click() - await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() - await expect.poll(async () => (await opened()).length).toBe(previousOpens + 2) - const retryReceipt = await receipt() - expect(retryReceipt).toMatchObject({ status: 'pending' }) - expect(retryReceipt?.completionId).not.toBe(pendingReceipt?.completionId) - await external.goto((await opened())[previousOpens + 1]) - await external.getByRole('link', { name: 'Authorize personal Search' }).click() - await expect.poll(receipt).toMatchObject({ - completionId: retryReceipt?.completionId, - status: 'connected', - credentialId: 'fixture-personal-account', + await test.step('desktop Search preserves pending receipts after inventory failure and allows cancellation/retry', async () => { + const previousOpens = (await opened()).length + await page.getByRole('button', { name: 'Connect personal Search', exact: true }).click() + await expect.poll(async () => (await opened()).length).toBe(previousOpens + 1) + await external.goto((await opened())[previousOpens]) + await external.getByRole('link', { name: 'Authorize personal Search' }).waitFor() + personalInventoryFailed = true + await external.getByRole('link', { name: 'Authorize personal Search' }).click() + await expect(external).toHaveURL(`${origin}/desktop/done?kind=connect`) + await expect.poll(() => personalInventoryFailures).toBeGreaterThan(0) + await expect( + page.getByRole('button', { name: 'Connect personal Search', exact: true }) + ).toBeEnabled() + const receipt = () => + page.evaluate(() => { + const entry = Object.entries(localStorage).find(([key]) => + key.startsWith('sim.search-connection.') + ) + if (!entry) return null + const attempt: { completionId: string; status: string; credentialId?: string } = + JSON.parse(entry[1]) + return attempt }) - } - ) - await page.screenshot({ path: test.info().outputPath('source-connect-desktop.png') }) - } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ checks }, null, 2)) - await browser?.close() - await app?.close() - await new Promise((resolve) => { - server.close(() => resolve()) - server.closeAllConnections() + const pendingReceipt = await receipt() + expect(pendingReceipt).toMatchObject({ status: 'pending' }) + const connect = page.getByRole('button', { name: 'Connect personal Search', exact: true }) + await connect.click() + // Cancel lands after the second Connect, so failing the first attempt's receipt shows + // that Connect neither replaced it nor started another authorization. + await page.getByRole('button', { name: 'Cancel personal Search', exact: true }).click() + await expect + .poll(receipt) + .toMatchObject({ completionId: pendingReceipt?.completionId, status: 'failed' }) + expect(await opened()).toHaveLength(previousOpens + 1) + personalInventoryFailed = false + await page.getByRole('button', { name: 'Retry personal inventory', exact: true }).click() + // Connect stays disabled until the retried inventory offers the source again. + await expect(connect).toBeEnabled() + await connect.click() + await expect.poll(async () => (await opened()).length).toBe(previousOpens + 2) + const retryReceipt = await receipt() + expect(retryReceipt).toMatchObject({ status: 'pending' }) + expect(retryReceipt?.completionId).not.toBe(pendingReceipt?.completionId) + await external.goto((await opened())[previousOpens + 1]) + await external.getByRole('link', { name: 'Authorize personal Search' }).click() + await expect.poll(receipt).toMatchObject({ + completionId: retryReceipt?.completionId, + status: 'connected', + credentialId: 'fixture-personal-account', + }) }) - rmSync(userData, { recursive: true, force: true }) + expect(pageErrors).toEqual([]) + } finally { + await server.close() } }) diff --git a/apps/desktop/e2e/terminal-cancel.spec.ts b/apps/desktop/e2e/terminal-cancel.spec.ts index 1d639b7dacc..b030b0e3358 100644 --- a/apps/desktop/e2e/terminal-cancel.spec.ts +++ b/apps/desktop/e2e/terminal-cancel.spec.ts @@ -1,13 +1,17 @@ import { execFileSync } from 'node:child_process' -import { chmodSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { chmodSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { type ElectronApplication, expect, type Page, test } from '@playwright/test' -import type { SimDesktopApi } from '@sim/desktop-bridge' -import { sleep } from '@sim/utils/helpers' +import type { Page } from '@playwright/test' import { randomInt } from '@sim/utils/random' -import { recordCheck } from './check-report' -import { FixtureSim, launch, processRunning, registeredDevice, settled } from './executor-sim' +import { + type ExecutorApp, + FixtureSim, + launchAgainst, + processRunning, + registeredDevice, + settled, +} from './executor-sim' +import { type DesktopBridge, type DesktopFixture, expect, test } from './harness' /** * Stopping the agent's terminal commands in the real app, with real shells and a real tmux @@ -19,8 +23,9 @@ import { FixtureSim, launch, processRunning, registeredDevice, settled } from '. * Agent commands in a plain shell ignore SIGHUP, SIGINT and SIGTERM, so closing the shell cannot * end them by accident: only Sim's own stop, which escalates to SIGKILL on the command's process * group, does. The user's commands ignore the same signals, so a stop that reached them would - * show. Each launch gets its own tmux server (TMUX_TMPDIR), which the app's shells and its tmux - * calls inherit. The tmux scenarios skip where tmux is not installed. + * show. Each test gets its own tmux server (TMUX_TMPDIR), which the app's shells and its tmux + * calls inherit. The tmux scenarios skip where tmux is not installed, except in CI, which + * installs it. */ const CHAT_PLAIN = 'chat-cancel-plain' @@ -30,8 +35,6 @@ const TMUX_SESSION = 'agent-e2e' const STUBBORN = "trap '' HUP INT TERM" const sim = new FixtureSim() -/** The app's own log output for the current test, attached when it fails. */ -const appOutput: string[] = [] /** The shells, sleeps and tmux processes running, for a failure about who started what. */ function processes(): string { @@ -71,8 +74,13 @@ function findTmux(): string | null { } } -/** One launch's own tmux server, and a way to read and reshape it as the user would. */ +function requireTmux(): void { + test.skip(!REAL_TMUX, 'tmux is not installed on this machine') +} + +/** One test's own tmux server, and a way to read and reshape it as the user would. */ class TmuxServer { + /** Short and under /tmp: the server's socket path must fit in 104 bytes. */ readonly dir = mkdtempSync('/tmp/sim-tmux-') run(args: string[]): string { @@ -102,9 +110,9 @@ class TmuxServer { } } - /** The pane an agent run opened, found by the run script it was started with. */ - runPane(): { id: string; runId: string } | undefined { - return this.panes().find((pane) => pane.command.includes('run.sh')) + /** The panes agent runs opened, found by the run script they were started with. */ + runPanes(): Array<{ id: string; runId: string }> { + return this.panes().filter((pane) => pane.command.includes('run.sh')) } hasPane(id: string): boolean { @@ -124,18 +132,19 @@ class TmuxServer { } } - kill(): void { + remove(): void { try { this.run(['kill-server']) } catch { // Already gone. } + rmSync(this.dir, { recursive: true, force: true }) } } /** A `tmux` ahead of the real one on PATH that refuses pane options, as tmux before 3.0 does. */ -function oldTmuxPath(): string { - const dir = mkdtempSync(join(tmpdir(), 'sim-old-tmux-')) +function oldTmuxPath(desktop: DesktopFixture): string { + const dir = desktop.tempDir('sim-old-tmux-') const binary = join(dir, 'tmux') writeFileSync( binary, @@ -156,8 +165,7 @@ function bridge(window: Page) { /** The user opens a terminal tab in a chat's terminal panel and starts a command in it. */ async userRuns(scope: string, command: string): Promise { const terminalId = await window.evaluate(async (scopeId) => { - const terminal = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }) - .simDesktop.terminal + const terminal = (globalThis as DesktopBridge).simDesktop.terminal await terminal.activateScope(scopeId) terminal.setVisible?.(true, scopeId) terminal.setFocused(true, scopeId) @@ -169,17 +177,14 @@ function bridge(window: Page) { await window.keyboard.press('Shift') await window.evaluate( ([id, text, scopeId]) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.terminal.write(id, text, scopeId), + (globalThis as DesktopBridge).simDesktop.terminal.write(id, text, scopeId), [terminalId, `${command}\r`, scope] as const ) }, /** The user puts a chat away: its terminals close, though tmux runs started in them go on. */ async putAway(scope: string): Promise { return window.evaluate(async (scopeId) => { - const terminal = (globalThis as typeof globalThis & { simDesktop: SimDesktopApi }) - .simDesktop.terminal + const terminal = (globalThis as DesktopBridge).simDesktop.terminal await terminal.activateScope(scopeId) return terminal.suspendScope(scopeId) }, scope) @@ -187,9 +192,7 @@ function bridge(window: Page) { async setTerminalEnabled(enabled: boolean): Promise { await window.evaluate( (value) => - ( - globalThis as typeof globalThis & { simDesktop: SimDesktopApi } - ).simDesktop.settings.setPreference('terminalEnabled', value), + (globalThis as DesktopBridge).simDesktop.settings.setPreference('terminalEnabled', value), enabled ) }, @@ -202,14 +205,16 @@ async function agentRunsPlain(deviceId: string, seconds: number): Promise processRunning(`${slept(seconds)}`), { timeout: 30_000 }).toBe(true) + await expect.poll(() => processRunning(slept(seconds)), { timeout: 30_000 }).toBe(true) return call } -/** - * The agent's terminal attaches to tmux (the agent starts a tmux client in it), and the agent then - * runs a command, which tmux gives its own tagged pane. Resolves with the call and that pane. - */ +/** The user starts a stubborn command in a tab of their own; resolves once it is running. */ +async function userRunsPlain(window: Page, seconds: number): Promise { + await bridge(window).userRuns(CHAT_PLAIN, stubborn(seconds)) + await expect.poll(() => processRunning(slept(seconds)), { timeout: 30_000 }).toBe(true) +} + /** The agent starts a tmux client in its chat's terminal, so its runs go to tmux panes. */ async function agentAttachesTmux(deviceId: string, tmux: TmuxServer): Promise { const before = tmux.clients() @@ -218,8 +223,17 @@ async function agentAttachesTmux(deviceId: string, tmux: TmuxServer): Promise tmux.clients(), { timeout: 30_000 }).toBe(before + 1) - // The terminal's attachment is looked up again once its short cache lapses. - await sleep(3_500) + // The terminal remembers for a few seconds that it was not in tmux. Listing panes only works + // once it sees the attachment, and the run that follows then goes to tmux as well. + await expect + .poll( + async () => { + const probe = sim.issue(deviceId, CHAT_TMUX, 'terminal', { operation: 'panes', args: {} }) + return (await settled(sim, probe)).status + }, + { timeout: 30_000 } + ) + .toBe('success') } /** @@ -233,6 +247,17 @@ async function agentRunsInTmux( waitSeconds = 120 ): Promise<{ call: string; pane: { id: string; runId: string } }> { await agentAttachesTmux(deviceId, tmux) + return agentRunsInAttachedTmux(deviceId, tmux, seconds, waitSeconds) +} + +/** {@link agentRunsInTmux} in a chat terminal that is already attached. */ +async function agentRunsInAttachedTmux( + deviceId: string, + tmux: TmuxServer, + seconds: number, + waitSeconds: number +): Promise<{ call: string; pane: { id: string; runId: string } }> { + const known = new Set(tmux.runPanes().map((pane) => pane.id)) // It ignores Ctrl-C, so stopping it takes closing its pane, the step that must spare the user's. const call = sim.issue(deviceId, CHAT_TMUX, 'terminal', { operation: 'run', @@ -241,18 +266,37 @@ async function agentRunsInTmux( waitSeconds, }, }) - await expect.poll(() => processRunning(`${slept(seconds)}`), { timeout: 30_000 }).toBe(true) - await expect.poll(() => tmux.runPane(), { timeout: 10_000 }).toBeTruthy() - return { call, pane: tmux.runPane() as { id: string; runId: string } } + await expect.poll(() => processRunning(slept(seconds)), { timeout: 30_000 }).toBe(true) + const newPane = () => tmux.runPanes().find((pane) => !known.has(pane.id)) + await expect.poll(newPane, { timeout: 10_000 }).toBeTruthy() + return { call, pane: newPane() as { id: string; runId: string } } } async function claimed(call: string): Promise { await expect.poll(() => sim.requireCall(call).claims, { timeout: 30_000 }).toBe(1) } +/** The runs this app has recorded for a later process to find. */ +function recordedRuns(userData: string): string[] { + try { + return readdirSync(join(userData, 'terminal-runs')) + } catch { + return [] + } +} + +/** Where a recorded run stands: `started`, or `delivered` once the model has its pane. */ +function recordedRunState(userData: string, runId: string): unknown { + try { + return JSON.parse(readFileSync(join(userData, 'terminal-runs', `${runId}.json`), 'utf8')).state + } catch { + return undefined + } +} + test.describe('terminal cancel', () => { - let app: ElectronApplication | null = null let tmux: TmuxServer + let launched: ExecutorApp[] = [] const leftovers: string[] = [] test.beforeAll(async () => { @@ -260,17 +304,13 @@ test.describe('terminal cancel', () => { }) test.beforeEach(() => { + // CI installs tmux, so a runner without it fails instead of quietly skipping half the suite. + if (process.env.CI) expect(REAL_TMUX, 'tmux is not installed').not.toBeNull() tmux = new TmuxServer() }) - test.afterEach(async () => { + test.afterEach(async ({ desktop }) => { const testInfo = test.info() - recordCheck(process.env.TERMINAL_CANCEL_REPORT_PATH, 'terminal-cancel', { - name: testInfo.title, - status: testInfo.status ?? 'unknown', - durationMs: testInfo.duration, - retry: testInfo.retry, - }) if (testInfo.status !== testInfo.expectedStatus) { // What each call came back with, and the panes tmux held, explain most failures. const calls = [...sim.calls.values()].map((call) => ({ @@ -286,23 +326,22 @@ test.describe('terminal cancel', () => { await testInfo.attach('calls', { body: JSON.stringify({ calls, panes: tmux.panes() }, null, 2), }) - await testInfo.attach('app-output', { body: appOutput.join('').slice(-6_000) }) + for (const [index, app] of launched.entries()) { + await testInfo.attach(`app-output-${index + 1}`, { body: app.output().slice(-6_000) }) + } await testInfo.attach('processes', { body: processes() }) } - appOutput.length = 0 - // Quitting with a command still running in a tab asks first (natively, on macOS), and nobody - // is there to answer, so a close that does not finish promptly ends the app instead. - const closing = app - const closed = await Promise.race([ - closing?.close().then( - () => true, - () => true - ) ?? Promise.resolve(true), - sleep(5_000).then(() => false), - ]) - if (!closed) closing?.process().kill('SIGKILL') - app = null - tmux.kill() + // Quit while the tmux server and the fixture Sim still answer, so a stall is the app's own. + let quitFailure: unknown + for (const app of launched) { + try { + await desktop.close(app) + } catch (error) { + quitFailure ??= error + } + } + launched = [] + tmux.remove() for (const pattern of leftovers.splice(0)) { try { execFileSync('pkill', ['-9', '-f', pattern]) @@ -311,33 +350,49 @@ test.describe('terminal cancel', () => { } } sim.reset() + if (quitFailure) throw quitFailure }) test.afterAll(async () => { await sim.stop() }) + /** Launches the app on this test's tmux server, on `userData` when relaunching. */ + async function launch( + desktop: DesktopFixture, + options: { userData?: string; env?: Record } = {} + ): Promise { + const app = await launchAgainst(desktop, sim, { + userData: options.userData, + env: { TMUX_TMPDIR: tmux.dir, ...options.env }, + }) + launched.push(app) + return app + } + async function start( - name: string, + desktop: DesktopFixture, env: Record = {} - ): Promise<{ window: Page; deviceId: string; userData: string }> { - const userData = mkdtempSync(join(tmpdir(), `sim-cancel-${name}-`)) - const launched = await launch(sim, userData, { TMUX_TMPDIR: tmux.dir, ...env }) - app = launched.app - launched.app.process().stdout?.on('data', (chunk: Buffer) => appOutput.push(chunk.toString())) - launched.app.process().stderr?.on('data', (chunk: Buffer) => appOutput.push(chunk.toString())) + ): Promise { + const app = await launch(desktop, { env }) const deviceId = await registeredDevice(sim) - await launched.window.goto(`${sim.origin}/workspace/ws-e2e/chat/${CHAT_PLAIN}`) - return { window: launched.window, deviceId, userData } + await app.window.goto(`${sim.origin}/workspace/ws-e2e/chat/${CHAT_PLAIN}`) + return { ...app, deviceId } } - test('Stop ends the agent command in a plain shell and leaves the user command running', async () => { - const { window, deviceId } = await start('stop-plain') + /** The app dies without a word: its shells go with it, and its tmux runs outlive it. */ + function crash(app: ExecutorApp): void { + app.child.kill('SIGKILL') + } + + test('Stop ends the agent command in a plain shell and leaves the user command running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) leftovers.push(slept(701), slept(702)) // The agent's terminal comes first; the user's own tab opens beside it. const call = await agentRunsPlain(deviceId, 701) - await bridge(window).userRuns(CHAT_PLAIN, stubborn(702)) - await expect.poll(() => processRunning(slept(702)), { timeout: 30_000 }).toBe(true) + await userRunsPlain(window, 702) sim.stopCall(call) @@ -346,9 +401,11 @@ test.describe('terminal cancel', () => { expect(processRunning(slept(702))).toBe(true) }) - test('Stop interrupts a tagged tmux run and closes only its pane, never the user pane beside it', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId } = await start('stop-tmux') + test('Stop interrupts a tagged tmux run and closes only its pane, never the user pane beside it', async ({ + desktop, + }) => { + requireTmux() + const { deviceId } = await start(desktop) leftovers.push(slept(711), slept(712)) const { call, pane } = await agentRunsInTmux(deviceId, tmux, 711) expect(pane.runId).not.toBe('') @@ -363,15 +420,17 @@ test.describe('terminal cancel', () => { expect(processRunning(slept(712))).toBe(true) }) - test('signing out stops every agent command and leaves the user commands running', async () => { - const { window, deviceId } = await start('sign-out') + test('signing out stops every agent command and leaves the user commands running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) leftovers.push(slept(721), slept(722), slept(723), slept(724)) const plain = await agentRunsPlain(deviceId, 721) await claimed(plain) - await bridge(window).userRuns(CHAT_PLAIN, stubborn(722)) - await expect.poll(() => processRunning(slept(722)), { timeout: 30_000 }).toBe(true) + await userRunsPlain(window, 722) const run = REAL_TMUX ? await agentRunsInTmux(deviceId, tmux, 723) : null const users = run ? tmux.split(run.pane.id, stubborn(724)) : null + if (users) await expect.poll(() => processRunning(slept(724)), { timeout: 15_000 }).toBe(true) // The web app signs out by navigating to its login page. await window.goto(`${sim.origin}/login?fromLogout=true`) @@ -386,53 +445,45 @@ test.describe('terminal cancel', () => { } }) - test('a session ended by another account signing in stops every agent command and leaves the user pane running', async () => { - const { window, deviceId } = await start('account') - leftovers.push(slept(731), slept(733), slept(734)) + // Sign-out, the session ending and Terminal off all stop through the same stop for everything; + // the sign-out test covers its tmux side, so these two prove only that their trigger reaches it. + test('a session ended by another account signing in stops the agent command and leaves the user command running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) + leftovers.push(slept(731), slept(732)) await agentRunsPlain(deviceId, 731) - const run = REAL_TMUX ? await agentRunsInTmux(deviceId, tmux, 733) : null - const users = run ? tmux.split(run.pane.id, stubborn(734)) : null - if (users) await expect.poll(() => processRunning(slept(734)), { timeout: 15_000 }).toBe(true) + await userRunsPlain(window, 732) // Another account signing in replaces the session: the old session cookie goes away. await window.goto(`${sim.origin}/session-ended`) await expect.poll(() => processRunning(slept(731)), { timeout: 30_000 }).toBe(false) - if (run && users) { - await expect.poll(() => processRunning(slept(733)), { timeout: 15_000 }).toBe(false) - await expect.poll(() => tmux.hasPane(run.pane.id), { timeout: 10_000 }).toBe(false) - expect(tmux.hasPane(users)).toBe(true) - expect(processRunning(slept(734))).toBe(true) - } + expect(processRunning(slept(732))).toBe(true) }) - test('switching Terminal off stops every agent command and leaves the user commands running', async () => { - const { window, deviceId } = await start('terminal-off') - leftovers.push(slept(741), slept(743), slept(744)) + test('switching Terminal off stops the agent command and leaves the user command running', async ({ + desktop, + }) => { + const { window, deviceId } = await start(desktop) + leftovers.push(slept(741), slept(742)) await agentRunsPlain(deviceId, 741) - const run = REAL_TMUX ? await agentRunsInTmux(deviceId, tmux, 743) : null - const users = run ? tmux.split(run.pane.id, stubborn(744)) : null + await userRunsPlain(window, 742) await bridge(window).setTerminalEnabled(false) await expect.poll(() => processRunning(slept(741)), { timeout: 30_000 }).toBe(false) - if (run && users) { - await expect.poll(() => processRunning(slept(743)), { timeout: 15_000 }).toBe(false) - await expect.poll(() => tmux.hasPane(run.pane.id), { timeout: 10_000 }).toBe(false) - expect(tmux.hasPane(users)).toBe(true) - expect(processRunning(slept(744))).toBe(true) - } + expect(processRunning(slept(742))).toBe(true) }) - test('signing out stops a tmux run whose chat was put away', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { window, deviceId, userData } = await start('put-away') + test('signing out stops a tmux run whose chat was put away', async ({ desktop }) => { + requireTmux() + const { window, deviceId, userData } = await start(desktop) leftovers.push(slept(801)) const { pane } = await agentRunsInTmux(deviceId, tmux, 801) // No live terminal holds the run any more; only its record does. expect(await bridge(window).putAway(CHAT_TMUX)).toBe(true) - await sleep(1_000) expect(processRunning(slept(801))).toBe(true) await window.goto(`${sim.origin}/login?fromLogout=true`) @@ -442,167 +493,127 @@ test.describe('terminal cancel', () => { await expect.poll(() => recordedRuns(userData), { timeout: 10_000 }).toEqual([]) }) - /** The app dies without a word: its shells go with it, and its tmux runs outlive it. */ - function crash(): void { - app?.process().kill('SIGKILL') - app = null - } - - /** The runs this app has recorded for a later process to find. */ - function recordedRuns(userData: string): string[] { - try { - return readdirSync(join(userData, 'terminal-runs')) - } catch { - return [] - } - } - - test('the launch after an interrupted sign-out stops the tmux run the previous app left running', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('recovery') + test('the launch after an interrupted sign-out stops the tmux run the previous app left running', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) leftovers.push(slept(751)) - const { pane } = await agentRunsInTmux(deviceId, tmux, 751) + const { pane } = await agentRunsInTmux(first.deviceId, tmux, 751) // The app dies mid sign-out: its recovery marker is on disk and the tmux run outlives it. - crash() + crash(first) writeFileSync( - join(userData, 'account-data-teardown-required.json'), + join(first.userData, 'account-data-teardown-required.json'), JSON.stringify({ version: 2, kind: 'account', origin: sim.origin }) ) expect(processRunning(slept(751))).toBe(true) - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app + await launch(desktop, { userData: first.userData }) await expect.poll(() => processRunning(slept(751)), { timeout: 30_000 }).toBe(false) expect(tmux.hasPane(pane.id)).toBe(false) - await expect.poll(() => recordedRuns(userData), { timeout: 10_000 }).toEqual([]) + await expect.poll(() => recordedRuns(first.userData), { timeout: 10_000 }).toEqual([]) }) - test('the launch after a crash stops the tmux run its call can no longer report', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('crash-live') + test('the launch after a crash stops the tmux run its call can no longer report', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) leftovers.push(slept(771), slept(772)) - const { pane } = await agentRunsInTmux(deviceId, tmux, 771) + const { pane } = await agentRunsInTmux(first.deviceId, tmux, 771) const users = tmux.split(pane.id, stubborn(772)) // Same user, plain crash: the journal settles the call as outcome unknown, and nothing will // ever read what the command does. - crash() + crash(first) expect(processRunning(slept(771))).toBe(true) - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app + await launch(desktop, { userData: first.userData }) await expect.poll(() => processRunning(slept(771)), { timeout: 30_000 }).toBe(false) expect(tmux.hasPane(pane.id)).toBe(false) expect(tmux.hasPane(users)).toBe(true) expect(processRunning(slept(772))).toBe(true) - await expect.poll(() => recordedRuns(userData), { timeout: 10_000 }).toEqual([]) + await expect.poll(() => recordedRuns(first.userData), { timeout: 10_000 }).toEqual([]) }) - test('the launch after a crash only forgets a tmux run that had already finished', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('crash-finished') + test('the launch after a crash only forgets a tmux run that had already finished', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) leftovers.push(slept(6), slept(782)) // Handed back as still running, it then finishes on its own. - const { call, pane } = await agentRunsInTmux(deviceId, tmux, 6, 2) + const { call, pane } = await agentRunsInTmux(first.deviceId, tmux, 6, 2) await settled(sim, call) const users = tmux.split(pane.id, stubborn(782)) await expect.poll(() => tmux.hasPane(pane.id), { timeout: 20_000 }).toBe(false) - expect(recordedRuns(userData)).toHaveLength(1) + expect(recordedRuns(first.userData)).toHaveLength(1) - crash() - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app + crash(first) + await launch(desktop, { userData: first.userData }) - await expect.poll(() => recordedRuns(userData), { timeout: 30_000 }).toEqual([]) + await expect.poll(() => recordedRuns(first.userData), { timeout: 30_000 }).toEqual([]) expect(tmux.hasPane(users)).toBe(true) expect(processRunning(slept(782))).toBe(true) }) - test('a run handed back as still going survives a quit and the relaunch, and can still be read', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('collectable') - leftovers.push(slept(811)) - const { call, pane } = await agentRunsInTmux(deviceId, tmux, 811, 2) - const handedBack = await settled(sim, call) - expect(handedBack.data).toMatchObject({ status: 'running', pane: pane.id }) - - // Quitting stops no tmux run; the relaunch leaves one the model may come back to. - const quitting = app - app = null - const quit = await Promise.race([ - quitting?.close().then(() => true) ?? Promise.resolve(true), - sleep(10_000).then(() => false), - ]) - if (!quit) quitting?.process().kill('SIGKILL') + test('a run handed back as still going survives a quit and the relaunch, and can still be read', async ({ + desktop, + }) => { + requireTmux() + const first = await start(desktop) + leftovers.push(slept(811), slept(812)) + const kept = await agentRunsInTmux(first.deviceId, tmux, 811, 2) + const handedBack = await settled(sim, kept.call) + expect(handedBack.data).toMatchObject({ status: 'running', pane: kept.pane.id }) + await expect.poll(() => recordedRunState(first.userData, kept.pane.runId)).toBe('delivered') + // Still running when the app quits, so its result never reaches the model: the relaunch stops + // it, which is also how this test knows the relaunch has decided about every recorded run. + const uncollectable = await agentRunsInAttachedTmux(first.deviceId, tmux, 812, 120) + + // Quitting stops no tmux run. + await desktop.close(first) expect(processRunning(slept(811))).toBe(true) - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app - // Same install, same device: it is back once its doorbell is open again. - const relaunched = await registeredDevice(sim) - await sleep(5_000) + expect(processRunning(slept(812))).toBe(true) + + await launch(desktop, { userData: first.userData }) + await expect.poll(() => processRunning(slept(812)), { timeout: 30_000 }).toBe(false) + await expect + .poll(() => recordedRuns(first.userData), { timeout: 10_000 }) + .toEqual([`${kept.pane.runId}.json`]) + expect(tmux.hasPane(uncollectable.pane.id)).toBe(false) expect(processRunning(slept(811))).toBe(true) - expect(tmux.hasPane(pane.id)).toBe(true) - expect(recordedRuns(userData)).toHaveLength(1) + expect(tmux.hasPane(kept.pane.id)).toBe(true) - // The model comes back to the pane it was handed. + // Same install, same device: it is back once its doorbell is open again, and the model comes + // back to the pane it was handed. + const relaunched = await registeredDevice(sim) await agentAttachesTmux(relaunched, tmux) const read = sim.issue(relaunched, CHAT_TMUX, 'terminal', { operation: 'read', - args: { pane: pane.id, lines: 50 }, + args: { pane: kept.pane.id, lines: 50 }, }) const output = await settled(sim, read) expect(output.status, output.message).toBe('success') expect(JSON.stringify(output.data)).toContain('collect-me') }) - test("never touches a pane that took a recorded run's id after tmux restarted", async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { deviceId, userData } = await start('stale-record') - leftovers.push(slept(791), slept(792)) - const { pane } = await agentRunsInTmux(deviceId, tmux, 791) - crash() - - // tmux restarts, ending the run with it, and the user's own pane gets the run's old id. - tmux.kill() - // The old server takes a moment to let go of its socket. - await expect - .poll( - () => { - try { - tmux.run(['-f', '/dev/null', 'new-session', '-d', '-s', 'users', stubborn(792)]) - return true - } catch { - return false - } - }, - { timeout: 10_000 } - ) - .toBe(true) - for (let panes = 0; panes < 10 && !tmux.hasPane(pane.id); panes += 1) { - tmux.split('users', stubborn(792)) - } - expect(processRunning(slept(791))).toBe(false) - - app = (await launch(sim, userData, { TMUX_TMPDIR: tmux.dir })).app - - await expect.poll(() => recordedRuns(userData), { timeout: 30_000 }).toEqual([]) - expect(tmux.hasPane(pane.id)).toBe(true) - expect(processRunning(slept(792))).toBe(true) - }) - - test('on tmux without pane options a run goes ahead untracked, and Stop and sign-out leave it alone', async () => { - test.skip(!REAL_TMUX, 'tmux is not installed on this machine') - const { window, deviceId } = await start('untracked', { PATH: oldTmuxPath() }) + test('on tmux without pane options a run goes ahead untracked, and Stop leaves it alone', async ({ + desktop, + }) => { + requireTmux() + const { deviceId } = await start(desktop, { PATH: oldTmuxPath(desktop) }) leftovers.push(slept(761)) const { call, pane } = await agentRunsInTmux(deviceId, tmux, 761) expect(pane.runId).toBe('') sim.stopCall(call) - await settled(sim, call, 20_000) - await sleep(6_000) - expect(processRunning(slept(761))).toBe(true) - expect(tmux.hasPane(pane.id)).toBe(true) - await window.goto(`${sim.origin}/login?fromLogout=true`) - await sleep(8_000) + // The call reports only once its stop has run, so whatever the stop did is done by now. + const stopped = await settled(sim, call, 20_000) + expect(stopped.status).toBe('cancelled') expect(processRunning(slept(761))).toBe(true) expect(tmux.hasPane(pane.id)).toBe(true) }) diff --git a/apps/desktop/e2e/update-notification.spec.ts b/apps/desktop/e2e/update-notification.spec.ts index b088ef4ca78..fed997f229c 100644 --- a/apps/desktop/e2e/update-notification.spec.ts +++ b/apps/desktop/e2e/update-notification.spec.ts @@ -1,112 +1,39 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' import type { DesktopUpdateState } from '@sim/desktop-bridge' -import { getErrorMessage } from '@sim/utils/errors' -import { sleep } from '@sim/utils/helpers' -import { build } from 'esbuild' -import postcss from 'postcss' -import loadPostcssConfig from 'postcss-load-config' +import { bundleSimFixture, type DesktopBridge, expect, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) -const SIM_DIR = fileURLToPath(new URL('../../sim/', import.meta.url)) const FIXTURE = fileURLToPath(new URL('./fixtures/update-notification.tsx', import.meta.url)) -test('desktop update actions survive navigation without repeating dismissed or stale offers', async () => { - const reportPath = - process.env.DESKTOP_UPDATE_NOTICE_REPORT_PATH ?? test.info().outputPath('update-notice.json') - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await test.step(name, run) - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - const userData = mkdtempSync(join(tmpdir(), 'sim-update-notice-e2e-')) - let app: Awaited> | undefined - let passed = false - let javascript = '' - let stylesheet = '' - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://localhost').pathname - if (path === '/fixture.js' || path === '/fixture.css') { - response.setHeader('Content-Type', path.endsWith('.js') ? 'text/javascript' : 'text/css') - response.end(path.endsWith('.js') ? javascript : stylesheet) - } else if (path.startsWith('/api/')) { - response.setHeader('Content-Type', 'application/json') - response.end('{}') +test('desktop update actions survive navigation without repeating dismissed or stale offers', async ({ + desktop, +}) => { + const { js, css } = await bundleSimFixture({ + source: `import { mountUpdateNotificationFixture } from ${JSON.stringify(FIXTURE)}; +import { DesktopUpdateNotification } from '@/app/_shell/desktop-update-notification'; +mountUpdateNotificationFixture(DesktopUpdateNotification);`, + }) + const fixture = await serve((_request, response, url) => { + if (url.pathname === '/fixture.js' || url.pathname === '/fixture.css') { + const script = url.pathname.endsWith('.js') + response.writeHead(200, { 'Content-Type': script ? 'text/javascript' : 'text/css' }) + response.end(script ? js : css) + } else if (url.pathname.startsWith('/api/')) { + response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') } else { - response.setHeader('Content-Type', 'text/html') + response.writeHead(200, { 'Content-Type': 'text/html' }) response.end( '
' ) } }) - try { - await check('load the production notification in Electron', async () => { - const config = await loadPostcssConfig({}, SIM_DIR) - const cssPath = join(SIM_DIR, 'app/_styles/globals.css') - const css = await postcss(config.plugins).process( - `${readFileSync(cssPath, 'utf8')}\n@source ${JSON.stringify(FIXTURE)};`, - { from: cssPath } - ) - const bundle = await build({ - stdin: { - contents: `import { mountUpdateNotificationFixture } from ${JSON.stringify(FIXTURE)}; -import { DesktopUpdateNotification } from '@/app/_shell/desktop-update-notification'; -mountUpdateNotificationFixture(DesktopUpdateNotification);`, - resolveDir: SIM_DIR, - loader: 'tsx', - }, - bundle: true, - write: false, - outfile: test.info().outputPath('fixture.js'), - external: ['node:async_hooks'], - banner: { js: 'var process={env:{NODE_ENV:"development"},browser:true};' }, - format: 'iife', - platform: 'browser', - tsconfig: join(SIM_DIR, 'tsconfig.json'), - define: { 'process.env.NODE_ENV': '"development"' }, - }) - javascript = bundle.outputFiles.find((file) => file.path.endsWith('.js'))?.text ?? '' - stylesheet = `${css.css}\n${bundle.outputFiles.find((file) => file.path.endsWith('.css'))?.text ?? ''}` - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - app = await electron.launch({ - args: [process.env.SIM_DESKTOP_E2E_MAIN ?? '.'], - cwd: DESKTOP_DIR, - env: { - ...process.env, - SIM_DESKTOP_ORIGIN: `http://127.0.0.1:${address.port}`, - SIM_DESKTOP_USER_DATA: userData, - }, - }) + const { app } = await desktop.launch({ + origin: fixture.origin, }) - if (!app) throw new Error('Electron did not launch') - const shell = app - const page = await shell.firstWindow() + const page = await app.firstWindow() const errors: string[] = [] page.on('pageerror', (error) => errors.push(error.message)) - await shell.evaluate(({ app, BrowserWindow }) => { + await app.evaluate(({ app, BrowserWindow }) => { const window = BrowserWindow.getAllWindows()[0] window.setContentSize(1000, 700) window.webContents.setBackgroundThrottling(false) @@ -114,87 +41,86 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, window.focus() }) const publish = (state: DesktopUpdateState) => - shell.evaluate(({ BrowserWindow }, next) => { + app.evaluate(({ BrowserWindow }, next) => { BrowserWindow.getAllWindows()[0].webContents.send('desktop:updates:state', next) }, state) + /** How many update states the page has received since it last loaded. */ + const delivered = () => + page.evaluate(() => (globalThis as { updateStatesDelivered?: number }).updateStatesDelivered) + const countDeliveries = () => + page.evaluate(() => { + const state = globalThis as { updateStatesDelivered?: number } + state.updateStatesDelivered = 0 + ;(globalThis as DesktopBridge).simDesktop.updates.onState(() => { + state.updateStatesDelivered = (state.updateStatesDelivered ?? 0) + 1 + }) + }) + const nextFrames = () => + page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())) + ) + ) const notice = page.getByRole('list', { name: 'Notifications' }) const restart = notice.getByRole('button', { name: 'Restart to update' }) const download = notice.getByRole('button', { name: 'Download update' }) - await check( - 'initial snapshot survives StrictMode and remains actionable across navigation', - async () => { - await shell.evaluate(({ ipcMain }) => { - ipcMain.removeHandler('desktop:updates:get-state') - ipcMain.handle('desktop:updates:get-state', () => ({ status: 'ready', version: '2.0.0' })) - }) - await page.reload() - await expect(restart).toHaveCount(1) - await expect(restart).toBeVisible() - await page.getByRole('button', { name: 'Switch workspace' }).click() - await expect(page.getByLabel('Current route')).toHaveText('/workspace/second') - await sleep(5_500) - await expect(restart).toBeVisible() - await page.screenshot({ - path: test.info().outputPath('update-ready-dark.png'), - animations: 'disabled', - }) - await page.evaluate(() => document.documentElement.classList.remove('dark')) - await page.screenshot({ - path: test.info().outputPath('update-ready-light.png'), - animations: 'disabled', - }) - } - ) + await test.step('initial snapshot survives StrictMode and remains actionable across navigation', async () => { + await app.evaluate(({ ipcMain }) => { + ipcMain.removeHandler('desktop:updates:get-state') + ipcMain.handle('desktop:updates:get-state', () => ({ status: 'ready', version: '2.0.0' })) + }) + await page.reload() + await expect(restart).toHaveCount(1) + await expect(restart).toBeVisible() + await page.getByRole('button', { name: 'Switch workspace' }).click() + await expect(page.getByLabel('Current route')).toHaveText('/workspace/second') + // Outlasts the 5s default toast lifetime: proving a real timer doesn't dismiss the notice needs + // its real duration, and a fake clock would also freeze the dismiss animations used below. + await page.waitForTimeout(5_500) + await expect(restart).toBeVisible() + }) - await check('dismissal survives repeated events and checking the same release', async () => { + await test.step('dismissal survives repeated events and checking the same release', async () => { await notice.getByRole('button', { name: 'Dismiss notification' }).click() await expect(restart).toHaveCount(0) + await countDeliveries() await publish({ status: 'ready', version: '2.0.0' }) await publish({ status: 'checking', version: '2.0.0' }) - await page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) + await nextFrames() await publish({ status: 'ready', version: '2.0.0' }) - await sleep(500) + await expect.poll(delivered).toBe(3) + await nextFrames() await expect(restart).toHaveCount(0) }) - await check( - 'a new release appears without stealing focus, and stale actions are withdrawn', - async () => { - const input = page.getByRole('textbox', { name: 'Work in progress' }) - await input.fill('Unsaved work') - await publish({ status: 'ready', version: '2.1.0' }) - await expect(restart).toBeVisible() - await expect(input).toBeFocused() - for (const status of ['checking', 'downloading', 'error', 'idle'] as const) { - await publish({ status, version: '2.1.0' }) - await expect(restart).toHaveCount(0) - await publish({ status: 'ready', version: '2.1.0' }) - await expect(restart).toHaveCount(1) - } - await expect(input).toHaveValue('Unsaved work') - } - ) - - await check( - 'a dismissed download offer can announce that the same release is ready', - async () => { - await publish({ status: 'available', version: '2.1.0' }) - await expect(download).toBeVisible() + await test.step('a new release appears without stealing focus, and stale actions are withdrawn', async () => { + const input = page.getByRole('textbox', { name: 'Work in progress' }) + await input.fill('Unsaved work') + await publish({ status: 'ready', version: '2.1.0' }) + await expect(restart).toBeVisible() + await expect(input).toBeFocused() + for (const status of ['checking', 'downloading', 'error', 'idle'] as const) { + await publish({ status, version: '2.1.0' }) await expect(restart).toHaveCount(0) - await notice.getByRole('button', { name: 'Dismiss notification' }).click() - await expect(download).toHaveCount(0) await publish({ status: 'ready', version: '2.1.0' }) - await expect(restart).toBeVisible() + await expect(restart).toHaveCount(1) } - ) + await expect(input).toHaveValue('Unsaved work') + }) - await check('stack eviction does not count as dismissing the update offer', async () => { + await test.step('a dismissed download offer can announce that the same release is ready', async () => { + await publish({ status: 'available', version: '2.1.0' }) + await expect(download).toBeVisible() + await expect(restart).toHaveCount(0) + await notice.getByRole('button', { name: 'Dismiss notification' }).click() + await expect(download).toHaveCount(0) + await publish({ status: 'ready', version: '2.1.0' }) + await expect(restart).toBeVisible() + }) + + await test.step('stack eviction does not count as dismissing the update offer', async () => { await publish({ status: 'checking', version: '2.4.0' }) await expect(restart).toHaveCount(0) await publish({ status: 'ready', version: '2.4.0' }) @@ -204,17 +130,12 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, await page.getByRole('button', { name: 'Clear notifications' }).click() await expect(notice).toHaveCount(0) await publish({ status: 'checking', version: '2.4.0' }) - await page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) + await nextFrames() await publish({ status: 'ready', version: '2.4.0' }) await expect(restart).toBeVisible() }) - await check('actions reach the real preload IPC with the correct operation', async () => { + await test.step('actions reach the real preload IPC with the correct operation', async () => { for (const { state, action, channel } of [ { state: { status: 'ready', version: '2.4.0' }, @@ -234,7 +155,7 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, ] satisfies { state: DesktopUpdateState; action: typeof restart; channel: string }[]) { await publish(state) await expect(action).toBeVisible() - const received = await shell.evaluateHandle(({ ipcMain }, name) => { + const received = await app.evaluateHandle(({ ipcMain }, name) => { const receipt: { url: string | null } = { url: null } ipcMain.once(name, (event) => { receipt.url = event.sender.getURL() @@ -249,14 +170,9 @@ mountUpdateNotificationFixture(DesktopUpdateNotification);`, await received.dispose() } } - expect(errors).toEqual([]) }) - passed = true + expect(errors).toEqual([]) } finally { - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync(reportPath, JSON.stringify({ passed, checks }, null, 2)) - await app?.close() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(userData, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/e2e/updater.spec.ts b/apps/desktop/e2e/updater.spec.ts index 65bdaabffcf..f5b7b57c7b7 100644 --- a/apps/desktop/e2e/updater.spec.ts +++ b/apps/desktop/e2e/updater.spec.ts @@ -1,68 +1,46 @@ import { createHash } from 'node:crypto' -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { _electron as electron, expect, test } from '@playwright/test' -import { getErrorMessage } from '@sim/utils/errors' +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import type { ElectronApplication } from '@playwright/test' import { build } from 'esbuild' +import { DESKTOP_DIR, expect, serve, test } from './harness' -const DESKTOP_DIR = fileURLToPath(new URL('..', import.meta.url)) - -test('the real MacUpdater waits for native staging, replaces old builds, retries failed staging, and restarts on one click', async () => { +test('the real MacUpdater waits for native staging, replaces old builds, retries failed staging, and restarts on one click', async ({ + desktop, +}) => { test.skip(process.platform !== 'darwin', 'Squirrel.Mac lifecycle') - const directory = mkdtempSync(join(tmpdir(), 'sim-updater-e2e-')) - const reportPath = - process.env.DESKTOP_UPDATER_REPORT_PATH ?? test.info().outputPath('updater.json') - let app: Awaited> | undefined + const directory = desktop.tempDir('sim-updater-e2e-') let offeredVersion = '2.0.0' - const requests: { path: string; status: number }[] = [] - const checks: { - name: string - status: 'passed' | 'failed' - durationMs: number - error?: string - }[] = [] - const check = async (name: string, run: () => Promise) => { - const started = Date.now() - try { - await run() - checks.push({ name, status: 'passed', durationMs: Date.now() - started }) - } catch (error) { - checks.push({ - name, - status: 'failed', - durationMs: Date.now() - started, - error: getErrorMessage(error), - }) - throw error - } - } - let snapshot: unknown - let completed = false - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - requests.push({ path, status: 200 }) - if (path === '/latest-mac.yml') { + const fixture = await serve((_request, response, url) => { + if (url.pathname === '/latest-mac.yml') { const archive = Buffer.from(offeredVersion) response.end( `version: ${offeredVersion}\nfiles:\n - url: Sim-${offeredVersion}-universal.zip\n sha512: ${createHash('sha512').update(archive).digest('base64')}\n size: ${archive.length}\n` ) } else { - response.end(/^\/Sim-(.+)-universal.zip$/.exec(path)?.[1] ?? '') + response.end(/^\/Sim-(.+)-universal.zip$/.exec(url.pathname)?.[1] ?? '') } }) - - try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('Missing fixture address') - mkdirSync(join(directory, 'user-data')) + const writeVersion = (version: string) => writeFileSync( join(directory, 'package.json'), - JSON.stringify({ name: 'sim-updater-fixture', version: '1.0.0', main: 'main.cjs' }) + JSON.stringify({ name: 'sim-updater-fixture', version, main: 'main.cjs' }) ) + /** Launches the fixture main, which keeps its profile in `user-data` under the fixture dir. */ + const launch = () => + desktop.launch({ + origin: fixture.origin, + main: directory, + args: ['--use-mock-keychain'], + userData: join(directory, 'user-data'), + env: { SIM_UPDATER_FIXTURE_DIR: directory, SIM_UPDATER_FIXTURE_ORIGIN: fixture.origin }, + }) + const installResults = (app: ElectronApplication) => + app.evaluate(() => globalThis.desktopUpdaterFixture?.read().events) + + try { + mkdirSync(join(directory, 'user-data')) + writeVersion('1.0.0') await build({ entryPoints: [join(DESKTOP_DIR, 'e2e/fixtures/updater.ts')], outfile: join(directory, 'main.cjs'), @@ -90,193 +68,140 @@ test('the real MacUpdater waits for native staging, replaces old builds, retries }, ], }) - app = await electron.launch({ - args: [directory, '--use-mock-keychain'], - env: { - ...process.env, - SIM_UPDATER_FIXTURE_DIR: directory, - SIM_UPDATER_FIXTURE_ORIGIN: `http://127.0.0.1:${address.port}`, - }, - }) - const shell = app - const read = () => shell.evaluate(() => globalThis.desktopUpdaterFixture.read()) + const first = await launch() + const { app } = first + const read = () => app.evaluate(() => globalThis.desktopUpdaterFixture.read()) await expect - .poll(() => shell.evaluate(() => Boolean(globalThis.desktopUpdaterFixture))) + .poll(() => app.evaluate(() => Boolean(globalThis.desktopUpdaterFixture))) .toBe(true) - await check('first download waits for native staging', async () => { - await shell.evaluate(() => globalThis.desktopUpdaterFixture.check()) + await test.step('first download waits for native staging', async () => { + await app.evaluate(() => globalThis.desktopUpdaterFixture.check()) await expect.poll(async () => (await read()).nativeArchive).toBe('2.0.0') expect((await read()).state).toEqual({ status: 'downloading', version: '2.0.0', percent: 100, }) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.install()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.install()) expect((await read()).installed).toEqual([]) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) expect((await read()).state).toEqual({ status: 'ready', version: '2.0.0' }) }) - await check('replacement cannot restart into stale native update', async () => { + await test.step('replacement cannot restart into stale native update', async () => { offeredVersion = '2.1.0' - await shell.evaluate(() => globalThis.desktopUpdaterFixture.check()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.check()) await expect.poll(async () => (await read()).nativeArchive).toBe('2.1.0') expect((await read()).state).toEqual({ status: 'downloading', version: '2.1.0', percent: 100, }) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.install()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.install()) expect((await read()).installed).toEqual([]) - await shell.evaluate(() => globalThis.desktopUpdaterFixture.failStaging()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.failStaging()) expect((await read()).state).toEqual({ status: 'error', version: '2.1.0' }) }) - await check('cached retry stages only the verified replacement', async () => { - await shell.evaluate(() => globalThis.desktopUpdaterFixture.check()) + await test.step('cached retry stages only the verified replacement', async () => { + await app.evaluate(() => globalThis.desktopUpdaterFixture.check()) await expect .poll(async () => (await read()).state) .toEqual({ status: 'downloading', version: '2.1.0', percent: 100 }) await expect.poll(async () => (await read()).nativeArchive).toBe('2.1.0') - await shell.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) + await app.evaluate(() => globalThis.desktopUpdaterFixture.finishStaging()) expect((await read()).state).toEqual({ status: 'ready', version: '2.1.0' }) }) - await check( - 'restart asks only about real in-flight work, then installs on one click', - async () => { - /** Sets the work in progress, clicks Restart to update, and answers any prompt with `response`. */ - const installWith = async ( - work: { - terminalCommands?: string[] - browserToolRunning?: boolean - unloadListener: 'passive' | 'unsaved-edits' - hungWindow?: boolean + await test.step('restart asks only about real in-flight work, then installs on one click', async () => { + /** Sets the work in progress, clicks Restart to update, and answers any prompt with `response`. */ + const installWith = async ( + work: { + terminalCommands?: string[] + browserToolRunning?: boolean + unloadListener: 'passive' | 'unsaved-edits' + hungWindow?: boolean + }, + response: number + ) => { + await app.evaluate( + async ( + _electron, + [{ terminalCommands = [], browserToolRunning = false, ...rest }, answer] + ) => { + await globalThis.desktopUpdaterFixture.setWork({ + terminalCommands, + browserToolRunning, + ...rest, + }) + globalThis.updaterFixtureDialogResponse = answer + globalThis.desktopUpdaterFixture.install() }, - response: number - ) => { - await shell.evaluate( - async ( - _electron, - [{ terminalCommands = [], browserToolRunning = false, ...rest }, answer] - ) => { - await globalThis.desktopUpdaterFixture.setWork({ - terminalCommands, - browserToolRunning, - ...rest, - }) - globalThis.updaterFixtureDialogResponse = answer - globalThis.desktopUpdaterFixture.install() - }, - [work, response] as const - ) - } - const expectNotNowPrompt = async (count: number, message: string) => { - await expect.poll(async () => (await read()).dialogs.length).toBe(count) - expect((await read()).dialogs.at(-1)).toEqual({ - title: 'Restart to install Sim 2.1.0?', - message, - buttons: ['Restart and Update', 'Not Now'], - defaultId: 0, - cancelId: 1, - }) - // The decline settles asynchronously; nothing may install, and the update stays ready. - await expect - .poll(async () => (await read()).state) - .toEqual({ status: 'ready', version: '2.1.0' }) - expect((await read()).installed).toEqual([]) - } - - await installWith( - { terminalCommands: ['cd /repo && claude "fix the build"'], unloadListener: 'passive' }, - 1 + [work, response] as const ) - await expectNotNowPrompt(1, 'claude is still running in a terminal.') + } + const expectNotNowPrompt = async (count: number, message: string) => { + await expect.poll(async () => (await read()).dialogs.length).toBe(count) + expect((await read()).dialogs.at(-1)).toEqual({ + title: 'Restart to install Sim 2.1.0?', + message, + buttons: ['Restart and Update', 'Not Now'], + defaultId: 0, + cancelId: 1, + }) + // The decline settles asynchronously; nothing may install, and the update stays ready. + await expect + .poll(async () => (await read()).state) + .toEqual({ status: 'ready', version: '2.1.0' }) + expect((await read()).installed).toEqual([]) + } - await installWith({ unloadListener: 'unsaved-edits' }, 1) - await expectNotNowPrompt(2, 'A window has unsaved changes.') + await installWith( + { terminalCommands: ['cd /repo && claude "fix the build"'], unloadListener: 'passive' }, + 1 + ) + await expectNotNowPrompt(1, 'claude is still running in a terminal.') - await installWith( - { browserToolRunning: true, unloadListener: 'passive', hungWindow: true }, - 1 - ) - await expectNotNowPrompt( - 3, - "An agent is using the browser. A window isn't responding and may have unsaved changes." - ) + await installWith({ unloadListener: 'unsaved-edits' }, 1) + await expectNotNowPrompt(2, 'A window has unsaved changes.') - // Answering Not Now again would leave nothing installed if a prompt appeared. - await installWith({ unloadListener: 'passive' }, 1) - await expect.poll(async () => (await read()).installed).toEqual(['2.1.0']) - expect((await read()).dialogs).toHaveLength(3) - } - ) - snapshot = await read() - await check( - 'the next process distinguishes an incomplete update from a successful install', - async () => { - const checkpoint = readFileSync(join(directory, 'update-install.json'), 'utf8') - await app?.close() - app = await electron.launch({ - args: [directory, '--use-mock-keychain'], - env: { - ...process.env, - SIM_UPDATER_FIXTURE_DIR: directory, - SIM_UPDATER_FIXTURE_ORIGIN: `http://127.0.0.1:${address.port}`, - }, + await installWith( + { browserToolRunning: true, unloadListener: 'passive', hungWindow: true }, + 1 + ) + await expectNotNowPrompt( + 3, + "An agent is using the browser. A window isn't responding and may have unsaved changes." + ) + + // Answering Not Now again would leave nothing installed if a prompt appeared. + await installWith({ unloadListener: 'passive' }, 1) + await expect.poll(async () => (await read()).installed).toEqual(['2.1.0']) + expect((await read()).dialogs).toHaveLength(3) + }) + await test.step('the next process distinguishes an incomplete update from a successful install', async () => { + const checkpoint = readFileSync(join(directory, 'update-install.json'), 'utf8') + await desktop.close(first) + const stale = await launch() + await expect + .poll(() => installResults(stale.app)) + .toContainEqual({ + name: 'update_install_result', + data: { expected: '2.1.0', installed: '1.0.0', success: false }, }) - await expect - .poll(() => app?.evaluate(() => globalThis.desktopUpdaterFixture?.read().events)) - .toContainEqual({ - name: 'update_install_result', - data: { expected: '2.1.0', installed: '1.0.0', success: false }, - }) - await app.close() - writeFileSync(join(directory, 'update-install.json'), checkpoint) - writeFileSync( - join(directory, 'package.json'), - JSON.stringify({ name: 'sim-updater-fixture', version: '2.1.0', main: 'main.cjs' }) - ) - app = await electron.launch({ - args: [directory, '--use-mock-keychain'], - env: { - ...process.env, - SIM_UPDATER_FIXTURE_DIR: directory, - SIM_UPDATER_FIXTURE_ORIGIN: `http://127.0.0.1:${address.port}`, - }, + await desktop.close(stale) + writeFileSync(join(directory, 'update-install.json'), checkpoint) + writeVersion('2.1.0') + const updated = await launch() + await expect + .poll(() => installResults(updated.app)) + .toContainEqual({ + name: 'update_install_result', + data: { expected: '2.1.0', installed: '2.1.0', success: true }, }) - await expect - .poll(() => app?.evaluate(() => globalThis.desktopUpdaterFixture?.read().events)) - .toContainEqual({ - name: 'update_install_result', - data: { expected: '2.1.0', installed: '2.1.0', success: true }, - }) - } - ) - completed = true + }) } finally { - if (!snapshot && app) - snapshot = await app - .evaluate(() => globalThis.desktopUpdaterFixture?.read()) - .catch(() => undefined) - mkdirSync(dirname(reportPath), { recursive: true }) - writeFileSync( - reportPath, - JSON.stringify( - { - passed: completed && checks.every((check) => check.status === 'passed'), - checks, - requests, - snapshot, - }, - null, - 2 - ) - ) - await app?.close() - server.closeAllConnections() - await new Promise((resolve) => server.close(() => resolve())) - rmSync(directory, { recursive: true, force: true }) + await fixture.close() } }) diff --git a/apps/desktop/playwright.config.ts b/apps/desktop/playwright.config.ts index 00181f3924d..63372eea169 100644 --- a/apps/desktop/playwright.config.ts +++ b/apps/desktop/playwright.config.ts @@ -4,5 +4,6 @@ export default defineConfig({ testDir: './e2e', timeout: 90_000, workers: 1, + forbidOnly: Boolean(process.env.CI), reporter: process.env.CI ? [['github'], ['list']] : [['list']], }) diff --git a/knip.jsonc b/knip.jsonc index 653978a5a85..6a2883159ae 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -114,8 +114,7 @@ }, "apps/desktop": { "includeEntryExports": false, - // scripts/build.ts and e2e/updater.spec.ts supply these to esbuild by path; the nested - // Playwright run in e2e/check-report.spec.ts loads worker-restart.ts through its config. + // scripts/build.ts and e2e/updater.spec.ts supply these to esbuild by path. "entry": [ "src/main/index.ts", "src/preload/*.ts", @@ -123,7 +122,6 @@ "src/renderer/*/index.tsx", "scripts/*.ts", "e2e/fixtures/updater.ts", - "e2e/fixtures/worker-restart.ts", // The native permission test launches this Electron fixture by filename. "native/computer-use/tests/electron-fixture/*.cjs" ], diff --git a/scripts/check-explicit-any.baseline.json b/scripts/check-explicit-any.baseline.json index 17d3017bd6d..70d8740321b 100644 --- a/scripts/check-explicit-any.baseline.json +++ b/scripts/check-explicit-any.baseline.json @@ -1030,7 +1030,6 @@ "scripts/generate-v2-cli-api.ts": 3 }, "nonNullAssertion": { - "apps/desktop/e2e/password-autofill.spec.ts": 11, "apps/desktop/e2e/source-connect.spec.ts": 2, "apps/desktop/src/main/browser-agent/cdp.test.ts": 1, "apps/desktop/src/main/browser-agent/context-menu.test.ts": 2, diff --git a/scripts/desktop-e2e.ts b/scripts/desktop-e2e.ts index fd28763429f..73c9e3a69c5 100644 --- a/scripts/desktop-e2e.ts +++ b/scripts/desktop-e2e.ts @@ -47,7 +47,8 @@ const run = spawnSync( 'playwright', 'test', ...selected.map((file) => `^${escapeRegExp(resolve(report.config.rootDir, file))}$`), - '--reporter=line,json', + // `github` turns failures into annotations; an explicit --reporter replaces the config's. + process.env.CI ? '--reporter=github,line,json' : '--reporter=line,json', ], { stdio: 'inherit', env: process.env } )