Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

test: in-thread message actions (e2e) and upgrade-path contract tests (#8995)

James Dam962d9cf46269
diff --git a/.github/workflows/update-feed-check.yml b/.github/workflows/update-feed-check.yml
new file mode 100644
index 000000000..3612746af
--- /dev/null
+++ b/.github/workflows/update-feed-check.yml
@@ -0,0 +1,79 @@
+# Guards the release-update feeds that the in-app updater polls
+# (apps.jan.ai/update-check for stable, delta.jan.ai/nightly/latest.json for
+# nightly). The updater only fires when the feed is well-formed -- semver
+# version, one manifest entry per shipped platform, live asset URLs, valid
+# signatures -- and any drift silently disables the update prompt for part of
+# the user base. This is the "old version never updates" bug class, caught
+# without installing anything.
+#
+# Two jobs:
+# - fixtures: the committed feed recordings under
+# scripts/fixtures/update-feeds/, checked on every push and PR that
+# touches the checker (fast, no network).
+# - live: fetches the real feeds and probes every advertised asset URL.
+#
+# The 23:00 UTC slot is deliberate: jan-tauri-build-nightly starts at 20:00 UTC
+# (cron '0 20 * * 1,2,3'), so on the nights it runs this validates the feed
+# users are actually being pointed at rather than the previous one. Note the
+# publish is Mon/Tue/Wed only while this check is daily -- on the other four
+# mornings it is re-validating an unchanged feed, which is still worth doing
+# (an asset can 404 without the feed changing) but is not evidence of a fresh
+# build. (Follow-up: also run the live check as the final step of the publish
+# job itself, for same-minute feedback.) Cancel-in-progress stays off so a
+# checker push cannot eat an in-flight nightly verification.
+#
+# Scope limit worth knowing: the live mode probes the feeds this script lists --
+# apps.jan.ai/update-check and delta.jan.ai/nightly/latest.json. Nightly builds
+# point the updater at apps-nightly.jan.ai/update-check first, and stable has a
+# GitHub releases fallback (tauri.conf.json); neither is probed here yet.
+#
+# Fixture mode only re-checks the schema, not the current truth: re-record the
+# fixtures whenever the feed schema evolves, and keep the required-platform
+# sets in scripts/check-update-feeds.mjs in sync with what the release
+# pipelines actually ship.
+name: update feed check
+
+# Nothing here writes: the checks read feeds and probe asset URLs.
+permissions:
+ contents: read
+
+on:
+ schedule:
+ - cron: '0 23 * * *'
+ workflow_dispatch:
+ push:
+ paths:
+ - 'scripts/check-update-feeds.mjs'
+ - 'scripts/fixtures/update-feeds/**'
+ - '.github/workflows/update-feed-check.yml'
+ pull_request:
+ paths:
+ - 'scripts/check-update-feeds.mjs'
+ - 'scripts/fixtures/update-feeds/**'
+ - '.github/workflows/update-feed-check.yml'
+
+concurrency:
+ group: update-feed-check-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ fixtures:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 20
+ - name: Check recorded feed fixtures
+ run: node scripts/check-update-feeds.mjs
+
+ live:
+ if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
+ with:
+ node-version: 20
+ - name: Check live update feeds
+ run: node scripts/check-update-feeds.mjs --live
diff --git a/e2e/README.md b/e2e/README.md
index 80bc69b8f..cb2a6ece5 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -31,8 +31,38 @@ yarn build:e2e:app # from the repo root
cd e2e && xvfb-run -a yarn test
```
-`xvfb-run -a yarn e2e` also works; it just puts the ~20-minute build inside the
-virtual display for no reason.
+`xvfb-run -a yarn e2e` also works; it just puts the build — 6-11 minutes cold
+on the hosted runners — inside the virtual display for no reason.
+
+## What it covers
+
+Three spec files, run in this order (see [Spec order](#spec-order-is-maintained-by-hand)):
+
+| Spec | Covers |
+|---|---|
+| `smoke.e2e.ts` | The app boots, React mounts, the first-run wizard renders, and the data folder Rust resolves is inside the throwaway profile. |
+| `chat.e2e.ts` | Configure a provider and a model through the real dialogs; send; stream a reply; a second turn; survive a webview reload; delete the thread and confirm it left disk. |
+| `message-actions.e2e.ts` | Regenerate; switch between reply versions; edit a user message and re-run; delete a single message; stop a reply mid-stream; New Chat into a fresh thread. |
+
+Those are the load-bearing items of the manual checklist's D section: if the
+chat loop and the actions on a message work, the product works. Much of D is
+still manual — rename, the search dialog, `Delete All`, projects, switching
+model mid-conversation, markdown/LaTeX/code-block rendering, image attachments,
+IME input, the token-speed readout.
+
+**Deliberately out of scope.** llama.cpp: a real local model means a
+multi-gigabyte download, minutes per run, and different behaviour on every
+backend, so it needs its own platform-specific test rather than a place in the
+critical path. Copy-to-clipboard: `CopyButton` calls
+`navigator.clipboard.writeText` without awaiting it or handling a rejection, and
+flips to the check icon either way, so a DOM assertion there would pass whether
+or not anything reached the clipboard.
+
+**Not testable at all, as of the sidebar revamp (`92b2de422`).** Starring a
+thread, the `Favorites`/`Recent` split, `Unstar All` and the inline sidebar
+search input were all rendered by `containers/LeftPanel.tsx`, which that commit
+deleted. `toggleFavorite`, `unstarAllThreads` and `getFavoriteThreads` survive in
+`hooks/useThreads.ts` with no production caller. The checklist still lists them.
## Running
@@ -336,7 +366,7 @@ 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:
+Use `clickWhenReady(selector)` from `helpers/interactions.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
@@ -347,9 +377,23 @@ exist is the streaming barrier.
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.
+`waitForExist()` instead, then a plain `click()` to focus it before the
+`opacity-0` rule stops applying. Two live examples, and they are hidden by
+different rules:
+
+- the thread overflow menu (third test in `specs/chat.e2e.ts`), which is
+ `md:opacity-0` with a `group-focus-within/menu-item:opacity-100` escape
+ (`components/ui/sidebar.tsx:714`), and additionally needs `Enter` because its
+ Radix *dropdown* trigger opens on pointerdown;
+- the whole **user-side message action row** — Copy, Edit, Ask again, Delete —
+ which is `opacity-0 ... group-hover/message:opacity-100 focus-within:opacity-100`
+ (`web-app/src/containers/MessageItem.tsx:631`). The edit test in
+ `specs/message-actions.e2e.ts` reaches it with `waitForExist()` + `click()`
+ and nothing else: `DialogTrigger` opens on `onClick`, so unlike the dropdown
+ no keypress is needed.
+
+The **assistant**-side row has no opacity rule at all — it is only `hidden`
+while that reply is streaming — so message actions on a reply need none of this.
### The analytics prompt covers the composer
@@ -360,10 +404,17 @@ 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
+`denyAnalyticsConsent({ required })` in `helpers/provider.ts` answers it 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.
+no business opting into telemetry.
+
+`required` is the part worth reading twice. The panel appears **once per
+profile**, so exactly one spec in a run sees it: the first to complete
+onboarding, which is `specs/chat.e2e.ts`. That one passes `required: true`,
+because silently skipping a panel that has not appeared yet just defers it to
+whatever is being clicked later. Every later spec passes `required: false`,
+because waiting for a panel that has already been answered hangs for the full
+timeout.
It is not the only thing that floats. The embedding-model download from
[Isolation](#isolation) completes at a different moment every run depending on
@@ -375,17 +426,33 @@ 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.
+A click that arrives in that window has also been seen to simply not take, and
+this is the suite's one **open** problem. Twice: once on an otherwise idle
+machine while the toast was landing, and once as a run of three consecutive red
+runs — `[data-testid="add-provider-trigger"]` present and enabled, dialog never
+appearing, in `chat.e2e.ts` and `message-actions.e2e.ts` alike — which then went
+green on their own and have not returned.
+
+**Why** it does not register is not known. The standing hypothesis is that
+`el.click()` goes to a node React has just replaced; it is unverified, and
+nothing observed supports the obvious culprit — 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 a mounting toast does not
+re-key the trigger.
+
+Attempts to reproduce it have all failed. Saturating every core produced 4/4
+green runs with the current `openDialog()` *and* 4/4 with the check-then-click
+version it replaced; a later series ran 30 consecutive whole-suite runs green —
+20 idle, 10 under combined CPU and I/O saturation. **So load is not the trigger,
+and the current version is not known to fix anything.** Do not read its shape as
+a solved problem. What it does is narrow the window between finding the trigger
+and clicking it from four round trips to none, and report what the last attempt
+actually observed when it times out — "clicked", "already-open", "missing",
+"disabled" or "hidden". If this goes red on CI, that word is the first thing to
+read, and it is the evidence this paragraph is still missing.
Opening a dialog therefore goes through
-`openDialog(triggerSelector, dialogSelector)` in `specs/chat.e2e.ts`, which
+`openDialog(triggerSelector, dialogSelector)` in `helpers/interactions.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
@@ -422,6 +489,21 @@ If a future spec is mysteriously slow and the log carries
`helpers/` holds the pieces more than one spec needs:
- `navigation.ts` — `goto()`, described above.
+- `interactions.ts` — `clickWhenReady()` and `openDialog()`, both described
+ above. They live here rather than in a spec because what they work around is
+ the driver, not the screen.
+- `provider.ts` — `configureMockProvider()` walks the real Add Provider and Add
+ Model dialogs, `denyAnalyticsConsent()` answers the consent panel, and
+ `selectModel()` picks a model in the composer. The last is not optional:
+ `useModelProvider` defaults to `{ selectedProvider: 'llamacpp', selectedModel:
+ null }` and `DropdownModelProvider`'s init effect only ever auto-selects a
+ llamacpp model or clears the selection — it never reaches for a custom
+ provider, so a spec that skips it sends at a model that is not there.
+- `chat.ts` — the `USER_MESSAGES` / `ASSISTANT_MESSAGES` selectors, `sendPrompt()`
+ and `waitForStreamToFinish()`. The two selectors pair the testid with
+ `data-message-role`, which matters: system notes take an early return in
+ `MessageItem.tsx` and render neither attribute, so counting these counts real
+ conversation turns and nothing else.
- `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.
@@ -463,6 +545,29 @@ 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.
+`startMockOpenAI()` takes two options, both of which exist for a specific spec:
+
+- `modelId` — what `GET /v1/models` advertises. A second spec **must** override
+ it. Nothing removes an earlier spec's provider, and the composer's dropdown
+ keys its option testid on the model id alone
+ (`DropdownModelProvider.tsx:584,684`), so two providers advertising the same
+ id put two elements behind `model-option-<id>` — and one of them points at a
+ server that was closed in the earlier spec's `after()`.
+- `chunkDelayMs` — milliseconds between streamed chunks, and writable on the
+ returned handle so one test can slow the stream down and put it back. At the
+ default of 0 the whole echo lands well inside one WebDriver round trip, so
+ there is nothing left to interrupt by the time a click on stop arrives.
+
+The handle also carries `streamedPrompts`: the last user turn of every
+*streaming* completion so far, live. It is there because some claims the UI
+makes are not observable in the DOM at all. A regenerated reply to an unchanged
+prompt is byte-identical to the one it replaced, so nothing on screen separates
+"asked the model again" from "re-rendered what was already there" — and asking
+again is the whole of what Regenerate does. Its mirror image is the version-nav
+test, which asserts the count did **not** move: switching between two versions
+has to read what the thread already holds. Title-summarizer calls are excluded,
+since they are not conversation turns.
+
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.
@@ -483,6 +588,10 @@ 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.
+The order is pristine first, most-configured last — `smoke` → `chat` →
+`message-actions` — and it is the reason `message-actions.e2e.ts` can assume a
+provider has already been configured and the analytics panel already answered.
+
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
@@ -497,7 +606,7 @@ configures the app.
### A green run still logs errors
-Both spec files leave `no such element` and `stale element reference` lines in
+The 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()`
diff --git a/e2e/helpers/chat.ts b/e2e/helpers/chat.ts
new file mode 100644
index 000000000..d216da9d1
--- /dev/null
+++ b/e2e/helpers/chat.ts
@@ -0,0 +1,57 @@
+import { $ } from '@wdio/globals'
+
+import { clickWhenReady } from './interactions.js'
+
+/**
+ * Selectors and actions for the composer and the transcript.
+ *
+ * data-message-role is on the same node as the testid
+ * (web-app/src/containers/MessageItem.tsx:558-559). System notes take an early
+ * return above it and render neither attribute, so counting these counts real
+ * conversation turns and nothing else.
+ */
+export const USER_MESSAGES =
+ '[data-testid="message-item"][data-message-role="user"]'
+export const ASSISTANT_MESSAGES =
+ '[data-testid="message-item"][data-message-role="assistant"]'
+
+/** The composer's send button, which is also the not-streaming signal below. */
+export const SEND_BUTTON = '[data-testid="send-message-button"]'
+
+/**
+ * Put `prompt` in the composer and send it.
+ *
+ * Waiting for the send 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.
+ */
+export async function sendPrompt(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)
+
+ await clickWhenReady(SEND_BUTTON, 60_000)
+}
+
+/**
+ * Block until nothing is streaming.
+ *
+ * The send button and the stop button are the two arms of one ternary
+ * (ChatInput.tsx:2917), so the send button coming back *is* the end of the
+ * stream -- there is no separate idle state to poll, and no "is it done yet"
+ * attribute to read off the message.
+ */
+export async function waitForStreamToFinish(timeout = 60_000) {
+ await $(SEND_BUTTON).waitForExist({
+ timeout,
+ timeoutMsg:
+ 'the composer still shows a stop button, so a reply is still streaming. ' +
+ 'If the mock was asked for something it has no route for it answers 404 ' +
+ 'with the path in the body -- check the driver log before suspecting a ' +
+ 'hang.',
+ })
+}
diff --git a/e2e/helpers/interactions.ts b/e2e/helpers/interactions.ts
new file mode 100644
index 000000000..742e9bdbd
--- /dev/null
+++ b/e2e/helpers/interactions.ts
@@ -0,0 +1,141 @@
+import { browser, $ } from '@wdio/globals'
+
+/**
+ * Clicking, for a driver with no real input.
+ *
+ * Both helpers here started life inside specs/chat.e2e.ts. They moved once a
+ * second spec needed them, which is also why the comments are long: what they
+ * work around is not obvious from reading them, and the failure they prevent
+ * reads as a timeout naming an element that is present, enabled and visible.
+ */
+
+/**
+ * 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 --
+ * the analytics consent panel floats over the composer, and an unseeded profile
+ * toasts "Download Complete" over the header. Neither stops the click, but
+ * either turns this into a 30s timeout naming an element that is fine.
+ *
+ * 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).
+ *
+ * Note that `opacity: 0` is NOT one of the differences -- waitForDisplayed()
+ * runs checkVisibility({opacityProperty: true}) browser-side and rejects a
+ * transparent element just as waitForClickable() would. Anything revealed only
+ * on hover or focus needs waitForExist() and a click to focus it instead; see
+ * the thread overflow menu in specs/chat.e2e.ts.
+ */
+export 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
+}
+
+/**
+ * What one attempt at opening a dialog did, for the timeout message below.
+ *
+ * `already-open` is the interesting one: it means the trigger says the dialog
+ * is open while the dialog is not displayed, which is a different bug from the
+ * click never landing and used to be indistinguishable from it.
+ */
+type OpenAttempt =
+ | 'clicked'
+ | 'already-open'
+ | 'missing'
+ | 'disabled'
+ | 'hidden'
+
+/**
+ * Click a dialog's trigger until the dialog is actually up.
+ *
+ * One click has been seen not to take. Twice now: once on an unloaded machine
+ * in the window where the embedder-download toast was landing, and once as a
+ * run of three consecutive red runs that went green again on their own. Both
+ * times the trigger was present and enabled and the dialog never appeared.
+ *
+ * **Why the code below is shaped this way, and what that does not claim.** The
+ * standing hypothesis is `el.click()` reaching a node React had already
+ * replaced: WDIO resolves `$(selector)` to an element id and spends a round
+ * trip per call against it, so a check-then-click sequence leaves a window --
+ * four round trips wide -- in which the node can be torn out, and this driver
+ * synthesizes clicks in JavaScript, so a click at a detached node is silent
+ * rather than an error. Doing the query and the click together in one
+ * `browser.execute` closes that window, and is the same operation rather than a
+ * workaround: `click_element` in this driver *is*
+ * `el.scrollIntoView(); el.click(); el.focus()` evaluated in the page
+ * (tauri-plugin-wdio-webdriver, src/platform/executor.rs). It also costs one
+ * round trip instead of five.
+ *
+ * But the hypothesis is untested. An attempt to reproduce the failure by
+ * saturating every core produced 4/4 green runs with this version *and* 4/4
+ * with the check-then-click version it replaced, so synthetic CPU load is not
+ * the trigger and this change is **not demonstrated to fix anything**. It is
+ * kept because a narrower window and one round trip are strictly better, not
+ * because the flake is understood.
+ *
+ * The part that will actually help is the timeout message: it now reports what
+ * the last attempt observed, so the next failure -- on CI, on a runner nobody
+ * can attach to -- says whether the click landed on a live node, whether the
+ * trigger thought the dialog was already open, or whether the selector matched
+ * nothing at all. Those are three different faults that until now produced one
+ * indistinguishable message.
+ *
+ * The retry stays, and its guard is the one verified part: Radix mirrors open
+ * state onto the trigger as `data-state` and its onClick is a **toggle**, so
+ * clicking one that already reads "open" would shut a dialog that had in fact
+ * opened.
+ */
+export async function openDialog(
+ triggerSelector: string,
+ dialogSelector: string
+) {
+ // Kept across iterations so the timeout can say what it kept seeing rather
+ // than assert something about the trigger it never checked.
+ let lastAttempt: OpenAttempt = 'missing'
+
+ await browser.waitUntil(
+ async () => {
+ if (await $(dialogSelector).isDisplayed()) return true
+
+ lastAttempt = await browser.execute((selector: string) => {
+ const el = document.querySelector(selector) as HTMLElement | null
+ if (!el) return 'missing'
+ if ((el as HTMLButtonElement).disabled) return 'disabled'
+ const style = window.getComputedStyle(el)
+ if (style.display === 'none' || style.visibility === 'hidden') {
+ return 'hidden'
+ }
+ // Radix's trigger toggles, so a second click on an open one shuts it.
+ if (el.getAttribute('data-state') === 'open') return 'already-open'
+ el.scrollIntoView()
+ el.click()
+ el.focus()
+ return 'clicked'
+ }, triggerSelector)
+
+ return false
+ },
+ {
+ timeout: 30_000,
+ interval: 1_000,
+ timeoutMsg:
+ `clicking ${triggerSelector} never brought up ${dialogSelector}. ` +
+ `The last attempt reported "${lastAttempt}": ` +
+ '"clicked" means the click landed on a live node and the dialog still ' +
+ 'did not open; "already-open" means the trigger believes it is open ' +
+ 'while the dialog is not displayed, which is a different fault; ' +
+ '"missing" means the selector matched nothing, so the page had not ' +
+ 'rendered or the testid changed.',
+ }
+ )
+}
diff --git a/e2e/helpers/mock-openai.ts b/e2e/helpers/mock-openai.ts
index 2088acb82..787f8c3c1 100644
--- a/e2e/helpers/mock-openai.ts
+++ b/e2e/helpers/mock-openai.ts
@@ -44,9 +44,57 @@ export const MOCK_REPLY_PREFIX = 'mock reply to: '
*/
export const MOCK_TITLE = 'Mock Thread Title'
+export type MockOptions = {
+ /**
+ * What `GET /v1/models` advertises, and so what a spec types into Add Model.
+ *
+ * Worth overriding when a second spec configures a second provider: both
+ * providers stay in the profile (nothing deletes the first), and the chat
+ * model dropdown keys its option testid on the model id alone
+ * (DropdownModelProvider.tsx), so two providers offering the same id put two
+ * matching elements on the page and `model-option-<id>` stops identifying one.
+ */
+ modelId?: string
+ /**
+ * Milliseconds to wait between streamed chunks.
+ *
+ * The default of 0 flushes the whole reply as fast as the socket takes it,
+ * which is what a spec asserting on the finished text wants. A spec that has
+ * to act on a reply *while it is still streaming* -- pressing stop -- needs
+ * the stream to outlive the round trip that clicks the button, and this is
+ * the only knob that makes that deterministic rather than a race against
+ * loopback.
+ */
+ chunkDelayMs?: number
+}
+
export type MockOpenAI = {
/** Feed this to the Add Provider dialog verbatim. */
baseUrl: string
+ /** What this instance advertises; echoes back `modelId`, or the default. */
+ modelId: string
+ /**
+ * How long the server pauses between streamed chunks, from now on.
+ *
+ * Writable, and read fresh for every chunk, so one test can slow the stream
+ * down and the next can put it back without standing up a second server on a
+ * second port and reconfiguring a second provider to reach it. The stop test
+ * is the only caller: everything else wants a reply that has already finished
+ * by the time it is asserted on.
+ */
+ chunkDelayMs: number
+ /**
+ * The last user turn of every *streaming* completion asked for so far, oldest
+ * first. Live -- read it again to see later requests.
+ *
+ * This is how a spec tells "the UI re-rendered something it already had" from
+ * "the UI asked the model again", which is the whole of what Regenerate
+ * claims to do and is invisible from the DOM: a regenerated reply to an
+ * unchanged prompt is byte-identical to the one it replaced. Title-summarizer
+ * calls are deliberately excluded -- they are not conversation turns, and
+ * they fire on a schedule of their own.
+ */
+ streamedPrompts: string[]
close: () => Promise<void>
}
@@ -99,6 +147,11 @@ function sendJson(res: ServerResponse, status: number, payload: unknown) {
const completionId = 'chatcmpl-jan-e2e'
+/** Resolves after `ms`; used only to pace a deliberately slow stream. */
+function sleep(ms: number) {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
/**
* Stream the echo back as SSE, in several chunks.
*
@@ -106,8 +159,20 @@ const completionId = 'chatcmpl-jan-e2e'
* 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).
+ *
+ * Bails out the moment the socket is gone. Two callers destroy it: the app,
+ * when a spec presses stop (tauri-plugin-http aborts the request), and close()
+ * below. Without the check a stopped stream goes on writing into a dead
+ * response for the rest of its chunk budget, and with a chunkDelayMs set that
+ * is long enough to outlive the test that pressed stop -- so the abort would
+ * look like it worked while the server disagreed.
*/
-function streamCompletion(res: ServerResponse, reply: string) {
+async function streamCompletion(
+ res: ServerResponse,
+ reply: string,
+ modelId: string,
+ chunkDelay: () => number
+) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
@@ -116,13 +181,14 @@ function streamCompletion(res: ServerResponse, reply: string) {
})
const created = Math.floor(Date.now() / 1000)
+ const gone = () => res.destroyed || res.writableEnded
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,
+ model: modelId,
choices: [{ index: 0, delta, finish_reason: finish }],
})}\n\n`
)
@@ -131,8 +197,12 @@ function streamCompletion(res: ServerResponse, reply: string) {
// 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]) {
+ if (gone()) return
chunk({ content: piece }, null)
+ const pause = chunkDelay()
+ if (pause > 0) await sleep(pause)
}
+ if (gone()) return
chunk({}, 'stop')
res.write(
@@ -140,7 +210,7 @@ function streamCompletion(res: ServerResponse, reply: string) {
id: completionId,
object: 'chat.completion.chunk',
created,
- model: MOCK_MODEL_ID,
+ model: modelId,
choices: [],
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
})}\n\n`
@@ -149,7 +219,13 @@ function streamCompletion(res: ServerResponse, reply: string) {
res.end()
}
-async function handle(req: IncomingMessage, res: ServerResponse) {
+async function handle(
+ req: IncomingMessage,
+ res: ServerResponse,
+ modelId: string,
+ chunkDelay: () => number,
+ streamedPrompts: string[]
+) {
const url = req.url ?? '/'
if (req.method === 'OPTIONS') {
@@ -170,7 +246,7 @@ async function handle(req: IncomingMessage, res: ServerResponse) {
object: 'list',
data: [
{
- id: MOCK_MODEL_ID,
+ id: modelId,
object: 'model',
created: Math.floor(Date.now() / 1000),
owned_by: 'jan-e2e',
@@ -199,7 +275,7 @@ async function handle(req: IncomingMessage, res: ServerResponse) {
id: completionId,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
- model: MOCK_MODEL_ID,
+ model: modelId,
choices: [
{
index: 0,
@@ -212,7 +288,11 @@ async function handle(req: IncomingMessage, res: ServerResponse) {
return
}
- streamCompletion(res, MOCK_REPLY_PREFIX + lastUserText(body.messages ?? []))
+ const prompt = lastUserText(body.messages ?? [])
+ // Recorded before the reply is written, so a spec that counts requests sees
+ // this one even if the stream it opens is aborted halfway through.
+ streamedPrompts.push(prompt)
+ await streamCompletion(res, MOCK_REPLY_PREFIX + prompt, modelId, chunkDelay)
return
}
@@ -233,9 +313,24 @@ async function handle(req: IncomingMessage, res: ServerResponse) {
* 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> {
+export function startMockOpenAI(
+ options: MockOptions = {}
+): Promise<MockOpenAI> {
+ const modelId = options.modelId ?? MOCK_MODEL_ID
+ const streamedPrompts: string[] = []
+ // Held in one place the handle also points at, so assigning to
+ // `mock.chunkDelayMs` mid-spec changes the next chunk rather than only the
+ // next server.
+ const state = { chunkDelayMs: options.chunkDelayMs ?? 0 }
+
const server: Server = createServer((req, res) => {
- handle(req, res).catch((error) => {
+ handle(
+ req,
+ res,
+ modelId,
+ () => state.chunkDelayMs,
+ streamedPrompts
+ ).catch((error) => {
if (res.headersSent) {
res.end()
return
@@ -250,6 +345,14 @@ export function startMockOpenAI(): Promise<MockOpenAI> {
const { port } = server.address() as AddressInfo
resolve({
baseUrl: `http://127.0.0.1:${port}/v1`,
+ modelId,
+ streamedPrompts,
+ get chunkDelayMs() {
+ return state.chunkDelayMs
+ },
+ set chunkDelayMs(ms: number) {
+ state.chunkDelayMs = ms
+ },
close: () =>
new Promise<void>((done, fail) => {
// closeAllConnections() first: close() only stops new connections and
diff --git a/e2e/helpers/provider.ts b/e2e/helpers/provider.ts
new file mode 100644
index 000000000..af3a42198
--- /dev/null
+++ b/e2e/helpers/provider.ts
@@ -0,0 +1,166 @@
+import { browser, $ } from '@wdio/globals'
+
+import { clickWhenReady, openDialog } from './interactions.js'
+import type { MockOpenAI } from './mock-openai.js'
+import { goto } from './navigation.js'
+
+/**
+ * Register a mock server with the app, through the real Add Provider and Add
+ * Model dialogs.
+ *
+ * Deliberately not by writing settings.json behind the app's back: provider
+ * creation is itself on the manual QA checklist, and a hand-written file would
+ * drift silently the next time the stored shape changes, turning a real
+ * regression into a passing test.
+ *
+ * Each spec that needs a model calls this with its own name and its own server.
+ * Nothing removes an earlier spec's provider, and an earlier spec's server is
+ * closed in its after() -- so a second spec reaching for the first's provider
+ * would be pointing at a dead port. Two providers coexisting is fine; two
+ * providers advertising the same *model id* is not, because the chat dropdown
+ * keys its option testid on the id alone. See MockOptions.modelId.
+ */
+export async function configureMockProvider(
+ mock: MockOpenAI,
+ providerName: string
+) {
+ 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(providerName)
+ // 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/${providerName}`,
+ {
+ timeout: 30_000,
+ timeoutMsg:
+ `Add Provider never landed on /settings/providers/${providerName}. ` +
+ '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.modelId)
+
+ // 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() 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 consent panel, which covers the composer's send button.
+ *
+ * The moment a provider completes onboarding, PromptAnalytic floats the panel at
+ * `fixed bottom-4 right-4 z-50` (containers/analytics/) directly over the send
+ * button. Deny rather than allow -- a test run has no business opting into
+ * telemetry.
+ *
+ * `required` is what makes this honest. The panel appears once per profile, so
+ * the spec that completes onboarding first must insist on seeing it (a silent
+ * skip there would mean it is still to come, landing over whatever is being
+ * clicked at the time). Every later spec in the same run must not, because the
+ * answer is already recorded and waiting for it would hang for the full timeout.
+ */
+export async function denyAnalyticsConsent({ required }: { required: boolean }) {
+ const deny = await $('[data-testid="analytic-deny"]')
+
+ if (!required) {
+ if (!(await deny.isExisting())) return
+ } else {
+ await deny.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 deny.click()
+ await $('[data-testid="analytic-consent"]').waitForDisplayed({
+ reverse: true,
+ timeout: 30_000,
+ })
+}
+
+/**
+ * Pick a model in the chat composer's dropdown.
+ *
+ * Mandatory and explicit: useModelProvider defaults to
+ * `{ selectedProvider: 'llamacpp', selectedModel: null }` and
+ * DropdownModelProvider's init effect only ever auto-selects a llamacpp model or
+ * clears the selection -- it never reaches for a custom provider. Skipping this
+ * sends the turn at a model that is not there.
+ */
+export async function selectModel(modelId: string) {
+ const trigger = await $('[data-testid="model-selector-trigger"]')
+ await trigger.waitForDisplayed({
+ timeout: 30_000,
+ timeoutMsg:
+ 'the chat model selector never appeared, so hasUsableProvider() is ' +
+ 'false and the app is sitting on SetupScreen -- the provider and model ' +
+ 'from configureMockProvider() were not persisted.',
+ })
+ await trigger.click()
+
+ // 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.
+ await clickWhenReady(`[data-testid="model-option-${modelId}"]`)
+}
diff --git a/e2e/specs/chat.e2e.ts b/e2e/specs/chat.e2e.ts
index 1272e45e1..de65b13f7 100644
--- a/e2e/specs/chat.e2e.ts
+++ b/e2e/specs/chat.e2e.ts
@@ -3,6 +3,12 @@ import { join } from 'node:path'
import { browser, expect, $, $$ } from '@wdio/globals'
+import {
+ ASSISTANT_MESSAGES,
+ sendPrompt,
+ USER_MESSAGES,
+} from '../helpers/chat.js'
+import { clickWhenReady } from '../helpers/interactions.js'
import {
MOCK_MODEL_ID,
MOCK_REPLY_PREFIX,
@@ -12,6 +18,11 @@ import {
} from '../helpers/mock-openai.js'
import { goto } from '../helpers/navigation.js'
import { janUserDataDir } from '../helpers/paths.js'
+import {
+ configureMockProvider,
+ denyAnalyticsConsent,
+ selectModel,
+} from '../helpers/provider.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
@@ -26,13 +37,6 @@ const PROVIDER_NAME = 'e2e-mock-provider'
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.
@@ -54,108 +58,11 @@ describe('chat critical path', () => {
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"]'
- )
+ await configureMockProvider(mock, PROVIDER_NAME)
- // 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,
- })
+ // This is the spec that completes onboarding, so the consent panel must be
+ // here; see the helper for why `required` is not always true.
+ await denyAnalyticsConsent({ required: true })
})
after(async () => {
@@ -168,124 +75,15 @@ describe('chat critical path', () => {
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}"]`)
+ // without any working credential.
+ await selectModel(MOCK_MODEL_ID)
- await send(FIRST_PROMPT)
+ await sendPrompt(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
@@ -347,7 +145,7 @@ describe('chat critical path', () => {
})
it('keeps every turn across a webview reload', async () => {
- await send(SECOND_PROMPT)
+ await sendPrompt(SECOND_PROMPT)
await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(2)
await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(2)
diff --git a/e2e/specs/message-actions.e2e.ts b/e2e/specs/message-actions.e2e.ts
new file mode 100644
index 000000000..b9129b5c4
--- /dev/null
+++ b/e2e/specs/message-actions.e2e.ts
@@ -0,0 +1,463 @@
+import { browser, expect, $, $$ } from '@wdio/globals'
+
+import {
+ ASSISTANT_MESSAGES,
+ sendPrompt,
+ USER_MESSAGES,
+ waitForStreamToFinish,
+} from '../helpers/chat.js'
+import { MOCK_REPLY_PREFIX, startMockOpenAI } from '../helpers/mock-openai.js'
+import type { MockOpenAI } from '../helpers/mock-openai.js'
+import { goto } from '../helpers/navigation.js'
+import {
+ configureMockProvider,
+ denyAnalyticsConsent,
+ selectModel,
+} from '../helpers/provider.js'
+
+// A provider and a model id of this spec's own, not chat.e2e.ts's.
+//
+// Both are needed. Nothing removes an earlier spec's provider, so its entry is
+// still in the profile -- but its mock server was closed in that spec's after(),
+// so its base URL now points at nothing. And the model id has to differ because
+// the chat dropdown keys its option testid on the id alone
+// (DropdownModelProvider.tsx:584,684): two providers offering `jan-e2e-mock`
+// would put two elements behind `model-option-jan-e2e-mock` and selectModel()
+// would be picking between a live server and a dead one by luck.
+const PROVIDER_NAME = 'e2e-actions-provider'
+const MODEL_ID = 'jan-e2e-actions'
+
+const OPENING_PROMPT = 'opening turn for the message actions spec'
+const EDITED_PROMPT = 'edited turn for the message actions spec'
+
+// Long enough that the echo is many chunks rather than a handful, so the stop
+// test has a stream to interrupt rather than a race to lose.
+const LONG_PROMPT =
+ 'this prompt is deliberately long so that the echoed reply arrives as many ' +
+ 'separate chunks and the stop button has something to interrupt'
+
+/**
+ * Milliseconds per chunk while the stop test needs a slow stream.
+ *
+ * 600 and not 400 because of the slowest leg rather than this machine. The echo
+ * is 26 word-chunks, so this paces roughly 15s of stream, against a stop path
+ * -- first-word detection on a 500ms poll, then waitForDisplayed, then the
+ * click -- that costs 2-3s here and closer to 5s on windows-11-arm. It is free
+ * on a green run: the stream is aborted a few seconds in and the remaining
+ * delay is never spent. Losing that race does not fail here either, it fails
+ * 30s later at the Continue-button wait, blaming message queueing, on the
+ * platform least convenient to debug.
+ */
+const SLOW_CHUNK_MS = 600
+
+// Derived rather than written out, so it cannot drift from what the mock sends.
+// The reply streams a word at a time, so this is the first thing to appear.
+const FIRST_REPLY_WORD = MOCK_REPLY_PREFIX.trim().split(' ')[0]
+
+/**
+ * The second chapter of the chat critical path: what a user does to a message
+ * *after* it has been sent.
+ *
+ * chat.e2e.ts covers send/stream/persist/delete-the-thread. These are the
+ * in-thread actions from the manual QA checklist's "In a thread" section --
+ * Regenerate, edit-and-regenerate, delete a message -- plus stopping a reply
+ * mid-flight, and New Chat, which the checklist calls out as "the user can
+ * immediately chat with the model".
+ *
+ * Like chat.e2e.ts the tests share one thread and run in declaration order.
+ * Each leaves the transcript in the state the next expects, which is stated
+ * rather than defended against: the alternative is streaming a reply from
+ * scratch six times over to assert six things about the same conversation.
+ */
+describe('message actions', () => {
+ let mock: MockOpenAI
+
+ // Written by before(), read by the New Chat test, which has to prove the
+ // thread it lands on is a *different* one.
+ let threadId = ''
+
+ before(async () => {
+ mock = await startMockOpenAI({ modelId: MODEL_ID })
+
+ await $('#root').waitForExist({ timeout: 60_000 })
+
+ await configureMockProvider(mock, PROVIDER_NAME)
+ // Not required: the panel appears once per profile and chat.e2e.ts already
+ // answered it earlier in this same app process. Insisting on it here would
+ // hang for the full timeout.
+ await denyAnalyticsConsent({ required: false })
+
+ await goto('/')
+ await selectModel(MODEL_ID)
+
+ await sendPrompt(OPENING_PROMPT)
+ await expect($(ASSISTANT_MESSAGES)).toHaveText(
+ expect.stringContaining(MOCK_REPLY_PREFIX + OPENING_PROMPT)
+ )
+ await waitForStreamToFinish()
+
+ 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 opening send, so ' +
+ 'the New Chat test has nothing to compare its new thread against.',
+ }
+ )
+ })
+
+ 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 (mock) await mock.close()
+ })
+
+ /**
+ * The version counter on the one visible assistant message, e.g. `2/2`.
+ *
+ * Absent entirely until a fork exists -- MessageItem.tsx:509 renders the whole
+ * nav only when `versionInfo.count > 1` -- so "no such element" here means no
+ * branch was created, which is a more useful failure than a text mismatch.
+ */
+ async function assistantVersionCounter() {
+ const counter = await $(
+ `${ASSISTANT_MESSAGES} [data-testid="message-version-counter"]`
+ )
+ await counter.waitForExist({
+ timeout: 30_000,
+ timeoutMsg:
+ 'the assistant message has no version counter, so no second version ' +
+ 'was created. The nav only renders once a message has siblings ' +
+ '(MessageItem.tsx:509), so this means the branch itself is missing ' +
+ 'rather than that it is showing the wrong number.',
+ })
+ return counter
+ }
+
+ it('regenerates the last reply and asks the model again', async () => {
+ const asked = mock.streamedPrompts.length
+
+ // Unique without scoping: the button renders only on the last assistant
+ // message and only while nothing is streaming (MessageItem.tsx:716-719).
+ await $('[data-testid="regenerate-message"]').click()
+
+ // The reason this assertion is on the server and not on the DOM: the
+ // regenerated reply answers an unchanged prompt, so it is byte-identical to
+ // the one it replaced. Nothing visible distinguishes "asked again" from
+ // "re-rendered what was already there", and "asked again" is the entire
+ // claim Regenerate makes.
+ await browser.waitUntil(
+ () => mock.streamedPrompts.length === asked + 1,
+ {
+ timeout: 60_000,
+ timeoutMsg:
+ 'clicking Regenerate did not produce another streaming completion. ' +
+ 'The button was there and enabled, so the click reached a handler ' +
+ 'that decided not to call the model.',
+ }
+ )
+ expect(mock.streamedPrompts.at(-1)).toBe(OPENING_PROMPT)
+
+ await waitForStreamToFinish()
+
+ // Branching, not appending: handleRegenerate keeps the old reply as a
+ // sibling and makes the new one active ($threadId.tsx:1355-1384), so the
+ // transcript still shows one reply and the counter is what says there are
+ // two of them.
+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(1)
+ await expect(await assistantVersionCounter()).toHaveText('2/2')
+ })
+
+ it('switches back to the previous version without asking again', async () => {
+ const asked = mock.streamedPrompts.length
+
+ await $('[data-testid="message-version-prev"]').click()
+ await expect(await assistantVersionCounter()).toHaveText('1/2')
+
+ // The half worth having. Switching versions reads a reply the thread
+ // already holds, so a request here would mean the app had thrown the old
+ // one away and was re-deriving it -- which would also make the two versions
+ // impossible to compare, since the model is free to answer differently.
+ //
+ // Read after a pause, not immediately: the counter flips from local state,
+ // so a request fired a moment behind it would slip past a snapshot taken
+ // the instant the DOM settles. Asserting a negative needs a window for the
+ // thing to fail to happen in.
+ await browser.pause(500)
+ expect(mock.streamedPrompts.length).toBe(asked)
+ })
+
+ it('re-runs the model when a user message is edited', async () => {
+ const asked = mock.streamedPrompts.length
+
+ const userMessage = await $(USER_MESSAGES)
+ const editTrigger = await userMessage.$(
+ '[data-testid="edit-message-trigger"]'
+ )
+
+ // waitForExist and a bare click, deliberately. The user-side action row is
+ // `opacity-0 ... group-hover/message:opacity-100 focus-within:opacity-100`
+ // (MessageItem.tsx:631) and this driver cannot produce the hover half -- a
+ // synthesized MouseEvent does not move CSS :hover. waitForDisplayed() would
+ // reject a fully transparent element, so anything that waits for visibility
+ // here times out on a control that works.
+ //
+ // The click itself is fine through the transparency: elementClick is
+ // `el.scrollIntoView(); el.click(); el.focus()` in JS, and DialogTrigger
+ // opens on onClick rather than the pointerdown that Radix's *dropdown*
+ // trigger wants. The trailing focus() is also what satisfies focus-within,
+ // so the row is opaque from here on.
+ await editTrigger.waitForExist({ timeout: 30_000 })
+ await editTrigger.click()
+
+ await $('[data-testid="edit-message-dialog"]').waitForDisplayed({
+ timeout: 30_000,
+ timeoutMsg:
+ 'the edit dialog never opened. The trigger exists but is transparent ' +
+ 'until focused, so if the click landed the dialog should follow -- ' +
+ 'check it is not disabled, which it is whenever no model is selected.',
+ })
+
+ // Wait for the dialog's *focus* timer, not for the text.
+ //
+ // The obvious wait -- poll until the textarea holds the original prompt --
+ // closes nothing, and is worth spelling out because it looks like it does.
+ // `draft` is seeded by `useState(initialCleanPrompt)`
+ // (EditMessageDialog.tsx:41) so the field holds the text on its very first
+ // paint, and that poll returns on its first attempt. (The effect at :47-52
+ // re-seeds it from the same source; it runs after paint and changes
+ // nothing here.) The thing worth waiting for is the *separate* effect at
+ // :54-61, which focus()es and select()s the textarea 100ms after open.
+ // Landing in the middle of typing, that select() makes the following
+ // keystrokes replace the selection, and the field ends up holding a suffix
+ // of what was typed.
+ //
+ // So wait for the element to actually be focused, which is the observable
+ // edge of that timer, and only then type.
+ const input = await $('[data-testid="edit-message-input"]')
+ await browser.waitUntil(async () => await input.isFocused(), {
+ timeout: 30_000,
+ timeoutMsg:
+ 'the edit dialog never focused its textarea, so the 100ms select() has ' +
+ 'not run yet and anything typed now could be half-replaced by it ' +
+ '(EditMessageDialog.tsx:54-61).',
+ })
+ await expect(input).toHaveValue(OPENING_PROMPT)
+
+ await input.setValue(EDITED_PROMPT)
+ // Confirm the field holds exactly what was typed before submitting it. If
+ // the select() above still managed to land mid-keystroke this is where it
+ // shows, naming the cause, rather than surfacing later as the model having
+ // been asked a truncated question.
+ await expect(input).toHaveValue(EDITED_PROMPT)
+
+ // Save is disabled while the draft is unchanged (EditMessageDialog.tsx:174-181),
+ // so it being enabled is itself the proof the field took the new text.
+ const save = await $('[data-testid="edit-message-save"]')
+ await save.waitForEnabled({ timeout: 30_000 })
+ await save.click()
+
+ await browser.waitUntil(() => mock.streamedPrompts.length === asked + 1, {
+ timeout: 60_000,
+ timeoutMsg:
+ 'saving an edited user message did not re-run the model. ' +
+ 'handleEditMessage only regenerates for role === "user" ' +
+ '($threadId.tsx:1430), so a silent no-op here means the edit was ' +
+ 'applied to something else.',
+ })
+ // The edited text, not the original -- this is what says the model was
+ // asked the new question rather than asked the old one again.
+ expect(mock.streamedPrompts.at(-1)).toBe(EDITED_PROMPT)
+
+ await waitForStreamToFinish()
+
+ await expect($(USER_MESSAGES)).toHaveText(
+ expect.stringContaining(EDITED_PROMPT)
+ )
+ await expect($(ASSISTANT_MESSAGES)).toHaveText(
+ expect.stringContaining(MOCK_REPLY_PREFIX + EDITED_PROMPT)
+ )
+ })
+
+ it('deletes a single message without touching the rest', async () => {
+ await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(1)
+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(1)
+
+ // The assistant row on purpose. Its actions are always visible when not
+ // streaming (MessageItem.tsx:677-682 hides the cluster only while the reply
+ // is in flight), so this covers delete without also re-covering the
+ // transparency workaround the edit test above already exercises.
+ const assistantMessage = await $(ASSISTANT_MESSAGES)
+ const deleteTrigger = await assistantMessage.$(
+ '[data-testid="delete-message-trigger"]'
+ )
+ await deleteTrigger.waitForDisplayed({ timeout: 30_000 })
+ await deleteTrigger.click()
+
+ await $('[data-testid="delete-message-dialog"]').waitForDisplayed({
+ timeout: 30_000,
+ })
+ await $('[data-testid="confirm-delete-message"]').click()
+
+ // The reply goes, the prompt stays. Counting both is the point: a delete
+ // that took the whole turn with it would satisfy an assertion that only
+ // looked for the reply being gone.
+ await browser.waitUntil(
+ async () => (await $$(ASSISTANT_MESSAGES).getElements()).length === 0,
+ {
+ timeout: 30_000,
+ timeoutMsg:
+ 'the assistant message is still rendered after the delete was ' +
+ 'confirmed.',
+ }
+ )
+ await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(1)
+ })
+
+ it('stops a reply while it is still streaming', async () => {
+ // Slow the server down for this test only. Every other test wants a reply
+ // that has already finished by the time it is asserted on, and at the
+ // default of 0 the whole echo lands well inside one WebDriver round trip --
+ // there would be nothing left to stop by the time the click arrived.
+ mock.chunkDelayMs = SLOW_CHUNK_MS
+ try {
+ await sendPrompt(LONG_PROMPT)
+
+ // Wait for the reply to have *started* before stopping it, which is both
+ // what the checklist item means and what makes the assertions below
+ // possible.
+ //
+ // The stop button is already there before the first token: it is shown
+ // for `submitted` as well as `streaming` (ChatInput.tsx:2019), and
+ // stopping in that window leaves a partial with no content at all --
+ // which $threadId.tsx:359 declines to persist, so there is no message to
+ // mark `stopped`, no Continue button, and nothing to show for it. That is
+ // exactly how this test failed the first time it was run.
+ //
+ // The *last* assistant message, and only after checking there is exactly
+ // one. `$(ASSISTANT_MESSAGES)` takes the first, which is the streaming
+ // reply only because the test before this one deleted the old one -- so
+ // if that test failed, this would wait on a message that already reads
+ // "mock reply to: ...", pass instantly, and press stop during the
+ // `submitted` window the comment above warns about. The failure would
+ // then be reported here, about queueing, for something that broke two
+ // tests ago.
+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(1)
+ const replies = await $$(ASSISTANT_MESSAGES).getElements()
+ const reply = replies[replies.length - 1]
+ await reply.waitForDisplayed({ timeout: 30_000 })
+ await browser.waitUntil(
+ async () => (await reply.getText()).includes(FIRST_REPLY_WORD),
+ {
+ timeout: 30_000,
+ timeoutMsg:
+ `the reply never began with "${FIRST_REPLY_WORD}", so there was no ` +
+ 'partial to interrupt.',
+ }
+ )
+
+ // The stop button replacing the send button is the streaming state; they
+ // are the two arms of one ternary (ChatInput.tsx:2917).
+ const stop = await $('[data-testid="stop-message-button"]')
+ await stop.waitForDisplayed({
+ timeout: 30_000,
+ timeoutMsg:
+ 'the composer never swapped in the stop button, so either the send ' +
+ 'did not start a stream or the stream finished before this looked. ' +
+ `Each chunk is paced at ${SLOW_CHUNK_MS}ms, so the latter would mean ` +
+ 'the delay is not reaching the server.',
+ })
+ await stop.click()
+
+ await waitForStreamToFinish(30_000)
+
+ // Not just "the stream ended" -- that is also what finishing looks like.
+ // The Continue button renders only when metadata.stopped is true
+ // (MessageItem.tsx:114, :700-714), so its presence is what says the app
+ // recorded a stop rather than a completion.
+ await $('[data-testid="continue-message"]').waitForDisplayed({
+ timeout: 30_000,
+ timeoutMsg:
+ 'no Continue button appeared after stopping, so the reply was not ' +
+ 'marked as stopped. Note the stop button *clears the message queue* ' +
+ 'instead of stopping when anything is queued (ChatInput.tsx:2924-2939) ' +
+ '-- if this spec ever sends twice without waiting, that is the cause.',
+ })
+
+ // The partial reply is kept, not discarded -- and it is genuinely
+ // partial. The echo ends with the prompt, so the full text arriving would
+ // mean the stream ran to completion and every assertion above was about a
+ // reply that was never interrupted.
+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(1)
+ await expect(await $(ASSISTANT_MESSAGES).getText()).not.toContain(
+ LONG_PROMPT
+ )
+ } finally {
+ mock.chunkDelayMs = 0
+ }
+ })
+
+ it('starts a fresh thread from New Chat that can be chatted in at once', async () => {
+ // Independent of how the stop test ended. Its `finally` puts the chunk
+ // delay back, but if it failed before pressing stop the slow stream is
+ // still running, and clicking New Chat mid-turn is untested behaviour that
+ // would make this test's failure say nothing about New Chat.
+ await waitForStreamToFinish()
+
+ await $('[data-testid="new-chat-button"]').click()
+
+ // New Chat navigates to `/` and creates nothing; the thread is created by
+ // the first send (ChatInput.tsx:769-794). So `/` here is the whole of what
+ // the button is supposed to do.
+ await browser.waitUntil(
+ async () => (await browser.execute(() => window.location.pathname)) === '/',
+ {
+ timeout: 30_000,
+ timeoutMsg: 'New Chat did not navigate to `/`.',
+ }
+ )
+
+ // Straight into a send, with no model picked and no provider chosen. That
+ // is the checklist item: after New Chat the last used model is still
+ // selected and the user can chat immediately.
+ await sendPrompt(OPENING_PROMPT)
+
+ await expect($(ASSISTANT_MESSAGES)).toHaveText(
+ expect.stringContaining(MOCK_REPLY_PREFIX + OPENING_PROMPT),
+ {
+ message:
+ 'the new thread produced no reply, so New Chat did not carry the ' +
+ 'selected model over. Nothing was sent at all in that case: ' +
+ 'handleSendMessage returns early with "Please select a model to ' +
+ 'start chatting." when selectedModel is null (ChatInput.tsx:634-638), ' +
+ 'so look for that message in the composer rather than for a failed ' +
+ 'request in the mock log.',
+ }
+ )
+
+ let newThreadId = ''
+ await browser.waitUntil(
+ async () => {
+ const path = await browser.execute(() => window.location.pathname)
+ newThreadId = path.startsWith('/threads/')
+ ? path.slice('/threads/'.length)
+ : ''
+ return newThreadId.length > 0
+ },
+ { timeout: 30_000, timeoutMsg: 'the send never created a thread.' }
+ )
+
+ // A genuinely new thread, not the old one reopened -- which is what a New
+ // Chat that only navigated would look like.
+ expect(newThreadId).not.toBe(threadId)
+ await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(1)
+ })
+})
diff --git a/e2e/wdio.conf.ts b/e2e/wdio.conf.ts
index a5caa74c3..8a299934d 100644
--- a/e2e/wdio.conf.ts
+++ b/e2e/wdio.conf.ts
@@ -257,7 +257,16 @@ export const config: WebdriverIO.Config = {
//
// 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'],
+ //
+ // The order below is smoke -> chat -> message-actions, pristine first and
+ // most-configured last. message-actions.e2e.ts registers a second provider
+ // and leaves two threads behind, so it has to come after anything that cares
+ // what the profile holds.
+ specs: [
+ './specs/smoke.e2e.ts',
+ './specs/chat.e2e.ts',
+ './specs/message-actions.e2e.ts',
+ ],
maxInstances: 1,
capabilities: [
{
diff --git a/scripts/check-update-feeds.mjs b/scripts/check-update-feeds.mjs
new file mode 100755
index 000000000..112b0f30a
--- /dev/null
+++ b/scripts/check-update-feeds.mjs
@@ -0,0 +1,233 @@
+#!/usr/bin/env node
+// Update-feed contract check.
+//
+// The in-app updater only fires when the release feed is well-formed: a semver
+// version the plugin can compare, a manifest entry per shipped platform, and a
+// URL + signature per entry. Any drift (a platform key renamed, a URL 404, a
+// version shape the semver parser rejects) silently disables the prompt for
+// part of the user base -- which is exactly the "old version never updates"
+// bug class, and it is testable without installing anything.
+//
+// Modes:
+// node scripts/check-update-feeds.mjs [--fixtures] check the committed
+// recordings under scripts/fixtures/update-feeds/ (the default). No
+// network; safe for per-PR runs. Re-record the fixtures when the feed
+// schema evolves.
+// node scripts/check-update-feeds.mjs --live fetch the live feeds
+// (apps.jan.ai / delta.jan.ai) and additionally HEAD every asset URL.
+// For the nightly scheduled job, not for per-PR runs.
+//
+// The version-comparison invariants encode the channel trap: a nightly
+// `0.8.4-<run>` is a semver PRERELEASE, i.e. strictly less than `0.8.4`. That
+// is what keeps stable users from being offered nightlies and vice versa; if
+// the comparison in this file disagrees with the updater's, the feed or the
+// channels changed shape and both need a look.
+
+import { readFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const scriptDir = dirname(fileURLToPath(import.meta.url))
+const fixturesDir = join(scriptDir, 'fixtures', 'update-feeds')
+
+const FEEDS = [
+ {
+ name: 'stable',
+ fixture: join(fixturesDir, 'stable.json'),
+ live: 'https://apps.jan.ai/update-check',
+ // windows-aarch64 is deliberately absent today; shipping a stable arm64
+ // build must consciously extend this set.
+ requiredPlatforms: ['darwin-aarch64', 'darwin-x86_64', 'windows-x86_64', 'linux-x86_64'],
+ },
+ {
+ name: 'nightly',
+ fixture: join(fixturesDir, 'nightly.json'),
+ live: 'https://delta.jan.ai/nightly/latest.json',
+ requiredPlatforms: [
+ 'darwin-aarch64',
+ 'darwin-x86_64',
+ 'windows-x86_64',
+ 'windows-aarch64',
+ 'linux-x86_64',
+ ],
+ },
+]
+
+const errors = []
+const fail = (msg) => errors.push(msg)
+
+// Minimal semver for the two shapes Jan ships: `x.y.z` and `x.y.z-<run>`.
+// Returns a negative number if a < b, positive if a > b, 0 if equal.
+function compareVersions(a, b) {
+ const parse = (v) => {
+ const m = /^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/.exec(v)
+ if (!m) throw new Error(`unparseable version: ${v}`)
+ return { major: +m[1], minor: +m[2], patch: +m[3], pre: m[4] ?? null }
+ }
+ const pa = parse(a)
+ const pb = parse(b)
+ for (const k of ['major', 'minor', 'patch']) {
+ if (pa[k] !== pb[k]) return pa[k] - pb[k]
+ }
+ // Semver: a release (no prerelease) outranks any prerelease of the same
+ // x.y.z; two numeric prereleases compare by number.
+ if (pa.pre === null && pb.pre === null) return 0
+ if (pa.pre === null) return 1
+ if (pb.pre === null) return -1
+ const na = Number(pa.pre)
+ const nb = Number(pb.pre)
+ if (!Number.isNaN(na) && !Number.isNaN(nb)) return na - nb
+ return pa.pre < pb.pre ? -1 : pa.pre > pb.pre ? 1 : 0
+}
+
+function checkFeed(feed, body) {
+ let parsed
+ try {
+ parsed = JSON.parse(body)
+ } catch (e) {
+ fail(`${feed.name}: feed is not valid JSON (${e.message})`)
+ return
+ }
+ if (typeof parsed.version !== 'string' || !parsed.version) {
+ fail(`${feed.name}: missing or empty "version"`)
+ return
+ }
+ try {
+ compareVersions(parsed.version, parsed.version)
+ } catch (e) {
+ fail(`${feed.name}: version "${parsed.version}" is not semver-shaped (${e.message})`)
+ return
+ }
+ if (Number.isNaN(Date.parse(parsed.pub_date ?? ''))) {
+ fail(`${feed.name}: pub_date "${parsed.pub_date}" is not ISO-parseable`)
+ }
+
+ const platforms = parsed.platforms ?? {}
+ for (const required of feed.requiredPlatforms) {
+ const entry = platforms[required]
+ if (!entry) {
+ fail(`${feed.name}: required platform "${required}" missing from manifest`)
+ continue
+ }
+ if (typeof entry.url !== 'string' || !entry.url.startsWith('https://')) {
+ fail(`${feed.name}: ${required} url must be an https URL (got ${JSON.stringify(entry.url)})`)
+ }
+ if (typeof entry.signature !== 'string' || entry.signature.length < 32) {
+ fail(`${feed.name}: ${required} signature missing or implausibly short`)
+ }
+ }
+}
+
+// Live-only: every advertised asset must actually resolve. A 404 here is the
+// "update prompt installs nothing" bug one week after a CDN path change.
+// HEAD is tried first; some CDN/WAF setups answer 403/405 to HEAD but serve
+// GET fine, so a non-200 HEAD retries once with GET before failing — the
+// check must not false-red on exactly the drift it exists to catch.
+async function checkLiveAssets(feed, body) {
+ let parsed
+ try {
+ parsed = JSON.parse(body)
+ } catch (e) {
+ fail(`${feed.name}: live body is not JSON (${e.message}); skipping asset probe`)
+ return
+ }
+ const platformEntries = Object.entries(parsed.platforms ?? {})
+ if (platformEntries.length === 0) {
+ fail(`${feed.name}: live feed has no platforms at all`)
+ return
+ }
+ for (const [platform, entry] of platformEntries) {
+ let status
+ try {
+ status = await fetch(entry.url, {
+ method: 'HEAD',
+ redirect: 'follow',
+ signal: AbortSignal.timeout(15_000),
+ }).then((r) => r.status)
+ if (status !== 200) {
+ // Retry with GET; cancel the body so we do not pull the whole asset.
+ status = await fetch(entry.url, {
+ redirect: 'follow',
+ signal: AbortSignal.timeout(15_000),
+ }).then((r) => {
+ r.body?.cancel()
+ return r.status
+ })
+ }
+ } catch (e) {
+ status = `network error: ${e.message}`
+ }
+ console.log(` ${feed.name} ${platform}: ${status} ${entry.url}`)
+ if (status !== 200) fail(`${feed.name}: ${platform} asset ${entry.url} -> ${status}`)
+ }
+}
+
+const flags = process.argv.slice(2)
+const unknown = flags.filter((f) => f !== '--live' && f !== '--fixtures')
+if (unknown.length > 0) {
+ // Rejected rather than ignored, because the silent failure is a false pass:
+ // a mistyped `--live` in the nightly job would quietly run fixtures mode --
+ // no network, no asset probes -- and report OK.
+ console.error(`unknown argument(s): ${unknown.join(' ')}`)
+ console.error('usage: check-update-feeds.mjs [--fixtures | --live]')
+ process.exit(2)
+}
+const mode = flags.includes('--live') ? 'live' : 'fixtures'
+console.log(`update-feed contract check (${mode} mode)`)
+
+// The comparison invariants that keep channels from cross-offering updates.
+// If any of these flip, the updater will offer stable builds to nightly users
+// (or nothing at all to stable users) — the silent no-update bug.
+const invariants = [
+ ['0.8.4-4980', '0.8.4-4970', 1, 'newer nightly run outranks older'],
+ ['0.8.4-4980', '0.8.4', -1, 'prerelease is less than its release (channel isolation)'],
+ ['0.8.5', '0.8.4-4980', 1, 'next stable outranks any 0.8.4 nightly'],
+ ['0.8.4', '0.8.4', 0, 'same version compares equal'],
+ ['0.8.10', '0.8.9', 1, 'numeric compare across digit boundary, not lexicographic'],
+]
+for (const [a, b, expected, why] of invariants) {
+ const got = compareVersions(a, b)
+ const sign = Math.sign(got)
+ if (sign !== expected) {
+ fail(`version compare ${a} vs ${b}: expected sign ${expected} (${why}), got ${got}`)
+ } else {
+ console.log(` cmp ${a} vs ${b} -> ${sign} ok (${why})`)
+ }
+}
+
+for (const feed of FEEDS) {
+ const body = readFileSync(feed.fixture, 'utf8')
+ console.log(`checking ${feed.name} fixture`)
+ checkFeed(feed, body)
+}
+
+if (mode === 'live') {
+ for (const feed of FEEDS) {
+ // Wrapped where every other fetch in this file already is: a DNS failure or
+ // a refused connection here would otherwise surface as an unhandled
+ // rejection and a stack trace instead of the curated failure report, which
+ // is the one output a nightly job is read for.
+ let res
+ try {
+ res = await fetch(feed.live, { signal: AbortSignal.timeout(15_000) })
+ } catch (error) {
+ fail(`${feed.name}: live feed ${feed.live} -> ${error.name}: ${error.message}`)
+ continue
+ }
+ if (res.status !== 200) {
+ fail(`${feed.name}: live feed ${feed.live} -> HTTP ${res.status}`)
+ continue
+ }
+ const body = await res.text()
+ console.log(`checking ${feed.name} live (${feed.live})`)
+ checkFeed(feed, body)
+ await checkLiveAssets(feed, body)
+ }
+}
+
+if (errors.length > 0) {
+ console.error(`\nFAILED (${errors.length}):`)
+ for (const e of errors) console.error(` - ${e}`)
+ process.exit(1)
+}
+console.log('\nOK: update feeds satisfy the contract')
diff --git a/scripts/fixtures/update-feeds/nightly.json b/scripts/fixtures/update-feeds/nightly.json
new file mode 100644
index 000000000..2d24e2ce2
--- /dev/null
+++ b/scripts/fixtures/update-feeds/nightly.json
@@ -0,0 +1,27 @@
+{
+ "version": "0.8.4-4980",
+ "notes": "",
+ "pub_date": "2026-09-16T21:01:20.471Z",
+ "platforms": {
+ "linux-x86_64": {
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGlJMVJ6aU4ySUc1WmEwVm5Mdk5WaDZUSDhhdEhyWGcyVjBsTlpHWnJ4ZTJPeFFrVUFDdDdYRUswTVRZeUZnY2l0ZjhOUWRGNVQraGNMdFhOVExJblFnPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg5NTkwODMzCWZpbGU6SmFuLW5pZ2h0bHlfMC44LjQtNDk4MF9hbWQ2NC5BcHBJbWFnZQptSTZPUkVVemRlM1F0alI3RFozaFluZktHM1lTYWNPeExPTDhjcFNNUFZobVNnekU2OVdVaGtzNFpCSSt3ekx3MEZkeG5iTFl3Q1hxQ09zOHFhQzJBZz09Cg==",
+ "url": "https://delta.jan.ai/nightly/Jan-nightly_0.8.4-4980_amd64.AppImage"
+ },
+ "windows-x86_64": {
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGpJdVkybG03Mk45ZUIyQVNyQ1hnM2VQa1JxbXQxUFdRUmZlblV4R1BLd1BCdDB3Nlp1dUs4TXQ4NTJhN3ZCWExTblBkcE5RVkdUcUJZMGVBaEZWR2c4PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg5NTkxNTcwCWZpbGU6SmFuLW5pZ2h0bHlfMC44LjQtNDk4MF94NjQtc2V0dXAuZXhlCkRrb3F1V0tmNzk2TXNRWkliL2tXbEt3eFNNOGpsazloZC8zREhCMW8xVHNwc204Vzg4NHpiQlZYNW1SRjVyVXliNlJGeHJMcENTRmVHN0swT0h2TUFRPT0K",
+ "url": "https://delta.jan.ai/nightly/Jan-nightly_0.8.4-4980_x64-setup.exe"
+ },
+ "darwin-aarch64": {
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTHVFczR5MlVlTjRMQ2l5bGRBdkgwTG1mRTIvbXpBOHc1RW1ITHkrZXd1bFpJRldMbDhWYTBER1RBWTZmMVR4czFadWhsUGRuTlJoeWFQREk0OEpFV1FZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg5NTkyNDI2CWZpbGU6SmFuLW5pZ2h0bHkuYXBwLnRhci5nego4RkUwWEFTQ0dWazVqQW9GeW5oQmlMQ211di9qUkR6Vzhic2dLZWh5MDRUNm8xVFVVKzJzNlZwQXFRUnp1dUtGcUdWVWc5WUxWcElaWjF4QWVDK0pCZz09Cg==",
+ "url": "https://delta.jan.ai/nightly/Jan-nightly_0.8.4-4980.app.tar.gz"
+ },
+ "darwin-x86_64": {
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTHVFczR5MlVlTjRMQ2l5bGRBdkgwTG1mRTIvbXpBOHc1RW1ITHkrZXd1bFpJRldMbDhWYTBER1RBWTZmMVR4czFadWhsUGRuTlJoeWFQREk0OEpFV1FZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg5NTkyNDI2CWZpbGU6SmFuLW5pZ2h0bHkuYXBwLnRhci5nego4RkUwWEFTQ0dWazVqQW9GeW5oQmlMQ211di9qUkR6Vzhic2dLZWh5MDRUNm8xVFVVKzJzNlZwQXFRUnp1dUtGcUdWVWc5WUxWcElaWjF4QWVDK0pCZz09Cg==",
+ "url": "https://delta.jan.ai/nightly/Jan-nightly_0.8.4-4980.app.tar.gz"
+ },
+ "windows-aarch64": {
+ "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGdiQWt2VjlZK0wvSXN2ZDlTNythZHZCaUh4THJsRTE3TlpRNEI1UEVRT29wbWNnRkRGSjZSaEFEalYwdDdhSnBWRXk2VWhSMVJ3azdrdjVwYzJTSVFjPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg5NTkxMjE3CWZpbGU6SmFuLW5pZ2h0bHlfMC44LjQtNDk4MF9hcm02NC1zZXR1cC5leGUKckEyTEZvVTMyeWViTzFZKzJETko1TncyNFV3dHgxT205eXVPanBvc2lGcmFVbzBQdDk0a2hkZGdpaDFHVm1EYTdRbDJRSTQwdXpEUVUzRTRMSjhsQWc9PQo=",
+ "url": "https://delta.jan.ai/nightly/Jan-nightly_0.8.4-4980_arm64-setup.exe"
+ }
+ }
+}
diff --git a/scripts/fixtures/update-feeds/stable.json b/scripts/fixtures/update-feeds/stable.json
new file mode 100644
index 000000000..fbf4422e8
--- /dev/null
+++ b/scripts/fixtures/update-feeds/stable.json
@@ -0,0 +1 @@
+{"version":"0.8.4","notes":"","pub_date":"2026-07-23T02:38:33.259Z","platforms":{"linux-x86_64":{"signature":"dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGpnQTJFTzZweVF3Tm9iS0ljcHVHYkU4RVYvK3E5Ujk1YlhUbHhBWWdDQkVEeWdsRllkdmNjWGZmeGpLVTdZSmlRV3BNSUZaSmZVZlA0djlCVmRJdVEwPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg0NzczMzcwCWZpbGU6SmFuXzAuOC40X2FtZDY0LkFwcEltYWdlClhPOUJ3cDRpMG1VckZ0UmRUYUhtUjZEaytaaWFzNS8wYlJVSXNoWS8vdjVCTVBWUDZsNCsvdm1JVUxTLzFZbE1sbTVDVDB6YkZlTUwwVDNrZGlLSERRPT0K","url":"https://github.com/janhq/jan/releases/download/v0.8.4/Jan_0.8.4_amd64.AppImage"},"windows-x86_64":{"signature":"dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGh4SVJRYU83dlNibnZvS1g4Sm83UWM0UTdndmd1OSt4ZHFPNW13V1lZTjd1UEVNRXorMDN3NkpwRHZMNXhsUTkyR1ZEVml0MHFRWHJKMXA0dzNUZ2dVPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg0Nzc0MDIyCWZpbGU6SmFuXzAuOC40X3g2NC1zZXR1cC5leGUKOERYeERBVFRYUVdlamJwRlRFRXcxRnI1WjdhbkVYbUN5YmVFaE42di91d0pMdFZObkdWdHp4cTdsK0Uzdm9WODdlY1VBR25tTG5vS3VQbmlOKzdDREE9PQo=","url":"https://github.com/janhq/jan/releases/download/v0.8.4/Jan_0.8.4_x64-setup.exe"},"darwin-aarch64":{"signature":"dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGg0ajNReDd1aWpkekxTZHR6ZHFWU1ZpZ1d5T2xyenc2VTVuRFhzYWt4NXR6OVdmb1FZZEt6TWEvUDJYT0ZlYzBYd0hTWXpUREMvUGdaS0FCOGVOandrPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg0Nzc0MjcwCWZpbGU6SmFuLmFwcC50YXIuZ3oKQU91V0diblJXdmdxTkFLN0RSNUl6NHRmdjlKNzlxNXQzOEpOeE1TdjkxYUJlb1p4SVUwVDdJOVRtYXVZTTFtandlMmVsSmNOczBuSTJMUytjRUwwQ1E9PQo=","url":"https://github.com/janhq/jan/releases/download/v0.8.4/Jan.app.tar.gz"},"darwin-x86_64":{"signature":"dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVSRXJUVWE2ekJCTGg0ajNReDd1aWpkekxTZHR6ZHFWU1ZpZ1d5T2xyenc2VTVuRFhzYWt4NXR6OVdmb1FZZEt6TWEvUDJYT0ZlYzBYd0hTWXpUREMvUGdaS0FCOGVOandrPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzg0Nzc0MjcwCWZpbGU6SmFuLmFwcC50YXIuZ3oKQU91V0diblJXdmdxTkFLN0RSNUl6NHRmdjlKNzlxNXQzOEpOeE1TdjkxYUJlb1p4SVUwVDdJOVRtYXVZTTFtandlMmVsSmNOczBuSTJMUytjRUwwQ1E9PQo=","url":"https://github.com/janhq/jan/releases/download/v0.8.4/Jan.app.tar.gz"}}}
\ No newline at end of file
diff --git a/src-tauri/src/core/setup.rs b/src-tauri/src/core/setup.rs
index 627095d2e..e82182076 100644
--- a/src-tauri/src/core/setup.rs
+++ b/src-tauri/src/core/setup.rs
@@ -16,6 +16,14 @@ use crate::core::mcp::helpers::add_server_config;
use super::{mcp::helpers::run_mcp_commands, state::AppState};
+/// The MCP store schema this build writes. `migrate_mcp_servers` walks every
+/// store older than this through the gates below, then pins this value. The
+/// upgrade-compat fixture test (tests/upgrade_compat.rs) asserts committed
+/// past-release stores sit below it, so bumping this constant without adding
+/// that release's store fixture breaks the build instead of skipping a
+/// migration silently.
+pub const CURRENT_MCP_SCHEMA_VERSION: i64 = 4;
+
// Migrate MCP servers configuration
pub fn migrate_mcp_servers(
app_handle: tauri::AppHandle,
@@ -67,13 +75,15 @@ pub fn migrate_mcp_servers(
log::error!("Failed to migrate Exa to HTTP: {e}");
}
}
- if mcp_version < 4 {
- log::info!("Migrating MCP schema version 4: Removing default Exa MCP (native web search cutover)");
+ if mcp_version < CURRENT_MCP_SCHEMA_VERSION {
+ log::info!(
+ "Migrating MCP schema version {CURRENT_MCP_SCHEMA_VERSION}: Removing default Exa MCP (native web search cutover)"
+ );
if let Err(e) = remove_exa_server(app_handle) {
log::error!("Failed to remove Exa MCP server: {e}");
}
}
- store.set("mcp_version", 4);
+ store.set("mcp_version", CURRENT_MCP_SCHEMA_VERSION);
store.save().expect("Failed to save store");
Ok(())
}
@@ -111,10 +121,42 @@ fn migrate_exa_to_http(app_handle: tauri::AppHandle) -> Result<(), String> {
Ok(())
}
+/// Whether an `exa` MCP server entry is one the web-search cutover removes:
+/// not currently active, and carrying no API key.
+///
+/// Note what `active: false` does *not* mean here. It is not evidence that the
+/// user never turned the server on: 0.8.3's own `migrate_exa_to_http` wrote
+/// the entry with `active: true` and an empty `env` for everybody, so a 0.8.3
+/// upgrader fails the `inactive` half and keeps the entry. The entries this
+/// actually removes are the ones a user deactivated themselves. See
+/// `remove_exa_server` for why that is left alone for now.
+///
+/// It inspects `active` and `env` only -- not `url` or `type` -- so an inactive
+/// *custom* exa entry with an empty env also matches. Callers must reject
+/// non-object values before calling (see `remove_exa_server`).
+///
+/// `pub` for the upgrade-compat fixture test, which pins the decision against
+/// real 0.8.3 bytes.
+pub fn is_default_exa_server(exa: &serde_json::Value) -> bool {
+ let inactive = exa.get("active").and_then(|v| v.as_bool()) != Some(true);
+ let no_key = exa
+ .get("env")
+ .and_then(|env| env.as_object())
+ .map(|env| env.is_empty())
+ .unwrap_or(true);
+ inactive && no_key
+}
+
/// One-time cutover to native web search: drop the default Exa MCP server so the
-/// built-in web_search/web_fetch tools own web search. Only removes the entry if
-/// it is still the inactive default (hosted HTTP endpoint, no API key); a user who
-/// activated it or supplied their own key keeps their configuration.
+/// built-in web_search/web_fetch tools own web search.
+///
+/// Narrower than the name suggests, and deliberately left that way in this
+/// change: removal needs the entry to be inactive *and* keyless, but 0.8.3
+/// shipped it `active: true` with an empty `env`, so upgraders from 0.8.3 keep
+/// it and the cutover is close to a no-op for them. Widening the match to the
+/// hosted endpoint regardless of `active` would delete configuration for the
+/// whole installed base at next startup, so it is tracked in janhq/jan#9010
+/// rather than changed in passing.
fn remove_exa_server(app_handle: tauri::AppHandle) -> Result<(), String> {
let config_path = get_jan_data_folder_path(app_handle).join("mcp_config.json");
if !config_path.exists() {
@@ -129,19 +171,16 @@ fn remove_exa_server(app_handle: tauri::AppHandle) -> Result<(), String> {
return Ok(());
};
+ // `is_object()` is load-bearing, not defensive noise: serde_json's `get`
+ // returns None on a non-object, so without it a malformed `exa` (a string,
+ // a number, null) would read as "inactive, no key" and be deleted. Before
+ // this predicate was extracted the guard was an `.and_then(as_object)` that
+ // left such an entry alone, and this migration runs once against every
+ // user's config at startup -- it must not start deleting things it used to
+ // skip.
let is_default_exa = servers
.get("exa")
- .and_then(|exa| exa.as_object())
- .map(|exa| {
- let inactive = exa.get("active").and_then(|v| v.as_bool()) != Some(true);
- let no_key = exa
- .get("env")
- .and_then(|env| env.as_object())
- .map(|env| env.is_empty())
- .unwrap_or(true);
- inactive && no_key
- })
- .unwrap_or(false);
+ .is_some_and(|exa| exa.is_object() && is_default_exa_server(exa));
if is_default_exa {
servers.remove("exa");
diff --git a/src-tauri/tests/fixtures/upgrade/0.8.3/mcp_config.json b/src-tauri/tests/fixtures/upgrade/0.8.3/mcp_config.json
new file mode 100644
index 000000000..c29bd5057
--- /dev/null
+++ b/src-tauri/tests/fixtures/upgrade/0.8.3/mcp_config.json
@@ -0,0 +1,66 @@
+{
+ "mcpServers": {
+ "Jan Browser MCP": {
+ "command": "npx",
+ "args": ["-y", "search-mcp-server@latest"],
+ "env": {
+ "BRIDGE_HOST": "127.0.0.1",
+ "BRIDGE_PORT": "17389"
+ },
+ "active": false,
+ "official": true
+ },
+ "exa": {
+ "type": "http",
+ "url": "https://mcp.exa.ai/mcp",
+ "command": "",
+ "args": [],
+ "env": {},
+ "active": true
+ },
+ "browsermcp": {
+ "command": "npx",
+ "args": ["@browsermcp/mcp"],
+ "env": {},
+ "active": false
+ },
+ "fetch": {
+ "command": "uvx",
+ "args": ["mcp-server-fetch"],
+ "env": {},
+ "active": false
+ },
+ "serper": {
+ "command": "npx",
+ "args": ["-y", "serper-search-scrape-mcp-server"],
+ "env": { "SERPER_API_KEY": "YOUR_SERPER_API_KEY_HERE" },
+ "active": false
+ },
+ "filesystem": {
+ "command": "npx",
+ "args": [
+ "-y",
+ "@modelcontextprotocol/server-filesystem",
+ "/path/to/other/allowed/dir"
+ ],
+ "env": {},
+ "active": false
+ },
+ "sequential-thinking": {
+ "command": "npx",
+ "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"],
+ "env": {},
+ "active": false
+ }
+ },
+ "mcpSettings": {
+ "toolCallTimeoutSeconds": 30,
+ "baseRestartDelayMs": 1000,
+ "maxRestartDelayMs": 30000,
+ "backoffMultiplier": 2.0,
+ "enableSmartToolRouting": true,
+ "useLightweightRouterModel": false,
+ "routerModelProvider": "",
+ "routerModelId": ""
+ }
+}
\ No newline at end of file
diff --git a/src-tauri/tests/fixtures/upgrade/0.8.3/store.json b/src-tauri/tests/fixtures/upgrade/0.8.3/store.json
new file mode 100644
index 000000000..cf867a400
--- /dev/null
+++ b/src-tauri/tests/fixtures/upgrade/0.8.3/store.json
@@ -0,0 +1,4 @@
+{
+ "version": "0.8.3",
+ "mcp_version": 3
+}
\ No newline at end of file
diff --git a/src-tauri/tests/fixtures/upgrade/0.8.3/threads/1fa772e9-47e5-4a8c-a664-4b1cef37c5aa/messages.jsonl b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/1fa772e9-47e5-4a8c-a664-4b1cef37c5aa/messages.jsonl
new file mode 100644
index 000000000..d9422368d
--- /dev/null
+++ b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/1fa772e9-47e5-4a8c-a664-4b1cef37c5aa/messages.jsonl
@@ -0,0 +1,2 @@
+{"completed_at":1789721235436,"content":[{"text":{"annotations":[],"value":"QA thread 2 on v0.8.3 - second data point"},"type":"text"}],"created_at":1789721235436,"id":"ems4ieYjTtZNIiLH","object":"thread.message","role":"user","status":"ready","thread_id":"1fa772e9-47e5-4a8c-a664-4b1cef37c5aa","type":"text"}
+{"completed_at":1789721235453,"content":[{"text":{"annotations":[],"value":"QA reply at 15:47:15 to: QA thread 2 on v0.8.3 - second data point "},"type":"text"}],"created_at":1789721235453,"id":"tB32lnM1PUctKSTo","metadata":{"finishReason":"other","tokenSpeed":{"durationMs":5,"tokenCount":0,"tokenSpeed":0},"usage":{"outputTokens":0,"totalTokens":0}},"object":"thread.message","role":"assistant","status":"ready","thread_id":"1fa772e9-47e5-4a8c-a664-4b1cef37c5aa","type":"text"}
diff --git a/src-tauri/tests/fixtures/upgrade/0.8.3/threads/1fa772e9-47e5-4a8c-a664-4b1cef37c5aa/thread.json b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/1fa772e9-47e5-4a8c-a664-4b1cef37c5aa/thread.json
new file mode 100644
index 000000000..768d3e95f
--- /dev/null
+++ b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/1fa772e9-47e5-4a8c-a664-4b1cef37c5aa/thread.json
@@ -0,0 +1,47 @@
+{
+ "assistants": [
+ {
+ "avatar": "👋",
+ "created_at": 1788928242.578,
+ "description": "Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user’s behalf.",
+ "file_ids": [],
+ "id": "jan",
+ "instructions": "You must output your response in the exact language used in the latest user message. Do not provide translations or switch languages unless explicitly instructed to do so. If the input is mostly English, respond in English.\n\nWhen handling user queries:\n\n1. Think step by step about the query:\n - Break complex questions into smaller, searchable parts\n - Identify key search terms and parameters\n - Consider what information is needed to provide a complete answer\n\n2. Mandatory logical analysis:\n - Before engaging any tools, articulate your complete thought process in natural language. You must act as a \"professional tool caller,\" demonstrating rigorous logic.\n - Analyze the information gap: explicitly state what data is missing.\n - Derive the strategy: explain why a specific tool is the logical next step.\n - Justify parameters: explain why you chose those specific search keywords or that specific URL.\n\nYou have tools to search for and access real-time, up-to-date data. Use them. Search before stating that you can't or don't know.\n\nCurrent date: {{current_date}}",
+ "model": {
+ "engine": "qa-mock",
+ "id": "mock-qa-model"
+ },
+ "name": "Jan",
+ "object": "assistant",
+ "parameters": {
+ "repeat_penalty": 1.12,
+ "temperature": 0.7,
+ "top_k": 20,
+ "top_p": 0.8
+ },
+ "tools": [
+ {
+ "enabled": false,
+ "settings": {
+ "chunk_overlap": 64,
+ "chunk_size": 1024,
+ "retrieval_template": "Use the following pieces of context to answer the question at the end.\n----------------\nCONTEXT: {CONTEXT}\n----------------\nQUESTION: {QUESTION}\n----------------\nHelpful Answer:",
+ "top_k": 2
+ },
+ "type": "retrieval",
+ "useTimeWeightedRetriever": false
+ }
+ ]
+ }
+ ],
+ "created": 1789721235.463,
+ "id": "1fa772e9-47e5-4a8c-a664-4b1cef37c5aa",
+ "metadata": {},
+ "model": {
+ "id": "mock-qa-model",
+ "provider": "qa-mock"
+ },
+ "object": "thread",
+ "title": "QA reply at 154715 to Summarize the following conversation into",
+ "updated": 1789721235.463
+}
\ No newline at end of file
diff --git a/src-tauri/tests/fixtures/upgrade/0.8.3/threads/784952d3-dc72-474e-ab24-0d78e7035280/messages.jsonl b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/784952d3-dc72-474e-ab24-0d78e7035280/messages.jsonl
new file mode 100644
index 000000000..8c8131ddf
--- /dev/null
+++ b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/784952d3-dc72-474e-ab24-0d78e7035280/messages.jsonl
@@ -0,0 +1,2 @@
+{"completed_at":1789721206948,"content":[{"text":{"annotations":[],"value":"QA thread 1 created on v0.8.3 - confirm mock roundtrip"},"type":"text"}],"created_at":1789721206948,"id":"AegNhoPJnR2OVJ0q","object":"thread.message","role":"user","status":"ready","thread_id":"784952d3-dc72-474e-ab24-0d78e7035280","type":"text"}
+{"completed_at":1789721206977,"content":[{"text":{"annotations":[],"value":"QA reply at 15:46:46 to: QA thread 1 created on v0.8.3 - confirm mock roundtrip "},"type":"text"}],"created_at":1789721206977,"id":"g7vb8J6r09ph7aZr","metadata":{"finishReason":"other","tokenSpeed":{"durationMs":5,"tokenCount":0,"tokenSpeed":0},"usage":{"outputTokens":0,"totalTokens":0}},"object":"thread.message","role":"assistant","status":"ready","thread_id":"784952d3-dc72-474e-ab24-0d78e7035280","type":"text"}
diff --git a/src-tauri/tests/fixtures/upgrade/0.8.3/threads/784952d3-dc72-474e-ab24-0d78e7035280/thread.json b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/784952d3-dc72-474e-ab24-0d78e7035280/thread.json
new file mode 100644
index 000000000..2d930a56d
--- /dev/null
+++ b/src-tauri/tests/fixtures/upgrade/0.8.3/threads/784952d3-dc72-474e-ab24-0d78e7035280/thread.json
@@ -0,0 +1,47 @@
+{
+ "assistants": [
+ {
+ "avatar": "👋",
+ "created_at": 1788928242.578,
+ "description": "Jan is a helpful desktop assistant that can reason through complex tasks and use tools to complete them on the user’s behalf.",
+ "file_ids": [],
+ "id": "jan",
+ "instructions": "You must output your response in the exact language used in the latest user message. Do not provide translations or switch languages unless explicitly instructed to do so. If the input is mostly English, respond in English.\n\nWhen handling user queries:\n\n1. Think step by step about the query:\n - Break complex questions into smaller, searchable parts\n - Identify key search terms and parameters\n - Consider what information is needed to provide a complete answer\n\n2. Mandatory logical analysis:\n - Before engaging any tools, articulate your complete thought process in natural language. You must act as a \"professional tool caller,\" demonstrating rigorous logic.\n - Analyze the information gap: explicitly state what data is missing.\n - Derive the strategy: explain why a specific tool is the logical next step.\n - Justify parameters: explain why you chose those specific search keywords or that specific URL.\n\nYou have tools to search for and access real-time, up-to-date data. Use them. Search before stating that you can't or don't know.\n\nCurrent date: {{current_date}}",
+ "model": {
+ "engine": "qa-mock",
+ "id": "mock-qa-model"
+ },
+ "name": "Jan",
+ "object": "assistant",
+ "parameters": {
+ "repeat_penalty": 1.12,
+ "temperature": 0.7,
+ "top_k": 20,
+ "top_p": 0.8
+ },
+ "tools": [
+ {
+ "enabled": false,
+ "settings": {
+ "chunk_overlap": 64,
+ "chunk_size": 1024,
+ "retrieval_template": "Use the following pieces of context to answer the question at the end.\n----------------\nCONTEXT: {CONTEXT}\n----------------\nQUESTION: {QUESTION}\n----------------\nHelpful Answer:",
+ "top_k": 2
+ },
+ "type": "retrieval",
+ "useTimeWeightedRetriever": false
+ }
+ ]
+ }
+ ],
+ "created": 1789721206.991,
+ "id": "784952d3-dc72-474e-ab24-0d78e7035280",
+ "metadata": {},
+ "model": {
+ "id": "mock-qa-model",
+ "provider": "qa-mock"
+ },
+ "object": "thread",
+ "title": "QA reply at 154646 to Summarize the following conversation into",
+ "updated": 1789721206.991
+}
\ No newline at end of file
diff --git a/src-tauri/tests/upgrade_compat.rs b/src-tauri/tests/upgrade_compat.rs
new file mode 100644
index 000000000..0ffafdf21
--- /dev/null
+++ b/src-tauri/tests/upgrade_compat.rs
@@ -0,0 +1,282 @@
+//! Upgrade-path compatibility: data written by past releases must stay
+//! readable by current code.
+//!
+//! Everything under `tests/fixtures/upgrade/` is real bytes written by the
+//! named release (0.8.3 stable on Windows for `store.json` and
+//! `mcp_config.json`, 0.8.3 stable on macOS for the thread files), committed
+//! so a schema drift that would silently eat user data fails here instead of
+//! on a user machine. Threads are plain per-thread JSON/JSONL files; the store
+//! marks the MCP schema version (3 on 0.8.3, 4 from 0.8.4) that
+//! `core/setup.rs migrate_mcp_servers` migrates against.
+//!
+//! When a release intentionally changes one of these schemas, commit the old
+//! release's output as a new fixture directory under
+//! `tests/fixtures/upgrade/<release>/` and add assertions for it (pass that
+//! directory to `fixture_root`); update an existing fixture only when the
+//! current schema itself is being pinned, never to make a test pass.
+
+// `core::setup` is desktop-only -- `core/mod.rs` gates it out of
+// `--features cli`, which builds this test target too. The fixtures are
+// desktop data folders, so the suite belongs to the desktop build.
+#![cfg(not(feature = "cli"))]
+
+use app_lib::core::mcp::models::McpSettings;
+use app_lib::core::setup::{is_default_exa_server, CURRENT_MCP_SCHEMA_VERSION};
+use app_lib::core::threads::helpers::read_messages_from_file;
+use app_lib::core::threads::utils::{get_messages_path, get_thread_dir, get_thread_metadata_path};
+use serde_json::Value;
+use std::path::PathBuf;
+
+/// Root of a committed release data-folder fixture. Mirrors the layout of
+/// `~/Library/Application Support/Jan/data` (macOS) / `%APPDATA%\Jan\data`
+/// (Windows): `threads/<id>/{thread.json,messages.jsonl}`, `store.json`,
+/// `mcp_config.json`.
+fn fixture_root(release: &str) -> PathBuf {
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures/upgrade")
+ .join(release)
+}
+
+/// Every committed release fixture, oldest first. Discovered rather than
+/// listed because the tripwire below exists to demand a new fixture on a
+/// schema bump -- if it also demanded an edit here, the edit is the thing that
+/// would get forgotten.
+fn fixture_releases() -> Vec<String> {
+ let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/upgrade");
+ let mut releases: Vec<(Vec<u64>, String)> = std::fs::read_dir(&root)
+ .unwrap_or_else(|e| panic!("upgrade fixture root {root:?} unreadable: {e}"))
+ .map(|entry| entry.expect("fixture directory entry must be readable"))
+ .filter(|entry| entry.path().is_dir())
+ .map(|entry| {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ // Sort on the parsed components, not the string: "0.8.10" must
+ // come after "0.8.9", which it does not lexicographically.
+ let parts = name
+ .split('.')
+ .map(|part| {
+ part.parse().unwrap_or_else(|_| {
+ panic!("fixture directory {name:?} is not a dotted release version")
+ })
+ })
+ .collect();
+ (parts, name)
+ })
+ .collect();
+ assert!(
+ !releases.is_empty(),
+ "no release fixtures under {root:?} -- this suite would pass vacuously"
+ );
+ releases.sort();
+ releases.into_iter().map(|(_, name)| name).collect()
+}
+
+/// `mcp_version` from a release fixture's `store.json`, checking on the way
+/// that the directory name and the release the store records agree.
+fn fixture_mcp_version(release: &str) -> i64 {
+ let path = fixture_root(release).join("store.json");
+ let raw = std::fs::read_to_string(&path)
+ .unwrap_or_else(|e| panic!("{release} store.json fixture missing at {path:?}: {e}"));
+ let store: Value = serde_json::from_str(&raw)
+ .unwrap_or_else(|e| panic!("{release} store.json must parse: {e}"));
+ assert_eq!(
+ store["version"].as_str(),
+ Some(release),
+ "fixture directory {release} holds a store.json written by a different release"
+ );
+ store["mcp_version"].as_i64().unwrap_or(0)
+}
+
+fn read_thread_metadata(release: &str, thread_id: &str) -> Value {
+ let path = get_thread_metadata_path(&fixture_root(release), thread_id);
+ let raw = std::fs::read_to_string(&path)
+ .unwrap_or_else(|e| panic!("{release} thread metadata {path:?} unreadable: {e}"));
+ serde_json::from_str(&raw).expect("thread.json must parse as JSON")
+}
+
+fn read_all_messages(release: &str, thread_id: &str) -> Vec<Value> {
+ // The reader returns Ok(vec![]) for a missing file, which would turn a
+ // layout-constant drift into a confusing downstream length failure —
+ // assert the resolved path exists first so the cause is named.
+ let path = get_messages_path(&fixture_root(release), thread_id);
+ assert!(
+ path.exists(),
+ "{release} messages file missing at {path:?} — layout constant drifted"
+ );
+ read_messages_from_file(&fixture_root(release), thread_id)
+ .unwrap_or_else(|e| panic!("{release} messages for {thread_id} failed to parse: {e}"))
+}
+
+#[test]
+fn threads_written_by_0_8_3_resolve_and_parse() {
+ let thread_ids = [
+ "1fa772e9-47e5-4a8c-a664-4b1cef37c5aa",
+ "784952d3-dc72-474e-ab24-0d78e7035280",
+ ];
+ for id in thread_ids {
+ let dir = get_thread_dir(&fixture_root("0.8.3"), id);
+ assert!(dir.is_dir(), "0.8.3 thread dir {id} missing from fixtures");
+ let metadata = read_thread_metadata("0.8.3", id);
+ assert_eq!(
+ metadata["object"], "thread",
+ "0.8.3 thread.json lost its `object` discriminator"
+ );
+ assert!(
+ metadata["title"].is_string(),
+ "0.8.3 thread.json lost its `title`"
+ );
+ assert!(
+ !metadata["assistants"]
+ .as_array()
+ .expect("assistants")
+ .is_empty(),
+ "0.8.3 thread.json carried a default assistant; schema must keep parsing it"
+ );
+ }
+}
+
+#[test]
+fn messages_written_by_0_8_3_round_trip_through_the_current_reader() {
+ // Seeded during the 0.8.3 QA run: user message plus the mock provider's
+ // reply. Both turns must survive the current JSONL reader.
+ let messages = read_all_messages("0.8.3", "784952d3-dc72-474e-ab24-0d78e7035280");
+ assert!(
+ messages.len() >= 2,
+ "0.8.3 thread should have at least a user and an assistant turn"
+ );
+ assert_eq!(messages[0]["role"], "user");
+ assert_eq!(messages[1]["role"], "assistant");
+ // 0.8.3 content shape: content[0] = {type: "text", text: {value: "..."}}.
+ let user_text = messages[0]["content"][0]["text"]["value"]
+ .as_str()
+ .expect("0.8.3 user message text must be readable");
+ assert!(
+ user_text.contains("QA thread 1"),
+ "0.8.3 message content drifted: {user_text}"
+ );
+}
+
+#[test]
+fn thread_dir_layout_matches_current_path_resolution() {
+ // get_thread_dir/get_messages_path are what every reader resolves through;
+ // if the layout constants drift (e.g. `threads` renamed), this fails.
+ let id = "1fa772e9-47e5-4a8c-a664-4b1cef37c5aa";
+ assert!(get_thread_dir(&fixture_root("0.8.3"), id).is_dir());
+ let messages = read_all_messages("0.8.3", id);
+ assert!(
+ !messages.is_empty(),
+ "0.8.3 messages must not read as empty"
+ );
+}
+
+#[test]
+fn every_store_fixture_sits_inside_the_migration_range() {
+ let releases = fixture_releases();
+
+ // `migrate_mcp_servers` (core/setup.rs) only walks stores *below*
+ // CURRENT_MCP_SCHEMA_VERSION through the gates, so a fixture at or above it
+ // would sit outside the migration path this suite exists to cover and
+ // assert nothing.
+ for release in &releases {
+ let mcp_version = fixture_mcp_version(release);
+ assert!(
+ mcp_version < CURRENT_MCP_SCHEMA_VERSION,
+ "{release} fixture carries mcp_version {mcp_version}, which the current schema \
+ ({CURRENT_MCP_SCHEMA_VERSION}) no longer migrates"
+ );
+ }
+
+ // The newest fixture is pinned at exactly CURRENT - 1, and that is the
+ // whole point of this test. `<` is satisfied by 3 < 5 just as well as by
+ // 3 < 4, so it would stay green through a schema bump and guard nothing --
+ // it only ever fired if the constant were *lowered*. Pinning the gap at
+ // exactly one release means bumping the constant fails here until the
+ // newly-superseded release's store output is committed as a fixture, which
+ // is the coverage this file exists to keep.
+ let newest = releases
+ .last()
+ .expect("fixture_releases rejects an empty set");
+ let newest_version = fixture_mcp_version(newest);
+ assert_eq!(
+ newest_version,
+ CURRENT_MCP_SCHEMA_VERSION - 1,
+ "the newest upgrade fixture ({newest}) carries mcp_version {newest_version}, but the \
+ current schema is {CURRENT_MCP_SCHEMA_VERSION}. If you just bumped \
+ CURRENT_MCP_SCHEMA_VERSION, commit the store.json written by the release that shipped \
+ schema {} as a new fixture directory under tests/fixtures/upgrade/.",
+ CURRENT_MCP_SCHEMA_VERSION - 1
+ );
+}
+
+#[test]
+fn mcp_config_written_by_0_8_3_parses_with_current_settings_schema() {
+ let raw = std::fs::read_to_string(fixture_root("0.8.3").join("mcp_config.json"))
+ .expect("0.8.3 mcp_config.json fixture missing");
+ let config: Value = serde_json::from_str(&raw).expect("0.8.3 mcp_config.json must parse");
+
+ // `mcpSettings` (0.8.3) deserializes into the current typed settings.
+ let settings: McpSettings = serde_json::from_value(config["mcpSettings"].clone())
+ .expect("0.8.3 mcpSettings must deserialize into the current McpSettings schema");
+ assert_eq!(settings.tool_call_timeout_seconds, 30);
+ assert_eq!(settings.backoff_multiplier, 2.0);
+
+ // Those two asserts cannot catch a renamed key, which is what makes the
+ // synthetic case below necessary rather than belt-and-braces. 0.8.3 stored
+ // the shipped defaults, and every McpSettings field carries
+ // `#[serde(default)]`, so a rename degrades to a value identical to the one
+ // the fixture holds and both asserts above stay green.
+ //
+ // Non-default values keyed by the same names do bite: if
+ // `toolCallTimeoutSeconds` or `backoffMultiplier` is renamed, these fall
+ // back to 30 and 2.0 and fail.
+ let renamed_probe: McpSettings = serde_json::from_value(serde_json::json!({
+ "toolCallTimeoutSeconds": 90,
+ "backoffMultiplier": 3.5,
+ }))
+ .expect("the current McpSettings schema must accept 0.8.3's camelCase keys");
+ assert_eq!(
+ renamed_probe.tool_call_timeout_seconds, 90,
+ "toolCallTimeoutSeconds no longer maps onto tool_call_timeout_seconds"
+ );
+ assert_eq!(
+ renamed_probe.backoff_multiplier, 3.5,
+ "backoffMultiplier no longer maps onto backoff_multiplier"
+ );
+
+ // Migration 4 removes only an exa entry that is inactive *and* keyless.
+ //
+ // What the fixture actually is, stated carefully because the obvious
+ // reading is wrong: 0.8.3's own `migrate_exa_to_http` wrote this entry with
+ // `active: true` (`git show v0.8.3:src-tauri/src/core/setup.rs`), so it is
+ // byte-for-byte 0.8.3's *default*, not evidence that a user activated
+ // anything. The contract pinned below is therefore "an exa entry as 0.8.3
+ // left it survives the 0.8.4 cutover" -- true precisely because 0.8.3's
+ // default is active.
+ //
+ // That is recorded as current behaviour, not endorsed: 0.8.3 wrote this
+ // shape for every user, so the cutover is close to a no-op for the whole
+ // 0.8.3 population. Widening it is a separate change against the shipping
+ // migration -- see janhq/jan#9010 and the note on `remove_exa_server`.
+ // If that widening lands, this assertion is expected to flip, and
+ // flipping it is the signal that the behaviour changed rather than a
+ // regression.
+ let servers = config["mcpServers"].as_object().expect("mcpServers object");
+ let fixture_exa = servers
+ .get("exa")
+ .expect("0.8.3 config carried an exa entry");
+ assert!(
+ !is_default_exa_server(fixture_exa),
+ "an exa entry as 0.8.3 wrote it must not be classified as the removable default"
+ );
+ let untouched_default = serde_json::json!({
+ "type": "http",
+ "url": "https://mcp.exa.ai/mcp",
+ "command": "",
+ "args": [],
+ "env": {},
+ "active": false
+ });
+ assert!(
+ is_default_exa_server(&untouched_default),
+ "the never-activated default exa entry is what migration 4 removes"
+ );
+}
diff --git a/vitest.config.ts b/vitest.config.ts
index dbadbfe52..40a601ff6 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -34,6 +34,12 @@ export default defineConfig({
// 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/**',
+ // The release-check scripts are run by node from workflows, never
+ // imported by a vitest suite, so they read as fully uncovered. Scoped
+ // to `check-*` rather than the whole tree so that a future `scripts/`
+ // module which is imported does not get dropped from the report by
+ // accident.
+ 'scripts/check-*.mjs',
],
},
},
diff --git a/web-app/src/components/left-sidebar/NavMain.tsx b/web-app/src/components/left-sidebar/NavMain.tsx
index 6ad7b0822..3362b8d34 100644
--- a/web-app/src/components/left-sidebar/NavMain.tsx
+++ b/web-app/src/components/left-sidebar/NavMain.tsx
@@ -63,6 +63,8 @@ type NavMainItem = {
isActive?: boolean
shortcut?: React.ReactNode
onClick?: () => void
+ /** Emitted as `data-testid` on the rendered control; see e2e/README.md. */
+ testId?: string
}
const getNavMainItems = (
@@ -75,6 +77,7 @@ const getNavMainItems = (
title: 'common:newChat',
animatedIcon: MessageCircleIcon,
onClick: onNewChat,
+ testId: 'new-chat-button',
shortcut: (
<KbdGroup className="ml-auto scale-90 gap-0">
<Kbd className="bg-transparent size-3">
@@ -158,6 +161,7 @@ function NavMainItemWithAnimatedIcon({
<SidebarMenuButton
asChild={!!item.url}
isActive={item.isActive}
+ data-testid={item.testId}
onMouseEnter={() => iconRef.current?.startAnimation()}
onMouseLeave={() => iconRef.current?.stopAnimation()}
onClick={item.onClick}
@@ -217,6 +221,7 @@ export function NavMain() {
<SidebarMenuButton
asChild={!!item.url}
isActive={item.isActive}
+ data-testid={item.testId}
onClick={item.onClick}
>
{item.url ? (
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index d3ea901b8..23515edc2 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -2920,6 +2920,7 @@ const ChatInput = memo(function ChatInput({
<Button
variant="destructive"
size="icon-sm"
+ data-testid="stop-message-button"
className="rounded-full mr-1 mb-1"
onClick={() => {
// Stopping with messages queued clears the queue —
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 2e0038f4e..3a33a90d2 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -510,6 +510,7 @@ export const MessageItem = memo(
<div className="flex items-center gap-0.5 text-muted-foreground">
<button
type="button"
+ data-testid="message-version-prev"
className="hover:text-foreground disabled:opacity-40"
disabled={versionInfo.index <= 1}
onClick={() => onSwitchVersion(message.id, -1)}
@@ -517,11 +518,12 @@ export const MessageItem = memo(
>
<IconChevronLeft size={14} />
</button>
- <span className="tabular-nums">
+ <span data-testid="message-version-counter" className="tabular-nums">
{versionInfo.index}/{versionInfo.count}
</span>
<button
type="button"
+ data-testid="message-version-next"
className="hover:text-foreground disabled:opacity-40"
disabled={versionInfo.index >= versionInfo.count}
onClick={() => onSwitchVersion(message.id, 1)}
@@ -703,6 +705,7 @@ export const MessageItem = memo(
<Button
variant="ghost"
size="icon-xs"
+ data-testid="continue-message"
onClick={handleContinue}
title={t('chat:actions.continue')}
>
@@ -717,6 +720,7 @@ export const MessageItem = memo(
<Button
variant="ghost"
size="icon-xs"
+ data-testid="regenerate-message"
onClick={handleRegenerate}
title={t('chat:actions.regenerate')}
>
diff --git a/web-app/src/containers/dialogs/DeleteMessageDialog.tsx b/web-app/src/containers/dialogs/DeleteMessageDialog.tsx
index a73dbc4a6..7c9201e06 100644
--- a/web-app/src/containers/dialogs/DeleteMessageDialog.tsx
+++ b/web-app/src/containers/dialogs/DeleteMessageDialog.tsx
@@ -39,6 +39,7 @@ export function DeleteMessageDialog({ onDelete }: DeleteMessageDialogProps) {
size="icon-xs"
role="button"
tabIndex={0}
+ data-testid="delete-message-trigger"
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
@@ -54,6 +55,7 @@ export function DeleteMessageDialog({ onDelete }: DeleteMessageDialogProps) {
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>{trigger}</DialogTrigger>
<DialogContent
+ data-testid="delete-message-dialog"
onOpenAutoFocus={(e) => {
e.preventDefault()
deleteButtonRef.current?.focus()
@@ -78,6 +80,7 @@ export function DeleteMessageDialog({ onDelete }: DeleteMessageDialogProps) {
onKeyDown={handleKeyDown}
size="sm"
className="w-full sm:w-auto"
+ data-testid="confirm-delete-message"
aria-label={t('common:deleteMessage')}
>
{t('common:delete')}
diff --git a/web-app/src/containers/dialogs/EditMessageDialog.tsx b/web-app/src/containers/dialogs/EditMessageDialog.tsx
index 792145e4d..7c4e5e191 100644
--- a/web-app/src/containers/dialogs/EditMessageDialog.tsx
+++ b/web-app/src/containers/dialogs/EditMessageDialog.tsx
@@ -85,6 +85,7 @@ export function EditMessageDialog({
size="icon-xs"
role="button"
tabIndex={0}
+ data-testid="edit-message-trigger"
disabled={!selectedModel}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -100,7 +101,7 @@ export function EditMessageDialog({
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>{triggerElement || defaultTrigger}</DialogTrigger>
- <DialogContent>
+ <DialogContent data-testid="edit-message-dialog">
<DialogHeader>
<DialogTitle>{t('common:dialogs.editMessage.title')}</DialogTitle>
{(keptImages.length > 0 || keptFiles.length > 0) && (
@@ -154,6 +155,7 @@ export function EditMessageDialog({
)}
<Textarea
dir="auto"
+ data-testid="edit-message-input"
ref={textareaRef}
value={draft}
onChange={(e) => setDraft(e.target.value)}
@@ -179,6 +181,7 @@ export function EditMessageDialog({
}
onClick={handleSave}
size="sm"
+ data-testid="edit-message-save"
className="w-full sm:w-auto"
>
{t('common:save')}