Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(desktop): add chat-open A/B spec comparing two Desktop builds
Alfredo Lopez92a9771720f5
diff --git a/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts b/desktop-app/test/e2e-playwright/chat-open-ab.spec.tsnew file mode 100644index 000000000..949dbcd28--- /dev/null+++ b/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts@@ -0,0 +1,678 @@+import { type ElectronApplication, type Page, expect, test } from '@playwright/test'+import { execFileSync } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { createFixture } from '../../scripts/bench-chat-open/fixtures.mjs'+import { ChatStore } from '../../src/chatStore'+import { isPathInside } from '../../src/devIsolation'+import { assertSafeFilesystemSegment } from '../../src/pathSafety'+import { type ChatAuthorityScope } from '../../src/types'+import {+ type HostSnapshot,+ readHostSnapshot,+ waitForStatelessReady,+ waitForStatelessSuspended,+} from './helpers/hostSnapshot'+import {+ EXTERNAL_REST_API_BASE_URL,+ MAIN_ENTRY,+ RPC_PROXY_BASE_URL,+ assertAllowedTarget,+ desktopCredentials,+ launchDesktopApp,+ login,+ openExactAgentChat,+ validateMainEntry,+} from './qa-recorder-helpers'++// E2E_GUARDIAN_IPC_FLOW: server reads are preconditions through Desktop IPC;+// the measured journey clicks real rows and observes the visible transcript.+// Inputs: CHAT_OPEN_AB_BEFORE_MAIN, CHAT_OPEN_AB_AFTER_MAIN, CHAT_OPEN_AB_KUBE_CONTEXT,+// CHAT_OPEN_AB_OUTPUT_JSON. Run only with playwright.chat-open-ab.config.ts.+type Build = 'before' | 'after'+type Chat = { id: string; count: number; lastText: string }+type Catalog = { host: string; size: number; eligible: number; K: number; chats: Chat[] }+type Sample = {+ round: number+ build: Build+ host: string+ metric: string+ ms: number+ pass?: number+ chatId?: string+ observed_at_install?: boolean+ observer_installed_ms?: number+}+const HOSTS = ['chatllm', 'chatllm-stateless'] as const+const MESSAGES = '[data-testid="user-message"], [data-testid="agent-response"]'+const rows = (host: string) =>+ `[data-testid="latest-session-row"][data-agent-ref=${JSON.stringify(host)}]`+const row = (host: string, id: string) => `${rows(host)}[data-chat-id=${JSON.stringify(id)}]`+const agentRow = (host: string, id: string) =>+ `[data-testid="agent-chat-row"][data-agent-ref=${JSON.stringify(host)}][data-chat-id=${JSON.stringify(id)}]`+const quantiles = (values: number[]) => {+ if (!values.length || values.some(value => !Number.isFinite(value)))+ throw new Error('Missing or invalid timing samples.')+ const sorted = [...values].sort((a, b) => a - b)+ return {+ p50: sorted[Math.ceil(sorted.length * 0.5) - 1]!,+ p95: sorted[Math.ceil(sorted.length * 0.95) - 1]!,+ n: sorted.length,+ }+}+function required(name: string): string {+ const value = process.env[name]+ if (!value || !value.trim()) throw new Error(`${name} is required for the Desktop A/B benchmark.`)+ return value+}+function isolatedPath(runDir: string, target: string): string {+ if (!isPathInside(runDir, target))+ throw new Error(`Cache target must be inside the isolated run directory: ${target}`)+ let ancestor = target+ while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor)+ const resolved = path.resolve(fs.realpathSync(ancestor), path.relative(ancestor, target))+ if (!isPathInside(fs.realpathSync(runDir), resolved))+ throw new Error(`Cache target escapes isolation through a symlink: ${target}`)+ return target+}+async function openChat(page: Page, host: string, chat: Chat): Promise<number> {+ await page+ .getByRole('navigation', { name: 'Chat breadcrumb', exact: true })+ .getByRole('button', { name: 'Chat', exact: true })+ .click()+ await openExactAgentChat(page, host)+ const more = page.getByRole('button', { name: 'Show more', exact: true })+ const loadMore = page.getByRole('button', { name: 'Load more', exact: true })+ const target = page.locator(agentRow(host, chat.id))+ await expect+ .poll(+ async () => {+ if (await target.isVisible()) return true+ if (await more.isVisible()) await more.click()+ else if ((await loadMore.isVisible()) && (await loadMore.isEnabled()))+ await loadMore.click()+ return target.isVisible()+ },+ {+ timeout: 30_000,+ message: `The selected Host must expose server chat ${chat.id} through its session list.`,+ }+ )+ .toBe(true)+ return page.evaluate(+ ({ selector, activeSelector, chat, messages }) =>+ new Promise<number>((resolve, reject) => {+ const button = document.querySelector<HTMLButtonElement>(`${selector} button`)+ if (!button || button.disabled)+ throw new Error(`Chat row has no enabled open button: ${selector}`)+ let started: number+ const finish = () => {+ const transcript = document.querySelector('[data-testid="message-list"]')+ const bubbles = transcript?.querySelectorAll(messages)+ if (+ bubbles?.length === chat.count &&+ bubbles[chat.count - 1]?.textContent?.includes(chat.lastText) &&+ transcript &&+ transcript.getBoundingClientRect().height > 0 &&+ document.querySelector(activeSelector)?.getAttribute('aria-current') === 'true'+ ) {+ observer.disconnect()+ clearTimeout(deadline)+ resolve(performance.now() - started)+ }+ }+ const observer = new MutationObserver(finish)+ observer.observe(document.documentElement, {+ childList: true,+ subtree: true,+ characterData: true,+ attributes: true,+ })+ const deadline = setTimeout(() => {+ observer.disconnect()+ reject(new Error(`Transcript did not match server chat ${chat.id}`))+ }, 120_000)+ started = performance.now()+ button.click()+ finish()+ }),+ {+ selector: agentRow(host, chat.id),+ activeSelector: row(host, chat.id),+ chat,+ messages: MESSAGES,+ }+ )+}+async function relaunchPaint(+ page: Page,+ targets: Array<{ host: string; metric: string; selector: string; chat?: Chat }>+) {+ return page.evaluate(+ ({ targets, messages }) =>+ new Promise<+ Array<{+ host: string+ metric: string+ ms: number+ observed_at_install: boolean+ observer_installed_ms: number+ }>+ >((resolve, reject) => {+ const navigation = performance.getEntriesByType('navigation')[0] as+ | PerformanceNavigationTiming+ | undefined+ if (!navigation) throw new Error('Window navigation timing is unavailable.')+ const installed = performance.now()+ const observed = new Map<string, { at: number; initial: boolean }>()+ let initial = true+ const visible = (element: Element) =>+ element.getBoundingClientRect().height > 0 &&+ getComputedStyle(element).visibility !== 'hidden'+ const finish = () => {+ for (const target of targets) {+ const transcript = document.querySelector('[data-testid="message-list"]')+ const ready =+ Array.from(document.querySelectorAll(target.selector)).some(visible) &&+ (!target.chat ||+ (transcript &&+ visible(transcript) &&+ transcript.querySelectorAll(messages).length === target.chat.count &&+ transcript+ .querySelectorAll(messages)+ [target.chat.count - 1]?.textContent?.includes(target.chat.lastText)))+ if (ready && !observed.has(target.metric))+ observed.set(target.metric, { at: performance.now(), initial })+ }+ if (observed.size === targets.length && navigation.loadEventEnd > 0) {+ observer.disconnect()+ clearTimeout(deadline)+ resolve(+ targets.map(target => {+ const result = observed.get(target.metric)!+ return {+ host: target.host,+ metric: target.metric,+ ms: Math.max(0, result.at - navigation.loadEventEnd),+ observed_at_install: result.initial,+ observer_installed_ms: installed - navigation.loadEventEnd,+ }+ })+ )+ }+ initial = false+ }+ const observer = new MutationObserver(finish)+ observer.observe(document.documentElement, {+ childList: true,+ subtree: true,+ characterData: true,+ attributes: true,+ })+ const deadline = setTimeout(() => {+ observer.disconnect()+ reject(new Error('Relaunch did not expose the required rows/transcript.'))+ }, 120_000)+ window.addEventListener('load', () => requestAnimationFrame(finish), { once: true })+ finish()+ }),+ { targets, messages: MESSAGES }+ )+}++if (+ process.env.DESKTOP_CHAT_OPEN_AB_CONFIG ===+ path.join(__dirname, 'playwright.chat-open-ab.config.ts')+) {+ test('compare two Desktop builds: cached chat open, large-cache relaunch and stateless wake', async ({}, testInfo) => {+ if (process.env.EVENFIRE_RENDERER_URL?.trim())+ throw new Error(+ "Unset EVENFIRE_RENDERER_URL: the A/B run must use each build's bundled renderer."+ )+ const entries = {+ before: required('CHAT_OPEN_AB_BEFORE_MAIN'),+ after: required('CHAT_OPEN_AB_AFTER_MAIN'),+ }+ for (const entry of Object.values(entries)) validateMainEntry(entry)+ if (+ path.resolve(entries.after) !== MAIN_ENTRY ||+ path.dirname(entries.before) === path.dirname(entries.after)+ )+ throw new Error(+ 'AFTER must be this worktree build; BEFORE must be a different worktree build.'+ )+ const context = required('CHAT_OPEN_AB_KUBE_CONTEXT')+ if (context !== context.trim() || context.startsWith('-'))+ throw new Error('CHAT_OPEN_AB_KUBE_CONTEXT must be the literal Kubernetes context.')+ const output = required('CHAT_OPEN_AB_OUTPUT_JSON')+ if (!path.isAbsolute(output) || path.extname(output) !== '.json')+ throw new Error('CHAT_OPEN_AB_OUTPUT_JSON must be an absolute JSON path.')+ const builds = Object.fromEntries(+ Object.entries(entries).map(([build, entry]) => [+ build,+ {+ entry,+ sha: execFileSync(+ 'git',+ ['-C', path.resolve(path.dirname(entry), '../..'), 'rev-parse', 'HEAD'],+ { encoding: 'utf8' }+ ).trim(),+ },+ ])+ )+ const samples: Sample[] = []+ const rounds: Array<{+ id: number+ scenario: string+ build: Build+ loadavg: number[]+ cache: { before: unknown; after?: unknown }+ snapshots: HostSnapshot[]+ invalidated: boolean+ }> = []+ const report = {+ builds,+ node: process.version,+ machine: {+ platform: os.platform(),+ arch: os.arch(),+ cpus: os.cpus().length,+ model: os.cpus()[0]!.model,+ },+ startedAt: new Date().toISOString(),+ catalogs: [] as Catalog[],+ fixtureRoot: '',+ rounds,+ samples,+ cells: {} as Record<string, ReturnType<typeof quantiles>>,+ gates: [] as Array<Record<string, string | number | boolean>>,+ complete: false,+ }+ let app: ElectronApplication | undefined+ let page: Page+ const runDir = testInfo.outputPath('electron-isolation')+ const close = async () => {+ if (app) {+ await app.close()+ app = undefined+ }+ }+ const launch = async (build: Build) => {+ await close()+ const launched = await launchDesktopApp(testInfo, 'issue-1091-ab', entries[build])+ app = launched.app+ page = launched.page+ }+ const authenticated = async () => {+ await expect(page.getByTestId('nav-chat')).toBeVisible()+ await expect(page.locator('#email-input')).toBeHidden()+ }+ const snapshot = () => readHostSnapshot(HOSTS[1], HOSTS[1], context)+ const ready = () => waitForStatelessReady(270_000, context, HOSTS[1], HOSTS[1])+ let cacheDir: string+ const cacheState = () => {+ if (!fs.existsSync(cacheDir)) return { agents: 0, chats: 0, pending: 0 }+ const indexes = fs+ .readdirSync(cacheDir, { withFileTypes: true })+ .filter(entry => entry.isDirectory())+ .map(entry =>+ JSON.parse(fs.readFileSync(path.join(cacheDir, entry.name, 'index.json'), 'utf8'))+ )+ return {+ agents: indexes.length,+ chats: indexes.reduce((sum, index) => sum + index.chats.length, 0),+ pending: indexes.reduce(+ (sum, index) => sum + (index.pendingChatCleanup ? index.pendingChatCleanup.length : 0),+ 0+ ),+ }+ }+ const round = async (scenario: string, build: Build, action: (id: number) => Promise<void>) => {+ const record: (typeof rounds)[number] = {+ id: rounds.length + 1,+ scenario,+ build,+ loadavg: os.loadavg(),+ cache: { before: cacheState() },+ snapshots: [await snapshot()],+ invalidated: false,+ }+ rounds.push(record)+ let stopped = false+ let observationFailure: { error: unknown } | undefined+ const observation = (async () => {+ while (!stopped) {+ record.snapshots.push(await snapshot())+ if (!stopped) await new Promise(resolve => setTimeout(resolve, 250))+ }+ })().catch(error => {+ observationFailure = { error }+ })+ try {+ await action(record.id)+ } finally {+ stopped = true+ await observation+ record.snapshots.push(await snapshot())+ record.cache.after = cacheState()+ record.invalidated =+ scenario !== 'W' &&+ record.snapshots.some(+ (state, index, all) =>+ index > 0 &&+ state.readyReplicas > 0 &&+ (all[index - 1]!.readyReplicas === 0 ||+ state.podNames.join(',') !== all[0]!.podNames.join(','))+ )+ if (observationFailure) throw observationFailure.error+ }+ }+ try {+ await test.step('precondition: one isolated login and existing server chats with at least two turns', async () => {+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)+ await launch('before')+ await login(page!, desktopCredentials())+ await ready()+ expect(+ (await readHostSnapshot(HOSTS[0], HOSTS[0], context)).readyReplicas,+ 'The stateful control Host must be Ready.'+ ).toBeGreaterThan(0)+ const scope = await page!.evaluate(async (): Promise<ChatAuthorityScope> => {+ const state = await window.clerum.auth.getSessionState()+ const config = await window.clerum.auth.getRuntimeConfigState()+ if (!state.authenticated || !state.me || !config.envKey)+ throw new Error('Logged-in authority scope is unavailable.')+ return { environmentKey: config.envKey, userId: state.me.id, teamId: state.me.teamId }+ })+ assertSafeFilesystemSegment('environmentKey', scope.environmentKey)+ assertSafeFilesystemSegment('userId', scope.userId)+ cacheDir = isolatedPath(+ runDir,+ path.join(runDir, 'chats', scope.environmentKey, scope.userId)+ )+ report.catalogs = await page!.evaluate(+ async hosts => {+ const catalogs: Catalog[] = []+ for (const host of hosts) {+ const items: Awaited<ReturnType<typeof window.clerum.rpc.listSessions>>['items'] = []+ let cursor: string | undefined+ do {+ const result = await window.clerum.rpc.listSessions(host, undefined, {+ limit: 100,+ cursor,+ })+ items.push(...result.items)+ cursor = result.nextCursor+ } while (cursor)+ const eligible = items.filter(item => item.turnCount >= 2)+ const K = Math.min(10, eligible.length)+ if (K < 5)+ throw new Error(+ `precondition: ${host} has ${K} eligible chats; at least 5 are required, without seeding.`+ )+ const chats: Chat[] = []+ for (const session of eligible.slice(0, K)) {+ const result = await window.clerum.rpc.loadSessionMessages(+ host,+ session.agent,+ session.chatId,+ undefined,+ { limit: session.turnCount }+ )+ const last = result.turns[result.turns.length - 1]+ if (+ result.turns.length !== session.turnCount ||+ !last?.response ||+ result.turns.some(turn => !turn.user_input || !turn.response)+ )+ throw new Error(+ `precondition: ${host}/${session.chatId} must expose all completed turns.`+ )+ const count = result.turns.length * 2+ if (session.messageCount !== undefined && session.messageCount !== count)+ throw new Error(+ `precondition: ${host}/${session.chatId} message count disagrees with completed turns.`+ )+ chats.push({ id: session.chatId, count, lastText: last.response })+ }+ catalogs.push({ host, size: items.length, eligible: eligible.length, K, chats })+ }+ return catalogs+ },+ [...HOSTS]+ )+ // The benchmark builder owns valid paged metadata; rebind its synthetic tombstones to the real session below.+ const fixtureDir = isolatedPath(runDir, path.join(runDir, 'fixture'))+ fs.mkdirSync(fixtureDir, { mode: 0o700 })+ const fixture = await createFixture({+ runDir: fixtureDir,+ ChatStore,+ adapter: {+ bind(Store: typeof ChatStore, root: string) {+ const store = new Store(root)+ store.setAuthorityScope(scope)+ return store+ },+ },+ agents: 25,+ chatsPerAgent: 200,+ pendingCleanupsPerAgent: 10,+ })+ for (const agent of fixture.agentNames) {+ const indexPath = isolatedPath(runDir, path.join(fixture.root, agent, 'index.json'))+ const index = JSON.parse(fs.readFileSync(indexPath, 'utf8'))+ for (const key of ['deletedChatTombstones', 'pendingChatCleanup'])+ for (const tombstone of index[key]) tombstone.authorityScope = scope+ fs.writeFileSync(indexPath, JSON.stringify(index), { mode: 0o600 })+ }+ report.fixtureRoot = fixture.root+ })+ for (const build of ['before', 'after', 'after', 'before'] as const) {+ await ready()+ await test.step(`O: ${build} cached chat opens`, () =>+ round('O', build, async id => {+ await launch(build)+ await authenticated()+ await page.getByTestId('nav-chat').click()+ for (const catalog of report.catalogs) {+ const checked = new Set<string>()+ for (let pass = 1; pass <= (id === 1 ? 3 : 2); pass++) {+ const remote = id === 1 && pass === 1+ if (!remote)+ await test.step(`precondition: ${catalog.host} transcripts are cached`, async () => {+ await expect+ .poll(+ () =>+ page.evaluate(+ async ({ host, chats }) => {+ const messages = await Promise.all(+ chats.map(chat => window.clerum.chat.loadMessages(host, chat.id))+ )+ return messages.every(+ (items, index) =>+ items.length === chats[index]!.count &&+ items[items.length - 1]?.content === chats[index]!.lastText+ )+ },+ { host: catalog.host, chats: catalog.chats }+ ),+ { timeout: 30_000 }+ )+ .toBe(true)+ })+ for (const chat of catalog.chats) {+ const ms = await openChat(page, catalog.host, chat)+ samples.push({+ round: id,+ build,+ host: catalog.host,+ metric: remote ? 'open_remote_ms' : 'open_cached_ms',+ pass,+ chatId: chat.id,+ ms,+ })+ if (!checked.has(chat.id)) {+ await expect(page.locator(row(catalog.host, chat.id))).toHaveAttribute(+ 'aria-current',+ 'true'+ )+ await expect(page.getByTestId('message-list').locator(MESSAGES)).toHaveCount(+ chat.count+ )+ checked.add(chat.id)+ }+ }+ }+ }+ }))+ }+ const selected = report.catalogs[0]!.chats[0]!+ await openChat(page!, HOSTS[0], selected)+ await expect+ .poll(() => page!.evaluate(host => window.clerum.chat.getLastActive(host), HOSTS[0]))+ .toBe(selected.id)+ await close()+ const savedCache = isolatedPath(runDir, path.join(runDir, 'cache-snapshot'))+ fs.cpSync(isolatedPath(runDir, cacheDir!), savedCache, { recursive: true })+ const fixtureRoot = report.fixtureRoot+ for (const agent of fs.readdirSync(fixtureRoot))+ fs.cpSync(+ isolatedPath(runDir, path.join(fixtureRoot, agent)),+ isolatedPath(runDir, path.join(savedCache, agent)),+ { recursive: true }+ )+ for (const build of ['before', 'after'] as const)+ for (let iteration = 0; iteration < 3; iteration++) {+ await ready()+ await close()+ fs.rmSync(isolatedPath(runDir, cacheDir!), { recursive: true })+ fs.cpSync(savedCache, isolatedPath(runDir, cacheDir!), { recursive: true })+ await test.step(`L: ${build} large-cache relaunch ${iteration + 1}`, () =>+ round('L', build, async id => {+ await launch(build)+ const [paint] = await Promise.all([+ relaunchPaint(page, [+ {+ host: HOSTS[0],+ metric: 'relaunch_ms',+ selector: row(HOSTS[0], selected.id),+ chat: selected,+ },+ ]),+ (async () => {+ await authenticated()+ await expect(page.locator(row(HOSTS[0], selected.id))).toBeVisible()+ await page.getByTestId('nav-chat').click()+ await openChat(page, HOSTS[0], selected)+ })(),+ ])+ for (const sample of paint) samples.push({ round: id, build, ...sample })+ await authenticated()+ }))+ }+ for (const build of ['before', 'after'] as const)+ for (let iteration = 0; iteration < 3; iteration++) {+ await close()+ await waitForStatelessSuspended(240_000, context, HOSTS[1], HOSTS[1])+ // Empty only the isolated chat cache: both observed rows must come from the remote catalog.+ if (fs.existsSync(cacheDir!))+ fs.rmSync(isolatedPath(runDir, cacheDir!), { recursive: true })+ await test.step(`W: ${build} suspended-stateless relaunch ${iteration + 1}`, () =>+ round('W', build, async id => {+ await launch(build)+ for (const sample of await relaunchPaint(+ page,+ HOSTS.map((host, index) => ({+ host,+ selector: rows(host),+ metric: index === 0 ? 'first_stateful_row_ms' : 'stateless_rows_ms',+ }))+ ))+ samples.push({ round: id, build, ...sample })+ await authenticated()+ await ready()+ }))+ }+ const values = (build: Build, host: string, metric: string, roundId?: number) =>+ samples+ .filter(+ sample =>+ sample.build === build &&+ sample.host === host &&+ sample.metric === metric &&+ (roundId === undefined || sample.round === roundId)+ )+ .map(sample => sample.ms)+ for (const sample of samples)+ report.cells[`${sample.build}/${sample.host}/${sample.metric}`] = quantiles(+ values(sample.build, sample.host, sample.metric)+ )+ for (const host of HOSTS) {+ const before = quantiles(values('before', host, 'open_cached_ms')).p50,+ after = quantiles(values('after', host, 'open_cached_ms')).p50+ const spread = Math.abs(+ quantiles(values('before', host, 'open_cached_ms', 1)).p50 -+ quantiles(values('before', host, 'open_cached_ms', 4)).p50+ )+ const budget = Math.max(spread, before * 0.1)+ report.gates.push({+ metric: 'open_cached_ms',+ host,+ before,+ after,+ aa_spread_ms: spread,+ budget_ms: budget,+ passed: after <= before + budget,+ })+ }+ const before = quantiles(values('before', HOSTS[0], 'relaunch_ms')).p50,+ after = quantiles(values('after', HOSTS[0], 'relaunch_ms')).p50+ report.gates.push({ metric: 'relaunch_ms', before, after, passed: after < before })+ const wakeAfter = Math.max(...values('after', HOSTS[0], 'first_stateful_row_ms'))+ report.gates.push({+ metric: 'first_stateful_row_ms',+ after_max_ms: wakeAfter,+ budget_ms: 2000,+ passed: wakeAfter < 2000,+ })+ report.gates.push({+ metric: 'round_validity',+ invalidated: rounds.filter(round => round.invalidated).length,+ passed: rounds.every(round => !round.invalidated),+ })+ // Rounds compared within a scenario must run under comparable 1-minute load.+ for (const scenario of ['O', 'L', 'W']) {+ const loads = rounds+ .filter(round => round.scenario === scenario)+ .map(round => round.loadavg[0]!)+ const spread = Math.max(...loads) - Math.min(...loads)+ report.gates.push({+ metric: 'loadavg_spread',+ scenario,+ spread,+ budget: 1,+ passed: loads.length > 0 && spread <= 1,+ })+ }+ report.complete = true+ } finally {+ try {+ await close()+ } finally {+ // Chat text stays in memory; evidence contains only catalog sizes, identities and raw timings.+ const catalogs = report.catalogs.map(({ chats, ...catalog }) => ({+ ...catalog,+ chats: chats.map(({ id, count }) => ({ id, count })),+ }))+ fs.mkdirSync(path.dirname(output), { recursive: true })+ fs.writeFileSync(output, JSON.stringify({ ...report, catalogs }, null, 2), { mode: 0o600 })+ }+ }+ expect(+ report.gates.every(gate => gate.passed),+ `Desktop A/B gates: ${JSON.stringify(report.gates)}; evidence: ${output}`+ ).toBe(true)+ })+}diff --git a/desktop-app/test/e2e-playwright/helpers/hostSnapshot.ts b/desktop-app/test/e2e-playwright/helpers/hostSnapshot.tsnew file mode 100644index 000000000..ae076f638--- /dev/null+++ b/desktop-app/test/e2e-playwright/helpers/hostSnapshot.ts@@ -0,0 +1,135 @@+import { expect } from '@playwright/test'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'++// E2E_GUARDIAN_IPC_FLOW: Host lifecycle is observed read-only through Kubernetes;+// Desktop RPC runs in the main process, outside renderer HTTP observation.+const execFileAsync = promisify(execFile)+const STATELESS_NAMESPACE = 'mcp-host'++async function kubectl(context: string, args: string[]): Promise<string> {+ if (!context.trim() || context.startsWith('-'))+ throw new Error('An explicit kube context is required.')+ const { stdout } = await execFileAsync('kubectl', ['--context', context, ...args], {+ timeout: 20_000,+ maxBuffer: 8 * 1024 * 1024,+ })+ return stdout.toString()+}++async function jsonKubectl(context: string, resource: string): Promise<any> {+ return JSON.parse(+ await kubectl(context, ['-n', STATELESS_NAMESPACE, 'get', resource, '-o', 'json'])+ )+}++export type HostSnapshot = {+ lifecycleState: string+ lifecycleReason: string+ replicas: number+ readyReplicas: number+ podNames: string[]+ imageIds: string[]+ pullPolicyRejection: string | null+}++export async function readHostSnapshot(+ deployment: string,+ hostName: string,+ context: string+): Promise<HostSnapshot> {+ const [deploymentJson, hostJson, podsJson] = await Promise.all([+ jsonKubectl(context, `deployment.apps/${deployment}`),+ jsonKubectl(context, `host/${hostName}`),+ kubectl(context, [+ '-n',+ STATELESS_NAMESPACE,+ 'get',+ 'pods',+ '-l',+ `app=${hostName}`,+ '-o',+ 'json',+ ]),+ ])+ const pods = JSON.parse(podsJson).items ?? []+ const spec = deploymentJson.spec ?? {}+ const status = deploymentJson.status ?? {}+ const lifecycle = hostJson.status?.lifecycle ?? {}+ const pullPolicyRejection = (hostJson.status?.conditions ?? []).find(+ (condition: { type?: string; status?: string }) =>+ condition.type === 'StatelessPullPolicyRejected' && condition.status === 'True'+ )+ return {+ lifecycleState: String(lifecycle.state ?? ''),+ lifecycleReason: String(lifecycle.reason ?? ''),+ replicas: Number(spec.replicas ?? -1),+ readyReplicas: Number(status.readyReplicas ?? 0),+ podNames: pods+ .map((pod: { metadata?: { name?: string } }) => pod.metadata?.name)+ .filter(Boolean)+ .sort(),+ imageIds: [+ ...new Set<string>(+ pods.flatMap((pod: { status?: { containerStatuses?: Array<{ imageID?: string }> } }) =>+ (pod.status?.containerStatuses ?? [])+ .map(container => container.imageID)+ .filter((id): id is string => typeof id === 'string' && id.length > 0)+ )+ ),+ ].sort(),+ pullPolicyRejection: pullPolicyRejection?.reason ?? null,+ }+}++export async function waitForStatelessSuspended(+ timeoutMs: number,+ context: string,+ deployment: string,+ hostName: string+): Promise<{+ snapshot: HostSnapshot+ elapsedMs: number+}> {+ const started = Date.now()+ let last = await readHostSnapshot(deployment, hostName, context)+ while (Date.now() - started < timeoutMs) {+ last = await readHostSnapshot(deployment, hostName, context)+ if (+ last.lifecycleState === 'suspended' &&+ last.replicas === 0 &&+ last.readyReplicas === 0 &&+ last.podNames.length === 0+ ) {+ expect(last.lifecycleReason, 'stateless suspension must be caused by idle timeout').toBe(+ 'idle'+ )+ return { snapshot: last, elapsedMs: Date.now() - started }+ }+ await new Promise(resolve => setTimeout(resolve, 5_000))+ }+ throw new Error(+ `Stateless host did not reach verified replicas-0 suspension: ${JSON.stringify(last)}`+ )+}++export async function waitForStatelessReady(+ timeoutMs: number,+ context: string,+ deployment: string,+ hostName: string+): Promise<{+ snapshot: HostSnapshot+ elapsedMs: number+}> {+ const started = Date.now()+ let last = await readHostSnapshot(deployment, hostName, context)+ while (Date.now() - started < timeoutMs) {+ last = await readHostSnapshot(deployment, hostName, context)+ if (last.replicas >= 1 && last.readyReplicas >= 1 && last.podNames.length > 0) {+ return { snapshot: last, elapsedMs: Date.now() - started }+ }+ await new Promise(resolve => setTimeout(resolve, 2_000))+ }+ throw new Error(`Stateless host did not become Ready: ${JSON.stringify(last)}`)+}diff --git a/desktop-app/test/e2e-playwright/human-stateless-continuity.spec.ts b/desktop-app/test/e2e-playwright/human-stateless-continuity.spec.tsindex e8ec0b697..085dab1a8 100644--- a/desktop-app/test/e2e-playwright/human-stateless-continuity.spec.ts+++ b/desktop-app/test/e2e-playwright/human-stateless-continuity.spec.ts@@ -19,6 +19,11 @@ import { type ElectronApplication, type Locator, type Page, expect, test } fromimport { type ChildProcess, execFile } from 'node:child_process'import { writeFileSync } from 'node:fs'import { promisify } from 'node:util'+import {+ readHostSnapshot,+ waitForStatelessReady,+ waitForStatelessSuspended,+} from './helpers/hostSnapshot'import {EXTERNAL_REST_API_BASE_URL,RPC_PROXY_BASE_URL,@@ -52,16 +57,6 @@ const SUSPEND_TIMEOUT_MS = 240_000// assistant response, known conversation marker, and Host CRD/pod state are// the business signals for this recorded journey.-type HostSnapshot = {- lifecycleState: string- lifecycleReason: string- replicas: number- readyReplicas: number- podNames: string[]- imageIds: string[]- pullPolicyRejection: string | null-}-type JourneyMetrics = {hcc_idle_minutes: numberhcc_idle_floor_minutes: number@@ -120,84 +115,6 @@ async function jsonKubectl(resource: string, namespace: string): Promise<any> {return JSON.parse(await kubectl(['-n', namespace, 'get', resource, '-o', 'json']))}-async function readHostSnapshot(deployment: string, hostName: string): Promise<HostSnapshot> {- const [deploymentJson, hostJson, podsJson] = await Promise.all([- jsonKubectl(`deployment.apps/${deployment}`, STATELESS_NAMESPACE),- jsonKubectl(`host/${hostName}`, STATELESS_NAMESPACE),- kubectl(['-n', STATELESS_NAMESPACE, 'get', 'pods', '-l', `app=${hostName}`, '-o', 'json']),- ])- const pods = JSON.parse(podsJson).items ?? []- const spec = deploymentJson.spec ?? {}- const status = deploymentJson.status ?? {}- const lifecycle = hostJson.status?.lifecycle ?? {}- const pullPolicyRejection = (hostJson.status?.conditions ?? []).find(- (condition: { type?: string; status?: string }) =>- condition.type === 'StatelessPullPolicyRejected' && condition.status === 'True'- )- return {- lifecycleState: String(lifecycle.state ?? ''),- lifecycleReason: String(lifecycle.reason ?? ''),- replicas: Number(spec.replicas ?? -1),- readyReplicas: Number(status.readyReplicas ?? 0),- podNames: pods- .map((pod: { metadata?: { name?: string } }) => pod.metadata?.name)- .filter(Boolean)- .sort(),- imageIds: [- ...new Set<string>(- pods.flatMap((pod: { status?: { containerStatuses?: Array<{ imageID?: string }> } }) =>- (pod.status?.containerStatuses ?? [])- .map(container => container.imageID)- .filter((id): id is string => typeof id === 'string' && id.length > 0)- )- ),- ].sort(),- pullPolicyRejection: pullPolicyRejection?.reason ?? null,- }-}--async function waitForStatelessSuspended(timeoutMs: number): Promise<{- snapshot: HostSnapshot- elapsedMs: number-}> {- const started = Date.now()- let last = await readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE)- while (Date.now() - started < timeoutMs) {- last = await readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE)- if (- last.lifecycleState === 'suspended' &&- last.replicas === 0 &&- last.readyReplicas === 0 &&- last.podNames.length === 0- ) {- expect(last.lifecycleReason, 'stateless suspension must be caused by idle timeout').toBe(- 'idle'- )- return { snapshot: last, elapsedMs: Date.now() - started }- }- await new Promise(resolve => setTimeout(resolve, 5_000))- }- throw new Error(- `Stateless host did not reach verified replicas-0 suspension: ${JSON.stringify(last)}`- )-}--async function waitForStatelessReady(timeoutMs: number): Promise<{- snapshot: HostSnapshot- elapsedMs: number-}> {- const started = Date.now()- let last = await readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE)- while (Date.now() - started < timeoutMs) {- last = await readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE)- if (last.replicas >= 1 && last.readyReplicas >= 1 && last.podNames.length > 0) {- return { snapshot: last, elapsedMs: Date.now() - started }- }- await new Promise(resolve => setTimeout(resolve, 2_000))- }- throw new Error(`Stateless host did not become Ready: ${JSON.stringify(last)}`)-}-async function readHccCadences(): Promise<{idleMinutes: numberidleFloorMinutes: number@@ -340,7 +257,12 @@ async function resolveColdSend(wakingVisibleMs = Date.now() - started// The retry is a user action. Wait for the observed Host to become Ready// before taking it; a fast click can fail while the pod is still waking.- await waitForStatelessReady(270_000)+ await waitForStatelessReady(+ 270_000,+ KUBE_CONTEXT,+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE+ )const retry = waking.getByRole('button', { name: /retry last send/i })await expect(retry).toBeEnabled({ timeout: 150_000 })await retry.click()@@ -484,8 +406,8 @@ test('human journey — two Hosts, restart, cache, and two verified stateless watry {await test.step('verify both Hosts and the branch-owned runtime baseline', async () => {const [statefulBefore, statelessBefore, cadences] = await Promise.all([- readHostSnapshot(STATEFUL_DEPLOYMENT, STATEFUL_HOST_RESOURCE),- readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE),+ readHostSnapshot(STATEFUL_DEPLOYMENT, STATEFUL_HOST_RESOURCE, KUBE_CONTEXT),+ readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE, KUBE_CONTEXT),readHccCadences(),])expect(@@ -553,7 +475,12 @@ test('human journey — two Hosts, restart, cache, and two verified stateless watimeout: 150_000,})await expect(statelessSend).toBeDisabled({ timeout: 150_000 })- const firstReady = await waitForStatelessReady(270_000)+ const firstReady = await waitForStatelessReady(+ 270_000,+ KUBE_CONTEXT,+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE+ )expect(firstReady.snapshot.imageIds,'record the actual stateless container imageID after the first UI response'@@ -592,7 +519,12 @@ test('human journey — two Hosts, restart, cache, and two verified stateless waapp = undefinedpage = undefined- const suspended = await waitForStatelessSuspended(SUSPEND_TIMEOUT_MS)+ const suspended = await waitForStatelessSuspended(+ SUSPEND_TIMEOUT_MS,+ KUBE_CONTEXT,+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE+ )metrics.first_suspend_ms = suspended.elapsedMsexpect(suspended.snapshot.lifecycleState).toBe('suspended')expect(suspended.snapshot.replicas).toBe(0)@@ -612,7 +544,12 @@ test('human journey — two Hosts, restart, cache, and two verified stateless wa// Observe the catalog-driven prewarm wake from authentication while the// retained conversation opens from local cache before Ready is observed.let readyObserved = false- const readyObservation = waitForStatelessReady(270_000).then(result => {+ const readyObservation = waitForStatelessReady(+ 270_000,+ KUBE_CONTEXT,+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE+ ).then(result => {readyObserved = truereturn { result, observedAt: Date.now() }})@@ -649,7 +586,12 @@ test('human journey — two Hosts, restart, cache, and two verified stateless waawait openExactSession(currentPage(), statelessTitle, STATELESS_HOST)const composer = currentPage().getByRole('textbox', { name: 'Agent message composer' })await composer.fill('')- const secondSuspended = await waitForStatelessSuspended(SUSPEND_TIMEOUT_MS)+ const secondSuspended = await waitForStatelessSuspended(+ SUSPEND_TIMEOUT_MS,+ KUBE_CONTEXT,+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE+ )metrics.second_suspend_ms = secondSuspended.elapsedMsexpect(secondSuspended.snapshot.lifecycleState).toBe('suspended')expect(secondSuspended.snapshot.replicas).toBe(0)@@ -662,7 +604,11 @@ test('human journey — two Hosts, restart, cache, and two verified stateless wa// second_launch_to_stateless_ready_ms. This fresh snapshot proves that// the second send is itself a cold wake intent, not a continuation of// that earlier prewarm window.- const preClick = await readHostSnapshot(STATELESS_DEPLOYMENT, STATELESS_HOST_RESOURCE)+ const preClick = await readHostSnapshot(+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE,+ KUBE_CONTEXT+ )metrics.cold_send_pre_click_ready_replicas = preClick.readyReplicasexpect(preClick.lifecycleState).toBe('suspended')expect(preClick.replicas).toBe(0)@@ -673,7 +619,12 @@ test('human journey — two Hosts, restart, cache, and two verified stateless wa// the still-suspended Host, and the stepper count baseline excludes// completed steppers from earlier turns that keep the same test id.let readyObserved = false- const readyObservation = waitForStatelessReady(270_000).then(result => {+ const readyObservation = waitForStatelessReady(+ 270_000,+ KUBE_CONTEXT,+ STATELESS_DEPLOYMENT,+ STATELESS_HOST_RESOURCE+ ).then(result => {readyObserved = truereturn { result, observedAt: Date.now() }})@@ -767,7 +718,11 @@ test('human journey — two Hosts, restart, cache, and two verified stateless waawait expect(currentPage().getByTestId('agent-response').filter({ hasText: statefulFollowMarker })).toContainText(statefulMarker)- const statefulAfter = await readHostSnapshot(STATEFUL_DEPLOYMENT, STATEFUL_HOST_RESOURCE)+ const statefulAfter = await readHostSnapshot(+ STATEFUL_DEPLOYMENT,+ STATEFUL_HOST_RESOURCE,+ KUBE_CONTEXT+ )metrics.stateful_pod_after = statefulAfter.podNamesexpect(statefulAfter.readyReplicas).toBeGreaterThan(0)expect(statefulAfter.podNames.join(',')).toBe(metrics.stateful_pod_before.join(','))diff --git a/desktop-app/test/e2e-playwright/playwright.chat-open-ab.config.ts b/desktop-app/test/e2e-playwright/playwright.chat-open-ab.config.tsnew file mode 100644index 000000000..5690f0d8a--- /dev/null+++ b/desktop-app/test/e2e-playwright/playwright.chat-open-ab.config.ts@@ -0,0 +1,27 @@+import { defineConfig } from '@playwright/test'+import { execFileSync } from 'node:child_process'+import path from 'node:path'+import base from './playwright.config'++// Only this config registers the opt-in benchmark; ordinary collection sees no test.+process.env.DESKTOP_CHAT_OPEN_AB_CONFIG = __filename+process.env.QA_RECORDER_SLOW_MO_MS = '0'+process.env.QA_RECORDER_VIDEO = '0'+const commonDir = execFileSync('git', ['rev-parse', '--git-common-dir'], {+ cwd: path.resolve(__dirname, '../../..'),+ encoding: 'utf8',+}).trim()+const repositoryRoot = path.resolve(__dirname, '../../..', commonDir, '..')++export default defineConfig({+ ...base,+ globalSetup: undefined,+ projects: [{ name: 'chat-open-ab', testMatch: /chat-open-ab\.spec\.ts/ }],+ timeout: 2_400_000,+ expect: { timeout: 30_000 },+ retries: 0,+ workers: 1,+ reporter: [['list']],+ outputDir: path.join(repositoryRoot, '.local-notes/issue1091-evidence/v2/C3/runs'),+ preserveOutput: 'always',+})diff --git a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts b/desktop-app/test/e2e-playwright/qa-recorder-helpers.tsindex 8aac2b570..a6eec826e 100644--- a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts+++ b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts@@ -24,6 +24,16 @@ import path from 'node:path'export const DESKTOP_APP_ROOT = path.resolve(__dirname, '../..')export const MAIN_ENTRY = path.join(DESKTOP_APP_ROOT, 'dist/main.js')++export function validateMainEntry(mainEntry: string): void {+ if (!path.isAbsolute(mainEntry) || !mainEntry.endsWith(`${path.sep}dist${path.sep}main.js`)) {+ throw new Error('Desktop mainEntry must be an absolute path ending in dist/main.js.')+ }+ if (!fs.existsSync(mainEntry) || !fs.statSync(mainEntry).isFile()) {+ throw new Error(`Desktop app build missing at ${mainEntry}. Run npm run build first.`)+ }+}+export const EXTERNAL_REST_API_BASE_URL =process.env.EXTERNAL_REST_API_BASE_URL ||process.env.EXTERNAL_REST_API_URL ||@@ -124,14 +134,13 @@ export function configuredHostRef(): string {*/export async function launchDesktopApp(testInfo: TestInfo,- isolationTarget?: string+ isolationTarget?: string,+ mainEntry: string = MAIN_ENTRY): Promise<{app: ElectronApplicationpage: Page}> {- if (!fs.existsSync(MAIN_ENTRY)) {- throw new Error(`Desktop app build missing at ${MAIN_ENTRY}. Run npm run build first.`)- }+ validateMainEntry(mainEntry)const isolationRunDir = testInfo.outputPath('electron-isolation')const userDataDir = isolationTarget@@ -144,7 +153,7 @@ export async function launchDesktopApp(const slowMo = Number(process.env.QA_RECORDER_SLOW_MO_MS ?? 75)const app = await electron.launch({- args: [`--user-data-dir=${userDataDir}`, MAIN_ENTRY],+ args: [`--user-data-dir=${userDataDir}`, mainEntry],env: {...process.env,ELECTRON_RENDERER_URL: '',@@ -161,7 +170,7 @@ export async function launchDesktopApp(EVENFIRE_DEV_ISOLATION_TARGET: isolationTarget,EVENFIRE_DEV_ISOLATION_REST_URL: EXTERNAL_REST_API_BASE_URL,EVENFIRE_DEV_ISOLATION_RPC_URL: RPC_PROXY_BASE_URL,- EVENFIRE_DEV_ISOLATION_APP_PATH: path.dirname(MAIN_ENTRY),+ EVENFIRE_DEV_ISOLATION_APP_PATH: path.dirname(mainEntry),}: {}),},diff --git a/desktop-app/test/qaRecorderHelpers.test.ts b/desktop-app/test/qaRecorderHelpers.test.tsindex 2cdf29494..9d05efd78 100644--- a/desktop-app/test/qaRecorderHelpers.test.ts+++ b/desktop-app/test/qaRecorderHelpers.test.ts@@ -1,5 +1,15 @@-import { afterEach, describe, expect, it, vi } from 'vitest'-import { assertAllowedTarget, desktopCredentials } from './e2e-playwright/qa-recorder-helpers'+import { type MockInstance, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { type ElectronApplication, type TestInfo, _electron as electron } from '@playwright/test'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import {+ MAIN_ENTRY,+ assertAllowedTarget,+ desktopCredentials,+ launchDesktopApp,+ validateMainEntry,+} from './e2e-playwright/qa-recorder-helpers'describe('QA recorder target guard', () => {const previousRemoteOptIn = process.env.QA_RECORDER_ALLOW_REMOTE@@ -62,3 +72,104 @@ describe('QA recorder target guard', () => {)})})++describe('QA recorder Desktop main entry', () => {+ let root: string+ let mainEntry: string+ let testInfo: TestInfo+ let launchMock: MockInstance<typeof electron.launch>++ beforeEach(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'qa-main-entry-'))+ mainEntry = path.join(root, 'build-a', 'dist', 'main.js')+ fs.mkdirSync(path.dirname(mainEntry), { recursive: true })+ // A filesystem validation fixture, never executed as an Electron entry.+ fs.writeFileSync(mainEntry, 'export {}\n')+ testInfo = { outputPath: (...parts: string[]) => path.join(root, 'run', ...parts) } as TestInfo+ launchMock = vi.spyOn(electron, 'launch').mockImplementation(async options => {+ const argument = options!.args![0]!+ const userData = argument.slice('--user-data-dir='.length)+ return {+ evaluate: vi.fn().mockResolvedValue(userData),+ firstWindow: vi.fn().mockResolvedValue({ waitForLoadState: vi.fn() }),+ close: vi.fn(),+ } as unknown as ElectronApplication+ })+ })++ afterEach(() => {+ vi.restoreAllMocks()+ fs.rmSync(root, { recursive: true, force: true })+ })++ it('launches both absolute build entries on the same isolated profile', async () => {+ const afterEntry = path.join(root, 'build-b', 'dist', 'main.js')+ fs.mkdirSync(path.dirname(afterEntry), { recursive: true })+ fs.copyFileSync(mainEntry, afterEntry)+ await launchDesktopApp(testInfo, 'issue-1091-ab', mainEntry)+ await launchDesktopApp(testInfo, 'issue-1091-ab', afterEntry)+ expect(launchMock).toHaveBeenCalledTimes(2)+ const [beforeOptions] = launchMock.mock.calls[0]!+ const [afterOptions] = launchMock.mock.calls[1]!+ expect(beforeOptions!.args).toEqual([+ `--user-data-dir=${path.join(root, 'run/electron-isolation/user-data')}`,+ mainEntry,+ ])+ expect(afterOptions!.args).toEqual([beforeOptions!.args![0], afterEntry])+ for (const [options] of launchMock.mock.calls) {+ expect(options!.env).toMatchObject({+ EVENFIRE_DEV_ISOLATION: '1',+ EVENFIRE_DEV_ISOLATION_TARGET: 'issue-1091-ab',+ EVENFIRE_DEV_ISOLATION_RUN_DIR: path.join(root, 'run/electron-isolation'),+ EVENFIRE_DEV_ISOLATION_APP_PATH: path.dirname(options!.args![1]!),+ CLERUM_DESKTOP_CONFIG_PATH: path.join(root, 'run/electron-isolation/runtime-config.json'),+ })+ }+ })++ it('keeps the default entry and non-isolated user-data path', async () => {+ const originalExists = fs.existsSync.bind(fs),+ originalStat = fs.statSync.bind(fs)+ vi.spyOn(fs, 'existsSync').mockImplementation(+ value => value === MAIN_ENTRY || originalExists(value)+ )+ vi.spyOn(fs, 'statSync').mockImplementation(value =>+ originalStat(value === MAIN_ENTRY ? mainEntry : value)+ )+ await launchDesktopApp(testInfo)+ expect(launchMock).toHaveBeenCalledWith(+ expect.objectContaining({+ args: [`--user-data-dir=${path.join(root, 'run/electron-user-data')}`, MAIN_ENTRY],+ })+ )+ })++ it.each(['relative', 'wrong directory', 'wrong basename', 'missing file', 'directory'])(+ 'rejects %s before launch, with a valid-launch witness',+ async kind => {+ let invalidEntry: string+ if (kind === 'relative') invalidEntry = 'build-a/dist/main.js'+ else if (kind === 'wrong directory') {+ invalidEntry = path.join(root, 'main.js')+ fs.copyFileSync(mainEntry, invalidEntry)+ } else if (kind === 'wrong basename') {+ invalidEntry = path.join(root, 'build-a/dist/other.js')+ fs.copyFileSync(mainEntry, invalidEntry)+ } else if (kind === 'missing file') invalidEntry = path.join(root, 'missing/dist/main.js')+ else {+ invalidEntry = path.join(root, 'directory/dist/main.js')+ fs.mkdirSync(invalidEntry, { recursive: true })+ }+ const mkdir = vi.spyOn(fs, 'mkdirSync')+ await expect(launchDesktopApp(testInfo, 'issue-1091-ab', invalidEntry)).rejects.toThrow(+ /absolute path ending in dist\/main.js|Desktop app build missing/+ )+ expect(launchMock).not.toHaveBeenCalled()+ expect(mkdir).not.toHaveBeenCalled()+ validateMainEntry(mainEntry)+ await launchDesktopApp(testInfo, 'issue-1091-ab', mainEntry)+ expect(launchMock).toHaveBeenCalledTimes(1)+ expect(mkdir).toHaveBeenCalled()+ }+ )+})