diff --git a/apps/desktop/e2e-durations.json b/apps/desktop/e2e-durations.json
index f839f479f5f..d5f02c13d50 100644
--- a/apps/desktop/e2e-durations.json
+++ b/apps/desktop/e2e-durations.json
@@ -1,6 +1,7 @@
{
"background-executor.spec.ts": 129.01,
"browser-chrome.spec.ts": 16.68,
+ "browser-find-and-media.spec.ts": 15.0,
"browser-focus.spec.ts": 14.91,
"browser-page-dialogs.spec.ts": 36.22,
"browser-page-parity.spec.ts": 3.89,
@@ -13,9 +14,11 @@
"local-files.spec.ts": 32.44,
"packaged-smoke.spec.ts": 0.0,
"password-autofill.spec.ts": 40.27,
+ "quit-guard.spec.ts": 10.0,
"session-cookies.spec.ts": 4.98,
"smoke.spec.ts": 28.65,
"source-connect.spec.ts": 40.84,
+ "startup.spec.ts": 25.0,
"terminal-cancel.spec.ts": 205.16,
"update-notification.spec.ts": 19.13,
"updater.spec.ts": 6.33
diff --git a/apps/desktop/e2e/browser-find-and-media.spec.ts b/apps/desktop/e2e/browser-find-and-media.spec.ts
new file mode 100644
index 00000000000..d20732174f4
--- /dev/null
+++ b/apps/desktop/e2e/browser-find-and-media.spec.ts
@@ -0,0 +1,192 @@
+import type { ElectronApplication, Page } from '@playwright/test'
+import { inPage, openShell, panelAction, titleAt, userInput } from './browser-page'
+import { type DesktopBridge, expect, type FixtureServer, serve, test } from './harness'
+
+const SCOPE = 'browser-find-media-e2e'
+const SHELL = { heading: 'Find and media fixture', top: 80 }
+const PRIMARY = process.platform === 'darwin' ? 'meta' : 'control'
+
+/** Records what the shell is told: Sim's find bar opening, and media requests awaiting the user. */
+const SHELL_PAGE = `
Sim fixture${SHELL.heading}
+`
+
+const SITE_PAGES: Record = {
+ '/own-find': `own-find:0`,
+ '/no-find': 'no-findNothing here handles find.
',
+ '/camera': `camera:0`,
+}
+
+type ShellGlobals = DesktopBridge & {
+ findOpened: number
+ mediaRequests: { requestId: string; devices: string[] }[]
+}
+
+/** Presses Cmd+F (Ctrl+F elsewhere) in the page at `url`, as the user's own keyboard would. */
+async function pressFind(app: ElectronApplication, url: string): Promise {
+ await app.evaluate(
+ ({ webContents }, { url, modifier }) => {
+ const contents = webContents.getAllWebContents().find((entry) => entry.getURL() === url)
+ if (!contents) throw new Error(`No page at ${url}`)
+ contents.focus()
+ const input = { keyCode: 'F', modifiers: [modifier] } as Electron.KeyboardInputEvent
+ contents.sendInputEvent({ ...input, type: 'keyDown' })
+ contents.sendInputEvent({ ...input, type: 'keyUp' })
+ },
+ { url, modifier: PRIMARY }
+ )
+}
+
+const findOpened = (shell: Page) => shell.evaluate(() => (globalThis as ShellGlobals).findOpened)
+const mediaRequests = (shell: Page) =>
+ shell.evaluate(() => (globalThis as ShellGlobals).mediaRequests)
+
+function tabs(shell: Page) {
+ return shell.evaluate(
+ (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.activateScope(scope),
+ SCOPE
+ )
+}
+
+test.describe('the built-in browser', () => {
+ let server: FixtureServer
+
+ test.beforeAll(async () => {
+ server = await serve((request, response, url) => {
+ // The app origin serves the shell; the same server on localhost is the web.
+ if (request.headers.host?.startsWith('localhost')) {
+ const page = SITE_PAGES[url.pathname]
+ response.writeHead(page ? 200 : 404, { 'Content-Type': 'text/html' })
+ response.end(page ?? 'not found')
+ return
+ }
+ response.writeHead(200, {
+ 'Content-Type': 'text/html',
+ 'Set-Cookie': 'better-auth.session_token=fixture; HttpOnly; Path=/',
+ })
+ response.end(SHELL_PAGE)
+ })
+ })
+
+ test.afterAll(async () => {
+ await server.close()
+ })
+
+ test("the find key goes to the page first and opens Sim's find bar only when the page leaves it", async ({
+ desktop,
+ }) => {
+ const { app } = await desktop.launch({ origin: server.origin })
+ const shell = await openShell(app, SCOPE, SHELL)
+ const ownFind = `${server.site}/own-find`
+ const noFind = `${server.site}/no-find`
+
+ await test.step('a page with its own find keeps the key', async () => {
+ await panelAction(shell, SCOPE, { action: 'navigate', url: ownFind })
+ await expect.poll(() => titleAt(app, ownFind)).toBe('own-find:0')
+ await pressFind(app, ownFind)
+ await expect.poll(() => titleAt(app, ownFind)).toBe('own-find:1')
+ // Well past the time Sim gives the page to answer before opening its own bar.
+ await shell.waitForTimeout(1_500)
+ expect(await findOpened(shell)).toBe(0)
+ })
+
+ await test.step("a page without one gets Sim's find bar", async () => {
+ await panelAction(shell, SCOPE, { action: 'navigate', url: noFind })
+ await expect.poll(() => titleAt(app, noFind)).toBe('no-find')
+ await pressFind(app, noFind)
+ await expect.poll(() => findOpened(shell)).toBe(1)
+ })
+ })
+
+ test('a camera the user allowed is given again silently only while its tab is in front', async ({
+ desktop,
+ }) => {
+ const { app } = await desktop.launch({
+ origin: server.origin,
+ args: ['--use-fake-device-for-media-stream'],
+ })
+ // macOS privacy consent for the app itself is the operating system's, not Sim's; the runner
+ // has none to give, so it answers as a user who allowed the camera there.
+ await app.evaluate(({ systemPreferences }) => {
+ systemPreferences.getMediaAccessStatus = () => 'granted'
+ systemPreferences.askForMediaAccess = async () => true
+ })
+ const shell = await openShell(app, SCOPE, SHELL)
+ const camera = `${server.site}/camera`
+ const title = () => titleAt(app, camera)
+
+ await test.step('the first request after a click asks, and Allow gives the camera', async () => {
+ await panelAction(shell, SCOPE, { action: 'navigate', url: camera })
+ await expect.poll(title).toBe('camera:0')
+ await userInput(app, camera, '#camera')
+ await expect.poll(() => mediaRequests(shell)).toHaveLength(1)
+ const [request] = await mediaRequests(shell)
+ expect(request.devices).toEqual(['camera'])
+ await panelAction(shell, SCOPE, {
+ action: 'respond-media-permission',
+ requestId: request.requestId,
+ allowed: true,
+ })
+ await expect.poll(title).toBe('camera:1:granted')
+ })
+
+ await test.step('asking again while the tab is in front is answered without a prompt', async () => {
+ await inPage(app, camera, 'startCamera()')
+ await expect.poll(title).toBe('camera:2:granted')
+ expect(await mediaRequests(shell)).toHaveLength(1)
+ })
+
+ const cameraTab = (await tabs(shell)).activeTabId
+ if (!cameraTab) throw new Error('The camera page has no tab')
+
+ await test.step('the same request from a background tab is refused', async () => {
+ const opened = await shell.evaluate(
+ (scope) => (globalThis as DesktopBridge).simDesktop.browserAgent.openTab?.(scope),
+ SCOPE
+ )
+ expect(opened?.activeTabId).not.toBe(cameraTab)
+ await inPage(app, camera, 'startCamera()')
+ await expect.poll(title).toBe('camera:3:NotAllowedError')
+ expect(await mediaRequests(shell)).toHaveLength(1)
+ })
+
+ await test.step('back in front, the tab still has the camera the user allowed', async () => {
+ await panelAction(shell, SCOPE, { action: 'switch-tab', tabId: cameraTab })
+ await expect.poll(async () => (await tabs(shell)).activeTabId).toBe(cameraTab)
+ await inPage(app, camera, 'startCamera()')
+ await expect.poll(title).toBe('camera:4:granted')
+ expect(await mediaRequests(shell)).toHaveLength(1)
+ })
+ })
+})
diff --git a/apps/desktop/e2e/harness.ts b/apps/desktop/e2e/harness.ts
index 6b0868f78b8..d88792f1226 100644
--- a/apps/desktop/e2e/harness.ts
+++ b/apps/desktop/e2e/harness.ts
@@ -26,6 +26,7 @@ import {
} from '@playwright/test'
import type { BrowserToolName } from '@sim/browser-protocol'
import type { SimDesktopApi } from '@sim/desktop-bridge'
+import { getErrorMessage } from '@sim/utils/errors'
import { type BuildOptions, build } from 'esbuild'
import postcss from 'postcss'
import loadPostcssConfig from 'postcss-load-config'
@@ -367,6 +368,50 @@ export async function serve(handler: FixtureHandler): Promise {
}
}
+/**
+ * The app's own dialog window (Sim's bundled shell dialog) showing `name`, found among the open
+ * windows rather than awaited, since a prompt shown at launch can open before a test listens.
+ */
+export async function shellDialog(app: ElectronApplication, name: string): Promise {
+ let found: Page | undefined
+ await expect
+ .poll(
+ async () => {
+ for (const page of app.windows()) {
+ if (!page.url().endsWith('/dialog.html')) continue
+ const dialog = page.getByRole('dialog', { name, exact: true })
+ if (await dialog.isVisible().catch(() => false)) {
+ found = page
+ return true
+ }
+ }
+ return false
+ },
+ { timeout: 30_000 }
+ )
+ .toBe(true)
+ if (!found) throw new Error(`No ${name} dialog`)
+ return found
+}
+
+/**
+ * Runs an action that closes `page` (answering a dialog, quitting the app) and waits for it to
+ * close, tolerating only the error from the page closing under the action.
+ */
+export async function closingPage(
+ page: Page,
+ action: (page: Page) => Promise
+): Promise {
+ const closed = page.waitForEvent('close')
+ await action(page).catch(ignorePageClosed)
+ await closed
+}
+
+/** Rethrows any error but the one from a page closing under an action, e.g. as the app exits. */
+export function ignorePageClosed(error: unknown): void {
+ if (!/closed/i.test(getErrorMessage(error))) throw error
+}
+
/** 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 }) => {
diff --git a/apps/desktop/e2e/quick-chat.spec.ts b/apps/desktop/e2e/quick-chat.spec.ts
index d9a2cd3ac58..38f897ef69d 100644
--- a/apps/desktop/e2e/quick-chat.spec.ts
+++ b/apps/desktop/e2e/quick-chat.spec.ts
@@ -1,3 +1,5 @@
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
import type { ElectronApplication, Page } from '@playwright/test'
import type { DesktopPreferences, QuickChatShortcut } from '@sim/desktop-bridge'
import { type DesktopBridge, expect, type FixtureServer, serve, test } from './harness'
@@ -91,6 +93,28 @@ const setShortcut = (page: Page, shortcut: string | null) =>
const isRegistered = (app: ElectronApplication, shortcut: string) =>
app.evaluate(({ globalShortcut }, value) => globalShortcut.isRegistered(value), shortcut)
+/**
+ * Whether Sim's application menu is in place. The stored shortcut is bound in the same step, so
+ * once it is, a shortcut that is not registered was never going to be.
+ */
+const startupBound = (app: ElectronApplication) =>
+ app.evaluate(({ Menu }) => {
+ const has = (items: Electron.MenuItem[]): boolean =>
+ items.some(
+ (item) => item.label === 'Quick Chat' || (item.submenu ? has(item.submenu.items) : false)
+ )
+ return has(Menu.getApplicationMenu()?.items ?? [])
+ })
+
+/** The shortcut the profile's settings file stores, `undefined` while it stores none. */
+const storedShortcut = (userData: string): unknown => {
+ try {
+ return JSON.parse(readFileSync(join(userData, 'settings.json'), 'utf8')).quickChatShortcut
+ } catch {
+ return undefined
+ }
+}
+
test.describe('quick chat window', () => {
let fixture: FixtureServer
/** Paths whose connections are dropped, so their loads fail. */
@@ -292,6 +316,36 @@ test.describe('quick chat window', () => {
})
})
+ test('an install from before the setting keeps ⌥Space; a new install claims no shortcut', async ({
+ desktop,
+ }) => {
+ test.skip(process.platform !== 'darwin', 'Only macOS ever bound ⌥Space by default')
+
+ await test.step('a settings file without the setting keeps the ⌥Space it always had', async () => {
+ const existing = await desktop.launch({ origin: fixture.origin, settings: settings() })
+ await expect.poll(() => isRegistered(existing.app, 'Alt+Space')).toBe(true)
+ await expect.poll(() => storedShortcut(existing.userData)).toBe('Alt+Space')
+ await desktop.close(existing)
+ })
+
+ const fresh =
+ await test.step('a first run binds nothing and records that it is off', async () => {
+ const launched = await desktop.launch({ origin: fixture.origin })
+ await expect.poll(() => startupBound(launched.app)).toBe(true)
+ expect(await isRegistered(launched.app, 'Alt+Space')).toBe(false)
+ await expect.poll(() => storedShortcut(launched.userData)).toBeNull()
+ await desktop.close(launched)
+ return launched
+ })
+
+ await test.step('relaunching that profile still binds nothing', async () => {
+ const relaunched = await desktop.launch({ origin: fixture.origin, userData: fresh.userData })
+ await expect.poll(() => startupBound(relaunched.app)).toBe(true)
+ expect(await isRegistered(relaunched.app, 'Alt+Space')).toBe(false)
+ expect(storedShortcut(relaunched.userData)).toBeNull()
+ })
+ })
+
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 { app } = await desktop.launch({ origin: fixture.origin, settings: '[]' })
diff --git a/apps/desktop/e2e/quit-guard.spec.ts b/apps/desktop/e2e/quit-guard.spec.ts
new file mode 100644
index 00000000000..544037440cb
--- /dev/null
+++ b/apps/desktop/e2e/quit-guard.spec.ts
@@ -0,0 +1,119 @@
+import { execFileSync } from 'node:child_process'
+import type { ElectronApplication, Page } from '@playwright/test'
+import { randomInt } from '@sim/utils/random'
+import { processRunning } from './executor-sim'
+import {
+ closingPage,
+ type DesktopBridge,
+ expect,
+ type FixtureServer,
+ ignorePageClosed,
+ serve,
+ test,
+} from './harness'
+
+/**
+ * Quitting while a terminal command runs, in the real shell with a real zsh: the app asks first,
+ * Cancel keeps the app, its window and the command, and Quit Anyway quits and stops the command.
+ */
+
+const SCOPE = 'quit-guard-e2e'
+/** Unique to this run, so a leftover from another run on the machine is never mistaken for it. */
+const COMMAND = `sleep 4242.${String(randomInt(0, 1_000_000)).padStart(6, '0')}`
+
+/** The user opens a terminal tab in a chat and starts `command` in it. */
+async function userRuns(window: Page, command: string): Promise {
+ const terminalId = await window.evaluate(async (scope) => {
+ const terminal = (globalThis as DesktopBridge).simDesktop.terminal
+ await terminal.activateScope(scope)
+ terminal.setVisible?.(true, scope)
+ terminal.setFocused(true, scope)
+ return (await terminal.openTerminal(undefined, scope)).activeTerminalId
+ }, SCOPE)
+ if (!terminalId) throw new Error('No terminal tab opened')
+ // Typing is gated on a real keypress in the window, as it is for the panel's own input.
+ await window.keyboard.press('Shift')
+ await window.evaluate(
+ ([id, text, scope]) => (globalThis as DesktopBridge).simDesktop.terminal.write(id, text, scope),
+ [terminalId, `${command}\r`, SCOPE] as const
+ )
+}
+
+/** Starts a quit the way Cmd+Q does and returns the quit prompt it opens. */
+async function quitAndAwaitPrompt(app: ElectronApplication): Promise {
+ const opened = app.waitForEvent('window')
+ await app.evaluate(({ app }) => app.quit())
+ const prompt = await opened
+ await expect(prompt.getByRole('dialog', { name: 'Quit Sim?', exact: true })).toBeVisible()
+ return prompt
+}
+
+function visibleAppWindows(app: ElectronApplication, origin: string): Promise {
+ return app.evaluate(
+ ({ BrowserWindow }, origin) =>
+ BrowserWindow.getAllWindows().filter(
+ (win) =>
+ !win.isDestroyed() && win.isVisible() && win.webContents.getURL().startsWith(origin)
+ ).length,
+ origin
+ )
+}
+
+test.describe('quitting over a running terminal command', () => {
+ let fixture: FixtureServer
+
+ test.beforeAll(async () => {
+ fixture = await serve((_request, response) => {
+ response.writeHead(200, { 'Content-Type': 'text/html' })
+ response.end('Sim fixtureQuit fixture
')
+ })
+ })
+
+ test.afterAll(async () => {
+ try {
+ execFileSync('pkill', ['-9', '-f', COMMAND])
+ } catch {}
+ await fixture.close()
+ })
+
+ test('asks first: Cancel keeps everything, Quit Anyway quits and stops the command', async ({
+ desktop,
+ }) => {
+ const launched = await desktop.launch({
+ origin: fixture.origin,
+ leaveDialogsToDesktop: true,
+ env: { SHELL: '/bin/zsh', ZDOTDIR: desktop.tempDir('sim-quit-zdotdir-') },
+ })
+ const { app, child } = launched
+ const window = await app.firstWindow()
+ await expect(window.getByRole('heading')).toHaveText('Quit fixture')
+ await userRuns(window, COMMAND)
+ await expect.poll(() => processRunning(COMMAND), { timeout: 30_000 }).toBe(true)
+
+ await test.step('the prompt names the running command and defaults to Cancel', async () => {
+ const prompt = await quitAndAwaitPrompt(app)
+ await expect(prompt.locator('#dialog-message')).toContainText(/still running in a terminal\./)
+ const cancel = prompt.getByRole('button', { name: 'Cancel', exact: true })
+ await expect(cancel).toBeFocused()
+ await closingPage(prompt, (page) => page.keyboard.press('Enter'))
+ })
+
+ await test.step('Cancel leaves the app, its window and the command running', async () => {
+ expect(child.exitCode).toBeNull()
+ expect(await visibleAppWindows(app, fixture.origin)).toBe(1)
+ await expect(window.getByRole('heading')).toHaveText('Quit fixture')
+ expect(processRunning(COMMAND)).toBe(true)
+ })
+
+ await test.step('a second quit asks again, and Quit Anyway quits and stops the command', async () => {
+ const prompt = await quitAndAwaitPrompt(app)
+ const exited = new Promise((resolve) => child.once('exit', () => resolve()))
+ await prompt
+ .getByRole('button', { name: 'Quit Anyway', exact: true })
+ .click()
+ .catch(ignorePageClosed)
+ await exited
+ await expect.poll(() => processRunning(COMMAND), { timeout: 15_000 }).toBe(false)
+ })
+ })
+})
diff --git a/apps/desktop/e2e/smoke.spec.ts b/apps/desktop/e2e/smoke.spec.ts
index aca424f1d9d..cd62a55a36b 100644
--- a/apps/desktop/e2e/smoke.spec.ts
+++ b/apps/desktop/e2e/smoke.spec.ts
@@ -11,6 +11,14 @@ const PAGES: Record = {
+
+
+
+