Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
test(e2e): add two-launch legacy profile migration smoke (#9464)
James Dam87d4786bcb00
diff --git a/e2e/README.md b/e2e/README.mdindex 6927e3535..d88160fa1 100644--- a/e2e/README.md+++ b/e2e/README.md@@ -180,8 +180,9 @@ server ever bound.## Isolation-Each run gets a throwaway profile in a temp dir, so tests never touch real Jan-data. The desktop app resolves its data folder from+Each run gets a throwaway profile in a temp dir to redirect Jan application+data. This is not complete isolation: macOS WebKit storage and the other gaps+below can still touch the real user profile. The desktop app resolves its data folder from`core::app::paths::data_dir()`; which variables that leaves you needing tooverride depends on the platform.@@ -191,6 +192,25 @@ override depends on the platform.| Linux | `$XDG_DATA_HOME`, else `$HOME/.local/share` | `HOME` **and** `XDG_DATA_HOME` || Windows | `FOLDERID_RoamingAppData` | nothing the OS provides — see below |+### Known macOS WebKit gap — follow-up++HOME redirection does **not** isolate WKWebView localStorage. In native macOS+arm64 validation on [#9457](https://github.com/janhq/jan/pull/9457) and+[#9464](https://github.com/janhq/jan/pull/9464), thinhlpg observed writes under the+real `~/Library/WebKit/<bundle id>/WebsiteData/Default/.../LocalStorage/`+(`jan.ai.app`), shared with an installed Jan. The redirected profile contained+no `Library/WebKit`; `Library/Caches/jan.ai.app` did redirect. Therefore both+normal and migration launches may read or modify installed-Jan browser state;+a passing migration smoke does not prove browser-storage isolation or migration.+Use a disposable macOS account/VM for separation, not merely `JAN_E2E_HOME`.++**Follow-up ([jan-internal#496](https://github.com/janhq/jan-internal/issues/496),+not fixed here):** isolate macOS e2e WebKit storage, evaluating a+distinct e2e bundle identifier, and verify with real installed-Jan storage that+launches do not touch it. The possible connection to a missing setup wizard on+an already-used Mac is unproven. This PR changes neither bundle IDs nor WebKit+storage behavior.+### Launch guard (limited guarantee)Before profile seeding, recursive cleanup registration, or launch,@@ -222,7 +242,7 @@ than `Jan` (including empty) are rejected too.This is an accidental-launch guard, **not a filesystem sandbox** or a proof ofcomplete confinement. It does not prevent concurrent symlink changes, hard-linkaliases, every possible legacy/plugin/config escape, Windows registry folder-redirection, or the Windows CLI/updater gaps below. Use a disposable OS account+redirection, the macOS WebKit gap, or the Windows CLI/updater gaps below. Use a disposable OS accountor VM if stronger separation is needed. Existing profiles should be disposable;the harness merges a bootstrap seed into their backend settings.@@ -676,3 +696,63 @@ Those lines no longer reach the terminal at all: `outputDir` sends the driverlog to `logs/<spec>-<cid>.log` instead of the console, so what you see live isthe spec reporter alone. The lines are still worth reading when something doesfail — that file is where the last attempt before the give-up is recorded.++## Migration smoke (separate scenario)++After building the same debug `e2e` binary described above:++```bash+cd e2e+xvfb-run -a yarn test:migration # Linux; omit xvfb-run on macOS/Windows+```++This copies the committed `src-tauri/tests/fixtures/upgrade/0.8.3` contents+(store, MCP config and two threads) into its own fresh guarded temporary+profile. It requires schema 3 and an Exa entry before starting. It launches+**two sequential WDIO commands / real desktop processes**, with the same+profile and no reseeding between them. The embedded driver port must be closed+before the first launch and after each launch; a still-listening process is+never killed by name or by port. A failed first phase stops the run.++Both starts assert on disk: schema 5, exactly the fixture MCP config minus Exa+(all other servers and settings unchanged), and all fixture thread IDs,+metadata, message IDs and content preserved. Both navigate to historical thread+`784952d3-dc72-474e-ab24-0d78e7035280` and assert its user and assistant text.+There is no provider setup, model download or inference request. The embedder+bootstrap suppression flag is seeded once; incidental app metadata requests+are not blocked, so this is not an offline/network-isolation test.++`JAN_E2E_SCENARIO` accepts only `default` (the existing five specs) or `migration`+(only `migration.e2e.ts`); use the runner, not a hand-exported migration scenario.+`test:migration` rejects inherited `JAN_E2E_HOME` and+`JAN_E2E_EMBEDDER_DOWNLOAD`. It uses the same launch safety guard as the default+suite. On failure/interruption the owned profile and phase-specific runner and+WDIO logs remain under the printed temporary path. On success it removes them+unless `JAN_E2E_KEEP=1`. The migration runner directly spawns and retains handles+for the app and WDIO; the migration config disables the service launcher to avoid+a second app. It waits for the embedded `/status` readiness before starting WDIO.+The spec then waits for the historical sidebar row (thread-store hydration), not+merely `#root`, before navigating to the historical conversation.++SIGINT/SIGTERM and the ten-minute phase deadline cancel startup or execution and+await cleanup of both owned roots. Unix sends TERM then KILL after five seconds;+Windows invokes bounded `taskkill /PID <owned-live-root> /T /F` before the root+exits, rather than force-killing WDIO and losing its tree. No PID is discovered+from a port, log, process name, or PID file; no detached processes/groups or broad+image-name kills are used. Each phase also requires the driver port to close.+Any failure or uncertain teardown retains the profile. This is a guarantee for+tracked roots and driver closure, **not** proof that every Unix grandchild has+exited: Unix app/worker descendants are not independently enumerated. SIGKILL of+the runner, machine shutdown, or already-orphaned Windows descendants cannot be+reliably cleaned up by this harness. Retained profiles are evidence, not a claim+that every possible orphan was terminated. Injectable lifecycle tests cover+startup/run cancellation, real short-deadline automatic cancellation, escalation,+and cleanup failure. Work and teardown failures are retained together (including+the driver-port closure barrier), rather than cleanup masking the original error.++This covers startup migrations and persistence across a second process start,+not an installer upgrade, old binary execution, browser localStorage migration,+provider credential migration, or an exhaustive upgrade matrix. The fixture is+not a copy of an OS browser profile. `yarn test:unit` exercises fixture comparison,+strict scenario selection, and launch/barrier ordering without starting Jan;+it does not substitute for the desktop smoke.diff --git a/e2e/isolation.ts b/e2e/isolation.tsindex c899e5534..e8a52b765 100644--- a/e2e/isolation.ts+++ b/e2e/isolation.ts@@ -79,6 +79,15 @@ import { join } from 'node:path'* (`jan.ai.app`) and not on the executable name, so an unconfined test run and* an installed Jan share one browser profile.*+ * macOS gap: HOME does not redirect WKWebView localStorage. Native validation+ * by thinhlpg on PRs #9457/#9464 observed writes in the real account's+ * ~/Library/WebKit/<bundle id>/WebsiteData/Default/.../LocalStorage, shared+ * with installed Jan (jan.ai.app), not in the temporary profile. Both normal+ * and migration launches can touch that state. Follow-up: isolate WebKit+ * storage (jan-internal#496; evaluate a distinct e2e bundle ID) and verify+ * that launches leave real-profile storage untouched. This is not fixed here.+ * Use a disposable macOS account/VM for stronger separation.+ ** Deliberately absent:* - XDG_DATA_DIRS / XDG_CONFIG_DIRS: read-only system paths; overriding them* breaks GTK schema and theme lookup.diff --git a/e2e/migration.ts b/e2e/migration.tsnew file mode 100644index 000000000..90deef2e8--- /dev/null+++ b/e2e/migration.ts@@ -0,0 +1,56 @@+import assert from 'node:assert/strict'+import { cpSync, mkdirSync, readFileSync, readdirSync } from 'node:fs'+import { join } from 'node:path'+import { janUserDataDir } from './helpers/paths.js'++export const fixtureDir = join(import.meta.dirname, '../src-tauri/tests/fixtures/upgrade/0.8.3')+export const historicalThread = '784952d3-dc72-474e-ab24-0d78e7035280'+const json = (path: string) => JSON.parse(readFileSync(path, 'utf8'))++export function assertFixture(source = fixtureDir) {+ assert.equal(json(join(source, 'store.json')).mcp_version, 3)+ assert.ok(json(join(source, 'mcp_config.json')).mcpServers.exa, 'fixture must carry Exa')+ assert.ok(readdirSync(join(source, 'threads')).includes(historicalThread))+}++/** Only called on the runner's own freshly-created, guarded profile. */+export function seedMigration(home: string, source = fixtureDir) {+ assertFixture(source)+ const destination = janUserDataDir(home)+ mkdirSync(destination, { recursive: true })+ cpSync(source, destination, { recursive: true, errorOnExist: true, force: false })+}++/** Compare all fixture thread IDs, metadata, message IDs and content, not just counts. */+export function assertMigrated(home: string, source = fixtureDir) {+ const destination = janUserDataDir(home)+ assert.equal(json(join(destination, 'store.json')).mcp_version, 5)+ const expected = json(join(source, 'mcp_config.json'))+ delete expected.mcpServers.exa+ assert.deepEqual(json(join(destination, 'mcp_config.json')), expected)+ const ids = readdirSync(join(source, 'threads')).sort()+ assert.deepEqual(readdirSync(join(destination, 'threads')).sort(), ids)+ for (const id of ids) {+ assert.deepEqual(json(join(destination, 'threads', id, 'thread.json')),+ json(join(source, 'threads', id, 'thread.json')))+ const messages = (root: string) => readFileSync(join(root, 'threads', id, 'messages.jsonl'), 'utf8')+ .trim().split('\n').map(line => JSON.parse(line))+ assert.deepEqual(messages(destination), messages(source))+ }+}++export function selectScenario(value = 'default'): 'default' | 'migration' {+ if (value !== 'default' && value !== 'migration') {+ throw new Error(`Invalid JAN_E2E_SCENARIO ${JSON.stringify(value)}: expected default or migration`)+ }+ return value+}++/** The second launch must never seed, even when the first launch fails. */+export async function migrationPhases(launch: (phase: number) => Promise<void>, closed: () => Promise<void>) {+ await closed()+ for (const phase of [1, 2]) {+ await launch(phase)+ await closed()+ }+}diff --git a/e2e/owned-process.ts b/e2e/owned-process.tsnew file mode 100644index 000000000..75f3a8369--- /dev/null+++ b/e2e/owned-process.ts@@ -0,0 +1,71 @@+import { spawn, type ChildProcess } from 'node:child_process'+import { withCleanup } from './phase-lifecycle.js'++export interface OwnedChild {+ pid?: number+ exitCode: number | null+ signalCode: string | null+ kill(signal: NodeJS.Signals): boolean+ once(event: 'exit' | 'error', listener: (...args: any[]) => void): unknown+ removeListener(event: 'exit' | 'error', listener: (...args: any[]) => void): unknown+}++// Keep the actual ChildProcess, not a PID read from logs or a reusable PID file.+// On Windows tree cleanup MUST happen before killing the owned root.+export async function stopOwned(child: OwnedChild, options: {+ platform?: string+ graceMs?: number+ killTree?: (pid: number) => Promise<void>+} = {}): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null || !child.pid) return+ const wait = (ms: number) => new Promise<boolean>(resolve => {+ const done = () => { clearTimeout(timer); child.removeListener('exit', done); resolve(true) }+ const timer = setTimeout(() => { child.removeListener('exit', done); resolve(false) }, ms)+ child.once('exit', done)+ if (child.exitCode !== null || child.signalCode !== null) done()+ })+ if ((options.platform ?? process.platform) === 'win32') {+ await (options.killTree ?? taskkillTree)(child.pid)+ } else {+ child.kill('SIGTERM')+ if (await wait(options.graceMs ?? 5_000)) return+ child.kill('SIGKILL')+ }+ if (!await wait(options.graceMs ?? 5_000)) throw new Error(`Owned process ${child.pid} did not exit`)+}++async function taskkillTree(pid: number): Promise<void> {+ await new Promise<void>((resolve, reject) => {+ const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true })+ const timer = setTimeout(() => {+ killer.kill('SIGKILL')+ reject(new Error(`taskkill owned PID ${pid} timed out`))+ }, 10_000)+ killer.once('error', error => { clearTimeout(timer); reject(error) })+ killer.once('exit', code => {+ clearTimeout(timer)+ code === 0 ? resolve() : reject(new Error(`taskkill owned PID ${pid}: ${code}`))+ })+ })+}++export function exited(child: ChildProcess): Promise<void> {+ return new Promise((resolve, reject) => {+ child.once('error', reject)+ child.once('exit', (code, signal) => code === 0 ? resolve() : reject(new Error(`Owned process failed: code=${code} signal=${signal}`)))+ })+}++// Cancellation races both startup and execution. Teardown is awaited even when+// work fails, and both roots are attempted if either teardown fails.+export async function ownedPhase(work: (own: (child: OwnedChild) => void) => Promise<void>, cancel: Promise<never>,+ stop: (child: OwnedChild) => Promise<void> = stopOwned): Promise<void> {+ const children: OwnedChild[] = []+ await withCleanup(+ () => Promise.race([work(child => children.push(child)), cancel]),+ // App is registered first: stop it before WDIO so Windows can traverse its+ // live tree. Attempt every root even if an earlier teardown fails.+ () => children.map(child => () => stop(child)),+ 'Owned process teardown failed',+ )+}diff --git a/e2e/package.json b/e2e/package.jsonindex e7ccc3539..8f8f1cb3e 100644--- a/e2e/package.json+++ b/e2e/package.json@@ -5,6 +5,7 @@"type": "module","scripts": {"test": "wdio run ./wdio.conf.ts",+ "test:migration": "tsx run-migration.ts","test:unit": "tsx --test tests/*.test.ts","typecheck": "tsc --noEmit"},diff --git a/e2e/phase-lifecycle.ts b/e2e/phase-lifecycle.tsnew file mode 100644index 000000000..62b63a806--- /dev/null+++ b/e2e/phase-lifecycle.ts@@ -0,0 +1,36 @@+// Preserve the original rejection (even undefined) and attempt every cleanup.+// A lone work failure is rethrown unchanged; combined failures retain it first+// in errors and as cause, followed by each cleanup failure in execution order.+export async function withCleanup<T>(work: () => Promise<T>,+ cleanups: () => Iterable<() => unknown | Promise<unknown>>, message: string): Promise<T> {+ let failed = false+ let original: unknown+ let result!: T+ try { result = await work() } catch (error) { failed = true; original = error }+ const failures: unknown[] = []+ for (const cleanup of cleanups()) {+ try { await cleanup() } catch (error) { failures.push(error) }+ }+ if (failures.length) {+ throw new AggregateError(failed ? [original, ...failures] : failures, message,+ failed ? { cause: original } : undefined)+ }+ if (failed) throw original+ return result+}++// The runner uses the same deadline path as tests, with a short duration in+// tests. dispose must be called during teardown to avoid a stale phase timer.+export function deadlineCancellation(ms: number, error: Error, onCancel: () => void = () => {}) {+ let reject!: (error: Error) => void+ let cancelled = false+ const promise = new Promise<never>((_, fail) => { reject = fail })+ const cancel = (reason: Error) => {+ if (cancelled) return+ cancelled = true+ onCancel()+ reject(reason)+ }+ const timer = setTimeout(() => cancel(error), ms)+ return { promise, cancel, dispose: () => clearTimeout(timer) }+}diff --git a/e2e/run-migration.ts b/e2e/run-migration.tsnew file mode 100644index 000000000..30a17d37a--- /dev/null+++ b/e2e/run-migration.ts@@ -0,0 +1,133 @@+import { spawn } from 'node:child_process'+import { closeSync, mkdirSync, mkdtempSync, openSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { connect } from 'node:net'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { isolationEnv } from './isolation.js'+import { exited, ownedPhase } from './owned-process.js'+import { deadlineCancellation, withCleanup } from './phase-lifecycle.js'+import { setTimeout as delay } from 'node:timers/promises'+import { assertSafeE2eHome, assertSafeLaunchEnvironment, canonicalPath, launchContext } from './launch-guard.js'+import { janUserDataDir } from './helpers/paths.js'+import { assertMigrated, migrationPhases, seedMigration } from './migration.js'++const context = launchContext()+assertSafeLaunchEnvironment(context)+// Never accept a caller's profile: this runner alone owns seeding and deletion.+if (process.env.JAN_E2E_HOME) throw new Error('Unset JAN_E2E_HOME: migration requires a fresh owned profile')+if (process.env.JAN_E2E_EMBEDDER_DOWNLOAD) throw new Error('Unset JAN_E2E_EMBEDDER_DOWNLOAD for migration smoke')+const port = Number(process.env.TAURI_WEBDRIVER_PORT ?? 4445)+if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid TAURI_WEBDRIVER_PORT')+const home = assertSafeE2eHome(mkdtempSync(join(realpathSync(tmpdir()), 'jan-e2e-migration-')), context)+const logs = join(home, 'runner-logs')+mkdirSync(logs)+let interrupted = false+let cancelPhase: ((error: Error) => void) | undefined+const interrupt = () => {+ interrupted = true+ cancelPhase?.(new Error('Migration interrupted'))+}+process.on('SIGINT', interrupt)+process.on('SIGTERM', interrupt)++async function listening() {+ return new Promise<boolean>((resolve, reject) => {+ const socket = connect({ host: '127.0.0.1', port })+ socket.setTimeout(1000)+ socket.once('connect', () => { socket.destroy(); resolve(true) })+ socket.once('timeout', () => { socket.destroy(); reject(new Error('driver port probe timed out')) })+ socket.once('error', error => {+ socket.destroy()+ if ((error as NodeJS.ErrnoException).code === 'ECONNREFUSED') resolve(false)+ else reject(error)+ })+ })+}+async function closed() {+ const deadline = Date.now() + 30_000+ while (await listening()) {+ if (Date.now() >= deadline) throw new Error(`Embedded driver port ${port} did not close; no foreign process will be killed`)+ await delay(200)+ }+}++let success = false+try {+ seedMigration(home)+ // Seed once, before either process starts. Config/worker evaluation must not+ // rewrite this file on launch two (see wdio.conf.ts).+ writeFileSync(join(janUserDataDir(home), 'settings.json'), JSON.stringify({ 'llamacpp-embedder-bootstrapped': 'true' }))+ await migrationPhases(async phase => {+ if (interrupted) throw new Error('Migration interrupted')+ assertSafeE2eHome(home, context)+ const output = openSync(join(logs, `phase-${phase}.log`), 'w')+ console.log(`Migration phase ${phase}: ${home} (logs: ${logs})`)+ let cancelled = false+ const deadline = deadlineCancellation(600_000,+ new Error(`Migration phase ${phase} timed out`), () => { cancelled = true })+ cancelPhase = deadline.cancel+ await withCleanup(async () => {+ await ownedPhase(async own => {+ mkdirSync(join(home, 'tmp'), { recursive: true })+ if (process.platform === 'win32') {+ mkdirSync(join(home, 'AppData', 'Roaming'), { recursive: true })+ mkdirSync(join(home, 'AppData', 'Local'), { recursive: true })+ }+ const app = spawn(resolve(import.meta.dirname, '../src-tauri/target/debug',+ process.platform === 'win32' ? 'Jan-Desktop.exe' : 'Jan-Desktop'), [], {+ env: { ...process.env, ...isolationEnv(home), TAURI_WEBDRIVER_PORT: String(port), WDIO_EMBEDDED_SERVER: 'true' },+ stdio: ['ignore', output, output],+ })+ own(app)+ // Subscribe immediately, including ENOENT / crashes before readiness.+ const appExit = exited(app).then(() => {+ cancelled = true+ throw new Error('App exited before phase teardown')+ }, error => { cancelled = true; throw error })+ const run = async () => {+ const deadline = Date.now() + 60_000+ while (!cancelled) {+ try {+ const response = await fetch(`http://127.0.0.1:${port}/status`, { signal: AbortSignal.timeout(1000) })+ const status = await response.json() as { value?: { ready?: boolean } }+ if (response.ok && status.value?.ready) break+ } catch { /* app may not have bound yet */ }+ if (Date.now() >= deadline) throw new Error('Embedded driver startup timed out')+ await delay(200)+ }+ // The cancellation race may already have entered teardown. Never+ // register another child after that point.+ if (cancelled) return+ const wdio = spawn(process.execPath, [join(import.meta.dirname, 'node_modules/@wdio/cli/bin/wdio.js'), 'run', './wdio.conf.ts'], {+ cwd: import.meta.dirname,+ env: { ...process.env, JAN_E2E_HOME: home, JAN_E2E_SCENARIO: 'migration', JAN_E2E_MIGRATION_PHASE: String(phase) },+ stdio: ['ignore', output, output],+ })+ own(wdio)+ await exited(wdio)+ }+ await Promise.race([run(), appExit])+ }, deadline.promise)+ }, () => [() => {+ cancelled = true+ deadline.dispose()+ cancelPhase = undefined+ closeSync(output)+ // A closed port is necessary, not sufficient: ownedPhase also awaited+ // each tracked root's exit. Failure of either barrier retains the profile.+ }, closed], 'Migration phase cleanup failed')+ assertMigrated(home)+ }, closed)+ success = true+} catch (error) {+ console.error(error)+ process.exitCode = 1+} finally {+ process.removeListener('SIGINT', interrupt)+ process.removeListener('SIGTERM', interrupt)+ if (success && !process.env.JAN_E2E_KEEP && canonicalPath(home) === home) {+ rmSync(home, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })+ } else {+ console.log(`Migration profile and logs retained: ${home}`)+ }+}diff --git a/e2e/specs/migration.e2e.ts b/e2e/specs/migration.e2e.tsnew file mode 100644index 000000000..33ca54f00--- /dev/null+++ b/e2e/specs/migration.e2e.ts@@ -0,0 +1,29 @@+import { browser, $, $$, expect } from '@wdio/globals'+import { assertFixture, assertMigrated, historicalThread } from '../migration.js'+import { goto } from '../helpers/navigation.js'+import { USER_MESSAGES, ASSISTANT_MESSAGES } from '../helpers/chat.js'++const home = process.env.JAN_E2E_HOME!+describe(`0.8.3 migration, process start ${process.env.JAN_E2E_MIGRATION_PHASE}`, () => {+ it('records schema 5, removes only Exa, and preserves all fixture threads and messages', async () => {+ assertFixture()+ await browser.waitUntil(() => {+ try { assertMigrated(home); return true } catch { return false }+ }, { timeout: 30_000, timeoutMsg: 'Migration never reached expected fixture state' })+ assertMigrated(home)+ })++ it('renders the historical user and assistant messages without configuring a provider', async () => {+ // A mounted root precedes extension registration and thread hydration.+ // The historical row only exists once fetchThreads has completed.+ await $(`[data-testid="thread-row-${historicalThread}"]`).waitForExist({ timeout: 60_000 })+ await goto(`/threads/${historicalThread}`)+ await expect($$(USER_MESSAGES)).toBeElementsArrayOfSize(1)+ await expect($$(ASSISTANT_MESSAGES)).toBeElementsArrayOfSize(1)+ const users = await $$(USER_MESSAGES).getElements()+ const assistants = await $$(ASSISTANT_MESSAGES).getElements()+ await expect(users[0]).toHaveText(expect.stringContaining('QA thread 1 created on v0.8.3 - confirm mock roundtrip'))+ await expect(assistants[0]).toHaveText(expect.stringContaining('QA reply at 15:46:46 to: QA thread 1 created on v0.8.3 - confirm mock roundtrip'))+ assertMigrated(home)+ })+})diff --git a/e2e/tests/migration.test.ts b/e2e/tests/migration.test.tsnew file mode 100644index 000000000..dd6ac207e--- /dev/null+++ b/e2e/tests/migration.test.ts@@ -0,0 +1,61 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { assertFixture, assertMigrated, historicalThread, migrationPhases, seedMigration, selectScenario } from '../migration.js'+import { janUserDataDir } from '../helpers/paths.js'++test('scenario selection is strict and defaults only when absent', () => {+ assert.equal(selectScenario(), 'default')+ assert.equal(selectScenario('migration'), 'migration')+ for (const value of ['', 'Migration', 'chat', ' migration']) assert.throws(() => selectScenario(value))+})++test('authentic fixture starts at schema 3; expected migration preserves every other field', () => {+ assertFixture()+ const home = mkdtempSync(join(tmpdir(), 'jan-migration-unit-'))+ try {+ seedMigration(home)+ const data = janUserDataDir(home)+ assert.throws(() => assertMigrated(home))+ const store = join(data, 'store.json')+ writeFileSync(store, JSON.stringify({ ...JSON.parse(readFileSync(store, 'utf8')), mcp_version: 5 }))+ assert.throws(() => assertMigrated(home)) // schema alone is not enough+ const config = join(data, 'mcp_config.json')+ const mcp = JSON.parse(readFileSync(config, 'utf8'))+ delete mcp.mcpServers.exa+ writeFileSync(config, JSON.stringify(mcp))+ assertMigrated(home)+ const messages = join(data, 'threads', historicalThread, 'messages.jsonl')+ const original = readFileSync(messages, 'utf8')+ writeFileSync(messages, original.replace('confirm mock roundtrip', 'lost history'))+ assert.throws(() => assertMigrated(home))+ writeFileSync(messages, original)+ delete mcp.mcpServers.fetch+ writeFileSync(config, JSON.stringify(mcp))+ assert.throws(() => assertMigrated(home))+ writeFileSync(config, JSON.stringify({ ...mcp, mcpServers: { ...mcp.mcpServers, fetch: { active: false } } }))+ assert.throws(() => assertMigrated(home)) // retaining only a server name is not enough+ } finally { rmSync(home, { recursive: true, force: true }) }+})++test('two separate launches have a port-closure barrier before, between and after', async () => {+ const events: string[] = []+ await migrationPhases(async phase => { events.push(`launch ${phase}`) }, async () => { events.push('closed') })+ assert.deepEqual(events, ['closed', 'launch 1', 'closed', 'launch 2', 'closed'])+})++test('failed first launch or closure barrier never launches phase two', async () => {+ for (const failLaunch of [true, false]) {+ const launches: number[] = []+ let barriers = 0+ await assert.rejects(migrationPhases(async phase => {+ launches.push(phase)+ if (failLaunch) throw new Error('launch failed')+ }, async () => {+ if (++barriers === 2) throw new Error('port still open')+ }))+ assert.deepEqual(launches, [1])+ }+})diff --git a/e2e/tests/owned-process.test.ts b/e2e/tests/owned-process.test.tsnew file mode 100644index 000000000..7f60b5a1b--- /dev/null+++ b/e2e/tests/owned-process.test.ts@@ -0,0 +1,200 @@+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import { test } from 'node:test'+import { ownedPhase, stopOwned, type OwnedChild } from '../owned-process.js'+import { deadlineCancellation, withCleanup } from '../phase-lifecycle.js'++class FakeChild extends EventEmitter implements OwnedChild {+ pid = 123+ exitCode: number | null = null+ signalCode: string | null = null+ signals: string[] = []+ ignoreTerm = false+ kill(signal: NodeJS.Signals) {+ this.signals.push(signal)+ if (signal !== 'SIGTERM' || !this.ignoreTerm) this.exit()+ return true+ }+ exit() { this.exitCode = 0; this.emit('exit', 0, null) }+}++for (const stage of ['startup', 'run']) {+ test(`${stage} interruption awaits app and runner teardown`, async () => {+ const app = new FakeChild()+ const wdio = new FakeChild()+ const events: string[] = []+ let cancel!: (error: Error) => void+ const cancellation = new Promise<never>((_, reject) => { cancel = reject })+ const phase = ownedPhase(async own => {+ own(app)+ if (stage !== 'startup') own(wdio)+ cancel(new Error(stage))+ await new Promise<void>(() => {})+ }, cancellation, async child => {+ events.push(child === app ? 'app' : 'wdio')+ await stopOwned(child, { platform: 'linux', graceMs: 5 })+ events.push('exited')+ })+ await assert.rejects(phase, new RegExp(stage))+ assert.deepEqual(events, stage === 'startup' ? ['app', 'exited'] : ['app', 'exited', 'wdio', 'exited'])+ })+}++test('Unix escalates a tracked handle and awaits exit', async () => {+ const app = new FakeChild()+ app.ignoreTerm = true+ await stopOwned(app, { platform: 'linux', graceMs: 5 })+ assert.deepEqual(app.signals, ['SIGTERM', 'SIGKILL'])+})++test('Windows kills only the owned PID tree before root termination', async () => {+ const app = new FakeChild()+ await stopOwned(app, { platform: 'win32', graceMs: 5, killTree: async pid => {+ assert.equal(pid, app.pid)+ assert.equal(app.exitCode, null)+ app.exit()+ } })+ assert.deepEqual(app.signals, [])+})++test('already exited roots are not signalled (avoid reused PIDs)', async () => {+ const app = new FakeChild()+ app.exit()+ await stopOwned(app, { platform: 'win32', killTree: async () => { assert.fail('must not taskkill') } })+ assert.deepEqual(app.signals, [])+})++test('cleanup failure still attempts the other root and rejects', async () => {+ const children = [new FakeChild(), new FakeChild()]+ const stopped: OwnedChild[] = []+ await assert.rejects(ownedPhase(async own => { children.forEach(own) }, new Promise<never>(() => {}), async child => {+ stopped.push(child)+ if (child === children[0]) throw new Error('uncertain exit')+ }), /teardown failed/)+ assert.deepEqual(stopped, children)+})++test('startup spawn failure still tears down registered handle', async () => {+ const app = new FakeChild()+ await assert.rejects(ownedPhase(async own => {+ own(app)+ throw new Error('spawn error')+ }, new Promise<never>(() => {}), child => stopOwned(child, { platform: 'linux', graceMs: 5 })), /spawn error/)+ assert.equal(app.exitCode, 0)+})++for (const workFails of [false, true]) {+ for (const cleanupFails of [false, true]) {+ test(`owned phase preserves failures: work=${workFails}, cleanup=${cleanupFails}`, async () => {+ const original = new Error('WDIO assertion failed')+ const teardown = new Error('app did not exit')+ const children = [new FakeChild(), new FakeChild()]+ const stopped: OwnedChild[] = []+ const phase = ownedPhase(async own => {+ children.forEach(own)+ if (workFails) throw original+ }, new Promise<never>(() => {}), async child => {+ stopped.push(child)+ if (cleanupFails && child === children[0]) throw teardown+ })+ if (cleanupFails) {+ await assert.rejects(phase, error => {+ assert.ok(error instanceof AggregateError)+ assert.deepEqual(error.errors, workFails ? [original, teardown] : [teardown])+ assert.equal(error.cause, workFails ? original : undefined)+ return true+ })+ } else if (workFails) await assert.rejects(phase, error => error === original)+ else await phase+ assert.deepEqual(stopped, children)+ })+ }+}++for (const phaseFails of [false, true]) {+ for (const portFails of [false, true]) {+ test(`port closure barrier preserves failures: phase=${phaseFails}, port=${portFails}`, async () => {+ const original = new Error('phase failed')+ const port = new Error('Embedded driver port did not close')+ let checked = false+ const phase = withCleanup(async () => {+ if (phaseFails) throw original+ return 42+ }, () => [async () => {+ checked = true+ if (portFails) throw port+ }], 'Migration phase cleanup failed')+ if (portFails) await assert.rejects(phase, error => {+ assert.ok(error instanceof AggregateError)+ assert.deepEqual(error.errors, phaseFails ? [original, port] : [port])+ assert.equal(error.cause, phaseFails ? original : undefined)+ return true+ })+ else if (phaseFails) await assert.rejects(phase, error => error === original)+ else assert.equal(await phase, 42)+ assert.equal(checked, true)+ })+ }+}++test('phase, owned teardown, log cleanup and port closure failures all survive', async () => {+ const original = new Error('startup failed')+ const teardown = new Error('owned teardown failed')+ const log = new Error('log close failed')+ const port = new Error('port closure failed')+ let checked = false+ await assert.rejects(withCleanup(() => ownedPhase(async own => {+ own(new FakeChild())+ throw original+ }, new Promise<never>(() => {}), async () => { throw teardown }), () => [+ () => { throw log },+ () => { checked = true; throw port },+ ], 'Migration phase cleanup failed'), error => {+ assert.ok(error instanceof AggregateError)+ assert.deepEqual(error.errors.slice(1), [log, port])+ const inner = error.errors[0]+ assert.ok(inner instanceof AggregateError)+ assert.deepEqual(inner.errors, [original, teardown])+ assert.equal(inner.cause, original)+ assert.equal(error.cause, inner)+ return true+ })+ assert.equal(checked, true)+})++test('undefined work rejection is not mistaken for success', async () => {+ await assert.rejects(withCleanup(async () => { throw undefined },+ () => [() => { throw new Error('cleanup') }], 'cleanup failed'), error => {+ assert.ok(error instanceof AggregateError)+ assert.equal(error.errors.length, 2)+ assert.equal(error.errors[0], undefined)+ return true+ })+})++test('real deadline automatically cancels work and awaits every owned root', async () => {+ const children = [new FakeChild(), new FakeChild()]+ const error = new Error('phase deadline expired')+ const events: string[] = []+ const deadline = deadlineCancellation(10, error, () => { events.push('cancel') })+ try {+ await assert.rejects(ownedPhase(async own => {+ children.forEach(own)+ await new Promise<void>(() => {})+ }, deadline.promise, async child => {+ assert.deepEqual(events[0], 'cancel')+ await stopOwned(child, { platform: 'linux', graceMs: 5 })+ events.push('exited')+ }), rejection => rejection === error)+ assert.deepEqual(events, ['cancel', 'exited', 'exited'])+ assert.ok(children.every(child => child.exitCode === 0))+ } finally { deadline.dispose() }+})++test('disposing the deadline prevents automatic cancellation', async () => {+ let cancelled = false+ const deadline = deadlineCancellation(5, new Error('unused'), () => { cancelled = true })+ deadline.dispose()+ await new Promise(resolve => setTimeout(resolve, 15))+ assert.equal(cancelled, false)+})diff --git a/e2e/wdio.conf.ts b/e2e/wdio.conf.tsindex 7323e517c..ffc0df8e0 100644--- a/e2e/wdio.conf.ts+++ b/e2e/wdio.conf.ts@@ -14,8 +14,14 @@ import type { TauriCapabilities, TauriServiceOptions } from '@wdio/tauri-serviceimport { SevereServiceError } from 'webdriverio'import { janUserDataDir } from './helpers/paths.js'import { isolationEnv } from './isolation.js'+import { selectScenario } from './migration.js'import { assertSafeE2eHome, assertSafeLaunchEnvironment, canonicalPath, containsPath, launchContext } from './launch-guard.js'+const scenario = selectScenario(process.env.JAN_E2E_SCENARIO)+if (scenario === 'migration' && (!process.env.JAN_E2E_HOME || !['1', '2'].includes(process.env.JAN_E2E_MIGRATION_PHASE ?? ''))) {+ throw new Error('Use yarn test:migration for the owned, two-launch migration profile')+}+// The app resolves its data folder through `core::app::paths::data_dir()`, and// isolation is only sound where that call can be redirected by environment://@@ -186,7 +192,7 @@ if (process.platform === 'win32') {// NOTE this is the backend settings store, at janUserDataDir() -- NOT the app// config `settings.json` one directory up at janDataDir(), which is the file// smoke.e2e.ts asserts on. Same filename, different file, different owner.-if (!process.env.JAN_E2E_EMBEDDER_DOWNLOAD) {+if (scenario !== 'migration' && !process.env.JAN_E2E_EMBEDDER_DOWNLOAD) {const backendSettingsDir = janUserDataDir(testHome)const backendSettingsFile = join(backendSettingsDir, 'settings.json')// A fresh mkdtemp profile cannot have one yet, but an inherited profile can,@@ -272,7 +278,7 @@ export const config: WebdriverIO.Config = {// nothing and reads only the sidebar, the settings menu and where a URL// lands, so it would pass anywhere; last keeps the three calibrated specs in// the order they were tuned in.- specs: [+ specs: scenario === 'migration' ? ['./specs/migration.e2e.ts'] : ['./specs/smoke.e2e.ts','./specs/chat.e2e.ts','./specs/message-actions.e2e.ts',@@ -287,7 +293,10 @@ export const config: WebdriverIO.Config = {'wdio:tauriServiceOptions': tauriServiceOptions,} as TauriCapabilities,],- services: [['@wdio/tauri-service', tauriServiceOptions]],+ // Migration runner owns the app from spawn through awaited teardown, even+ // during startup. No service launcher may spawn a second app.+ services: scenario === 'migration' ? [] : [['@wdio/tauri-service', tauriServiceOptions]],+ ...(scenario === 'migration' ? { hostname: '127.0.0.1', port: driverPort } : {}),framework: 'mocha',reporters: ['spec'],logLevel: 'info',@@ -298,7 +307,9 @@ export const config: WebdriverIO.Config = {// says which selector a polling helper gave up on -- survives as a file CI// can upload after the runner is gone. A local run of the two specs writes// ~630 webdriver lines here and none to the terminal.- outputDir: join(import.meta.dirname, 'logs'),+ outputDir: scenario === 'migration'+ ? join(testHome, 'runner-logs', `wdio-phase-${process.env.JAN_E2E_MIGRATION_PHASE}`)+ : join(import.meta.dirname, 'logs'),waitforTimeout: 20_000,connectionRetryTimeout: 120_000,connectionRetryCount: 3,@@ -359,7 +370,7 @@ export const config: WebdriverIO.Config = {// plain Error here is printed and then ignored, and the run continues into the// collision this is meant to prevent -- which is exactly what it did.onPrepare: async () => {- if (!(await somethingIsListening(driverPort))) return+ if (scenario === 'migration' || !(await somethingIsListening(driverPort))) returnthrow new SevereServiceError(`something is already listening on 127.0.0.1:${driverPort}, the port the ` +'embedded WebDriver server uses. This run would drive that process ' +