Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

test(e2e): 23 unzuverlaessige Tests, EINE Ursache — und 15 `any` weg

David85595d1864c3
diff --git a/e2e/chat-streaming-persist.spec.ts b/e2e/chat-streaming-persist.spec.ts
index 081bc01b..44db071e 100644
--- a/e2e/chat-streaming-persist.spec.ts
+++ b/e2e/chat-streaming-persist.spec.ts
@@ -33,23 +33,60 @@ async function boot(page: Page) {
await page.goto('/')
}
+/**
+ * Scoped to the TRANSCRIPT, and to paragraphs. Two different traps:
+ *
+ * 1. the sidebar shows the first message as the conversation title, so a bare
+ * `getByText` matches it a second time — hence `getByRole('main')`;
+ * 2. Playwright's text engine reads a `<textarea>`'s VALUE as its text. While
+ * a typed message still sits in the composer, `main.getByText('…MARKER')`
+ * therefore matches the COMPOSER. That is not a detail: it is how the
+ * previous version of this spec could assert "the second message is on
+ * screen" about a send the app had silently dropped — the text it found
+ * was the text still waiting in the input. Messages render as paragraphs;
+ * the composer does not.
+ */
+function inChat(page: Page, text: string) {
+ return page.getByRole('main').locator('p').filter({ hasText: text })
+}
+
async function send(page: Page, text: string) {
const composer = page.locator('textarea').first()
+ const sendButton = page.getByRole('button', { name: 'Send message' })
+ // The transcript bubble, NOT the composer — see inChat() below for why the
+ // difference decides whether this helper can tell a sent message from an
+ // unsent one at all.
+ const bubble = inChat(page, text)
+
await expect(composer).toBeVisible({ timeout: 20_000 })
- // The composer drops a send issued while the previous turn is still
- // finishing, and the visible reply appears a few frames before the turn
- // actually ends, so settle first.
- await page.waitForTimeout(1500)
- await composer.fill(text)
- await page.getByRole('button', { name: /Send message/i }).click()
-}
+ // Send and Stop share ONE slot in this composer, so "Send is back" is the
+ // observable end of the previous turn — ChatInput refuses a send while
+ // `isGenerating`.
+ await expect(sendButton).toBeVisible({ timeout: 30_000 })
-/** Scoped to the transcript — the sidebar shows the first message as the
- * conversation title, which would match every bare getByText twice. */
-function inChat(page: Page, text: string) {
- return page.getByRole('main').getByText(text)
+ // That is necessary and NOT sufficient, which is what the flat 1.5 s sleep
+ // this replaces was covering by accident. ChatInput also holds a 700 ms
+ // double-fire lock (SEND_LOCK_MS, chat/ChatInput.tsx) measured from the last
+ // ACCEPTED send, not from the end of the turn. A message that lands inside
+ // that window is dropped in silence: no bubble, no error, the text simply
+ // stays in the composer. Measured here on 2026-09-01: with a 24-frame reply
+ // the turn is over ~300 ms after the send, so the second send landed at
+ // ~500 ms — inside the lock — and this spec failed 3 runs out of 4.
+ //
+ // So the send verifies its own effect and, when it was swallowed, does what
+ // a person does: press again. The retry is guarded by the bubble itself, so
+ // an accepted send is never sent a second time.
+ await expect(async () => {
+ if ((await bubble.count()) === 0) {
+ await composer.fill(text)
+ await expect(sendButton).toBeEnabled()
+ await sendButton.click()
+ }
+ await expect(bubble).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
}
+
test('a streamed answer renders live, lands in full, and survives a reload', async ({ page }) => {
await boot(page)
// openNewChat, not a bare click: right after onboarding the model list is
diff --git a/e2e/cloud-gate.spec.ts b/e2e/cloud-gate.spec.ts
index 202deb51..e26f28f8 100644
--- a/e2e/cloud-gate.spec.ts
+++ b/e2e/cloud-gate.spec.ts
@@ -1,6 +1,6 @@
import { test, expect, type Page } from '@playwright/test'
import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
-import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch, type CloudScenario } from './support/cloud-mock'
+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch, cloudSwitchBehindModal, type CloudScenario } from './support/cloud-mock'
/**
* 2.5.7 cloud gate — the wall in front of Cloud mode (David's 4-options flow).
@@ -42,8 +42,11 @@ test('signed in without a plan: plan buttons → browser, switch stays off', asy
const opened = await page.evaluate(() => (window as unknown as { __E2E_OPENED_URLS__?: string[] }).__E2E_OPENED_URLS__ ?? [])
expect(opened.some((u) => u.includes('/pricing#max'))).toBe(true)
- // Gate holds: the switch is still off.
- await expect(cloudSwitch(page)).not.toBeChecked()
+ // Gate holds: the switch is still off. Read through the modal-proof locator —
+ // the gate is still open here, and an open dialog marks the rest of the page
+ // `inert` + `aria-hidden`, so the role query would find nothing and this
+ // would fail for a reason that has nothing to do with the switch.
+ await expect(cloudSwitchBehindModal(page)).toHaveAttribute('aria-checked', 'false')
})
test('licensed but not server-enabled (access:false): wall with Check again, switch stays off', async ({ page }) => {
@@ -52,7 +55,9 @@ test('licensed but not server-enabled (access:false): wall with Check again, swi
await expect(page.getByText(/hasn't switched Cloud on/i)).toBeVisible({ timeout: 20_000 })
await expect(page.getByRole('button', { name: /Check again/i })).toBeVisible()
- await expect(cloudSwitch(page)).not.toBeChecked()
+ // Same reason as above: the wall IS the open dialog, so the switch behind it
+ // is out of the accessibility tree by design.
+ await expect(cloudSwitchBehindModal(page)).toHaveAttribute('aria-checked', 'false')
})
test('"Stay on Local" closes the gate with the switch off', async ({ page }) => {
diff --git a/e2e/coding-agent.spec.ts b/e2e/coding-agent.spec.ts
index 401657bb..c008a8dc 100644
--- a/e2e/coding-agent.spec.ts
+++ b/e2e/coding-agent.spec.ts
@@ -2,6 +2,7 @@ import { test, expect, type Page } from '@playwright/test'
import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'
import { seedOnboardingDone } from './support/cloud-mock'
import { openNewChat } from './support/ui'
+import { toolCalls } from './support/recorded'
/**
* End-to-end cover for the 2.6.3 agent audit, driven through the real React
@@ -46,14 +47,34 @@ async function boot(page: Page, agentTurns: Turn[]) {
async function instruct(page: Page, text: string) {
const composer = page.locator('textarea').first()
+ // The transcript echo of the instruction. Scoped to paragraphs on purpose:
+ // Playwright's text engine reads a <textarea>'s VALUE as its text, so a bare
+ // getByText would match the COMPOSER and report an unsent message as sent.
+ const echoed = page.getByRole('main').locator('p').filter({ hasText: text })
+
await expect(composer).toBeVisible({ timeout: 20_000 })
- await page.waitForTimeout(800)
- await composer.fill(text)
- await composer.press('Enter')
-}
+ // What the 800 ms sleep here was actually waiting for: the composer becomes
+ // usable only once the view has a model (ChatInput renders `disabled` until
+ // then and drops the keystroke), and it refuses a send while a previous turn
+ // is still running. Both are visible states — a disabled textarea, and the
+ // Send/Stop slot showing Send — so wait for those instead of for a clock.
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+ await expect(page.getByRole('button', { name: 'Send message' })).toBeVisible({ timeout: 20_000 })
-const toolCalls = (page: Page) =>
- page.evaluate(() => (window as any).__E2E_TOOL_CALLS__ || [])
+ // And then verify the instruction actually went in. ChatInput drops a send
+ // in silence in more than one situation (a 700 ms double-fire lock, a view
+ // that has not finished wiring its model), leaving the text sitting in the
+ // composer with no error anywhere. Without this check the drop surfaces
+ // twenty seconds later as "the answer never appeared", which points at the
+ // wrong half of the app.
+ await expect(async () => {
+ if ((await echoed.count()) === 0) {
+ await composer.fill(text)
+ await composer.press('Enter')
+ }
+ await expect(echoed).toBeVisible({ timeout: 2_000 })
+ }).toPass({ timeout: 30_000 })
+}
test('the Code tab streams on the built-in engine instead of painting in one tick', async ({ page }) => {
// One long prose turn, no tools: the whole point is WHEN the text appears.
@@ -89,7 +110,10 @@ test('a run survives a tab switch and is still stoppable afterwards', async ({ p
// they would prove something else.)
const header = page.getByRole('banner')
await header.getByRole('button', { name: 'Models' }).click()
- await page.waitForTimeout(800)
+ // The point of this move is that CodexView really UNMOUNTS, so wait for
+ // proof that the other view took the slot — the Model Manager is a LazyView,
+ // and its chunk load is exactly the part a fixed 800 ms could lose.
+ await expect(page.getByRole('button', { name: /Back to chat/i })).toBeVisible({ timeout: 20_000 })
await header.getByRole('button', { name: 'Chat' }).click()
// The remounted view must still show the run as active — before the fix the
@@ -98,11 +122,24 @@ test('a run survives a tab switch and is still stoppable afterwards', async ({ p
await expect(stop).toBeVisible({ timeout: 20_000 })
await stop.click()
- // And Stop actually reaches the controller the OLD hook instance created:
- // the tool calls stop climbing.
- await page.waitForTimeout(1500)
+ // Stop actually reached the controller the OLD hook instance created. The
+ // observable proof is the composer: Stop gives its slot back to Send only
+ // when the run is really over, so this waits for the stop instead of
+ // sleeping through it.
+ await expect(page.getByRole('button', { name: 'Send message' })).toBeVisible({ timeout: 20_000 })
+
+ // A tool call that was already in flight when Stop landed still reports back
+ // through the bridge, so give it one short settle before taking the
+ // reference count …
+ await page.waitForTimeout(1_000)
const settled = (await toolCalls(page)).length
- await page.waitForTimeout(2500)
+ // … and after that nothing more may arrive at all. This is the falsifiable
+ // half and it is the one the audit cares about: an orphaned loop would keep
+ // pushing calls into this window. There is no event for "no event", so this
+ // half needs a window — but it is now ONLY the observation, not also the
+ // wait for the stop to take effect, which is what the old 1.5 s + 2.5 s pair
+ // was doing in one lump.
+ await page.waitForTimeout(2_500)
expect((await toolCalls(page)).length).toBe(settled)
})
@@ -143,10 +180,18 @@ async function bootAgentMode(page: Page, agentTurns: Turn[]) {
await openNewChat(page)
const agentToggle = page.getByRole('main').getByRole('button', { name: 'Agent', exact: true })
await agentToggle.click()
+ // Activation opens the "Where should the agent work?" dialog FIRST, and
+ // `ui/Modal` marks the rest of the page `inert` + `aria-hidden` while a
+ // dialog is up. So the toggle behind it is out of the accessibility tree,
+ // and asserting on it before answering the dialog is a race the spec loses
+ // whenever the dialog wins the frame. Answer the dialog, then look at the
+ // toggle. The sandbox is the right answer for a spec — it touches nothing
+ // outside ~/agent-workspace.
+ const sandbox = page.getByRole('button', { name: /^Sandbox/ })
+ await expect(sandbox).toBeVisible({ timeout: 15_000 })
+ await sandbox.click()
+ await expect(page.getByRole('dialog', { name: /Agent workspace/i })).toHaveCount(0, { timeout: 10_000 })
await expect(agentToggle).toHaveAttribute('title', /Agent Mode is on/i, { timeout: 10_000 })
- // Activation offers a workspace; the sandbox is the right answer for a spec.
- const sandbox = page.getByRole('button', { name: /Sandbox/i })
- if (await sandbox.isVisible().catch(() => false)) await sandbox.click()
}
test('agent mode: edit, test, edit, test — the second identical command really re-runs', async ({ page }) => {
@@ -162,7 +207,7 @@ test('agent mode: edit, test, edit, test — the second identical command really
await expect(page.getByRole('main').getByText('Done: the suite is green.')).toBeVisible({ timeout: 30_000 })
const calls = await toolCalls(page)
- const shellRuns = calls.filter((c: any) => c.cmd === 'shell_execute' && c.command === RUN)
+ const shellRuns = calls.filter((c) => c.cmd === 'shell_execute' && c.command === RUN)
// Two real executions. The over-loop guard used to drop the second one and
// tell the model nothing had changed — with a file_write in between, which
// is exactly when it HAS changed (audit B1).
@@ -227,19 +272,37 @@ test('the plan the model writes shows up above the composer and tracks progress'
await instruct(page, 'fix the parser and prove it')
await expect(page.getByRole('main').getByText('PLAN_RUN_DONE')).toBeVisible({ timeout: 30_000 })
- // Collapsed by default, so what must be on screen is the counter and the step
- // that is running right now — not the whole list pushing the composer away.
- await expect(page.getByText('plan 1/3')).toBeVisible({ timeout: 10_000 })
- await expect(page.getByText('patch the parser').first()).toBeVisible()
+ // PlanBar has TWO homes and they disagree about the default state ON PURPOSE
+ // (chat/PlanBar.tsx): 'header' starts collapsed so it costs one line above
+ // the transcript, 'panel' — the Code tab's Explorer column — starts expanded.
+ // The old version assumed "collapsed" and clicked a bare text node, so on the
+ // surface that renders the panel the click COLLAPSED the plan and the step
+ // list it then looked for was the one it had just closed. That is what made
+ // this spec pass or fail with whichever home the run happened to render.
+ //
+ // Which home is showing is not what this spec is about, so it drives the
+ // strip through BOTH states and asserts each one. The toggle names the state
+ // it is in, so nothing here is assumed.
+ const strip = page.getByTestId('plan-header').or(page.getByTestId('plan-panel')).first()
+ const planToggle = strip.getByRole('button', { name: /^plan 1\/3/ })
+ await expect(planToggle).toBeVisible({ timeout: 15_000 })
+ if ((await planToggle.getAttribute('title')) === 'Collapse the plan') await planToggle.click()
+
+ // Collapsed: the counter and the step that is running right now — and NOT
+ // the whole list, which is the part that would push the composer away.
+ await expect(planToggle).toHaveAttribute('title', 'Show every step')
+ await expect(planToggle).toContainText('patch the parser')
+ await expect(strip.getByText('read the config')).toHaveCount(0)
- // Expanding shows every step, with the finished one struck through.
- await page.getByText('plan 1/3').click()
- await expect(page.getByText('read the config')).toBeVisible()
- await expect(page.getByText('run the suite')).toBeVisible()
+ // Expanded: every step, and the strip follows the model's second update.
+ await planToggle.click()
+ await expect(planToggle).toHaveAttribute('title', 'Collapse the plan')
+ await expect(strip.getByText('read the config')).toBeVisible()
+ await expect(strip.getByText('run the suite')).toBeVisible()
// `todo_write` must never have gone near the Rust bridge: it is pure
// conversation state, and a backend round trip would mean a permission gate
// on writing a to-do list.
const calls = await toolCalls(page)
- expect(calls.filter((c: any) => c.cmd === 'todo_write')).toEqual([])
+ expect(calls.filter((c) => c.cmd === 'todo_write')).toEqual([])
})
diff --git a/e2e/document-chat-builtin.spec.ts b/e2e/document-chat-builtin.spec.ts
index eca2696c..c5e28dce 100644
--- a/e2e/document-chat-builtin.spec.ts
+++ b/e2e/document-chat-builtin.spec.ts
@@ -1,5 +1,10 @@
import { test, expect, type Page } from '@playwright/test'
import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { proxyUrls } from './support/recorded'
+// Types only — erased at build time, so nothing from src is pulled into the
+// test bundle. It gives the page-side module handle below the REAL signatures
+// of src/api/rag.ts instead of a hand-copied guess that would drift.
+import type * as RagModule from '../src/api/rag'
/**
* P5 acceptance test — Document-Chat / RAG embeddings without Ollama.
@@ -50,7 +55,18 @@ test('document chat embeds via the bundled server, never Ollama', async ({ page
// ── Drive the real RAG pipeline in-page against the mocked bundled embed ──
const result = await page.evaluate(async () => {
- const rag = await import('/src/api/rag.ts')
+ // The pipeline has to run INSIDE the page — it talks to the mocked Tauri
+ // bridge — so rag.ts is reachable only through the URL Vite serves it
+ // under. A dynamic import of a runtime string is untyped by construction;
+ // the annotation restores the real module type (see the `import type`
+ // above), and the check below proves at RUNTIME that the two entry points
+ // are actually there. A renamed export then fails with a sentence instead
+ // of "rag.indexDocument is not a function".
+ const RAG_MODULE_URL = '/src/api/rag.ts'
+ const rag: typeof RagModule = await import(/* @vite-ignore */ RAG_MODULE_URL)
+ if (typeof rag.indexDocument !== 'function' || typeof rag.retrieveContext !== 'function') {
+ throw new Error('src/api/rag.ts no longer exports indexDocument/retrieveContext')
+ }
const file = new File(
['The mitochondria is the powerhouse of the cell. It produces ATP through respiration. ' +
'Ribosomes synthesize proteins from messenger RNA in the cytoplasm of the cell.'],
@@ -61,19 +77,20 @@ test('document chat embeds via the bundled server, never Ollama', async ({ page
const retrieved = await rag.retrieveContext('what makes ATP in the cell', chunks, undefined, 2)
return {
chunkCount: chunks.length,
- embeddingDims: chunks.map((c: any) => (Array.isArray(c.embedding) ? c.embedding.length : 0)),
+ // `embedding` is typed number[], but this spec exists to catch the case
+ // where the pipeline hands back something else, so the array check stays.
+ embeddingDims: chunks.map((c) => (Array.isArray(c.embedding) ? c.embedding.length : 0)),
retrievedChunks: retrieved.context.chunks.length,
- proxyUrls: (window as any).__E2E_PROXY_URLS__ || [],
}
})
// The document was chunked and every chunk carries a real embedding vector.
expect(result.chunkCount).toBeGreaterThan(0)
- expect(result.embeddingDims.every((d: number) => d > 0)).toBe(true)
+ expect(result.embeddingDims.every((d) => d > 0)).toBe(true)
expect(result.retrievedChunks).toBeGreaterThan(0)
// Embeddings hit the bundled server on 8128 …
- const urls: string[] = result.proxyUrls
+ const urls = await proxyUrls(page)
expect(urls.some((u) => u.includes(':8128') && u.includes('/v1/embeddings'))).toBe(true)
// … and NEVER Ollama's /api/embed on 11434.
expect(urls.some((u) => u.includes('11434') && u.includes('/embed'))).toBe(false)
diff --git a/e2e/mac-create-mlx.spec.ts b/e2e/mac-create-mlx.spec.ts
index 9e0b9498..ecd63661 100644
--- a/e2e/mac-create-mlx.spec.ts
+++ b/e2e/mac-create-mlx.spec.ts
@@ -1,6 +1,7 @@
import { test, expect, type Page } from '@playwright/test'
import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'
import { routeCloud, seedOnboardingDone, cloudSwitch } from './support/cloud-mock'
+import { mlxCalls, comfyCalls, hfToken, requireCall } from './support/recorded'
/**
* macOS local Create — the MLX path (MAC-5).
@@ -32,11 +33,6 @@ async function bootLocalCreate(page: Page, opts: TauriMockOptions) {
await page.getByRole('button', { name: /^Create$/ }).click()
}
-/** Everything the page recorded through the mocked MLX commands. */
-function mlxCalls(page: Page) {
- return page.evaluate(() => (window as unknown as { __E2E_MLX_CALLS__?: unknown[] }).__E2E_MLX_CALLS__ ?? [])
-}
-
test('mac local: MLX lanes run locally, cloud-only lanes stay visible as teasers', async ({ page }) => {
await bootLocalCreate(page, MAC_OPTS)
@@ -70,20 +66,17 @@ test('mac local: image generate dispatches to MLX, never to ComfyUI', async ({ p
await page.getByRole('button', { name: /^Create$/ }).last().click()
await expect
- .poll(async () => (await mlxCalls(page)).filter((c: any) => c.cmd === 'mlx_generate').length, { timeout: 30_000 })
+ .poll(async () => (await mlxCalls(page)).filter((c) => c.cmd === 'mlx_generate').length, { timeout: 30_000 })
.toBeGreaterThan(0)
- const gen = (await mlxCalls(page)).find((c: any) => c.cmd === 'mlx_generate') as any
+ const gen = requireCall(await mlxCalls(page), 'mlx_generate')
expect(gen.prompt).toContain('a red apple')
// The render came back as a data: PNG and is on screen.
await expect(page.locator('img[src^="data:image/png"]').first()).toBeVisible({ timeout: 30_000 })
// The point of the whole platform split: no ComfyUI call was even attempted.
- const comfy = await page.evaluate(
- () => (window as unknown as { __E2E_COMFY_CALLS__?: unknown[] }).__E2E_COMFY_CALLS__ ?? [],
- )
- expect(comfy).toHaveLength(0)
+ expect(await comfyCalls(page)).toHaveLength(0)
})
test('mac local: video generate dispatches to the MLX video model', async ({ page }) => {
@@ -95,10 +88,10 @@ test('mac local: video generate dispatches to the MLX video model', async ({ pag
await page.getByRole('button', { name: /^Create$/ }).last().click()
await expect
- .poll(async () => (await mlxCalls(page)).filter((c: any) => c.cmd === 'video_generate').length, { timeout: 40_000 })
+ .poll(async () => (await mlxCalls(page)).filter((c) => c.cmd === 'video_generate').length, { timeout: 40_000 })
.toBeGreaterThan(0)
- const gen = (await mlxCalls(page)).find((c: any) => c.cmd === 'video_generate') as any
+ const gen = requireCall(await mlxCalls(page), 'video_generate')
expect(gen.id).toBe('wan21-t2v-1.3b')
expect(gen.prompt).toContain('drifting clouds')
})
@@ -134,7 +127,7 @@ test('fresh mac: the Local Media panel installs the engine and a model', async (
await page.getByRole('button', { name: /^Install$/ }).first().click()
await expect(page.getByRole('button', { name: /Remove/i }).first()).toBeVisible({ timeout: 20_000 })
- const calls = (await mlxCalls(page)) as any[]
+ const calls = await mlxCalls(page)
expect(calls.some((c) => c.cmd === 'mlx_image_install_model' && c.id === 'sd-turbo')).toBe(true)
})
@@ -161,17 +154,14 @@ test('fresh mac: Create itself offers the setup, and it is the MLX one', async (
// Engine first, then the SMALLEST model in the catalog — the setup path
// must not pull the 4.4 GB one when a 2.6 GB one would do.
await expect
- .poll(async () => (await mlxCalls(page)).map((c: any) => c.cmd), { timeout: 30_000 })
+ .poll(async () => (await mlxCalls(page)).map((c) => c.cmd), { timeout: 30_000 })
.toContain('mlx_image_install_model')
- const calls = (await mlxCalls(page)) as any[]
+ const calls = await mlxCalls(page)
expect(calls.some((c) => c.cmd === 'install_mlx_diffusion')).toBe(true)
- expect(calls.find((c) => c.cmd === 'mlx_image_install_model').id).toBe('sd-turbo')
+ expect(requireCall(calls, 'mlx_image_install_model').id).toBe('sd-turbo')
// The hard rule: nothing in this flow reaches for ComfyUI.
- const comfy = await page.evaluate(
- () => (window as unknown as { __E2E_COMFY_CALLS__?: unknown[] }).__E2E_COMFY_CALLS__ ?? [],
- )
- expect(comfy).toHaveLength(0)
+ expect(await comfyCalls(page)).toHaveLength(0)
})
test('mac: the Model Manager offers MLX media instead of hiding the rails', async ({ page }) => {
@@ -226,12 +216,14 @@ test('mac: saving the HuggingFace token in Settings pushes it to Rust', async ({
await page.getByRole('button', { name: /^Save$/ }).click()
await expect(page.getByRole('button', { name: /Saved/i })).toBeVisible({ timeout: 10_000 })
- const token = await page.evaluate(() => (window as unknown as { __E2E_HF_TOKEN__?: string }).__E2E_HF_TOKEN__)
- expect(token).toBe('hf_e2e_probe')
+ expect(await hfToken(page)).toBe('hf_e2e_probe')
- const call = ((await mlxCalls(page)) as any[]).find((c) => c.cmd === 'set_hf_token')
- expect(call).toMatchObject({ present: true })
- expect(JSON.stringify(call)).not.toContain('hf_e2e_probe')
+ const call = requireCall(await mlxCalls(page), 'set_hf_token')
+ expect(call.present).toBe(true)
+ // Against the UNPARSED record: a leak in a field this file does not model
+ // would be invisible in the parsed projection, and the check would pass on
+ // nothing. `raw` is exactly what the page pushed.
+ expect(JSON.stringify(call.raw)).not.toContain('hf_e2e_probe')
})
test('mac: a stored token reaches Rust at boot, without opening Settings', async ({ page }) => {
@@ -250,9 +242,5 @@ test('mac: a stored token reaches Rust at boot, without opening Settings', async
await page.goto('/')
await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })
- await expect
- .poll(async () => page.evaluate(() => (window as unknown as { __E2E_HF_TOKEN__?: string }).__E2E_HF_TOKEN__), {
- timeout: 15_000,
- })
- .toBe('hf_boot_probe')
+ await expect.poll(() => hfToken(page), { timeout: 15_000 }).toBe('hf_boot_probe')
})
diff --git a/e2e/support/cloud-mock.ts b/e2e/support/cloud-mock.ts
index 76d2a52e..eeec00bc 100644
--- a/e2e/support/cloud-mock.ts
+++ b/e2e/support/cloud-mock.ts
@@ -1,4 +1,7 @@
import type { Page } from '@playwright/test'
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
/**
* Network mock for the LU Cloud e2e specs: intercepts the Supabase auth host
@@ -189,17 +192,54 @@ export async function routeCloud(page: Page, scenario: CloudScenario): Promise<v
}
/**
- * Pre-seed the persisted settings so the app boots straight into chat (no
+ * The version this build IS. `ReleaseNotesModal` imports package.json directly
+ * and compares against that string, so anything else here would rot at the
+ * next version bump — and rot silently, because the symptom is a modal, not an
+ * error. Read the same way tts-csp.spec.ts reads tauri.conf.json.
+ */
+const APP_VERSION: string = (
+ JSON.parse(
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json'), 'utf8'),
+ ) as { version: string }
+).version
+
+/**
+ * Pre-seed the persisted state so the app boots straight into chat (no
* onboarding walk) in LOCAL mode. The settingsStore merge() backfills every
* missing field from defaults, so the minimal shape is enough.
+ *
+ * TWO markers, not one, and the second is the one that used to be missing:
+ *
+ * `onboardingDone: true` with NO release-notes stamp is not "a user who has
+ * finished onboarding" — it is exactly the fingerprint of an UPGRADER, and
+ * that is a state the app deliberately reacts to. `shouldShowReleaseNotes`
+ * (stores/releaseNotesStore.ts) reads `lastNotesVersion === null` together
+ * with `onboardingDone === true` as "has not seen this version's notes yet"
+ * and opens the "What is new" sheet, which is a `fixed inset-0 z-[90]`
+ * backdrop over the whole app. Every click a spec then issues lands on the
+ * backdrop, so the specs did not fail on what they assert — they never got to
+ * assert it. The specs that walk the real onboarding wizard were unaffected,
+ * because finishing it stamps the version; only the ones that took this
+ * shortcut were hit. That is the whole difference between the green and the
+ * red half of this suite.
+ *
+ * So the stamp belongs here: it is not a workaround for the sheet, it is the
+ * rest of the state "onboarded on this build" actually consists of. A spec
+ * that wants to see the sheet simply does not call this helper.
*/
export async function seedOnboardingDone(page: Page): Promise<void> {
- await page.addInitScript(() => {
+ await page.addInitScript((version: string) => {
window.localStorage.setItem(
'chat-settings',
JSON.stringify({ state: { settings: { onboardingDone: true, appMode: 'local' }, _version: 10 }, version: 10 }),
)
- })
+ // Same key and shape zustand's persist writes for useReleaseNotesStore
+ // (no `version` option there, so the envelope version is 0).
+ window.localStorage.setItem(
+ 'lu_release_notes',
+ JSON.stringify({ state: { lastNotesVersion: version }, version: 0 }),
+ )
+ }, APP_VERSION)
}
/** The purple Cloud light-switch in the header (right cluster). */
@@ -207,6 +247,24 @@ export function cloudSwitch(page: Page) {
return page.getByRole('switch', { name: /^Cloud$/i })
}
+/**
+ * The same switch, reachable WHILE a modal is open.
+ *
+ * `ui/Modal` puts `inert` + `aria-hidden="true"` on the rest of the page for
+ * as long as a dialog is up (Modal.tsx, "(2) Hintergrund inert"), which is
+ * exactly what a dialog is supposed to do. The consequence for a spec is that
+ * every role-based query — `cloudSwitch()` included — finds NOTHING behind an
+ * open gate, and an assertion like "the switch stayed off" then fails with
+ * `element(s) not found` instead of telling you about the switch.
+ *
+ * This reads the SAME `aria-checked` attribute through a locator the dialog
+ * does not filter. It is not a weaker assertion, it is the same one asked in a
+ * way the dialog cannot swallow. Use `cloudSwitch()` whenever no modal is up.
+ */
+export function cloudSwitchBehindModal(page: Page) {
+ return page.locator('button[role="switch"][aria-label="Cloud"]')
+}
+
/** Sign in through the CloudGateModal that the header switch opens. The
* signed-out gate is a stepped flow: hero → plans → in-app sign-in. */
export async function signInViaGate(page: Page): Promise<void> {
diff --git a/e2e/support/recorded.ts b/e2e/support/recorded.ts
new file mode 100644
index 00000000..7b01ce96
--- /dev/null
+++ b/e2e/support/recorded.ts
@@ -0,0 +1,213 @@
+import type { Page } from '@playwright/test'
+
+/**
+ * Typed read-back for everything the in-page Tauri mock records.
+ *
+ * `support/tauri-mock.ts` runs inside the BROWSER and pushes plain objects onto
+ * `window.__E2E_*__`. What comes back through `page.evaluate` therefore crosses
+ * a serialization boundary: Node did not build those values and cannot know
+ * their shape. That is the same situation as a foreign HTTP body, so this file
+ * follows the same rule as `src/api/providers/wire.ts` — check before you
+ * claim. `isRecord` before a property read, `Array.isArray` before iterating,
+ * `typeof` before a string or number is handed on.
+ *
+ * The one rule this file adds on top: a recorded entry WITHOUT a string `cmd`
+ * is an error, not a value to drop. Every spec here filters on `cmd`, so a
+ * silently discarded record turns `expect(calls.filter(…))` into an assertion
+ * about the empty set — a green test that proves nothing. The mock has already
+ * produced exactly that bug once (`video_install_model` recorded `id:
+ * undefined` because the payload is nested under `args`; see the comment in
+ * tauri-mock.ts), which is why the parse is loud instead of forgiving.
+ *
+ * Parsed calls keep a reference to their untouched source record in `raw`.
+ * Assertions about what must NOT be in a call ("the token value is never
+ * echoed") have to run against what the page actually recorded — running them
+ * against the parsed projection would only test this parser.
+ */
+
+// ── Boundary primitives ────────────────────────────────────────
+
+/** True for a plain object we may index. Arrays and null are rejected. */
+export function isRecord(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
+}
+
+export function asString(v: unknown): string | undefined {
+ return typeof v === 'string' ? v : undefined
+}
+
+export function asNumber(v: unknown): number | undefined {
+ return typeof v === 'number' && Number.isFinite(v) ? v : undefined
+}
+
+export function asBoolean(v: unknown): boolean | undefined {
+ return typeof v === 'boolean' ? v : undefined
+}
+
+/** Array of strings, or [] — the shape of the plain URL buckets. */
+export function asStringArray(v: unknown): string[] {
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
+}
+
+// ── The recorded envelope ──────────────────────────────────────
+
+/** Anything `record()` in the mock pushed: a plain object naming a command. */
+type CommandRecord = Record<string, unknown> & { cmd: string }
+
+function isCommandRecord(v: unknown): v is CommandRecord {
+ return isRecord(v) && typeof v.cmd === 'string'
+}
+
+/**
+ * Validate one recorded bucket. An absent bucket is legitimately empty (the
+ * mock only creates it on first write); anything else that is not an array of
+ * `{ cmd: string, … }` means the mock and this parser have drifted apart, and
+ * the spec must hear about that rather than silently measure nothing.
+ */
+function commandRecords(raw: unknown, bucket: string): CommandRecord[] {
+ if (raw === undefined || raw === null) return []
+ if (!Array.isArray(raw)) {
+ throw new Error(`${bucket}: expected an array of recorded calls, got ${JSON.stringify(raw)}`)
+ }
+ return raw.map((entry, i) => {
+ if (!isCommandRecord(entry)) {
+ throw new Error(`${bucket}[${i}]: recorded entry has no string \`cmd\`: ${JSON.stringify(entry)}`)
+ }
+ return entry
+ })
+}
+
+// ── MLX media surface (commands/mlx.rs + video.rs) ─────────────
+
+/**
+ * One entry of `__E2E_MLX_CALLS__`. Only `cmd` is guaranteed — which fields
+ * ride along depends on the command, and a field the mock did not record must
+ * read as `undefined` here rather than as a wrong value.
+ */
+export interface RecordedMlxCall {
+ /** The record exactly as the page pushed it. */
+ readonly raw: Readonly<Record<string, unknown>>
+ cmd: string
+ /** Model id — `mlx_image_install_model`, `video_install_model`, … */
+ id?: string
+ /** `mlx_generate` / `video_generate`. */
+ prompt?: string
+ model?: string
+ steps?: number
+ seed?: number
+ width?: number
+ height?: number
+ seconds?: number
+ /** `set_hf_token` reports only PRESENCE, never the token value. */
+ present?: boolean
+}
+
+function parseMlxCall(e: CommandRecord): RecordedMlxCall {
+ return {
+ raw: e,
+ cmd: e.cmd,
+ id: asString(e.id),
+ prompt: asString(e.prompt),
+ model: asString(e.model),
+ steps: asNumber(e.steps),
+ seed: asNumber(e.seed),
+ width: asNumber(e.width),
+ height: asNumber(e.height),
+ seconds: asNumber(e.seconds),
+ present: asBoolean(e.present),
+ }
+}
+
+/** Everything the page recorded through the mocked MLX / video commands. */
+export async function mlxCalls(page: Page): Promise<RecordedMlxCall[]> {
+ const raw = await page.evaluate(
+ () => (window as unknown as { __E2E_MLX_CALLS__?: unknown }).__E2E_MLX_CALLS__,
+ )
+ return commandRecords(raw, '__E2E_MLX_CALLS__').map(parseMlxCall)
+}
+
+// ── Agent file/shell bridge ────────────────────────────────────
+
+/** One entry of `__E2E_TOOL_CALLS__` (fs_read/fs_write/fs_list/shell_execute). */
+export interface RecordedToolCall {
+ readonly raw: Readonly<Record<string, unknown>>
+ cmd: string
+ path?: string
+ /** `shell_execute` — the command line the agent asked Rust to run. */
+ command?: string
+ /** `shell_execute` — the timeout the caller injected, in milliseconds. */
+ timeout?: number
+}
+
+function parseToolCall(e: CommandRecord): RecordedToolCall {
+ return {
+ raw: e,
+ cmd: e.cmd,
+ path: asString(e.path),
+ command: asString(e.command),
+ timeout: asNumber(e.timeout),
+ }
+}
+
+/** Every file/shell tool call the agent loop pushed through the Tauri bridge. */
+export async function toolCalls(page: Page): Promise<RecordedToolCall[]> {
+ const raw = await page.evaluate(
+ () => (window as unknown as { __E2E_TOOL_CALLS__?: unknown }).__E2E_TOOL_CALLS__,
+ )
+ return commandRecords(raw, '__E2E_TOOL_CALLS__').map(parseToolCall)
+}
+
+// ── ComfyUI probe ──────────────────────────────────────────────
+
+/** One entry of `__E2E_COMFY_CALLS__`. The mock records the bare command. */
+export interface RecordedComfyCall {
+ readonly raw: Readonly<Record<string, unknown>>
+ cmd: string
+}
+
+/**
+ * Every ComfyUI probe the page attempted. The Mac specs assert this stays
+ * empty, so the parse must be strict: a malformed entry that got dropped would
+ * make "no ComfyUI call happened" true for the wrong reason.
+ */
+export async function comfyCalls(page: Page): Promise<RecordedComfyCall[]> {
+ const raw = await page.evaluate(
+ () => (window as unknown as { __E2E_COMFY_CALLS__?: unknown }).__E2E_COMFY_CALLS__,
+ )
+ return commandRecords(raw, '__E2E_COMFY_CALLS__').map((e) => ({ raw: e, cmd: e.cmd }))
+}
+
+// ── Plain buckets ──────────────────────────────────────────────
+
+/** Every URL that went through `proxy_localhost`, in call order. */
+export async function proxyUrls(page: Page): Promise<string[]> {
+ const raw = await page.evaluate(
+ () => (window as unknown as { __E2E_PROXY_URLS__?: unknown }).__E2E_PROXY_URLS__,
+ )
+ return asStringArray(raw)
+}
+
+/** The HuggingFace token Rust currently holds — `undefined` when it holds none. */
+export async function hfToken(page: Page): Promise<string | undefined> {
+ const raw = await page.evaluate(
+ () => (window as unknown as { __E2E_HF_TOKEN__?: unknown }).__E2E_HF_TOKEN__,
+ )
+ return asString(raw)
+}
+
+// ── Lookup ─────────────────────────────────────────────────────
+
+/**
+ * The first recorded call for `cmd`, or a failure that names what was actually
+ * recorded. `calls.find(…)!.field` reads the same until it does not, and then
+ * reports "cannot read properties of undefined" — which says nothing about
+ * which command never arrived.
+ */
+export function requireCall<T extends { cmd: string }>(calls: readonly T[], cmd: string): T {
+ const hit = calls.find((c) => c.cmd === cmd)
+ if (!hit) {
+ const seen = calls.map((c) => c.cmd).join(', ')
+ throw new Error(`no \`${cmd}\` call was recorded — recorded instead: ${seen || '(nothing)'}`)
+ }
+ return hit
+}