Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
test(e2e): cover the chat critical path with a mock provider (#8981)
James Dam9c453ef2bc4c
diff --git a/e2e/README.md b/e2e/README.mdindex e8c035a68..24007e5b8 100644--- a/e2e/README.md+++ b/e2e/README.md@@ -218,6 +218,21 @@ Because the profile is always fresh, **every run is a first launch** — noproviders are configured, so `/` renders `SetupScreen`. The suite asserts thatrather than working around it.+A first launch used to **download**: Jan fetches its embedding model+`sentence-transformer-mini` (~45MB) on a profile it has not bootstrapped before,+and announces it with a toast that mounts over the header at a moment set by+network speed. `wdio.conf.ts` now pre-seeds the one-shot flag that suppresses+that bootstrap, so a run neither downloads it nor shows the toast — a kept+profile is ~112KB rather than ~45MB. Set `JAN_E2E_EMBEDDER_DOWNLOAD=1` to get+the real bootstrap back, which is what a spec *about* the embedder needs.++That is the one large download removed, not every network call: the app still+fetches small metadata such as the model catalogue, and no attempt has been made+to verify the suite on a machine with no network at all. What it buys is+determinism — the toast was landing on whatever a spec was clicking, and see+[the analytics prompt section](#the-analytics-prompt-covers-the-composer) for+what that cost.+## Writing specs`browser.tauri.execute()` is unavailable: it needs `window.__TAURI__`, which@@ -225,7 +240,7 @@ requires `withGlobalTauri: true` in `tauri.conf.json`. That would expose thefull Tauri API to anything running in the webview, so it stays off. Assertthrough the UI instead — which is closer to what users actually see.-Navigate with the `goto()` helper in `specs/smoke.e2e.ts` rather than+Navigate with the `goto()` helper in `helpers/navigation.ts` rather than`browser.url()`: the Tauri asset protocol has no SPA fallback for deep paths, soa hard navigation 404s. The helper pushes history (which TanStack patches tonotify its own subscribers) and carries `__TSR_index` forward so back/forward@@ -239,3 +254,234 @@ Prefer `data-testid` selectors — around ten shipped components already carrythem. Note that a `grep` for `data-testid` turns up many more hits in`__tests__` mocks than in real components, so check whether the one you wantactually exists before assuming it does.++Before asserting that something is **absent** from disk, assert it was there+first. An "is it gone?" check against a path that was never written passes+whatever the code does, and it fails silently rather than loudly — nothing about+the green run says the assertion proved nothing. `specs/chat.e2e.ts` brackets its+delete this way: it waits for the thread directory to exist, deletes, then waits+for it to go away.++The same shape applies in time rather than on disk: when you are asserting on+something produced by a **fire-and-forget background request, assert it before+doing anything that cancels it**. The generated thread title is the live example,+and it is product behaviour rather than a harness quirk. The summarizer runs from+`onFinish` only on a refresh tick — the first assistant message, then every fourth+(`web-app/src/routes/threads/$threadId.tsx:632-635`,+`TITLE_REFRESH_EVERY_N_ASSISTANT_MESSAGES = 4`) — and sending the next message+aborts whatever title request is in flight (same file, line 957;+`lib/thread-title-summarizer.ts` swallows the `AbortError` and returns null). With+two assistant messages there is no second attempt, so a spec that sends again+before the title lands leaves the row reading "New Thread" permanently, and no+retry recovers it. `specs/chat.e2e.ts` asserts the title at the end of its first+test, while the thread has exactly one reply.++### The embedded driver has no real input++`tauri-plugin-wdio-webdriver` synthesizes every interaction in JavaScript. From+`src/platform/executor.rs` (v1.4):++- `dispatch_pointer_event()` builds a `MouseEvent` (`mousedown`/`mouseup`/+ `mousemove`, plus a `click` synthesized after a same-spot down+up) and+ dispatches it at `document.elementFromPoint(x, y)`. It never produces a+ `PointerEvent`.+- `click_element()` — what `elementClick`, and so `elem.click()`, maps to — is+ `el.scrollIntoView(); el.click(); el.focus()`.+- `send_keys_to_element()` focuses the element and then dispatches synthesized+ `keydown`/`keyup` at `document.activeElement`.++Three consequences, all of which read as a failure about the wrong thing:++- **CSS `:hover` never applies.** A synthesized `MouseEvent` does not move the+ hover state, so `moveTo()` cannot reveal hover-only UI, and+ `browser.action('pointer')` cannot either.+- **Radix components that open on `pointerdown` never open from a click.**+ `DropdownMenuTrigger` is the one in Jan's sidebar. `DialogTrigger` and+ `PopoverTrigger` use `onClick` and are fine.+- **The workaround for both is the keyboard**, and it is not a hack — it is the+ route a keyboard user takes. `elementClick` leaves the element focused, which+ both satisfies a `group-focus-within:opacity-100` rule and gives+ `browser.keys('Enter')` a target; Radix's trigger opens on Enter.+ `specs/chat.e2e.ts` does exactly this for the thread overflow menu and carries+ the long-form comment.++**Do not use `waitForClickable()` in this suite.** WDIO's clickability check+includes an `elementFromPoint` test; this driver's click does not.+`click_element()` goes straight through anything painted on top, so the precheck+can only ever reject clicks that would have succeeded — and on a first launch+there is plenty painted on top (the analytics consent panel over the composer,+the download toast over the header; both below). The failure mode is a 30-60s+timeout naming an element that is fine.++Use `clickWhenReady(selector)` from `specs/chat.e2e.ts` instead:+`waitForDisplayed()` + `waitForEnabled()` + `click()`. Displayed and enabled are+still worth waiting for, because they are real states this app uses — Add Model+stays disabled until the model-id field is non-empty, and the send button is+*replaced* outright by a stop button while a reply streams, so waiting for it to+exist is the streaming barrier.++`opacity: 0` is **not** one of the differences, so `clickWhenReady()` is no help+there: `waitForDisplayed()` runs `checkVisibility({opacityProperty: true})`+browser-side and rejects a fully transparent element exactly as+`waitForClickable()` would. Anything revealed only on hover or focus needs+`waitForExist()` instead — which is what the third test in `specs/chat.e2e.ts`+does for the thread overflow menu, clicking it to focus it before the+`opacity-0` rule stops applying.++### The analytics prompt covers the composer++Once a provider makes onboarding complete, `PromptAnalytic`+(`web-app/src/containers/analytics/`) floats the consent panel at+`fixed bottom-4 right-4 z-50` — directly over the chat composer's send button.+The button stays present, enabled and non-zero-sized, so it fails only+WebDriver's elementFromPoint check and reports as "still not clickable", which+names an element that is fine.++`specs/chat.e2e.ts` dismisses it in `before()` via+`[data-testid="analytic-deny"]` — deny rather than allow, because a test run has+no business opting into telemetry. Any new spec that reaches a post-onboarding+state has to do the same.++It is not the only thing that floats. The embedding-model download from+[Isolation](#isolation) completes at a different moment every run depending on+network speed, and when it lands a sonner toast (*Download Complete — Model+"sentence-transformer-mini" downloaded and verified successfully*) mounts+top-right, over the header of whatever page is open. Anything that depends on the+header being unobstructed is therefore a coin flip. This produced three+consecutive red runs, with `[data-testid="add-provider-trigger"]` reported as+"still not clickable" while being present, enabled, visible and 132x32 — which is+the `waitForClickable()` ban above, in the wild.++A click that arrives in that window has also been seen to simply not take. Once:+the click on `[data-testid="add-provider-trigger"]` returned and the dialog never+appeared, while the toast was landing. It has not reproduced, and **why** it did+not register is not known. The likeliest explanation is that `el.click()` went to+a node React had just replaced, but that is unverified — the Toaster is a sibling+of the page in `routes/__root.tsx`, and `routes/settings/providers/index.tsx`+does not remount its header when the model list changes, so nothing observed says+a mounting toast re-keys the trigger.++Opening a dialog therefore goes through+`openDialog(triggerSelector, dialogSelector)` in `specs/chat.e2e.ts`, which+re-clicks until the dialog is displayed — kept because the retry is cheap and the+guard makes it safe, not because the cause is understood. The guard is the+load-bearing part and it *is* verified: Radix mirrors open state onto the trigger+as `data-state="open"`, and the trigger's `onClick` is a **toggle**, so a blind+second click would shut a dialog that had in fact opened. The helper skips the+click whenever the trigger already reads `data-state="open"`.++### Per-command focus recovery is switched off++`@wdio/tauri-service`'s `beforeCommand` hook calls `ensureActiveWindowFocus()`+for `getTitle`/`findElement`/`findElements`/`$`/`$$`/`elementClick`, which asks+the app for its window states over `browser.tauri.execute()`. That needs+`window.__wdio_original_core__`, absent here for the same reason+`browser.tauri.execute()` is unavailable to specs — `withGlobalTauri` is off — so+the probe cannot succeed. It times out after 5s **per command**, logging+`Failed to get window states` each time.++`wdio.conf.ts`'s `before` hook turns it off by doing+`browser.switchToWindow(await browser.getWindowHandle())`: `afterCommand` treats+a successful non-internal `switchToWindow` as the user taking charge of window+selection and suppresses the probe for the rest of the session, so switching to+the handle we are already on is a no-op that disables it. Jan runs a single+window under test, so there is nothing to recover. The numbers are the spec+reporter's own per-file timings on macOS: `smoke.e2e.ts` went from 40.3s to+~70ms for the same three assertions, and `chat.e2e.ts` from dying on the Mocha+hook timeout to a few seconds. The work did not get faster — roughly 5s per+element lookup stopped being spent.++If a future spec is mysteriously slow and the log carries+`Failed to get window states`, that hook is what to check.++### Shared helpers++`helpers/` holds the pieces more than one spec needs:++- `navigation.ts` — `goto()`, described above.+- `paths.ts` — two directories, and they are not the same one. Asserting against+ a real on-disk path is what makes a filesystem check meaningful; asserting+ against `isolationEnv()` would only restate what the harness injected.+ - `janDataDir(testHome)` — the directory the Rust side resolves for app data+ inside the throwaway profile (`data_dir()/Jan`). `settings.json` lives here.+ - `janUserDataDir(testHome)` — `janDataDir()/data`, which is what+ `settings.json`'s `data_folder` points at and what the Rust thread code+ takes as its `data_folder` argument (`core/threads/utils.rs`,+ `get_thread_dir`). Threads are at `janUserDataDir()/threads/<id>`.++ Picking the wrong one of those is quiet rather than loud, which is why it is+ worth stating: a path one segment short simply never exists, and an "is it+ gone?" assertion against it passes for the wrong reason.+- `mock-openai.ts` — see below.++### Talking to a model without a model++`specs/chat.e2e.ts` covers the loop the product lives or dies by — send, stream a+reply, keep it across a reload, delete it — against a mock OpenAI-compatible+server on loopback rather than a real one.++`startMockOpenAI()` binds port 0 on `127.0.0.1` and answers three things, all of+which the app genuinely asks for:++- `GET /v1/models` — `useProviderModels` → `fetchModelsFromProvider`+ (`services/providers/tauri.ts`) fetches `${base_url}/models` as soon as the Add+ Model dialog opens. Without it that dialog renders an error state.+- `POST /v1/chat/completions` with `stream: true` — SSE, echoing+ `MOCK_REPLY_PREFIX` plus the last user message back across several chunks.+ Echoing proves the typed text reached the server and returned; several chunks+ prove the webview assembles a stream rather than rendering one blob.+- the same path with a falsy `stream` — the thread-title summarizer, which goes+ through `generateText`. It answers a fixed `MOCK_TITLE` so the sidebar+ assertion is deterministic.++This works from Node because Jan issues those requests from Rust+(`getRuntimeFetch()` → `tauri-plugin-http`), so the server sees an ordinary HTTP+client: no CORS, no preflight, and the capability set already allows+`http://*:*`. The provider is registered through the real Add Provider and Add+Model dialogs, so the configuration path is covered too.++Start the server in `before()` and close it in `after()` — an open listener keeps+the worker's event loop alive and the run never exits.++What this deliberately does not cover is llama.cpp. A real local model means a+multi-gigabyte download, minutes per run, and different behaviour on every+backend; it needs its own platform-specific test rather than a place in the+critical-path suite.++What the mock removes is the *LLM* download from the chat path, not every+download. The app still fetches its `sentence-transformer-mini` embedding model+on a profile that has not been bootstrapped, which the harness now seeds around+— see [Isolation](#isolation).++### Spec order is maintained by hand++`specs` in `wdio.conf.ts` is an explicit array, not a glob, because state leaks+forwards between spec files: `smoke.e2e.ts` asserts the first-run setup wizard+and `chat.e2e.ts` configures a provider, which under an alphabetically sorted+glob ran first and broke it.++It leaks further than a shared profile would explain. The embedded provider+spawns **one** app in the launcher's `onPrepare` and every spec file drives that+same process over its own WebDriver session — the run log carries a single+`Tauri app spawned (PID: …)` line, not one per file. So a later spec inherits+not just what an earlier one wrote to disk but the live webview: its route, its+zustand stores, and any dialog left open. Only an explicit `browser.refresh()`+clears the in-memory half, and `goto()` does not.++A new spec therefore has to be added to that array, and it is worth thinking+about where: a spec that needs a pristine profile belongs before anything that+configures the app.++### A green run still logs errors++Both spec files leave `no such element` and `stale element reference` lines in+the wdio log even when every test passes — on a two-run Linux check, 14 and 23+of them respectively; on Windows, 53. They are `INFO webdriver: RESULT`+responses, not failures: `waitForDisplayed()`, `waitUntil()` and `openDialog()`+all work by polling, so every attempt before the one that succeeds is logged as+an error the client then swallows. React swapping a node under a held reference+produces the stale ones.++The consequence is that grepping a run for `error` tells you nothing. Read the+`✓`/`✗` lines and the `Spec Files:` summary instead, and treat the exit code as+the verdict.diff --git a/e2e/helpers/mock-openai.ts b/e2e/helpers/mock-openai.tsnew file mode 100644index 000000000..2088acb82--- /dev/null+++ b/e2e/helpers/mock-openai.ts@@ -0,0 +1,264 @@+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import { AddressInfo } from 'node:net'++/**+ * A minimal OpenAI-compatible server, so the chat spec can exercise the real+ * send/stream/persist loop without a real model.+ *+ * The alternative -- driving llamacpp -- means a multi-gigabyte download, minutes+ * per run, and a different backend on every architecture. This is deterministic,+ * takes milliseconds, and is byte-identical on macOS, Linux and both Windows+ * targets. It deliberately does NOT cover llamacpp; that needs its own+ * platform-specific test.+ *+ * It works from Node because the request is put on the wire by Rust rather than+ * by the webview's own network stack -- the call is made from webview JS, but+ * getRuntimeFetch() hands it tauri-plugin-http's fetch+ * (web-app/src/lib/model-factory.ts), and providers/tauri.ts fetches the model+ * list the same way. So this sees an ordinary HTTP client -- no CORS, no+ * preflight -- and the capability set already allows http://*:*.+ *+ * The permissive CORS headers and the OPTIONS branch below are therefore not+ * needed by the suite. They are there so that pointing a browser-hosted dev+ * build at this server also works, which costs three headers and saves the+ * confusion of a preflight failing against a server that looks fine from Tauri.+ */++/** The model id the spec types into the Add Model combobox. */+export const MOCK_MODEL_ID = 'jan-e2e-mock'++/**+ * Prefixed onto the echoed prompt. The echo is the point: asserting the reply+ * contains prefix + the text that was typed proves the prompt travelled all the+ * way to the server and the response travelled all the way back, rather than+ * just proving that *some* text rendered.+ */+export const MOCK_REPLY_PREFIX = 'mock reply to: '++/**+ * What the non-streaming branch answers, which is the thread-title summarizer.+ * Plain ASCII words on purpose: cleanTitle()+ * (web-app/src/lib/thread-title-summarizer.ts) strips everything outside+ * [\p{L}\p{N}\s], caps at 10 words, and returns null under 2 characters -- so+ * punctuation here would silently change what the sidebar shows.+ */+export const MOCK_TITLE = 'Mock Thread Title'++export type MockOpenAI = {+ /** Feed this to the Add Provider dialog verbatim. */+ baseUrl: string+ close: () => Promise<void>+}++type ChatMessage = {+ role?: string+ content?: unknown+}++/**+ * The last user turn, as plain text.+ *+ * `content` is a string on the simple path but an array of typed parts once the+ * AI SDK has anything structured to send, so handle both rather than assuming.+ */+function lastUserText(messages: ChatMessage[]): string {+ const lastUser = [...messages].reverse().find((m) => m.role === 'user')+ const content = lastUser?.content+ if (typeof content === 'string') return content+ if (Array.isArray(content)) {+ return content+ .map((part) =>+ part && typeof part === 'object' && 'text' in part+ ? String((part as { text: unknown }).text)+ : ''+ )+ .join('')+ }+ return ''+}++function readBody(req: IncomingMessage): Promise<string> {+ return new Promise((resolve, reject) => {+ let body = ''+ req.setEncoding('utf8')+ req.on('data', (chunk) => (body += chunk))+ req.on('end', () => resolve(body))+ req.on('error', reject)+ })+}++function sendJson(res: ServerResponse, status: number, payload: unknown) {+ const body = JSON.stringify(payload)+ res.writeHead(status, {+ 'Content-Type': 'application/json',+ 'Content-Length': Buffer.byteLength(body),+ 'Access-Control-Allow-Origin': '*',+ })+ res.end(body)+}++const completionId = 'chatcmpl-jan-e2e'++/**+ * Stream the echo back as SSE, in several chunks.+ *+ * Several and not one: a single blob would pass even if the webview only ever+ * rendered a whole response, which is precisely the part of the pipeline worth+ * covering. The trailing usage-only chunk is what OpenAI emits under+ * stream_options.include_usage, which model-factory.ts sets (includeUsage: true).+ */+function streamCompletion(res: ServerResponse, reply: string) {+ res.writeHead(200, {+ 'Content-Type': 'text/event-stream',+ 'Cache-Control': 'no-cache',+ Connection: 'keep-alive',+ 'Access-Control-Allow-Origin': '*',+ })++ const created = Math.floor(Date.now() / 1000)+ const chunk = (delta: Record<string, unknown>, finish: string | null) =>+ res.write(+ `data: ${JSON.stringify({+ id: completionId,+ object: 'chat.completion.chunk',+ created,+ model: MOCK_MODEL_ID,+ choices: [{ index: 0, delta, finish_reason: finish }],+ })}\n\n`+ )++ chunk({ role: 'assistant', content: '' }, null)+ // Words, not characters: enough pieces to be a real stream, few enough to keep+ // the transcript readable when a run is being debugged with logLevel debug.+ for (const piece of reply.match(/\S+\s*/g) ?? [reply]) {+ chunk({ content: piece }, null)+ }+ chunk({}, 'stop')++ res.write(+ `data: ${JSON.stringify({+ id: completionId,+ object: 'chat.completion.chunk',+ created,+ model: MOCK_MODEL_ID,+ choices: [],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ })}\n\n`+ )+ res.write('data: [DONE]\n\n')+ res.end()+}++async function handle(req: IncomingMessage, res: ServerResponse) {+ const url = req.url ?? '/'++ if (req.method === 'OPTIONS') {+ res.writeHead(204, {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Headers': '*',+ 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',+ })+ res.end()+ return+ }++ // Asked for by useProviderModels -> providers/tauri.ts fetchModelsFromProvider,+ // which GETs `${base_url}/models` the moment the Add Model dialog opens. Answer+ // it or that dialog renders an error state instead of a model list.+ if (req.method === 'GET' && url.startsWith('/v1/models')) {+ sendJson(res, 200, {+ object: 'list',+ data: [+ {+ id: MOCK_MODEL_ID,+ object: 'model',+ created: Math.floor(Date.now() / 1000),+ owned_by: 'jan-e2e',+ },+ ],+ })+ return+ }++ if (req.method === 'POST' && url.startsWith('/v1/chat/completions')) {+ const raw = await readBody(req)+ let body: { stream?: boolean; messages?: ChatMessage[] } = {}+ try {+ body = JSON.parse(raw)+ } catch {+ sendJson(res, 400, { error: { message: `unparseable body: ${raw}` } })+ return+ }++ // Chat always streams (streamText). The only non-streaming caller is the+ // thread-title summarizer, which goes through generateText -- so `stream`+ // is what tells the two apart, and the title must be fixed for the sidebar+ // assertion to be deterministic.+ if (!body.stream) {+ sendJson(res, 200, {+ id: completionId,+ object: 'chat.completion',+ created: Math.floor(Date.now() / 1000),+ model: MOCK_MODEL_ID,+ choices: [+ {+ index: 0,+ message: { role: 'assistant', content: MOCK_TITLE },+ finish_reason: 'stop',+ },+ ],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ })+ return+ }++ streamCompletion(res, MOCK_REPLY_PREFIX + lastUserText(body.messages ?? []))+ return+ }++ // Loud on purpose. A silent 404 here surfaces much later as an empty message+ // bubble, and the path is the only clue about which call was missed.+ sendJson(res, 404, {+ error: { message: `jan e2e mock has no route for ${req.method} ${url}` },+ })+}++/**+ * Start the mock on a free loopback port.+ *+ * Port 0 rather than a fixed one so two runs -- or a run alongside a developer's+ * own server -- cannot collide; the caller reads the real port back off the+ * returned baseUrl.+ *+ * Start it in the spec's before() and close it in after(): an open listener keeps+ * the wdio worker's event loop alive and the run never exits.+ */+export function startMockOpenAI(): Promise<MockOpenAI> {+ const server: Server = createServer((req, res) => {+ handle(req, res).catch((error) => {+ if (res.headersSent) {+ res.end()+ return+ }+ sendJson(res, 500, { error: { message: String(error) } })+ })+ })++ return new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const { port } = server.address() as AddressInfo+ resolve({+ baseUrl: `http://127.0.0.1:${port}/v1`,+ close: () =>+ new Promise<void>((done, fail) => {+ // closeAllConnections() first: close() only stops new connections and+ // waits for live ones, and tauri-plugin-http keeps its sockets alive,+ // so without this the callback never fires and the worker hangs.+ server.closeAllConnections()+ server.close((error) => (error ? fail(error) : done()))+ }),+ })+ })+ })+}diff --git a/e2e/helpers/navigation.ts b/e2e/helpers/navigation.tsnew file mode 100644index 000000000..97fdcb5a0--- /dev/null+++ b/e2e/helpers/navigation.ts@@ -0,0 +1,32 @@+import { browser } from '@wdio/globals'++/**+ * Navigate the TanStack router client-side.+ *+ * A hard `browser.url()` would ask the Tauri asset protocol for a deep path it+ * has no SPA fallback for, and 404. TanStack patches `history.pushState` to+ * notify its own subscribers (@tanstack/history), so pushing is enough on its+ * own -- no synthetic popstate needed.+ *+ * The state object matters: TanStack tracks position in `__TSR_index` and+ * computes back/forward deltas by subtracting it. Pushing a bare `{}` wipes+ * that key and turns later deltas into NaN, so carry the index forward.+ */+export async function goto(path: string) {+ await browser.execute((target: string) => {+ const previous = (window.history.state ?? {}) as Record<string, unknown>+ const index =+ typeof previous.__TSR_index === 'number' ? previous.__TSR_index + 1 : 0+ const key = Math.random().toString(36).slice(2, 10)+ window.history.pushState(+ { ...previous, __TSR_index: index, key, __TSR_key: key },+ '',+ target+ )+ }, path)++ await browser.waitUntil(+ async () => (await browser.execute(() => window.location.pathname)) === path,+ { timeout: 20_000, timeoutMsg: `never navigated to ${path}` }+ )+}diff --git a/e2e/helpers/paths.ts b/e2e/helpers/paths.tsnew file mode 100644index 000000000..98e6c5254--- /dev/null+++ b/e2e/helpers/paths.ts@@ -0,0 +1,33 @@+import { join } from 'node:path'++/**+ * The directory the Rust side resolves for app data, inside a throwaway profile.+ *+ * Mirrors `app_data_dir_with_fallback()` -> `data_dir()/Jan`+ * (src-tauri/src/core/app/commands.rs, core/app/paths.rs). Kept as a plain+ * function of the test HOME so specs can assert against real on-disk paths+ * rather than against the environment the harness itself injected.+ */+export function janDataDir(testHome: string) {+ return process.platform === 'darwin'+ ? join(testHome, 'Library/Application Support/Jan')+ : process.platform === 'win32'+ ? join(testHome, 'AppData/Roaming/Jan')+ : join(testHome, '.local/share/Jan')+}++/**+ * The folder Jan stores user data in -- threads, and everything else the Rust+ * side writes per-thread.+ *+ * Not the same directory as janDataDir(): that one holds `settings.json`, and+ * `settings.json` in turn points `data_folder` at this subdirectory. The Rust+ * thread code takes that folder as an argument+ * (core/threads/utils.rs get_thread_dir), so a spec checking for a thread on+ * disk has to go through the extra `data` segment or it asserts against a path+ * that never existed -- which passes for the wrong reason when the assertion is+ * that something is absent.+ */+export function janUserDataDir(testHome: string) {+ return join(janDataDir(testHome), 'data')+}diff --git a/e2e/specs/chat.e2e.ts b/e2e/specs/chat.e2e.tsnew file mode 100644index 000000000..1272e45e1--- /dev/null+++ b/e2e/specs/chat.e2e.ts@@ -0,0 +1,491 @@+import { existsSync } from 'node:fs'+import { join } from 'node:path'++import { browser, expect, $, $$ } from '@wdio/globals'++import {+ MOCK_MODEL_ID,+ MOCK_REPLY_PREFIX,+ MOCK_TITLE,+ startMockOpenAI,+ type MockOpenAI,+} from '../helpers/mock-openai.js'+import { goto } from '../helpers/navigation.js'+import { janUserDataDir } from '../helpers/paths.js'++// The worker inherits this from the launcher; see wdio.conf.ts. Read from the+// environment rather than importing the config, so the spec does not trigger a+// second evaluation of a module with top-level side effects.+const testHome = process.env.JAN_E2E_HOME!++const PROVIDER_NAME = 'e2e-mock-provider'++// Deliberately unalike, and unalike in their first word: when the echo assertion+// fails, the diff has to say which turn produced the text without being read+// twice.+const FIRST_PROMPT = 'first turn ping from the e2e suite'+const SECOND_PROMPT = 'second turn pong from the e2e suite'++// data-message-role is on the same node as the testid (MessageItem.tsx:556-557).+// System notes take an early return above it and render neither attribute, so+// counting these counts real conversation turns and nothing else.+const USER_MESSAGES = '[data-testid="message-item"][data-message-role="user"]'+const ASSISTANT_MESSAGES =+ '[data-testid="message-item"][data-message-role="assistant"]'++/**+ * The manual QA checklist's critical path: configure a provider, send, stream a+ * reply, send again, survive a reload, delete the thread.+ *+ * The three tests share one thread and run in order -- test 1 creates it and+ * captures `threadId`, tests 2 and 3 address it. Mocha runs them in declaration+ * order, so this is stated rather than defended against; splitting them into+ * independent tests would mean configuring a provider and streaming two replies+ * three times over to assert the same thing.+ */+describe('chat critical path', () => {+ let mock: MockOpenAI++ // Written by test 1, read by tests 2 and 3.+ let threadId = ''++ before(async () => {+ mock = await startMockOpenAI()++ await $('#root').waitForExist({ timeout: 60_000 })++ // Configure through the real dialogs rather than by writing settings.json+ // behind the app's back: provider creation is itself on the checklist, and a+ // hand-written file would drift silently the next time the shape changes.+ await goto('/settings/providers')++ await openDialog(+ '[data-testid="add-provider-trigger"]',+ '[data-testid="add-provider-dialog"]'+ )++ // setValue and not addValue throughout: addValue appends, so anything that+ // retries a step leaves a field holding its value twice over.+ await $('[data-testid="provider-name-input"]').setValue(PROVIDER_NAME)+ // Satisfies AddProviderDialog's /^https?:\/\/[^\s]+$/i check. The port is+ // whatever the mock got from binding port 0, hence reading it off the+ // handle rather than hardcoding one.+ await $('[data-testid="provider-base-url-input"]').setValue(mock.baseUrl)+ // Required by the dialog, ignored by the mock -- which is the point: this+ // suite must not need a real credential to reach a usable provider.+ await $('[data-testid="provider-api-key-input"]').setValue(+ 'e2e-not-a-real-key'+ )+ // The API type radio is left alone on purpose: it defaults to `openai`,+ // which is the dialect the mock speaks.++ await $('[data-testid="add-provider-submit"]').click()++ // createProvider navigates on a setTimeout(..., 0)+ // (routes/settings/providers/index.tsx:42-87), so the click returns before+ // the route changes. Wait for the destination instead of assuming arrival --+ // otherwise a rejected field shows up below as a missing add-model trigger.+ await browser.waitUntil(+ async () =>+ (await browser.execute(() => window.location.pathname)) ===+ `/settings/providers/${PROVIDER_NAME}`,+ {+ timeout: 30_000,+ timeoutMsg:+ `Add Provider never landed on /settings/providers/${PROVIDER_NAME}. ` ++ 'Either the dialog rejected a field (name, base URL and API key are ' ++ 'all required, and the URL must match ^https?://\\S+$), or ' ++ 'createProvider bailed out on the duplicate-name toast.',+ }+ )++ await openDialog(+ '[data-testid="add-model-trigger"]',+ '[data-testid="add-model-dialog"]'+ )++ // The typed text *is* the model id. handleInputChange (ModelCombobox.tsx:345)+ // calls onChange on every keystroke, so there is nothing to confirm with+ // Enter and add-model-submit un-disables the moment the field is non-empty.+ await $('[data-testid="model-combobox-input"]').setValue(MOCK_MODEL_ID)++ // Typing also opened the suggestion list, which Radix portals to+ // document.body, outside the dialog. It does sit over the submit button,+ // but that is not why this line is here: elementClick is el.click() in JS+ // and goes straight through anything painted on top, which is the whole+ // reason clickWhenReady() below exists. The reason to close it is that an+ // open combobox list is a live keyboard handler -- it takes Enter, Escape+ // and the arrow keys -- so leaving it up puts a receiver for every+ // subsequent keypress between the spec and the dialog.+ //+ // One Escape closes exactly that list and nothing else, which is the least+ // obvious line in this file. The combobox's own 'Escape' case closes itself+ // and calls stopPropagation() (ModelCombobox.tsx:216-221), and AddModel.tsx's+ // onEscapeKeyDown guard preventDefault()s while isComboboxOpen, so Radix does+ // not take the same keypress as a dismiss of the dialog.+ await browser.keys('Escape')++ await clickWhenReady('[data-testid="add-model-submit"]')++ // Closing the dialog is handleSubmit's last act (AddModel.tsx), so its+ // disappearance is the signal that the model was written onto the provider+ // rather than bounced by the already-exists toast.+ await $('[data-testid="add-model-dialog"]').waitForDisplayed({+ reverse: true,+ timeout: 30_000,+ })++ // Answer the analytics question, because a real user has to before they can+ // get on with anything: the moment the provider completes onboarding,+ // PromptAnalytic floats the consent panel at `fixed bottom-4 right-4 z-50`+ // (containers/analytics/), directly over the composer's send button.+ //+ // Deny rather than allow -- a test run has no business opting into+ // telemetry. Every run starts on a fresh profile, so the panel is always+ // there and failing loudly if it is not is correct.+ const denyAnalytics = await $('[data-testid="analytic-deny"]')+ await denyAnalytics.waitForDisplayed({+ timeout: 30_000,+ timeoutMsg:+ 'the analytics consent prompt never appeared after the provider was ' ++ 'configured. If it moved behind another condition, drop this step -- ' ++ 'but check first that it cannot appear later and cover the composer.',+ })+ await denyAnalytics.click()+ await $('[data-testid="analytic-consent"]').waitForDisplayed({+ reverse: true,+ timeout: 30_000,+ })+ })++ after(async () => {+ // Non-negotiable: an open listener keeps the wdio worker's event loop alive+ // and the run never exits, long after the last assertion has passed.+ //+ // Guarded because after() still runs when before() threw: if startMockOpenAI+ // itself failed, an unguarded close() throws "Cannot read properties of+ // undefined" and that is the error the report shows instead of the real one.+ if (mock) await mock.close()+ })++ /**+ * Wait for a control to be there and usable, then click it.+ *+ * Deliberately not waitForClickable(). WDIO's clickability check includes an+ * elementFromPoint test, and this driver's click does not: elementClick is+ * `el.scrollIntoView(); el.click(); el.focus()` in JS+ * (tauri-plugin-wdio-webdriver, src/platform/executor.rs), which sails through+ * anything painted on top. So the precheck can only ever reject clicks that+ * would have worked, and on a first launch there is plenty painted on top --+ * Jan downloads its embedding model and toasts "Download Complete" over the+ * header, and the analytics consent panel floats over the composer. Both are+ * transient and neither stops the click, but either turns this into a 30s+ * timeout naming an element that is present, enabled and visible.+ *+ * Displayed and enabled are still worth waiting for: those are real states+ * this app puts its controls in (Add Model stays disabled until the id field+ * has something in it, and the send button is swapped out entirely while a+ * reply streams).+ */+ async function clickWhenReady(selector: string, timeout = 30_000) {+ const element = await $(selector)+ await element.waitForDisplayed({ timeout })+ await element.waitForEnabled({ timeout })+ await element.click()+ return element+ }++ /**+ * Click a dialog's trigger until the dialog is actually up.+ *+ * One click has been seen not to take. On a run that still did the embedder+ * download, the click on `add-provider-trigger` returned and the dialog never+ * appeared, in the window where the "Download Complete" toast was landing+ * over the header. Once -- it has not reproduced.+ *+ * Why the click did not register is not known. The likeliest explanation is+ * that `el.click()` went to a node React had just replaced, but that is a+ * hypothesis and nobody has traced it: the Toaster is a sibling of the page+ * in routes/__root.tsx, and routes/settings/providers/index.tsx does not+ * remount its header when the model list changes, so nothing observed says a+ * mounting toast re-keys this trigger.+ *+ * The retry stays because it is cheap and safe, not because the cause is+ * understood. Safe is the verified half: Radix mirrors the open state onto+ * the trigger as data-state and its onClick is a *toggle*, so clicking one+ * that already says "open" would shut the dialog again.+ */+ async function openDialog(triggerSelector: string, dialogSelector: string) {+ await browser.waitUntil(+ async () => {+ if (await $(dialogSelector).isDisplayed()) return true++ const trigger = await $(triggerSelector)+ if (!(await trigger.isExisting())) return false+ if (!(await trigger.isDisplayed())) return false+ if (!(await trigger.isEnabled())) return false+ if ((await trigger.getAttribute('data-state')) === 'open') return false++ await trigger.click()+ return false+ },+ {+ timeout: 30_000,+ interval: 1_000,+ timeoutMsg:+ `clicking ${triggerSelector} never brought up ${dialogSelector}. The ` ++ 'trigger was present and enabled, so either the dialog moved behind ' ++ 'another condition or its testid changed.',+ }+ )+ }++ /** Put `prompt` in the composer and send it. */+ async function send(prompt: string) {+ const input = await $('[data-testid="chat-input"]')+ await input.waitForDisplayed({ timeout: 30_000 })+ // Typed through WDIO rather than assigned with browser.execute: the textarea+ // is React-controlled, and a direct value assignment fires no change event,+ // so `prompt` in ChatInput stays empty and the send button stays disabled.+ await input.setValue(prompt)++ // Waiting for this button is also the barrier for the *previous* turn: while+ // a response streams, ChatInput replaces it outright with a destructive stop+ // button (ChatInput.tsx:2917-2947), so it existing means no stream is in+ // flight, and it being enabled means the composer holds text.+ await clickWhenReady('[data-testid="send-message-button"]', 60_000)+ }++ it('sends a prompt and renders the streamed reply', async () => {+ await goto('/')++ // A single model on a custom provider is enough for hasUsableProvider()+ // (routes/index.tsx:52), so `/` renders the composer instead of SetupScreen+ // without any working credential. If this times out, the before() hook's+ // provider did not stick.+ const modelSelector = await $('[data-testid="model-selector-trigger"]')+ await modelSelector.waitForDisplayed({+ timeout: 30_000,+ timeoutMsg:+ '`/` never showed the model selector, so hasUsableProvider() is still ' ++ 'false and the app is sitting on SetupScreen -- the provider or its ' ++ 'model from before() was not persisted.',+ })+ await modelSelector.click()++ // Selecting is mandatory and explicit: useModelProvider defaults to llamacpp+ // and DropdownModelProvider's init effect never auto-selects a custom+ // provider, so skipping this sends the turn at a model that is not there.+ //+ // This testid is emitted by two sibling branches -- the favourites section+ // and the provider list (DropdownModelProvider.tsx:584 and :684) -- which+ // cannot both render the same model while the list skips favourites, and a+ // fresh profile has no favourites anyway. Both call the same handleSelect,+ // so matching either is correct; only a future $$ count over this selector+ // would need to care.+ await clickWhenReady(`[data-testid="model-option-${MOCK_MODEL_ID}"]`)++ await send(FIRST_PROMPT)++ // The echo is the whole assertion. MOCK_REPLY_PREFIX followed by exactly+ // what was typed can only appear if the prompt reached the mock over+ // tauri-plugin-http and the SSE chunks were reassembled in the webview;+ // asserting that *some* bubble rendered would pass on an error state.+ const reply = await $(ASSISTANT_MESSAGES)+ await reply.waitForDisplayed({+ timeout: 60_000,+ timeoutMsg:+ 'no assistant message appeared after sending the first prompt. The ' ++ 'mock logs a 404 body for any route it was not asked to answer, so ' ++ 'check for an unexpected path before suspecting the stream itself.',+ })+ await expect(reply).toHaveText(+ expect.stringContaining(MOCK_REPLY_PREFIX + FIRST_PROMPT)+ )++ // The first send creates the thread and the router lands on /threads/<id>.+ // Everything after this addresses the thread by that id -- in the sidebar+ // and on disk -- so capture it here rather than re-deriving it later.+ await browser.waitUntil(+ async () => {+ const path = await browser.execute(() => window.location.pathname)+ threadId = path.startsWith('/threads/')+ ? path.slice('/threads/'.length)+ : ''+ return threadId.length > 0+ },+ {+ timeout: 30_000,+ timeoutMsg:+ 'the router never moved to /threads/<id> after the first send, so ' ++ 'the remaining tests have no thread id to work with.',+ }+ )++ // Wait out the generated title here, while the thread still has exactly one+ // reply, because this is the only moment it is deterministic.+ //+ // The summarizer is fire-and-forget from onFinish and runs only on a refresh+ // tick -- the first assistant message, then every fourth+ // (routes/threads/$threadId.tsx:632-635). Sending the next turn aborts+ // whatever is in flight (line 957; thread-title-summarizer.ts swallows the+ // AbortError and returns null). So with two assistant messages there is no+ // second attempt: lose that race once and the row reads "New Thread" for the+ // rest of the run, which is a failure no retry can recover.+ //+ // It also belongs here on its own merits -- a title appearing is what the+ // first reply is supposed to trigger.+ await expect($(`[data-testid="thread-row-${threadId}"]`)).toHaveText(+ expect.stringContaining(MOCK_TITLE),+ {+ message:+ 'the thread was never titled. The summarizer is the one non-streaming ' ++ 'completion the mock answers, so a 404 or a changed request shape ' ++ 'shows up here and nowhere else.',+ }+ )+ })++ it('keeps every turn across a webview reload', async () => {+ await send(SECOND_PROMPT)++ await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(2)+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(2)++ // The second bubble exists as soon as the stream opens, so the count above+ // can be satisfied by a half-written reply; this is what waits for the echo+ // of the *second* prompt specifically, and pins the ordering while it is at+ // it.+ // getElements() rather than indexing the chainable $$ result: it resolves to+ // a plain array, so `.length` here is a number and not a promise.+ const replies = await $$(ASSISTANT_MESSAGES).getElements()+ await expect(replies[replies.length - 1]).toHaveText(+ expect.stringContaining(MOCK_REPLY_PREFIX + SECOND_PROMPT)+ )++ // Reload from `/`, and only from `/`. browser.refresh() re-requests whatever+ // is in the address bar; our routes are pushState-only and the Tauri asset+ // protocol has no SPA fallback, so refreshing at /threads/<id> asks it for a+ // deep path and 404s into a dead window. That is the same reason goto()+ // exists instead of browser.url(). Shallow first, then reload, then push+ // back in -- this ordering is load-bearing, not incidental.+ await goto('/')+ await browser.refresh()++ await $('#root').waitForExist({ timeout: 60_000 })+ // Not just #root: the selector renders only once React has mounted *and*+ // hasUsableProvider() is true again, so it proves the provider came back out+ // of persisted settings rather than out of the zustand stores the reload+ // just threw away.+ await $('[data-testid="model-selector-trigger"]').waitForDisplayed({+ timeout: 60_000,+ timeoutMsg:+ 'the app never came back up at `/` with a usable provider after ' ++ 'browser.refresh(). A blank window here usually means the refresh ran ' ++ 'from a deep path and the asset protocol 404ed it.',+ })++ await goto(`/threads/${threadId}`)++ // The payoff. This process holds no in-memory copy of the conversation any+ // more, so two turns -- four messages -- rendering here means they were read+ // back out of the Rust-side thread store.+ await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(2)+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(2)++ const restored = await $$(ASSISTANT_MESSAGES).getElements()+ await expect(restored[0]).toHaveText(+ expect.stringContaining(MOCK_REPLY_PREFIX + FIRST_PROMPT)+ )+ await expect(restored[1]).toHaveText(+ expect.stringContaining(MOCK_REPLY_PREFIX + SECOND_PROMPT)+ )++ // The same row after the reload. The title is part of what had to survive,+ // and this one cannot be the summarizer doing the work a second time: it+ // does not run again at two assistant messages. Test 1 already waited for it+ // to arrive, so nothing here is racing anything.+ await expect($(`[data-testid="thread-row-${threadId}"]`)).toHaveText(+ expect.stringContaining(MOCK_TITLE)+ )+ })++ it('deletes the thread from the sidebar and from disk', async () => {+ const rowSelector = `[data-testid="thread-row-${threadId}"]`+ const threadDir = join(janUserDataDir(testHome), 'threads', threadId)++ // Establish the directory is there before deleting it. Without this the+ // check at the end of this test passes for a thread id that was never+ // right -- a path that never existed does not exist afterwards either.+ await browser.waitUntil(() => existsSync(threadDir), {+ timeout: 30_000,+ timeoutMsg:+ `${threadDir} does not exist, so the delete assertion below would ` ++ 'prove nothing. Either the thread id captured in the first test is ' ++ 'wrong, or threads are no longer stored one directory per id ' ++ '(src-tauri/src/core/threads/utils.rs).',+ })++ const row = await $(rowSelector)+ await row.waitForDisplayed({ timeout: 30_000 })++ // Opening this menu is the one genuinely awkward interaction in the suite,+ // and both halves of the awkwardness come from the embedded driver rather+ // than from Jan.+ //+ // The driver has no real input: dispatch_pointer_event() builds a MouseEvent+ // in JS and dispatches it at the coordinates, and click_element() is+ // `el.click()` followed by `el.focus()` (tauri-plugin-wdio-webdriver,+ // src/platform/executor.rs). Nothing it does produces a PointerEvent, and a+ // synthesized MouseEvent does not move CSS :hover.+ //+ // So: this trigger is `md:opacity-0` until its row is hovered+ // (SidebarMenuAction showOnHover, components/ui/sidebar.tsx:713) and no+ // amount of moveTo() will reveal it, while Radix's DropdownMenuTrigger opens+ // on pointerdown, which never arrives -- a plain click leaves the menu shut+ // and the failure reads as "element still not clickable", naming an element+ // that is present and enabled.+ //+ // The keyboard path sidesteps both. The click's el.focus() satisfies the+ // rule's `group-focus-within/menu-item:opacity-100` arm, and Radix's trigger+ // also opens on Enter -- which is the route a keyboard user takes anyway.+ // Deliberately no waitForClickable here: it would reject the opacity-0+ // element before the focus that fixes it has happened.+ const threadMenu = await $(`[data-testid="thread-menu-${threadId}"]`)+ await threadMenu.waitForExist({ timeout: 30_000 })+ await threadMenu.click()+ await browser.keys('Enter')++ const deleteItem = await $('[data-testid="thread-delete"]')+ await deleteItem.waitForDisplayed({+ timeout: 30_000,+ timeoutMsg:+ 'the thread overflow menu never opened. Radix renders its content only ' ++ 'while open, so this selector finding nothing means the Enter above did ' ++ 'not reach the trigger -- check that the click focused it.',+ })+ await deleteItem.click()++ await clickWhenReady('[data-testid="confirm-delete-thread"]')++ // Re-query rather than reusing `row`: the node is gone, and the assertion+ // should be about the selector finding nothing, not about a stale reference.+ await expect($(rowSelector)).not.toBeExisting()++ // This is the half that covers the checklist's "stays deleted even after a+ // restart". The row vanishing only proves the zustand store dropped it, and+ // a webview reload is not a process restart, so nothing else in this spec+ // would notice a directory left behind for the next launch to re-read.+ // delete_thread is a remove_dir_all+ // (src-tauri/src/core/threads/commands.rs:121-137), so the directory going+ // away is also the proof the IPC call reached Rust at all.+ await browser.waitUntil(() => !existsSync(threadDir), {+ timeout: 30_000,+ timeoutMsg:+ `${threadDir} still exists after the delete was confirmed. The UI ` ++ 'dropped the thread but the on-disk copy survives, so it comes back on ' ++ 'the next launch -- check delete_thread in core/threads/commands.rs and ' ++ 'the caller that invokes it.',+ })+ })+})diff --git a/e2e/specs/smoke.e2e.ts b/e2e/specs/smoke.e2e.tsindex 482dd77af..ecaed8d9e 100644--- a/e2e/specs/smoke.e2e.ts+++ b/e2e/specs/smoke.e2e.ts@@ -3,43 +3,14 @@ import { join } from 'node:path'import { browser, expect, $ } from '@wdio/globals'+import { goto } from '../helpers/navigation.js'+import { janDataDir } from '../helpers/paths.js'+// The worker inherits this from the launcher; see wdio.conf.ts. Read from the// environment rather than importing the config, so the spec does not trigger a// second evaluation of a module with top-level side effects.const testHome = process.env.JAN_E2E_HOME!-/**- * Navigate the TanStack router client-side.- *- * A hard `browser.url()` would ask the Tauri asset protocol for a deep path it- * has no SPA fallback for, and 404. TanStack patches `history.pushState` to- * notify its own subscribers (@tanstack/history), so pushing is enough on its- * own -- no synthetic popstate needed.- *- * The state object matters: TanStack tracks position in `__TSR_index` and- * computes back/forward deltas by subtracting it. Pushing a bare `{}` wipes- * that key and turns later deltas into NaN, so carry the index forward.- */-async function goto(path: string) {- await browser.execute((target: string) => {- const previous = (window.history.state ?? {}) as Record<string, unknown>- const index =- typeof previous.__TSR_index === 'number' ? previous.__TSR_index + 1 : 0- const key = Math.random().toString(36).slice(2, 10)- window.history.pushState(- { ...previous, __TSR_index: index, key, __TSR_key: key },- '',- target- )- }, path)-- await browser.waitUntil(- async () =>- (await browser.execute(() => window.location.pathname)) === path,- { timeout: 20_000, timeoutMsg: `never navigated to ${path}` }- )-}-describe('Jan desktop app', () => {before(async () => {// The webview has loaded the document. React mounting into it is asserted@@ -89,12 +60,7 @@ describe('on-disk isolation', () => {it('wrote its config inside the throwaway profile', async () => {// app_data_dir_with_fallback() -> data_dir()/Jan, + CONFIGURATION_FILE_NAME// (core/app/commands.rs, core/app/constants.rs).- const settings =- process.platform === 'darwin'- ? join(testHome, 'Library/Application Support/Jan/settings.json')- : process.platform === 'win32'- ? join(testHome, 'AppData/Roaming/Jan/settings.json')- : join(testHome, '.local/share/Jan/settings.json')+ const settings = join(janDataDir(testHome), 'settings.json')await browser.waitUntil(() => existsSync(settings), {timeout: 30_000,diff --git a/e2e/wdio.conf.ts b/e2e/wdio.conf.tsindex e28baf20e..f6fc92f34 100644--- a/e2e/wdio.conf.ts+++ b/e2e/wdio.conf.ts@@ -1,9 +1,18 @@-import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs'+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs'import { connect } from 'node:net'import { tmpdir } from 'node:os'import { join, resolve } from 'node:path'import type { TauriCapabilities, TauriServiceOptions } from '@wdio/tauri-service'import { SevereServiceError } from 'webdriverio'+import { janUserDataDir } from './helpers/paths.js'import { isolationEnv } from './isolation.js'// The app resolves its data folder through `core::app::paths::data_dir()`, and@@ -126,6 +135,77 @@ if (process.platform === 'win32') {mkdirSync(join(testHome, 'AppData', 'Local'), { recursive: true })}+// Pre-seed the one-shot flag that turns off the fallback embedder download, so+// a fresh profile never fetches a model over the network mid-spec.+//+// bootstrapDefaultEmbedder() (extensions/llamacpp-extension/src/index.ts) is a+// startup install of `sentence-transformer-mini` that returns immediately when+// getBackendSetting('llamacpp-embedder-bootstrapped') is truthy. That setting+// comes from the `settings_get` Tauri command, which is backed by+// src-tauri/src/core/app/settings_store.rs: a flat JSON string->string map at+// `<jan_data_folder>/settings.json`. Writing the key here, before the app is+// spawned, is indistinguishable from a previous run having done the bootstrap.+//+// Worth doing because the alternative is a ~45MB download to+// `<jan_data_folder>/llamacpp/models/sentence-transformer-mini/model.gguf` on+// every single run, and with it a "Download Complete" toast that mounts over+// the header at a moment set by network speed rather than by the spec. That is+// a coin flip landing on whatever is being clicked: it produced three+// consecutive red runs where `add-provider-trigger` was reported "still not+// clickable" while present, enabled and visible. Seeding removes the download+// and the toast together; a seeded run leaves a ~112KB profile where an unseeded+// one leaves ~45MB. It does not make the app offline -- it still makes small+// metadata requests, the model catalogue among them -- but nothing in these+// specs waits on one.+//+// Not a workaround for a fragile download. A failed bootstrap is already+// non-fatal -- the whole body is try/caught, logged as "will import on demand",+// and retried next launch because the flag is only recorded on success -- and+// nothing in these specs touches the embedder, which serves RAG rather than+// chat. This is about determinism, not about avoiding a hard failure.+//+// Set JAN_E2E_EMBEDDER_DOWNLOAD to skip the seeding and get the real bootstrap+// back, which is what a spec *about* the embedder needs.+//+// Seeded whether or not this process created the profile. Gating it on+// ownership would let an inherited JAN_E2E_HOME -- a stray export, a CI+// variable, someone reusing a profile -- quietly take the download and the+// toast back, with nothing in the log saying so, which is precisely the+// nondeterminism this block exists to remove. Writing one key into a profile+// we did not create is acceptable: it is the same key the product writes+// itself after a successful bootstrap, it only adds to the file, and a caller+// who wants the real download has the env var above.+//+// NOTE this is the backend settings store, at janUserDataDir() -- NOT the app+// config `settings.json` one directory up at janDataDir(), which is the file+// smoke.e2e.ts asserts on. Same filename, different file, different owner.+if (!process.env.JAN_E2E_EMBEDDER_DOWNLOAD) {+ const backendSettingsDir = janUserDataDir(testHome)+ const backendSettingsFile = join(backendSettingsDir, 'settings.json')+ // A fresh mkdtemp profile cannot have one yet, but an inherited profile can,+ // and a populated one at that -- so merge rather than clobber. An unparseable+ // file is left untouched, since losing whatever it holds is worse than the+ // download this avoids.+ let settings: Record<string, string> | undefined = {}+ if (existsSync(backendSettingsFile)) {+ try {+ settings = JSON.parse(readFileSync(backendSettingsFile, 'utf8'))+ } catch {+ settings = undefined+ }+ }+ if (settings) {+ mkdirSync(backendSettingsDir, { recursive: true })+ writeFileSync(+ backendSettingsFile,+ JSON.stringify({+ ...settings,+ 'llamacpp-embedder-bootstrapped': 'true',+ })+ )+ }+}+// Resolved exactly as the service resolves it -- getEmbeddedPort(): the// TAURI_WEBDRIVER_PORT env var, else a hardcoded 4445.const driverPort = Number(process.env.TAURI_WEBDRIVER_PORT) || 4445@@ -157,7 +237,27 @@ const tauriServiceOptions: TauriServiceOptions = {export const config: WebdriverIO.Config = {runner: 'local',- specs: ['./specs/**/*.e2e.ts'],+ // Ordered by hand, not globbed. State leaks forwards between spec files, and+ // further than the shared profile explains. Every spec in a run shares one+ // on-disk profile: JAN_E2E_HOME is created in the launcher and inherited by+ // each worker (above), so whatever one spec file writes is still there for+ // the next. But the embedded provider also spawns *one* app, in the+ // launcher's onPrepare, and every spec file drives that same process over its+ // own WebDriver session -- one `Tauri app spawned` line per run, and the+ // service skips the per-worker spawn for this provider. So a later spec+ // inherits the live webview as well: its route, its zustand stores, any+ // dialog left open. Only an explicit browser.refresh() clears that half.+ //+ // smoke.e2e.ts asserts the first-run setup wizard, which the app only+ // renders while no provider is configured, and chat.e2e.ts configures one.+ // The previous glob left ordering to wdio, which sorts matches+ // alphabetically -- `chat` ran first and smoke then failed on a provider+ // another file had written, a reason that has nothing to do with what it+ // tests.+ //+ // The cost is that this list is maintained by hand: a new spec that is not+ // added here does not run, and nothing reports its absence.+ specs: ['./specs/smoke.e2e.ts', './specs/chat.e2e.ts'],maxInstances: 1,capabilities: [{@@ -173,7 +273,39 @@ export const config: WebdriverIO.Config = {waitforTimeout: 20_000,connectionRetryTimeout: 120_000,connectionRetryCount: 3,- mochaOpts: { ui: 'bdd', timeout: 120_000 },+ // Generous on purpose, because this is a backstop rather than the real+ // deadline. Every wait inside the specs is individually bounded and carries a+ // timeoutMsg that names what broke; Mocha's timeout carries none, so whenever+ // it fires first it replaces a diagnosis with "Timeout of Nms exceeded". A+ // before() hook that walks Add Provider and Add Model has half a dozen phases+ // and budgets ~30s each, which sums past two minutes on a machine slow enough+ // to need any of it -- exactly when the message matters most.+ mochaOpts: { ui: 'bdd', timeout: 300_000 },++ // Suppress the service's per-command window-focus recovery, which this app can+ // never satisfy and which costs five seconds on every element lookup.+ //+ // @wdio/tauri-service's beforeCommand hook calls ensureActiveWindowFocus() for+ // getTitle/findElement/findElements/$/$$/elementClick. That asks the app for+ // its window states over `browser.tauri.execute()`, which waits for+ // `window.__wdio_original_core__` -- a global the plugin's guest JS installs,+ // and which is absent here for the same reason `browser.tauri.execute()` is+ // unavailable to specs: `withGlobalTauri` is off. So the probe cannot ever+ // succeed; it just times out after 5s, per command, and the service logs+ // "Failed to get window states" and carries on. A spec doing thirty lookups+ // spends two and a half minutes waiting for a feature that is not there, which+ // is how a correct spec hits the Mocha timeout in a hook.+ //+ // afterCommand treats a successful, non-internal `switchToWindow` as the user+ // taking charge of window selection and suppresses focus recovery for the rest+ // of the session -- so switching to the handle we are already on is a no-op+ // that turns the probe off. Jan runs a single window under test, so there is+ // nothing for the recovery to recover.+ //+ // `before` runs once per worker, before any spec file.+ before: async (_capabilities, _specs, browser) => {+ await browser.switchToWindow(await browser.getWindowHandle())+ },// The embedded provider spawns the app and then polls// http://127.0.0.1:<port>/status until *something* reports ready. It neverdiff --git a/vitest.config.ts b/vitest.config.tsindex 60f540db8..dbadbfe52 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -31,6 +31,9 @@ export default defineConfig({'**/src/**/*.test.tsx','**/src/test/**/*','src-tauri',+ // The e2e suite is a separate package driven by WebdriverIO, not by+ // vitest, so every line of it reads as uncovered and dilutes the total.+ 'e2e/**',],},},diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex b185660e6..d3ea901b8 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -2951,6 +2951,7 @@ const ChatInput = memo(function ChatInput({size="icon-sm"disabled={(!prompt.trim() && !hasSendableMedia) || ingestingAny}data-test-id="send-message-button"+ data-testid="send-message-button"onClick={() => handleSendMessage(prompt)}className="rounded-full mr-1 mb-1">diff --git a/web-app/src/containers/DropdownModelProvider.tsx b/web-app/src/containers/DropdownModelProvider.tsxindex 06e433d4a..14dfa3455 100644--- a/web-app/src/containers/DropdownModelProvider.tsx+++ b/web-app/src/containers/DropdownModelProvider.tsx@@ -472,7 +472,10 @@ const DropdownModelProvider = memo(function DropdownModelProvider({return (<Popover open={open} onOpenChange={onOpenChange}><PopoverTrigger asChild>- <div className="border relative z-20 px-4 py-1.5 flex items-center gap-1.5 rounded-full">+ <div+ data-testid="model-selector-trigger"+ className="border relative z-20 px-4 py-1.5 flex items-center gap-1.5 rounded-full"+ ><buttontype="button"className="font-medium cursor-pointer flex items-center gap-1.5 relative z-20 min-w-0"@@ -578,6 +581,7 @@ const DropdownModelProvider = memo(function DropdownModelProvider({return (<divkey={`fav-${searchableModel.value}`}+ data-testid={`model-option-${searchableModel.model.id}`}onClick={() => handleSelect(searchableModel)}className={cn('mx-1 mb-1 px-2 py-1.5 rounded-sm cursor-pointer flex items-center gap-2 transition-all duration-200',@@ -677,6 +681,7 @@ const DropdownModelProvider = memo(function DropdownModelProvider({return (<divkey={searchableModel.value}+ data-testid={`model-option-${searchableModel.model.id}`}onClick={() => handleSelect(searchableModel)}className={cn('mx-1 mb-1 px-2 py-1.5 rounded-sm cursor-pointer flex items-center gap-2 transition-all duration-200',diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex b92fd8e57..2e0038f4e 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -553,6 +553,8 @@ export const MessageItem = memo(return (<div+ data-testid="message-item"+ data-message-role={message.role}className={cn('w-full mb-4 group/message',message.role === 'user' && !isFirstMessage && 'mt-8'diff --git a/web-app/src/containers/ModelCombobox.tsx b/web-app/src/containers/ModelCombobox.tsxindex 43b879c30..106a19316 100644--- a/web-app/src/containers/ModelCombobox.tsx+++ b/web-app/src/containers/ModelCombobox.tsx@@ -398,6 +398,7 @@ export function ModelCombobox({<div className={cn('relative', className)} ref={containerRef}><div className="relative"><Input+ data-testid="model-combobox-input"ref={inputRef}value={inputValue}onChange={(e) => handleInputChange(e.target.value)}diff --git a/web-app/src/containers/ThreadList.tsx b/web-app/src/containers/ThreadList.tsxindex 90633fb4d..be4cbe8c6 100644--- a/web-app/src/containers/ThreadList.tsx+++ b/web-app/src/containers/ThreadList.tsx@@ -154,7 +154,7 @@ const ThreadItem = memo(return (<SidebarMenuItem>{currentProjectId ?- <Link to="/threads/$threadId" params={{ threadId: thread.id }} className={cn("bg-card dark:bg-secondary/20 mb-2 px-4 py-4 border hover:dark:bg-secondary/30 rounded-lg block max-w-full overflow-hidden", isSelected && "border-primary")}>+ <Link to="/threads/$threadId" params={{ threadId: thread.id }} data-testid={`thread-row-${thread.id}`} className={cn("bg-card dark:bg-secondary/20 mb-2 px-4 py-4 border hover:dark:bg-secondary/30 rounded-lg block max-w-full overflow-hidden", isSelected && "border-primary")}><div className="flex items-center gap-1.5 min-w-0">{isActive && (<Loader2 className="size-3 shrink-0 animate-spin text-muted-foreground" />@@ -169,7 +169,7 @@ const ThreadItem = memo(</Link>:<SidebarMenuButton asChild isActive={isSelected}>- <Link to="/threads/$threadId" params={{ threadId: thread.id }}>+ <Link to="/threads/$threadId" params={{ threadId: thread.id }} data-testid={`thread-row-${thread.id}`}>{isActive && (<Loader2 className="size-3 shrink-0 animate-spin text-muted-foreground" />)}@@ -180,6 +180,7 @@ const ThreadItem = memo(<DropdownMenu><DropdownMenuTrigger asChild><SidebarMenuAction+ data-testid={`thread-menu-${thread.id}`}showOnHoverclassName={cn("hover:bg-sidebar-foreground/8", currentProjectId && 'mt-4 mr-2')}>@@ -251,6 +252,7 @@ const ThreadItem = memo()}<DropdownMenuSeparator /><DropdownMenuItem+ data-testid="thread-delete"variant="destructive"disabled={thread.title === 'What is Jan?' && !localStorage.getItem('setup-completed')}onSelect={() => {diff --git a/web-app/src/containers/analytics/AnalyticConsent.tsx b/web-app/src/containers/analytics/AnalyticConsent.tsxindex 838431d2b..83ab2386c 100644--- a/web-app/src/containers/analytics/AnalyticConsent.tsx+++ b/web-app/src/containers/analytics/AnalyticConsent.tsx@@ -30,13 +30,18 @@ export function AnalyticConsent() {<p className="mt-2 text-sm">{t('analyticsConsentQuestion')}</p><div className="mt-4 flex justify-end space-x-2"><Button+ data-testid="analytic-deny"variant="ghost"size="sm"onClick={() => handleProductAnalytics(false)}>{t('deny')}</Button>- <Button size="sm" onClick={() => handleProductAnalytics(true)}>+ <Button+ data-testid="analytic-allow"+ size="sm"+ onClick={() => handleProductAnalytics(true)}+ >{t('allow')}</Button></div>diff --git a/web-app/src/containers/dialogs/AddModel.tsx b/web-app/src/containers/dialogs/AddModel.tsxindex 6704e89e3..819b7b56d 100644--- a/web-app/src/containers/dialogs/AddModel.tsx+++ b/web-app/src/containers/dialogs/AddModel.tsx@@ -71,12 +71,17 @@ export const DialogAddModel = ({ provider, trigger }: DialogAddModelProps) => {<Dialog open={open} onOpenChange={setOpen}><DialogTrigger asChild>{trigger || (- <Button variant="secondary" size="icon-xs">+ <Button+ data-testid="add-model-trigger"+ variant="secondary"+ size="icon-xs"+ ><IconPlus size={18} className="text-muted-foreground" /></Button>)}</DialogTrigger><DialogContent+ data-testid="add-model-dialog"onEscapeKeyDown={(e: KeyboardEvent) => {if (isComboboxOpen) {e.preventDefault()@@ -134,6 +139,7 @@ export const DialogAddModel = ({ provider, trigger }: DialogAddModelProps) => {<DialogFooter><Button+ data-testid="add-model-submit"variant="default"size="sm"onClick={handleSubmit}diff --git a/web-app/src/containers/dialogs/AddProviderDialog.tsx b/web-app/src/containers/dialogs/AddProviderDialog.tsxindex 121b1cc60..63e44d12c 100644--- a/web-app/src/containers/dialogs/AddProviderDialog.tsx+++ b/web-app/src/containers/dialogs/AddProviderDialog.tsx@@ -78,6 +78,7 @@ export function AddProviderDialog({<Dialog open={isOpen} onOpenChange={handleOpenChange}><DialogTrigger asChild>{children}</DialogTrigger><DialogContent+ data-testid="add-provider-dialog"className="sm:max-w-[460px] max-w-[90vw]"onOpenAutoFocus={(e) => {e.preventDefault()@@ -90,6 +91,7 @@ export function AddProviderDialog({<div className="flex flex-col gap-3 mt-2"><Input+ data-testid="provider-name-input"ref={nameInputRef}value={name}onChange={(e) => setName(e.target.value)}@@ -120,6 +122,7 @@ export function AddProviderDialog({{t('provider:baseUrlLabel')}</label><Input+ data-testid="provider-base-url-input"value={baseUrl}onChange={(e) => {setBaseUrl(e.target.value)@@ -134,6 +137,7 @@ export function AddProviderDialog({{t('provider:apiKeyLabel')}</label><Input+ data-testid="provider-api-key-input"type="password"value={apiKey}onChange={(e) => setApiKey(e.target.value)}@@ -163,6 +167,7 @@ export function AddProviderDialog({</Button></DialogClose><Button+ data-testid="add-provider-submit"disabled={!canSubmit}onClick={handleCreate}className="w-full sm:w-auto"diff --git a/web-app/src/containers/dialogs/DeleteThreadDialog.tsx b/web-app/src/containers/dialogs/DeleteThreadDialog.tsxindex 7df49c92b..eaac94ec3 100644--- a/web-app/src/containers/dialogs/DeleteThreadDialog.tsx+++ b/web-app/src/containers/dialogs/DeleteThreadDialog.tsx@@ -107,6 +107,7 @@ export function DeleteThreadDialog({</Button></DialogClose><Button+ data-testid="confirm-delete-thread"ref={deleteButtonRef}variant="destructive"onClick={handleDelete}diff --git a/web-app/src/routes/settings/providers/index.tsx b/web-app/src/routes/settings/providers/index.tsxindex 6a04d31f0..602cccd99 100644--- a/web-app/src/routes/settings/providers/index.tsx+++ b/web-app/src/routes/settings/providers/index.tsx@@ -93,6 +93,7 @@ function ModelProviders() {<span className='font-medium text-base font-studio'>{t('common:settings')}</span><AddProviderDialog onCreateProvider={createProvider}><Button+ data-testid="add-provider-trigger"variant="outline"size="sm"className="flex items-center gap-2 relative z-20"