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-find

Nothing 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 fixture

Quit 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 = { + + + + `, + '/mcp-links': `

provider-page

+ + + `, '/workspace/two': '

second-route

', '/login': '

fixture-login

', @@ -30,17 +38,31 @@ async function closeWith(page: Page, action: () => Promise): Promise await closed } -/** Replaces `shell.openExternal` with a recorder, read back by `openedExternally`. */ +/** + * Replaces `shell.openExternal` with a recorder, read back by `openedExternally`, and makes the + * `simfixture:` scheme one an installed app handles, so no real app is ever launched. + */ async function recordExternalOpens(app: ElectronApplication): Promise { - await app.evaluate(({ shell }) => { + await app.evaluate(({ app, shell }) => { const opened: string[] = [] ;(globalThis as { __openedExternal?: string[] }).__openedExternal = opened shell.openExternal = async (url: string) => { opened.push(url) } + app.getApplicationNameForProtocol = (url: string) => + url.startsWith('simfixture:') ? 'Fixture Meetings' : '' }) } +/** Whether any of the app's own dialog windows is open. */ +function dialogOpen(app: ElectronApplication): Promise { + return app.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some( + (win) => !win.isDestroyed() && win.webContents.getURL().endsWith('/dialog.html') + ) + ) +} + function openedExternally(app: ElectronApplication): Promise { return app.evaluate(() => (globalThis as { __openedExternal?: string[] }).__openedExternal) } @@ -132,6 +154,63 @@ test.describe('desktop shell smoke', () => { }) }) + test('links to other apps ask first and plain http opens from Sim windows, never from popups', async ({ + desktop, + }) => { + const { app } = await desktop.launch({ origin: fixture.origin }) + const window = await app.firstWindow() + await expect(window.locator('#app')).toHaveText('fixture-app') + await recordExternalOpens(app) + + await test.step('an app link asks to open the app, and Cancel, the default, opens nothing', async () => { + const opened = app.waitForEvent('window') + await window.locator('#app-link').click() + const prompt = await opened + await expect( + prompt.getByRole('dialog', { name: 'Open Fixture Meetings?', exact: true }) + ).toBeVisible() + await expect(prompt.getByRole('button', { name: 'Cancel', exact: true })).toBeFocused() + await closeWith(prompt, () => prompt.keyboard.press('Enter')) + expect(await openedExternally(app)).toEqual([]) + }) + + await test.step('Open hands the link to the app', async () => { + const opened = app.waitForEvent('window') + await window.locator('#app-link').click() + const prompt = await opened + await closeWith(prompt, () => + prompt.getByRole('button', { name: 'Open', exact: true }).click() + ) + await expect.poll(() => openedExternally(app)).toEqual(['simfixture://join?id=42']) + }) + + await test.step('a plain http link opens in the system browser', async () => { + await window.locator('#http-blank').click() + await expect + .poll(() => openedExternally(app)) + .toEqual(['simfixture://join?id=42', 'http://example.com/plain']) + }) + + await test.step('an OAuth popup can open https but never an app link or plain http', async () => { + const popupOpened = app.waitForEvent('window') + await window.locator('#mcp-links').click() + const popup = await popupOpened + await expect(popup.locator('#provider')).toHaveText('provider-page') + await popup.locator('#popup-app-link').click() + await popup.locator('#popup-http').click() + // Opened last, so once it arrives the two before it have been decided. + await popup.locator('#popup-https').click() + await expect + .poll(() => openedExternally(app)) + .toEqual([ + 'simfixture://join?id=42', + 'http://example.com/plain', + 'https://docs.sim.ai/from-popup', + ]) + expect(await dialogOpen(app)).toBe(false) + }) + }) + test('OAuth popups share the session without inheriting the privileged preload', async ({ desktop, }) => { diff --git a/apps/desktop/e2e/startup.spec.ts b/apps/desktop/e2e/startup.spec.ts new file mode 100644 index 00000000000..fcdedf29312 --- /dev/null +++ b/apps/desktop/e2e/startup.spec.ts @@ -0,0 +1,158 @@ +import { + chmodSync, + existsSync, + readdirSync, + readFileSync, + statSync, + utimesSync, + writeFileSync, +} from 'node:fs' +import { join } from 'node:path' +import type { Page } from '@playwright/test' +import { + closingPage, + type DesktopApp, + expect, + type FixtureServer, + ignorePageClosed, + serve, + shellDialog, + test, +} from './harness' + +/** + * What the app does with an existing profile as it starts: a settings file it cannot use is + * reported and left alone unless the user resets it, and download staging files an earlier run + * abandoned are cleared while newer ones stay. + */ + +/** A hand-edit's trailing comma: read fine, but not JSON. */ +const CORRUPT_SETTINGS = '{\n "origin": "https://example.com",\n}\n' +const UNUSABLE = 'Sim could not use its settings' +const UNREADABLE = 'Sim could not read its settings' +const DAY_MS = 24 * 60 * 60 * 1000 + +const settingsPath = (userData: string) => join(userData, 'settings.json') +const backups = (userData: string) => + readdirSync(userData).filter((name) => name.startsWith('settings.json.bak-')) + +const answerWithDefault = (prompt: Page) => + closingPage(prompt, (page) => page.keyboard.press('Enter')) + +test.describe('settings file problems at launch', () => { + let fixture: FixtureServer + + test.beforeAll(async () => { + fixture = await serve((_request, response) => { + response.writeHead(200, { 'Content-Type': 'text/html' }) + response.end('Sim fixture

Startup fixture

') + }) + }) + + test.afterAll(async () => { + await fixture.close() + }) + + async function expectUsable(desktop: DesktopApp): Promise { + const window = await desktop.app.firstWindow() + await expect(window.getByRole('heading')).toHaveText('Startup fixture') + } + + test('Not Now, the default, leaves a corrupt settings file byte for byte', async ({ + desktop, + }) => { + const launched = await desktop.launch({ origin: fixture.origin, settings: CORRUPT_SETTINGS }) + const prompt = await shellDialog(launched.app, UNUSABLE) + await expect(prompt.getByRole('button', { name: 'Reset Settings', exact: true })).toBeVisible() + await expect(prompt.getByRole('button', { name: 'Not Now', exact: true })).toBeFocused() + await answerWithDefault(prompt) + + await expectUsable(launched) + expect(readFileSync(settingsPath(launched.userData), 'utf8')).toBe(CORRUPT_SETTINGS) + // Quitting flushes settings; a file Sim could not use must survive that too. + await desktop.close(launched) + expect(readFileSync(settingsPath(launched.userData), 'utf8')).toBe(CORRUPT_SETTINGS) + expect(backups(launched.userData)).toEqual([]) + }) + + test('Reset Settings keeps a copy of the corrupt file, rewrites it, and restarts', async ({ + desktop, + }) => { + const launched = await desktop.launch({ origin: fixture.origin, settings: CORRUPT_SETTINGS }) + const { app, child, userData } = launched + const prompt = await shellDialog(app, UNUSABLE) + // A real relaunch would start a second app outside the test's control; record it instead. + const marker = join(desktop.tempDir('sim-relaunch-'), 'relaunched') + await app.evaluate(({ app }, marker) => { + app.relaunch = () => { + process.getBuiltinModule('node:fs').writeFileSync(marker, 'relaunch') + } + }, marker) + const exited = new Promise((resolve) => child.once('exit', () => resolve())) + + await prompt + .getByRole('button', { name: 'Reset Settings', exact: true }) + .click() + .catch(ignorePageClosed) + await exited + + expect(existsSync(marker)).toBe(true) + const [backup, ...others] = backups(userData) + expect(others).toEqual([]) + expect(readFileSync(join(userData, backup), 'utf8')).toBe(CORRUPT_SETTINGS) + const rewritten: unknown = JSON.parse(readFileSync(settingsPath(userData), 'utf8')) + expect(rewritten).toMatchObject({ origin: expect.stringMatching(/^https:\/\//) }) + }) + + test('an unreadable settings file is reported, never reset, and left untouched', async ({ + desktop, + }) => { + const userData = desktop.tempDir('sim-desktop-e2e-profile-') + const contents = JSON.stringify({ origin: 'https://example.com' }) + writeFileSync(settingsPath(userData), contents) + chmodSync(settingsPath(userData), 0o000) + const launched = await desktop.launch({ origin: fixture.origin, userData }) + + const prompt = await shellDialog(launched.app, UNREADABLE) + await expect(prompt.getByRole('button', { name: 'OK', exact: true })).toBeFocused() + await expect(prompt.getByRole('button', { name: 'Reset Settings', exact: true })).toHaveCount(0) + await answerWithDefault(prompt) + await expectUsable(launched) + + await desktop.close(launched) + expect(statSync(settingsPath(userData)).mode & 0o777).toBe(0) + chmodSync(settingsPath(userData), 0o600) + expect(readFileSync(settingsPath(userData), 'utf8')).toBe(contents) + expect(backups(userData)).toEqual([]) + }) +}) + +test('download staging files abandoned over a day ago are removed at launch', async ({ + desktop, +}) => { + const downloads = desktop.tempDir('sim-download-dir-') + const stale = `.sim-download-${'a'.repeat(21)}` + const stalePartial = `.sim-download-${'b'.repeat(21)}.crdownload` + const recent = `.sim-download-${'c'.repeat(21)}` + const usersOwn = 'report.pdf' + const now = Date.now() + for (const [name, age] of [ + [stale, 2 * DAY_MS], + [stalePartial, 2 * DAY_MS], + [recent, DAY_MS / 24], + [usersOwn, 2 * DAY_MS], + ] as const) { + const path = join(downloads, name) + writeFileSync(path, name) + const modified = new Date(now - age) + utimesSync(path, modified, modified) + } + + const launched = await desktop.launch({ + origin: 'http://127.0.0.1:1', + settings: { browserDownloadDirectory: downloads }, + }) + await launched.app.firstWindow() + + await expect.poll(() => readdirSync(downloads).sort()).toEqual([recent, usersOwn].sort()) +})