Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Migrate bun:test imports to Vitest (#2800)

Dimitri POSTOLOV3c549e6cda98
diff --git a/.github/scripts/bridge-public-pr-to-monorepo.test.mjs b/.github/scripts/bridge-public-pr-to-monorepo.test.mjs
index 539dd07ee..38c09cc6c 100644
--- a/.github/scripts/bridge-public-pr-to-monorepo.test.mjs
+++ b/.github/scripts/bridge-public-pr-to-monorepo.test.mjs
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
+import { describe, expect, test } from 'vitest';
import { gitCleanEnv } from '../../scripts/git-clean-env.mjs';
import {
applyPatchWithConflictDetection,
diff --git a/.github/scripts/cla-gate.test.mjs b/.github/scripts/cla-gate.test.mjs
index bc49c3f7f..2c2a34bbd 100644
--- a/.github/scripts/cla-gate.test.mjs
+++ b/.github/scripts/cla-gate.test.mjs
@@ -1,65 +1,65 @@
-import { describe, expect, test } from "bun:test";
-import { applyClaGate, BOT_ALLOWLIST, evaluateClaGate, isBot } from "./cla-gate.mjs";
+import { describe, expect, test } from 'vitest';
+import { applyClaGate, BOT_ALLOWLIST, evaluateClaGate, isBot } from './cla-gate.mjs';
-describe("evaluateClaGate", () => {
- test("an exempt author is released regardless of status", () => {
- for (const claStatus of ["failure", "pending", "error", null, undefined]) {
+describe('evaluateClaGate', () => {
+ test('an exempt author is released regardless of status', () => {
+ for (const claStatus of ['failure', 'pending', 'error', null, undefined]) {
expect(evaluateClaGate({ claStatus, exempt: true })).toEqual({
gated: false,
- reason: "exempt",
+ reason: 'exempt',
});
}
});
- test("a signed non-exempt author is released", () => {
- expect(evaluateClaGate({ claStatus: "success" })).toEqual({
+ test('a signed non-exempt author is released', () => {
+ expect(evaluateClaGate({ claStatus: 'success' })).toEqual({
gated: false,
- reason: "cla-signed",
+ reason: 'cla-signed',
});
});
- test("an unsigned (failure) non-exempt author is gated", () => {
- expect(evaluateClaGate({ claStatus: "failure" })).toEqual({
+ test('an unsigned (failure) non-exempt author is gated', () => {
+ expect(evaluateClaGate({ claStatus: 'failure' })).toEqual({
gated: true,
- reason: "cla-unsigned",
+ reason: 'cla-unsigned',
});
});
- test("absent or pending status fails closed", () => {
- for (const claStatus of [null, undefined, "pending"]) {
- expect(evaluateClaGate({ claStatus })).toEqual({ gated: true, reason: "cla-pending" });
+ test('absent or pending status fails closed', () => {
+ for (const claStatus of [null, undefined, 'pending']) {
+ expect(evaluateClaGate({ claStatus })).toEqual({ gated: true, reason: 'cla-pending' });
}
});
- test("errored status fails closed with a distinct infra-error reason", () => {
- expect(evaluateClaGate({ claStatus: "error" })).toEqual({ gated: true, reason: "cla-errored" });
+ test('errored status fails closed with a distinct infra-error reason', () => {
+ expect(evaluateClaGate({ claStatus: 'error' })).toEqual({ gated: true, reason: 'cla-errored' });
});
- test("failure (unsigned) and error (infra) are distinct reasons", () => {
- expect(evaluateClaGate({ claStatus: "failure" }).reason).toBe("cla-unsigned");
- expect(evaluateClaGate({ claStatus: "error" }).reason).toBe("cla-errored");
+ test('failure (unsigned) and error (infra) are distinct reasons', () => {
+ expect(evaluateClaGate({ claStatus: 'failure' }).reason).toBe('cla-unsigned');
+ expect(evaluateClaGate({ claStatus: 'error' }).reason).toBe('cla-errored');
});
});
-describe("isBot", () => {
- test("matches listed bots case-insensitively", () => {
- expect(isBot("inkeep-oss-sync[bot]")).toBe(true);
- expect(isBot("Copilot-SWE-Agent[bot]")).toBe(true);
+describe('isBot', () => {
+ test('matches listed bots case-insensitively', () => {
+ expect(isBot('inkeep-oss-sync[bot]')).toBe(true);
+ expect(isBot('Copilot-SWE-Agent[bot]')).toBe(true);
});
- test("non-bots and empty logins are not bots", () => {
- expect(isBot("outsider")).toBe(false);
+ test('non-bots and empty logins are not bots', () => {
+ expect(isBot('outsider')).toBe(false);
expect(isBot(null)).toBe(false);
expect(isBot(undefined)).toBe(false);
});
- test("the published BOT_ALLOWLIST holds only bot actors, no humans", () => {
+ test('the published BOT_ALLOWLIST holds only bot actors, no humans', () => {
expect(BOT_ALLOWLIST.length).toBeGreaterThan(0);
- expect(BOT_ALLOWLIST.every((login) => login.endsWith("[bot]"))).toBe(true);
+ expect(BOT_ALLOWLIST.every((login) => login.endsWith('[bot]'))).toBe(true);
});
});
-describe("applyClaGate", () => {
+describe('applyClaGate', () => {
const fakeGh = (
claStatus,
{ isMember = false, throwOnRead = false, throwOnMembership = false } = {},
@@ -75,12 +75,12 @@ describe("applyClaGate", () => {
recorded,
isOrgMember: async () => {
recorded.memberChecks += 1;
- if (throwOnMembership) throw new Error("membership api unavailable");
+ if (throwOnMembership) throw new Error('membership api unavailable');
return isMember;
},
readClaStatus: async () => {
recorded.reads += 1;
- if (throwOnRead) throw new Error("status api unavailable");
+ if (throwOnRead) throw new Error('status api unavailable');
return claStatus;
},
setDraft: async (_pr, shouldBeDraft) => {
@@ -92,89 +92,93 @@ describe("applyClaGate", () => {
},
};
};
- const publicPr = (login, draft = false) => ({ user: { login }, draft, head: { sha: "public-sha" } });
- const internalPr = { head: { sha: "internal-sha" } };
+ const publicPr = (login, draft = false) => ({
+ user: { login },
+ draft,
+ head: { sha: 'public-sha' },
+ });
+ const internalPr = { head: { sha: 'internal-sha' } };
- test("unsigned non-member external PR is held draft with a failing cla/verified status", async () => {
- const gh = fakeGh("failure");
- const gate = await applyClaGate({ gh, publicPr: publicPr("outsider"), internalPr });
+ test('unsigned non-member external PR is held draft with a failing cla/verified status', async () => {
+ const gh = fakeGh('failure');
+ const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe("failure");
- expect(gate).toMatchObject({ gated: true, reason: "cla-unsigned" });
+ expect(gh.recorded.status).toBe('failure');
+ expect(gate).toMatchObject({ gated: true, reason: 'cla-unsigned' });
});
- test("signed non-member external PR is set ready with a success status", async () => {
- const gh = fakeGh("success");
- const gate = await applyClaGate({ gh, publicPr: publicPr("outsider"), internalPr });
+ test('signed non-member external PR is set ready with a success status', async () => {
+ const gh = fakeGh('success');
+ const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
expect(gh.recorded.draft).toBe(false);
- expect(gh.recorded.status).toBe("success");
+ expect(gh.recorded.status).toBe('success');
expect(gate.gated).toBe(false);
});
- test("an org member is released without reading the CLA status", async () => {
+ test('an org member is released without reading the CLA status', async () => {
const gh = fakeGh(null, { isMember: true });
- const gate = await applyClaGate({ gh, publicPr: publicPr("employee"), internalPr });
- expect(gate).toMatchObject({ gated: false, reason: "exempt" });
+ const gate = await applyClaGate({ gh, publicPr: publicPr('employee'), internalPr });
+ expect(gate).toMatchObject({ gated: false, reason: 'exempt' });
expect(gh.recorded.reads).toBe(0);
expect(gh.recorded.draft).toBe(false);
- expect(gh.recorded.status).toBe("success");
+ expect(gh.recorded.status).toBe('success');
});
- test("a listed bot is released without any membership or status read", async () => {
+ test('a listed bot is released without any membership or status read', async () => {
const gh = fakeGh(null);
- const gate = await applyClaGate({ gh, publicPr: publicPr("inkeep-oss-sync[bot]"), internalPr });
- expect(gate).toMatchObject({ gated: false, reason: "exempt" });
+ const gate = await applyClaGate({ gh, publicPr: publicPr('inkeep-oss-sync[bot]'), internalPr });
+ expect(gate).toMatchObject({ gated: false, reason: 'exempt' });
expect(gh.recorded.memberChecks).toBe(0);
expect(gh.recorded.reads).toBe(0);
});
- test("a membership read failure fails closed", async () => {
- const gh = fakeGh("success", { throwOnMembership: true });
- const gate = await applyClaGate({ gh, publicPr: publicPr("outsider"), internalPr });
- expect(gate.reason).toBe("cla-read-error");
+ test('a membership read failure fails closed', async () => {
+ const gh = fakeGh('success', { throwOnMembership: true });
+ const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
+ expect(gate.reason).toBe('cla-read-error');
expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe("failure");
+ expect(gh.recorded.status).toBe('failure');
});
- test("a status read failure fails closed", async () => {
+ test('a status read failure fails closed', async () => {
const gh = fakeGh(null, { throwOnRead: true });
- const gate = await applyClaGate({ gh, publicPr: publicPr("outsider"), internalPr });
- expect(gate.reason).toBe("cla-read-error");
+ const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
+ expect(gate.reason).toBe('cla-read-error');
expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe("failure");
+ expect(gh.recorded.status).toBe('failure');
});
test("an errored CLA check is held but not told to 'sign the CLA'", async () => {
- const gh = fakeGh("error");
- const gate = await applyClaGate({ gh, publicPr: publicPr("outsider"), internalPr });
- expect(gate.reason).toBe("cla-errored");
+ const gh = fakeGh('error');
+ const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
+ expect(gate.reason).toBe('cla-errored');
expect(gh.recorded.draft).toBe(true);
expect(gh.recorded.description).not.toMatch(/sign the cla/i);
});
- test("re-sync after a new unsigned head re-blocks a released PR", async () => {
- const signed = fakeGh("success");
- await applyClaGate({ gh: signed, publicPr: publicPr("outsider"), internalPr });
+ test('re-sync after a new unsigned head re-blocks a released PR', async () => {
+ const signed = fakeGh('success');
+ await applyClaGate({ gh: signed, publicPr: publicPr('outsider'), internalPr });
expect(signed.recorded.draft).toBe(false);
- const reUnsigned = fakeGh("failure");
- await applyClaGate({ gh: reUnsigned, publicPr: publicPr("outsider"), internalPr });
+ const reUnsigned = fakeGh('failure');
+ await applyClaGate({ gh: reUnsigned, publicPr: publicPr('outsider'), internalPr });
expect(reUnsigned.recorded.draft).toBe(true);
- expect(reUnsigned.recorded.status).toBe("failure");
+ expect(reUnsigned.recorded.status).toBe('failure');
});
- test("a signed PR that is itself a draft upstream stays draft, with success status", async () => {
- const gh = fakeGh("success");
- await applyClaGate({ gh, publicPr: publicPr("outsider", true), internalPr });
+ test('a signed PR that is itself a draft upstream stays draft, with success status', async () => {
+ const gh = fakeGh('success');
+ await applyClaGate({ gh, publicPr: publicPr('outsider', true), internalPr });
expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe("success");
+ expect(gh.recorded.status).toBe('success');
});
- test("forceDraft holds a signed, ungated PR draft (conflict markers need manual resolution)", async () => {
- const gh = fakeGh("success");
+ test('forceDraft holds a signed, ungated PR draft (conflict markers need manual resolution)', async () => {
+ const gh = fakeGh('success');
const gate = await applyClaGate({
gh,
- publicPr: publicPr("outsider"),
+ publicPr: publicPr('outsider'),
internalPr,
forceDraft: true,
});
@@ -182,12 +186,16 @@ describe("applyClaGate", () => {
// The gate itself is not gated (CLA is signed); the draft is purely the
// conflict hold, so cla/verified still reports success.
expect(gate.gated).toBe(false);
- expect(gh.recorded.status).toBe("success");
+ expect(gh.recorded.status).toBe('success');
});
- test("a missing author is gated (no bot or member match, fails closed on status)", async () => {
+ test('a missing author is gated (no bot or member match, fails closed on status)', async () => {
const gh = fakeGh(null);
- const gate = await applyClaGate({ gh, publicPr: { draft: false, head: { sha: "s" } }, internalPr });
+ const gate = await applyClaGate({
+ gh,
+ publicPr: { draft: false, head: { sha: 's' } },
+ internalPr,
+ });
expect(gate.gated).toBe(true);
expect(gh.recorded.memberChecks).toBe(0);
});
diff --git a/.github/scripts/select-beta-to-promote.test.mjs b/.github/scripts/select-beta-to-promote.test.mjs
index a35ab029b..22ed79adb 100644
--- a/.github/scripts/select-beta-to-promote.test.mjs
+++ b/.github/scripts/select-beta-to-promote.test.mjs
@@ -1,16 +1,16 @@
-import { describe, expect, test } from "bun:test";
-import { parseBetaTags, selectPromotion } from "./select-beta-to-promote.mjs";
+import { describe, expect, test } from 'vitest';
+import { parseBetaTags, selectPromotion } from './select-beta-to-promote.mjs';
// Fixed clock so tests never call Date.now().
-const NOW = Date.parse("2026-07-08T20:00:00Z");
+const NOW = Date.parse('2026-07-08T20:00:00Z');
const SOAK = 86400; // 24h
-const SOAKED = "2026-07-07T14:00:00Z"; // 30h before NOW
-const FRESH = "2026-07-08T17:00:00Z"; // 3h before NOW
+const SOAKED = '2026-07-07T14:00:00Z'; // 30h before NOW
+const FRESH = '2026-07-08T17:00:00Z'; // 3h before NOW
function meta({ isDraft = false, publishedAt = SOAKED, dmg = true, manifest = true } = {}) {
const assets = [];
- if (dmg) assets.push({ name: "OpenKnowledge-universal.dmg" });
- if (manifest) assets.push({ name: "beta-mac.yml" });
+ if (dmg) assets.push({ name: 'OpenKnowledge-universal.dmg' });
+ if (manifest) assets.push({ name: 'beta-mac.yml' });
return { isDraft, publishedAt, assets };
}
@@ -19,7 +19,7 @@ function meta({ isDraft = false, publishedAt = SOAKED, dmg = true, manifest = tr
function fetcher(map) {
return (tag) => {
if (!(tag in map)) return null;
- if (map[tag] === "THROW") throw new Error("simulated non-404 infra error");
+ if (map[tag] === 'THROW') throw new Error('simulated non-404 infra error');
return map[tag];
};
}
@@ -33,127 +33,127 @@ const shippedIn = (...tags) => {
const select = (over) =>
selectPromotion({ isAlreadyShipped: shippedNone, soakSeconds: SOAK, nowMs: NOW, ...over });
-describe("parseBetaTags", () => {
- test("filters to conforming beta tags, preserving order", () => {
- const raw = "v0.10.0-beta.6\nv0.10.0\nrandomtag\n\nv0.10.0-beta.5\nv0.9.0-beta.12\n";
- expect(parseBetaTags(raw)).toEqual(["v0.10.0-beta.6", "v0.10.0-beta.5", "v0.9.0-beta.12"]);
+describe('parseBetaTags', () => {
+ test('filters to conforming beta tags, preserving order', () => {
+ const raw = 'v0.10.0-beta.6\nv0.10.0\nrandomtag\n\nv0.10.0-beta.5\nv0.9.0-beta.12\n';
+ expect(parseBetaTags(raw)).toEqual(['v0.10.0-beta.6', 'v0.10.0-beta.5', 'v0.9.0-beta.12']);
});
- test("empty input yields no tags", () => {
- expect(parseBetaTags("")).toEqual([]);
+ test('empty input yields no tags', () => {
+ expect(parseBetaTags('')).toEqual([]);
});
});
-describe("selectPromotion", () => {
- test("reaches back to the latest soaked beta when the head is under-soaked", () => {
+describe('selectPromotion', () => {
+ test('reaches back to the latest soaked beta when the head is under-soaked', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.6": meta({ publishedAt: FRESH }),
- "v0.10.0-beta.5": meta({ publishedAt: SOAKED }),
+ 'v0.10.0-beta.6': meta({ publishedAt: FRESH }),
+ 'v0.10.0-beta.5': meta({ publishedAt: SOAKED }),
}),
});
- expect(r).toEqual({ kind: "select", target: "v0.10.0-beta.5" });
+ expect(r).toEqual({ kind: 'select', target: 'v0.10.0-beta.5' });
});
- test("selects the head when the head itself is soaked", () => {
+ test('selects the head when the head itself is soaked', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.6": meta({ publishedAt: SOAKED }),
- "v0.10.0-beta.5": meta({ publishedAt: SOAKED }),
+ 'v0.10.0-beta.6': meta({ publishedAt: SOAKED }),
+ 'v0.10.0-beta.5': meta({ publishedAt: SOAKED }),
}),
});
- expect(r).toEqual({ kind: "select", target: "v0.10.0-beta.6" });
+ expect(r).toEqual({ kind: 'select', target: 'v0.10.0-beta.6' });
});
- test("selects the newest soaked UNSHIPPED beta, even across a version boundary", () => {
+ test('selects the newest soaked UNSHIPPED beta, even across a version boundary', () => {
// Catch-up shape: a fresh head, then several soaked betas spanning two X.Y.Z
// lines, none shipped yet -> pick the newest soaked (promote-stable batches
// the whole changeset delta over the latest stable into one bump).
const r = select({
- betaTags: ["v0.31.0-beta.1", "v0.31.0-beta.0", "v0.30.1-beta.8"],
+ betaTags: ['v0.31.0-beta.1', 'v0.31.0-beta.0', 'v0.30.1-beta.8'],
fetchReleaseMeta: fetcher({
- "v0.31.0-beta.1": meta({ publishedAt: FRESH }),
- "v0.31.0-beta.0": meta({ publishedAt: SOAKED }),
- "v0.30.1-beta.8": meta({ publishedAt: SOAKED }),
+ 'v0.31.0-beta.1': meta({ publishedAt: FRESH }),
+ 'v0.31.0-beta.0': meta({ publishedAt: SOAKED }),
+ 'v0.30.1-beta.8': meta({ publishedAt: SOAKED }),
}),
});
- expect(r).toEqual({ kind: "select", target: "v0.31.0-beta.0" });
+ expect(r).toEqual({ kind: 'select', target: 'v0.31.0-beta.0' });
});
- test("stops at the first already-shipped beta and never reaches an older cycle", () => {
+ test('stops at the first already-shipped beta and never reaches an older cycle', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.9.0-beta.3"],
- isAlreadyShipped: shippedIn("v0.10.0-beta.6"), // beta.6 is contained in the latest stable
+ betaTags: ['v0.10.0-beta.6', 'v0.9.0-beta.3'],
+ isAlreadyShipped: shippedIn('v0.10.0-beta.6'), // beta.6 is contained in the latest stable
fetchReleaseMeta: fetcher({
- "v0.9.0-beta.3": meta({ publishedAt: SOAKED }), // soaked but must NOT be chosen
+ 'v0.9.0-beta.3': meta({ publishedAt: SOAKED }), // soaked but must NOT be chosen
}),
});
- expect(r).toEqual({ kind: "none" });
+ expect(r).toEqual({ kind: 'none' });
});
- test("skips a draft head and promotes the older soaked beta", () => {
+ test('skips a draft head and promotes the older soaked beta', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.6": meta({ isDraft: true, publishedAt: SOAKED }),
- "v0.10.0-beta.5": meta({ publishedAt: SOAKED }),
+ 'v0.10.0-beta.6': meta({ isDraft: true, publishedAt: SOAKED }),
+ 'v0.10.0-beta.5': meta({ publishedAt: SOAKED }),
}),
});
- expect(r).toEqual({ kind: "select", target: "v0.10.0-beta.5" });
+ expect(r).toEqual({ kind: 'select', target: 'v0.10.0-beta.5' });
});
- test("skips a head missing the DMG asset", () => {
+ test('skips a head missing the DMG asset', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.6": meta({ dmg: false }),
- "v0.10.0-beta.5": meta(),
+ 'v0.10.0-beta.6': meta({ dmg: false }),
+ 'v0.10.0-beta.5': meta(),
}),
});
- expect(r.target).toBe("v0.10.0-beta.5");
+ expect(r.target).toBe('v0.10.0-beta.5');
});
- test("skips a head missing the mac.yml manifest", () => {
+ test('skips a head missing the mac.yml manifest', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.6": meta({ manifest: false }),
- "v0.10.0-beta.5": meta(),
+ 'v0.10.0-beta.6': meta({ manifest: false }),
+ 'v0.10.0-beta.5': meta(),
}),
});
- expect(r.target).toBe("v0.10.0-beta.5");
+ expect(r.target).toBe('v0.10.0-beta.5');
});
- test("treats a 404 (null) as no-release-yet and considers the next-older beta", () => {
+ test('treats a 404 (null) as no-release-yet and considers the next-older beta', () => {
const r = select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
// beta.6 unknown -> 404 -> null
- "v0.10.0-beta.5": meta(),
+ 'v0.10.0-beta.5': meta(),
}),
});
- expect(r.target).toBe("v0.10.0-beta.5");
+ expect(r.target).toBe('v0.10.0-beta.5');
});
- test("returns none when nothing is soaked", () => {
+ test('returns none when nothing is soaked', () => {
const r = select({
- betaTags: ["v0.10.0-beta.2", "v0.10.0-beta.1"],
+ betaTags: ['v0.10.0-beta.2', 'v0.10.0-beta.1'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.2": meta({ publishedAt: FRESH }),
- "v0.10.0-beta.1": meta({ publishedAt: FRESH }),
+ 'v0.10.0-beta.2': meta({ publishedAt: FRESH }),
+ 'v0.10.0-beta.1': meta({ publishedAt: FRESH }),
}),
});
- expect(r).toEqual({ kind: "none" });
+ expect(r).toEqual({ kind: 'none' });
});
- test("propagates a non-404 infra error instead of skipping the candidate (fail loud)", () => {
+ test('propagates a non-404 infra error instead of skipping the candidate (fail loud)', () => {
expect(() =>
select({
- betaTags: ["v0.10.0-beta.6", "v0.10.0-beta.5"],
+ betaTags: ['v0.10.0-beta.6', 'v0.10.0-beta.5'],
fetchReleaseMeta: fetcher({
- "v0.10.0-beta.6": "THROW", // auth/network/rate-limit on the newest candidate
- "v0.10.0-beta.5": meta(), // would otherwise be wrongly promoted as latest
+ 'v0.10.0-beta.6': 'THROW', // auth/network/rate-limit on the newest candidate
+ 'v0.10.0-beta.5': meta(), // would otherwise be wrongly promoted as latest
}),
}),
).toThrow(/infra error/);
diff --git a/docs/src/app/d/[encoded]/download/route.test.ts b/docs/src/app/d/[encoded]/download/route.test.ts
index 5799d243a..badfce3cf 100644
--- a/docs/src/app/d/[encoded]/download/route.test.ts
+++ b/docs/src/app/d/[encoded]/download/route.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
const SPLASH_URL =
'https://github.com/inkeep/open-knowledge/releases/latest/download/OpenKnowledge-arm64.dmg';
@@ -10,7 +10,7 @@ type CaptureOpts = {
};
let _lastCapture: CaptureOpts | null = null;
let _isPrefetch = false;
-mock.module('../../../../lib/track.ts', () => ({
+vi.doMock('../../../../lib/track.ts', () => ({
captureServerEvent: (opts: CaptureOpts) => {
_lastCapture = opts;
},
@@ -21,12 +21,12 @@ mock.module('../../../../lib/track.ts', () => ({
// Flip the decoded-share outcome per test.
let _viewKind: 'ok' | 'invalid' | 'unsupported-version' = 'ok';
-mock.module('../../../../lib/share-splash.ts', () => ({
+vi.doMock('../../../../lib/share-splash.ts', () => ({
buildSplashViewModel: () => ({ kind: _viewKind }),
SPLASH_DOWNLOAD_URL: SPLASH_URL,
}));
-mock.module('../../../../lib/deferred-share.ts', () => ({
+vi.doMock('../../../../lib/deferred-share.ts', () => ({
buildPendingShareCookie: (encoded: string) => ({ name: 'ok-pending-share', value: encoded }),
}));
diff --git a/docs/src/app/d/[encoded]/opengraph-image.test.ts b/docs/src/app/d/[encoded]/opengraph-image.test.ts
index 80c2187db..ce4d1e8db 100644
--- a/docs/src/app/d/[encoded]/opengraph-image.test.ts
+++ b/docs/src/app/d/[encoded]/opengraph-image.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
/**
* The OG image route uses `next/og`'s `ImageResponse` which spins up satori
@@ -15,7 +15,7 @@ const recordedCalls: Array<{
options: { fonts?: unknown; headers?: Record<string, string>; width?: number; height?: number };
}> = [];
-mock.module('next/og', () => ({
+vi.doMock('next/og', () => ({
ImageResponse: class MockImageResponse extends Response {
constructor(
body: unknown,
diff --git a/docs/src/app/download/beta/route.test.ts b/docs/src/app/download/beta/route.test.ts
index 21560e5c2..e52f5154b 100644
--- a/docs/src/app/download/beta/route.test.ts
+++ b/docs/src/app/download/beta/route.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
type BetaRedirect,
DMG_ASSET_NAME,
@@ -15,7 +15,7 @@ let _redirect: BetaRedirect = { kind: 'fresh', url: TEST_DMG_URL };
// Mock must be registered before route.ts is loaded so the module-scope
// `createBetaResolver()` call in route.ts uses the injected resolver.
-mock.module('../../../lib/download-links.ts', () => ({
+vi.doMock('../../../lib/download-links.ts', () => ({
createBetaResolver: () => () => Promise.resolve(_redirect),
toRedirectResponse: (r: BetaRedirect): Response =>
new Response(null, {
@@ -33,7 +33,7 @@ type CaptureOpts = {
properties?: Record<string, string | undefined>;
};
let _lastCapture: CaptureOpts | null = null;
-mock.module('../../../lib/track.ts', () => ({
+vi.doMock('../../../lib/track.ts', () => ({
captureServerEvent: (opts: CaptureOpts) => {
_lastCapture = opts;
},
diff --git a/docs/src/app/download/stable/route.test.ts b/docs/src/app/download/stable/route.test.ts
index 667956405..35d65d723 100644
--- a/docs/src/app/download/stable/route.test.ts
+++ b/docs/src/app/download/stable/route.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { STABLE_DMG_URL } from '../../../lib/download-links.ts';
type CaptureOpts = {
@@ -10,7 +10,7 @@ type CaptureOpts = {
// Spy on the capture so we can assert the event without a PostHog round-trip.
// Registered before route.ts loads so its `@/lib/track` import resolves here.
let _lastCapture: CaptureOpts | null = null;
-mock.module('../../../lib/track.ts', () => ({
+vi.doMock('../../../lib/track.ts', () => ({
captureServerEvent: (opts: CaptureOpts) => {
_lastCapture = opts;
},
diff --git a/docs/src/app/llms.mdx/[...slug]/route.test.ts b/docs/src/app/llms.mdx/[...slug]/route.test.ts
index 1859fbbc2..bb14f7e63 100644
--- a/docs/src/app/llms.mdx/[...slug]/route.test.ts
+++ b/docs/src/app/llms.mdx/[...slug]/route.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
const overviewPage = {
url: '/docs/get-started/overview',
@@ -11,7 +11,7 @@ const overviewPage = {
// `getPage` returns the fixture for the overview slug, undefined otherwise —
// lets us exercise both the 200 and the notFound paths.
-mock.module('@/lib/source', () => ({
+vi.doMock('@/lib/source', () => ({
source: {
getPage: (slug: string[]) =>
slug.join('/') === 'get-started/overview' ? overviewPage : undefined,
@@ -21,7 +21,7 @@ mock.module('@/lib/source', () => ({
// notFound() throws a sentinel in the App Router; mirror that so the handler's
// `if (!page) notFound()` branch is observable in a unit test.
-mock.module('next/navigation', () => ({
+vi.doMock('next/navigation', () => ({
notFound: () => {
throw new Error('NEXT_HTTP_ERROR_FALLBACK;404');
},
diff --git a/docs/src/app/updates/[channel]/[...path]/route.test.ts b/docs/src/app/updates/[channel]/[...path]/route.test.ts
index 0945b5aa7..62619111d 100644
--- a/docs/src/app/updates/[channel]/[...path]/route.test.ts
+++ b/docs/src/app/updates/[channel]/[...path]/route.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
type CaptureOpts = {
event: string;
@@ -7,7 +7,7 @@ type CaptureOpts = {
};
let _lastCapture: CaptureOpts | null = null;
-mock.module('../../../../lib/track.ts', () => ({
+vi.doMock('../../../../lib/track.ts', () => ({
captureServerEvent: (opts: CaptureOpts) => {
_lastCapture = opts;
},
@@ -20,7 +20,7 @@ const BETA_DMG_URL =
// Mutable so a test can flip the beta resolver from a fresh tag to a fallback.
type BetaRedirect = { kind: string; url: string; cause?: string };
let _betaRedirect: BetaRedirect = { kind: 'fresh', url: BETA_DMG_URL };
-mock.module('../../../../lib/download-links.ts', () => ({
+vi.doMock('../../../../lib/download-links.ts', () => ({
createBetaResolver: () => () => Promise.resolve(_betaRedirect),
}));
diff --git a/docs/src/components/tabs.test.ts b/docs/src/components/tabs.test.ts
index 9c81c2eb8..11d58b975 100644
--- a/docs/src/components/tabs.test.ts
+++ b/docs/src/components/tabs.test.ts
@@ -11,7 +11,7 @@
* name that explains why it's load-bearing.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { composeTabId, slugifyTabId } from './tabs.tsx';
describe('slugifyTabId', () => {
diff --git a/docs/src/hsts-header.test.ts b/docs/src/hsts-header.test.ts
index 37a35f8d6..78a785e8f 100644
--- a/docs/src/hsts-header.test.ts
+++ b/docs/src/hsts-header.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import nextConfig from '../next.config.ts';
/**
diff --git a/docs/src/lib/deferred-share.test.ts b/docs/src/lib/deferred-share.test.ts
index 3880e07e1..efdccba9c 100644
--- a/docs/src/lib/deferred-share.test.ts
+++ b/docs/src/lib/deferred-share.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildPendingShareCookie,
decideContinue,
diff --git a/docs/src/lib/download-links.test.ts b/docs/src/lib/download-links.test.ts
index ec10d5535..e8e2bb464 100644
--- a/docs/src/lib/download-links.test.ts
+++ b/docs/src/lib/download-links.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createBetaResolver,
DMG_ASSET_NAME,
diff --git a/docs/src/lib/get-llm-text.test.ts b/docs/src/lib/get-llm-text.test.ts
index bd50922ec..29e6462ee 100644
--- a/docs/src/lib/get-llm-text.test.ts
+++ b/docs/src/lib/get-llm-text.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { getLLMText } from './get-llm-text.ts';
type Page = Parameters<typeof getLLMText>[0];
diff --git a/docs/src/lib/site.test.ts b/docs/src/lib/site.test.ts
index 499c7f4e9..e2d459a4a 100644
--- a/docs/src/lib/site.test.ts
+++ b/docs/src/lib/site.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { metaDescription, SITE_DESCRIPTION } from './site.ts';
const MAX = 160;
diff --git a/docs/src/lib/track.test.ts b/docs/src/lib/track.test.ts
index d53b5e205..756bdf049 100644
--- a/docs/src/lib/track.test.ts
+++ b/docs/src/lib/track.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
attribution,
buildCapturePayload,
diff --git a/docs/src/proxy.test.ts b/docs/src/proxy.test.ts
index 8d6b815c0..f71b1084c 100644
--- a/docs/src/proxy.test.ts
+++ b/docs/src/proxy.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { NextRequest } from 'next/server';
+import { describe, expect, test } from 'vitest';
import { proxy } from './proxy.ts';
/**
diff --git a/docs/vitest.config.ts b/docs/vitest.config.ts
index f7f5da32e..988793e21 100644
--- a/docs/vitest.config.ts
+++ b/docs/vitest.config.ts
@@ -1,6 +1,6 @@
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
-import { bunTestShimPath, okVitestBase } from '../test-support/vitest.base';
+import { okVitestBase } from '../test-support/vitest.base';
/**
* Vitest config for the docs (Next.js) package.
@@ -8,9 +8,8 @@ import { bunTestShimPath, okVitestBase } from '../test-support/vitest.base';
* Spreads the shared workspace base but replaces the alias map: docs route
* tests resolve `@/…` against `docs/src` (and `@/.source` against the generated
* fumadocs content), matching the Next.js `paths` in `docs/tsconfig.json`. The
- * base's object-form alias only carries `bun:test`, so it is re-added here as
- * the first array entry (array form is required to express the ordered `@`
- * prefixes — `.source` must win before the general `@/` rule).
+ * Array form is required to express the ordered `@` prefixes — `.source` must
+ * win before the general `@/` rule.
*/
const docsRoot = fileURLToPath(new URL('.', import.meta.url));
@@ -19,7 +18,6 @@ export default defineConfig({
resolve: {
...okVitestBase.resolve,
alias: [
- { find: 'bun:test', replacement: bunTestShimPath },
{ find: /^@\/\.source(?=$|\/)/, replacement: `${docsRoot}.source` },
{ find: /^@\//, replacement: `${docsRoot}src/` },
],
diff --git a/oxlint.config.ts b/oxlint.config.ts
index 59f115f55..e66dcca8e 100644
--- a/oxlint.config.ts
+++ b/oxlint.config.ts
@@ -61,6 +61,17 @@ export default defineConfig({
},
],
'eslint-js/no-restricted-syntax': ['error', ...restrictedSyntax],
+ 'no-restricted-imports': [
+ 'error',
+ {
+ paths: [
+ {
+ name: 'bun:test',
+ message: 'Import test APIs directly from vitest.',
+ },
+ ],
+ },
+ ],
// TODO(oxlint): enable in priority order as each backlog is audited.
// Correctness rules catch async/control-flow bugs; graduate these first.
'typescript/no-floating-promises': 'off',
diff --git a/packages/app/src/build/app-version.test.ts b/packages/app/src/build/app-version.test.ts
index 5ad0ed168..c0ae732df 100644
--- a/packages/app/src/build/app-version.test.ts
+++ b/packages/app/src/build/app-version.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { APP_VERSION_ENV_VAR, injectAppVersionEnv, resolveAppVersion } from './app-version.ts';
const here = dirname(fileURLToPath(import.meta.url));
diff --git a/packages/app/src/build/chrome-tokens-vite-plugin.test.ts b/packages/app/src/build/chrome-tokens-vite-plugin.test.ts
index 3559b39bc..b21796750 100644
--- a/packages/app/src/build/chrome-tokens-vite-plugin.test.ts
+++ b/packages/app/src/build/chrome-tokens-vite-plugin.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { CHROME_BG_DARK, CHROME_BG_LIGHT } from '../../../core/src/constants/chrome.ts';
import { chromeTokensVitePlugin } from './chrome-tokens-vite-plugin.ts';
diff --git a/packages/app/src/build/rejection-loop-guard-plugin.test.ts b/packages/app/src/build/rejection-loop-guard-plugin.test.ts
index 9eb817eb7..873d7ef71 100644
--- a/packages/app/src/build/rejection-loop-guard-plugin.test.ts
+++ b/packages/app/src/build/rejection-loop-guard-plugin.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { rejectionLoopGuardPlugin } from './rejection-loop-guard-plugin.ts';
import GUARD_SCRIPT from './rejection-loop-guard-script.js?raw';
diff --git a/packages/app/src/components/ActivityPanelBurstRow.test.tsx b/packages/app/src/components/ActivityPanelBurstRow.test.tsx
index dc7c81bb1..d9a489c78 100644
--- a/packages/app/src/components/ActivityPanelBurstRow.test.tsx
+++ b/packages/app/src/components/ActivityPanelBurstRow.test.tsx
@@ -3,8 +3,9 @@
* Click-to-open (row → full-pane AgentDiffPane) and the Restore confirm flow
* are exercised in Playwright.
*/
-import { describe, expect, test } from 'bun:test';
+
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ActivityPanelBurstRow } from './ActivityPanelBurstRow';
diff --git a/packages/app/src/components/ActivityPanelDiffView.test.tsx b/packages/app/src/components/ActivityPanelDiffView.test.tsx
index 6342754cd..04390a7b0 100644
--- a/packages/app/src/components/ActivityPanelDiffView.test.tsx
+++ b/packages/app/src/components/ActivityPanelDiffView.test.tsx
@@ -8,9 +8,10 @@
* - Valid unified-diff input → react-diff-view's Diff component is rendered.
* - Unparseable input doesn't crash (fallback to <pre> or placeholder).
*/
-import { describe, expect, test } from 'bun:test';
+
import { createPatch } from 'diff';
import type { ReactElement, ReactNode } from 'react';
+import { describe, expect, test } from 'vitest';
import { ActivityPanelDiffView } from './ActivityPanelDiffView';
type ElementWithProps = ReactElement<{
diff --git a/packages/app/src/components/ActivityPanelFileRow.test.tsx b/packages/app/src/components/ActivityPanelFileRow.test.tsx
index 17878e0be..256a6220d 100644
--- a/packages/app/src/components/ActivityPanelFileRow.test.tsx
+++ b/packages/app/src/components/ActivityPanelFileRow.test.tsx
@@ -3,8 +3,9 @@
* static HTML shape. Interactive behavior (row click → diff, per-edit Restore
* confirm, onNavigate firing) is exercised in Playwright E2E.
*/
-import { describe, expect, test } from 'bun:test';
+
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { FileData } from '@/lib/use-activity-panel';
import { ActivityPanelFileRow } from './ActivityPanelFileRow';
diff --git a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
index 5ebced4e1..54c0a512a 100644
--- a/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
+++ b/packages/app/src/components/AddPropertyRow.add-property-focus.dom.test.tsx
@@ -16,11 +16,12 @@
* Exercises `render` + `userEvent` under the jsdom substrate; invocation via
* `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import type { FrontmatterType } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useState } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import { type AddDraft, AddPropertyRow } from './FrontmatterRow';
import { DEFAULT_VALUE_FOR_TYPE } from './PropertyWidgets';
diff --git a/packages/app/src/components/AppErrorBoundary.dom.test.tsx b/packages/app/src/components/AppErrorBoundary.dom.test.tsx
index 264213101..e27df6f6b 100644
--- a/packages/app/src/components/AppErrorBoundary.dom.test.tsx
+++ b/packages/app/src/components/AppErrorBoundary.dom.test.tsx
@@ -4,10 +4,11 @@
* nesting contract (document errors stay with DocumentErrorBoundary).
* Invocation via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import type { OkBugReportCreateResult } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { AppErrorBoundary, CrashReportingBoundary } from './AppErrorBoundary';
import { DocumentErrorBoundary } from './DocumentErrorBoundary';
@@ -90,13 +91,13 @@ function clearBugReportBridge() {
}
describe('AppErrorBoundary', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
shouldThrow = false;
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -200,7 +201,7 @@ describe('AppErrorBoundary', () => {
installBugReportBridge();
render(
<AppErrorBoundary>
- <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={mock(() => {})}>
+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={vi.fn(() => {})}>
<MaybeThrow label="alpha" />
</DocumentErrorBoundary>
</AppErrorBoundary>,
@@ -226,11 +227,11 @@ describe('AppErrorBoundary', () => {
});
describe('CrashReportingBoundary', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
shouldThrow = false;
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/AssetPreview.dom.test.tsx b/packages/app/src/components/AssetPreview.dom.test.tsx
index 426783351..78f800b69 100644
--- a/packages/app/src/components/AssetPreview.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.dom.test.tsx
@@ -16,17 +16,18 @@
*
* Runs under `bun run test:dom` (jsdom substrate per precedent #43).
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
@@ -36,7 +37,7 @@ mock.module('@lingui/react/macro', () => ({
// without a provider — stub the app-default view. `mergedConfig` is a knob so
// the indicator tests below can flip the only-markdown axis.
let mergedConfig: { appearance?: { sidebar?: { showOnlyMarkdownFiles?: boolean } } } | null = null;
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: mergedConfig,
projectLocalBinding: null,
@@ -52,7 +53,7 @@ mock.module('@/lib/config-provider', () => ({
// pin `mediaKind="pdf"` → Pdf-branch chosen without mounting the real
// component. Sibling `Pdf.dom.test.tsx` (per `bun run test:dom`'s
// substrate) is the right place for Pdf's internal coverage.
-mock.module('@/editor/components/Pdf', () => ({
+vi.doMock('@/editor/components/Pdf', () => ({
Pdf: (props: { src?: string; title?: string; fillContainer?: boolean }) => (
<div data-testid="pdf-stub" data-src={props.src} data-fill={String(!!props.fillContainer)}>
pdf:{props.title ?? ''}
@@ -63,12 +64,12 @@ mock.module('@/editor/components/Pdf', () => ({
const { AssetPreview } = await import('./AssetPreview');
describe('AssetPreview — image loading-state placeholder (PRD-6638)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx b/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
index 13715e71a..cb042261a 100644
--- a/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
@@ -21,22 +21,23 @@
*
* Runs under `bun run test:dom` (jsdom substrate per precedent #43).
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
// Stub dispatchAssetClick so the button's onClick does not attempt a
// real shell.openAsset IPC or window.open in jsdom. The no-anchor
// assertion is the load-bearing proof; the stub keeps the test
// self-contained and prevents unhandled-promise noise in jsdom.
-const dispatchAssetClickStub = mock(async () => {});
-mock.module('@/editor/asset-dispatch', () => ({
+const dispatchAssetClickStub = vi.fn(async () => {});
+vi.doMock('@/editor/asset-dispatch', () => ({
dispatchAssetClick: dispatchAssetClickStub,
}));
// The asset view hosts the NotInSidebarIndicator, whose config hook throws
// without a provider — stub the app-default view (all fixtures here use
// visible paths, so the indicator stays unmounted).
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: null,
projectLocalBinding: null,
diff --git a/packages/app/src/components/AuthModal.dom.test.tsx b/packages/app/src/components/AuthModal.dom.test.tsx
index 153449c5a..1be5ad1e7 100644
--- a/packages/app/src/components/AuthModal.dom.test.tsx
+++ b/packages/app/src/components/AuthModal.dom.test.tsx
@@ -11,8 +11,8 @@
* device-flow panel renders without touching the network in jsdom.
*/
-import { afterEach, describe, expect, jest, test } from 'bun:test';
import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkLocalOpAuthEvent, OkLocalOpAuthStatusResponse } from '@/lib/desktop-bridge-types';
import type { AuthQueryTransport } from '@/lib/transports/auth-query-transport';
import type { AuthTransport } from '@/lib/transports/auth-transport';
@@ -171,7 +171,7 @@ describe('AuthModal identityPrompt (set-identity) path', () => {
repos: async () => ({ ok: true, host: 'github.com', repos: [] }),
};
- jest.useFakeTimers();
+ vi.useFakeTimers();
try {
renderModal({ identityPrompt: true, queryTransport: hungQuery });
@@ -181,14 +181,14 @@ describe('AuthModal identityPrompt (set-identity) path', () => {
// Advance past the probe timeout — the latch falls back to 'auth'.
act(() => {
- jest.advanceTimersByTime(10_000);
+ vi.advanceTimersByTime(10_000);
});
expect(screen.getByText('Starting sign-in flow')).toBeDefined();
expect(screen.getByText('Connect GitHub')).toBeDefined();
expect(screen.queryByLabelText('Name')).toBeNull();
} finally {
- jest.useRealTimers();
+ vi.useRealTimers();
}
});
diff --git a/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx b/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx
index fa9cefdb6..a387b2112 100644
--- a/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx
+++ b/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
type SyncWriter = (enabled: boolean) => { ok: true } | { ok: false; error: string };
@@ -10,7 +10,7 @@ const toastErrors: string[] = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -19,7 +19,7 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (message: string) => {
toastErrors.push(message);
@@ -27,7 +27,7 @@ mock.module('sonner', () => ({
},
}));
-mock.module('@/hooks/use-enable-sync-with-confirm', () => ({
+vi.doMock('@/hooks/use-enable-sync-with-confirm', () => ({
useSyncEnabledWriter: () => writer,
}));
diff --git a/packages/app/src/components/BetaBadge.dom.test.tsx b/packages/app/src/components/BetaBadge.dom.test.tsx
index b1d80b1c2..5c7934009 100644
--- a/packages/app/src/components/BetaBadge.dom.test.tsx
+++ b/packages/app/src/components/BetaBadge.dom.test.tsx
@@ -1,19 +1,19 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
let channel: 'beta' | 'latest' | null = null;
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@/hooks/use-update-channel', () => ({
+vi.doMock('@/hooks/use-update-channel', () => ({
useUpdateChannel: () => ({ channel }),
}));
diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsx
index df865b66d..ada3a3cdf 100644
--- a/packages/app/src/components/BottomComposer.dom.test.tsx
+++ b/packages/app/src/components/BottomComposer.dom.test.tsx
@@ -379,7 +379,7 @@ function stubReducedMotion(matches: boolean): () => void {
};
}
-let consoleErrorSpy: ReturnType<typeof spyOn>;
+let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
diff --git a/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx b/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx
index 2994b258c..2205fedc1 100644
--- a/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx
+++ b/packages/app/src/components/ClaudeReadinessBanner.dom.test.tsx
@@ -6,20 +6,20 @@
* click triggers) — never on internal call patterns.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';
const toastErrors: string[] = [];
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: { error: (message: string) => toastErrors.push(message) },
}));
const { ClaudeReadinessBanner } = await import('./ClaudeReadinessBanner');
function makeBridge(rewireResult: ClaudeReadiness = { claude: 'present', mcp: 'wired' }) {
- const openExternal = mock(async (_url: string) => {});
- const rewireClaudeMcp = mock(async () => rewireResult);
+ const openExternal = vi.fn(async (_url: string) => {});
+ const rewireClaudeMcp = vi.fn(async () => rewireResult);
const bridge = {
shell: { openExternal },
terminal: { rewireClaudeMcp },
@@ -53,7 +53,7 @@ describe('ClaudeReadinessBanner', () => {
});
test('present + needs-rewire: offers a re-wire affordance and dismisses on success', async () => {
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const { bridge, rewireClaudeMcp, openExternal } = makeBridge();
render(
<ClaudeReadinessBanner
@@ -72,7 +72,7 @@ describe('ClaudeReadinessBanner', () => {
});
test('present + needs-rewire: a rewire that reports an error surfaces a toast and keeps the banner', async () => {
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const { bridge } = makeBridge({
claude: 'present',
mcp: 'needs-rewire',
@@ -121,7 +121,7 @@ describe('ClaudeReadinessBanner', () => {
});
test('exposes a status live region and an accessible dismiss control', () => {
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const { bridge } = makeBridge();
render(
<ClaudeReadinessBanner
diff --git a/packages/app/src/components/CloneDialog.dom.test.tsx b/packages/app/src/components/CloneDialog.dom.test.tsx
index b30506f6d..e73febfe1 100644
--- a/packages/app/src/components/CloneDialog.dom.test.tsx
+++ b/packages/app/src/components/CloneDialog.dom.test.tsx
@@ -7,8 +7,8 @@
* is on the cache-seeded first frame, not a resolved re-check.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { getLastKnownSignedIn, setLastKnownSignedIn } from '@/lib/auth-state-cache';
import type { AuthQueryTransport } from '@/lib/transports/auth-query-transport';
import { CloneDialog } from './CloneDialog';
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
index 21a169adc..3e800ce8c 100644
--- a/packages/app/src/components/CommandPalette.dom.test.tsx
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
__resetLocalMenuActionBusForTests,
subscribeLocalMenuAction,
@@ -58,7 +58,7 @@ const COMMAND_PALETTE_POLL_GRACE_MS = 1400;
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
@@ -67,7 +67,7 @@ mock.module('@lingui/react/macro', () => ({
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@/components/ui/command', () => ({
+vi.doMock('@/components/ui/command', () => ({
CommandDialog: (props: CommandDialogProps) => {
commandDialogProps.push(props);
return props.open ? (
@@ -120,13 +120,13 @@ mock.module('@/components/ui/command', () => ({
),
}));
-mock.module('@/components/doc-panel-events', () => ({
+vi.doMock('@/components/doc-panel-events', () => ({
requestDocPanelTab: (tab: string) => {
requestDocPanelTabCalls.push(tab);
},
}));
-mock.module('@/components/NewItemDialog', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({
NewItemDialog: (props: { open: boolean; kind: string; initialDir: string }) => {
newItemDialogProps.push(props);
return (
@@ -135,14 +135,14 @@ mock.module('@/components/NewItemDialog', () => ({
},
}));
-mock.module('@/components/SeedDialog', () => ({
+vi.doMock('@/components/SeedDialog', () => ({
SeedDialog: (props: { open: boolean }) => {
seedDialogProps.push(props);
return <div data-open={String(props.open)} data-testid="seed-dialog" />;
},
}));
-mock.module('@/components/CreateProjectDialog', () => ({
+vi.doMock('@/components/CreateProjectDialog', () => ({
CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
createProjectDialogProps.push(props);
return (
@@ -155,14 +155,14 @@ mock.module('@/components/CreateProjectDialog', () => ({
},
}));
-mock.module('@/components/ReportBugDialog', () => ({
+vi.doMock('@/components/ReportBugDialog', () => ({
ReportBugDialog: (props: { open: boolean }) => {
reportBugDialogProps.push(props);
return <div data-open={String(props.open)} data-testid="report-bug-dialog" />;
},
}));
-mock.module('@/components/FeedbackFormDialog', () => ({
+vi.doMock('@/components/FeedbackFormDialog', () => ({
FeedbackFormDialog: (props: { open: boolean; source?: string }) => {
feedbackDialogProps.push(props);
return (
@@ -175,7 +175,7 @@ mock.module('@/components/FeedbackFormDialog', () => ({
},
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({
pages: new Set<string>(),
pageTitles: new Map<string, string>(),
@@ -186,49 +186,49 @@ mock.module('@/components/PageListContext', () => ({
}),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName,
activeTarget,
}),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => workspaceValue,
}));
-mock.module('./handoff/useInstalledAgents', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({
states: installedAgentStates,
refresh: refreshInstallStates,
}),
}));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildHandoffInput: ({ docName, workspace }: { docName: string | null; workspace: unknown }) =>
docName && workspace ? { docName, workspace } : null,
useHandoffDispatch: () => ({
- dispatch: mock(() => Promise.resolve()),
+ dispatch: vi.fn(() => Promise.resolve()),
}),
}));
-mock.module('@/components/command-palette-tag-search', () => ({
+vi.doMock('@/components/command-palette-tag-search', () => ({
TAG_QUERY_PREFIX: 'tag:',
parseTagPaletteQuery: () => ({ kind: 'normal' }),
filterTagList: () => [],
- fetchTagsList: mock(() => Promise.resolve([])),
- fetchDocsForTag: mock(() => Promise.resolve([])),
+ fetchTagsList: vi.fn(() => Promise.resolve([])),
+ fetchDocsForTag: vi.fn(() => Promise.resolve([])),
}));
// The cached worktree model is read via useWorktrees (backed by window.okDesktop,
// not the bridge prop). Default null so the existing suite sees no Worktrees
// group; the dedicated test sets a model.
let worktreeModelMock: import('@inkeep/open-knowledge-core').WorktreeSelectorModel | null = null;
-mock.module('@/hooks/use-worktrees', () => ({
+vi.doMock('@/hooks/use-worktrees', () => ({
useWorktrees: () => worktreeModelMock,
}));
-const refreshWorktreesMock = mock(() => {});
-mock.module('@/lib/worktree-store', () => ({ refreshWorktrees: refreshWorktreesMock }));
+const refreshWorktreesMock = vi.fn(() => {});
+vi.doMock('@/lib/worktree-store', () => ({ refreshWorktrees: refreshWorktreesMock }));
function recent(name: string, path = `/projects/${name.toLowerCase()}`) {
return { name, path: path.replaceAll(' ', '-') };
@@ -241,25 +241,25 @@ function createBridge() {
projectPath: '/projects/current',
},
project: {
- listRecent: mock(() =>
+ listRecent: vi.fn(() =>
Promise.resolve([
recent('Current', '/projects/current'),
recent('Alpha', '/projects/alpha'),
recent('Omega', '/archive/omega-project'),
]),
),
- open: mock(() => Promise.resolve()),
- openFile: mock(() => Promise.resolve()),
- removeRecent: mock(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ openFile: vi.fn(() => Promise.resolve()),
+ removeRecent: vi.fn(() => Promise.resolve()),
},
dialog: {
- openFolder: mock(() => Promise.resolve('/chosen/folder')),
+ openFolder: vi.fn(() => Promise.resolve('/chosen/folder')),
},
navigator: {
- open: mock(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
},
worktree: {
- create: mock(() =>
+ create: vi.fn(() =>
Promise.resolve({
ok: true as const,
path: '/projects/current/.ok/worktrees/feature-x',
@@ -269,16 +269,16 @@ function createBridge() {
},
// Surfaces the backfilled bridge-invoke commands reach.
update: {
- checkNow: mock(() => Promise.resolve()),
+ checkNow: vi.fn(() => Promise.resolve()),
},
mcpWiring: {
- reconfigure: mock(() => Promise.resolve(true)),
+ reconfigure: vi.fn(() => Promise.resolve(true)),
},
spellcheck: {
- toggle: mock(() => Promise.resolve(true)),
+ toggle: vi.fn(() => Promise.resolve(true)),
},
shell: {
- openExternal: mock(() => Promise.resolve()),
+ openExternal: vi.fn(() => Promise.resolve()),
},
};
}
@@ -292,7 +292,7 @@ async function renderPalette({
} = {}) {
activeDocName = docName;
activeTarget = docName ? { kind: 'doc', docName } : null;
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
const { CommandPalette } = await import('./CommandPalette');
render(<CommandPalette bridge={bridge as never} open={true} onOpenChange={onOpenChange} />);
await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
@@ -323,7 +323,7 @@ describe('CommandPalette DOM behavior', () => {
worktreeModelMock = null;
refreshWorktreesMock.mockClear();
window.location.hash = '';
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 })),
) as never;
});
@@ -603,7 +603,7 @@ describe('CommandPalette DOM behavior', () => {
test('a query typed during cold load auto-fires the body search once the page list loads', async () => {
pageListLoading = true;
const { CommandPalette } = await import('./CommandPalette');
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
const { rerender } = render(
<CommandPalette bridge={null} open={true} onOpenChange={onOpenChange} />,
);
@@ -632,7 +632,7 @@ describe('CommandPalette DOM behavior', () => {
// First /api/search answers warming; later answers ready with a hit. Any
// non-search fetch (e.g. the semantic-capability probe) stays the default.
let searchCalls = 0;
- globalThis.fetch = mock((input: unknown) => {
+ globalThis.fetch = vi.fn((input: unknown) => {
if (input === '/api/search') {
searchCalls += 1;
const body =
@@ -662,7 +662,7 @@ describe('CommandPalette DOM behavior', () => {
});
test('closing the palette mid-warming stops the poll (no further /api/search calls)', async () => {
- globalThis.fetch = mock((input: unknown) => {
+ globalThis.fetch = vi.fn((input: unknown) => {
if (input === '/api/search') {
return Promise.resolve(
new Response(JSON.stringify({ results: [], ready: false }), { status: 200 }),
@@ -672,7 +672,7 @@ describe('CommandPalette DOM behavior', () => {
}) as never;
const { CommandPalette } = await import('./CommandPalette');
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
const { rerender } = render(
<CommandPalette bridge={null} open={true} onOpenChange={onOpenChange} />,
);
@@ -697,7 +697,7 @@ describe('CommandPalette DOM behavior', () => {
test('a transient error while warming keeps polling and recovers, never showing "Search failed."', async () => {
let call = 0;
- globalThis.fetch = mock((input: unknown) => {
+ globalThis.fetch = vi.fn((input: unknown) => {
if (input === '/api/search') {
call += 1;
if (call === 1) {
@@ -955,7 +955,7 @@ describe('Cmd+K menu-parity backfill', () => {
activeTarget = { kind: 'doc', docName: 'docs/active' };
pageListLoading = false;
window.location.hash = '';
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 })),
) as never;
// Panels visible + a live terminal so the state-aware View toggles render
@@ -1050,7 +1050,7 @@ describe('Cmd+K menu-parity backfill', () => {
// unreachable" gap that the id ratchets alone cannot see.
test('Ratchet C: every classified palette-command id renders a row or is a pre-existing surface', async () => {
// Imported dynamically: the helper pulls in the command registry, and a
- // static import would evaluate the registry before the `mock.module`
+ // static import would evaluate the registry before the `vi.doMock`
// calls above register — freezing real module bindings (e.g.
// doc-panel-events) into it for every test in this file.
const { PALETTE_COMMAND_IDS, PRE_EXISTING_PALETTE_IDS } = await import(
@@ -1094,7 +1094,7 @@ describe('Cmd+K menu-parity backfill', () => {
});
test('AC1: OpenKnowledge on GitHub falls back to window.open on the web host', async () => {
- const openSpy = mock(() => null);
+ const openSpy = vi.fn(() => null);
const originalOpen = window.open;
window.open = openSpy as unknown as typeof window.open;
try {
@@ -1116,8 +1116,8 @@ describe('Cmd+K menu-parity backfill', () => {
// a null prop bridge must take the web `window.open` path and must not
// reach through to an ambient `window.okDesktop` global. Guards the
// injected-bridge seam the shared opener relies on.
- const openSpy = mock(() => null);
- const ambientOpenExternal = mock(() => Promise.resolve());
+ const openSpy = vi.fn(() => null);
+ const ambientOpenExternal = vi.fn(() => Promise.resolve());
const originalOpen = window.open;
window.open = openSpy as unknown as typeof window.open;
(window as { okDesktop?: unknown }).okDesktop = {
diff --git a/packages/app/src/components/CommandPalette.test.ts b/packages/app/src/components/CommandPalette.test.ts
index f79bc5a50..e69df6278 100644
--- a/packages/app/src/components/CommandPalette.test.ts
+++ b/packages/app/src/components/CommandPalette.test.ts
@@ -11,7 +11,7 @@
* DOM-level command visibility, routing, and overlay-prop contracts live in
* `CommandPalette.dom.test.tsx`.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
describe('CommandPalette module', () => {
test('Component module imports cleanly', async () => {
@@ -24,14 +24,14 @@ describe('CommandPalette module', () => {
describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () => {
test('success: no toast.error fires', async () => {
const { runWithToast } = await import('./CommandPalette');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Command failed.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
test('Error rejection: toast.error fires with Error.message', async () => {
const { runWithToast } = await import('./CommandPalette');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(
() => Promise.reject(new Error('utility failed to boot')),
'Command failed.',
@@ -42,21 +42,21 @@ describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () =>
test('non-Error rejection: toast.error fires with fallback', async () => {
const { runWithToast } = await import('./CommandPalette');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject('network dropped'), 'Command failed.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Command failed.');
});
test('empty-message Error: toast.error fires with fallback', async () => {
const { runWithToast } = await import('./CommandPalette');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject(new Error('')), 'Command failed.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Command failed.');
});
test('does not re-throw on rejection (runAction continues)', async () => {
const { runWithToast } = await import('./CommandPalette');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
let afterAwait = false;
await runWithToast(() => Promise.reject(new Error('x')), 'Command failed.', toastApi);
afterAwait = true;
@@ -68,7 +68,7 @@ describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () =>
// first to clear stale state; our adapter must filter the null rather
// than passing it to toast.error(null).
const { runWithToast } = await import('./CommandPalette');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Command failed.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
diff --git a/packages/app/src/components/ComposerContextChips.dom.test.tsx b/packages/app/src/components/ComposerContextChips.dom.test.tsx
index a8c68b288..563b55bb3 100644
--- a/packages/app/src/components/ComposerContextChips.dom.test.tsx
+++ b/packages/app/src/components/ComposerContextChips.dom.test.tsx
@@ -7,12 +7,12 @@
* button removes on click/Enter/Space and on Backspace/Delete when focused.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
diff --git a/packages/app/src/components/ConflictsSection.dom.test.tsx b/packages/app/src/components/ConflictsSection.dom.test.tsx
index 528a299f0..d60286533 100644
--- a/packages/app/src/components/ConflictsSection.dom.test.tsx
+++ b/packages/app/src/components/ConflictsSection.dom.test.tsx
@@ -15,8 +15,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
interface MockConflictsResult {
conflicts: Array<{ file: string; detectedAt: string }>;
@@ -26,7 +27,7 @@ interface MockConflictsResult {
let mockResult: MockConflictsResult = { conflicts: [], loading: false, error: null };
-mock.module('@/hooks/use-conflicts', () => ({
+vi.doMock('@/hooks/use-conflicts', () => ({
useConflicts: () => mockResult,
}));
diff --git a/packages/app/src/components/ConnectingBanner.test.ts b/packages/app/src/components/ConnectingBanner.test.ts
index 2e8d9d943..752de33eb 100644
--- a/packages/app/src/components/ConnectingBanner.test.ts
+++ b/packages/app/src/components/ConnectingBanner.test.ts
@@ -11,7 +11,7 @@
* collabUrl === null + grace → 'retrying'
* collabUrl === null + !grace → 'hidden' (flash prevention)
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeBannerMode, describeError, isNoCollabServerError } from './ConnectingBanner';
describe('computeBannerMode', () => {
diff --git a/packages/app/src/components/ConsentDialogBody.dom.test.tsx b/packages/app/src/components/ConsentDialogBody.dom.test.tsx
index 640912579..50dadb2d1 100644
--- a/packages/app/src/components/ConsentDialogBody.dom.test.tsx
+++ b/packages/app/src/components/ConsentDialogBody.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { ConsentStore } from '@/lib/consent-store';
import type {
OkDesktopBridge,
@@ -10,16 +10,17 @@ import type {
OkOnboardingShowPayload,
} from '@/lib/desktop-bridge-types';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-import ConsentDialogBody from './ConsentDialogBody';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, msg: renderLinguiTemplate }));
+vi.doMock('@lingui/core/macro', () => ({ ...actualLinguiMacro, msg: renderLinguiTemplate }));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
+const { default: ConsentDialogBody } = await import('./ConsentDialogBody');
+
const payload: OkOnboardingShowPayload = {
pickedPath: '/project',
projectDir: '/project',
diff --git a/packages/app/src/components/CopyButton.dom.test.tsx b/packages/app/src/components/CopyButton.dom.test.tsx
index e202d5047..b161f2918 100644
--- a/packages/app/src/components/CopyButton.dom.test.tsx
+++ b/packages/app/src/components/CopyButton.dom.test.tsx
@@ -15,8 +15,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
// CopyButton mounts a Radix Tooltip (focus-scope) which reaches for DOM globals
// the shared jsdom-preload does not expose. Hoist the needed shims — same
diff --git a/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx b/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx
index cef2df945..83fd72fe4 100644
--- a/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx
+++ b/packages/app/src/components/CreateProjectDialog.cascade-staleness.dom.test.tsx
@@ -33,8 +33,9 @@
* the cascade-probe effect's dep-change handling, not in `computeCascade`
* itself.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type {
OkDesktopBridge,
OkFindEnclosingGitRootResult,
@@ -223,12 +224,12 @@ async function waitForLocation(expected = PARENT) {
}
describe('CreateProjectDialog cascade staleness (Tier-3 mount)', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// The dialog's `defaultProjectsRoot` catch + cascade-probe `catch`
// arms log via console.warn; suppress to keep test output clean.
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -787,7 +788,7 @@ describe('CreateProjectDialog cascade staleness (Tier-3 mount)', () => {
// Don't override the implementation — let the real setInterval
// schedule. The test completes well under 5 s, so the real interval
// never fires during the test; we drive it manually instead.
- const setIntervalSpy = spyOn(globalThis, 'setInterval');
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
try {
render(<CreateProjectDialog open={true} onOpenChange={() => {}} bridge={stub.bridge} />);
diff --git a/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx b/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
index a05005587..a072159bc 100644
--- a/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
+++ b/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
@@ -1,14 +1,14 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { ALL_EDITOR_IDS, EDITOR_LABELS } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Spy on the sonner toast surface so the empty-name submit can be asserted
// deterministically (the e2e can't reliably catch the transient portal toast
// in Electron). Mock before importing the component so its `toast` binding
// resolves to the spy.
-const toastErrorSpy = mock((_message: string) => {});
-mock.module('sonner', () => ({
+const toastErrorSpy = vi.fn((_message: string) => {});
+vi.doMock('sonner', () => ({
toast: { error: toastErrorSpy, success: () => {}, warning: () => {}, message: () => {} },
}));
@@ -84,27 +84,27 @@ function makeBridge() {
const bridge = {
fs: {
- defaultProjectsRoot: mock(() => defaultRootImpl()),
- findEnclosingProjectRoot: mock(() => Promise.resolve(null)),
- findEnclosingGitRoot: mock(() => Promise.resolve(null)),
- folderState: mock((path: string) => {
+ defaultProjectsRoot: vi.fn(() => defaultRootImpl()),
+ findEnclosingProjectRoot: vi.fn(() => Promise.resolve(null)),
+ findEnclosingGitRoot: vi.fn(() => Promise.resolve(null)),
+ folderState: vi.fn((path: string) => {
folderStateCalls.push(path);
return folderStateImpl(path);
}),
- removeGitFolder: mock(() => Promise.resolve()),
+ removeGitFolder: vi.fn(() => Promise.resolve()),
},
dialog: {
- openFolder: mock((options?: unknown) => {
+ openFolder: vi.fn((options?: unknown) => {
openFolderArgs.push(options);
return Promise.resolve(pickedParent);
}),
},
project: {
- recordCreateNewBannerShown: mock((banner: string) => {
+ recordCreateNewBannerShown: vi.fn((banner: string) => {
bannerCalls.push(banner);
return Promise.resolve();
}),
- createNew: mock(
+ createNew: vi.fn(
(payload: {
parent: string;
name: string;
@@ -116,7 +116,7 @@ function makeBridge() {
return createNewImpl();
},
),
- open: mock(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
},
} as unknown as OkDesktopBridge;
@@ -142,7 +142,7 @@ function makeBridge() {
}
async function renderDialog(stub = makeBridge()) {
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
render(<CreateProjectDialog open={true} onOpenChange={onOpenChange} bridge={stub.bridge} />);
await screen.findByTestId('create-project-dialog');
return { ...stub, onOpenChange };
@@ -256,7 +256,7 @@ describe('CreateProjectDialog runtime wiring', () => {
// Guard it: expand once, close, reopen, and assert the sharing control is
// gone again (not left mounted from the prior expand).
const stub = makeBridge();
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
const { rerender } = render(
<CreateProjectDialog open={true} onOpenChange={onOpenChange} bridge={stub.bridge} />,
);
@@ -371,7 +371,7 @@ describe('CreateProjectDialog runtime wiring', () => {
// desktop integration tests call `runCreateNew` directly — neither
// exercises the real dialog → bridge payload with a pack).
const stub = makeBridge();
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
render(
<CreateProjectDialog
open={true}
diff --git a/packages/app/src/components/CreateProjectDialog.test.tsx b/packages/app/src/components/CreateProjectDialog.test.tsx
index dab265ab8..c37c3eebe 100644
--- a/packages/app/src/components/CreateProjectDialog.test.tsx
+++ b/packages/app/src/components/CreateProjectDialog.test.tsx
@@ -11,7 +11,7 @@
* `CreateProjectDialog.runtime.dom.test.tsx`; cascade effect behavior lives
* in `CreateProjectDialog.cascade-staleness.dom.test.tsx`.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
basenamePreview,
CreateProjectDialog,
diff --git a/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx b/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx
index 4c1f6ec93..136894849 100644
--- a/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx
+++ b/packages/app/src/components/CreateProjectMenuTrigger.dom.test.tsx
@@ -13,8 +13,9 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import {
__resetLocalMenuActionBusForTests,
@@ -76,12 +77,12 @@ function makeBridge(): OkDesktopBridge {
}
describe('CreateProjectMenuTrigger', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// CreateProjectDialog's defaultProjectsRoot catch arm logs via
// console.warn on unhappy paths; suppress to keep output clean.
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/DiffView.dom.test.tsx b/packages/app/src/components/DiffView.dom.test.tsx
index d95e3da90..8b217b775 100644
--- a/packages/app/src/components/DiffView.dom.test.tsx
+++ b/packages/app/src/components/DiffView.dom.test.tsx
@@ -10,8 +10,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { DiffView } from './DiffView';
describe('DiffView oursOverride (FR3)', () => {
diff --git a/packages/app/src/components/DiffViewBoundary.dom.test.tsx b/packages/app/src/components/DiffViewBoundary.dom.test.tsx
index 420496cb2..8df24012b 100644
--- a/packages/app/src/components/DiffViewBoundary.dom.test.tsx
+++ b/packages/app/src/components/DiffViewBoundary.dom.test.tsx
@@ -9,25 +9,26 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
// `sonner` toasts fire DOM portals; we don't need to render them here.
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: { error: () => {}, success: () => {}, info: () => {} },
}));
// `next-themes` is consumed by DiffView for the CM6 theme. Provide a no-op
// so the test mount doesn't require a ThemeProvider.
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
// `subscribeToDocumentsChanged` is consumed by `useConflicts` (needed for the
// extension-aware file path lookup). The DOM tests don't need CC1 fan-out, so
// return a no-op unsubscriber.
-mock.module('@/lib/documents-events', () => ({
+vi.doMock('@/lib/documents-events', () => ({
subscribeToDocumentsChanged: () => () => {},
}));
@@ -98,7 +99,7 @@ function lastResolveBody(): { file?: string; strategy?: string } {
}
describe('DiffViewBoundary (Tier-3 mount)', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchCalls.length = 0;
@@ -141,7 +142,7 @@ describe('DiffViewBoundary (Tier-3 mount)', () => {
}
return Promise.resolve(new Response('not found', { status: 404 }));
};
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/DocumentBoundary.test.ts b/packages/app/src/components/DocumentBoundary.test.ts
index 52e59f758..4e87dc0f1 100644
--- a/packages/app/src/components/DocumentBoundary.test.ts
+++ b/packages/app/src/components/DocumentBoundary.test.ts
@@ -12,8 +12,8 @@
* dev-mode double-invoke of the component body.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { HocuspocusProvider } from '@hocuspocus/provider';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { __resetSyncPromiseCache, syncPromise } from '@/editor/sync-promise';
import { DocumentBoundary } from './DocumentBoundary';
diff --git a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
index d7e4ec4c1..f9493607f 100644
--- a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
+++ b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
@@ -5,10 +5,11 @@
* `bun run test:dom`. Throw injection follows the MaybeThrow Pattern C
* documented in precedent #43(d).
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import type { OkBugReportCreateResult } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as syncPromiseModule from '@/editor/sync-promise';
import { DocumentErrorBoundary, errorCopy } from './DocumentErrorBoundary';
@@ -90,13 +91,13 @@ function clearBugReportBridge() {
}
describe('DocumentErrorBoundary (Tier-3 mount)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
shouldThrow = false;
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -107,7 +108,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
});
test('renders children when no throw', () => {
- const onRecycle = mock(() => {});
+ const onRecycle = vi.fn(() => {});
render(
<DocumentErrorBoundary activeDocName="alpha.md" onRecycle={onRecycle}>
<MaybeThrow label="hello" />
@@ -120,7 +121,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
test('renders fallback UI with role=alert + heading + try-again button on child throw', () => {
shouldThrow = true;
- const onRecycle = mock(() => {});
+ const onRecycle = vi.fn(() => {});
const error = new Error('MaybeThrow boom: alpha');
const { title } = errorCopy(error);
@@ -145,7 +146,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
test('Try again invokes onRecycle BEFORE the bracket-prefix retry log fires', async () => {
shouldThrow = true;
const callOrder: string[] = [];
- const onRecycle = mock((docName: string) => {
+ const onRecycle = vi.fn((docName: string) => {
callOrder.push(`recycle:${docName}`);
});
consoleWarnSpy.mockImplementation((message: unknown) => {
@@ -174,8 +175,8 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
test('renders Go back button when previousDocName + onNavigateBack are both set', () => {
shouldThrow = true;
- const onRecycle = mock(() => {});
- const onNavigateBack = mock(() => {});
+ const onRecycle = vi.fn(() => {});
+ const onNavigateBack = vi.fn(() => {});
render(
<DocumentErrorBoundary
@@ -194,16 +195,16 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
test('Go back click navigates with previousDocName, invalidates sync promise, and does NOT call onRecycle', async () => {
shouldThrow = true;
- const onRecycle = mock((_docName: string) => {});
- const onNavigateBack = mock((_previousDocName: string) => {});
+ const onRecycle = vi.fn((_docName: string) => {});
+ const onNavigateBack = vi.fn((_previousDocName: string) => {});
// Spy on the named export — ES module live binding lets DocumentErrorBoundary's
// captured `invalidateSyncPromise` reference see the spy's mockImplementation.
// This pins the load-bearing "back-nav clears the cached rejected sync
// promise so re-visiting the errored doc later gets a fresh attempt"
// contract at DocumentErrorBoundary.tsx.
- const invalidateSpy = spyOn(syncPromiseModule, 'invalidateSyncPromise').mockImplementation(
- () => {},
- );
+ const invalidateSpy = vi
+ .spyOn(syncPromiseModule, 'invalidateSyncPromise')
+ .mockImplementation(() => {});
render(
<DocumentErrorBoundary
@@ -239,7 +240,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
shouldThrow = true;
const createCalls = installBugReportBridge();
render(
- <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={mock(() => {})}>
+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={vi.fn(() => {})}>
<MaybeThrow label="alpha" />
</DocumentErrorBoundary>,
);
@@ -269,7 +270,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
shouldThrow = true;
clearBugReportBridge();
render(
- <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={mock(() => {})}>
+ <DocumentErrorBoundary activeDocName="alpha.md" onRecycle={vi.fn(() => {})}>
<MaybeThrow label="alpha" />
</DocumentErrorBoundary>,
);
@@ -280,7 +281,7 @@ describe('DocumentErrorBoundary (Tier-3 mount)', () => {
test('onError logs bracket-prefix console.error including the doc name and error title', () => {
shouldThrow = true;
- const onRecycle = mock(() => {});
+ const onRecycle = vi.fn(() => {});
const error = new Error('MaybeThrow boom: alpha');
const { title } = errorCopy(error);
diff --git a/packages/app/src/components/DocumentErrorBoundary.test.ts b/packages/app/src/components/DocumentErrorBoundary.test.ts
index 09f8d784b..f98e86148 100644
--- a/packages/app/src/components/DocumentErrorBoundary.test.ts
+++ b/packages/app/src/components/DocumentErrorBoundary.test.ts
@@ -8,7 +8,7 @@
* helpers — no DOM, no React renderer, no @testing-library dependency added.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { MountAbortError } from '@/editor/mount-promise';
import {
BridgeSetupError,
diff --git a/packages/app/src/components/EditorActivityPool.lazy.test.ts b/packages/app/src/components/EditorActivityPool.lazy.test.ts
index 006c17b99..8729321fa 100644
--- a/packages/app/src/components/EditorActivityPool.lazy.test.ts
+++ b/packages/app/src/components/EditorActivityPool.lazy.test.ts
@@ -1,10 +1,10 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
describe('EditorActivityPool source lazy boundary', () => {
test('does not import SourceEditor until the lazy loader runs', async () => {
let sourceEditorModuleLoads = 0;
- mock.module('@/editor/SourceEditor', () => {
+ vi.doMock('@/editor/SourceEditor', () => {
sourceEditorModuleLoads += 1;
return {
SourceEditor: () => null,
diff --git a/packages/app/src/components/EditorActivityPool.test.ts b/packages/app/src/components/EditorActivityPool.test.ts
index e605ab03f..7e7cb5db3 100644
--- a/packages/app/src/components/EditorActivityPool.test.ts
+++ b/packages/app/src/components/EditorActivityPool.test.ts
@@ -15,8 +15,8 @@
* 3. Otherwise: top-N by `lastAccessedAt` descending (MRU first).
*/
-import { describe, expect, test } from 'bun:test';
import { SYSTEM_DOC_NAME } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
ACTIVITY_MOUNT_LIMIT,
computeActivityMountList,
diff --git a/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx b/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx
index 69eeb62d0..50ceca095 100644
--- a/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx
+++ b/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx
@@ -18,9 +18,10 @@
*
* Runs under `bun run test:dom` (jsdom substrate).
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
import { Suspense, useEffect, useLayoutEffect, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
__consumeRenameSnapshot,
__resetRenameSnapshotStore,
@@ -92,13 +93,13 @@ const baseSnap = (html: string): RenameSnapshot => ({ html, scrollTop: 0, select
// ---------------------------------------------------------------------------
describe('WarmContentFallback DOM geometry', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
__resetRenameSnapshotStore();
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -144,13 +145,13 @@ describe('WarmContentFallback DOM geometry', () => {
});
describe('rename-snapshot store → warm-fallback selection contract', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
__resetRenameSnapshotStore();
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -218,8 +219,8 @@ describe('rename-snapshot store → warm-fallback selection contract', () => {
describe('warm-fallback scroll restoration', () => {
let scrollContainer: HTMLDivElement;
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
__resetRenameSnapshotStore();
@@ -237,8 +238,8 @@ describe('warm-fallback scroll restoration', () => {
scrollContainer.appendChild(inner);
document.body.appendChild(scrollContainer);
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -284,8 +285,8 @@ describe('warm-fallback scroll restoration', () => {
describe('captureRenameSnapshots — scrollTop capture (DOM)', () => {
let scrollContainer: HTMLDivElement;
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
__resetRenameSnapshotStore();
@@ -297,8 +298,8 @@ describe('captureRenameSnapshots — scrollTop capture (DOM)', () => {
inner.style.height = '5000px';
scrollContainer.appendChild(inner);
document.body.appendChild(scrollContainer);
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
index add6bcdc9..daf102364 100644
--- a/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.share-receive-miss.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { ConfigProvider } from '@/lib/config-provider';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
@@ -18,47 +18,47 @@ const MISSING_DOC_CTX = {
};
let docCtx: typeof MISSING_DOC_CTX = MISSING_DOC_CTX;
-mock.module('@/lib/perf', () => ({
+vi.doMock('@/lib/perf', () => ({
mark: () => {},
ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
}));
-mock.module('@/components/PropertyContext', () => ({
+vi.doMock('@/components/PropertyContext', () => ({
PropertyProvider: ({ children }: { children: ReactNode }) => children,
useProperties: () => ({ requestAddProperty: () => {} }),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => docCtx,
useDocumentTransition: () => ({ openDocumentTransition: null }),
}));
-mock.module('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));
-mock.module('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));
-mock.module('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
-mock.module('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));
-mock.module('@/lib/use-settings-route', () => ({
+vi.doMock('@/hooks/use-document-stats', () => ({ useDocumentStats: () => null }));
+vi.doMock('@/hooks/use-selection-stats', () => ({ useSelectionStats: () => null }));
+vi.doMock('@/hooks/use-lifecycle-status', () => ({ useLifecycleStatus: () => 'ready' }));
+vi.doMock('@/presence/use-sync-status', () => ({ useSyncStatus: () => 'synced' }));
+vi.doMock('@/lib/use-settings-route', () => ({
useSettingsRoute: () => ({ open: false, close: () => {} }),
SETTINGS_OPEN_HASH: '#settings',
isSettingsShortcut: () => false,
}));
-mock.module('@/components/settings/SettingsDialogShell', () => ({
+vi.doMock('@/components/settings/SettingsDialogShell', () => ({
SettingsDialogShell: () => <div data-testid="settings-shell" />,
}));
-mock.module('@/components/EditorSkeleton', () => ({
+vi.doMock('@/components/EditorSkeleton', () => ({
EditorSkeleton: () => <div data-testid="editor-skeleton" />,
}));
-mock.module('@/components/EmptyEditorState', () => ({
+vi.doMock('@/components/EmptyEditorState', () => ({
EmptyEditorState: () => <div data-testid="empty-editor-state" />,
}));
-mock.module('./TerminalDock', () => ({
+vi.doMock('./TerminalDock', () => ({
TerminalDock: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
-mock.module('react-resizable-panels', () => ({
+vi.doMock('react-resizable-panels', () => ({
usePanelRef: () => ({ current: { collapse: () => {}, expand: () => {} } }),
// EditorArea imports `useGroupRef` alongside `usePanelRef`; the mock must
// carry BOTH named exports or the `import { useGroupRef }` binding fails to
// resolve and the whole file errors on load.
useGroupRef: () => ({ current: { getLayout: () => [], setLayout: () => {} } }),
}));
-mock.module('@/components/ui/resizable', () => ({
+vi.doMock('@/components/ui/resizable', () => ({
ResizablePanelGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
ResizablePanel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
ResizableHandle: () => <div />,
@@ -66,7 +66,7 @@ mock.module('@/components/ui/resizable', () => ({
// The share-receive miss panel — stubbed so this test observes only which
// branch EditorArea takes, not the panel's own fetch/verdict behavior (its own
// dom test owns that).
-mock.module('@/components/ShareReceiveMissPanel', () => ({
+vi.doMock('@/components/ShareReceiveMissPanel', () => ({
ShareReceiveMissPanel: ({ nav }: { nav: { path: string } }) => (
<div data-testid="miss-panel" data-path={nav.path} />
),
@@ -74,29 +74,29 @@ mock.module('@/components/ShareReceiveMissPanel', () => ({
// Editor-branch children — stubbed to a marker that surfaces the create-mode
// placeholder, so "fell through to create-mode" is observable without the real
// TipTap/CodeMirror stack.
-mock.module('./EditorActivityPool', () => ({
+vi.doMock('./EditorActivityPool', () => ({
EditorActivityPool: ({ editorPlaceholder }: { editorPlaceholder?: string }) => (
<div data-testid="editor-pool" data-placeholder={editorPlaceholder} />
),
}));
-mock.module('@/editor/find-replace/FindReplaceController', () => ({
+vi.doMock('@/editor/find-replace/FindReplaceController', () => ({
FindReplaceController: () => null,
}));
-mock.module('./EditorToolbar', () => ({
+vi.doMock('./EditorToolbar', () => ({
EditorToolbar: () => <div data-testid="editor-toolbar" />,
}));
-mock.module('./EditorFooter', () => ({ EditorFooter: () => <div data-testid="editor-footer" /> }));
+vi.doMock('./EditorFooter', () => ({ EditorFooter: () => <div data-testid="editor-footer" /> }));
// The create-mode branch mounts BottomComposer, which reaches useConfigContext
// via useHandoffDispatch — stub it out (this test only asserts which primary
// view renders, not the ask-composer, and pulling in the real config context
// is out of scope).
-mock.module('./BottomComposer', () => ({
+vi.doMock('./BottomComposer', () => ({
BottomComposer: () => <div data-testid="bottom-composer" />,
}));
-mock.module('./editor-area-overlay', () => ({ shouldPaintOverlay: () => false }));
+vi.doMock('./editor-area-overlay', () => ({ shouldPaintOverlay: () => false }));
// The editor `else` branch mounts DocPanel as its right panel; it reads
// usePageList, so stub it out — this test only cares which primary view renders.
-mock.module('@/components/DocPanel', () => ({ DocPanel: () => <div data-testid="doc-panel" /> }));
+vi.doMock('@/components/DocPanel', () => ({ DocPanel: () => <div data-testid="doc-panel" /> }));
const { EditorArea } = await import('./EditorArea');
diff --git a/packages/app/src/components/EditorArea.test.ts b/packages/app/src/components/EditorArea.test.ts
index b409a2f13..fe2689457 100644
--- a/packages/app/src/components/EditorArea.test.ts
+++ b/packages/app/src/components/EditorArea.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('EditorArea module', () => {
test('exports EditorArea component', async () => {
diff --git a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
index 80b95aa08..9d9b3db75 100644
--- a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
+++ b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
@@ -10,8 +10,9 @@
* Exercises `render` under the jsdom substrate (precedent #43); invocation
* via `bunx turbo run test:dom`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
import { EditorBreadcrumb } from './EditorBreadcrumb';
diff --git a/packages/app/src/components/EditorFooter.dom.test.tsx b/packages/app/src/components/EditorFooter.dom.test.tsx
index 4ecb108d9..569c53fa4 100644
--- a/packages/app/src/components/EditorFooter.dom.test.tsx
+++ b/packages/app/src/components/EditorFooter.dom.test.tsx
@@ -3,13 +3,14 @@
* brings the dismissed bottom composer back. Identity + lingui are mocked so the
* test is scoped to the badge's presence + click wiring next to the stats.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { DocumentStats } from '@/lib/document-stats';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
@@ -22,7 +23,7 @@ mock.module('@lingui/react/macro', () => ({
}));
// No project/branch identity — keep the footer scoped to stats + badge.
-mock.module('@/hooks/use-editor-footer-identity', () => ({
+vi.doMock('@/hooks/use-editor-footer-identity', () => ({
useEditorFooterIdentity: () => null,
}));
@@ -47,7 +48,7 @@ describe('EditorFooter (Ask AI reopen badge)', () => {
});
test('clicking the badge calls onReopen', async () => {
- const onReopen = mock(() => {});
+ const onReopen = vi.fn(() => {});
await renderFooter({ onReopen });
fireEvent.click(screen.getByTestId('ask-ai-reopen-badge'));
diff --git a/packages/app/src/components/EditorHeader.dom.test.tsx b/packages/app/src/components/EditorHeader.dom.test.tsx
index 6964859ca..3643d5b08 100644
--- a/packages/app/src/components/EditorHeader.dom.test.tsx
+++ b/packages/app/src/components/EditorHeader.dom.test.tsx
@@ -1,14 +1,14 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -24,11 +24,11 @@ let isDraggingRail = false;
// Captures the `input` prop EditorHeader hands to ShareButton.
let lastShareInput: unknown;
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({ activeDocName, activeTarget }),
}));
-mock.module('@/components/ui/sidebar', () => ({
+vi.doMock('@/components/ui/sidebar', () => ({
useSidebar: () => ({ state: sidebarState, isDraggingRail }),
SidebarTrigger: ({ className }: { className?: string }) => (
<button type="button" data-testid="sidebar-trigger" className={className}>
@@ -37,11 +37,11 @@ mock.module('@/components/ui/sidebar', () => ({
),
}));
-mock.module('./EditorTabs', () => ({
+vi.doMock('./EditorTabs', () => ({
EditorTabs: () => <div data-testid="editor-tabs" />,
}));
-mock.module('./ShareButton', () => ({
+vi.doMock('./ShareButton', () => ({
ShareButton: ({ input }: { input: unknown }) => {
lastShareInput = input;
return (
@@ -52,29 +52,29 @@ mock.module('./ShareButton', () => ({
},
}));
-mock.module('./PublishToGitHubDialog', () => ({
+vi.doMock('./PublishToGitHubDialog', () => ({
PublishToGitHubDialog: ({ open }: { open: boolean }) => (
<div data-testid="publish-dialog" data-open={String(open)} />
),
}));
-mock.module('./SyncStatusBadge', () => ({
+vi.doMock('./SyncStatusBadge', () => ({
SyncStatusBadge: () => <div data-testid="sync-status-badge" />,
}));
-mock.module('@/presence/PresenceBar', () => ({
+vi.doMock('@/presence/PresenceBar', () => ({
PresenceBar: () => <div data-testid="presence-bar" />,
}));
-mock.module('./BetaBadge', () => ({
+vi.doMock('./BetaBadge', () => ({
BetaBadge: () => <div data-testid="beta-badge" />,
}));
-mock.module('./SettingsButton', () => ({
+vi.doMock('./SettingsButton', () => ({
SettingsButton: () => <button type="button">Settings</button>,
}));
-mock.module('./HelpPopover', () => ({
+vi.doMock('./HelpPopover', () => ({
HelpPopover: () => <button type="button">Resources</button>,
}));
diff --git a/packages/app/src/components/EditorTabs.dnd-portal.dom.test.tsx b/packages/app/src/components/EditorTabs.dnd-portal.dom.test.tsx
index 9ab645a36..01c8f9ad6 100644
--- a/packages/app/src/components/EditorTabs.dnd-portal.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dnd-portal.dom.test.tsx
@@ -16,10 +16,11 @@
* `:first-child` slot, leaving `+` 6px below where the icon-row sits
* (cy=37 instead of cy=32 in a 48px header).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { DndContext } from '@dnd-kit/core';
import { SortableContext } from '@dnd-kit/sortable';
import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
function StripFixture({ items, withPortal }: { items: string[]; withPortal: boolean }) {
return (
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
index 0756a4ba5..914a37e4c 100644
--- a/packages/app/src/components/EditorTabs.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, jest, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { isMacOS } from '@tiptap/core';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { assetTabId, folderTabId } from '@/editor/editor-tabs';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
@@ -22,19 +22,19 @@ let pageMeta: Map<string, { docExt?: string }> = new Map();
let lifecycleStatuses: Map<string, string> = new Map();
let toastErrors: string[] = [];
-const activateTab = mock(() => {});
-const activateNewTab = mock(() => {});
-const closeAndClearForRename = mock(() => Promise.resolve());
-const closeNewTab = mock(() => {});
-const closeTab = mock(() => {});
-const closeTabs = mock(() => {});
-const getPoolActiveDocName = mock(() => null as string | null);
-const openNewTab = mock(() => {});
-const pinTab = mock(() => {});
-const reopenClosedTab = mock(() => {});
-const remapTabsForRename = mock(() => {});
-const reorderTabs = mock(() => {});
-const unpinTab = mock(() => {});
+const activateTab = vi.fn(() => {});
+const activateNewTab = vi.fn(() => {});
+const closeAndClearForRename = vi.fn(() => Promise.resolve());
+const closeNewTab = vi.fn(() => {});
+const closeTab = vi.fn(() => {});
+const closeTabs = vi.fn(() => {});
+const getPoolActiveDocName = vi.fn(() => null as string | null);
+const openNewTab = vi.fn(() => {});
+const pinTab = vi.fn(() => {});
+const reopenClosedTab = vi.fn(() => {});
+const remapTabsForRename = vi.fn(() => {});
+const reorderTabs = vi.fn(() => {});
+const unpinTab = vi.fn(() => {});
function primaryShortcutModifier(): Pick<KeyboardEventInit, 'ctrlKey' | 'metaKey'> {
return isMacOS() ? { metaKey: true } : { ctrlKey: true };
@@ -59,13 +59,13 @@ const sortableOptions: Array<{ id: string; disabled?: boolean }> = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@dnd-kit/core', () => ({
+vi.doMock('@dnd-kit/core', () => ({
closestCenter: closestCenterToken,
DndContext: (props: DndContextProps) => {
dndContextProps.push(props);
@@ -91,7 +91,7 @@ mock.module('@dnd-kit/core', () => ({
useSensors: (...sensors: unknown[]) => sensors,
}));
-mock.module('@dnd-kit/sortable', () => ({
+vi.doMock('@dnd-kit/sortable', () => ({
arrayMove: <T,>(items: T[], from: number, to: number) => {
const next = [...items];
const [item] = next.splice(from, 1);
@@ -130,7 +130,7 @@ mock.module('@dnd-kit/sortable', () => ({
},
}));
-mock.module('@dnd-kit/utilities', () => ({
+vi.doMock('@dnd-kit/utilities', () => ({
CSS: {
Transform: {
toString: () => undefined,
@@ -138,7 +138,7 @@ mock.module('@dnd-kit/utilities', () => ({
},
}));
-mock.module('@/components/ui/context-menu', () => ({
+vi.doMock('@/components/ui/context-menu', () => ({
ContextMenu: ({ children }: { children?: ReactNode }) => <>{children}</>,
ContextMenuContent: ({ children, className }: { children?: ReactNode; className?: string }) => (
<div className={className} role="menu">
@@ -172,13 +172,13 @@ mock.module('@/components/ui/context-menu', () => ({
ContextMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
-mock.module('@/components/ui/tooltip', () => ({
+vi.doMock('@/components/ui/tooltip', () => ({
Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
TooltipContent: ({ children }: { children?: ReactNode }) => <div role="tooltip">{children}</div>,
TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName,
activeNewTabId,
@@ -205,17 +205,17 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({
pageMeta,
}),
}));
-mock.module('@/hooks/use-lifecycle-status', () => ({
+vi.doMock('@/hooks/use-lifecycle-status', () => ({
useLifecycleStatus: (docName: string) => lifecycleStatuses.get(docName) ?? null,
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (message: string) => {
toastErrors.push(message);
@@ -283,7 +283,7 @@ function resetState() {
value: undefined,
});
window.location.hash = '';
- globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
}
async function renderEditorTabs() {
@@ -487,7 +487,7 @@ describe('EditorTabs runtime behavior', () => {
});
test('modifier hold delays per-tab shortcut hints and non-active close affordances', async () => {
- jest.useFakeTimers();
+ vi.useFakeTimers();
try {
await renderEditorTabs();
@@ -506,7 +506,7 @@ describe('EditorTabs runtime behavior', () => {
);
act(() => {
- jest.advanceTimersByTime(999);
+ vi.advanceTimersByTime(999);
});
expect(screen.queryAllByTestId('editor-tab-shortcut-hint')).toHaveLength(0);
@@ -516,7 +516,7 @@ describe('EditorTabs runtime behavior', () => {
);
act(() => {
- jest.advanceTimersByTime(1);
+ vi.advanceTimersByTime(1);
});
expect(
@@ -532,7 +532,7 @@ describe('EditorTabs runtime behavior', () => {
fireEvent.keyDown(window, { key: 'Meta', metaKey: true });
act(() => {
- jest.advanceTimersByTime(1000);
+ vi.advanceTimersByTime(1000);
});
expect(screen.getAllByTestId('editor-tab-shortcut-hint')).toHaveLength(6);
@@ -541,7 +541,7 @@ describe('EditorTabs runtime behavior', () => {
expect(screen.queryAllByTestId('editor-tab-shortcut-hint')).toHaveLength(0);
expect(screen.getByRole('button', { name: 'Close docs/team/notes.md' })).toBeTruthy();
} finally {
- jest.useRealTimers();
+ vi.useRealTimers();
}
});
@@ -627,7 +627,7 @@ describe('EditorTabs runtime behavior', () => {
remapTabsForRename.mockImplementation(() => {
throw new Error('idb clear failed');
});
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(
new Response(
JSON.stringify({
diff --git a/packages/app/src/components/EditorTabs.test.ts b/packages/app/src/components/EditorTabs.test.ts
index 56b2265fa..4f2dccab9 100644
--- a/packages/app/src/components/EditorTabs.test.ts
+++ b/packages/app/src/components/EditorTabs.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('EditorTabs module', () => {
test('exports the EditorTabs component', async () => {
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index bce95815f..e7cf86940 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -1,18 +1,18 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('./EditorBreadcrumb', () => ({
+vi.doMock('./EditorBreadcrumb', () => ({
EditorBreadcrumb: ({ docName }: { docName: string | null }) => (
<span data-testid="editor-breadcrumb-probe">{docName}</span>
),
@@ -21,7 +21,7 @@ mock.module('./EditorBreadcrumb', () => ({
// The breadcrumb cell's NotInSidebarIndicator reads merged config through the
// context hook, which throws without a provider — stub the app-default view
// (no toggles set, binding absent) so the toolbar mounts standalone.
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: null,
projectLocalBinding: null,
diff --git a/packages/app/src/components/EmptyEditorState.dom.test.tsx b/packages/app/src/components/EmptyEditorState.dom.test.tsx
index ad0884c6a..f920f5ad2 100644
--- a/packages/app/src/components/EmptyEditorState.dom.test.tsx
+++ b/packages/app/src/components/EmptyEditorState.dom.test.tsx
@@ -9,12 +9,13 @@
* the document-list fetch are mocked at the module boundary so the assertions
* pin exactly the branch this component owns.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -25,35 +26,35 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('@/components/empty-state/EmptyStateHeader', () => ({
+vi.doMock('@/components/empty-state/EmptyStateHeader', () => ({
EmptyStateHeader: () => <div data-testid="empty-state-header" />,
}));
-mock.module('@/components/empty-state/empty-state-copy', () => ({
+vi.doMock('@/components/empty-state/empty-state-copy', () => ({
getEmptyStateCopy: () => ({ title: 'title', subtitle: 'subtitle' }),
}));
-mock.module('@/components/empty-state/CreateView', () => ({
+vi.doMock('@/components/empty-state/CreateView', () => ({
CreateView: () => <div data-testid="create-view" />,
}));
-mock.module('@/components/empty-state/CreatePromptComposer', () => ({
+vi.doMock('@/components/empty-state/CreatePromptComposer', () => ({
CreatePromptComposer: () => <div data-testid="create-prompt-composer" />,
}));
-mock.module('@/components/empty-state/CopyablePromptList', () => ({
+vi.doMock('@/components/empty-state/CopyablePromptList', () => ({
CopyablePromptList: () => <div data-testid="copyable-prompt-list" />,
}));
-mock.module('@/components/PackCardGrid', () => ({
+vi.doMock('@/components/PackCardGrid', () => ({
PackCardGrid: () => <div data-testid="pack-card-grid" />,
}));
-mock.module('@/components/SeedDialog', () => ({
+vi.doMock('@/components/SeedDialog', () => ({
SeedDialog: () => null,
}));
-mock.module('@/hooks/use-is-embedded', () => ({
+vi.doMock('@/hooks/use-is-embedded', () => ({
useIsEmbedded: () => false,
}));
-mock.module('@/lib/documents-events', () => ({
+vi.doMock('@/lib/documents-events', () => ({
subscribeToDocumentsChanged: () => () => {},
}));
// One existing document → the non-onboarding (CreateView) branch of the full view.
-mock.module('@/lib/documents-fetch', () => ({
+vi.doMock('@/lib/documents-fetch', () => ({
fetchDocumentListShared: async () => ({
ok: true,
body: { documents: [{ kind: 'document', docName: 'welcome' }] },
diff --git a/packages/app/src/components/EmptyEditorState.test.ts b/packages/app/src/components/EmptyEditorState.test.ts
index 1e44a83be..765852817 100644
--- a/packages/app/src/components/EmptyEditorState.test.ts
+++ b/packages/app/src/components/EmptyEditorState.test.ts
@@ -9,7 +9,7 @@
* folders fill the empty state with infrastructure.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { countEntries } from './EmptyEditorState';
describe('countEntries() — onboarding gate', () => {
diff --git a/packages/app/src/components/FeedbackMenuTrigger.dom.test.tsx b/packages/app/src/components/FeedbackMenuTrigger.dom.test.tsx
index e43cf4bf0..cb40fc0ae 100644
--- a/packages/app/src/components/FeedbackMenuTrigger.dom.test.tsx
+++ b/packages/app/src/components/FeedbackMenuTrigger.dom.test.tsx
@@ -11,8 +11,8 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetLocalMenuActionBusForTests,
emitLocalMenuAction,
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
index b93fe32f1..57cccc2a9 100644
--- a/packages/app/src/components/FileSidebar.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { type ReactNode, useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
expectVisualClassTokens,
@@ -93,16 +93,16 @@ let pillRenderErrors: unknown[][] = [];
const treeListeners = new Set<() => void>();
const treeCalls = {
- collapseAll: mock(() => {}),
- createFromTemplate: mock((_parentDir: string, _templateName: string) => {}),
- expandAll: mock(() => {}),
- startCreating: mock((_kind: 'file' | 'folder', _parentDir: string) => {}),
- startCreatingFromTemplate: mock((_parentDir: string) => {}),
+ collapseAll: vi.fn(() => {}),
+ createFromTemplate: vi.fn((_parentDir: string, _templateName: string) => {}),
+ expandAll: vi.fn(() => {}),
+ startCreating: vi.fn((_kind: 'file' | 'folder', _parentDir: string) => {}),
+ startCreatingFromTemplate: vi.fn((_parentDir: string) => {}),
};
-const projectLocalPatch = mock((_patch: unknown) => projectPatchResult);
-const showItemInFolderMock = mock((_path: string) => Promise.resolve());
-const notifyViewMenuStateChangedMock = mock((_snapshot: unknown) => {});
-const onOpenSearch = mock(() => {});
+const projectLocalPatch = vi.fn((_patch: unknown) => projectPatchResult);
+const showItemInFolderMock = vi.fn((_path: string) => Promise.resolve());
+const notifyViewMenuStateChangedMock = vi.fn((_snapshot: unknown) => {});
+const onOpenSearch = vi.fn(() => {});
function setFolderState(next: FolderState) {
folderState = next;
@@ -127,17 +127,17 @@ function installBridge() {
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@/lib/perf', () => ({
+vi.doMock('@/lib/perf', () => ({
ProfilerBoundary: PassThrough,
}));
-mock.module('@/components/FileTree', () => ({
+vi.doMock('@/components/FileTree', () => ({
FileTree: ({ ref }: { ref?: (handle: unknown) => void }) => {
useEffect(() => {
const handle = {
@@ -160,22 +160,22 @@ mock.module('@/components/FileTree', () => ({
},
}));
-mock.module('@/components/ConflictsSection', () => ({
+vi.doMock('@/components/ConflictsSection', () => ({
ConflictsSection: () => <div data-testid="conflicts-section" />,
}));
// Heavy sidebar child (pulls in skill-actions → dropdown submenu + handoff
// builders). Not under test here; stubbed like FileTree/ConflictsSection so the
// sidebar's own behavior tests don't depend on the skills subtree's deep graph.
-mock.module('@/components/SkillsSidebarSection', () => ({
+vi.doMock('@/components/SkillsSidebarSection', () => ({
SkillsSidebarSection: () => <div data-testid="skills-sidebar-section" />,
}));
-mock.module('@/components/ProjectSwitcher', () => ({
+vi.doMock('@/components/ProjectSwitcher', () => ({
ProjectSwitcher: () => <button type="button">Project switcher</button>,
}));
-mock.module('@/components/SidebarSearchBar', () => ({
+vi.doMock('@/components/SidebarSearchBar', () => ({
SidebarSearchBar: ({ onClick }: { onClick: () => void }) => {
if (sidebarSearchThrows) throw new Error('search pill render failed');
return (
@@ -189,18 +189,18 @@ mock.module('@/components/SidebarSearchBar', () => ({
},
}));
-mock.module('@/components/UpdateNotices', () => ({
+vi.doMock('@/components/UpdateNotices', () => ({
UpdateNotices: () => <div data-testid="update-notices" />,
}));
-mock.module('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
+vi.doMock('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
OpenInAgentEmptySpaceSubmenu: (props: { input: unknown }) => {
openInAgentSubmenuProps.push(props);
return <div data-testid="open-in-agent-empty-space-submenu" />;
},
}));
-mock.module('@/components/handoff/useHandoffDispatch', () => ({
+vi.doMock('@/components/handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => ({ docContext: null, docPath: '', folderRelativePath: 'docs' }),
buildHandoffInput: () => ({
docContext: { docName: 'docs/current' },
@@ -208,18 +208,18 @@ mock.module('@/components/handoff/useHandoffDispatch', () => ({
}),
buildProjectScopedHandoffInput: ({ workspace: inputWorkspace }: { workspace: unknown }) =>
inputWorkspace ? { docContext: null, docPath: '', projectDir: '/tmp/open-knowledge' } : null,
- useHandoffDispatch: () => ({ dispatch: mock(() => Promise.resolve({ ok: true })) }),
+ useHandoffDispatch: () => ({ dispatch: vi.fn(() => Promise.resolve({ ok: true })) }),
}));
-mock.module('@/components/handoff/useInstalledAgents', () => ({
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: { codex: { installed: true } } }),
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button,
}));
-mock.module('@/components/ui/context-menu', () => ({
+vi.doMock('@/components/ui/context-menu', () => ({
ContextMenu: PassThrough,
ContextMenuContent: ({ children }: { children?: ReactNode }) => <div role="menu">{children}</div>,
ContextMenuItem: ({
@@ -278,7 +278,7 @@ mock.module('@/components/ui/context-menu', () => ({
ContextMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: ({
checked,
@@ -323,7 +323,7 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/sidebar', () => ({
+vi.doMock('@/components/ui/sidebar', () => ({
Sidebar: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<aside data-testid="sidebar" {...props}>
{children}
@@ -355,13 +355,13 @@ mock.module('@/components/ui/sidebar', () => ({
useSidebar: () => ({ state: sidebarState }),
}));
-mock.module('@/components/ui/tooltip', () => ({
+vi.doMock('@/components/ui/tooltip', () => ({
Tooltip: PassThrough,
TooltipContent: ({ children }: { children?: ReactNode }) => <div role="tooltip">{children}</div>,
TooltipTrigger: PassThrough,
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName,
activeTarget,
@@ -392,7 +392,7 @@ function templateEntries(folderPath: string | null) {
];
}
-mock.module('@/hooks/use-folder-config', () => ({
+vi.doMock('@/hooks/use-folder-config', () => ({
useFolderConfig: (folderPath: string | null) => ({
state: {
status: 'ready',
@@ -401,7 +401,7 @@ mock.module('@/hooks/use-folder-config', () => ({
}),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: mergedConfig,
projectLocalBinding: projectLocalBindingNull
@@ -412,11 +412,11 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => workspace,
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (...args: unknown[]) => toastErrors.push(args),
success: (...args: unknown[]) => toastSuccesses.push(args),
@@ -466,7 +466,7 @@ describe('FileSidebar runtime behavior', () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
- writeText: mock(() => Promise.resolve()),
+ writeText: vi.fn(() => Promise.resolve()),
},
});
});
@@ -906,7 +906,7 @@ describe('FileSidebar runtime behavior', () => {
test('search pill render failures are contained to the pill row and reset when sidebar state changes', async () => {
const originalConsoleError = console.error;
- console.error = mock(() => {}) as never;
+ console.error = vi.fn(() => {}) as never;
try {
sidebarSearchThrows = true;
const rendered = await renderSidebar();
diff --git a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
index 8b11ccc47..e9ce3de8a 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, waitFor } from '@testing-library/react';
import { type ReactNode, useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ResolvedNavigationTarget } from './navigation-targets';
type MenuAction =
@@ -55,19 +55,19 @@ const ACTIVE_TARGET = {
} satisfies ResolvedNavigationTarget;
let activeTarget: ResolvedNavigationTarget | null = ACTIVE_TARGET;
-const notifyViewMenuStateChangedMock = mock(() => {});
-const toggleSidebarMock = mock(() => {});
-const showItemInFolderMock = mock((_path: string) => Promise.resolve());
-const handoffDispatchMock = mock((_target: string, _input: unknown) =>
+const notifyViewMenuStateChangedMock = vi.fn(() => {});
+const toggleSidebarMock = vi.fn(() => {});
+const showItemInFolderMock = vi.fn((_path: string) => Promise.resolve());
+const handoffDispatchMock = vi.fn((_target: string, _input: unknown) =>
Promise.resolve({ ok: true }),
);
const treeCalls = {
- collapseAll: mock(() => {}),
- expandAll: mock(() => {}),
- startCreating: mock((_kind: 'file' | 'folder', _parentDir: string) => {}),
- startCreatingFromTemplate: mock((_parentDir: string) => {}),
+ collapseAll: vi.fn(() => {}),
+ expandAll: vi.fn(() => {}),
+ startCreating: vi.fn((_kind: 'file' | 'folder', _parentDir: string) => {}),
+ startCreatingFromTemplate: vi.fn((_parentDir: string) => {}),
};
-const projectLocalPatch = mock((_patch: unknown) => ({ ok: true as const }));
+const projectLocalPatch = vi.fn((_patch: unknown) => ({ ok: true as const }));
// Production `projectLocalBinding` keeps its identity across config-value
// changes (the provider swaps only `config` on binding updates), so the
// menu-action effect re-binds on a visibility flip ONLY when the flipped
@@ -80,11 +80,11 @@ const DEFAULT_MERGED_CONFIG = { appearance: { sidebar: { showHiddenFiles: false
let mergedConfig: { appearance?: { sidebar?: Record<string, boolean> } } = DEFAULT_MERGED_CONFIG;
let menuActionCallback: ((action: MenuAction) => void) | null = null;
-mock.module('@/lib/perf', () => ({
+vi.doMock('@/lib/perf', () => ({
ProfilerBoundary: PassThrough,
}));
-mock.module('@/components/FileTree', () => ({
+vi.doMock('@/components/FileTree', () => ({
FileTree: ({ ref }: { ref?: (handle: unknown) => void }) => {
useEffect(() => {
const handle = {
@@ -103,15 +103,15 @@ mock.module('@/components/FileTree', () => ({
},
}));
-mock.module('@/components/ConflictsSection', () => ({
+vi.doMock('@/components/ConflictsSection', () => ({
ConflictsSection: () => null,
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button,
}));
-mock.module('@/components/ui/sidebar', () => ({
+vi.doMock('@/components/ui/sidebar', () => ({
Sidebar: ElementPassThrough,
SidebarContent: ElementPassThrough,
SidebarFooter: ElementPassThrough,
@@ -129,11 +129,11 @@ mock.module('@/components/ui/sidebar', () => ({
// primitive set (SidebarMenuButton, SidebarGroup*) plus useSkills. This
// menu-action test is about the file tree's context menu, not skills — stub the
// section so its imports don't need mocking here.
-mock.module('@/components/SkillsSidebarSection', () => ({
+vi.doMock('@/components/SkillsSidebarSection', () => ({
SkillsSidebarSection: () => null,
}));
-mock.module('@/components/ui/context-menu', () => ({
+vi.doMock('@/components/ui/context-menu', () => ({
ContextMenu: PassThrough,
ContextMenuCheckboxItem: Button,
ContextMenuContent: ElementPassThrough,
@@ -145,7 +145,7 @@ mock.module('@/components/ui/context-menu', () => ({
ContextMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: ({
checked,
@@ -175,17 +175,17 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/tooltip', () => ({
+vi.doMock('@/components/ui/tooltip', () => ({
Tooltip: PassThrough,
TooltipContent: ElementPassThrough,
TooltipTrigger: PassThrough,
}));
-mock.module('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
+vi.doMock('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
OpenInAgentEmptySpaceSubmenu: () => null,
}));
-mock.module('@/components/handoff/useHandoffDispatch', () => ({
+vi.doMock('@/components/handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => ({ docContext: null, docPath: '', folderRelativePath: 'notes' }),
buildHandoffInput: () => ({
docContext: { docName: 'notes/source' },
@@ -204,31 +204,31 @@ mock.module('@/components/handoff/useHandoffDispatch', () => ({
// a fresh object per render would churn the menu-action effect's
// `handoffInstallStates` dep and re-subscribe on every render.
const installedAgentStates = { codex: { installed: true } };
-mock.module('@/components/handoff/useInstalledAgents', () => ({
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: installedAgentStates }),
}));
-mock.module('@/components/ProjectSwitcher', () => ({
+vi.doMock('@/components/ProjectSwitcher', () => ({
ProjectSwitcher: () => null,
}));
-mock.module('@/components/SidebarSearchBar', () => ({
+vi.doMock('@/components/SidebarSearchBar', () => ({
SidebarSearchBar: () => <button type="button">Search</button>,
onPillRenderError: () => {},
}));
-mock.module('@/components/UpdateNotices', () => ({
+vi.doMock('@/components/UpdateNotices', () => ({
UpdateNotices: () => null,
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
activeTarget,
}),
}));
-mock.module('@/hooks/use-folder-config', () => ({
+vi.doMock('@/hooks/use-folder-config', () => ({
useFolderConfig: () => ({
state: {
status: 'ready',
@@ -237,7 +237,7 @@ mock.module('@/hooks/use-folder-config', () => ({
}),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalBinding: projectLocalBindingStub,
merged: mergedConfig,
@@ -250,14 +250,14 @@ const workspaceStub = {
contentDir: '/tmp/open-knowledge',
pathSeparator: '/',
};
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => workspaceStub,
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
- error: mock(() => {}),
- success: mock(() => {}),
+ error: vi.fn(() => {}),
+ success: vi.fn(() => {}),
},
}));
@@ -289,7 +289,7 @@ describe('FileSidebar menu-action runtime routing', () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
- writeText: mock(() => Promise.resolve()),
+ writeText: vi.fn(() => Promise.resolve()),
},
});
Object.defineProperty(window, 'okDesktop', {
diff --git a/packages/app/src/components/FileSidebar.share.dom.test.tsx b/packages/app/src/components/FileSidebar.share.dom.test.tsx
index 51608bf4b..e36be892c 100644
--- a/packages/app/src/components/FileSidebar.share.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.share.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Controls the mocked git-sync hook's hasRemote signal per test.
let hasRemote = true;
// Captures the input runShareAction receives.
let lastShareInput: unknown;
-const runShareActionMock = mock(async (input: unknown) => {
+const runShareActionMock = vi.fn(async (input: unknown) => {
lastShareInput = input;
return { kind: 'copied' as const, shareUrl: 'https://example.test/x', branch: 'main' };
});
@@ -62,15 +62,15 @@ function Button({
);
}
-mock.module('@/lib/perf', () => ({ ProfilerBoundary: PassThrough }));
+vi.doMock('@/lib/perf', () => ({ ProfilerBoundary: PassThrough }));
-mock.module('@/components/FileTree', () => ({
+vi.doMock('@/components/FileTree', () => ({
FileTree: () => <div data-testid="file-tree-stub" />,
}));
-mock.module('@/components/ConflictsSection', () => ({ ConflictsSection: () => null }));
+vi.doMock('@/components/ConflictsSection', () => ({ ConflictsSection: () => null }));
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatusDetailed: () => ({
status: { hasRemote, syncEnabled: hasRemote, behind: 0, ahead: 0 },
fetchError: null,
@@ -78,18 +78,18 @@ mock.module('@/hooks/use-git-sync-status', () => ({
useGitSyncStatus: () => ({ hasRemote, syncEnabled: hasRemote, behind: 0, ahead: 0 }),
}));
-mock.module('@/lib/share/clipboard-adapter', () => ({
+vi.doMock('@/lib/share/clipboard-adapter', () => ({
scheduleClipboardWrite: async () => {},
}));
-mock.module('@/lib/share/run-share-action', () => ({
+vi.doMock('@/lib/share/run-share-action', () => ({
buildFolderShareInput: (folderRelativePath: string) => ({ kind: 'folder', folderRelativePath }),
runShareAction: runShareActionMock,
}));
-mock.module('@/components/ui/button', () => ({ Button }));
+vi.doMock('@/components/ui/button', () => ({ Button }));
-mock.module('@/components/ui/collapsible', () => ({
+vi.doMock('@/components/ui/collapsible', () => ({
Collapsible: ({ children, defaultOpen: _defaultOpen, ...props }: Record<string, unknown>) => (
<div {...props}>{children as ReactNode}</div>
),
@@ -97,7 +97,7 @@ mock.module('@/components/ui/collapsible', () => ({
CollapsibleTrigger: Button,
}));
-mock.module('@/components/ui/sidebar', () => ({
+vi.doMock('@/components/ui/sidebar', () => ({
Sidebar: ElementPassThrough,
SidebarContent: ElementPassThrough,
SidebarFooter: ElementPassThrough,
@@ -111,11 +111,11 @@ mock.module('@/components/ui/sidebar', () => ({
useSidebar: () => ({ state: 'expanded', toggleSidebar: () => {} }),
}));
-mock.module('@/components/SkillsSidebarSection', () => ({
+vi.doMock('@/components/SkillsSidebarSection', () => ({
SkillsSidebarSection: () => null,
}));
-mock.module('@/components/ui/context-menu', () => ({
+vi.doMock('@/components/ui/context-menu', () => ({
ContextMenu: PassThrough,
ContextMenuCheckboxItem: Button,
ContextMenuContent: ElementPassThrough,
@@ -127,7 +127,7 @@ mock.module('@/components/ui/context-menu', () => ({
ContextMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: ({
checked,
@@ -157,62 +157,62 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/tooltip', () => ({
+vi.doMock('@/components/ui/tooltip', () => ({
Tooltip: PassThrough,
TooltipContent: ElementPassThrough,
TooltipTrigger: PassThrough,
}));
-mock.module('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
+vi.doMock('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
OpenInAgentEmptySpaceSubmenu: () => null,
}));
-mock.module('@/components/handoff/useHandoffDispatch', () => ({
+vi.doMock('@/components/handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
buildProjectScopedHandoffInput: () => ({ docContext: null, docPath: '', projectDir: '/tmp/ok' }),
useHandoffDispatch: () => ({ dispatch: async () => ({ ok: true as const }) }),
}));
-mock.module('@/components/handoff/useInstalledAgents', () => ({
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-mock.module('@/components/ProjectSwitcher', () => ({ ProjectSwitcher: () => null }));
+vi.doMock('@/components/ProjectSwitcher', () => ({ ProjectSwitcher: () => null }));
-mock.module('@/components/SidebarSearchBar', () => ({
+vi.doMock('@/components/SidebarSearchBar', () => ({
SidebarSearchBar: () => <button type="button">Search</button>,
onPillRenderError: () => {},
}));
-mock.module('@/components/UpdateNotices', () => ({ UpdateNotices: () => null }));
+vi.doMock('@/components/UpdateNotices', () => ({ UpdateNotices: () => null }));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
}),
}));
-mock.module('@/hooks/use-folder-config', () => ({
+vi.doMock('@/hooks/use-folder-config', () => ({
useFolderConfig: () => ({
state: { status: 'ready', data: { folder: { templates_available: [] } } },
}),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalBinding: { patch: () => ({ ok: true as const }) },
merged: { appearance: { sidebar: { showHiddenFiles: false } } },
}),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => ({ contentDir: '/tmp/open-knowledge', pathSeparator: '/' }),
}));
-mock.module('sonner', () => ({
- toast: { error: mock(() => {}), success: mock(() => {}) },
+vi.doMock('sonner', () => ({
+ toast: { error: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
const { FileSidebar } = await import('./FileSidebar');
diff --git a/packages/app/src/components/FileSidebar.test.ts b/packages/app/src/components/FileSidebar.test.ts
index 7131858d9..42531f809 100644
--- a/packages/app/src/components/FileSidebar.test.ts
+++ b/packages/app/src/components/FileSidebar.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isInteractiveSidebarControl } from './FileSidebar';
describe('FileSidebar module', () => {
diff --git a/packages/app/src/components/FileTree.create.dom.test.tsx b/packages/app/src/components/FileTree.create.dom.test.tsx
index cbf6cd43a..155fc57d9 100644
--- a/packages/app/src/components/FileTree.create.dom.test.tsx
+++ b/packages/app/src/components/FileTree.create.dom.test.tsx
@@ -8,10 +8,11 @@
*
* Mocks `PageListContext.usePageList` to intercept `addPage`.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { FileEntry } from './file-tree-utils';
type MenuItemProps = {
@@ -47,16 +48,16 @@ function MenuSeparator() {
return <hr />;
}
-const toastSuccessMock = mock(() => {});
-const toastErrorMock = mock(() => {});
-const addPageMock = mock(() => {});
-const openTargetMock = mock(() => {});
-const notifySidebarFileSelectedMock = mock(() => {});
-const closeTabsMock = mock(() => {});
-const closeDocumentMock = mock(() => {});
-const closeAndClearForRenameMock = mock(async () => {});
-const remapTabsForRenameMock = mock(() => {});
-const dispatchHandoffMock = mock(async () => ({ ok: true as const }));
+const toastSuccessMock = vi.fn(() => {});
+const toastErrorMock = vi.fn(() => {});
+const addPageMock = vi.fn(() => {});
+const openTargetMock = vi.fn(() => {});
+const notifySidebarFileSelectedMock = vi.fn(() => {});
+const closeTabsMock = vi.fn(() => {});
+const closeDocumentMock = vi.fn(() => {});
+const closeAndClearForRenameMock = vi.fn(async () => {});
+const remapTabsForRenameMock = vi.fn(() => {});
+const dispatchHandoffMock = vi.fn(async () => ({ ok: true as const }));
const DOCUMENTS: FileEntry[] = [
{
@@ -127,7 +128,7 @@ class StubModel {
focusedPath: string | null = null;
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
getFocusedPath() {
return this.focusedPath;
@@ -178,7 +179,7 @@ class StubModel {
let model = new StubModel();
let menuItem: { kind: 'file' | 'directory'; path: string };
-let closeMenuMock = mock(() => {});
+let closeMenuMock = vi.fn(() => {});
let createResponse: unknown;
let createStatus = 200;
let createGate: Promise<void> | null = null;
@@ -214,7 +215,7 @@ function createPageCalls() {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchCalls.push({ url, init });
if (url.startsWith('/api/documents')) return jsonResponse({ documents: DOCUMENTS });
@@ -243,18 +244,18 @@ function makeFetchMock() {
});
}
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
success: toastSuccessMock,
error: toastErrorMock,
},
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
@@ -272,15 +273,15 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ addPage: addPageMock }),
}));
-mock.module('./ui/sidebar', () => ({
+vi.doMock('./ui/sidebar', () => ({
useSidebar: () => ({ notifySidebarFileSelected: notifySidebarFileSelectedMock }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
@@ -288,7 +289,7 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('@/hooks/use-folder-config', () => ({
+vi.doMock('@/hooks/use-folder-config', () => ({
useFolderConfig: (folderPath: string | null) => {
lastFolderConfigPath = folderPath;
if (folderConfigStatus === 'loading') {
@@ -304,26 +305,26 @@ mock.module('@/hooks/use-folder-config', () => ({
},
}));
-mock.module('./handoff/useInstalledAgents', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
useHandoffDispatch: () => ({ dispatch: dispatchHandoffMock }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -331,11 +332,11 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/dialog', () => ({
+vi.doMock('@/components/ui/dialog', () => ({
Dialog: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: MenuItem,
DropdownMenuContent: MenuContent,
@@ -347,34 +348,34 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({
NewItemDialog: () => null,
}));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({
renderContextMenu,
@@ -412,12 +413,12 @@ function renderFileTree() {
}
describe('FileTree startCreating addPage symmetry', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
model = new StubModel();
menuItem = { kind: 'directory', path: 'notes/' };
- closeMenuMock = mock(() => {});
+ closeMenuMock = vi.fn(() => {});
createResponse = {
docName: 'notes/Untitled',
path: 'notes/Untitled.md',
@@ -435,7 +436,7 @@ describe('FileTree startCreating addPage symmetry', () => {
addPageMock.mockClear();
openTargetMock.mockClear();
notifySidebarFileSelectedMock.mockClear();
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTree.duplicate.dom.test.tsx b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
index 442c92e0b..9765d3696 100644
--- a/packages/app/src/components/FileTree.duplicate.dom.test.tsx
+++ b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { FileEntry } from './file-tree-utils';
import type { ResolvedNavigationTarget } from './navigation-targets';
@@ -60,16 +60,16 @@ function MenuSeparator() {
return <hr />;
}
-const toastSuccessMock = mock(() => {});
-const toastErrorMock = mock(() => {});
-const addPageMock = mock(() => {});
-const openTargetMock = mock(() => {});
-const notifySidebarFileSelectedMock = mock(() => {});
-const closeTabsMock = mock(() => {});
-const closeDocumentMock = mock(() => {});
-const closeAndClearForRenameMock = mock(async () => {});
-const remapTabsForRenameMock = mock(() => {});
-const dispatchHandoffMock = mock(async () => ({ ok: true as const }));
+const toastSuccessMock = vi.fn(() => {});
+const toastErrorMock = vi.fn(() => {});
+const addPageMock = vi.fn(() => {});
+const openTargetMock = vi.fn(() => {});
+const notifySidebarFileSelectedMock = vi.fn(() => {});
+const closeTabsMock = vi.fn(() => {});
+const closeDocumentMock = vi.fn(() => {});
+const closeAndClearForRenameMock = vi.fn(async () => {});
+const remapTabsForRenameMock = vi.fn(() => {});
+const dispatchHandoffMock = vi.fn(async () => ({ ok: true as const }));
const DOCUMENTS: FileEntry[] = [
{
@@ -149,7 +149,7 @@ class StubModel {
focusedPath: string | null = null;
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
getFocusedPath() {
return this.focusedPath;
@@ -201,7 +201,7 @@ class StubModel {
let model = new StubModel();
let menuItem: { kind: 'file' | 'directory'; path: string };
-let closeMenuMock = mock(() => {});
+let closeMenuMock = vi.fn(() => {});
let duplicateResponse: unknown;
let duplicateStatus = 200;
let duplicateGate: Promise<void> | null = null;
@@ -215,9 +215,9 @@ let fetchCalls: FetchCall[] = [];
let extraDocuments: FileEntry[] = [];
let okignoreBindingMock: {
current: () => string;
- patch: ReturnType<typeof mock>;
+ patch: ReturnType<typeof vi.fn>;
} | null = null;
-let projectLocalBindingMock: { patch: ReturnType<typeof mock> } | null = null;
+let projectLocalBindingMock: { patch: ReturnType<typeof vi.fn> } | null = null;
let mergedConfigMock: {
appearance?: { sidebar?: { showHiddenFiles?: boolean } };
} | null = null;
@@ -258,7 +258,7 @@ function expectMenuOrder(labels: readonly RegExp[]) {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchCalls.push({ url, init });
if (url.startsWith('/api/documents'))
@@ -290,18 +290,18 @@ function makeFetchMock() {
});
}
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
success: toastSuccessMock,
error: toastErrorMock,
},
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
@@ -319,15 +319,15 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ addPage: addPageMock, pageMeta: new Map() }),
}));
-mock.module('./ui/sidebar', () => ({
+vi.doMock('./ui/sidebar', () => ({
useSidebar: () => ({ notifySidebarFileSelected: notifySidebarFileSelectedMock }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: okignoreBindingMock,
projectLocalBinding: projectLocalBindingMock,
@@ -335,17 +335,17 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('./handoff/useInstalledAgents', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
useHandoffDispatch: () => ({ dispatch: dispatchHandoffMock }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => (
<button type="button" role="menuitem" data-testid="file-tree-menu-open-in-agent">
Open with AI
@@ -353,12 +353,12 @@ mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
),
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -366,11 +366,11 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/dialog', () => ({
+vi.doMock('@/components/ui/dialog', () => ({
Dialog: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: MenuItem,
DropdownMenuContent: MenuContent,
@@ -382,11 +382,11 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: (props: {
itemName?: string;
customTitle?: string;
@@ -398,26 +398,26 @@ mock.module('@/components/DeleteConfirmationDialog', () => ({
},
}));
-mock.module('@/components/NewItemDialog', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({
NewItemDialog: () => null,
}));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({
renderContextMenu,
@@ -458,12 +458,12 @@ function renderFileTree() {
}
describe('FileTree duplicate action runtime behavior', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
model = new StubModel();
menuItem = { kind: 'file', path: 'notes/source.mdx' };
- closeMenuMock = mock(() => {});
+ closeMenuMock = vi.fn(() => {});
duplicateResponse = {
kind: 'file',
path: 'notes/source copy',
@@ -486,7 +486,7 @@ describe('FileTree duplicate action runtime behavior', () => {
addPageMock.mockClear();
openTargetMock.mockClear();
notifySidebarFileSelectedMock.mockClear();
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -528,7 +528,7 @@ describe('FileTree duplicate action runtime behavior', () => {
test('file context-menu Hide appends an anchored okignore pattern and shows reversible copy', async () => {
okignoreBindingMock = {
current: () => '',
- patch: mock(() => ({ ok: true })),
+ patch: vi.fn(() => ({ ok: true })),
};
const user = userEvent.setup();
renderFileTree();
@@ -556,7 +556,7 @@ describe('FileTree duplicate action runtime behavior', () => {
okignoreBindingMock = {
current: () => '/notes/source.mdx\n',
- patch: mock(() => ({ ok: true })),
+ patch: vi.fn(() => ({ ok: true })),
};
const user = userEvent.setup();
renderFileTree();
@@ -606,7 +606,7 @@ describe('FileTree duplicate action runtime behavior', () => {
menuItem = { kind: 'directory', path: 'notes/' };
okignoreBindingMock = {
current: () => '',
- patch: mock(() => ({ ok: true })),
+ patch: vi.fn(() => ({ ok: true })),
};
const user = userEvent.setup();
renderFileTree();
@@ -660,7 +660,7 @@ describe('FileTree duplicate action runtime behavior', () => {
menuItem = { kind: 'file', path: '.ok/templates/greeting.md' };
okignoreBindingMock = {
current: () => '',
- patch: mock(() => ({ ok: true })),
+ patch: vi.fn(() => ({ ok: true })),
};
renderFileTree();
@@ -680,7 +680,7 @@ describe('FileTree duplicate action runtime behavior', () => {
menuItem = { kind: 'directory', path: '.ok/' };
okignoreBindingMock = {
current: () => '',
- patch: mock(() => ({ ok: true })),
+ patch: vi.fn(() => ({ ok: true })),
};
renderFileTree();
diff --git a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
index f5bd0b2be..e1aa94dc5 100644
--- a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
+++ b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
@@ -15,10 +15,11 @@
* Exercises `render` + `userEvent` under the jsdom substrate (precedent #43);
* invocation via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useRef, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { useSelectionMirror } from './use-selection-mirror';
interface StubItem {
@@ -106,10 +107,10 @@ function Harness({ initialPath, model }: { initialPath: string | null; model: St
}
describe('FileTree selection-mirror (Tier-3 mount)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTree.share.dom.test.tsx b/packages/app/src/components/FileTree.share.dom.test.tsx
index a4d129f55..b8fef3ff4 100644
--- a/packages/app/src/components/FileTree.share.dom.test.tsx
+++ b/packages/app/src/components/FileTree.share.dom.test.tsx
@@ -1,14 +1,14 @@
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { FileEntry } from './file-tree-utils';
// Controls the mocked git-sync hook's hasRemote signal per test.
let hasRemote = true;
// Captures the input runShareAction receives.
let lastShareInput: unknown;
-const runShareActionMock = mock(async (input: unknown) => {
+const runShareActionMock = vi.fn(async (input: unknown) => {
lastShareInput = input;
return { kind: 'copied' as const, shareUrl: 'https://example.test/x', branch: 'main' };
});
@@ -68,8 +68,8 @@ function MenuSeparator() {
return <hr />;
}
-const toastSuccessMock = mock(() => {});
-const toastErrorMock = mock(() => {});
+const toastSuccessMock = vi.fn(() => {});
+const toastErrorMock = vi.fn(() => {});
const DOCUMENTS: FileEntry[] = [
{ kind: 'folder', path: 'notes', size: 0, modified: '2026-05-18T00:00:00.000Z' },
@@ -129,7 +129,7 @@ class StubModel {
focusedPath: string | null = null;
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
getFocusedPath() {
return this.focusedPath;
}
@@ -169,7 +169,7 @@ class StubModel {
let model = new StubModel();
let menuItem: { kind: 'file' | 'directory'; path: string };
-let closeMenuMock = mock(() => {});
+let closeMenuMock = vi.fn(() => {});
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
@@ -179,7 +179,7 @@ function jsonResponse(body: unknown, status = 200): Response {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL) => {
+ return vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (url.startsWith('/api/documents')) return jsonResponse({ documents: DOCUMENTS });
if (url === '/api/workspace') {
@@ -194,15 +194,15 @@ function makeFetchMock() {
});
}
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: { success: toastSuccessMock, error: toastErrorMock },
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatusDetailed: () => ({
status: { hasRemote, syncEnabled: hasRemote, behind: 0, ahead: 0 },
fetchError: null,
@@ -210,17 +210,17 @@ mock.module('@/hooks/use-git-sync-status', () => ({
useGitSyncStatus: () => ({ hasRemote, syncEnabled: hasRemote, behind: 0, ahead: 0 }),
}));
-mock.module('@/lib/share/clipboard-adapter', () => ({
+vi.doMock('@/lib/share/clipboard-adapter', () => ({
scheduleClipboardWrite: async () => {},
}));
-mock.module('@/lib/share/run-share-action', () => ({
+vi.doMock('@/lib/share/run-share-action', () => ({
buildDocShareInput: (docName: string) => ({ kind: 'doc', docName }),
buildFolderShareInput: (folderRelativePath: string) => ({ kind: 'folder', folderRelativePath }),
runShareAction: runShareActionMock,
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
@@ -238,29 +238,29 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ addPage: () => {}, pageMeta: new Map() }),
}));
-mock.module('./ui/sidebar', () => ({
+vi.doMock('./ui/sidebar', () => ({
useSidebar: () => ({ notifySidebarFileSelected: () => {} }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({ okignoreBinding: null, projectLocalBinding: null, merged: null }),
}));
-mock.module('./handoff/useInstalledAgents', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
useHandoffDispatch: () => ({ dispatch: async () => ({ ok: true as const }) }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => (
<button type="button" role="menuitem" data-testid="file-tree-menu-open-in-agent">
Open with AI
@@ -268,12 +268,12 @@ mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
),
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -281,9 +281,9 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: MenuItem,
DropdownMenuContent: MenuContent,
@@ -295,32 +295,32 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({
renderContextMenu,
@@ -355,19 +355,19 @@ function renderFileTree() {
}
describe('FileTree context-menu Share action', () => {
- let consoleLogSpy: ReturnType<typeof spyOn>;
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
model = new StubModel();
menuItem = { kind: 'file', path: 'notes/source.mdx' };
- closeMenuMock = mock(() => {});
+ closeMenuMock = vi.fn(() => {});
hasRemote = true;
lastShareInput = undefined;
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
runShareActionMock.mockClear();
toastSuccessMock.mockClear();
toastErrorMock.mockClear();
- consoleLogSpy = spyOn(console, 'log').mockImplementation(() => {});
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
index 467f9f33b..72e155c66 100644
--- a/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
+++ b/packages/app/src/components/FileTree.showall-lazy.dom.test.tsx
@@ -18,10 +18,11 @@
* `subscribe` fires on every state change (expand/collapse included), and
* `resetPaths` re-applies `initialExpandedPaths`.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { i18n } from '@lingui/core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { emitDocumentsChanged } from '@/lib/documents-events';
// Deterministic `Intl.NumberFormat` output for the truncation-notice smoke
@@ -97,7 +98,7 @@ function folderEntry(path: string, hasChildren: boolean) {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchUrls.push(url);
const override = responseByUrl.get(url);
@@ -157,7 +158,7 @@ class StubModel {
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
listeners = new Set<() => void>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
notify() {
for (const listener of this.listeners) listener();
}
@@ -209,62 +210,62 @@ class StubModel {
}
const model = new StubModel();
-const openTargetMock = mock(() => {});
+const openTargetMock = vi.fn(() => {});
-mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));
-mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('sonner', () => ({ toast: { success: vi.fn(() => {}), error: vi.fn(() => {}) } }));
+vi.doMock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: null,
activeTarget: null,
- closeTabs: mock(() => {}),
- closeDocument: mock(() => {}),
- closeAndClearDocument: mock(async () => {}),
- closeAndClearForDelete: mock(async () => {}),
- closeAndClearForRename: mock(async () => {}),
+ closeTabs: vi.fn(() => {}),
+ closeDocument: vi.fn(() => {}),
+ closeAndClearDocument: vi.fn(async () => {}),
+ closeAndClearForDelete: vi.fn(async () => {}),
+ closeAndClearForRename: vi.fn(async () => {}),
getPoolActiveDocName: () => null,
poolHas: () => false,
isNewTabActive: false,
openTarget: openTargetMock,
prewarm: () => {},
- remapTabsForRename: mock(() => {}),
+ remapTabsForRename: vi.fn(() => {}),
}),
}));
-mock.module('@/components/PageListContext', () => ({
- usePageList: () => ({ addPage: mock(() => {}), pages: new Set<string>() }),
+vi.doMock('@/components/PageListContext', () => ({
+ usePageList: () => ({ addPage: vi.fn(() => {}), pages: new Set<string>() }),
}));
-mock.module('./ui/sidebar', () => ({
- useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),
+vi.doMock('./ui/sidebar', () => ({
+ useSidebar: () => ({ notifySidebarFileSelected: vi.fn(() => {}) }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
merged: mergedConfig,
}),
}));
-mock.module('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
- useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),
+ useHandoffDispatch: () => ({ dispatch: vi.fn(async () => ({ ok: true as const })) }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (
<button type="button" {...props}>
{children}
</button>
),
}));
-mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: PassThrough,
DropdownMenuContent: PassThrough,
@@ -275,26 +276,26 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuSubTrigger: PassThrough,
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({
header,
@@ -332,7 +333,7 @@ const { attachRelaunchStateSubscribers, resetRelaunchStoreForTest } = await impo
);
describe('FileTree showAll lazy root seed', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -346,7 +347,7 @@ describe('FileTree showAll lazy root seed', () => {
openTargetMock.mockClear();
window.location.hash = '';
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -683,7 +684,7 @@ describe('FileTree showAll lazy root seed', () => {
});
describe('FileTree showAll lazy folder expansion', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -699,7 +700,7 @@ describe('FileTree showAll lazy folder expansion', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -912,7 +913,7 @@ describe('FileTree showAll lazy folder expansion', () => {
});
describe('FileTree showAll scoped refresh', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -928,7 +929,7 @@ describe('FileTree showAll scoped refresh', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -1116,7 +1117,7 @@ describe('FileTree showAll scoped refresh', () => {
});
describe('FileTree relaunch-aware reconnect (desktop auto-update)', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
let fireRelaunching: () => void;
let fireRelaunchFailed: () => void;
let detachRelaunch: () => void;
@@ -1132,7 +1133,7 @@ describe('FileTree relaunch-aware reconnect (desktop auto-update)', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
fireRelaunching = () => {};
fireRelaunchFailed = () => {};
// Drive the real relaunch-store through captured bridge callbacks —
@@ -1251,7 +1252,7 @@ describe('FileTree relaunch-aware reconnect (desktop auto-update)', () => {
});
describe('FileTree only-markdown visibility', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -1263,7 +1264,7 @@ describe('FileTree only-markdown visibility', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -1429,7 +1430,7 @@ describe('FileTree only-markdown visibility', () => {
});
describe('FileTree filtered-to-zero empty state', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -1441,7 +1442,7 @@ describe('FileTree filtered-to-zero empty state', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -1504,7 +1505,7 @@ describe('FileTree filtered-to-zero empty state', () => {
});
describe('FileTree show-ok-folders visibility', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
const SHOW_OK_DEPTH1_URL = '/api/documents?showAll=true&showOk=true&dir=&depth=1';
const lazyOkDirUrl = (dir: string) =>
@@ -1520,7 +1521,7 @@ describe('FileTree show-ok-folders visibility', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsx b/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsx
index 6f27c2098..a7b9c3ad0 100644
--- a/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsx
+++ b/packages/app/src/components/FileTree.showall-lifecycle.dom.test.tsx
@@ -19,14 +19,15 @@
* (the banner shows only the title).
*
* Same harness as FileTree.showall-lazy.dom.test.tsx (recording Pierre stub;
- * `mock.module` is safe per-file under the runner's `--isolate`), plus a
+ * `vi.doMock` is safe per-file under the runner's `--isolate`), plus a
* mutable `activeDocName` so the drill-down test can mount with a deep link
* active.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { i18n } from '@lingui/core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { emitDocumentsChanged } from '@/lib/documents-events';
i18n.load('en', {});
@@ -78,7 +79,7 @@ function folderEntry(path: string, hasChildren: boolean) {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchUrls.push(url);
const override = responseByUrl.get(url);
@@ -134,7 +135,7 @@ class StubModel {
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
listeners = new Set<() => void>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
notify() {
for (const listener of this.listeners) listener();
}
@@ -185,60 +186,60 @@ class StubModel {
const model = new StubModel();
-mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));
-mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('sonner', () => ({ toast: { success: vi.fn(() => {}), error: vi.fn(() => {}) } }));
+vi.doMock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: activeDocNameForTest,
activeTarget: null,
- closeTabs: mock(() => {}),
- closeDocument: mock(() => {}),
- closeAndClearDocument: mock(async () => {}),
- closeAndClearForDelete: mock(async () => {}),
- closeAndClearForRename: mock(async () => {}),
+ closeTabs: vi.fn(() => {}),
+ closeDocument: vi.fn(() => {}),
+ closeAndClearDocument: vi.fn(async () => {}),
+ closeAndClearForDelete: vi.fn(async () => {}),
+ closeAndClearForRename: vi.fn(async () => {}),
getPoolActiveDocName: () => null,
poolHas: () => false,
isNewTabActive: false,
- openTarget: mock(() => {}),
+ openTarget: vi.fn(() => {}),
prewarm: () => {},
- remapTabsForRename: mock(() => {}),
+ remapTabsForRename: vi.fn(() => {}),
}),
}));
-mock.module('@/components/PageListContext', () => ({
- usePageList: () => ({ addPage: mock(() => {}) }),
+vi.doMock('@/components/PageListContext', () => ({
+ usePageList: () => ({ addPage: vi.fn(() => {}) }),
}));
-mock.module('./ui/sidebar', () => ({
- useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),
+vi.doMock('./ui/sidebar', () => ({
+ useSidebar: () => ({ notifySidebarFileSelected: vi.fn(() => {}) }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
merged: mergedConfig,
}),
}));
-mock.module('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
- useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),
+ useHandoffDispatch: () => ({ dispatch: vi.fn(async () => ({ ok: true as const })) }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (
<button type="button" {...props}>
{children}
</button>
),
}));
-mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: PassThrough,
DropdownMenuContent: PassThrough,
@@ -249,26 +250,26 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuSubTrigger: PassThrough,
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({ header }: { header?: ReactNode }) => (
<div data-testid="fake-pierre-tree" role="tree">
@@ -280,7 +281,7 @@ mock.module('@pierre/trees/react', () => ({
const { FileTree } = await import('./FileTree');
describe('FileTree showAll notice lifecycle', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -297,7 +298,7 @@ describe('FileTree showAll notice lifecycle', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -409,7 +410,7 @@ describe('FileTree showAll notice lifecycle', () => {
});
describe('FileTree showAll interrupted NDJSON seed', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -422,7 +423,7 @@ describe('FileTree showAll interrupted NDJSON seed', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -508,7 +509,7 @@ describe('FileTree showAll interrupted NDJSON seed', () => {
});
describe('FileTree showAll deep-link progressive drill-down', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -522,7 +523,7 @@ describe('FileTree showAll deep-link progressive drill-down', () => {
model.focusedPath = null;
model.selectedPaths = [];
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx b/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx
index a505d6ece..958082ded 100644
--- a/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx
+++ b/packages/app/src/components/FileTree.showall-truncation.dom.test.tsx
@@ -20,10 +20,11 @@
* the notice lives); the create/duplicate `.dom.test` precedents mock it to
* render only `renderContextMenu`, which would hide the surface under test.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { i18n } from '@lingui/core';
import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// The component formats the truncation count with `Intl.NumberFormat` keyed
// off `useLingui().i18n.locale`; the macro test shim hands back this real
@@ -69,7 +70,7 @@ function docEntry(docName: string) {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL) => {
+ return vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchUrls.push(url);
if (url === SHOW_ALL_DEPTH1_URL) return jsonResponse(showAllBody, showAllStatus);
@@ -123,7 +124,7 @@ class StubModel {
focusedPath: string | null = null;
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
getFocusedPath() {
return this.focusedPath;
}
@@ -161,60 +162,60 @@ class StubModel {
const model = new StubModel();
-mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));
-mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('sonner', () => ({ toast: { success: vi.fn(() => {}), error: vi.fn(() => {}) } }));
+vi.doMock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: null,
activeTarget: null,
- closeTabs: mock(() => {}),
- closeDocument: mock(() => {}),
- closeAndClearDocument: mock(async () => {}),
- closeAndClearForDelete: mock(async () => {}),
- closeAndClearForRename: mock(async () => {}),
+ closeTabs: vi.fn(() => {}),
+ closeDocument: vi.fn(() => {}),
+ closeAndClearDocument: vi.fn(async () => {}),
+ closeAndClearForDelete: vi.fn(async () => {}),
+ closeAndClearForRename: vi.fn(async () => {}),
getPoolActiveDocName: () => null,
poolHas: () => false,
isNewTabActive: false,
- openTarget: mock(() => {}),
+ openTarget: vi.fn(() => {}),
prewarm: () => {},
- remapTabsForRename: mock(() => {}),
+ remapTabsForRename: vi.fn(() => {}),
}),
}));
-mock.module('@/components/PageListContext', () => ({
- usePageList: () => ({ addPage: mock(() => {}) }),
+vi.doMock('@/components/PageListContext', () => ({
+ usePageList: () => ({ addPage: vi.fn(() => {}) }),
}));
-mock.module('./ui/sidebar', () => ({
- useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),
+vi.doMock('./ui/sidebar', () => ({
+ useSidebar: () => ({ notifySidebarFileSelected: vi.fn(() => {}) }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
merged: mergedConfig,
}),
}));
-mock.module('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
- useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),
+ useHandoffDispatch: () => ({ dispatch: vi.fn(async () => ({ ok: true as const })) }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (
<button type="button" {...props}>
{children}
</button>
),
}));
-mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: PassThrough,
DropdownMenuContent: PassThrough,
@@ -225,26 +226,26 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuSubTrigger: PassThrough,
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
// RENDER the header — that is the surface under test.
FileTree: ({ header }: { header?: ReactNode }) => (
@@ -257,7 +258,7 @@ mock.module('@pierre/trees/react', () => ({
const { FileTree } = await import('./FileTree');
describe('FileTree showAll truncation notice', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
mergedConfig = { appearance: { sidebar: {} } };
@@ -265,7 +266,7 @@ describe('FileTree showAll truncation notice', () => {
showAllStatus = 200;
fetchUrls.length = 0;
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTree.superseded-refresh.dom.test.tsx b/packages/app/src/components/FileTree.superseded-refresh.dom.test.tsx
index 4a2b17517..7b8023eca 100644
--- a/packages/app/src/components/FileTree.superseded-refresh.dom.test.tsx
+++ b/packages/app/src/components/FileTree.superseded-refresh.dom.test.tsx
@@ -21,9 +21,10 @@
* FileTree; mock `@pierre/trees/react` to render the `header` prop so the
* `role="alert"` banner surface is observable).
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
function PassThrough({ children }: { children?: ReactNode }) {
return <>{children}</>;
@@ -127,7 +128,7 @@ function docEntry(docName: string) {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (url.startsWith('/api/documents')) {
documentsCallCount += 1;
@@ -184,7 +185,7 @@ class StubModel {
focusedPath: string | null = null;
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
getFocusedPath() {
return this.focusedPath;
}
@@ -222,60 +223,60 @@ class StubModel {
let model = new StubModel();
-mock.module('sonner', () => ({ toast: { success: mock(() => {}), error: mock(() => {}) } }));
-mock.module('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('sonner', () => ({ toast: { success: vi.fn(() => {}), error: vi.fn(() => {}) } }));
+vi.doMock('next-themes', () => ({ useTheme: () => ({ resolvedTheme: 'light' }) }));
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: null,
activeTarget: null,
- closeTabs: mock(() => {}),
- closeDocument: mock(() => {}),
- closeAndClearDocument: mock(async () => {}),
- closeAndClearForDelete: mock(async () => {}),
- closeAndClearForRename: mock(async () => {}),
+ closeTabs: vi.fn(() => {}),
+ closeDocument: vi.fn(() => {}),
+ closeAndClearDocument: vi.fn(async () => {}),
+ closeAndClearForDelete: vi.fn(async () => {}),
+ closeAndClearForRename: vi.fn(async () => {}),
getPoolActiveDocName: () => null,
poolHas: () => false,
isNewTabActive: false,
- openTarget: mock(() => {}),
+ openTarget: vi.fn(() => {}),
prewarm: () => {},
- remapTabsForRename: mock(() => {}),
+ remapTabsForRename: vi.fn(() => {}),
}),
}));
-mock.module('@/components/PageListContext', () => ({
- usePageList: () => ({ addPage: mock(() => {}) }),
+vi.doMock('@/components/PageListContext', () => ({
+ usePageList: () => ({ addPage: vi.fn(() => {}) }),
}));
-mock.module('./ui/sidebar', () => ({
- useSidebar: () => ({ notifySidebarFileSelected: mock(() => {}) }),
+vi.doMock('./ui/sidebar', () => ({
+ useSidebar: () => ({ notifySidebarFileSelected: vi.fn(() => {}) }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
merged: mergedConfig,
}),
}));
-mock.module('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({ useInstalledAgents: () => ({ states: {} }) }));
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
- useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),
+ useHandoffDispatch: () => ({ dispatch: vi.fn(async () => ({ ok: true as const })) }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [k: string]: unknown }) => (
<button type="button" {...props}>
{children}
</button>
),
}));
-mock.module('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dialog', () => ({ Dialog: PassThrough }));
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: PassThrough,
DropdownMenuContent: PassThrough,
@@ -286,26 +287,26 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuSubTrigger: PassThrough,
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({ NewItemDialog: () => null }));
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
// RENDER the header — the role=alert error banner lives there.
FileTree: ({ header }: { header?: ReactNode }) => (
@@ -318,7 +319,7 @@ mock.module('@pierre/trees/react', () => ({
const { FileTree } = await import('./FileTree');
describe('FileTree superseded documents refresh', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
model = new StubModel();
@@ -327,7 +328,7 @@ describe('FileTree superseded documents refresh', () => {
documentsCallCount = 0;
resolveTrailingDocuments = null;
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx b/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
index 69411be9c..213a89c87 100644
--- a/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
+++ b/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
@@ -7,12 +7,13 @@
*
* Runs under `bun run test:dom` (jsdom substrate per precedent #43).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
@@ -22,7 +23,7 @@ let patchResultOk = true;
const patchCalls: unknown[] = [];
const toastErrors: unknown[][] = [];
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: null,
projectLocalBinding: projectLocalBindingNull
@@ -38,7 +39,7 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (...args: unknown[]) => toastErrors.push(args),
success: () => {},
diff --git a/packages/app/src/components/GraphLegend.test.tsx b/packages/app/src/components/GraphLegend.test.tsx
index 132c0958d..d1970c86b 100644
--- a/packages/app/src/components/GraphLegend.test.tsx
+++ b/packages/app/src/components/GraphLegend.test.tsx
@@ -1,10 +1,10 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import * as actualNextThemes from 'next-themes';
import type { ReactElement, ReactNode } from 'react';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
-const useThemeMock = mock(() => ({ resolvedTheme: 'light' as const }));
+const useThemeMock = vi.fn(() => ({ resolvedTheme: 'light' as const }));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
...actualNextThemes,
useTheme: useThemeMock,
}));
diff --git a/packages/app/src/components/InstanceBadge.dom.test.tsx b/packages/app/src/components/InstanceBadge.dom.test.tsx
index 55339a25d..e7db404a1 100644
--- a/packages/app/src/components/InstanceBadge.dom.test.tsx
+++ b/packages/app/src/components/InstanceBadge.dom.test.tsx
@@ -1,15 +1,15 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
useLingui: () => ({ t: renderLinguiTemplate }),
}));
// Tooltip is decorative chrome; pass its parts through so the badge renders
// without a TooltipProvider ancestor.
-mock.module('@/components/ui/tooltip', () => ({
+vi.doMock('@/components/ui/tooltip', () => ({
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
TooltipContent: ({ children }: { children: ReactNode }) => <>{children}</>,
diff --git a/packages/app/src/components/LargeFileEditorState.dom.test.tsx b/packages/app/src/components/LargeFileEditorState.dom.test.tsx
index 017f3f7f3..c1df429ae 100644
--- a/packages/app/src/components/LargeFileEditorState.dom.test.tsx
+++ b/packages/app/src/components/LargeFileEditorState.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { LargeFileEditorState } from './LargeFileEditorState';
describe('LargeFileEditorState', () => {
@@ -26,7 +26,7 @@ describe('LargeFileEditorState', () => {
});
test('go back action routes to the previous document', async () => {
- const onNavigateBack = mock(() => {});
+ const onNavigateBack = vi.fn(() => {});
render(
<LargeFileEditorState
docName="big-note"
diff --git a/packages/app/src/components/McpConsentDialog.dom.test.tsx b/packages/app/src/components/McpConsentDialog.dom.test.tsx
index 4d8050067..3dd9d923e 100644
--- a/packages/app/src/components/McpConsentDialog.dom.test.tsx
+++ b/packages/app/src/components/McpConsentDialog.dom.test.tsx
@@ -1,14 +1,14 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkMcpWiringResult, OkMcpWiringShowPayload } from '@/lib/desktop-bridge-types';
import type { McpConsentStore } from '@/lib/mcp-consent-store';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import type { ToastImpl } from './McpConsentDialogBody';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
diff --git a/packages/app/src/components/McpConsentDialog.test.ts b/packages/app/src/components/McpConsentDialog.test.ts
index f4e595daa..7fcd9b425 100644
--- a/packages/app/src/components/McpConsentDialog.test.ts
+++ b/packages/app/src/components/McpConsentDialog.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import type { OkMcpWiringEditorId, OkMcpWiringShowPayload } from '@/lib/desktop-bridge-types';
import { McpConsentDialog } from './McpConsentDialog';
import {
@@ -164,7 +164,7 @@ describe('McpConsentDialog module shape', () => {
test('mock module-level usage check: toast.error is invocable from a Set-like context', () => {
// Smoke that the ToastImpl shape composes through `mock()` for callers
// that want to inject a spy.
- const spy = mock((_msg: string) => {});
+ const spy = vi.fn((_msg: string) => {});
const toast: ToastImpl = { error: spy };
toast.error('hello');
expect(spy.mock.calls.length).toBe(1);
diff --git a/packages/app/src/components/MermaidDocEditor.test.ts b/packages/app/src/components/MermaidDocEditor.test.ts
index 356dddb98..ae1d3fa10 100644
--- a/packages/app/src/components/MermaidDocEditor.test.ts
+++ b/packages/app/src/components/MermaidDocEditor.test.ts
@@ -7,7 +7,7 @@
* manifesting as corrupted diagram labels after a click-edit.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { replaceYText } from './MermaidDocEditor.tsx';
diff --git a/packages/app/src/components/NavigatorApp.dom.test.tsx b/packages/app/src/components/NavigatorApp.dom.test.tsx
index 09835d512..053851bda 100644
--- a/packages/app/src/components/NavigatorApp.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
let themeBridgeCalls: Array<[unknown, string]> = [];
@@ -10,21 +10,21 @@ let cloneDialogProps: Array<{
onCloneComplete: (payload: { dir: string }) => void;
}> = [];
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ theme: undefined }),
}));
-mock.module('@/hooks/use-theme-bridge', () => ({
+vi.doMock('@/hooks/use-theme-bridge', () => ({
useThemeBridge: (bridge: unknown, theme: string) => {
themeBridgeCalls.push([bridge, theme]);
},
}));
-mock.module('./BetaBadge', () => ({
+vi.doMock('./BetaBadge', () => ({
BetaBadge: () => <span data-testid="beta-badge">Beta</span>,
}));
-mock.module('./ui/button', () => ({
+vi.doMock('./ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -32,63 +32,63 @@ mock.module('./ui/button', () => ({
),
}));
-mock.module('./ui/badge', () => ({
+vi.doMock('./ui/badge', () => ({
Badge: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<span {...props}>{children}</span>
),
}));
-mock.module('./CreateProjectDialog', () => ({
+vi.doMock('./CreateProjectDialog', () => ({
CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
createDialogProps.push(props);
return <div data-testid="create-project-dialog" data-open={String(props.open)} />;
},
}));
-mock.module('./CloneDialog', () => ({
+vi.doMock('./CloneDialog', () => ({
CloneDialog: (props: { open: boolean; onCloneComplete: (payload: { dir: string }) => void }) => {
cloneDialogProps.push(props);
return <div data-testid="clone-dialog" data-open={String(props.open)} />;
},
}));
-mock.module('./AuthModal', () => ({
+vi.doMock('./AuthModal', () => ({
AuthModal: () => null,
}));
-mock.module('./ConsentDialog', () => ({
+vi.doMock('./ConsentDialog', () => ({
ConsentDialog: () => null,
}));
-mock.module('./McpConsentDialog', () => ({
+vi.doMock('./McpConsentDialog', () => ({
McpConsentDialog: () => null,
}));
-mock.module('./ShareReceiveDialog', () => ({
+vi.doMock('./ShareReceiveDialog', () => ({
ShareReceiveDialog: () => null,
}));
-mock.module('@/lib/share/clone-controller', () => ({
+vi.doMock('@/lib/share/clone-controller', () => ({
createCloneController: () => ({}),
}));
-mock.module('@/lib/transports/auth-query-transport', () => ({
+vi.doMock('@/lib/transports/auth-query-transport', () => ({
ipcAuthQueryTransport: () => ({}),
}));
-mock.module('@/lib/transports/auth-transport', () => ({
+vi.doMock('@/lib/transports/auth-transport', () => ({
ipcAuthTransport: () => ({}),
}));
-mock.module('@/lib/transports/clone-transport', () => ({
+vi.doMock('@/lib/transports/clone-transport', () => ({
ipcCloneTransport: () => ({}),
}));
function createBridge() {
return {
appVersion: '0.4.0-beta.1',
- onMenuAction: mock(() => () => {}),
- onRecentRemovedMissing: mock(
+ onMenuAction: vi.fn(() => () => {}),
+ onRecentRemovedMissing: vi.fn(
(_cb: (info: { path: string; projectName: string }) => void) => () => {},
),
config: {
@@ -99,20 +99,20 @@ function createBridge() {
mode: 'navigator',
},
project: {
- listRecent: mock(() =>
+ listRecent: vi.fn(() =>
Promise.resolve([{ path: '/projects/recent', name: 'Recent Project' }]),
),
- removeRecent: mock(() => Promise.resolve()),
- getSessionState: mock(() => Promise.resolve({})),
- setSessionState: mock(() => Promise.resolve()),
- open: mock(() => Promise.resolve()),
- openFile: mock(() => Promise.resolve()),
- createNew: mock(() => Promise.resolve()),
- recordCreateNewBannerShown: mock(() => Promise.resolve()),
- close: mock(() => Promise.resolve()),
+ removeRecent: vi.fn(() => Promise.resolve()),
+ getSessionState: vi.fn(() => Promise.resolve({})),
+ setSessionState: vi.fn(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ openFile: vi.fn(() => Promise.resolve()),
+ createNew: vi.fn(() => Promise.resolve()),
+ recordCreateNewBannerShown: vi.fn(() => Promise.resolve()),
+ close: vi.fn(() => Promise.resolve()),
},
dialog: {
- openFolder: mock(() => Promise.resolve('/picked/folder')),
+ openFolder: vi.fn(() => Promise.resolve('/picked/folder')),
},
};
}
@@ -219,7 +219,7 @@ describe('NavigatorApp launcher runtime behavior', () => {
// production, where `project.open` stays pending through the whole
// main-side spawn + lock-poll (and the Stop-Server-Retry path).
let resolveOpen: (() => void) | undefined;
- bridge.project.open = mock(
+ bridge.project.open = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveOpen = resolve;
@@ -248,7 +248,7 @@ describe('NavigatorApp launcher runtime behavior', () => {
test('labels a linked-worktree recent with its branch over its base project, leaving plain projects unchanged', async () => {
const bridge = createBridge();
- bridge.project.listRecent = mock(() =>
+ bridge.project.listRecent = vi.fn(() =>
Promise.resolve([
{
path: '/Users/x/pnw-fishing/.ok/worktrees/dev',
@@ -273,7 +273,7 @@ describe('NavigatorApp launcher runtime behavior', () => {
test('flags worktrees with a badge + branch chip; projects show their path', async () => {
const bridge = createBridge();
- bridge.project.listRecent = mock(() =>
+ bridge.project.listRecent = vi.fn(() =>
Promise.resolve([
{
path: '/Users/x/pnw-fishing/.ok/worktrees/dev',
@@ -317,7 +317,7 @@ describe('NavigatorApp launcher runtime behavior', () => {
test('drops only the matching row when main pushes recent-removed-missing', async () => {
const bridge = createBridge();
- bridge.project.listRecent = mock(() =>
+ bridge.project.listRecent = vi.fn(() =>
Promise.resolve([
{ path: '/projects/keep', name: 'Keep Project' },
{ path: '/projects/gone', name: 'Gone Project' },
diff --git a/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx b/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx
index 5b6402c31..445219cdc 100644
--- a/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.first-run.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
let createDialogProps: Array<{
open: boolean;
@@ -22,19 +22,19 @@ let listPacksImpl: () => Promise<unknown> = () =>
],
});
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ theme: undefined }),
}));
-mock.module('@/hooks/use-theme-bridge', () => ({
+vi.doMock('@/hooks/use-theme-bridge', () => ({
useThemeBridge: () => {},
}));
-mock.module('./BetaBadge', () => ({
+vi.doMock('./BetaBadge', () => ({
BetaBadge: () => <span data-testid="beta-badge">Beta</span>,
}));
-mock.module('./ui/button', () => ({
+vi.doMock('./ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -42,7 +42,7 @@ mock.module('./ui/button', () => ({
),
}));
-mock.module('./ui/badge', () => ({
+vi.doMock('./ui/badge', () => ({
Badge: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<span {...props}>{children}</span>
),
@@ -54,7 +54,7 @@ mock.module('./ui/badge', () => ({
// shows skeletons while null) — so `findByTestId(card)` waits for the launcher's
// listPacks fetch to settle before a click, and the resolved pack name is
// available by then (avoids racing the async fetch under full-suite timing).
-mock.module('./PackCardGrid', () => ({
+vi.doMock('./PackCardGrid', () => ({
PackCardGrid: ({
onPackSelect,
packs,
@@ -75,11 +75,11 @@ mock.module('./PackCardGrid', () => ({
),
}));
-mock.module('@/lib/seed-client', () => ({
+vi.doMock('@/lib/seed-client', () => ({
seedClient: () => ({ listPacks: () => listPacksImpl() }),
}));
-mock.module('./CreateProjectDialog', () => ({
+vi.doMock('./CreateProjectDialog', () => ({
CreateProjectDialog: (props: {
open: boolean;
initialPackId?: string;
@@ -107,37 +107,37 @@ mock.module('./CreateProjectDialog', () => ({
},
}));
-mock.module('./CloneDialog', () => ({
+vi.doMock('./CloneDialog', () => ({
CloneDialog: (props: { open: boolean }) => (
<div data-testid="clone-dialog" data-open={String(props.open)} />
),
}));
-mock.module('./AuthModal', () => ({ AuthModal: () => null }));
-mock.module('./ConsentDialog', () => ({ ConsentDialog: () => null }));
-mock.module('./McpConsentDialog', () => ({ McpConsentDialog: () => null }));
-mock.module('./ShareReceiveDialog', () => ({ ShareReceiveDialog: () => null }));
-mock.module('@/lib/share/clone-controller', () => ({ createCloneController: () => ({}) }));
-mock.module('@/lib/transports/auth-query-transport', () => ({ ipcAuthQueryTransport: () => ({}) }));
-mock.module('@/lib/transports/auth-transport', () => ({ ipcAuthTransport: () => ({}) }));
-mock.module('@/lib/transports/clone-transport', () => ({ ipcCloneTransport: () => ({}) }));
+vi.doMock('./AuthModal', () => ({ AuthModal: () => null }));
+vi.doMock('./ConsentDialog', () => ({ ConsentDialog: () => null }));
+vi.doMock('./McpConsentDialog', () => ({ McpConsentDialog: () => null }));
+vi.doMock('./ShareReceiveDialog', () => ({ ShareReceiveDialog: () => null }));
+vi.doMock('@/lib/share/clone-controller', () => ({ createCloneController: () => ({}) }));
+vi.doMock('@/lib/transports/auth-query-transport', () => ({ ipcAuthQueryTransport: () => ({}) }));
+vi.doMock('@/lib/transports/auth-transport', () => ({ ipcAuthTransport: () => ({}) }));
+vi.doMock('@/lib/transports/clone-transport', () => ({ ipcCloneTransport: () => ({}) }));
function createBridge(recents: unknown[]) {
return {
appVersion: '0.4.0-beta.1',
- onMenuAction: mock(() => () => {}),
- onRecentRemovedMissing: mock(() => () => {}),
+ onMenuAction: vi.fn(() => () => {}),
+ onRecentRemovedMissing: vi.fn(() => () => {}),
config: { mode: 'navigator' },
project: {
- listRecent: mock(() => Promise.resolve(recents)),
- removeRecent: mock(() => Promise.resolve()),
- open: mock(() => Promise.resolve()),
- createNew: mock(() => Promise.resolve()),
- recordCreateNewBannerShown: mock(() => Promise.resolve()),
- readHeadBranch: mock(() => Promise.resolve({ currentBranch: null })),
+ listRecent: vi.fn(() => Promise.resolve(recents)),
+ removeRecent: vi.fn(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ createNew: vi.fn(() => Promise.resolve()),
+ recordCreateNewBannerShown: vi.fn(() => Promise.resolve()),
+ readHeadBranch: vi.fn(() => Promise.resolve({ currentBranch: null })),
},
dialog: {
- openFolder: mock(() => Promise.resolve('/picked/folder')),
+ openFolder: vi.fn(() => Promise.resolve('/picked/folder')),
},
};
}
@@ -294,7 +294,7 @@ describe('NavigatorApp first-run packs-forward launcher', () => {
// fetch must NOT read as "brand-new user" and show the first-run packs
// onboarding. It falls back to the returning-user three-card launcher.
const bridge = createBridge([]);
- bridge.project.listRecent = mock(() => Promise.reject(new Error('boom')));
+ bridge.project.listRecent = vi.fn(() => Promise.reject(new Error('boom')));
await renderNavigator(bridge);
expect(await screen.findByTestId('nav-create-new')).not.toBeNull();
diff --git a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
index b48fca6be..3234dafaa 100644
--- a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
@@ -13,8 +13,9 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import {
__resetLocalMenuActionBusForTests,
@@ -23,14 +24,14 @@ import {
// `next-themes` is consumed at the top of NavigatorApp; provide a stable
// stub so the test mount doesn't require a ThemeProvider.
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ theme: 'system' }),
}));
// `useThemeBridge` drives the cold-launch show-gate via real IPC calls
// (setThemeSource / signalThemeApplied). Stub to a no-op so the bridge stub
// doesn't need those methods.
-mock.module('@/hooks/use-theme-bridge', () => ({
+vi.doMock('@/hooks/use-theme-bridge', () => ({
useThemeBridge: () => {},
}));
@@ -131,15 +132,15 @@ function makeNavigatorBridge(): NavigatorBridgeStub {
}
describe('NavigatorApp new-project menu-action subscription', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// CreateProjectDialog's defaultProjectsRoot catch arm logs via
// console.warn on unhappy paths; NavigatorApp's listRecent catch logs
// via console.error. Suppress both to keep output clean.
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
@@ -235,7 +236,7 @@ describe('NavigatorApp new-project menu-action subscription', () => {
});
test('close-active-tab-or-window menu action closes the navigator window', async () => {
- const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
+ const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {});
const stub = makeNavigatorBridge();
render(<NavigatorApp bridge={stub.bridge} />);
diff --git a/packages/app/src/components/NavigatorApp.test.ts b/packages/app/src/components/NavigatorApp.test.ts
index 357b49e37..6c578e1e2 100644
--- a/packages/app/src/components/NavigatorApp.test.ts
+++ b/packages/app/src/components/NavigatorApp.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
interface MockBridge {
config: {
@@ -9,18 +9,18 @@ interface MockBridge {
mode: 'navigator' | 'editor';
};
project: {
- listRecent: ReturnType<typeof mock>;
- removeRecent: ReturnType<typeof mock>;
- getSessionState: ReturnType<typeof mock>;
- setSessionState: ReturnType<typeof mock>;
- open: ReturnType<typeof mock>;
- createNew: ReturnType<typeof mock>;
- recordCreateNewBannerShown: ReturnType<typeof mock>;
- readHeadBranch: ReturnType<typeof mock>;
- close: ReturnType<typeof mock>;
+ listRecent: ReturnType<typeof vi.fn>;
+ removeRecent: ReturnType<typeof vi.fn>;
+ getSessionState: ReturnType<typeof vi.fn>;
+ setSessionState: ReturnType<typeof vi.fn>;
+ open: ReturnType<typeof vi.fn>;
+ createNew: ReturnType<typeof vi.fn>;
+ recordCreateNewBannerShown: ReturnType<typeof vi.fn>;
+ readHeadBranch: ReturnType<typeof vi.fn>;
+ close: ReturnType<typeof vi.fn>;
};
dialog: {
- openFolder: ReturnType<typeof mock>;
+ openFolder: ReturnType<typeof vi.fn>;
};
}
@@ -34,9 +34,9 @@ function makeBridge(overrides: Partial<MockBridge> = {}): MockBridge {
mode: 'navigator',
},
project: {
- listRecent: mock(() => Promise.resolve([])),
- removeRecent: mock(() => Promise.resolve()),
- getSessionState: mock(() =>
+ listRecent: vi.fn(() => Promise.resolve([])),
+ removeRecent: vi.fn(() => Promise.resolve()),
+ getSessionState: vi.fn(() =>
Promise.resolve({
openTabs: [],
pinnedTabIds: [],
@@ -45,17 +45,17 @@ function makeBridge(overrides: Partial<MockBridge> = {}): MockBridge {
updatedAt: null,
}),
),
- setSessionState: mock(() => Promise.resolve()),
- open: mock(() => Promise.resolve()),
- createNew: mock(() => Promise.resolve()),
- recordCreateNewBannerShown: mock(() => Promise.resolve()),
- readHeadBranch: mock(() =>
+ setSessionState: vi.fn(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ createNew: vi.fn(() => Promise.resolve()),
+ recordCreateNewBannerShown: vi.fn(() => Promise.resolve()),
+ readHeadBranch: vi.fn(() =>
Promise.resolve({ currentBranch: null, headSha: null, detached: false }),
),
- close: mock(() => Promise.resolve()),
+ close: vi.fn(() => Promise.resolve()),
},
dialog: {
- openFolder: mock(() => Promise.resolve(null)),
+ openFolder: vi.fn(() => Promise.resolve(null)),
},
...overrides,
};
@@ -72,14 +72,14 @@ describe('NavigatorApp bridge contract', () => {
test('bridge.project.listRecent returns RecentProjectEntry[] shape', async () => {
const bridge = makeBridge({
project: {
- listRecent: mock(() =>
+ listRecent: vi.fn(() =>
Promise.resolve([
{ path: '/tmp/a', name: 'a', lastOpenedAt: '2026-04-20T00:00:00Z' },
{ path: '/tmp/b', name: 'b', lastOpenedAt: '2026-04-19T00:00:00Z', missing: true },
]),
),
- removeRecent: mock(() => Promise.resolve()),
- getSessionState: mock(() =>
+ removeRecent: vi.fn(() => Promise.resolve()),
+ getSessionState: vi.fn(() =>
Promise.resolve({
openTabs: [],
pinnedTabIds: [],
@@ -88,11 +88,11 @@ describe('NavigatorApp bridge contract', () => {
updatedAt: null,
}),
),
- setSessionState: mock(() => Promise.resolve()),
- open: mock(() => Promise.resolve()),
- createNew: mock(() => Promise.resolve()),
- recordCreateNewBannerShown: mock(() => Promise.resolve()),
- close: mock(() => Promise.resolve()),
+ setSessionState: vi.fn(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ createNew: vi.fn(() => Promise.resolve()),
+ recordCreateNewBannerShown: vi.fn(() => Promise.resolve()),
+ close: vi.fn(() => Promise.resolve()),
},
});
const list = await bridge.project.listRecent();
@@ -124,7 +124,7 @@ describe('NavigatorApp bridge contract', () => {
test('bridge.dialog.openFolder returns string | null', async () => {
const bridge = makeBridge({
dialog: {
- openFolder: mock(() => Promise.resolve('/tmp/picked')),
+ openFolder: vi.fn(() => Promise.resolve('/tmp/picked')),
},
});
const result = await bridge.dialog.openFolder();
@@ -134,9 +134,9 @@ describe('NavigatorApp bridge contract', () => {
test('bridge.project.readHeadBranch resolves to a HeadBranchInfo shape', async () => {
const bridge = makeBridge({
project: {
- listRecent: mock(() => Promise.resolve([])),
- removeRecent: mock(() => Promise.resolve()),
- getSessionState: mock(() =>
+ listRecent: vi.fn(() => Promise.resolve([])),
+ removeRecent: vi.fn(() => Promise.resolve()),
+ getSessionState: vi.fn(() =>
Promise.resolve({
openTabs: [],
pinnedTabIds: [],
@@ -145,14 +145,14 @@ describe('NavigatorApp bridge contract', () => {
updatedAt: null,
}),
),
- setSessionState: mock(() => Promise.resolve()),
- open: mock(() => Promise.resolve()),
- createNew: mock(() => Promise.resolve()),
- recordCreateNewBannerShown: mock(() => Promise.resolve()),
- readHeadBranch: mock(() =>
+ setSessionState: vi.fn(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ createNew: vi.fn(() => Promise.resolve()),
+ recordCreateNewBannerShown: vi.fn(() => Promise.resolve()),
+ readHeadBranch: vi.fn(() =>
Promise.resolve({ currentBranch: 'feat/test', headSha: null, detached: false }),
),
- close: mock(() => Promise.resolve()),
+ close: vi.fn(() => Promise.resolve()),
},
});
const info = await bridge.project.readHeadBranch('/tmp/proj');
@@ -211,8 +211,8 @@ describe('NavigatorApp error-state helpers', () => {
test('runWithErrorStatePure clears error state then awaits the wrapped fn', async () => {
const { runWithErrorStatePure } = await import('./NavigatorApp');
- const setError = mock(() => {});
- const fn = mock(() => Promise.resolve());
+ const setError = vi.fn(() => {});
+ const fn = vi.fn(() => Promise.resolve());
await runWithErrorStatePure(fn, 'fallback', setError);
expect(setError).toHaveBeenCalledWith(null);
expect(fn).toHaveBeenCalled();
diff --git a/packages/app/src/components/NewItemDialog.test.ts b/packages/app/src/components/NewItemDialog.test.ts
index 5f9caf405..2215af093 100644
--- a/packages/app/src/components/NewItemDialog.test.ts
+++ b/packages/app/src/components/NewItemDialog.test.ts
@@ -6,7 +6,7 @@
* Cmd/Ctrl+Alt+N keydown predicate used by App.tsx's NewItemShortcutHandler.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
composeNewItemPath,
diff --git a/packages/app/src/components/NewTemplateDialog.dom.test.tsx b/packages/app/src/components/NewTemplateDialog.dom.test.tsx
index 4ccc127bb..10d9db084 100644
--- a/packages/app/src/components/NewTemplateDialog.dom.test.tsx
+++ b/packages/app/src/components/NewTemplateDialog.dom.test.tsx
@@ -12,9 +12,10 @@
* can pin the foundational invariant the shift rides on: a dismiss press must
* not perturb the form's validation state.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { NewTemplateDialog } from './NewTemplateDialog';
// Radix Dialog (focus-trap) reaches for DOM globals the shared jsdom preload
diff --git a/packages/app/src/components/NewWorktreeDialog.dom.test.tsx b/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
index 961659ef8..0385fc6d5 100644
--- a/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
+++ b/packages/app/src/components/NewWorktreeDialog.dom.test.tsx
@@ -1,13 +1,13 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
-const refreshWorktrees = mock(() => {});
-mock.module('@/lib/worktree-store', () => ({ refreshWorktrees }));
+const refreshWorktrees = vi.fn(() => {});
+vi.doMock('@/lib/worktree-store', () => ({ refreshWorktrees }));
function createBridge(createResult: unknown) {
return {
- worktree: { create: mock(() => Promise.resolve(createResult)) },
- project: { open: mock(() => Promise.resolve()) },
+ worktree: { create: vi.fn(() => Promise.resolve(createResult)) },
+ project: { open: vi.fn(() => Promise.resolve()) },
};
}
@@ -478,7 +478,7 @@ describe('NewWorktreeDialog', () => {
});
test('opening an existing-worktree branch still calls create (createBranch false, no base) and opens its path', async () => {
- const onOpenChange = mock(() => {});
+ const onOpenChange = vi.fn(() => {});
const bridge = createBridge({ ok: true, path: '/repo/.ok/worktrees/dev', created: false });
render(
<NewWorktreeDialog
diff --git a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
index 3f9dd288d..572fee6f3 100644
--- a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
+++ b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
@@ -6,13 +6,14 @@
*
* Runs under `bun run test:dom` (jsdom substrate per precedent #43).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import type { Config } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
@@ -32,7 +33,7 @@ let patchResultOk = true;
const patchCalls: unknown[] = [];
const toastErrors: unknown[][] = [];
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: mergedConfig as Config | null,
projectLocalBinding: projectLocalBindingNull
@@ -48,7 +49,7 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (...args: unknown[]) => toastErrors.push(args),
success: () => {},
diff --git a/packages/app/src/components/OnboardingCard.dom.test.tsx b/packages/app/src/components/OnboardingCard.dom.test.tsx
index bcd480802..9336cdf30 100644
--- a/packages/app/src/components/OnboardingCard.dom.test.tsx
+++ b/packages/app/src/components/OnboardingCard.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Stub the animated mascot — its rAF/SVG internals aren't under test here.
-mock.module('@/components/OkBlob', () => ({
+vi.doMock('@/components/OkBlob', () => ({
OkBlob: () => <span data-testid="ok-blob" />,
}));
@@ -31,7 +31,7 @@ function freshStore(): OnboardingCardStore {
let originalFetch: typeof globalThis.fetch;
beforeEach(() => {
originalFetch = globalThis.fetch;
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
) as never;
});
diff --git a/packages/app/src/components/OnboardingCardMount.dom.test.tsx b/packages/app/src/components/OnboardingCardMount.dom.test.tsx
index d967d4258..544cab6ad 100644
--- a/packages/app/src/components/OnboardingCardMount.dom.test.tsx
+++ b/packages/app/src/components/OnboardingCardMount.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
let mockVisible = false;
-mock.module('@/hooks/use-onboarding-card-visible', () => ({
+vi.doMock('@/hooks/use-onboarding-card-visible', () => ({
useOnboardingCardVisible: () => mockVisible,
}));
@@ -13,7 +13,7 @@ const { OnboardingCardMount } = await import('./OnboardingCard');
let originalFetch: typeof globalThis.fetch;
beforeEach(() => {
originalFetch = globalThis.fetch;
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
) as never;
});
diff --git a/packages/app/src/components/PackCardGrid.dom.test.tsx b/packages/app/src/components/PackCardGrid.dom.test.tsx
index 7c9bd86ae..6cc4f282d 100644
--- a/packages/app/src/components/PackCardGrid.dom.test.tsx
+++ b/packages/app/src/components/PackCardGrid.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ComponentProps, ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkPackId, OkSeedListPacksResult, OkSeedPackInfo } from '@/lib/desktop-bridge-types';
let listPacksImpl: () => Promise<OkSeedListPacksResult> = async () => ({
@@ -12,7 +12,7 @@ const listPacksCalls: string[] = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/core/macro', () => ({
+vi.doMock('@lingui/core/macro', () => ({
...actualLinguiMacro,
plural: (count: number, forms: { one: string; other: string }) =>
(count === 1 ? forms.one : forms.other).replace('#', String(count)),
@@ -20,7 +20,7 @@ mock.module('@lingui/core/macro', () => ({
strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -29,7 +29,7 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('@/lib/seed-client', () => ({
+vi.doMock('@/lib/seed-client', () => ({
seedClient: () => ({
listPacks: () => {
listPacksCalls.push('listPacks');
@@ -104,7 +104,7 @@ describe('PackCardGrid runtime behavior', () => {
});
test('renders a create-a-new-file footer button and fires the callback on click', async () => {
- const onCreateBlankFile = mock(() => {});
+ const onCreateBlankFile = vi.fn(() => {});
await renderPackCardGrid({ packs: allPacks, onCreateBlankFile });
const buttons = screen.getAllByRole('button');
diff --git a/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx b/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx
index 2b0296f67..7cce9c082 100644
--- a/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx
+++ b/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx
@@ -20,8 +20,9 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
interface PageListCachePayload {
pages: Set<string>;
@@ -32,13 +33,13 @@ interface PageListCachePayload {
pageIcons: ReadonlyMap<string, string>;
}
-const setPageListCacheMock = mock((_payload: PageListCachePayload) => {});
+const setPageListCacheMock = vi.fn((_payload: PageListCachePayload) => {});
-mock.module('@/lib/documents-events', () => ({
+vi.doMock('@/lib/documents-events', () => ({
subscribeToDocumentsChanged: () => () => {},
}));
-mock.module('@/editor/page-list-cache', () => ({
+vi.doMock('@/editor/page-list-cache', () => ({
buildPageIconsIndex: (pageMeta: ReadonlyMap<string, { icon?: string }>) => {
const icons = new Map<string, string>();
for (const [docName, meta] of pageMeta) {
diff --git a/packages/app/src/components/PageListContext.push-coalescing.dom.test.tsx b/packages/app/src/components/PageListContext.push-coalescing.dom.test.tsx
index 933f529f1..9138e2e7c 100644
--- a/packages/app/src/components/PageListContext.push-coalescing.dom.test.tsx
+++ b/packages/app/src/components/PageListContext.push-coalescing.dom.test.tsx
@@ -17,12 +17,13 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, beforeEach, describe, expect, jest, mock, test } from 'bun:test';
+
import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-const setPageListCacheMock = mock((_payload: unknown) => {});
+const setPageListCacheMock = vi.fn((_payload: unknown) => {});
-mock.module('@/editor/page-list-cache', () => ({
+vi.doMock('@/editor/page-list-cache', () => ({
buildPageIconsIndex: () => new Map<string, string>(),
buildPagesBySlugIndex: (pages: ReadonlySet<string>, toSlug: (docName: string) => string) => {
const index = new Map<string, string>();
@@ -82,7 +83,7 @@ beforeEach(() => {
docResolvers = [];
setPageListCacheMock.mockClear();
__resetDocumentListInflightForTests();
- jest.useFakeTimers();
+ vi.useFakeTimers();
originalFetch = globalThis.fetch;
globalThis.fetch = ((input: RequestInfo | URL) => {
const url = String(input);
@@ -102,7 +103,7 @@ beforeEach(() => {
afterEach(() => {
cleanup();
- jest.useRealTimers();
+ vi.useRealTimers();
globalThis.fetch = originalFetch;
});
@@ -155,13 +156,13 @@ describe('PageListContext push coalescing', () => {
// Nothing fires inside the window.
expect(pageResolvers.length).toBe(0);
act(() => {
- jest.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS - 1);
+ vi.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS - 1);
});
expect(pageResolvers.length).toBe(0);
// The trailing edge flushes exactly one fetch pair for the whole burst.
act(() => {
- jest.advanceTimersByTime(1);
+ vi.advanceTimersByTime(1);
});
expect(pageResolvers.length).toBe(1);
expect(docResolvers.length).toBe(1);
@@ -172,7 +173,7 @@ describe('PageListContext push coalescing', () => {
// A push after the flush arms a fresh window and fetches again.
emitFilesPush();
act(() => {
- jest.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS);
+ vi.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS);
});
expect(pageResolvers.length).toBe(1);
});
@@ -187,11 +188,11 @@ describe('PageListContext push coalescing', () => {
emitFilesPush();
act(() => {
- jest.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS / 2);
+ vi.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS / 2);
});
emitFilesPush();
act(() => {
- jest.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS / 2);
+ vi.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS / 2);
});
// The flush fired at the ORIGINAL deadline even though the second push
@@ -211,7 +212,7 @@ describe('PageListContext push coalescing', () => {
emitDocumentsChanged(['backlinks', 'graph']);
});
act(() => {
- jest.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS * 2);
+ vi.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS * 2);
});
expect(pageResolvers.length).toBe(0);
});
@@ -230,7 +231,7 @@ describe('PageListContext push coalescing', () => {
unmount();
act(() => {
- jest.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS * 2);
+ vi.advanceTimersByTime(PUSH_REFRESH_COALESCE_MS * 2);
});
// Cleanup cleared the armed timer and disposed the scheduler, so the
diff --git a/packages/app/src/components/PageListContext.test.ts b/packages/app/src/components/PageListContext.test.ts
index ec8f7fbc7..dbcd04b87 100644
--- a/packages/app/src/components/PageListContext.test.ts
+++ b/packages/app/src/components/PageListContext.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { mergePageSets, pruneConfirmedOptimisticPages } from './PageListContext';
describe('PageListContext helpers', () => {
diff --git a/packages/app/src/components/ProjectSwitcher.dom.test.tsx b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
index 8c6fe13bb..87d1f4067 100644
--- a/packages/app/src/components/ProjectSwitcher.dom.test.tsx
+++ b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
@@ -1,6 +1,6 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { createContext, type ReactNode, use } from 'react';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import {
__resetLocalMenuActionBusForTests,
emitLocalMenuAction,
@@ -30,7 +30,7 @@ const SubStateContext = createContext<{ open: boolean; onOpenChange: (o: boolean
open: false,
onOpenChange: () => {},
});
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: ({ children, onOpenChange }: MenuProps) => {
lastDropdownOpenChange = onOpenChange ?? null;
return <div>{children}</div>;
@@ -104,7 +104,7 @@ mock.module('@/components/ui/dropdown-menu', () => ({
},
}));
-mock.module('@/components/ui/input-group', () => ({
+vi.doMock('@/components/ui/input-group', () => ({
InputGroup: ({ children, ...props }: ItemProps) => (
<fieldset
{...props}
@@ -119,7 +119,7 @@ mock.module('@/components/ui/input-group', () => ({
InputGroupInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
}));
-mock.module('@/components/ui/sidebar', () => ({
+vi.doMock('@/components/ui/sidebar', () => ({
SidebarMenuButton: ({ children, ...props }: ItemProps) => (
<button type="button" {...props}>
{children}
@@ -127,7 +127,7 @@ mock.module('@/components/ui/sidebar', () => ({
),
}));
-mock.module('./CreateProjectDialog', () => ({
+vi.doMock('./CreateProjectDialog', () => ({
CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
createDialogProps.push(props);
return <div data-testid="create-project-dialog" data-open={String(props.open)} />;
@@ -142,7 +142,7 @@ let newWorktreeProps: Array<{
behindByBranch?: ReadonlyMap<string, number>;
initialBranchName?: string;
}> = [];
-mock.module('./NewWorktreeDialog', () => ({
+vi.doMock('./NewWorktreeDialog', () => ({
NewWorktreeDialog: (props: {
open: boolean;
branches?: readonly string[];
@@ -164,7 +164,7 @@ mock.module('./NewWorktreeDialog', () => ({
// The current window's project is a git repo on `main` — drives the trigger's
// branch line and the gate on the top-level "New worktree…" item.
-mock.module('@/hooks/use-current-branch', () => ({
+vi.doMock('@/hooks/use-current-branch', () => ({
useCurrentBranch: () => 'main',
}));
// The switcher's cached worktree model feeds RecentProjectsMenu's grouped-view
@@ -172,7 +172,7 @@ mock.module('@/hooks/use-current-branch', () => ({
// row in a projects-AND-worktrees search — the projects-only search must gate
// it out. Grouping/branch-search behavior is covered in
// RecentProjectsMenu.dom.test.tsx.
-mock.module('@/hooks/use-worktrees', () => ({
+vi.doMock('@/hooks/use-worktrees', () => ({
useWorktrees: () => ({
mainRoot: '/projects/current',
currentBranch: 'main',
@@ -217,7 +217,7 @@ function createBridge() {
projectPath: '/projects/current',
},
project: {
- listRecent: mock(() =>
+ listRecent: vi.fn(() =>
Promise.resolve([
recent('Current', '/projects/current'),
...Array.from({ length: 10 }, (_, index) => recent(`Project ${index + 1}`)),
@@ -234,20 +234,20 @@ function createBridge() {
},
]),
),
- open: mock(() => Promise.resolve()),
- openFile: mock(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ openFile: vi.fn(() => Promise.resolve()),
},
dialog: {
- openFolder: mock(() => Promise.resolve('/chosen/folder')),
+ openFolder: vi.fn(() => Promise.resolve('/chosen/folder')),
},
navigator: {
- open: mock(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
},
worktree: {
- list: mock(() => Promise.resolve({ ok: false as const, reason: 'no-git' as const })),
- create: mock(() => Promise.resolve({ ok: false as const, reason: 'no-git' as const })),
+ list: vi.fn(() => Promise.resolve({ ok: false as const, reason: 'no-git' as const })),
+ create: vi.fn(() => Promise.resolve({ ok: false as const, reason: 'no-git' as const })),
},
- onMenuAction: mock(() => () => {}),
+ onMenuAction: vi.fn(() => () => {}),
};
}
@@ -340,7 +340,7 @@ describe('ProjectSwitcher dropdown behavior', () => {
test('the per-row × removes a recent from the list without opening it', async () => {
const bridge = createBridge();
- bridge.project.removeRecent = mock(() => Promise.resolve());
+ bridge.project.removeRecent = vi.fn(() => Promise.resolve());
render(<ProjectSwitcher bridge={bridge as never} />);
await openMenu();
@@ -421,7 +421,7 @@ describe('ProjectSwitcher dropdown behavior', () => {
// project). The cached model (mocked useWorktrees) has no branch matching
// the query, so the flyout's no-match create option appears.
const bridge = createBridge();
- bridge.project.listRecent = mock(() =>
+ bridge.project.listRecent = vi.fn(() =>
Promise.resolve([
{
name: 'current',
@@ -471,7 +471,7 @@ describe('ProjectSwitcher dropdown behavior', () => {
test('scrolling the recents list closes an open worktree flyout (submenu does not follow the row off-screen)', async () => {
// Same git-enriched current project with a worktree so its submenu renders.
const bridge = createBridge();
- bridge.project.listRecent = mock(() =>
+ bridge.project.listRecent = vi.fn(() =>
Promise.resolve([
{
name: 'current',
@@ -579,7 +579,7 @@ describe('ProjectSwitcher dropdown behavior', () => {
resolveList = resolve;
});
const bridge = createBridge();
- bridge.project.listRecent = mock(() => pending);
+ bridge.project.listRecent = vi.fn(() => pending);
render(<ProjectSwitcher bridge={bridge as never} />);
// Open the menu but do NOT wait for the search box (it can't appear until
@@ -609,7 +609,7 @@ describe('ProjectSwitcher dropdown behavior', () => {
test('shows "No recent projects." only once loaded AND genuinely empty', async () => {
const bridge = createBridge();
- bridge.project.listRecent = mock(() => Promise.resolve([]));
+ bridge.project.listRecent = vi.fn(() => Promise.resolve([]));
render(<ProjectSwitcher bridge={bridge as never} />);
fireEvent.click(screen.getByTestId('project-switcher-trigger'));
diff --git a/packages/app/src/components/ProjectSwitcher.test.ts b/packages/app/src/components/ProjectSwitcher.test.ts
index 00efec449..3b35e0ff1 100644
--- a/packages/app/src/components/ProjectSwitcher.test.ts
+++ b/packages/app/src/components/ProjectSwitcher.test.ts
@@ -11,7 +11,7 @@
* - `runWithToast` non-Error rejection falls back to the provided fallback
* - setError(null) clear-at-start does NOT surface as a toast
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
describe('ProjectSwitcher module', () => {
test('Component module imports cleanly', async () => {
@@ -24,14 +24,14 @@ describe('ProjectSwitcher module', () => {
describe('runWithToast (IPC rejection → toast feedback)', () => {
test('success: no toast.error fires', async () => {
const { runWithToast } = await import('./ProjectSwitcher');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Failed to open.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
test('Error rejection: toast.error fires with Error.message', async () => {
const { runWithToast } = await import('./ProjectSwitcher');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(
() => Promise.reject(new Error('utility failed to boot')),
'Failed to open.',
@@ -42,21 +42,21 @@ describe('runWithToast (IPC rejection → toast feedback)', () => {
test('non-Error rejection: toast.error fires with fallback', async () => {
const { runWithToast } = await import('./ProjectSwitcher');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject('network dropped'), 'Failed to open.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Failed to open.');
});
test('empty-message Error: toast.error fires with fallback', async () => {
const { runWithToast } = await import('./ProjectSwitcher');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.reject(new Error('')), 'Failed to open.', toastApi);
expect(toastApi.error).toHaveBeenCalledWith('Failed to open.');
});
test('does not re-throw on rejection (caller awaits without try/catch)', async () => {
const { runWithToast } = await import('./ProjectSwitcher');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
let afterAwait = false;
await runWithToast(() => Promise.reject(new Error('x')), 'Failed to open.', toastApi);
afterAwait = true;
@@ -68,7 +68,7 @@ describe('runWithToast (IPC rejection → toast feedback)', () => {
// clear stale state; our adapter must filter the null out rather than
// passing it to toast.error(null).
const { runWithToast } = await import('./ProjectSwitcher');
- const toastApi = { error: mock(() => {}) };
+ const toastApi = { error: vi.fn(() => {}) };
await runWithToast(() => Promise.resolve(), 'Failed to open.', toastApi);
expect(toastApi.error).not.toHaveBeenCalled();
});
diff --git a/packages/app/src/components/PropertyInlineLinks.dom.test.tsx b/packages/app/src/components/PropertyInlineLinks.dom.test.tsx
index de4c6fae4..9488c7672 100644
--- a/packages/app/src/components/PropertyInlineLinks.dom.test.tsx
+++ b/packages/app/src/components/PropertyInlineLinks.dom.test.tsx
@@ -15,8 +15,8 @@
* helpers — assert through queries on the rendered DOM after `render`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { PropertyInlineLinks } from './PropertyInlineLinks';
afterEach(() => {
diff --git a/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx b/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx
index fb5bb2c53..76d11783d 100644
--- a/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx
+++ b/packages/app/src/components/PropertyPanel.nested-crud.dom.test.tsx
@@ -13,11 +13,11 @@
* a mounted React tree with effects. These tests pin that seam.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { readFmMap } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { PropertyProvider } from './PropertyContext';
import { PropertyPanel } from './PropertyPanel';
diff --git a/packages/app/src/components/PropertyPanel.test.tsx b/packages/app/src/components/PropertyPanel.test.tsx
index 411c3aa0f..186894b37 100644
--- a/packages/app/src/components/PropertyPanel.test.tsx
+++ b/packages/app/src/components/PropertyPanel.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { renderToString } from 'react-dom/server';
+import { afterEach, describe, expect, test } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { PropertyProvider } from './PropertyContext';
import { PropertyPanel } from './PropertyPanel';
diff --git a/packages/app/src/components/PropertyWidgets.dom.test.tsx b/packages/app/src/components/PropertyWidgets.dom.test.tsx
index 8ad1f6fcb..15319672e 100644
--- a/packages/app/src/components/PropertyWidgets.dom.test.tsx
+++ b/packages/app/src/components/PropertyWidgets.dom.test.tsx
@@ -10,8 +10,9 @@
* boundary — feed it `value` + an `onCommit` spy and the grammar gate
* becomes a pure-React assertion.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ListWidget, TextWidget } from './PropertyWidgets';
@@ -20,7 +21,7 @@ function renderWidget(opts: {
value: string[];
onCommit?: (next: string[]) => void;
}) {
- const onCommit = opts.onCommit ?? mock(() => {});
+ const onCommit = opts.onCommit ?? vi.fn(() => {});
// TooltipProvider wraps the tree because invalid tag chips render
// inside a Radix Tooltip — production has a root provider; test
// substrate has to opt in.
@@ -105,7 +106,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
});
test('addChip rejects invalid input on Enter — no onCommit fires; draft persists', () => {
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'tags', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'bad!' } });
@@ -124,7 +125,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
});
test('addChip accepts a valid tag on Enter — commits + clears draft + no rejection state', () => {
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'tags', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'showcase' } });
@@ -139,7 +140,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
test('addChip accepts a digit-leading tag like a year (2026)', () => {
// Digit-leading tags are valid in frontmatter even though the inline
// `#tag` surface rejects them — a year is a legitimate tag.
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'tags', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: '2026' } });
@@ -164,7 +165,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
});
test('Escape clears rejection state without committing', () => {
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'tags', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'bad!' } });
@@ -182,7 +183,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
// would either render as invalid on the next paint (renderer's
// `FRONTMATTER_TAG_VALUE_RE` rejects bare `#`) or silently re-
// normalize on the next on-disk YAML round-trip.
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'tags', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: '#showcase' } });
@@ -197,7 +198,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
// Generic list fields (`aliases`, `categories`, …) commit values
// verbatim — the `#`-strip is scoped to `isTagsField` since
// other fields don't share the tag grammar's tolerance.
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'aliases', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: '#literal' } });
@@ -207,7 +208,7 @@ describe('ListWidget — input-side grammar gate (tags field only)', () => {
});
test('a non-tag list field commits any string — grammar gate stays scoped', () => {
- const onCommit = mock(() => {});
+ const onCommit = vi.fn(() => {});
const { container } = renderWidget({ keyName: 'aliases', value: [], onCommit });
const input = container.querySelector('[data-testid="list-chip-input"]') as HTMLInputElement;
fireEvent.change(input, { target: { value: '2026' } });
@@ -228,7 +229,7 @@ function renderTextWidget(opts: {
value: string;
onCommit?: (next: string) => void;
}) {
- const onCommit = opts.onCommit ?? mock(() => {});
+ const onCommit = opts.onCommit ?? vi.fn(() => {});
const result = render(
<TooltipProvider>
<TextWidget keyName={opts.keyName} value={opts.value} onCommit={onCommit} />
diff --git a/packages/app/src/components/PropertyWidgets.test.ts b/packages/app/src/components/PropertyWidgets.test.ts
index 5e503e1e4..481d46af9 100644
--- a/packages/app/src/components/PropertyWidgets.test.ts
+++ b/packages/app/src/components/PropertyWidgets.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { format } from 'date-fns';
+import { describe, expect, test } from 'vitest';
import { parseFromInput } from './PropertyWidgets';
describe('PropertyWidgets — parseFromInput', () => {
diff --git a/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx b/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx
index a6f1331fe..da502e9c1 100644
--- a/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx
+++ b/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { SharePublishOwner } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
import { act } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { PublishErrorPresentation } from '@/lib/share/publish-wizard';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
@@ -60,37 +60,37 @@ function sanitizeRepoName(value: string) {
.replace(/^-|-$/g, '');
}
-const fetchPublishOwnersMock = mock(
+const fetchPublishOwnersMock = vi.fn(
async () => ownersQueue.shift() ?? { ok: true, owners: defaultOwners },
);
-const fetchPublishNameCheckMock = mock(async () => ({ ok: true }));
-const submitPublishRequestMock = mock(async (payload: SubmitPayload) => {
+const fetchPublishNameCheckMock = vi.fn(async () => ({ ok: true }));
+const submitPublishRequestMock = vi.fn(async (payload: SubmitPayload) => {
submitCalls.push(payload);
return submitResult;
});
-const requestShareConstructUrlMock = mock(async () => shareConstructUrlResponse);
-const mapShareErrorToToastMock = mock((error: string, branch?: string) =>
+const requestShareConstructUrlMock = vi.fn(async () => shareConstructUrlResponse);
+const mapShareErrorToToastMock = vi.fn((error: string, branch?: string) =>
branch ? `mapped ${error} on ${branch}` : `mapped ${error}`,
);
-const scheduleClipboardWriteMock = mock(async (text: string) => {
+const scheduleClipboardWriteMock = vi.fn(async (text: string) => {
clipboardCalls.push(text);
if (clipboardError) throw clipboardError;
});
-const isPermissionsPolicyRefusalMock = mock(() => permissionsPolicyRefusal);
+const isPermissionsPolicyRefusalMock = vi.fn(() => permissionsPolicyRefusal);
const toastMock = {
- error: mock(() => {}),
- success: mock(() => {}),
+ error: vi.fn(() => {}),
+ success: vi.fn(() => {}),
};
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@/components/AuthModal', () => ({
+vi.doMock('@/components/AuthModal', () => ({
AuthModal: ({ onSuccess, open }: { onSuccess: () => void; open: boolean }) =>
open ? (
<button data-testid="auth-modal" type="button" onClick={onSuccess}>
@@ -99,25 +99,25 @@ mock.module('@/components/AuthModal', () => ({
) : null,
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({ activeDocName }),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => ({ contentDir: workspaceContentDir }),
}));
-mock.module('@/lib/share/run-share-action', () => ({
+vi.doMock('@/lib/share/run-share-action', () => ({
mapShareErrorToToast: mapShareErrorToToastMock,
requestShareConstructUrl: requestShareConstructUrlMock,
}));
-mock.module('@/lib/share/clipboard-adapter', () => ({
+vi.doMock('@/lib/share/clipboard-adapter', () => ({
isPermissionsPolicyRefusal: isPermissionsPolicyRefusalMock,
scheduleClipboardWrite: scheduleClipboardWriteMock,
}));
-mock.module('@/lib/share/publish-wizard', () => ({
+vi.doMock('@/lib/share/publish-wizard', () => ({
canSubmitPublish: ({
nameCheck,
owner,
@@ -144,7 +144,7 @@ mock.module('@/lib/share/publish-wizard', () => ({
submitPublishRequest: submitPublishRequestMock,
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: toastMock,
}));
@@ -158,7 +158,7 @@ function setDesktopBridge(bridge: unknown) {
async function renderDialog() {
const { PublishToGitHubDialog } = await import('./PublishToGitHubDialog');
- const onOpenChange = mock((_open: boolean) => {});
+ const onOpenChange = vi.fn((_open: boolean) => {});
await act(async () => {
render(<PublishToGitHubDialog open={true} onOpenChange={onOpenChange} />);
await Promise.resolve();
diff --git a/packages/app/src/components/PublishToGitHubDialog.test.ts b/packages/app/src/components/PublishToGitHubDialog.test.ts
index f4d1727e8..d8f16063a 100644
--- a/packages/app/src/components/PublishToGitHubDialog.test.ts
+++ b/packages/app/src/components/PublishToGitHubDialog.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { PublishToGitHubDialog } from './PublishToGitHubDialog';
describe('PublishToGitHubDialog module', () => {
diff --git a/packages/app/src/components/ReadonlyPropertyPanel.dom.test.tsx b/packages/app/src/components/ReadonlyPropertyPanel.dom.test.tsx
index 4a0a32c38..eca686afe 100644
--- a/packages/app/src/components/ReadonlyPropertyPanel.dom.test.tsx
+++ b/packages/app/src/components/ReadonlyPropertyPanel.dom.test.tsx
@@ -5,11 +5,11 @@
* and that complex values fall back to the read-only preview.
*/
-import { describe, expect, mock, test } from 'bun:test';
import { render, screen } from '@testing-library/react';
+import { describe, expect, test, vi } from 'vitest';
import * as linguiShim from '../../tests/lingui-macro-shim';
-mock.module('@lingui/react/macro', () => linguiShim);
+vi.doMock('@lingui/react/macro', () => linguiShim);
const { ReadonlyPropertyPanel } = await import('./ReadonlyPropertyPanel');
diff --git a/packages/app/src/components/RecentProjectsMenu.dom.test.tsx b/packages/app/src/components/RecentProjectsMenu.dom.test.tsx
index a29a9b38e..5b66be1e9 100644
--- a/packages/app/src/components/RecentProjectsMenu.dom.test.tsx
+++ b/packages/app/src/components/RecentProjectsMenu.dom.test.tsx
@@ -1,7 +1,7 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { createContext, type ReactNode, use, useState } from 'react';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { RecentProjectEntry } from '@/lib/desktop-bridge-types';
type ItemProps = {
@@ -27,7 +27,7 @@ const SubStateContext = createContext<{ open: boolean; onOpenChange: (o: boolean
open: false,
onOpenChange: () => {},
});
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenuItem: ({ children, onSelect, ...props }: ItemProps) => (
<div
role="menuitem"
@@ -117,16 +117,16 @@ mock.module('@/components/ui/dropdown-menu', () => ({
},
}));
-mock.module('@/components/ui/input-group', () => ({
+vi.doMock('@/components/ui/input-group', () => ({
InputGroup: ({ children, ...props }: ItemProps) => <div {...props}>{children}</div>,
InputGroupAddon: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
InputGroupInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
}));
-const refreshWorktrees = mock(() => {});
-mock.module('@/lib/worktree-store', () => ({ refreshWorktrees }));
-const toastError = mock((_msg: string) => {});
-mock.module('sonner', () => ({ toast: { error: toastError, success: mock(() => {}) } }));
+const refreshWorktrees = vi.fn(() => {});
+vi.doMock('@/lib/worktree-store', () => ({ refreshWorktrees }));
+const toastError = vi.fn((_msg: string) => {});
+vi.doMock('sonner', () => ({ toast: { error: toastError, success: vi.fn(() => {}) } }));
function main(path: string, commonDir: string): RecentProjectEntry {
return {
@@ -169,9 +169,9 @@ function model(
function createBridge() {
return {
- project: { open: mock(() => Promise.resolve()) },
+ project: { open: vi.fn(() => Promise.resolve()) },
worktree: {
- create: mock(() =>
+ create: vi.fn(() =>
Promise.resolve({
ok: true as const,
path: '/repo/.ok/worktrees/feature-x',
@@ -233,8 +233,8 @@ function renderMenu(
}> = {},
) {
const bridge = overrides.bridge ?? createBridge();
- const closeMenu = overrides.closeMenu ?? mock(() => {});
- const openNewWorktreeWith = overrides.openNewWorktreeWith ?? mock((_name: string) => {});
+ const closeMenu = overrides.closeMenu ?? vi.fn(() => {});
+ const openNewWorktreeWith = overrides.openNewWorktreeWith ?? vi.fn((_name: string) => {});
render(
<Host
bridge={bridge}
@@ -609,7 +609,7 @@ describe('RecentProjectsMenu — grouped browse (no query)', () => {
});
test('the current project flyout offers "Create worktree <query>" when nothing matches; clicking it opens the pre-filled dialog', async () => {
- const openNewWorktreeWith = mock((_name: string) => {});
+ const openNewWorktreeWith = vi.fn((_name: string) => {});
renderMenu({
recents: [
main('/repo', '/repo/.git'),
@@ -1005,7 +1005,7 @@ describe('RecentProjectsMenu — search (cross-project)', () => {
test('a failed create-on-demand toasts and does not open a window', async () => {
toastError.mockClear();
const bridge = createBridge();
- bridge.worktree.create = mock(() =>
+ bridge.worktree.create = vi.fn(() =>
Promise.resolve({ ok: false as const, reason: 'branch-exists' as const }),
);
renderMenu({
diff --git a/packages/app/src/components/RenderedDiffView.dom.test.tsx b/packages/app/src/components/RenderedDiffView.dom.test.tsx
index e0b3de964..678df7223 100644
--- a/packages/app/src/components/RenderedDiffView.dom.test.tsx
+++ b/packages/app/src/components/RenderedDiffView.dom.test.tsx
@@ -12,8 +12,9 @@
*
* Invocation: `bun run test:dom src/components/RenderedDiffView.dom.test.tsx`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
countRenderedDiffAnchors,
RENDERED_DIFF_CHANGE_SELECTOR,
diff --git a/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx b/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
index 457d07e91..210ea2c7e 100644
--- a/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
+++ b/packages/app/src/components/ReportBugCrashInviteTrigger.dom.test.tsx
@@ -11,10 +11,11 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
import { crashInviteStore } from '@/lib/crash-invite-store';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { ReportBugCrashInviteTrigger } from './ReportBugCrashInviteTrigger';
diff --git a/packages/app/src/components/ReportBugDialog.dom.test.tsx b/packages/app/src/components/ReportBugDialog.dom.test.tsx
index f4139356a..67e599246 100644
--- a/packages/app/src/components/ReportBugDialog.dom.test.tsx
+++ b/packages/app/src/components/ReportBugDialog.dom.test.tsx
@@ -7,7 +7,7 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import type {
OkBugReportCrashDetectedEvent,
OkBugReportCreateResult,
@@ -19,10 +19,11 @@ import type {
import { act, cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
<>{(value === 1 ? one : other).replace('#', String(value))}</>
diff --git a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
index 4a0b2b9ed..31c7888de 100644
--- a/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
+++ b/packages/app/src/components/ReportBugMenuTrigger.dom.test.tsx
@@ -10,8 +10,9 @@
*
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetLocalMenuActionBusForTests,
emitLocalMenuAction,
diff --git a/packages/app/src/components/ServerDriftToast.dom.test.tsx b/packages/app/src/components/ServerDriftToast.dom.test.tsx
index 59a2154e2..c383dc8c4 100644
--- a/packages/app/src/components/ServerDriftToast.dom.test.tsx
+++ b/packages/app/src/components/ServerDriftToast.dom.test.tsx
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { ServerDriftToast } from '@/components/ServerDriftToast';
afterEach(cleanup);
@@ -24,14 +24,14 @@ describe('ServerDriftToast', () => {
});
test('the restart button calls onRestart', () => {
- const onRestart = mock(() => {});
+ const onRestart = vi.fn(() => {});
render(<ServerDriftToast {...baseProps} onRestart={onRestart} onDismiss={() => {}} />);
fireEvent.click(screen.getByRole('button', { name: baseProps.restartLabel }));
expect(onRestart).toHaveBeenCalledTimes(1);
});
test('the cancel button calls onDismiss', () => {
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
render(<ServerDriftToast {...baseProps} onRestart={() => {}} onDismiss={onDismiss} />);
fireEvent.click(screen.getByRole('button', { name: baseProps.cancelLabel }));
expect(onDismiss).toHaveBeenCalledTimes(1);
diff --git a/packages/app/src/components/SettingsButton.dom.test.tsx b/packages/app/src/components/SettingsButton.dom.test.tsx
index aa93f2da8..1b5098ef8 100644
--- a/packages/app/src/components/SettingsButton.dom.test.tsx
+++ b/packages/app/src/components/SettingsButton.dom.test.tsx
@@ -1,18 +1,18 @@
-import { afterEach, beforeEach, describe, expect, jest, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
const preloadCalls: string[] = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
-mock.module('@/components/settings/SettingsDialogBodyLazy', () => ({
+vi.doMock('@/components/settings/SettingsDialogBodyLazy', () => ({
SettingsDialogBodyLazy: {
preload: () => {
preloadCalls.push('preload');
@@ -32,17 +32,17 @@ async function renderSettingsButton() {
function flushPendingPreloadTimers() {
act(() => {
- jest.runOnlyPendingTimers();
+ vi.runOnlyPendingTimers();
});
}
describe('SettingsButton runtime behavior', () => {
beforeEach(() => {
- jest.useFakeTimers();
+ vi.useFakeTimers();
});
afterEach(() => {
- jest.useRealTimers();
+ vi.useRealTimers();
cleanup();
preloadCalls.length = 0;
window.location.hash = '';
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
index b327c3b1e..3e7affb8d 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
@@ -11,7 +11,6 @@
* AddPropertyRow.dom.test.tsx avoids by stubbing the macro).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type {
BranchInfoResponse,
CheckoutResponse,
@@ -19,6 +18,7 @@ import type {
} from '@inkeep/open-knowledge-core';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge, OkShareReceivedPayload } from '@/lib/desktop-bridge-types';
// Radix Dialog (focus-trap) reaches for `NodeFilter` + `ResizeObserver`.
@@ -47,7 +47,7 @@ if (globalWithDomShims.ResizeObserver === undefined) {
// passthrough `t` template tag.
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => children,
useLingui: () => ({
@@ -65,28 +65,28 @@ mock.module('@lingui/react/macro', () => ({
}));
// Sonner is loaded by the SUT — stub to mute its real toaster.
-const toastError = mock(() => {});
-mock.module('sonner', () => ({
- toast: { error: toastError, info: mock(() => {}), success: mock(() => {}) },
+const toastError = vi.fn(() => {});
+vi.doMock('sonner', () => ({
+ toast: { error: toastError, info: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
// The worktree leg refreshes the window's cached worktree model on create
// success. Spy at the module seam (same pattern as NewWorktreeDialog.dom.test)
// so the production store never boots against the absent test bridge.
-const refreshWorktrees = mock(() => {});
-mock.module('@/lib/worktree-store', () => ({ refreshWorktrees }));
+const refreshWorktrees = vi.fn(() => {});
+vi.doMock('@/lib/worktree-store', () => ({ refreshWorktrees }));
const { createShareReceiveStore } = await import('@/lib/share/receive-store');
const { missDialogStore } = await import('@/lib/share/miss-dialog-store');
const { ShareBranchSwitchDialog } = await import('./ShareBranchSwitchDialog');
interface BridgeMock {
- fetchBranchInfo: ReturnType<typeof mock>;
- runCheckout: ReturnType<typeof mock>;
- fetchTargetStatus: ReturnType<typeof mock>;
- awaitBranchSwitched: ReturnType<typeof mock>;
- open: ReturnType<typeof mock>;
- checkout: ReturnType<typeof mock>;
+ fetchBranchInfo: ReturnType<typeof vi.fn>;
+ runCheckout: ReturnType<typeof vi.fn>;
+ fetchTargetStatus: ReturnType<typeof vi.fn>;
+ awaitBranchSwitched: ReturnType<typeof vi.fn>;
+ open: ReturnType<typeof vi.fn>;
+ checkout: ReturnType<typeof vi.fn>;
}
function makeBridge(overrides: Partial<BridgeMock> = {}): {
@@ -96,7 +96,7 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {
const calls: BridgeMock = {
fetchBranchInfo:
overrides.fetchBranchInfo ??
- mock(
+ vi.fn(
async (): Promise<BranchInfoResponse> => ({
ok: true,
currentBranch: 'main',
@@ -107,13 +107,14 @@ function makeBridge(overrides: Partial<BridgeMock> = {}): {
}),
),
runCheckout:
- overrides.runCheckout ?? mock(async (): Promise<CheckoutResponse> => ({ ok: true })),
- fetchTargetStatus: overrides.fetchTargetStatus ?? mock(async () => null),
- awaitBranchSwitched: overrides.awaitBranchSwitched ?? mock(async () => ({ ok: true as const })),
- open: overrides.open ?? mock(async () => undefined),
+ overrides.runCheckout ?? vi.fn(async (): Promise<CheckoutResponse> => ({ ok: true })),
+ fetchTargetStatus: overrides.fetchTargetStatus ?? vi.fn(async () => null),
+ awaitBranchSwitched:
+ overrides.awaitBranchSwitched ?? vi.fn(async () => ({ ok: true as const })),
+ open: overrides.open ?? vi.fn(async () => undefined),
checkout:
overrides.checkout ??
- mock(async () => ({ ok: true as const, path: '/repo/.ok/worktrees/branch', created: true })),
+ vi.fn(async () => ({ ok: true as const, path: '/repo/.ok/worktrees/branch', created: true })),
};
const bridge = {
project: {
@@ -150,11 +151,11 @@ function missWithFalseOriginHint(): BranchInfoResponse {
}
function pivotBridge(
- targetStatus: ReturnType<typeof mock>,
+ targetStatus: ReturnType<typeof vi.fn>,
extra: Partial<BridgeMock> = {},
): { bridge: OkDesktopBridge; calls: BridgeMock } {
return makeBridge({
- fetchBranchInfo: mock(async () => missWithFalseOriginHint()),
+ fetchBranchInfo: vi.fn(async () => missWithFalseOriginHint()),
fetchTargetStatus: targetStatus,
...extra,
});
@@ -219,7 +220,7 @@ describe('ShareBranchSwitchDialog — payload gating', () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
// Pending so we observe the loading state before info arrives.
- fetchBranchInfo: mock(() => new Promise<BranchInfoResponse>(() => {})),
+ fetchBranchInfo: vi.fn(() => new Promise<BranchInfoResponse>(() => {})),
});
const payload = projectBranchSwitchPayload();
const fakeBridgeForStore = {
@@ -255,7 +256,7 @@ describe('ShareBranchSwitchDialog — Cancel discipline (OQ2)', () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
// Hold the fetch open so we Cancel during loading state.
- fetchBranchInfo: mock(() => new Promise<BranchInfoResponse>(() => {})),
+ fetchBranchInfo: vi.fn(() => new Promise<BranchInfoResponse>(() => {})),
});
const payload = projectBranchSwitchPayload();
const fakeBridgeForStore = {
@@ -317,7 +318,7 @@ describe('ShareBranchSwitchDialog — Open-in-current dispatch', () => {
test('open-current open() reject surfaces a toast — no silent swallow', async () => {
const store = createShareReceiveStore();
const { bridge } = makeBridge({
- open: mock(async () => {
+ open: vi.fn(async () => {
throw new Error('ipc-timeout');
}),
});
@@ -358,7 +359,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
test('dirty conflicts disable Switch and describe the blocking file list', async () => {
const store = createShareReceiveStore();
const { bridge } = makeBridge({
- fetchBranchInfo: mock(
+ fetchBranchInfo: vi.fn(
async (): Promise<BranchInfoResponse> => ({
ok: true,
currentBranch: 'main',
@@ -445,7 +446,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
resolveCc1 = resolve;
});
const { bridge, calls } = makeBridge({
- awaitBranchSwitched: mock(() => cc1Promise),
+ awaitBranchSwitched: vi.fn(() => cc1Promise),
});
const payload = projectBranchSwitchPayload();
const fakeBridgeForStore = {
@@ -512,7 +513,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
const store = createShareReceiveStore();
// Checkout + CC1 ack succeed; only the final warm-focus open() rejects.
const { bridge, calls } = makeBridge({
- open: mock(async () => {
+ open: vi.fn(async () => {
throw new Error('window-manager-error');
}),
});
@@ -551,7 +552,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
test('Switch with runCheckout {ok:false, checkout-failed} toasts and does not navigate', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
- runCheckout: mock(async () => ({ ok: false as const, reason: 'checkout-failed' as const })),
+ runCheckout: vi.fn(async () => ({ ok: false as const, reason: 'checkout-failed' as const })),
});
const payload = projectBranchSwitchPayload();
const fakeBridgeForStore = {
@@ -583,7 +584,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
const store = createShareReceiveStore();
// Checkout succeeds; the CC1 recycle never acks within the window.
const { bridge, calls } = makeBridge({
- awaitBranchSwitched: mock(async () => ({ ok: false as const })),
+ awaitBranchSwitched: vi.fn(async () => ({ ok: false as const })),
});
const payload = projectBranchSwitchPayload();
const fakeBridgeForStore = {
@@ -639,7 +640,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
test('a false origin hint fetches target-status and renders the on-origin verdict', async () => {
const store = createShareReceiveStore();
- const targetStatus = mock(async () => ({ verdict: 'on-origin' as const }));
+ const targetStatus = vi.fn(async () => ({ verdict: 'on-origin' as const }));
const { bridge, calls } = pivotBridge(targetStatus);
const payload = installAndRender(bridge, store);
@@ -655,7 +656,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
test('on-origin "Switch and update branch" runs a fast-forward checkout and navigates to the doc', async () => {
const store = createShareReceiveStore();
- const { bridge, calls } = pivotBridge(mock(async () => ({ verdict: 'on-origin' as const })));
+ const { bridge, calls } = pivotBridge(vi.fn(async () => ({ verdict: 'on-origin' as const })));
const payload = installAndRender(bridge, store);
const btn = await screen.findByTestId('share-branch-switch-verdict-switch-update');
@@ -680,7 +681,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
test('renamed offer opens the NEW path with a fast-forward checkout', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = pivotBridge(
- mock(async () => ({ verdict: 'renamed' as const, renamedTo: 'guides/notes.md' })),
+ vi.fn(async () => ({ verdict: 'renamed' as const, renamedTo: 'guides/notes.md' })),
);
const payload = installAndRender(bridge, store);
@@ -710,7 +711,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
test('deleted verdict hands off to the miss dialog (no switch, dismisses this shell)', async () => {
missDialogStore.dismiss();
const store = createShareReceiveStore();
- const { bridge, calls } = pivotBridge(mock(async () => ({ verdict: 'deleted' as const })));
+ const { bridge, calls } = pivotBridge(vi.fn(async () => ({ verdict: 'deleted' as const })));
installAndRender(bridge, store);
// A gone-on-the-share-branch target has nothing to switch to — this shell
@@ -733,7 +734,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
missDialogStore.dismiss();
const store = createShareReceiveStore();
const { bridge, calls } = pivotBridge(
- mock(async () => ({ verdict: 'never-on-branch' as const })),
+ vi.fn(async () => ({ verdict: 'never-on-branch' as const })),
);
installAndRender(bridge, store);
@@ -749,13 +750,13 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
const store = createShareReceiveStore();
// The server refuses the fast-forward only when it is requested; a plain
// switch (no fastForward) succeeds.
- const runCheckout = mock(async (req: { fastForward?: boolean }) =>
+ const runCheckout = vi.fn(async (req: { fastForward?: boolean }) =>
req.fastForward
? { ok: false as const, reason: 'ff-diverged' as const }
: { ok: true as const },
);
const { bridge, calls } = pivotBridge(
- mock(async () => ({ verdict: 'on-origin' as const })),
+ vi.fn(async () => ({ verdict: 'on-origin' as const })),
{
runCheckout,
},
@@ -790,7 +791,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
test('unknown verdict falls back to today plain switch and does NOT re-probe', async () => {
const store = createShareReceiveStore();
- const targetStatus = mock(async () => ({ verdict: 'unknown' as const }));
+ const targetStatus = vi.fn(async () => ({ verdict: 'unknown' as const }));
const { bridge, calls } = pivotBridge(targetStatus);
const payload = installAndRender(bridge, store);
@@ -817,7 +818,7 @@ describe('ShareBranchSwitchDialog — verdict pivot (FR9)', () => {
test('a missing target with NO origin hint keeps today plain switch (no probe)', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
- fetchBranchInfo: mock(
+ fetchBranchInfo: vi.fn(
async (): Promise<BranchInfoResponse> =>
({
ok: true,
@@ -919,7 +920,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
test(`Open in worktree renders enabled in variant ${fixture.kind} (${fixture.label})`, async () => {
const store = createShareReceiveStore();
const { bridge } = makeBridge({
- fetchBranchInfo: mock(async () => branchInfoFor(fixture)),
+ fetchBranchInfo: vi.fn(async () => branchInfoFor(fixture)),
});
renderDialog(bridge, store);
await findEnabledWorktreeButton();
@@ -929,7 +930,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
test('variant D routes the dead end to the worktree action: new copy, switch disabled with the conflict list', async () => {
const store = createShareReceiveStore();
const { bridge } = makeBridge({
- fetchBranchInfo: mock(async () =>
+ fetchBranchInfo: vi.fn(async () =>
branchInfoFor({
shareTargetExists: false,
conflictFiles: ['docs/notes.md', 'package.json'],
@@ -962,7 +963,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
const store = createShareReceiveStore();
const existingPath = '/Users/alice/projects/open-knowledge/.ok/worktrees/feat-branch-x';
const { bridge, calls } = makeBridge({
- checkout: mock(async () => ({ ok: true as const, path: existingPath, created: false })),
+ checkout: vi.fn(async () => ({ ok: true as const, path: existingPath, created: false })),
});
renderDialog(bridge, store);
@@ -985,8 +986,8 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
const store = createShareReceiveStore();
const worktreePath = '/Users/alice/projects/open-knowledge/.ok/worktrees/feat-branch-x';
const { bridge, calls } = makeBridge({
- checkout: mock(async () => ({ ok: true as const, path: worktreePath, created: true })),
- open: mock(async () => {
+ checkout: vi.fn(async () => ({ ok: true as const, path: worktreePath, created: true })),
+ open: vi.fn(async () => {
throw new Error('window spawn failed');
}),
});
@@ -1043,7 +1044,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
const store = createShareReceiveStore();
const worktreePath = '/Users/alice/projects/open-knowledge/.ok/worktrees/feat-branch-x';
const { bridge, calls } = makeBridge({
- checkout: mock(async () => ({ ok: true as const, path: worktreePath, created: true })),
+ checkout: vi.fn(async () => ({ ok: true as const, path: worktreePath, created: true })),
});
const payload = projectBranchSwitchPayload();
const fakeBridgeForStore = {
@@ -1094,7 +1095,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
const store = createShareReceiveStore();
let resolveCheckout: (result: WorktreeCreateResult) => void = () => {};
const { bridge, calls } = makeBridge({
- checkout: mock(
+ checkout: vi.fn(
() =>
new Promise<WorktreeCreateResult>((resolve) => {
resolveCheckout = resolve;
@@ -1142,7 +1143,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
test('a fetch failure keeps the dialog open with the connection toast so the user can retry', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
- checkout: mock(async () => ({ ok: false as const, reason: 'fetch-failed' as const })),
+ checkout: vi.fn(async () => ({ ok: false as const, reason: 'fetch-failed' as const })),
});
renderDialog(bridge, store);
@@ -1170,7 +1171,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
test('a branch deleted upstream dismisses the dialog with the no-longer-exists toast', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
- checkout: mock(async () => ({ ok: false as const, reason: 'branch-not-found' as const })),
+ checkout: vi.fn(async () => ({ ok: false as const, reason: 'branch-not-found' as const })),
});
renderDialog(bridge, store);
@@ -1196,7 +1197,7 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
const store = createShareReceiveStore();
let resolveCheckout: (result: WorktreeCreateResult) => void = () => {};
const { bridge, calls } = makeBridge({
- checkout: mock(
+ checkout: vi.fn(
() =>
new Promise<WorktreeCreateResult>((resolve) => {
resolveCheckout = resolve;
diff --git a/packages/app/src/components/ShareButton.dom.test.tsx b/packages/app/src/components/ShareButton.dom.test.tsx
index 66e5c0fea..611c2b544 100644
--- a/packages/app/src/components/ShareButton.dom.test.tsx
+++ b/packages/app/src/components/ShareButton.dom.test.tsx
@@ -22,8 +22,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ShareTargetInput } from '@/lib/share/run-share-action';
// ShareButton mounts a Radix Tooltip + Popover (focus-scope) which reach for
@@ -51,7 +52,7 @@ if (globalWithDomShims.ResizeObserver === undefined) {
// Stub the sync-status hook so the button reads a remote without mounting the
// CC1 subscription / fetch path. `hasRemote: true` routes a click through the
// construct-url branch instead of `onClickWhenNoRemote`.
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatusDetailed: () => ({
status: { hasRemote: true },
fetchError: null,
@@ -61,7 +62,7 @@ mock.module('@/hooks/use-git-sync-status', () => ({
// The freshness warning row inside the popover reads the project-local config
// binding (for its "Enable auto-sync" gate). Stub the context so mounting the
// popover doesn't require a full <ConfigProvider>.
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({ projectLocalBinding: { patch: () => ({ ok: true }) } }),
}));
@@ -84,7 +85,7 @@ describe('ShareButton', () => {
configurable: true,
value: undefined,
});
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(
new Response(
JSON.stringify({
@@ -133,7 +134,7 @@ describe('ShareButton', () => {
// popover opens in success mode rather than the manual-copy fallback.
Object.defineProperty(globalThis.navigator, 'clipboard', {
configurable: true,
- value: { writeText: mock(() => Promise.resolve()) },
+ value: { writeText: vi.fn(() => Promise.resolve()) },
});
renderShareButton({ kind: 'doc', docName: 'docs/readme' });
@@ -172,7 +173,7 @@ describe('ShareButton', () => {
});
test('threads an absent freshness from the response into a warning row', async () => {
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(
new Response(
JSON.stringify({
@@ -201,7 +202,7 @@ describe('ShareButton', () => {
});
test('renders no warning row when the response reports current freshness', async () => {
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(
new Response(
JSON.stringify({
diff --git a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx
index 9680f228a..01f18ddd3 100644
--- a/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx
+++ b/packages/app/src/components/ShareFreshnessWarning.dom.test.tsx
@@ -5,8 +5,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
// The Sync now CTA fires a real fetch through `triggerSync`; stub it so the
@@ -14,13 +15,13 @@ import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
// driven by re-rendering with an updated status, not by this call resolving).
// A mutable impl lets one test drive a rejected trigger (offline / server down).
let triggerSyncImpl: () => Promise<void> = () => Promise.resolve();
-mock.module('@/lib/trigger-sync', () => ({ triggerSync: () => triggerSyncImpl() }));
+vi.doMock('@/lib/trigger-sync', () => ({ triggerSync: () => triggerSyncImpl() }));
// "Enable auto-sync" enables in place via the project-local config binding
// (through useSyncEnabledWriter). Capture the writes so a test can assert the
// off → on transition instead of a navigation.
let autoSyncWrites: boolean[] = [];
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalBinding: {
patch: (value: { autoSync?: { enabled?: boolean } }) => {
diff --git a/packages/app/src/components/ShareMetadataRows.dom.test.tsx b/packages/app/src/components/ShareMetadataRows.dom.test.tsx
index cc79c4a50..8d6b47c89 100644
--- a/packages/app/src/components/ShareMetadataRows.dom.test.tsx
+++ b/packages/app/src/components/ShareMetadataRows.dom.test.tsx
@@ -20,8 +20,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, screen, within } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { ShareMetadataRows } from '@/components/share-metadata-rows';
describe('ShareMetadataRows', () => {
diff --git a/packages/app/src/components/ShareReceiveDialog.test.ts b/packages/app/src/components/ShareReceiveDialog.test.ts
index db4a955b4..8d8f61987 100644
--- a/packages/app/src/components/ShareReceiveDialog.test.ts
+++ b/packages/app/src/components/ShareReceiveDialog.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('ShareReceiveDialog module', () => {
test('exports the named component', async () => {
diff --git a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx
index c0d2fcc61..df3010ded 100644
--- a/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareReceiveMissDialog.dom.test.tsx
@@ -7,10 +7,11 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { useSyncExternalStore } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
import { missDialogStore } from '@/lib/share/miss-dialog-store';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
@@ -19,7 +20,7 @@ import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
// useConfigContext; mock the binding so the guarded flow runs without a live
// config context, and capture writes. Mocked before the dynamic import below.
let autoSyncWrites: boolean[] = [];
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalBinding: {
patch: (value: { autoSync?: { enabled?: boolean } }) => {
@@ -39,7 +40,7 @@ function setSyncStatus(next: GitSyncStatus | null): void {
syncStatus = next;
for (const listener of syncStatusListeners) listener();
}
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatus: () =>
useSyncExternalStore(
(onStoreChange: () => void) => {
@@ -53,7 +54,7 @@ mock.module('@/hooks/use-git-sync-status', () => ({
let syncTriggers: string[] = [];
let triggerSyncImpl: () => Promise<void> = () => Promise.resolve();
-mock.module('@/lib/trigger-sync', () => ({
+vi.doMock('@/lib/trigger-sync', () => ({
triggerSync: (op: string) => {
syncTriggers.push(op);
return triggerSyncImpl();
diff --git a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx
index f893c8634..8b4778988 100644
--- a/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx
+++ b/packages/app/src/components/ShareReceiveMissPanel.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { ShareTargetStatusResponse } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
@@ -9,7 +9,7 @@ import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
// writes so the guarded off → on flow is assertable without a live binding.
// Mocked at the module boundary so the dynamic import below picks it up.
let autoSyncWrites: boolean[] = [];
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalBinding: {
patch: (value: { autoSync?: { enabled?: boolean } }) => {
@@ -23,7 +23,7 @@ mock.module('@/lib/config-provider', () => ({
// The changed-locally cell picks its CTA off the live sync status: Enable
// auto-sync when the toggle is off, Sync now when it is already on.
let syncStatus: GitSyncStatus | null = null;
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatus: () => syncStatus,
useGitSyncStatusDetailed: () => ({ status: syncStatus, fetchError: null }),
}));
diff --git a/packages/app/src/components/SharingModeField.dom.test.tsx b/packages/app/src/components/SharingModeField.dom.test.tsx
index ce4f3eea6..ae31bdd38 100644
--- a/packages/app/src/components/SharingModeField.dom.test.tsx
+++ b/packages/app/src/components/SharingModeField.dom.test.tsx
@@ -1,19 +1,21 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { type ReactNode, useState } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-import { type SharingMode, SharingModeField } from './SharingModeField';
+import type { SharingMode } from './SharingModeField';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, msg: renderLinguiTemplate }));
+vi.doMock('@lingui/core/macro', () => ({ ...actualLinguiMacro, msg: renderLinguiTemplate }));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
+const { SharingModeField } = await import('./SharingModeField');
+
/** Controlled wrapper so clicks actually move the selection. */
function Harness({
initial = 'shared',
diff --git a/packages/app/src/components/SidebarSearchBar.dom.test.tsx b/packages/app/src/components/SidebarSearchBar.dom.test.tsx
index 85bc9a6fa..96625571a 100644
--- a/packages/app/src/components/SidebarSearchBar.dom.test.tsx
+++ b/packages/app/src/components/SidebarSearchBar.dom.test.tsx
@@ -1,10 +1,10 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
diff --git a/packages/app/src/components/SidebarSearchBar.test.ts b/packages/app/src/components/SidebarSearchBar.test.ts
index 2660dd4bf..48bad67b1 100644
--- a/packages/app/src/components/SidebarSearchBar.test.ts
+++ b/packages/app/src/components/SidebarSearchBar.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { getParseHealth, resetParseHealth } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { onPillRenderError } from './SidebarSearchBar';
describe('SidebarSearchBar module', () => {
@@ -31,11 +31,11 @@ describe('onPillRenderError — Pattern C runtime observability emission', () =>
// a future refactor that swaps `incrementJsxRenderFailure` for an
// equivalent counter path without changing observable behavior.
- let warnSpy: ReturnType<typeof spyOn>;
+ let warnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
resetParseHealth();
- warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/SkillEditorActions.dom.test.tsx b/packages/app/src/components/SkillEditorActions.dom.test.tsx
index ebdfb2906..02722e71e 100644
--- a/packages/app/src/components/SkillEditorActions.dom.test.tsx
+++ b/packages/app/src/components/SkillEditorActions.dom.test.tsx
@@ -8,12 +8,12 @@
* pill reverts from the optimistic "Draft" back to server-truth "Installed".
*/
-import { describe, expect, mock, test } from 'bun:test';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { describe, expect, test, vi } from 'vitest';
import * as linguiShim from '../../tests/lingui-macro-shim';
-mock.module('@lingui/react/macro', () => linguiShim);
+vi.doMock('@lingui/react/macro', () => linguiShim);
const installedEntry = {
scope: 'project' as const,
@@ -24,13 +24,13 @@ const installedEntry = {
hosts: ['claude'],
};
-const uninstall = mock(async () => ({ ok: false as const, error: 'boom' }));
-const install = mock(async () => ({ ok: false as const, error: 'boom' }));
+const uninstall = vi.fn(async () => ({ ok: false as const, error: 'boom' }));
+const install = vi.fn(async () => ({ ok: false as const, error: 'boom' }));
-mock.module('@/hooks/use-skills', () => ({
+vi.doMock('@/hooks/use-skills', () => ({
useSkills: () => ({ status: 'ready', data: [installedEntry] }),
}));
-mock.module('@/components/skill-actions', () => ({
+vi.doMock('@/components/skill-actions', () => ({
useSkillActions: () => ({
installingName: null,
install,
diff --git a/packages/app/src/components/SkillFileViewer.dom.test.tsx b/packages/app/src/components/SkillFileViewer.dom.test.tsx
index 683cad682..4020c4fe2 100644
--- a/packages/app/src/components/SkillFileViewer.dom.test.tsx
+++ b/packages/app/src/components/SkillFileViewer.dom.test.tsx
@@ -18,17 +18,18 @@
*
* Runs under `bun run test:dom` (jsdom substrate).
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
// Mock the shared loader both render branches call. Capturing its args is the
// load-bearing proof the read routes through the scope-aware endpoint (not the
// content-dir asset path).
-const loadSkillFileTextMock = mock(
+const loadSkillFileTextMock = vi.fn(
async (_input: { scope: string; name: string; path: string }) =>
({ ok: true, text: '' }) as { ok: true; text: string } | { ok: false; status?: number },
);
-mock.module('@/lib/skills-api', () => ({
+vi.doMock('@/lib/skills-api', () => ({
loadSkillFileText: loadSkillFileTextMock,
}));
diff --git a/packages/app/src/components/SkillProperties.dom.test.tsx b/packages/app/src/components/SkillProperties.dom.test.tsx
index 016761c56..c8d589dfd 100644
--- a/packages/app/src/components/SkillProperties.dom.test.tsx
+++ b/packages/app/src/components/SkillProperties.dom.test.tsx
@@ -7,13 +7,13 @@
* provider — the same pattern `SourceEditor.dom.test.tsx` uses.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import * as linguiShim from '../../tests/lingui-macro-shim';
-mock.module('@lingui/react/macro', () => linguiShim);
+vi.doMock('@lingui/react/macro', () => linguiShim);
const { SkillProperties } = await import('./SkillProperties');
const { PropertyProvider } = await import('./PropertyContext');
@@ -51,7 +51,7 @@ describe('SkillProperties (CRDT)', () => {
test('committing a changed name fires onRename (a git-mv rename), not a patch', () => {
const { provider, ytext } = makeProvider(SOURCE);
- const onRename = mock((_next: string) => {});
+ const onRename = vi.fn((_next: string) => {});
renderPanel(<SkillProperties provider={provider} name="foo" onRename={onRename} />);
const nameInput = screen.getByTestId('skill-name-input');
fireEvent.change(nameInput, { target: { value: 'bar' } });
@@ -63,7 +63,7 @@ describe('SkillProperties (CRDT)', () => {
test('an unchanged name does not fire onRename', () => {
const { provider } = makeProvider(SOURCE);
- const onRename = mock((_next: string) => {});
+ const onRename = vi.fn((_next: string) => {});
renderPanel(<SkillProperties provider={provider} name="foo" onRename={onRename} />);
const nameInput = screen.getByTestId('skill-name-input');
fireEvent.blur(nameInput);
diff --git a/packages/app/src/components/SubscribeCard.dom.test.tsx b/packages/app/src/components/SubscribeCard.dom.test.tsx
index b2f3b2fbf..7b7261c44 100644
--- a/packages/app/src/components/SubscribeCard.dom.test.tsx
+++ b/packages/app/src/components/SubscribeCard.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
createSubscribeCardStore,
type SubscribeCardStorage,
@@ -10,17 +10,17 @@ import {
} from '@/lib/subscribe-card-store';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-const submitSubscribe = mock(
+const submitSubscribe = vi.fn(
async (_email: string) =>
({ ok: true }) as Awaited<ReturnType<typeof import('@/lib/subscribe').submitSubscribe>>,
);
-mock.module('@/lib/subscribe', () => ({ submitSubscribe }));
+vi.doMock('@/lib/subscribe', () => ({ submitSubscribe }));
function memoryStorage(): SubscribeCardStorage {
const map = new Map<string, string>();
@@ -47,8 +47,8 @@ async function renderCard(
const { SubscribeCard } = await import('./SubscribeCard');
const props = {
version: '1.4.0',
- onOpenReleaseNotes: mock(() => {}),
- onClose: mock(() => {}),
+ onOpenReleaseNotes: vi.fn(() => {}),
+ onClose: vi.fn(() => {}),
store: makeStore(),
autoDismissMs: 5,
...overrides,
@@ -87,14 +87,14 @@ describe('SubscribeCard (combined release-notes + subscribe)', () => {
});
test('clicking Release notes opens the release notes', async () => {
- const onOpenReleaseNotes = mock(() => {});
+ const onOpenReleaseNotes = vi.fn(() => {});
await renderCard({ onOpenReleaseNotes });
await userEvent.click(screen.getByRole('button', { name: 'Release notes' }));
expect(onOpenReleaseNotes).toHaveBeenCalledTimes(1);
});
test('dismissing closes the card and stops the prompt for good', async () => {
- const onClose = mock(() => {});
+ const onClose = vi.fn(() => {});
const store = makeStore();
await renderCard({ store, onClose });
await userEvent.click(screen.getByRole('button', { name: 'Close' }));
@@ -104,7 +104,7 @@ describe('SubscribeCard (combined release-notes + subscribe)', () => {
test('a confirmed subscribe marks subscribed, collapses socials, then auto-dismisses', async () => {
submitSubscribe.mockResolvedValue({ ok: true });
- const onClose = mock(() => {});
+ const onClose = vi.fn(() => {});
const store = makeStore();
await renderCard({ store, onClose, autoDismissMs: 5 });
diff --git a/packages/app/src/components/SubscribeForm.dom.test.tsx b/packages/app/src/components/SubscribeForm.dom.test.tsx
index 4be1892b4..d87221362 100644
--- a/packages/app/src/components/SubscribeForm.dom.test.tsx
+++ b/packages/app/src/components/SubscribeForm.dom.test.tsx
@@ -1,21 +1,21 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-const submitSubscribe = mock(
+const submitSubscribe = vi.fn(
async (_email: string) =>
({ ok: true }) as Awaited<ReturnType<typeof import('@/lib/subscribe').submitSubscribe>>,
);
-mock.module('@/lib/subscribe', () => ({ submitSubscribe }));
+vi.doMock('@/lib/subscribe', () => ({ submitSubscribe }));
async function renderForm(onSuccess?: () => void) {
const { SubscribeForm } = await import('./SubscribeForm');
@@ -39,7 +39,7 @@ describe('SubscribeForm', () => {
});
test('submits a valid email and shows the success view', async () => {
- const onSuccess = mock(() => {});
+ const onSuccess = vi.fn(() => {});
submitSubscribe.mockResolvedValue({ ok: true });
await renderForm(onSuccess);
diff --git a/packages/app/src/components/TemplateForm.dom.test.tsx b/packages/app/src/components/TemplateForm.dom.test.tsx
index 103b1d538..94b2a7b6f 100644
--- a/packages/app/src/components/TemplateForm.dom.test.tsx
+++ b/packages/app/src/components/TemplateForm.dom.test.tsx
@@ -2,9 +2,10 @@
* DOM tests for the template form — the filename-slug derivation helper and
* the Name -> derived-filename behavior. Runs under jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
import {
composeDocBody,
parseDocBody,
diff --git a/packages/app/src/components/TemplateProperties.dom.test.tsx b/packages/app/src/components/TemplateProperties.dom.test.tsx
index 524c32744..a526df8f1 100644
--- a/packages/app/src/components/TemplateProperties.dom.test.tsx
+++ b/packages/app/src/components/TemplateProperties.dom.test.tsx
@@ -6,13 +6,13 @@
* patch). Uses a real-Y.Doc fake provider — same pattern `SourceEditor` uses.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import * as linguiShim from '../../tests/lingui-macro-shim';
-mock.module('@lingui/react/macro', () => linguiShim);
+vi.doMock('@lingui/react/macro', () => linguiShim);
const { TemplateProperties } = await import('./TemplateProperties');
@@ -53,7 +53,7 @@ describe('TemplateProperties (CRDT)', () => {
test('committing a changed name fires onRename (a git-mv rename), not a patch', () => {
const { provider, ytext } = makeProvider(SOURCE);
- const onRename = mock((_next: string) => {});
+ const onRename = vi.fn((_next: string) => {});
render(
<TemplateProperties provider={provider} name="meeting" folder="notes" onRename={onRename} />,
);
diff --git a/packages/app/src/components/TemplateRow.dom.test.tsx b/packages/app/src/components/TemplateRow.dom.test.tsx
index c87295229..b09f55ab7 100644
--- a/packages/app/src/components/TemplateRow.dom.test.tsx
+++ b/packages/app/src/components/TemplateRow.dom.test.tsx
@@ -7,15 +7,15 @@
* (matching FileTree / ProjectSwitcher), so opening it must not lock the body.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { TemplateMenuEntry } from '@/hooks/use-folder-config';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
diff --git a/packages/app/src/components/TerminalCliMissingBanner.dom.test.tsx b/packages/app/src/components/TerminalCliMissingBanner.dom.test.tsx
index 34cfe3663..0a1951130 100644
--- a/packages/app/src/components/TerminalCliMissingBanner.dom.test.tsx
+++ b/packages/app/src/components/TerminalCliMissingBanner.dom.test.tsx
@@ -6,15 +6,15 @@
* which already tests its "Get Claude Code" action.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { TERMINAL_CLIS } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -26,7 +26,7 @@ mock.module('@lingui/react/macro', () => ({
const { TerminalCliMissingBanner } = await import('./TerminalCliMissingBanner');
function makeBridge() {
- const openExternal = mock(async (_url: string) => {});
+ const openExternal = vi.fn(async (_url: string) => {});
return {
bridge: { shell: { openExternal } } as unknown as OkDesktopBridge,
openExternal,
@@ -61,7 +61,7 @@ describe('TerminalCliMissingBanner', () => {
test('the dismiss control fires onDismiss without opening docs', async () => {
const { bridge, openExternal } = makeBridge();
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
render(<TerminalCliMissingBanner cli="codex" bridge={bridge} onDismiss={onDismiss} />);
await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
index b5eaf7d2c..9d0f1bbfc 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.dom.test.tsx
@@ -166,7 +166,7 @@ vi.doMock('@/lib/terminal-height-store', () => ({
const { TerminalDock } = await import('./TerminalDock');
const { TerminalSessionsHost } = await import('./TerminalSessionsHost');
-// After the mock.module block (a static import would load the real xterm).
+// After the vi.doMock block (a static import would load the real xterm).
const { STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel');
function makeBridge() {
diff --git a/packages/app/src/components/TerminalExitNotice.dom.test.tsx b/packages/app/src/components/TerminalExitNotice.dom.test.tsx
index c2574cc39..2f5256444 100644
--- a/packages/app/src/components/TerminalExitNotice.dom.test.tsx
+++ b/packages/app/src/components/TerminalExitNotice.dom.test.tsx
@@ -6,8 +6,8 @@
* or internal call patterns.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TerminalExitNotice } from './TerminalExitNotice';
afterEach(() => cleanup());
@@ -43,7 +43,7 @@ describe('TerminalExitNotice', () => {
});
test('the restart control is an accessible button that spawns a fresh session', () => {
- const onRestart = mock(() => {});
+ const onRestart = vi.fn(() => {});
render(<TerminalExitNotice info={{ exitCode: 0, signal: null }} onRestart={onRestart} />);
const restart = screen.getByRole('button', { name: 'Restart terminal' });
diff --git a/packages/app/src/components/TerminalGate.dom.test.tsx b/packages/app/src/components/TerminalGate.dom.test.tsx
index c4aa305a0..c4228b370 100644
--- a/packages/app/src/components/TerminalGate.dom.test.tsx
+++ b/packages/app/src/components/TerminalGate.dom.test.tsx
@@ -9,9 +9,10 @@
* writer; the mount is held until the binding syncs so an opted-out project
* never flashes the shell.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { act, cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
type ConsentState = { enabled: boolean | null; synced: boolean };
@@ -24,7 +25,7 @@ const toastErrors: string[] = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -33,18 +34,18 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: { error: (message: string) => toastErrors.push(message) },
}));
-mock.module('@/hooks/use-terminal-enabled', () => ({
+vi.doMock('@/hooks/use-terminal-enabled', () => ({
useTerminalConsentState: () => consentState,
useTerminalEnabledWriter: () => writerImpl,
}));
// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props, asserted structurally
let lastPanelProps: Record<string, any> | null = null;
-mock.module('./TerminalPanel', () => ({
+vi.doMock('./TerminalPanel', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
TerminalPanel: (props: any) => {
lastPanelProps = props;
@@ -87,9 +88,9 @@ describe('TerminalGate', () => {
});
test('forwards onClose, onTitleChange, launch, onPtyId, and adoptPtyId to the mounted terminal panel', async () => {
- const onClose = mock(() => {});
- const onTitleChange = mock((_title: string) => {});
- const onPtyId = mock((_ptyId: string | null) => {});
+ const onClose = vi.fn(() => {});
+ const onTitleChange = vi.fn((_title: string) => {});
+ const onPtyId = vi.fn((_ptyId: string | null) => {});
const launch = { prompt: 'work on docs/notes', nonce: 1 };
consentState = { enabled: null, synced: true };
render(
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index a55a917e5..972764612 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -10,8 +10,8 @@
* rendering + a real PTY are the browser/packaged rung.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type {
ClaudeReadiness,
OkDesktopBridge,
@@ -21,7 +21,7 @@ import type {
// --- xterm mocks (3rd-party system boundary) ---
class MockFitAddon {
- fit = mock(() => {});
+ fit = vi.fn(() => {});
constructor() {
lastFit = this;
}
@@ -52,8 +52,8 @@ class MockTerminal {
// Captures the synchronous render-debouncer flush the resize path invokes to
// repaint in the same frame (the WebGL canvas is cleared on resize; without
// the flush the glyphs land one frame late — a visible blank flash).
- renderFlush = mock(() => {});
- refresh = mock((_start: number, _end: number) => {});
+ renderFlush = vi.fn(() => {});
+ refresh = vi.fn((_start: number, _end: number) => {});
get _core() {
return {
coreMouseService: { activeEncoding: this.mouseEncoding },
@@ -91,8 +91,8 @@ class MockTerminal {
linkProvider: {
provideLinks(line: number, cb: (links: unknown[] | undefined) => void): void;
} | null = null;
- linkProviderDispose = mock(() => {});
- registerLinkProvider = mock(
+ linkProviderDispose = vi.fn(() => {});
+ registerLinkProvider = vi.fn(
(provider: {
provideLinks(line: number, cb: (links: unknown[] | undefined) => void): void;
}) => {
@@ -107,28 +107,28 @@ class MockTerminal {
// Builds the minimal WebGL-renderer DOM (.xterm-screen > canvas) so the
// panel's device-pixel canvas observer — the second-clear repaint hook —
// has a canvas to find, matching real xterm's structure.
- open = mock((container: HTMLElement) => {
+ open = vi.fn((container: HTMLElement) => {
const screen = document.createElement('div');
screen.className = 'xterm-screen';
screen.appendChild(document.createElement('canvas'));
container.appendChild(screen);
});
- focus = mock(() => {});
- dispose = mock(() => {});
- write = mock((_data: string, cb?: () => void) => {
+ focus = vi.fn(() => {});
+ dispose = vi.fn(() => {});
+ write = vi.fn((_data: string, cb?: () => void) => {
cb?.();
});
- loadAddon = mock((addon: unknown) => {
+ loadAddon = vi.fn((addon: unknown) => {
if (webglThrows && addon instanceof MockWebglAddon) throw new Error('no webgl2 context');
});
- onData = mock((cb: (d: string) => void) => {
+ onData = vi.fn((cb: (d: string) => void) => {
this.onDataCb = cb;
return { dispose() {} };
});
// Captures the OSC 0/2 title listener; firing onTitleChangeCb mimics the PTY
// program setting the window title. Returns a disposable like real xterm.
onTitleChangeCb: ((title: string) => void) | null = null;
- onTitleChange = mock((cb: (title: string) => void) => {
+ onTitleChange = vi.fn((cb: (title: string) => void) => {
this.onTitleChangeCb = cb;
return { dispose() {} };
});
@@ -137,13 +137,13 @@ class MockTerminal {
// default so it reaches the PTY instead of escaping focus) and Shift+Enter
// (send LF instead of xterm's default CR so the CLI inserts a newline). Every
// other key returns true, so xterm processes it and Escape reaches the PTY.
- attachCustomKeyEventHandler = mock((h: (e: KeyboardEvent) => boolean) => {
+ attachCustomKeyEventHandler = vi.fn((h: (e: KeyboardEvent) => boolean) => {
this.keyHandler = h;
});
// Production attaches a wheel handler that, in mouse-tracking mode, replaces
// xterm's flooding one-report-per-event behavior with an accumulated,
// frequency-independent stream (see terminal-wheel.ts).
- attachCustomWheelEventHandler = mock((h: (e: WheelEvent) => boolean) => {
+ attachCustomWheelEventHandler = vi.fn((h: (e: WheelEvent) => boolean) => {
this.wheelHandler = h;
});
constructor(options: Record<string, unknown>) {
@@ -169,11 +169,11 @@ let allROs: MockResizeObserver[] = [];
class MockResizeObserver {
cb: () => void;
observed: Array<{ el: Element; opts?: ResizeObserverOptions }> = [];
- observe = mock((el: Element, opts?: ResizeObserverOptions) => {
+ observe = vi.fn((el: Element, opts?: ResizeObserverOptions) => {
this.observed.push({ el, opts });
});
- unobserve = mock(() => {});
- disconnect = mock(() => {});
+ unobserve = vi.fn(() => {});
+ disconnect = vi.fn(() => {});
constructor(cb: () => void) {
this.cb = cb;
roCallback = cb;
@@ -181,13 +181,13 @@ class MockResizeObserver {
}
}
-mock.module('@xterm/xterm', () => ({ Terminal: MockTerminal }));
-mock.module('@xterm/addon-fit', () => ({ FitAddon: MockFitAddon }));
-mock.module('@xterm/addon-webgl', () => ({ WebglAddon: MockWebglAddon }));
-mock.module('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon }));
-mock.module('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
-mock.module('@xterm/xterm/css/xterm.css', () => ({}));
-mock.module('next-themes', () => ({
+vi.doMock('@xterm/xterm', () => ({ Terminal: MockTerminal }));
+vi.doMock('@xterm/addon-fit', () => ({ FitAddon: MockFitAddon }));
+vi.doMock('@xterm/addon-webgl', () => ({ WebglAddon: MockWebglAddon }));
+vi.doMock('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon }));
+vi.doMock('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
+vi.doMock('@xterm/xterm/css/xterm.css', () => ({}));
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: mockResolvedTheme }),
}));
@@ -209,41 +209,41 @@ function makeBridge(
) {
const dataSubs: Array<(m: OkPtyData) => void> = [];
const exitSubs: Array<(m: OkPtyExit) => void> = [];
- const unsubData = mock(() => {});
- const unsubExit = mock(() => {});
- const openExternal = mock(async (_url: string) => {});
- const openAsset = mock(
+ const unsubData = vi.fn(() => {});
+ const unsubExit = vi.fn(() => {});
+ const openExternal = vi.fn(async (_url: string) => {});
+ const openAsset = vi.fn(
async (_relPath: string): Promise<{ ok: true } | { ok: false; reason: string }> => ({
ok: true,
}),
);
- const revealAsset = mock(async (_relPath: string) => ({ ok: true }) as { ok: true });
- const revealExternal = mock(
+ const revealAsset = vi.fn(async (_relPath: string) => ({ ok: true }) as { ok: true });
+ const revealExternal = vi.fn(
async (_absPath: string) =>
({ ok: true, outcome: 'revealed' }) as { ok: true; outcome: 'revealed' },
);
- const checkTargetExists = mock(
+ const checkTargetExists = vi.fn(
async (_req: { projectPath: string; kind: 'doc' | 'folder'; path: string }) =>
'exists' as const,
);
- const rewireClaudeMcp = mock(async () => preflight);
+ const rewireClaudeMcp = vi.fn(async () => preflight);
const terminal = {
- create: mock(async () => createResult),
- adopt: mock(adopt),
- input: mock((_id: string, _d: string) => {}),
- resize: mock((_id: string, _c: number, _r: number) => {}),
- kill: mock(async (_id: string) => {}),
- drain: mock((_id: string, _bytes: number) => {}),
- onData: mock((cb: (m: OkPtyData) => void) => {
+ create: vi.fn(async () => createResult),
+ adopt: vi.fn(adopt),
+ input: vi.fn((_id: string, _d: string) => {}),
+ resize: vi.fn((_id: string, _c: number, _r: number) => {}),
+ kill: vi.fn(async (_id: string) => {}),
+ drain: vi.fn((_id: string, _bytes: number) => {}),
+ onData: vi.fn((cb: (m: OkPtyData) => void) => {
dataSubs.push(cb);
return unsubData;
}),
- onExit: mock((cb: (m: OkPtyExit) => void) => {
+ onExit: vi.fn((cb: (m: OkPtyExit) => void) => {
exitSubs.push(cb);
return unsubExit;
}),
- claudePreflight: mock(async () => preflight),
- cliPreflight: mock(async () => ({ onPath: 'present' as const })),
+ claudePreflight: vi.fn(async () => preflight),
+ cliPreflight: vi.fn(async () => ({ onPath: 'present' as const })),
rewireClaudeMcp,
};
return {
@@ -317,7 +317,7 @@ describe('TerminalPanel', () => {
test('screen-reader mode follows the assistive-tech signal: off when inactive, live-toggled on attach', async () => {
const { bridge, terminal } = makeBridge({ ok: true, ptyId: 'pty-1' });
const a11ySubs: Array<(active: boolean) => void> = [];
- const a11yUnsub = mock(() => {});
+ const a11yUnsub = vi.fn(() => {});
const withA11y = {
...(bridge as unknown as Record<string, unknown>),
accessibility: {
@@ -460,7 +460,7 @@ describe('TerminalPanel', () => {
test('forwards xterm OSC 0/2 title changes to onTitleChange', async () => {
const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
- const onTitleChange = mock((_title: string) => {});
+ const onTitleChange = vi.fn((_title: string) => {});
render(<TerminalPanel bridge={bridge} onTitleChange={onTitleChange} />);
// xterm registers the title listener synchronously at mount (before the PTY
@@ -477,7 +477,7 @@ describe('TerminalPanel', () => {
test('disposes the title listener on unmount', async () => {
const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
- const onTitleChange = mock((_title: string) => {});
+ const onTitleChange = vi.fn((_title: string) => {});
const { unmount } = render(<TerminalPanel bridge={bridge} onTitleChange={onTitleChange} />);
await waitFor(() => expect(lastTerm?.onTitleChangeCb).toBeTruthy());
@@ -721,7 +721,7 @@ describe('TerminalPanel', () => {
// Shift+Tab keydown: browser default cancelled, but still handed to xterm
// (returns true) so the reverse-tab sequence reaches the PTY / Claude TUI.
- const shiftTabPreventDefault = mock(() => {});
+ const shiftTabPreventDefault = vi.fn(() => {});
const shiftTab = {
type: 'keydown',
key: 'Tab',
@@ -732,7 +732,7 @@ describe('TerminalPanel', () => {
expect(shiftTabPreventDefault).toHaveBeenCalledTimes(1);
// Plain Tab is left to xterm, which already cancels that one itself.
- const plainTabPreventDefault = mock(() => {});
+ const plainTabPreventDefault = vi.fn(() => {});
const plainTab = {
type: 'keydown',
key: 'Tab',
@@ -744,7 +744,7 @@ describe('TerminalPanel', () => {
// Escape is never intercepted (no preventDefault) so terminal apps (vim, the
// `claude` TUI) receive it — and it reaches the PTY via the data callback.
- const escapePreventDefault = mock(() => {});
+ const escapePreventDefault = vi.fn(() => {});
const escapeKey = {
type: 'keydown',
key: 'Escape',
@@ -767,7 +767,7 @@ describe('TerminalPanel', () => {
// Shift+Enter: send LF ourselves and return false so xterm does NOT also
// emit its default CR — the CLI inserts a newline rather than submitting.
- const shiftEnterPreventDefault = mock(() => {});
+ const shiftEnterPreventDefault = vi.fn(() => {});
const shiftEnter = {
type: 'keydown',
key: 'Enter',
@@ -779,7 +779,7 @@ describe('TerminalPanel', () => {
expect(terminal.input).toHaveBeenCalledWith('pty-1', '\n');
// Plain Enter is left to xterm, which sends its default CR (submit).
- const plainEnterPreventDefault = mock(() => {});
+ const plainEnterPreventDefault = vi.fn(() => {});
const plainEnter = {
type: 'keydown',
key: 'Enter',
@@ -1009,7 +1009,7 @@ describe('TerminalPanel', () => {
});
test('renders a refusal notice (not a blank canvas) when main refuses with not-consented', async () => {
- const onClose = mock(() => {});
+ const onClose = vi.fn(() => {});
const { bridge, terminal } = makeBridge({ ok: false, reason: 'not-consented' });
render(<TerminalPanel bridge={bridge} onClose={onClose} />);
@@ -1044,15 +1044,15 @@ describe('TerminalPanel', () => {
const createPromise = new Promise<CreateResult>((res) => {
resolveCreate = res;
});
- const kill = mock(async (_id: string) => {});
+ const kill = vi.fn(async (_id: string) => {});
const terminal = {
- create: mock(() => createPromise),
- input: mock(() => {}),
- resize: mock(() => {}),
+ create: vi.fn(() => createPromise),
+ input: vi.fn(() => {}),
+ resize: vi.fn(() => {}),
kill,
- drain: mock(() => {}),
- onData: mock(() => mock(() => {})),
- onExit: mock(() => mock(() => {})),
+ drain: vi.fn(() => {}),
+ onData: vi.fn(() => vi.fn(() => {})),
+ onExit: vi.fn(() => vi.fn(() => {})),
};
const bridge = { terminal, config: { e2eSmoke: false } } as unknown as OkDesktopBridge;
@@ -1133,26 +1133,26 @@ describe('TerminalPanel', () => {
resolveCreate = res;
});
const terminal = {
- create: mock(async () => {
+ create: vi.fn(async () => {
createCalls += 1;
if (createCalls === 1) throw new Error('fork EMFILE');
// After restart, succeed so we can prove the restart path works.
await createGate;
return { ok: true, ptyId: 'pty-restarted' } as const;
}),
- input: mock(() => {}),
- resize: mock(() => {}),
- kill: mock(async () => {}),
- drain: mock(() => {}),
- onData: mock(() => mock(() => {})),
- onExit: mock(() => mock(() => {})),
- claudePreflight: mock(async () => WIRED),
- cliPreflight: mock(async () => ({ onPath: 'present' as const })),
- rewireClaudeMcp: mock(async () => WIRED),
+ input: vi.fn(() => {}),
+ resize: vi.fn(() => {}),
+ kill: vi.fn(async () => {}),
+ drain: vi.fn(() => {}),
+ onData: vi.fn(() => vi.fn(() => {})),
+ onExit: vi.fn(() => vi.fn(() => {})),
+ claudePreflight: vi.fn(async () => WIRED),
+ cliPreflight: vi.fn(async () => ({ onPath: 'present' as const })),
+ rewireClaudeMcp: vi.fn(async () => WIRED),
};
const bridge = {
terminal,
- shell: { openExternal: mock(async () => {}) },
+ shell: { openExternal: vi.fn(async () => {}) },
config: { e2eSmoke: false },
} as unknown as OkDesktopBridge;
@@ -1259,28 +1259,28 @@ describe('TerminalPanel', () => {
// session's PTY and leave the sibling's PTY untouched.
const exitSubs: Array<(m: OkPtyExit) => void> = [];
let created = 0;
- const create = mock(async () => {
+ const create = vi.fn(async () => {
created += 1;
return { ok: true as const, ptyId: `pty-${created}` };
});
- const kill = mock(async (_id: string) => {});
+ const kill = vi.fn(async (_id: string) => {});
const terminal = {
create,
- input: mock(() => {}),
- resize: mock(() => {}),
+ input: vi.fn(() => {}),
+ resize: vi.fn(() => {}),
kill,
- drain: mock(() => {}),
- onData: mock(() => mock(() => {})),
- onExit: mock((cb: (m: OkPtyExit) => void) => {
+ drain: vi.fn(() => {}),
+ onData: vi.fn(() => vi.fn(() => {})),
+ onExit: vi.fn((cb: (m: OkPtyExit) => void) => {
exitSubs.push(cb);
- return mock(() => {});
+ return vi.fn(() => {});
}),
- claudePreflight: mock(async () => WIRED),
- rewireClaudeMcp: mock(async () => WIRED),
+ claudePreflight: vi.fn(async () => WIRED),
+ rewireClaudeMcp: vi.fn(async () => WIRED),
};
const bridge = {
terminal,
- shell: { openExternal: mock(async () => {}) },
+ shell: { openExternal: vi.fn(async () => {}) },
config: { e2eSmoke: false },
} as unknown as OkDesktopBridge;
const pushExit = (m: OkPtyExit) => {
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index b55f2f2cb..551c9836d 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -14,10 +14,10 @@
* boundary, mirroring `TerminalPanel.dom.test.tsx`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { buildStartupInjectionBytes, type TerminalCli } from '@inkeep/open-knowledge-core';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactElement } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import type {
ClaudeReadiness,
@@ -27,7 +27,7 @@ import type {
} from '@/lib/desktop-bridge-types';
class MockFitAddon {
- fit = mock(() => {});
+ fit = vi.fn(() => {});
}
class MockWebglAddon {}
class MockWebLinksAddon {}
@@ -40,30 +40,30 @@ class MockTerminal {
onDataCb: ((d: string) => void) | null = null;
keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
options: Record<string, unknown>;
- open = mock(() => {});
- focus = mock(() => {});
- dispose = mock(() => {});
- write = mock((_data: string, cb?: () => void) => {
+ open = vi.fn(() => {});
+ focus = vi.fn(() => {});
+ dispose = vi.fn(() => {});
+ write = vi.fn((_data: string, cb?: () => void) => {
cb?.();
});
- loadAddon = mock(() => {});
- onData = mock((cb: (d: string) => void) => {
+ loadAddon = vi.fn(() => {});
+ onData = vi.fn((cb: (d: string) => void) => {
this.onDataCb = cb;
return { dispose() {} };
});
// The panel subscribes to OSC 0/2 title changes at mount; this stub only needs
// to return a disposable (the launch tests don't exercise title forwarding).
- onTitleChange = mock((_cb: (title: string) => void) => ({ dispose() {} }));
- attachCustomKeyEventHandler = mock((h: (e: KeyboardEvent) => boolean) => {
+ onTitleChange = vi.fn((_cb: (title: string) => void) => ({ dispose() {} }));
+ attachCustomKeyEventHandler = vi.fn((h: (e: KeyboardEvent) => boolean) => {
this.keyHandler = h;
});
// Production attaches a wheel handler at mount; these launch tests never fire
// wheel events, so the no-op presence is all that's needed to avoid throwing.
- attachCustomWheelEventHandler = mock(() => {});
+ attachCustomWheelEventHandler = vi.fn(() => {});
// The panel registers a file-path link provider at mount; these launch tests
// never hover a link, so a disposable-returning stub (plus an empty buffer for
// the provider's readLine) is all that's needed to avoid throwing on mount.
- registerLinkProvider = mock(() => ({ dispose() {} }));
+ registerLinkProvider = vi.fn(() => ({ dispose() {} }));
get buffer() {
return { active: { getLine: () => ({ translateToString: () => '' }) } };
}
@@ -73,17 +73,17 @@ class MockTerminal {
}
class MockResizeObserver {
- observe = mock(() => {});
- unobserve = mock(() => {});
- disconnect = mock(() => {});
+ observe = vi.fn(() => {});
+ unobserve = vi.fn(() => {});
+ disconnect = vi.fn(() => {});
}
-mock.module('@xterm/xterm', () => ({ Terminal: MockTerminal }));
-mock.module('@xterm/addon-fit', () => ({ FitAddon: MockFitAddon }));
-mock.module('@xterm/addon-webgl', () => ({ WebglAddon: MockWebglAddon }));
-mock.module('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon }));
-mock.module('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
-mock.module('@xterm/xterm/css/xterm.css', () => ({}));
+vi.doMock('@xterm/xterm', () => ({ Terminal: MockTerminal }));
+vi.doMock('@xterm/addon-fit', () => ({ FitAddon: MockFitAddon }));
+vi.doMock('@xterm/addon-webgl', () => ({ WebglAddon: MockWebglAddon }));
+vi.doMock('@xterm/addon-web-links', () => ({ WebLinksAddon: MockWebLinksAddon }));
+vi.doMock('@xterm/addon-unicode11', () => ({ Unicode11Addon: MockUnicode11Addon }));
+vi.doMock('@xterm/xterm/css/xterm.css', () => ({}));
/** Fully ready: claude on PATH, OK tools wired, AND the project's own
* `open-knowledge` entry verified as OK's canonical server (mcpPreApprovable),
@@ -104,33 +104,33 @@ const CODEX_OK_CONFIGURED: CliReadiness = { onPath: 'present', okServerConfigure
function makeBridge(preflight: ClaudeReadiness = WIRED, cliReadiness: CliReadiness = ON_PATH) {
const dataSubs: Array<(m: OkPtyData) => void> = [];
const terminal = {
- create: mock(async (_opts: { cols: number; rows: number; launchCommand?: string }) => ({
+ create: vi.fn(async (_opts: { cols: number; rows: number; launchCommand?: string }) => ({
ok: true as const,
ptyId: 'pty-1',
})),
- input: mock((_id: string, _d: string) => {}),
- resize: mock(() => {}),
- kill: mock(async () => {}),
- drain: mock(() => {}),
- adopt: mock(
+ input: vi.fn((_id: string, _d: string) => {}),
+ resize: vi.fn(() => {}),
+ kill: vi.fn(async () => {}),
+ drain: vi.fn(() => {}),
+ adopt: vi.fn(
async (): Promise<{ ok: true; replay: string } | { ok: false; reason: string }> => ({
ok: true,
replay: '',
}),
),
- onData: mock((cb: (m: OkPtyData) => void) => {
+ onData: vi.fn((cb: (m: OkPtyData) => void) => {
dataSubs.push(cb);
- return mock(() => {});
+ return vi.fn(() => {});
}),
- onExit: mock(() => mock(() => {})),
- claudePreflight: mock(async () => preflight),
- cliPreflight: mock(async (_cli: TerminalCli) => cliReadiness),
- rewireClaudeMcp: mock(async () => preflight),
+ onExit: vi.fn(() => vi.fn(() => {})),
+ claudePreflight: vi.fn(async () => preflight),
+ cliPreflight: vi.fn(async (_cli: TerminalCli) => cliReadiness),
+ rewireClaudeMcp: vi.fn(async () => preflight),
};
return {
bridge: {
terminal,
- shell: { openExternal: mock(async () => {}) },
+ shell: { openExternal: vi.fn(async () => {}) },
config: { e2eSmoke: false },
} as unknown as OkDesktopBridge,
terminal,
@@ -144,7 +144,7 @@ const { TerminalPanel, STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel')
/** The `launchCommand` baked into the (single) `create` call, or undefined when
* none was passed (plain shell). The launch's only sanctioned transport. */
-function bakedLaunch(createMock: ReturnType<typeof mock>): string | undefined {
+function bakedLaunch(createMock: ReturnType<typeof vi.fn>): string | undefined {
const calls = createMock.mock.calls;
const last = calls.at(-1)?.[0] as { launchCommand?: string } | undefined;
return last?.launchCommand;
@@ -152,7 +152,7 @@ function bakedLaunch(createMock: ReturnType<typeof mock>): string | undefined {
/** Any `terminal.input` write that looks like a baked launch command — must stay
* empty: the launch rides `create`, never the line editor (the whole fix). */
-function launchInputWrites(inputMock: ReturnType<typeof mock>): string[] {
+function launchInputWrites(inputMock: ReturnType<typeof vi.fn>): string[] {
return inputMock.mock.calls
.map((c) => c[1] as string)
.filter((d) => typeof d === 'string' && /^(claude|codex|cursor-agent|opencode) /.test(d));
@@ -367,7 +367,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
// the bake so the terminal can't show a raw `command not found`, and surface
// the readiness banner so the user gets feedback rather than a silent no-op.
const { bridge, terminal } = makeBridge();
- terminal.claudePreflight = mock(async () => {
+ terminal.claudePreflight = vi.fn(async () => {
throw new Error('ipc boom');
});
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'claude', nonce: 1 }} />);
@@ -492,7 +492,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
test('cursor probe UNKNOWN then PRESENT on re-probe: bakes the preserved prompt', async () => {
let calls = 0;
const { bridge, terminal } = makeBridge(WIRED);
- terminal.cliPreflight = mock(async () => {
+ terminal.cliPreflight = vi.fn(async () => {
calls += 1;
return calls === 1 ? { onPath: 'unknown' as const } : { onPath: 'present' as const };
});
@@ -505,7 +505,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
test('cliPreflight IPC rejection spawns plain + surfaces the banner (no raw command-not-found)', async () => {
const { bridge, terminal } = makeBridge(WIRED);
- terminal.cliPreflight = mock(async () => {
+ terminal.cliPreflight = vi.fn(async () => {
throw new Error('ipc channel closed');
});
render(<TerminalPanel bridge={bridge} launch={{ prompt: 'hi', cli: 'codex', nonce: 1 }} />);
@@ -545,7 +545,7 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
// not be silently re-issued on a reconnect attempt. So create spawns a plain
// shell (no launchCommand) and nothing is baked.
const { bridge, terminal } = makeBridge(WIRED);
- terminal.adopt = mock(
+ terminal.adopt = vi.fn(
async (): Promise<{ ok: true; replay: string } | { ok: false; reason: string }> => ({
ok: false,
reason: 'unknown-session',
diff --git a/packages/app/src/components/TextViewer.error-message.dom.test.tsx b/packages/app/src/components/TextViewer.error-message.dom.test.tsx
index 9f24e8a39..6ecf2f276 100644
--- a/packages/app/src/components/TextViewer.error-message.dom.test.tsx
+++ b/packages/app/src/components/TextViewer.error-message.dom.test.tsx
@@ -11,8 +11,9 @@
*
* Runs under `bun run test:dom` (jsdom substrate).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
const { TextViewer } = await import('./TextViewer.tsx');
diff --git a/packages/app/src/components/TimelinePanel.test.ts b/packages/app/src/components/TimelinePanel.test.ts
index 238598a9f..646bd3ba5 100644
--- a/packages/app/src/components/TimelinePanel.test.ts
+++ b/packages/app/src/components/TimelinePanel.test.ts
@@ -5,8 +5,9 @@
* test focuses on the summary-flattening helper so refactors survive without
* a browser.
*/
-import { describe, expect, test } from 'bun:test';
+
import type { TimelineEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { allSummariesFor } from './TimelinePanel.tsx';
function baseEntry(overrides: Partial<TimelineEntry>): TimelineEntry {
diff --git a/packages/app/src/components/TrashFailureModal.test.ts b/packages/app/src/components/TrashFailureModal.test.ts
index f6d61a2d9..8df0c3194 100644
--- a/packages/app/src/components/TrashFailureModal.test.ts
+++ b/packages/app/src/components/TrashFailureModal.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
coerceTrashFailureReason,
diff --git a/packages/app/src/components/UpdateNotices.dom.test.tsx b/packages/app/src/components/UpdateNotices.dom.test.tsx
index fd02977e6..dada31e3e 100644
--- a/packages/app/src/components/UpdateNotices.dom.test.tsx
+++ b/packages/app/src/components/UpdateNotices.dom.test.tsx
@@ -11,8 +11,9 @@
* `tests/lingui-macro-preload.ts`, so `t`Dismiss notice`` is the X's
* accessible name. Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { NoticeCard } from './UpdateNotices';
import { TOAST_A_PROGRESS_BODY, type UpdateNotice } from './UpdateNotices.shared';
@@ -30,7 +31,7 @@ describe('NoticeCard — dismiss X visibility', () => {
priority: 2,
action: { label: 'Relaunch', onClick: () => {} },
};
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
render(<NoticeCard notice={notice} onDismiss={onDismiss} />);
const x = screen.getByRole('button', { name: DISMISS_NAME });
diff --git a/packages/app/src/components/UpdateNotices.test.ts b/packages/app/src/components/UpdateNotices.test.ts
index b76bf3532..5d0913a7f 100644
--- a/packages/app/src/components/UpdateNotices.test.ts
+++ b/packages/app/src/components/UpdateNotices.test.ts
@@ -12,7 +12,7 @@
* Playwright's job.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import {
addSchemaIncompatibilityNotice,
@@ -45,21 +45,21 @@ type WhatsNewDismissedCb = (info: { version: string }) => void;
type StuckHintCb = (info: { downloadUrl: string }) => void;
interface FakeBridge {
- onUpdateDownloaded: ReturnType<typeof mock>;
- onUpdateRelaunching: ReturnType<typeof mock>;
- onUpdateRelaunchFailed: ReturnType<typeof mock>;
- onWhatsNew: ReturnType<typeof mock>;
- onWhatsNewDismissed: ReturnType<typeof mock>;
- onUpdateStuckHint: ReturnType<typeof mock>;
+ onUpdateDownloaded: ReturnType<typeof vi.fn>;
+ onUpdateRelaunching: ReturnType<typeof vi.fn>;
+ onUpdateRelaunchFailed: ReturnType<typeof vi.fn>;
+ onWhatsNew: ReturnType<typeof vi.fn>;
+ onWhatsNewDismissed: ReturnType<typeof vi.fn>;
+ onUpdateStuckHint: ReturnType<typeof vi.fn>;
update: {
- relaunchNow: ReturnType<typeof mock>;
- dismissWhatsNew: ReturnType<typeof mock>;
+ relaunchNow: ReturnType<typeof vi.fn>;
+ dismissWhatsNew: ReturnType<typeof vi.fn>;
};
state: {
- query: ReturnType<typeof mock>;
- resetIncompatible: ReturnType<typeof mock>;
+ query: ReturnType<typeof vi.fn>;
+ resetIncompatible: ReturnType<typeof vi.fn>;
};
- shell: { openExternal: ReturnType<typeof mock> };
+ shell: { openExternal: ReturnType<typeof vi.fn> };
/** Test-side handles — set by the `on*` mocks so tests can drive dispatches. */
_downloaded?: UpdateDownloadedCb;
_relaunching?: RelaunchingCb;
@@ -67,59 +67,59 @@ interface FakeBridge {
_whatsNew?: WhatsNewCb;
_whatsNewDismissed?: WhatsNewDismissedCb;
_stuckHint?: StuckHintCb;
- _downloadedUnsub: ReturnType<typeof mock>;
- _relaunchingUnsub: ReturnType<typeof mock>;
- _relaunchFailedUnsub: ReturnType<typeof mock>;
- _whatsNewUnsub: ReturnType<typeof mock>;
- _whatsNewDismissedUnsub: ReturnType<typeof mock>;
- _stuckHintUnsub: ReturnType<typeof mock>;
+ _downloadedUnsub: ReturnType<typeof vi.fn>;
+ _relaunchingUnsub: ReturnType<typeof vi.fn>;
+ _relaunchFailedUnsub: ReturnType<typeof vi.fn>;
+ _whatsNewUnsub: ReturnType<typeof vi.fn>;
+ _whatsNewDismissedUnsub: ReturnType<typeof vi.fn>;
+ _stuckHintUnsub: ReturnType<typeof vi.fn>;
}
function makeFakeBridge(): FakeBridge {
const b: FakeBridge = {
- _downloadedUnsub: mock(() => {}),
- _relaunchingUnsub: mock(() => {}),
- _relaunchFailedUnsub: mock(() => {}),
- _whatsNewUnsub: mock(() => {}),
- _whatsNewDismissedUnsub: mock(() => {}),
- _stuckHintUnsub: mock(() => {}),
- onUpdateDownloaded: mock(() => {}),
- onUpdateRelaunching: mock(() => {}),
- onUpdateRelaunchFailed: mock(() => {}),
- onWhatsNew: mock(() => {}),
- onWhatsNewDismissed: mock(() => {}),
- onUpdateStuckHint: mock(() => {}),
+ _downloadedUnsub: vi.fn(() => {}),
+ _relaunchingUnsub: vi.fn(() => {}),
+ _relaunchFailedUnsub: vi.fn(() => {}),
+ _whatsNewUnsub: vi.fn(() => {}),
+ _whatsNewDismissedUnsub: vi.fn(() => {}),
+ _stuckHintUnsub: vi.fn(() => {}),
+ onUpdateDownloaded: vi.fn(() => {}),
+ onUpdateRelaunching: vi.fn(() => {}),
+ onUpdateRelaunchFailed: vi.fn(() => {}),
+ onWhatsNew: vi.fn(() => {}),
+ onWhatsNewDismissed: vi.fn(() => {}),
+ onUpdateStuckHint: vi.fn(() => {}),
update: {
- relaunchNow: mock(() => Promise.resolve(undefined)),
- dismissWhatsNew: mock(() => Promise.resolve(undefined)),
+ relaunchNow: vi.fn(() => Promise.resolve(undefined)),
+ dismissWhatsNew: vi.fn(() => Promise.resolve(undefined)),
},
state: {
- query: mock(() => Promise.resolve({ channel: 'latest', schemaIncompatibility: null })),
- resetIncompatible: mock(() => Promise.resolve(undefined)),
+ query: vi.fn(() => Promise.resolve({ channel: 'latest', schemaIncompatibility: null })),
+ resetIncompatible: vi.fn(() => Promise.resolve(undefined)),
},
- shell: { openExternal: mock(() => Promise.resolve(undefined)) },
+ shell: { openExternal: vi.fn(() => Promise.resolve(undefined)) },
};
- b.onUpdateDownloaded = mock((cb: UpdateDownloadedCb) => {
+ b.onUpdateDownloaded = vi.fn((cb: UpdateDownloadedCb) => {
b._downloaded = cb;
return b._downloadedUnsub;
});
- b.onUpdateRelaunching = mock((cb: RelaunchingCb) => {
+ b.onUpdateRelaunching = vi.fn((cb: RelaunchingCb) => {
b._relaunching = cb;
return b._relaunchingUnsub;
});
- b.onUpdateRelaunchFailed = mock((cb: RelaunchFailedCb) => {
+ b.onUpdateRelaunchFailed = vi.fn((cb: RelaunchFailedCb) => {
b._relaunchFailed = cb;
return b._relaunchFailedUnsub;
});
- b.onWhatsNew = mock((cb: WhatsNewCb) => {
+ b.onWhatsNew = vi.fn((cb: WhatsNewCb) => {
b._whatsNew = cb;
return b._whatsNewUnsub;
});
- b.onWhatsNewDismissed = mock((cb: WhatsNewDismissedCb) => {
+ b.onWhatsNewDismissed = vi.fn((cb: WhatsNewDismissedCb) => {
b._whatsNewDismissed = cb;
return b._whatsNewDismissedUnsub;
});
- b.onUpdateStuckHint = mock((cb: StuckHintCb) => {
+ b.onUpdateStuckHint = vi.fn((cb: StuckHintCb) => {
b._stuckHint = cb;
return b._stuckHintUnsub;
});
@@ -205,7 +205,7 @@ describe('appendErrorDetail', () => {
describe('attachUpdateSubscribers — registration', () => {
test('subscribes to all six update channels on the bridge', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
expect(bridge.onUpdateDownloaded).toHaveBeenCalledTimes(1);
expect(bridge.onUpdateRelaunching).toHaveBeenCalledTimes(1);
@@ -217,7 +217,7 @@ describe('attachUpdateSubscribers — registration', () => {
test('returns a single unsubscribe closure that detaches ALL six listeners', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
const unsubscribe = attachUpdateSubscribers(castBridge(bridge), addNotice);
unsubscribe();
expect(bridge._downloadedUnsub).toHaveBeenCalledTimes(1);
@@ -241,7 +241,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
// card the clicked window shows — same stable id (in-place replace), no
// action button (blocks a redundant relaunch), no dismiss X.
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunching?.({ version: '0.1.1' });
@@ -256,7 +256,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
test('does NOT invoke relaunchNow — it is the echo, not the trigger (no loop)', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunching?.({ version: '0.1.1' });
expect(bridge.update.relaunchNow).not.toHaveBeenCalled();
@@ -264,7 +264,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
test('onUpdateRelaunchFailed → error notice with detail, same id as the rejection path', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunchFailed?.({ version: '0.1.1', message: 'App Still Running Error' });
const errorNotice = addNotice.mock.calls.at(-1)?.[0] as UpdateNotice;
@@ -277,7 +277,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
test('onUpdateRelaunchFailed without message → canonical body, no trailing colon', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunchFailed?.({ version: '0.1.1' });
const errorNotice = addNotice.mock.calls.at(-1)?.[0] as UpdateNotice;
@@ -286,7 +286,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
test('boot-detected failed install (downloadUrl present) → richer two-action card', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunchFailed?.({
version: '0.16.0-beta.3',
@@ -302,7 +302,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
test('failed-install Retry invokes relaunchNow; Download manually opens the URL', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
const url = 'https://github.com/inkeep/open-knowledge/releases';
bridge._relaunchFailed?.({ version: '0.16.0-beta.3', downloadUrl: url });
@@ -315,7 +315,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
test('relaunch-failed WITHOUT downloadUrl keeps the plain error notice (no actions)', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunchFailed?.({ version: '0.16.0-beta.3' });
const notice = addNotice.mock.calls.at(-1)?.[0] as UpdateNotice;
@@ -330,7 +330,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
// Relaunch action and dismiss X) replaces the button-less in-progress
// card — the non-clicked window is never stranded on a dead-end card.
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._relaunching?.({ version: '0.1.1' });
bridge._downloaded?.({ version: '0.1.1' });
@@ -349,7 +349,7 @@ describe('Notice A cross-window relaunch — ok:update:relaunching', () => {
describe('Notice A — ok:update:downloaded', () => {
test('emits notice with canonical copy + relaunch action on dispatch', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
@@ -367,7 +367,7 @@ describe('Notice A — ok:update:downloaded', () => {
test('action onClick invokes bridge.update.relaunchNow', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -384,7 +384,7 @@ describe('Notice A — ok:update:downloaded', () => {
// `dismissible: false` also drops the X — this terminal state has nothing
// to dismiss; the card disappears when the app restarts.
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
const armed = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -399,8 +399,8 @@ describe('Notice A — ok:update:downloaded', () => {
test('relaunchNow rejection → error notice with appended detail + armed card restored for retry', async () => {
const bridge = makeFakeBridge();
- bridge.update.relaunchNow = mock(() => Promise.reject(new Error('quitAndInstall failed')));
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ bridge.update.relaunchNow = vi.fn(() => Promise.reject(new Error('quitAndInstall failed')));
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
const noticeA = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -423,8 +423,8 @@ describe('Notice A — ok:update:downloaded', () => {
test('relaunchNow non-Error rejection (string throw) → error notice without trailing colon', async () => {
const bridge = makeFakeBridge();
- bridge.update.relaunchNow = mock(() => Promise.reject('not-an-error'));
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ bridge.update.relaunchNow = vi.fn(() => Promise.reject('not-an-error'));
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
const noticeA = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -437,7 +437,7 @@ describe('Notice A — ok:update:downloaded', () => {
test('relaunchNow success → no error notice (armed card + in-progress swap only)', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -453,8 +453,8 @@ describe('Notice A — ok:update:downloaded', () => {
test('relaunchNow success → dismissNotice fires with the Toast A id (dev-mode feedback)', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice);
bridge._downloaded?.({ version: '0.1.1' });
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -467,9 +467,9 @@ describe('Notice A — ok:update:downloaded', () => {
test('relaunchNow rejection → dismissNotice does NOT fire (error notice takes over)', async () => {
const bridge = makeFakeBridge();
- bridge.update.relaunchNow = mock(() => Promise.reject(new Error('quitAndInstall failed')));
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ bridge.update.relaunchNow = vi.fn(() => Promise.reject(new Error('quitAndInstall failed')));
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice);
bridge._downloaded?.({ version: '0.1.1' });
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -491,7 +491,7 @@ describe('Notice A — ok:update:downloaded', () => {
// install advanced to the newer version — the user saw "Version
// beta.18 ready to install" but relaunched onto beta.19.
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
bridge._downloaded?.({ version: '0.1.2' });
@@ -508,8 +508,8 @@ describe('Notice A — ok:update:downloaded', () => {
// (`relaunch-error-${version}`). If the stale beta.18 closure fired,
// the error id would be `relaunch-error-0.1.1`.
const bridge = makeFakeBridge();
- bridge.update.relaunchNow = mock(() => Promise.reject(new Error('quitAndInstall failed')));
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ bridge.update.relaunchNow = vi.fn(() => Promise.reject(new Error('quitAndInstall failed')));
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
bridge._downloaded?.({ version: '0.1.2' });
@@ -523,7 +523,7 @@ describe('Notice A — ok:update:downloaded', () => {
test('same version dispatched twice keeps the same id (in-place dedup at the store)', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._downloaded?.({ version: '0.1.1' });
bridge._downloaded?.({ version: '0.1.1' });
@@ -539,7 +539,7 @@ describe('Notice A — ok:update:downloaded', () => {
describe('Notice B — ok:update:whats-new', () => {
test('emits notice with version-specific copy + release URL action', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
const releaseUrl = 'https://github.com/inkeep/open-knowledge/releases/tag/v0.3.1';
bridge._whatsNew?.({ version: '0.3.1', releaseUrl });
@@ -560,8 +560,8 @@ describe('Notice B — ok:update:whats-new', () => {
test('notice self-dismisses after the auto-dismiss window', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 15);
bridge._whatsNew?.({ version: '0.3.1', releaseUrl: 'https://example.com/r' });
expect(dismissNotice).not.toHaveBeenCalled();
@@ -571,8 +571,8 @@ describe('Notice B — ok:update:whats-new', () => {
test('unsubscribe clears the pending auto-dismiss timer', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
const unsubscribe = attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 15);
bridge._whatsNew?.({ version: '0.3.1', releaseUrl: 'https://example.com/r' });
unsubscribe();
@@ -584,8 +584,8 @@ describe('Notice B — ok:update:whats-new', () => {
// The timer-tracking Set exists to hold multiple concurrent timers; a
// regression to a single variable would silently drop the first one.
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 15);
bridge._whatsNew?.({ version: '0.3.0', releaseUrl: 'https://example.com/r0' });
bridge._whatsNew?.({ version: '0.3.1', releaseUrl: 'https://example.com/r1' });
@@ -597,7 +597,7 @@ describe('Notice B — ok:update:whats-new', () => {
test('dismissing the notice (X) notifies main so every window can clear', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._whatsNew?.({ version: '0.3.1', releaseUrl: 'https://example.com/r' });
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -607,8 +607,8 @@ describe('Notice B — ok:update:whats-new', () => {
test('auto-dismiss also notifies main so the other windows clear in lockstep', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 15);
bridge._whatsNew?.({ version: '0.3.1', releaseUrl: 'https://example.com/r' });
await new Promise((resolve) => setTimeout(resolve, 45));
@@ -617,8 +617,8 @@ describe('Notice B — ok:update:whats-new', () => {
test('onWhatsNewDismissed echo clears the card by id without re-notifying main (no loop)', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice);
bridge._whatsNewDismissed?.({ version: '0.3.1' });
expect(dismissNotice).toHaveBeenCalledWith('whats-new-0.3.1');
@@ -634,9 +634,9 @@ describe('Notice B — ok:update:whats-new', () => {
describe('Notice B — combined subscribe path', () => {
test('eligible → combined notice: distinct id, whatsNew data, onShown + dismissWhatsNew at creation, no auto-dismiss', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
- const onShown = mock<(version: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
+ const onShown = vi.fn<(version: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 15, {
isEligible: () => true,
onShown,
@@ -658,9 +658,9 @@ describe('Notice B — combined subscribe path', () => {
test('ineligible → plain notice with auto-dismiss (combined branch skipped, onShown not called)', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
- const onShown = mock<(version: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
+ const onShown = vi.fn<(version: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 15, {
isEligible: () => false,
onShown,
@@ -677,8 +677,8 @@ describe('Notice B — combined subscribe path', () => {
test('onWhatsNewDismissed echo does not remove the combined card (distinct id is load-bearing)', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice, dismissNotice, 60_000, {
isEligible: () => true,
onShown: () => {},
@@ -699,7 +699,7 @@ describe('Notice B — combined subscribe path', () => {
describe('Notice C — ok:update:stuck-hint', () => {
test('emits notice with D12 copy + download URL action', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
const downloadUrl = 'https://github.com/inkeep/open-knowledge/releases';
bridge._stuckHint?.({ downloadUrl });
@@ -715,7 +715,7 @@ describe('Notice C — ok:update:stuck-hint', () => {
test('stuck-hint uses a fixed id — second dispatch from main hits the list-level dedup', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
attachUpdateSubscribers(castBridge(bridge), addNotice);
bridge._stuckHint?.({ downloadUrl: 'https://x/y' });
bridge._stuckHint?.({ downloadUrl: 'https://x/y' });
@@ -737,7 +737,7 @@ describe('Notice E — schema-incompatibility refuse-downgrade', () => {
test('emits notice with spec body, a single Reset action, and priority 0', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice);
expect(addNotice).toHaveBeenCalledTimes(1);
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
@@ -750,7 +750,7 @@ describe('Notice E — schema-incompatibility refuse-downgrade', () => {
test('Reset action invokes bridge.state.resetIncompatible', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice);
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
notice.action?.onClick();
@@ -759,8 +759,8 @@ describe('Notice E — schema-incompatibility refuse-downgrade', () => {
test('Reset success → dismissNotice fires for the active id', async () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice, dismissNotice);
const notice = addNotice.mock.calls[0]?.[0] as UpdateNotice;
notice.action?.onClick();
@@ -771,9 +771,9 @@ describe('Notice E — schema-incompatibility refuse-downgrade', () => {
test('Reset rejection → parent dismissed + error notice with spec shape and appended detail', async () => {
const bridge = makeFakeBridge();
- bridge.state.resetIncompatible = mock(() => Promise.reject(new Error('disk fail')));
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
- const dismissNotice = mock<(id: string) => void>(() => {});
+ bridge.state.resetIncompatible = vi.fn(() => Promise.reject(new Error('disk fail')));
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
+ const dismissNotice = vi.fn<(id: string) => void>(() => {});
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice, dismissNotice);
const initial = addNotice.mock.calls[0]?.[0] as UpdateNotice;
initial.action?.onClick();
@@ -791,7 +791,7 @@ describe('Notice E — schema-incompatibility refuse-downgrade', () => {
test('different persistedSchemaVersion produces distinct notice ids', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice);
addSchemaIncompatibilityNotice(
castBridge(bridge),
@@ -804,7 +804,7 @@ describe('Notice E — schema-incompatibility refuse-downgrade', () => {
test('repeat call with same diagnostic reuses the same id (list-level dedup)', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice);
addSchemaIncompatibilityNotice(castBridge(bridge), diagnostic, addNotice);
const ids = addNotice.mock.calls.map((c) => (c[0] as UpdateNotice).id);
@@ -847,7 +847,7 @@ describe('pickActiveNotice', () => {
describe('unsubscribe semantics', () => {
test('after unsubscribe, all six per-channel unsub closures fire', () => {
const bridge = makeFakeBridge();
- const addNotice = mock<(notice: UpdateNotice) => void>(() => {});
+ const addNotice = vi.fn<(notice: UpdateNotice) => void>(() => {});
const unsubscribe = attachUpdateSubscribers(castBridge(bridge), addNotice);
unsubscribe();
expect(bridge._downloadedUnsub).toHaveBeenCalledTimes(1);
diff --git a/packages/app/src/components/auth-event-stream.test.ts b/packages/app/src/components/auth-event-stream.test.ts
index 47e0a5eb2..e094bdc99 100644
--- a/packages/app/src/components/auth-event-stream.test.ts
+++ b/packages/app/src/components/auth-event-stream.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { consumeAuthEventStream } from './auth-event-stream';
function streamFromChunks(chunks: string[]): ReadableStream<Uint8Array> {
diff --git a/packages/app/src/components/auto-sync-onboarding-gate.test.ts b/packages/app/src/components/auto-sync-onboarding-gate.test.ts
index cf0c4f802..54b75f8c9 100644
--- a/packages/app/src/components/auto-sync-onboarding-gate.test.ts
+++ b/packages/app/src/components/auto-sync-onboarding-gate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type AutoSyncOnboardingGateInputs,
shouldShowAutoSyncOnboarding,
diff --git a/packages/app/src/components/bottom-composer-gate.test.ts b/packages/app/src/components/bottom-composer-gate.test.ts
index 278e126bf..ad0b123a7 100644
--- a/packages/app/src/components/bottom-composer-gate.test.ts
+++ b/packages/app/src/components/bottom-composer-gate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type BottomComposerGateInputs,
shouldShowBottomComposer,
diff --git a/packages/app/src/components/command-palette-flicker.test.ts b/packages/app/src/components/command-palette-flicker.test.ts
index f8b341b6e..4d31735c5 100644
--- a/packages/app/src/components/command-palette-flicker.test.ts
+++ b/packages/app/src/components/command-palette-flicker.test.ts
@@ -14,7 +14,7 @@
* after error / tag-mode exit.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { WorkspaceEntry, WorkspaceSearchEntry } from './command-palette-search';
// Dynamic import so a missing export surfaces as an assertion error in the
diff --git a/packages/app/src/components/command-palette-recents.test.ts b/packages/app/src/components/command-palette-recents.test.ts
index 647b840e0..9f6ada2d4 100644
--- a/packages/app/src/components/command-palette-recents.test.ts
+++ b/packages/app/src/components/command-palette-recents.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
filterOmnibarRecents,
loadOmnibarRecents,
diff --git a/packages/app/src/components/command-palette-search.test.ts b/packages/app/src/components/command-palette-search.test.ts
index 39829304a..b2c2243b1 100644
--- a/packages/app/src/components/command-palette-search.test.ts
+++ b/packages/app/src/components/command-palette-search.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
buildWorkspaceEntries,
classifyOmnibarSearchHint,
diff --git a/packages/app/src/components/command-palette-semantic.test.ts b/packages/app/src/components/command-palette-semantic.test.ts
index f3ebcfc9d..141887e8e 100644
--- a/packages/app/src/components/command-palette-semantic.test.ts
+++ b/packages/app/src/components/command-palette-semantic.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeSemanticModeView, type SemanticModeState } from './command-palette-semantic';
function view(over: Partial<SemanticModeState>) {
diff --git a/packages/app/src/components/command-palette-tag-search.test.ts b/packages/app/src/components/command-palette-tag-search.test.ts
index 9523eb2d5..ce48d87c4 100644
--- a/packages/app/src/components/command-palette-tag-search.test.ts
+++ b/packages/app/src/components/command-palette-tag-search.test.ts
@@ -11,7 +11,7 @@
* - returns the full list (no cap — host CommandList scrolls)
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { TagSummaryEntry } from '../editor/extensions/tag-suggestion.ts';
import { filterTagList, parseTagPaletteQuery } from './command-palette-tag-search.ts';
diff --git a/packages/app/src/components/composer-draft-store.test.ts b/packages/app/src/components/composer-draft-store.test.ts
index d3b56da6d..aabfd0250 100644
--- a/packages/app/src/components/composer-draft-store.test.ts
+++ b/packages/app/src/components/composer-draft-store.test.ts
@@ -13,8 +13,8 @@
* hand-built doc literals in that shape.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetComposerDraftForTests,
clearComposerDraft,
diff --git a/packages/app/src/components/doc-panel-events.test.ts b/packages/app/src/components/doc-panel-events.test.ts
index c104c9858..27c8d91b7 100644
--- a/packages/app/src/components/doc-panel-events.test.ts
+++ b/packages/app/src/components/doc-panel-events.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
consumePendingDocPanelTabRequest,
requestDocPanelTab,
@@ -8,7 +8,7 @@ import {
describe('doc-panel-events', () => {
test('dispatches and subscribes tab requests through the shared event name', () => {
const target = new EventTarget();
- const onRequest = mock(() => {});
+ const onRequest = vi.fn(() => {});
const unsubscribe = subscribeToDocPanelTabRequests(onRequest, target);
consumePendingDocPanelTabRequest();
diff --git a/packages/app/src/components/editor-area-overlay.test.ts b/packages/app/src/components/editor-area-overlay.test.ts
index 947046f70..a21e903ba 100644
--- a/packages/app/src/components/editor-area-overlay.test.ts
+++ b/packages/app/src/components/editor-area-overlay.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { shouldPaintOverlay } from './editor-area-overlay';
/**
diff --git a/packages/app/src/components/editor-area-sticky-repin.test.ts b/packages/app/src/components/editor-area-sticky-repin.test.ts
index 52ee38fd8..99ccc0632 100644
--- a/packages/app/src/components/editor-area-sticky-repin.test.ts
+++ b/packages/app/src/components/editor-area-sticky-repin.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeStickyRepinLayout } from './editor-area-sticky-repin';
describe('computeStickyRepinLayout', () => {
diff --git a/packages/app/src/components/editor-tabs-chrome.test.ts b/packages/app/src/components/editor-tabs-chrome.test.ts
index 219adc906..879eb65c3 100644
--- a/packages/app/src/components/editor-tabs-chrome.test.ts
+++ b/packages/app/src/components/editor-tabs-chrome.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { type CollisionDetection, KeyboardCode, type Modifier } from '@dnd-kit/core';
+import { describe, expect, test } from 'vitest';
import {
createTabReorderModifier,
DRAGGING_TAB_Z_INDEX,
diff --git a/packages/app/src/components/editor/SelectionAnnouncer.test.ts b/packages/app/src/components/editor/SelectionAnnouncer.test.ts
index 94d817ac0..480baf6c6 100644
--- a/packages/app/src/components/editor/SelectionAnnouncer.test.ts
+++ b/packages/app/src/components/editor/SelectionAnnouncer.test.ts
@@ -8,9 +8,9 @@
* message shape the E2E harness only asserts partially.
*/
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, NodeSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import type { BlockSelection } from '../../editor/extensions/selection-state-plugin.ts';
import { formatSelectionMessage } from './SelectionAnnouncer.tsx';
diff --git a/packages/app/src/components/empty-state/CopyablePromptList.dom.test.tsx b/packages/app/src/components/empty-state/CopyablePromptList.dom.test.tsx
index 3c56fd3b1..8fa1c9411 100644
--- a/packages/app/src/components/empty-state/CopyablePromptList.dom.test.tsx
+++ b/packages/app/src/components/empty-state/CopyablePromptList.dom.test.tsx
@@ -17,13 +17,14 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
@@ -48,7 +49,7 @@ describe('CopyablePromptList', () => {
});
test('flips a row to "Copied" when the clipboard write resolves', async () => {
- const writeText = mock(() => Promise.resolve());
+ const writeText = vi.fn(() => Promise.resolve());
Object.defineProperty(globalThis.navigator, 'clipboard', {
configurable: true,
value: { writeText },
@@ -70,7 +71,7 @@ describe('CopyablePromptList', () => {
test('falls back to execCommand and still copies when embedded-iframe policy refuses the async write', async () => {
// Reproduce Claude's embedded iframe: navigator.clipboard exists but the
// Permissions-Policy refusal surfaces as a rejected writeText.
- const writeText = mock(() =>
+ const writeText = vi.fn(() =>
Promise.reject(
Object.assign(new Error('blocked because of a permissions policy'), {
name: 'NotAllowedError',
@@ -81,7 +82,7 @@ describe('CopyablePromptList', () => {
configurable: true,
value: { writeText },
});
- const execCommand = mock(() => true);
+ const execCommand = vi.fn(() => true);
Object.defineProperty(globalThis.document, 'execCommand', {
configurable: true,
value: execCommand,
@@ -105,14 +106,14 @@ describe('CopyablePromptList', () => {
// execCommand fallback returns false (no Electron bridge either), the row
// must stay on "Copy" — never show a false success. Guards the trivial
// `.catch()` in handleCopy against silent removal.
- const writeText = mock(() =>
+ const writeText = vi.fn(() =>
Promise.reject(Object.assign(new Error('blocked'), { name: 'NotAllowedError' })),
);
Object.defineProperty(globalThis.navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
- const execCommand = mock(() => false);
+ const execCommand = vi.fn(() => false);
Object.defineProperty(globalThis.document, 'execCommand', {
configurable: true,
value: execCommand,
diff --git a/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx b/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx
index 41d5701a7..1bd402e55 100644
--- a/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx
+++ b/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx
@@ -1,11 +1,11 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@/components/OkBlob', () => ({
+vi.doMock('@/components/OkBlob', () => ({
OkBlob: ({ celebrateSignal, size }: { celebrateSignal: number; size: number }) => (
<div
data-testid="ok-blob-probe"
diff --git a/packages/app/src/components/extension-picker-utils.test.ts b/packages/app/src/components/extension-picker-utils.test.ts
index ee0472983..61d3b0eb2 100644
--- a/packages/app/src/components/extension-picker-utils.test.ts
+++ b/packages/app/src/components/extension-picker-utils.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type DocExtension,
detectExtension,
diff --git a/packages/app/src/components/file-entry-icon.test.tsx b/packages/app/src/components/file-entry-icon.test.tsx
index 3f226330d..a56a3024b 100644
--- a/packages/app/src/components/file-entry-icon.test.tsx
+++ b/packages/app/src/components/file-entry-icon.test.tsx
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { File, Film, ImageIcon, Volume2 } from 'lucide-react';
+import { describe, expect, test } from 'vitest';
import { lucideIconToSvgString } from '@/editor/registry/lucide-svg';
import {
fileEntryPathIconToSvgString,
diff --git a/packages/app/src/components/file-tree-adapter.test.ts b/packages/app/src/components/file-tree-adapter.test.ts
index 4591f137c..a510c7e53 100644
--- a/packages/app/src/components/file-tree-adapter.test.ts
+++ b/packages/app/src/components/file-tree-adapter.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { ContextMenuItem, FileTreeDropTarget } from '@pierre/trees';
+import { describe, expect, test } from 'vitest';
import { OK_SIDEBAR_DRAG_MIME } from '@/lib/sidebar-drag';
import {
appendSidebarUploadFields,
diff --git a/packages/app/src/components/file-tree-density.test.ts b/packages/app/src/components/file-tree-density.test.ts
index 887417120..e9fb89471 100644
--- a/packages/app/src/components/file-tree-density.test.ts
+++ b/packages/app/src/components/file-tree-density.test.ts
@@ -9,7 +9,7 @@
* skips the row-height clamp, this test fails before render-time regressions
* show up in dogfood.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createFileTreeStyle,
FILE_TREE_DENSITY_OPTIONS,
diff --git a/packages/app/src/components/file-tree-extension-badge.dom.test.tsx b/packages/app/src/components/file-tree-extension-badge.dom.test.tsx
index d1a25946f..7d0149245 100644
--- a/packages/app/src/components/file-tree-extension-badge.dom.test.tsx
+++ b/packages/app/src/components/file-tree-extension-badge.dom.test.tsx
@@ -9,8 +9,9 @@
* no monospace), the basename loses its trailing dot, and folders /
* extension-less rows are ignored.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
applyExtensionBadges,
OK_EXT_BADGE_ATTR,
diff --git a/packages/app/src/components/file-tree-merge.test.ts b/packages/app/src/components/file-tree-merge.test.ts
index 5f2fb00a1..9a0bd7816 100644
--- a/packages/app/src/components/file-tree-merge.test.ts
+++ b/packages/app/src/components/file-tree-merge.test.ts
@@ -21,7 +21,7 @@
* without relying on two `Date.now()` calls landing in the same millisecond.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
mergeAndPruneRecentLocalAdds,
mergeRootEntriesAdditive,
diff --git a/packages/app/src/components/file-tree-okignore.test.ts b/packages/app/src/components/file-tree-okignore.test.ts
index f2db6e70c..c8057ebd2 100644
--- a/packages/app/src/components/file-tree-okignore.test.ts
+++ b/packages/app/src/components/file-tree-okignore.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import ignore from 'ignore';
+import { describe, expect, test } from 'vitest';
import { buildOkignorePatternFromTarget } from './file-tree-okignore';
describe('buildOkignorePatternFromTarget — file leaves', () => {
diff --git a/packages/app/src/components/file-tree-operations.test.ts b/packages/app/src/components/file-tree-operations.test.ts
index 9ed38038a..1e398d819 100644
--- a/packages/app/src/components/file-tree-operations.test.ts
+++ b/packages/app/src/components/file-tree-operations.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
applyDeleteToDocuments,
applyDuplicateToDocuments,
diff --git a/packages/app/src/components/file-tree-path-helpers.test.ts b/packages/app/src/components/file-tree-path-helpers.test.ts
index 65714cab0..3b5d94473 100644
--- a/packages/app/src/components/file-tree-path-helpers.test.ts
+++ b/packages/app/src/components/file-tree-path-helpers.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { FileTreeTarget } from './file-tree-operations';
import {
alternateMarkdownTreePath,
diff --git a/packages/app/src/components/file-tree-refresh.dom.test.tsx b/packages/app/src/components/file-tree-refresh.dom.test.tsx
index 4bfa9f239..0d0a71647 100644
--- a/packages/app/src/components/file-tree-refresh.dom.test.tsx
+++ b/packages/app/src/components/file-tree-refresh.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
type DocumentsChangedListener = (channels: string[]) => void;
type TemplatesChangedListener = () => void;
@@ -75,15 +75,15 @@ class StubModel {
let model = new StubModel();
let documentsChangedListener: DocumentsChangedListener | null = null;
let templatesChangedListener: TemplatesChangedListener | null = null;
-let unsubscribeDocumentsChangedMock = mock(() => {});
-let unsubscribeTemplatesChangedMock = mock(() => {});
-let schedulerRequestMock = mock(() => {});
-let schedulerDisposeMock = mock(() => {});
-const createRefreshSchedulerMock = mock(() => ({
+let unsubscribeDocumentsChangedMock = vi.fn(() => {});
+let unsubscribeTemplatesChangedMock = vi.fn(() => {});
+let schedulerRequestMock = vi.fn(() => {});
+let schedulerDisposeMock = vi.fn(() => {});
+const createRefreshSchedulerMock = vi.fn(() => ({
request: schedulerRequestMock,
dispose: schedulerDisposeMock,
}));
-const fetchMock = mock(async (input: RequestInfo | URL) => {
+const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (url === '/api/workspace') {
return new Response(
@@ -98,18 +98,18 @@ const fetchMock = mock(async (input: RequestInfo | URL) => {
throw new Error(`unexpected fetch: ${url}`);
});
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
success: () => {},
error: () => {},
},
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'notes/source',
activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
@@ -124,15 +124,15 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ addPage: () => {} }),
}));
-mock.module('./ui/sidebar', () => ({
+vi.doMock('./ui/sidebar', () => ({
useSidebar: () => ({ notifySidebarFileSelected: () => {} }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
@@ -140,30 +140,30 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('@/hooks/use-conflicts', () => ({
+vi.doMock('@/hooks/use-conflicts', () => ({
useConflicts: () => ({ conflicts: [], loading: false, error: null }),
}));
-mock.module('./handoff/useInstalledAgents', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
useHandoffDispatch: () => ({ dispatch: async () => ({ ok: true as const }) }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -171,11 +171,11 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/dialog', () => ({
+vi.doMock('@/components/ui/dialog', () => ({
Dialog: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: MenuItem,
DropdownMenuContent: ({ children }: { children?: ReactNode }) => (
@@ -189,34 +189,34 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({
NewItemDialog: () => null,
}));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: () => null,
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: () => ({ model }),
FileTree: ({
onClickCapture,
@@ -237,7 +237,7 @@ mock.module('@pierre/trees/react', () => ({
),
}));
-mock.module('@/lib/documents-events', () => ({
+vi.doMock('@/lib/documents-events', () => ({
emitDocumentsChanged: () => {},
emitTemplatesChanged: () => {},
subscribeToDocumentsChanged: (listener: DocumentsChangedListener) => {
@@ -260,29 +260,29 @@ mock.module('@/lib/documents-events', () => ({
},
}));
-mock.module('@/lib/refresh-scheduler', () => ({
+vi.doMock('@/lib/refresh-scheduler', () => ({
createRefreshScheduler: createRefreshSchedulerMock,
}));
const { FileTree } = await import('./FileTree');
describe('FileTree document-list refresh scheduling', () => {
- let setIntervalSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let setIntervalSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
model = new StubModel();
documentsChangedListener = null;
templatesChangedListener = null;
- unsubscribeDocumentsChangedMock = mock(() => {});
- unsubscribeTemplatesChangedMock = mock(() => {});
- schedulerRequestMock = mock(() => {});
- schedulerDisposeMock = mock(() => {});
+ unsubscribeDocumentsChangedMock = vi.fn(() => {});
+ unsubscribeTemplatesChangedMock = vi.fn(() => {});
+ schedulerRequestMock = vi.fn(() => {});
+ schedulerDisposeMock = vi.fn(() => {});
createRefreshSchedulerMock.mockClear();
fetchMock.mockClear();
globalThis.fetch = fetchMock as unknown as typeof fetch;
- setIntervalSpy = spyOn(globalThis, 'setInterval');
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/file-tree-rename-chip.dom.test.tsx b/packages/app/src/components/file-tree-rename-chip.dom.test.tsx
index d905c8fbb..70d43b914 100644
--- a/packages/app/src/components/file-tree-rename-chip.dom.test.tsx
+++ b/packages/app/src/components/file-tree-rename-chip.dom.test.tsx
@@ -8,8 +8,9 @@
* so the user can immediately type to replace it, and the selection is
* idempotent across multiple calls within the same rename session.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { cleanup } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetRenameInputAffordanceForTesting,
applyRenameInputAffordance,
diff --git a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
index 0d7ef1941..96661eb06 100644
--- a/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
+++ b/packages/app/src/components/file-tree-rename-focus-reconciliation.dom.test.tsx
@@ -13,9 +13,10 @@
* path is gone from the new set (Pierre's `resolveFocusedIndex` →
* index-0 fallback — the user-visible bug mechanism).
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, render, waitFor } from '@testing-library/react';
import type { MouseEventHandler, ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { FileEntry } from './file-tree-utils';
type MenuItemProps = {
@@ -51,16 +52,16 @@ function MenuSeparator() {
return <hr />;
}
-const toastSuccessMock = mock(() => {});
-const toastErrorMock = mock(() => {});
-const addPageMock = mock(() => {});
-const openTargetMock = mock(() => {});
-const notifySidebarFileSelectedMock = mock(() => {});
-const closeTabsMock = mock(() => {});
-const closeDocumentMock = mock(() => {});
-const closeAndClearForRenameMock = mock(async () => {});
-const remapTabsForRenameMock = mock(() => {});
-const dispatchHandoffMock = mock(async () => ({ ok: true as const }));
+const toastSuccessMock = vi.fn(() => {});
+const toastErrorMock = vi.fn(() => {});
+const addPageMock = vi.fn(() => {});
+const openTargetMock = vi.fn(() => {});
+const notifySidebarFileSelectedMock = vi.fn(() => {});
+const closeTabsMock = vi.fn(() => {});
+const closeDocumentMock = vi.fn(() => {});
+const closeAndClearForRenameMock = vi.fn(async () => {});
+const remapTabsForRenameMock = vi.fn(() => {});
+const dispatchHandoffMock = vi.fn(async () => ({ ok: true as const }));
// Three documents alphabetically. `foo.md` (index 1) is the rename target.
// After rename: ['aaa.md', 'bar.md', 'zzz.md']. The index-0 row (`aaa.md`)
@@ -157,7 +158,7 @@ class StubModel {
focusedPath: string | null = null;
selectedPaths: string[] = [];
items = new Map<string, StubItem>();
- startRenaming = mock(() => {});
+ startRenaming = vi.fn(() => {});
getFocusedPath() {
return this.focusedPath;
@@ -275,7 +276,7 @@ function jsonResponse(body: unknown, status = 200): Response {
}
function makeFetchMock() {
- return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ return vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
fetchCalls.push({ url, init });
if (url.startsWith('/api/documents')) {
@@ -295,18 +296,18 @@ function makeFetchMock() {
});
}
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
success: toastSuccessMock,
error: toastErrorMock,
},
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
activeDocName: 'foo',
activeTarget: { kind: 'doc', target: 'foo', docName: 'foo' },
@@ -324,15 +325,15 @@ mock.module('@/editor/DocumentContext', () => ({
}),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ addPage: addPageMock, pageMeta: new Map() }),
}));
-mock.module('./ui/sidebar', () => ({
+vi.doMock('./ui/sidebar', () => ({
useSidebar: () => ({ notifySidebarFileSelected: notifySidebarFileSelectedMock }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
okignoreBinding: null,
projectLocalBinding: null,
@@ -340,26 +341,26 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('./handoff/useInstalledAgents', () => ({
+vi.doMock('./handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {} }),
}));
-mock.module('./handoff/useHandoffDispatch', () => ({
+vi.doMock('./handoff/useHandoffDispatch', () => ({
buildFolderHandoffInput: () => null,
buildHandoffInput: () => null,
useHandoffDispatch: () => ({ dispatch: dispatchHandoffMock }),
}));
-mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+vi.doMock('./handoff/OpenInAgentContextSubmenu', () => ({
OpenInAgentContextSubmenu: () => null,
}));
-mock.module('./sidebar-hover-prewarm', () => ({
+vi.doMock('./sidebar-hover-prewarm', () => ({
cancelHoverPrewarm: () => {},
scheduleHoverPrewarm: () => {},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
<button type="button" {...props}>
{children}
@@ -367,11 +368,11 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/dialog', () => ({
+vi.doMock('@/components/ui/dialog', () => ({
Dialog: PassThrough,
}));
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: PassThrough,
DropdownMenuCheckboxItem: MenuItem,
DropdownMenuContent: MenuContent,
@@ -383,34 +384,34 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: PassThrough,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => <span className={className} />,
}));
-mock.module('@/components/DeleteConfirmationDialog', () => ({
+vi.doMock('@/components/DeleteConfirmationDialog', () => ({
DeleteConfirmationDialog: () => null,
}));
-mock.module('@/components/NewItemDialog', () => ({
+vi.doMock('@/components/NewItemDialog', () => ({
NewItemDialog: () => null,
}));
-mock.module('@/components/TrashFailureModal', () => ({
+vi.doMock('@/components/TrashFailureModal', () => ({
TrashFailureModal: () => null,
coerceTrashFailureReason: (reason: string) => reason,
}));
-mock.module('@/components/use-selection-mirror', () => ({
+vi.doMock('@/components/use-selection-mirror', () => ({
asDirectoryHandle: (item: StubItem | null) => (item?.isDirectory() ? item : null),
useSelectionMirror: () => {},
}));
-mock.module('@pierre/trees', () => ({
+vi.doMock('@pierre/trees', () => ({
FILE_TREE_TAG_NAME: 'ok-file-tree',
themeToTreeStyles: () => ({}),
}));
-mock.module('@pierre/trees/react', () => ({
+vi.doMock('@pierre/trees/react', () => ({
useFileTree: (options: unknown) => {
capturedOptions = options;
return { model };
@@ -464,7 +465,7 @@ function simulatePierreCommitRename(
}
describe('FileTree post-rename Pierre/React store reconciliation', () => {
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
model = new StubModel();
@@ -488,7 +489,7 @@ describe('FileTree post-rename Pierre/React store reconciliation', () => {
notifySidebarFileSelectedMock.mockClear();
closeAndClearForRenameMock.mockClear();
remapTabsForRenameMock.mockClear();
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/file-tree-rename-validation.test.ts b/packages/app/src/components/file-tree-rename-validation.test.ts
index 085f056be..b1ab6a74a 100644
--- a/packages/app/src/components/file-tree-rename-validation.test.ts
+++ b/packages/app/src/components/file-tree-rename-validation.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
getFileExtension,
hasSupportedDocumentExtension,
diff --git a/packages/app/src/components/file-tree-reveal.test.ts b/packages/app/src/components/file-tree-reveal.test.ts
index 65c49b4a3..b65954bf7 100644
--- a/packages/app/src/components/file-tree-reveal.test.ts
+++ b/packages/app/src/components/file-tree-reveal.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, mock, test } from 'bun:test';
import type { FileTree } from '@pierre/trees';
+import { describe, expect, test, vi } from 'vitest';
import { revealActiveRow } from './file-tree-reveal';
type RevealModel = Pick<FileTree, 'getFocusedPath' | 'scrollToPath'>;
@@ -8,7 +8,7 @@ type RevealModel = Pick<FileTree, 'getFocusedPath' | 'scrollToPath'>;
// so the contract is "scroll the active row into view without stealing focus."
// A spy on the model is the behavior surface — no DOM/shadow-root walking left.
function makeModel(focusedPath: string | null) {
- const scrollToPath = mock(() => {});
+ const scrollToPath = vi.fn(() => {});
const model = {
getFocusedPath: () => focusedPath,
scrollToPath,
diff --git a/packages/app/src/components/file-tree-selection.test.ts b/packages/app/src/components/file-tree-selection.test.ts
index b346b1198..4fc5fc0bd 100644
--- a/packages/app/src/components/file-tree-selection.test.ts
+++ b/packages/app/src/components/file-tree-selection.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveFileTreeSelection, resolveFileTreeSelectionAction } from './file-tree-selection';
describe('resolveFileTreeSelection', () => {
diff --git a/packages/app/src/components/file-tree-trash-copy.test.ts b/packages/app/src/components/file-tree-trash-copy.test.ts
index b02f991e1..27139184e 100644
--- a/packages/app/src/components/file-tree-trash-copy.test.ts
+++ b/packages/app/src/components/file-tree-trash-copy.test.ts
@@ -7,7 +7,7 @@
* VSCode source: `microsoft/vscode/blob/main/src/vs/workbench/contrib/files/browser/fileActions.ts`
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { FileTreeTarget } from '@/components/file-tree-operations';
import {
buildTrashConfirmCopyElectron,
diff --git a/packages/app/src/components/file-tree-utils.test.ts b/packages/app/src/components/file-tree-utils.test.ts
index 5c4dc930c..593a6b7c0 100644
--- a/packages/app/src/components/file-tree-utils.test.ts
+++ b/packages/app/src/components/file-tree-utils.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { type DocumentListEntry, DocumentListEntrySchema } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
attributeTreeHiddenAxes,
classifyEmptyTree,
diff --git a/packages/app/src/components/folder-overview-data.test.ts b/packages/app/src/components/folder-overview-data.test.ts
index 0db7f1555..f3ee693f6 100644
--- a/packages/app/src/components/folder-overview-data.test.ts
+++ b/packages/app/src/components/folder-overview-data.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildFolderOverviewData } from './folder-overview-data';
describe('buildFolderOverviewData', () => {
diff --git a/packages/app/src/components/graph-colors.test.ts b/packages/app/src/components/graph-colors.test.ts
index 63bc8abed..1b06ba790 100644
--- a/packages/app/src/components/graph-colors.test.ts
+++ b/packages/app/src/components/graph-colors.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { clusterColor } from './graph-colors';
describe('clusterColor', () => {
diff --git a/packages/app/src/components/graph-label-layout.test.ts b/packages/app/src/components/graph-label-layout.test.ts
index 2f3f18cdd..c12b9813b 100644
--- a/packages/app/src/components/graph-label-layout.test.ts
+++ b/packages/app/src/components/graph-label-layout.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type GraphLabelLayoutLink,
type GraphLabelLayoutNode,
diff --git a/packages/app/src/components/graph-label-utils.test.ts b/packages/app/src/components/graph-label-utils.test.ts
index 7a562c88b..0359447b4 100644
--- a/packages/app/src/components/graph-label-utils.test.ts
+++ b/packages/app/src/components/graph-label-utils.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildGraphLabelDescriptors, pickGraphLabelText } from './graph-label-utils';
diff --git a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts
index cfcd7e6a4..b696b5c4f 100644
--- a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts
+++ b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { contextRowHint } from './OpenInAgentContextSubmenu';
describe('contextRowHint', () => {
diff --git a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts
index 5f3c1ed1b..61f15c570 100644
--- a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts
+++ b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { emptySpaceRowHint } from './OpenInAgentEmptySpaceSubmenu';
describe('OpenInAgentEmptySpaceSubmenu module surface', () => {
diff --git a/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts b/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts
index 008259a57..e39d5aac4 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts
+++ b/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts
@@ -8,8 +8,8 @@
* - `computeRowHint` short inline status copy
*/
-import { describe, expect, test } from 'bun:test';
import type { InstallState, TargetData } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { KNOWN_TARGETS } from '@/lib/handoff/targets';
function targetById(id: TargetData['id']): TargetData {
diff --git a/packages/app/src/components/handoff/compose-lint-fix-prompt.test.ts b/packages/app/src/components/handoff/compose-lint-fix-prompt.test.ts
index 8b4440ebd..6202fbc74 100644
--- a/packages/app/src/components/handoff/compose-lint-fix-prompt.test.ts
+++ b/packages/app/src/components/handoff/compose-lint-fix-prompt.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { LintDiagnostic } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { composeLintFixTerminalPaste } from './compose-lint-fix-prompt.ts';
function diag(over: Partial<LintDiagnostic> = {}): LintDiagnostic {
diff --git a/packages/app/src/components/handoff/dispatch-single-entry-point.test.ts b/packages/app/src/components/handoff/dispatch-single-entry-point.test.ts
index 20fe10e8a..715934101 100644
--- a/packages/app/src/components/handoff/dispatch-single-entry-point.test.ts
+++ b/packages/app/src/components/handoff/dispatch-single-entry-point.test.ts
@@ -23,9 +23,9 @@
* tests, and fails a PR at the exact file that introduced the direct import.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
+import { describe, expect, test } from 'vitest';
// `import.meta.url` → `…/packages/app/src/components/handoff/…`. Walk up two
// levels to land on `packages/app/src/`, the new scope root.
diff --git a/packages/app/src/components/handoff/terminal-launch-events.test.ts b/packages/app/src/components/handoff/terminal-launch-events.test.ts
index 3a00a26f7..29ef2eeb5 100644
--- a/packages/app/src/components/handoff/terminal-launch-events.test.ts
+++ b/packages/app/src/components/handoff/terminal-launch-events.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { requestTerminalLaunch, subscribeToTerminalLaunchRequests } from './terminal-launch-events';
describe('terminal-launch-events', () => {
diff --git a/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts
index d50914ede..fcd95cfdc 100644
--- a/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts
+++ b/packages/app/src/components/handoff/useHandoffDispatch.terminal-budget.test.ts
@@ -24,7 +24,6 @@
* string is byte-identical to what the PTY receives).
*/
-import { describe, expect, test } from 'bun:test';
import {
assembleHandoffPrompt,
buildCliLaunchArgString,
@@ -34,6 +33,7 @@ import {
TERMINAL_CLI_IDS,
TERMINAL_INLINE_PROMPT_BUDGET,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import type { HandoffDispatchInput } from './useHandoffDispatch';
/** The composer's truncation marker (`INSTRUCTION_TRUNCATION_MARKER` in
diff --git a/packages/app/src/components/handoff/useInstalledAgents.test.ts b/packages/app/src/components/handoff/useInstalledAgents.test.ts
index b567bee24..a80e4f9f7 100644
--- a/packages/app/src/components/handoff/useInstalledAgents.test.ts
+++ b/packages/app/src/components/handoff/useInstalledAgents.test.ts
@@ -18,7 +18,7 @@
* tooltip) lands under Playwright coverage.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('useInstalledAgents module surface', () => {
test('exports the hook + classifier + deps factory', async () => {
diff --git a/packages/app/src/components/link-target-intent.test.ts b/packages/app/src/components/link-target-intent.test.ts
index d8e9dff22..0872b5b85 100644
--- a/packages/app/src/components/link-target-intent.test.ts
+++ b/packages/app/src/components/link-target-intent.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveLinkTargetIntent } from './link-target-intent';
describe('resolveLinkTargetIntent', () => {
diff --git a/packages/app/src/components/navigation-targets.test.ts b/packages/app/src/components/navigation-targets.test.ts
index fd42aff56..da8f4c233 100644
--- a/packages/app/src/components/navigation-targets.test.ts
+++ b/packages/app/src/components/navigation-targets.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
deriveKnownFolderPaths,
docNameForNavigationTarget,
diff --git a/packages/app/src/components/ok-blob-logic.test.ts b/packages/app/src/components/ok-blob-logic.test.ts
index 218585e8f..c7e621aec 100644
--- a/packages/app/src/components/ok-blob-logic.test.ts
+++ b/packages/app/src/components/ok-blob-logic.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
FIREWORK_COLORS,
FIREWORK_LEVEL_CONFIG,
diff --git a/packages/app/src/components/page-header-utils.test.ts b/packages/app/src/components/page-header-utils.test.ts
index 4122c20d0..0cae99271 100644
--- a/packages/app/src/components/page-header-utils.test.ts
+++ b/packages/app/src/components/page-header-utils.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolvePageCover, resolvePageIcon } from './page-header-utils';
// ---------------------------------------------------------------------------
diff --git a/packages/app/src/components/prewarm-correlation.test.ts b/packages/app/src/components/prewarm-correlation.test.ts
index bd3c04337..57acb1f49 100644
--- a/packages/app/src/components/prewarm-correlation.test.ts
+++ b/packages/app/src/components/prewarm-correlation.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { getCollector } from '../lib/perf/collector';
import {
__peekPrewarmRecord,
diff --git a/packages/app/src/components/project-switcher-recents.test.ts b/packages/app/src/components/project-switcher-recents.test.ts
index 07f836c46..4fa04c710 100644
--- a/packages/app/src/components/project-switcher-recents.test.ts
+++ b/packages/app/src/components/project-switcher-recents.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import type { RecentProjectEntry } from '@/lib/desktop-bridge-types';
import {
basenameOf,
diff --git a/packages/app/src/components/property-inline-link-tokens.test.ts b/packages/app/src/components/property-inline-link-tokens.test.ts
index 9d6bfad21..ffe5d25ad 100644
--- a/packages/app/src/components/property-inline-link-tokens.test.ts
+++ b/packages/app/src/components/property-inline-link-tokens.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
hasInlineLinks,
type PropertyInlineSegment,
diff --git a/packages/app/src/components/recent-remove-controls.dom.test.tsx b/packages/app/src/components/recent-remove-controls.dom.test.tsx
index 685183f52..66769b758 100644
--- a/packages/app/src/components/recent-remove-controls.dom.test.tsx
+++ b/packages/app/src/components/recent-remove-controls.dom.test.tsx
@@ -1,12 +1,12 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { RecentItemContextMenu, RecentRemoveButton } from './recent-remove-controls';
afterEach(cleanup);
describe('RecentRemoveButton', () => {
test('clicking the × removes exactly that path', () => {
- const onRemoveRecent = mock((_path: string) => {});
+ const onRemoveRecent = vi.fn((_path: string) => {});
render(
<RecentRemoveButton
path="/projects/one"
@@ -27,7 +27,7 @@ describe('RecentRemoveButton', () => {
describe('RecentItemContextMenu', () => {
test('right-click surfaces a Remove item that removes that path', () => {
- const onRemoveRecent = mock((_path: string) => {});
+ const onRemoveRecent = vi.fn((_path: string) => {});
render(
<RecentItemContextMenu
path="/projects/two"
diff --git a/packages/app/src/components/settings/AiToolsSection.dom.test.tsx b/packages/app/src/components/settings/AiToolsSection.dom.test.tsx
index 87e6d1504..2496e2910 100644
--- a/packages/app/src/components/settings/AiToolsSection.dom.test.tsx
+++ b/packages/app/src/components/settings/AiToolsSection.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type {
OkIntegrationsSetRequest,
OkIntegrationsSetResult,
@@ -10,16 +10,16 @@ import type {
} from '@/lib/desktop-bridge-types';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
// Sonner is loaded by the SUT — stub to mute its real toaster.
-const toastError = mock(() => {});
-mock.module('sonner', () => ({
- toast: { error: toastError, info: mock(() => {}), success: mock(() => {}) },
+const toastError = vi.fn(() => {});
+vi.doMock('sonner', () => ({
+ toast: { error: toastError, info: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
const { AiToolsSection } = await import('./AiToolsSection');
diff --git a/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx b/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx
index d3ba4e1a3..73591183f 100644
--- a/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx
+++ b/packages/app/src/components/settings/ColorThemePicker.dom.test.tsx
@@ -1,10 +1,10 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { COLOR_THEMES } from '@/lib/color-themes';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
diff --git a/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsx b/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsx
index b662fafbc..b58121418 100644
--- a/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsx
+++ b/packages/app/src/components/settings/CustomThemeEditor.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { DEFAULT_CUSTOM_SEED } from '@/lib/color-themes';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
@@ -8,15 +8,15 @@ let mergedConfig: { appearance?: { colorTheme?: string; customTheme?: Record<str
{};
const patchCalls: unknown[] = [];
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('next-themes', () => ({ useTheme: () => ({ setTheme: () => {} }) }));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('next-themes', () => ({ useTheme: () => ({ setTheme: () => {} }) }));
+vi.doMock('@/lib/config-context', () => ({
useConfigContextOptional: () => ({ merged: mergedConfig }),
}));
-mock.module('@/lib/use-apply-config-color-theme', () => ({
+vi.doMock('@/lib/use-apply-config-color-theme', () => ({
applyColorThemeToDom: () => {},
}));
diff --git a/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx b/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx
index 5660cc7ef..5b818dacb 100644
--- a/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx
+++ b/packages/app/src/components/settings/EmbeddingsKeySection.dom.test.tsx
@@ -7,10 +7,10 @@
* (no-key / file-key / env), and that Save/Clear call the transport.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import type { SemanticIndexStatus } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { EmbeddingsKeyTransport } from '@/lib/transports/embeddings-key-transport';
import { EmbeddingsKeySection } from './EmbeddingsKeySection';
diff --git a/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx b/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx
index 1698be0c7..e2a07f0b7 100644
--- a/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx
+++ b/packages/app/src/components/settings/LinkPreviewsSection.dom.test.tsx
@@ -9,10 +9,10 @@
* the wrong key.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { Config, ConfigBinding } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Radix Dialog mounts a focus-trap that reaches for DOM globals the jsdom
// preload doesn't expose. Hoist the same shims the sibling settings DOM tests
@@ -40,7 +40,7 @@ let mockProjectLocalConfig: Config | null = null;
let mockProjectLocalSynced = true;
let mockProjectLocalBinding: ConfigBinding | null = null;
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
userBinding: null,
userSynced: false,
diff --git a/packages/app/src/components/settings/OkignoreSection.dom.test.tsx b/packages/app/src/components/settings/OkignoreSection.dom.test.tsx
index 3d7d7153b..acf04eea3 100644
--- a/packages/app/src/components/settings/OkignoreSection.dom.test.tsx
+++ b/packages/app/src/components/settings/OkignoreSection.dom.test.tsx
@@ -1,12 +1,12 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { emitConfigIgnoreNestedError } from '@/lib/config-ignore-nested-error-events';
import { emitConfigValidationRejected } from '@/lib/config-validation-events';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
const toast = {
- error: mock((_message: string, _opts?: unknown) => {}),
+ error: vi.fn((_message: string, _opts?: unknown) => {}),
};
type DragEndHandler = (event: { active: { id: string }; over: { id: string } | null }) => void;
@@ -40,7 +40,7 @@ function installLocalStorage() {
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
<>{(value === 1 ? one : other).replace('#', String(value))}</>
@@ -49,11 +49,11 @@ mock.module('@lingui/react/macro', () => ({
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast,
}));
-mock.module('@dnd-kit/core', () => ({
+vi.doMock('@dnd-kit/core', () => ({
closestCenter: { name: 'closestCenter' },
DndContext: ({ children, onDragEnd }: { children?: ReactNode; onDragEnd?: DragEndHandler }) => {
latestDragEnd = onDragEnd ?? null;
@@ -65,7 +65,7 @@ mock.module('@dnd-kit/core', () => ({
useSensors: (...sensors: unknown[]) => sensors,
}));
-mock.module('@dnd-kit/sortable', () => ({
+vi.doMock('@dnd-kit/sortable', () => ({
SortableContext: ({
children,
items,
@@ -95,7 +95,7 @@ mock.module('@dnd-kit/sortable', () => ({
verticalListSortingStrategy: verticalListSortingStrategyToken,
}));
-mock.module('@dnd-kit/utilities', () => ({
+vi.doMock('@dnd-kit/utilities', () => ({
CSS: {
Transform: {
toString: () => undefined,
@@ -103,7 +103,7 @@ mock.module('@dnd-kit/utilities', () => ({
},
}));
-mock.module('@/components/ui/button', () => ({
+vi.doMock('@/components/ui/button', () => ({
Button: ({
children,
size: _size,
@@ -121,23 +121,23 @@ mock.module('@/components/ui/button', () => ({
),
}));
-mock.module('@/components/ui/input', () => ({
+vi.doMock('@/components/ui/input', () => ({
Input: (props: Record<string, unknown>) => <input {...props} />,
}));
-mock.module('@/components/ui/skeleton', () => ({
+vi.doMock('@/components/ui/skeleton', () => ({
Skeleton: ({ className }: { className?: string }) => (
<div className={className} data-testid="skeleton" />
),
}));
-mock.module('@/components/ui/tooltip', () => ({
+vi.doMock('@/components/ui/tooltip', () => ({
Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
TooltipContent: ({ children }: { children?: ReactNode }) => <div role="tooltip">{children}</div>,
TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({
assetPaths: new Set(['assets/logo.png']),
pageMeta: new Map([
@@ -157,7 +157,7 @@ function createBinding(initialText: string) {
notifyRejection: (error: unknown) => {
for (const listener of rejectionListeners) listener({ error });
},
- patch: mock((next: string) => {
+ patch: vi.fn((next: string) => {
currentText = next;
for (const listener of textListeners) listener(next);
return { ok: true };
diff --git a/packages/app/src/components/settings/OkignoreSection.test.ts b/packages/app/src/components/settings/OkignoreSection.test.ts
index 2b43190d5..1443b4f25 100644
--- a/packages/app/src/components/settings/OkignoreSection.test.ts
+++ b/packages/app/src/components/settings/OkignoreSection.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
derivePreviewPaths,
parseRows,
diff --git a/packages/app/src/components/settings/ProjectAiToolsSection.dom.test.tsx b/packages/app/src/components/settings/ProjectAiToolsSection.dom.test.tsx
index 1eaa91cc1..b00795c3e 100644
--- a/packages/app/src/components/settings/ProjectAiToolsSection.dom.test.tsx
+++ b/packages/app/src/components/settings/ProjectAiToolsSection.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type {
OkProjectIntegrationsSetRequest,
OkProjectIntegrationsSetResult,
@@ -10,15 +10,15 @@ import type {
} from '@/lib/desktop-bridge-types';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-const toastError = mock(() => {});
-mock.module('sonner', () => ({
- toast: { error: toastError, info: mock(() => {}), success: mock(() => {}) },
+const toastError = vi.fn(() => {});
+vi.doMock('sonner', () => ({
+ toast: { error: toastError, info: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
const { ProjectAiToolsSection } = await import('./ProjectAiToolsSection');
diff --git a/packages/app/src/components/settings/SearchSection.dom.test.tsx b/packages/app/src/components/settings/SearchSection.dom.test.tsx
index f217b26da..08838a611 100644
--- a/packages/app/src/components/settings/SearchSection.dom.test.tsx
+++ b/packages/app/src/components/settings/SearchSection.dom.test.tsx
@@ -7,7 +7,6 @@
* gate, the disable-is-immediate path, and the coverage / needs-a-key panel.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import {
type Config,
type ConfigBinding,
@@ -16,6 +15,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Radix Dialog mounts a focus-trap that reaches for DOM globals the jsdom
// preload doesn't expose. Hoist the same shims the sibling settings DOM tests
@@ -43,7 +43,7 @@ let mockProjectLocalConfig: Config | null = null;
let mockProjectLocalSynced = true;
let mockProjectLocalBinding: ConfigBinding | null = null;
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
userBinding: null,
userSynced: false,
diff --git a/packages/app/src/components/settings/SettingsDialogBody.test.ts b/packages/app/src/components/settings/SettingsDialogBody.test.ts
index 1070e741e..7c17a1079 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.test.ts
+++ b/packages/app/src/components/settings/SettingsDialogBody.test.ts
@@ -6,7 +6,7 @@
* - `SettingsDialogBody.sections.dom.test.tsx` for section dispatch, Sync, Okignore, and Integrations wiring.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('SettingsDialogBody module', () => {
test('exports SettingsDialogBody component', async () => {
diff --git a/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx
index e113047bd..befcaeebc 100644
--- a/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx
@@ -8,8 +8,9 @@
* contained, the app survives. Throw injection follows the MaybeThrow
* (precedent #43(d)); invocation via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SettingsDialogErrorBoundary } from './SettingsDialogErrorBoundary';
let throwError: Error | null = null;
@@ -20,11 +21,11 @@ function MaybeThrow() {
}
describe('SettingsDialogErrorBoundary (Tier-3 mount)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
throwError = null;
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx
index dd6638928..01a435309 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.link-previews.dom.test.tsx
@@ -8,7 +8,7 @@
* keeps the item.
*
* jsdom's window.location is unforgeable, so the test stubs the
- * `isFileProtocolPage` helper seam instead — the same mock.module capability
+ * `isFileProtocolPage` helper seam instead — the same vi.doMock capability
* faking the terminal desktop-only test uses for the Electron bridge.
*/
diff --git a/packages/app/src/components/settings/SettingsDialogShell.test.ts b/packages/app/src/components/settings/SettingsDialogShell.test.ts
index 8a5ee80af..28bac811c 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.test.ts
+++ b/packages/app/src/components/settings/SettingsDialogShell.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('SettingsDialogShell module', () => {
test('exports SettingsDialogShell component', async () => {
diff --git a/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx b/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
index 562a69aa1..4f4fe92f3 100644
--- a/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
+++ b/packages/app/src/components/settings/SkillTargetsPicker.dom.test.tsx
@@ -6,12 +6,12 @@
* to `/api/skill-targets`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => children,
useLingui: () => ({
@@ -27,8 +27,8 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('sonner', () => ({
- toast: { error: mock(() => {}), info: mock(() => {}), success: mock(() => {}) },
+vi.doMock('sonner', () => ({
+ toast: { error: vi.fn(() => {}), info: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
const { SkillTargetsPicker } = await import('./SkillTargetsPicker');
@@ -41,7 +41,7 @@ afterEach(() => {
describe('SkillTargetsPicker', () => {
test('renders a checkbox per editor reflecting the committed set', async () => {
- global.fetch = mock(async () => ({
+ global.fetch = vi.fn(async () => ({
ok: true,
status: 200,
json: async () => ({ targets: ['claude'], configured: true }),
@@ -58,7 +58,7 @@ describe('SkillTargetsPicker', () => {
test('toggling an editor PUTs the updated target set', async () => {
const calls: Array<{ url: string; method?: string; body?: string }> = [];
- global.fetch = mock(async (input: RequestInfo | URL, init?: RequestInit) => {
+ global.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input.toString();
calls.push({ url, method: init?.method, body: init?.body as string | undefined });
if (init?.method === 'PUT') {
diff --git a/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx b/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
index e4ac7039a..e1b73786c 100644
--- a/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
+++ b/packages/app/src/components/settings/SkillsManagerSection.dom.test.tsx
@@ -11,13 +11,13 @@
* renderers, same as the sibling .dom.test.tsx files.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { SkillsListSuccess } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => children,
useLingui: () => ({
@@ -33,18 +33,18 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('sonner', () => ({
- toast: { error: mock(() => {}), info: mock(() => {}), success: mock(() => {}) },
+vi.doMock('sonner', () => ({
+ toast: { error: vi.fn(() => {}), info: vi.fn(() => {}), success: vi.fn(() => {}) },
}));
// The row's "Open with AI" menu pulls config / workspace / install-detection
// context this section test doesn't provide; stub it (handoff is covered by
// its own tests + useHandoffDispatch.test.ts).
-mock.module('@/components/handoff/OpenInAgentMenu', () => ({
+vi.doMock('@/components/handoff/OpenInAgentMenu', () => ({
OpenInAgentMenu: () => null,
}));
// The section opens skills as editor tabs via DocumentContext; this list test
// renders the section standalone (no provider), so stub the open hook.
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({ openDocument: () => {} }),
}));
@@ -66,7 +66,7 @@ const EMPTY_TARGETS = { targets: [], configured: false };
function routeFetch(
skillsResponse: () => { ok: boolean; status: number; json: () => Promise<unknown> },
) {
- global.fetch = mock(async (input: RequestInfo | URL) => {
+ global.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input.toString();
if (url.includes('/api/skill-targets')) {
return { ok: true, status: 200, json: async () => EMPTY_TARGETS };
diff --git a/packages/app/src/components/settings/TerminalSection.dom.test.tsx b/packages/app/src/components/settings/TerminalSection.dom.test.tsx
index 54a2416bc..521e61524 100644
--- a/packages/app/src/components/settings/TerminalSection.dom.test.tsx
+++ b/packages/app/src/components/settings/TerminalSection.dom.test.tsx
@@ -6,10 +6,11 @@
* are mocked; the real shadcn Switch is rendered. Two switches now exist, so
* every query is scoped by test id.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
type ConsentState = { enabled: boolean | null; synced: boolean };
type Writer = ((enabled: boolean) => { ok: true } | { ok: false; error: string }) | null;
@@ -29,7 +30,7 @@ const userPatchCalls: unknown[] = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -38,16 +39,16 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: { error: () => {} },
}));
-mock.module('@/hooks/use-terminal-enabled', () => ({
+vi.doMock('@/hooks/use-terminal-enabled', () => ({
useTerminalConsentState: () => consentState,
useTerminalEnabledWriter: () => writerImpl,
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({ userConfig, userSynced, userBinding }),
}));
diff --git a/packages/app/src/components/settings/lint-plugin-meta.test.ts b/packages/app/src/components/settings/lint-plugin-meta.test.ts
index b626763f2..6a6637af6 100644
--- a/packages/app/src/components/settings/lint-plugin-meta.test.ts
+++ b/packages/app/src/components/settings/lint-plugin-meta.test.ts
@@ -8,8 +8,8 @@
* this covers the remaining array.
*/
-import { describe, expect, test } from 'bun:test';
import { LINT_PLUGINS } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { LINT_PLUGIN_META } from './lint-plugin-meta.ts';
describe('LINT_PLUGIN_META ⟷ plugin registry', () => {
diff --git a/packages/app/src/components/settings/markdownlint-rule-toggle.test.ts b/packages/app/src/components/settings/markdownlint-rule-toggle.test.ts
index 36e2ec59b..ef35af0f6 100644
--- a/packages/app/src/components/settings/markdownlint-rule-toggle.test.ts
+++ b/packages/app/src/components/settings/markdownlint-rule-toggle.test.ts
@@ -6,8 +6,8 @@
* value computation.
*/
-import { describe, expect, test } from 'bun:test';
import { MARKDOWNLINT_RULE_CATALOG } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
governingRuleValue,
isRuleModified,
diff --git a/packages/app/src/components/settings/okignore-doc.test.ts b/packages/app/src/components/settings/okignore-doc.test.ts
index 8a6152379..1a2384cc0 100644
--- a/packages/app/src/components/settings/okignore-doc.test.ts
+++ b/packages/app/src/components/settings/okignore-doc.test.ts
@@ -6,7 +6,7 @@
* and the no-edit path must be a no-op.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
appendPattern,
editPatternAt,
diff --git a/packages/app/src/components/settings/okignore-preview.test.ts b/packages/app/src/components/settings/okignore-preview.test.ts
index 61ac12482..a36637886 100644
--- a/packages/app/src/components/settings/okignore-preview.test.ts
+++ b/packages/app/src/components/settings/okignore-preview.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetPreviewCacheForTests,
__testing_getCacheSize,
diff --git a/packages/app/src/components/settings/okignore-warnings.test.ts b/packages/app/src/components/settings/okignore-warnings.test.ts
index ae87dfc20..7d9fe1157 100644
--- a/packages/app/src/components/settings/okignore-warnings.test.ts
+++ b/packages/app/src/components/settings/okignore-warnings.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { checkHeuristicWarnings, WARNING_MESSAGES } from './okignore-warnings';
describe('checkHeuristicWarnings — quiet on uninteresting input', () => {
diff --git a/packages/app/src/components/settings/rule-option-field.dom.test.tsx b/packages/app/src/components/settings/rule-option-field.dom.test.tsx
index 40aa87e01..652bcfbc3 100644
--- a/packages/app/src/components/settings/rule-option-field.dom.test.tsx
+++ b/packages/app/src/components/settings/rule-option-field.dom.test.tsx
@@ -6,10 +6,11 @@
* union-typed `lines_above`/`lines_below` must fall back to the read-only
* chip while its sibling `include_front_matter` stays editable.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { MARKDOWNLINT_RULE_CATALOG, type RuleOptionSpec } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { RULE_OPTION_WIDGET_OVERRIDES, RuleOptionField } from './rule-option-field';
// Radix primitives reach for pointer-capture and scroll APIs the jsdom
@@ -46,7 +47,7 @@ afterEach(() => {
describe('RuleOptionField — boolean', () => {
test('renders a Switch seeded from the spec default and emits the flipped boolean', async () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD022"
@@ -64,7 +65,7 @@ describe('RuleOptionField — boolean', () => {
});
test('a set value wins over the spec default and toggles back off', async () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD022"
@@ -159,7 +160,7 @@ describe('RuleOptionField — unsupported fallback (MD022)', () => {
describe('RuleOptionField — integer', () => {
test('shows the spec default when unset and emits the typed number on blur', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD013"
@@ -177,7 +178,7 @@ describe('RuleOptionField — integer', () => {
});
test('a set value wins over the default and Enter commits', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD013"
@@ -195,7 +196,7 @@ describe('RuleOptionField — integer', () => {
test('honors the schema minimum by clamping the committed value', () => {
// MD013 line_length carries minimum 1 in the vendored schema.
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD013"
@@ -213,7 +214,7 @@ describe('RuleOptionField — integer', () => {
});
test('an emptied input reverts to the committed value without emitting', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD013"
@@ -230,7 +231,7 @@ describe('RuleOptionField — integer', () => {
});
test('re-committing the unchanged value does not emit', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD013"
@@ -247,7 +248,7 @@ describe('RuleOptionField — integer', () => {
describe('RuleOptionField — string', () => {
test('shows the spec default when unset and emits the edited string on blur', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD001"
@@ -265,7 +266,7 @@ describe('RuleOptionField — string', () => {
});
test('an emptied string commits (a meaningful markdownlint value)', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD001"
@@ -283,7 +284,7 @@ describe('RuleOptionField — string', () => {
describe('RuleOptionField — enum', () => {
test('renders a Select showing the effective value and emits the chosen literal', async () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD003"
@@ -328,7 +329,7 @@ describe('RuleOptionField — string-array', () => {
test('renders existing entries as pills and commits grammar-free values verbatim', () => {
// MD043 headings hold values like `## Summary` — spaces and a leading
// `#` must survive (the frontmatter tag grammar would reject/mangle).
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD043"
@@ -348,7 +349,7 @@ describe('RuleOptionField — string-array', () => {
});
test('removing a pill emits the shortened array', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
render(
<RuleOptionField
ruleId="MD043"
diff --git a/packages/app/src/components/settings/schema-walker.test.ts b/packages/app/src/components/settings/schema-walker.test.ts
index 99613784c..bdce35e87 100644
--- a/packages/app/src/components/settings/schema-walker.test.ts
+++ b/packages/app/src/components/settings/schema-walker.test.ts
@@ -4,8 +4,8 @@
* the published schema and the form's introspection surfaces here.
*/
-import { describe, expect, test } from 'bun:test';
import { ConfigSchema } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
buildPatch,
getEnumOptions,
diff --git a/packages/app/src/components/settings/use-config-form.dom.test.tsx b/packages/app/src/components/settings/use-config-form.dom.test.tsx
index 76fe1acbf..0d7ed563e 100644
--- a/packages/app/src/components/settings/use-config-form.dom.test.tsx
+++ b/packages/app/src/components/settings/use-config-form.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { Config, ConfigBinding, ConfigPatch } from '@inkeep/open-knowledge-core';
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { useConfigForm } from './use-config-form';
type ConfigListener = (next: Config) => void;
let subscribeListener: ConfigListener | null = null;
-let unsubscribeMock = mock(() => {});
-let patchMock = mock((_patch: ConfigPatch) => ({
+let unsubscribeMock = vi.fn(() => {});
+let patchMock = vi.fn((_patch: ConfigPatch) => ({
ok: true as const,
effective: {} as Config,
appliedPaths: ['appearance.theme'],
@@ -49,8 +49,8 @@ function Harness({ binding }: { binding: ConfigBinding }) {
describe('useConfigForm runtime wiring', () => {
beforeEach(() => {
subscribeListener = null;
- unsubscribeMock = mock(() => {});
- patchMock = mock((_patch: ConfigPatch) => ({
+ unsubscribeMock = vi.fn(() => {});
+ patchMock = vi.fn((_patch: ConfigPatch) => ({
ok: true as const,
effective: {} as Config,
appliedPaths: ['appearance.theme'],
diff --git a/packages/app/src/components/settings/use-config-form.test.ts b/packages/app/src/components/settings/use-config-form.test.ts
index 0c286a483..50051fabf 100644
--- a/packages/app/src/components/settings/use-config-form.test.ts
+++ b/packages/app/src/components/settings/use-config-form.test.ts
@@ -16,13 +16,13 @@
* contract.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type {
Config,
ConfigBindingPatchResult,
ConfigPatch,
ConfigValidationError,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import {
type ApplyExternalUpdateForm,
applyExternalUpdate,
@@ -38,7 +38,7 @@ import {
describe('applyExternalUpdate', () => {
test('calls form.reset with keepDirtyValues + keepDirty + keepTouched', () => {
- const reset = mock();
+ const reset = vi.fn();
const form: ApplyExternalUpdateForm<Config> = {
reset: reset as unknown as ApplyExternalUpdateForm<Config>['reset'],
};
@@ -67,15 +67,15 @@ interface MockedRunCommitForm extends RunCommitForm<Config> {
function createMockForm(getValuesImpl: (name: string) => unknown): {
form: MockedRunCommitForm;
- setError: ReturnType<typeof mock>;
- clearErrors: ReturnType<typeof mock>;
- resetField: ReturnType<typeof mock>;
- getValues: ReturnType<typeof mock>;
+ setError: ReturnType<typeof vi.fn>;
+ clearErrors: ReturnType<typeof vi.fn>;
+ resetField: ReturnType<typeof vi.fn>;
+ getValues: ReturnType<typeof vi.fn>;
} {
- const setError = mock();
- const clearErrors = mock();
- const resetField = mock();
- const getValues = mock(getValuesImpl);
+ const setError = vi.fn();
+ const clearErrors = vi.fn();
+ const resetField = vi.fn();
+ const getValues = vi.fn(getValuesImpl);
const form: MockedRunCommitForm = {
getValues: getValues as unknown as MockedRunCommitForm['getValues'],
setError: setError as unknown as MockedRunCommitForm['setError'],
@@ -87,9 +87,9 @@ function createMockForm(getValuesImpl: (name: string) => unknown): {
function createMockBinding(patchImpl: (patch: ConfigPatch) => ConfigBindingPatchResult): {
binding: RunCommitBinding;
- patch: ReturnType<typeof mock>;
+ patch: ReturnType<typeof vi.fn>;
} {
- const patch = mock(patchImpl);
+ const patch = vi.fn(patchImpl);
const binding: RunCommitBinding = {
patch: patch as unknown as RunCommitBinding['patch'],
};
diff --git a/packages/app/src/components/sidebar-drag-payload.test.ts b/packages/app/src/components/sidebar-drag-payload.test.ts
index c75daa2b4..54fee8523 100644
--- a/packages/app/src/components/sidebar-drag-payload.test.ts
+++ b/packages/app/src/components/sidebar-drag-payload.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { FileEntry } from '@/components/file-tree-utils';
import { sidebarDragPayloadForTreePath } from './sidebar-drag-payload';
diff --git a/packages/app/src/components/sidebar-hover-prewarm.test.ts b/packages/app/src/components/sidebar-hover-prewarm.test.ts
index bd85d49e8..6b3689ce5 100644
--- a/packages/app/src/components/sidebar-hover-prewarm.test.ts
+++ b/packages/app/src/components/sidebar-hover-prewarm.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { getCollector } from '../lib/perf/collector';
import { __peekPrewarmRecord, __resetPrewarmCorrelation } from './prewarm-correlation';
import {
@@ -20,7 +20,7 @@ afterEach(() => {
describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
test('hover → prewarm fires after 80ms intent window', async () => {
- const prewarm = mock((docName: string): string | null => {
+ const prewarm = vi.fn((docName: string): string | null => {
expect(docName).toBe('doc-a');
return null;
});
@@ -31,7 +31,7 @@ describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
});
test('quick mouse trail (dismiss before 80ms) fires no prewarm', async () => {
- const prewarm = mock((): string | null => null);
+ const prewarm = vi.fn((): string | null => null);
scheduleHoverPrewarm('doc-a', prewarm);
// Mouse leaves after 30ms, well before the 80ms intent threshold.
await wait(30);
@@ -41,7 +41,7 @@ describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
});
test('system docs are refused (__system__)', () => {
- const prewarm = mock((): string | null => null);
+ const prewarm = vi.fn((): string | null => null);
scheduleHoverPrewarm('__system__', prewarm);
// No timer scheduled — cancel is a no-op.
cancelHoverPrewarm('__system__');
@@ -50,7 +50,7 @@ describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
});
test('already-prewarmed doc does not re-fire', async () => {
- const prewarm = mock(() => null);
+ const prewarm = vi.fn(() => null);
scheduleHoverPrewarm('doc-b', prewarm);
await wait(120);
expect(prewarm).toHaveBeenCalledTimes(1);
@@ -61,7 +61,7 @@ describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
});
test('successful prewarm emits ok/sidebar/prewarm-success and records the correlation seed', async () => {
- const prewarm = mock(() => 'pool-event-x');
+ const prewarm = vi.fn(() => 'pool-event-x');
scheduleHoverPrewarm('doc-c', prewarm);
await wait(120);
expect(prewarm).toHaveBeenCalledTimes(1);
@@ -76,7 +76,7 @@ describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
});
test('null poolEventId from prewarm callback is treated as failure (no success mark)', async () => {
- const prewarm = mock(() => null);
+ const prewarm = vi.fn(() => null);
scheduleHoverPrewarm('doc-d', prewarm);
await wait(120);
expect(prewarm).toHaveBeenCalledTimes(1);
@@ -99,7 +99,7 @@ describe('sidebar-hover-prewarm (review Major #7 + V2 FR12 Option G)', () => {
// notifications. Pattern B test — real failure-inducing input
// through the public interface.
const failureMessage = 'synthetic ProviderPool ctor failure';
- const prewarm = mock(() => {
+ const prewarm = vi.fn(() => {
throw new Error(failureMessage);
});
let uncaughtCount = 0;
diff --git a/packages/app/src/components/target-navigation-intent.test.ts b/packages/app/src/components/target-navigation-intent.test.ts
index 47844a16f..ac0a78d65 100644
--- a/packages/app/src/components/target-navigation-intent.test.ts
+++ b/packages/app/src/components/target-navigation-intent.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveTargetNavigationIntent } from './target-navigation-intent';
describe('resolveTargetNavigationIntent', () => {
diff --git a/packages/app/src/components/terminal-link-provider.test.ts b/packages/app/src/components/terminal-link-provider.test.ts
index 4044f3d58..d54e8b9ae 100644
--- a/packages/app/src/components/terminal-link-provider.test.ts
+++ b/packages/app/src/components/terminal-link-provider.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, mock, test } from 'bun:test';
import type { ILink, ILinkProvider } from '@xterm/xterm';
+import { describe, expect, test, vi } from 'vitest';
import type { CheckTargetExistsResult } from '@/lib/desktop-bridge-types';
import type { PageListCacheSnapshot } from '../editor/page-list-cache';
import {
@@ -16,7 +16,7 @@ function snapshot(partial: Partial<PageListCacheSnapshot> = {}): PageListCacheSn
function makeProvider(overrides: Partial<TerminalFileLinkProviderDeps> = {}) {
const activated: TerminalLinkTarget[] = [];
- const checkTargetExists = mock(
+ const checkTargetExists = vi.fn(
async (_kind: 'doc' | 'folder', _path: string): Promise<CheckTargetExistsResult> => 'exists',
);
const deps: TerminalFileLinkProviderDeps = {
@@ -159,7 +159,7 @@ describe('createTerminalFileLinkProvider', () => {
// `packages/app` (no trailing slash, no extension) classifies as an asset, so
// the file probe (`checkTargetExists('doc')` → isFile) misses on a real
// directory. The provider retries as a folder rather than dropping the link.
- const checkTargetExists = mock(
+ const checkTargetExists = vi.fn(
async (kind: 'doc' | 'folder'): Promise<CheckTargetExistsResult> =>
kind === 'folder' ? 'exists' : 'missing',
);
@@ -178,7 +178,7 @@ describe('createTerminalFileLinkProvider', () => {
test('a missing path WITH an extension does not waste a folder retry', async () => {
// The folder fallback is gated on extension-less tokens; `gone/file.md` is a
// file by shape, so a miss is final (one probe, no folder retry).
- const checkTargetExists = mock(async (): Promise<CheckTargetExistsResult> => 'missing');
+ const checkTargetExists = vi.fn(async (): Promise<CheckTargetExistsResult> => 'missing');
const { provider } = makeProvider({
readLogicalLine: row('open gone/file.md'),
checkTargetExists,
diff --git a/packages/app/src/components/terminal-links.test.ts b/packages/app/src/components/terminal-links.test.ts
index 15166ccef..f870118c8 100644
--- a/packages/app/src/components/terminal-links.test.ts
+++ b/packages/app/src/components/terminal-links.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { PageListCacheSnapshot } from '../editor/page-list-cache';
import {
classifyTarget,
diff --git a/packages/app/src/components/terminal-render-flush.test.ts b/packages/app/src/components/terminal-render-flush.test.ts
index a3f800c0a..b261dad0c 100644
--- a/packages/app/src/components/terminal-render-flush.test.ts
+++ b/packages/app/src/components/terminal-render-flush.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { createSameFrameRepaint, type RepaintableTerminal } from './terminal-render-flush';
function makeTerm(withDebouncer: boolean) {
- const refresh = mock((_start: number, _end: number) => {});
- const innerRefresh = mock(() => {});
+ const refresh = vi.fn((_start: number, _end: number) => {});
+ const innerRefresh = vi.fn(() => {});
const term = {
rows: 24,
refresh,
@@ -17,7 +17,7 @@ function makeTerm(withDebouncer: boolean) {
describe('createSameFrameRepaint', () => {
test('queues a full-viewport refresh then flushes the render debouncer synchronously', () => {
const { term, refresh, innerRefresh } = makeTerm(true);
- const warn = mock((_m: string) => {});
+ const warn = vi.fn((_m: string) => {});
const repaint = createSameFrameRepaint(term, warn);
repaint();
expect(refresh).toHaveBeenCalledWith(0, 23);
@@ -27,7 +27,7 @@ describe('createSameFrameRepaint', () => {
test('warns once (not per call) when an xterm bump moves the debouncer internal', () => {
const { term, refresh } = makeTerm(false);
- const warn = mock((_m: string) => {});
+ const warn = vi.fn((_m: string) => {});
const repaint = createSameFrameRepaint(term, warn);
repaint();
repaint();
diff --git a/packages/app/src/components/terminal-resize-throttle.test.ts b/packages/app/src/components/terminal-resize-throttle.test.ts
index 26b5a2383..9a5dc1357 100644
--- a/packages/app/src/components/terminal-resize-throttle.test.ts
+++ b/packages/app/src/components/terminal-resize-throttle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createResizeThrottle, type ResizeThrottleTimers } from './terminal-resize-throttle';
function makeHarness(intervalMs = 100) {
diff --git a/packages/app/src/components/terminal-session-registry.test.ts b/packages/app/src/components/terminal-session-registry.test.ts
index 244d178af..bea4941fe 100644
--- a/packages/app/src/components/terminal-session-registry.test.ts
+++ b/packages/app/src/components/terminal-session-registry.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import {
_clearTerminalSessionRegistry,
findIdleMatchingSession,
diff --git a/packages/app/src/components/terminal-theme.test.ts b/packages/app/src/components/terminal-theme.test.ts
index a97eb39e5..021811457 100644
--- a/packages/app/src/components/terminal-theme.test.ts
+++ b/packages/app/src/components/terminal-theme.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
computeLiveXtermTheme,
XTERM_DARK_THEME,
diff --git a/packages/app/src/components/terminal-wheel.test.ts b/packages/app/src/components/terminal-wheel.test.ts
index 373fc946c..74260ad76 100644
--- a/packages/app/src/components/terminal-wheel.test.ts
+++ b/packages/app/src/components/terminal-wheel.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
nextWheelReports,
sgrWheelReport,
diff --git a/packages/app/src/components/ui/command.dom.test.tsx b/packages/app/src/components/ui/command.dom.test.tsx
index cd4ec3092..ceb859be0 100644
--- a/packages/app/src/components/ui/command.dom.test.tsx
+++ b/packages/app/src/components/ui/command.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
diff --git a/packages/app/src/components/ui/context-menu.dom.test.tsx b/packages/app/src/components/ui/context-menu.dom.test.tsx
index d5a95a4af..3a3da65ad 100644
--- a/packages/app/src/components/ui/context-menu.dom.test.tsx
+++ b/packages/app/src/components/ui/context-menu.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { act } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
diff --git a/packages/app/src/components/ui/dialog.dom.test.tsx b/packages/app/src/components/ui/dialog.dom.test.tsx
index 2ead37a2f..4533aca5b 100644
--- a/packages/app/src/components/ui/dialog.dom.test.tsx
+++ b/packages/app/src/components/ui/dialog.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
diff --git a/packages/app/src/components/ui/dropdown-menu.dom.test.tsx b/packages/app/src/components/ui/dropdown-menu.dom.test.tsx
index ba2d122ba..18f1c389d 100644
--- a/packages/app/src/components/ui/dropdown-menu.dom.test.tsx
+++ b/packages/app/src/components/ui/dropdown-menu.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
import { act } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
diff --git a/packages/app/src/components/ui/form.test.ts b/packages/app/src/components/ui/form.test.ts
index 87d0907ec..a1a53b9d0 100644
--- a/packages/app/src/components/ui/form.test.ts
+++ b/packages/app/src/components/ui/form.test.ts
@@ -4,7 +4,7 @@
* `settings/use-config-form.test.ts` and `settings/SettingsDialog.test.ts`.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('ui/form module', () => {
test('exports the shadcn Form primitives as functions', async () => {
diff --git a/packages/app/src/components/ui/popover.dom.test.tsx b/packages/app/src/components/ui/popover.dom.test.tsx
index 7903b4d99..55751b773 100644
--- a/packages/app/src/components/ui/popover.dom.test.tsx
+++ b/packages/app/src/components/ui/popover.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
import { act } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
diff --git a/packages/app/src/components/ui/select.dom.test.tsx b/packages/app/src/components/ui/select.dom.test.tsx
index 19f5637dd..67aae96cb 100644
--- a/packages/app/src/components/ui/select.dom.test.tsx
+++ b/packages/app/src/components/ui/select.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
import { act } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
diff --git a/packages/app/src/components/ui/sheet.dom.test.tsx b/packages/app/src/components/ui/sheet.dom.test.tsx
index aa553da99..c972cc3ca 100644
--- a/packages/app/src/components/ui/sheet.dom.test.tsx
+++ b/packages/app/src/components/ui/sheet.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
diff --git a/packages/app/src/components/ui/sidebar.dom.test.tsx b/packages/app/src/components/ui/sidebar.dom.test.tsx
index f1c9bd4e1..fee3d3010 100644
--- a/packages/app/src/components/ui/sidebar.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.dom.test.tsx
@@ -1,10 +1,10 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
diff --git a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
index f503568c1..058620fe5 100644
--- a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
@@ -15,8 +15,9 @@
*
* Substrate: jsdom (precedent #43); invocation via `bunx turbo run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { readPins, SIDEBAR_PINS_KEY } from '@/lib/sidebar-pin-store';
import {
Sidebar,
diff --git a/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx b/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx
index ae53fd883..e70b57053 100644
--- a/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx
@@ -15,8 +15,9 @@
* desktop width so `toggleSidebar` takes the `setOpen` branch and the derived
* state is `expanded` → `collapsed` on a single toggle.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { SIDEBAR_PINS_KEY } from '@/lib/sidebar-pin-store';
import { SidebarProvider, useSidebar } from './sidebar';
diff --git a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx b/packages/app/src/components/ui/tag-pill-input.dom.test.tsx
index ae1349cfb..4d74f0ac4 100644
--- a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx
+++ b/packages/app/src/components/ui/tag-pill-input.dom.test.tsx
@@ -8,9 +8,10 @@
* satisfy the "Never assert raw source text for JSX / classes /
* imports / hooks / props" rule for the grammar-gate additions.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render } from '@testing-library/react';
import { createRef } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { TagPillInput } from './tag-pill-input';
@@ -23,7 +24,7 @@ interface RenderOpts {
}
function renderInput(opts: RenderOpts = {}) {
- const onChange = opts.onChange ?? mock(() => {});
+ const onChange = opts.onChange ?? vi.fn(() => {});
const result = render(
<TooltipProvider>
<TagPillInput
@@ -75,7 +76,7 @@ describe('TagPillInput — input-side grammar gate', () => {
});
test('Enter on invalid input does not commit; draft + role="alert" helper appear', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'bad!' } });
@@ -91,7 +92,7 @@ describe('TagPillInput — input-side grammar gate', () => {
});
test('Enter on valid input commits + clears draft + clears any prior rejection state', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'showcase' } });
@@ -103,7 +104,7 @@ describe('TagPillInput — input-side grammar gate', () => {
});
test('comma, Tab, and blur commit non-empty drafts while empty comma is swallowed', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
@@ -125,7 +126,7 @@ describe('TagPillInput — input-side grammar gate', () => {
});
test('Backspace on an empty draft removes the last pill', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ value: ['alpha', 'beta'], onChange });
const input = container.querySelector('input') as HTMLInputElement;
@@ -138,7 +139,7 @@ describe('TagPillInput — input-side grammar gate', () => {
test('Enter on a digit-leading tag like a year (2026) commits', () => {
// Digit-leading tags are valid in frontmatter even though the inline
// `#tag` surface rejects them.
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: '2026' } });
@@ -160,7 +161,7 @@ describe('TagPillInput — input-side grammar gate', () => {
});
test('Escape clears rejection without committing', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'bad!' } });
@@ -178,7 +179,7 @@ describe('TagPillInput — input-side grammar gate', () => {
// YAML parse would silently re-normalize the value (drifting
// display) and the dedup check would miss a `#showcase` / `showcase`
// pair.
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: '#showcase' } });
@@ -193,7 +194,7 @@ describe('TagPillInput — input-side grammar gate', () => {
// Before the normalization fix, an author with `showcase` already
// in the list could re-add `#showcase` (the raw dedup check would
// miss it). Pin post-normalize dedup so this regression stays caught.
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ value: ['showcase'], onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: '#showcase' } });
@@ -204,7 +205,7 @@ describe('TagPillInput — input-side grammar gate', () => {
});
test('duplicate tag silently dedupes (no commit, no rejection state)', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ value: ['showcase'], onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: 'showcase' } });
@@ -221,7 +222,7 @@ describe('TagPillInput — free-text grammar', () => {
});
function renderFreeText(opts: RenderOpts = {}) {
- const onChange = opts.onChange ?? mock(() => {});
+ const onChange = opts.onChange ?? vi.fn(() => {});
const result = render(
<TooltipProvider>
<TagPillInput value={opts.value ?? []} onChange={onChange} grammar="free-text" />
@@ -234,7 +235,7 @@ describe('TagPillInput — free-text grammar', () => {
// markdownlint option lists hold values like MD043's `## Summary`:
// spaces fail the tag grammar and the leading `#` would be stripped
// by the frontmatter normalization. Free-text must preserve both.
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderFreeText({ onChange });
const input = container.querySelector('input') as HTMLInputElement;
fireEvent.change(input, { target: { value: '## Summary' } });
@@ -251,7 +252,7 @@ describe('TagPillInput — free-text grammar', () => {
});
test('still trims, drops empty drafts, and dedupes', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderFreeText({ value: ['*'], onChange });
const input = container.querySelector('input') as HTMLInputElement;
@@ -343,7 +344,7 @@ describe('TagPillInput — a11y id wiring (regression: PR #1288 review findings)
});
test('remove buttons include the tag value in their accessible names', () => {
- const onChange = mock(() => {});
+ const onChange = vi.fn(() => {});
const { container } = renderInput({ value: ['showcase', 'docs'], onChange });
fireEvent.click(
diff --git a/packages/app/src/components/ui/toast-outside-guard.test.ts b/packages/app/src/components/ui/toast-outside-guard.test.ts
index c8db9d078..0650c2658 100644
--- a/packages/app/src/components/ui/toast-outside-guard.test.ts
+++ b/packages/app/src/components/ui/toast-outside-guard.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { ignoreToastInteractOutside } from './toast-outside-guard';
// The guard's only DOM touch is `event.target.closest('[data-sonner-toaster]')`,
@@ -6,7 +6,7 @@ import { ignoreToastInteractOutside } from './toast-outside-guard';
type GuardEvent = Parameters<ReturnType<typeof ignoreToastInteractOutside>>[0];
function makeEvent(insideToaster: boolean) {
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
const event = {
target: {
closest: (selector: string) =>
@@ -19,7 +19,7 @@ function makeEvent(insideToaster: boolean) {
describe('ignoreToastInteractOutside', () => {
test('interaction inside the toaster is neutralized and does not reach the consumer', () => {
- const consumer = mock(() => {});
+ const consumer = vi.fn(() => {});
const { event, preventDefault } = makeEvent(true);
ignoreToastInteractOutside(consumer)(event);
@@ -29,7 +29,7 @@ describe('ignoreToastInteractOutside', () => {
});
test('interaction outside the toaster falls through to the consumer untouched', () => {
- const consumer = mock(() => {});
+ const consumer = vi.fn(() => {});
const { event, preventDefault } = makeEvent(false);
ignoreToastInteractOutside(consumer)(event);
diff --git a/packages/app/src/components/ui/tooltip.dom.test.tsx b/packages/app/src/components/ui/tooltip.dom.test.tsx
index 724832d7e..7c94a5504 100644
--- a/packages/app/src/components/ui/tooltip.dom.test.tsx
+++ b/packages/app/src/components/ui/tooltip.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { act } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
expectVisualClassTokens,
expectVisualClassTokensAbsent,
diff --git a/packages/app/src/editor/ComposerMentionInput.dom.test.tsx b/packages/app/src/editor/ComposerMentionInput.dom.test.tsx
index 2aee78574..1f1f2b181 100644
--- a/packages/app/src/editor/ComposerMentionInput.dom.test.tsx
+++ b/packages/app/src/editor/ComposerMentionInput.dom.test.tsx
@@ -11,11 +11,12 @@
* active-editor registry, so `getEditorForDoc` keeps returning the real
* document editor (which selection-as-passage reads from).
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import type { Content, JSONContent } from '@tiptap/core';
import { Editor } from '@tiptap/core';
import { createRef } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { fileEntryPathIconToSvgString } from '@/components/file-entry-icon';
import { getEditorForDoc, registerEditor, unregisterEditor } from './active-editor';
import { ComposerMentionInput, type ComposerMentionInputHandle } from './ComposerMentionInput';
@@ -38,12 +39,12 @@ function mentionNode(path: string, label = path): Content {
return { type: 'composerMention', attrs: { path, label } };
}
-let consoleErrorSpy: ReturnType<typeof spyOn>;
+let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// The editor's async mount emits act() warnings under jsdom; real failures
// still surface as missing-element assertion failures.
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
@@ -126,7 +127,7 @@ describe('ComposerMentionInput (component)', () => {
});
test('Enter calls onSubmit; Shift+Enter does not', () => {
- const onSubmit = mock(() => {});
+ const onSubmit = vi.fn(() => {});
render(
<ComposerMentionInput ariaLabel="Ask AI" onEmptyChange={() => {}} onSubmit={onSubmit} />,
);
@@ -313,14 +314,14 @@ describe('ComposerMentionInput (component)', () => {
* the load-bearing branch: submit-vs-defer keyed on plugin `active` state.
*/
describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {
- let fetchSpy: ReturnType<typeof spyOn>;
+ let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// The suggestion's async `items` step calls `fetch('/api/pages')`; jsdom has
// no backend, so stub it to an empty corpus. The plugin's `active` state
// does not depend on the fetch resolving — it is computed synchronously from
// the inserted `@`-trigger — so the empty corpus does not affect the assertion.
- fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(
+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(
async () =>
new Response(JSON.stringify({ pages: [], documents: [] }), {
status: 200,
@@ -347,7 +348,7 @@ describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {
}
test('Enter submits while the popup is closed', () => {
- const onSubmit = mock(() => {});
+ const onSubmit = vi.fn(() => {});
render(
<ComposerMentionInput ariaLabel="Ask AI" onEmptyChange={() => {}} onSubmit={onSubmit} />,
);
@@ -360,7 +361,7 @@ describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {
});
test('Enter does NOT submit while the @-popup is open (defers to the suggestion plugin)', () => {
- const onSubmit = mock(() => {});
+ const onSubmit = vi.fn(() => {});
render(
<ComposerMentionInput ariaLabel="Ask AI" onEmptyChange={() => {}} onSubmit={onSubmit} />,
);
@@ -376,7 +377,7 @@ describe('ComposerMentionInput — Enter defers to the @-mention popup', () => {
});
test('Enter resumes submitting once the popup closes', () => {
- const onSubmit = mock(() => {});
+ const onSubmit = vi.fn(() => {});
render(
<ComposerMentionInput ariaLabel="Ask AI" onEmptyChange={() => {}} onSubmit={onSubmit} />,
);
diff --git a/packages/app/src/editor/DocumentContext.branch-fanout.dom.test.tsx b/packages/app/src/editor/DocumentContext.branch-fanout.dom.test.tsx
index f3e6808ae..2b8eb5352 100644
--- a/packages/app/src/editor/DocumentContext.branch-fanout.dom.test.tsx
+++ b/packages/app/src/editor/DocumentContext.branch-fanout.dom.test.tsx
@@ -1,12 +1,12 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { subscribeToDocumentsChanged } from '@/lib/documents-events';
// Use a dummy ws URL: pool constructs but providers never reach the wire,
// matching `branch-invalidation.test.ts`'s established pattern.
-mock.module('@/lib/use-collab-url', () => ({
+vi.doMock('@/lib/use-collab-url', () => ({
useCollabUrl: () => ({
collabUrl: 'ws://localhost:1/collab',
attempts: 0,
diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsx
index 1a1f81550..718fa0c64 100644
--- a/packages/app/src/editor/DocumentContext.dom.test.tsx
+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { type ReactNode, useLayoutEffect, useState } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { hashFromAssetPath } from '@/lib/doc-hash';
import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';
@@ -9,7 +9,7 @@ import { assetTabId, docTabId, localTabSessionStorageKey } from './editor-tabs';
let mockCollabUrl: string | null = null;
-mock.module('@/lib/use-collab-url', () => ({
+vi.doMock('@/lib/use-collab-url', () => ({
useCollabUrl: () => ({
collabUrl: mockCollabUrl,
attempts: 0,
@@ -306,7 +306,7 @@ describe('DocumentContext tab close force contract', () => {
test('reopenClosedTab skips already-open entries and continues to the next closed tab', async () => {
mockCollabUrl = 'ws://localhost:1/collab';
- globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
seedThreeTabSession();
render(<CloseActiveHarness />, { wrapper: ProviderHarness });
@@ -401,7 +401,7 @@ describe('DocumentContext tab close force contract', () => {
test('desktop close-active-tab-or-window action closes tabs before closing the editor window', async () => {
seedActiveOtherTabSession();
- const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
+ const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {});
const stub = makeEditorBridgeStub();
render(<BridgeCloseActiveHarness bridge={stub.bridge} />, { wrapper: ProviderHarness });
@@ -717,7 +717,7 @@ describe('DocumentContext syncOpenTabsWithKnownTargets — cold-start hash prese
test('same-stem md and mdx tabs survive canonical extensionless page sync', async () => {
mockCollabUrl = 'ws://localhost:1/collab';
- globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
seedSameStemActiveMdxSession();
window.location.hash = '#/foo.mdx';
render(<SameStemSyncHarness />, { wrapper: ProviderHarness });
@@ -752,7 +752,7 @@ describe('DocumentContext tab restore', () => {
test('restores an extension-qualified mdx tab over an ambiguous extensionless hash', async () => {
mockCollabUrl = 'ws://localhost:1/collab';
- globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
seedSameStemActiveMdxSession();
window.location.hash = '#/foo';
@@ -766,7 +766,7 @@ describe('DocumentContext tab restore', () => {
test('keeps saved tab order when an active asset hash opens before session restore resolves', async () => {
mockCollabUrl = 'ws://localhost:1/collab';
- globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('unexpected fetch'))) as never;
const stub = makeDeferredSessionBridgeStub({
openTabs: [OTHER_TAB_ID, LICENSE_TAB_ID],
pinnedTabIds: [],
diff --git a/packages/app/src/editor/SourceEditor.dom.test.tsx b/packages/app/src/editor/SourceEditor.dom.test.tsx
index 1cca7415c..a6c87e9dd 100644
--- a/packages/app/src/editor/SourceEditor.dom.test.tsx
+++ b/packages/app/src/editor/SourceEditor.dom.test.tsx
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { EditorSelection } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Config } from '@inkeep/open-knowledge-core';
import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';
@@ -111,7 +111,7 @@ describe('SourceEditor word-wrap preference wiring', () => {
unsubscribeComposer = subscribeToOpenAskAiComposer(() => {
composerOpenRequests += 1;
});
- globalThis.fetch = mock(async (input: RequestInfo | URL) => {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === '/api/pages') return Response.json({ pages: [] });
if (url === '/api/documents') return Response.json({ documents: [] });
@@ -241,7 +241,7 @@ describe('SourceEditor word-wrap preference wiring', () => {
describe('SourceEditor outline navigation', () => {
beforeEach(() => {
- globalThis.fetch = mock(async (input: RequestInfo | URL) => {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === '/api/pages') return Response.json({ pages: [] });
if (url === '/api/documents') return Response.json({ documents: [] });
diff --git a/packages/app/src/editor/TiptapEditor.test.tsx b/packages/app/src/editor/TiptapEditor.test.tsx
index 9fc7a9a24..aeacb760d 100644
--- a/packages/app/src/editor/TiptapEditor.test.tsx
+++ b/packages/app/src/editor/TiptapEditor.test.tsx
@@ -1,7 +1,7 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { Editor } from '@tiptap/core';
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { buildPatternDConstructorOptions } from './TiptapEditor';
import {
diff --git a/packages/app/src/editor/active-editor.test.ts b/packages/app/src/editor/active-editor.test.ts
index a6bd29175..d17347af1 100644
--- a/packages/app/src/editor/active-editor.test.ts
+++ b/packages/app/src/editor/active-editor.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/core';
+import { afterEach, describe, expect, test } from 'vitest';
import { getEditorForDoc, registerEditor, unregisterEditor } from './active-editor';
const fakeEditor = (id: string): Editor => ({ __id: id }) as unknown as Editor;
diff --git a/packages/app/src/editor/apply-lint-fix.test.ts b/packages/app/src/editor/apply-lint-fix.test.ts
index 602020d89..e8bb33ff3 100644
--- a/packages/app/src/editor/apply-lint-fix.test.ts
+++ b/packages/app/src/editor/apply-lint-fix.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { LintDiagnostic, LintTextEdit } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { applyLintFixes, collectFixes, LINT_SOURCE_FIXED_EVENT } from './apply-lint-fix.ts';
diff --git a/packages/app/src/editor/asset-dispatch/dispatcher.test.ts b/packages/app/src/editor/asset-dispatch/dispatcher.test.ts
index 933559e52..82838091b 100644
--- a/packages/app/src/editor/asset-dispatch/dispatcher.test.ts
+++ b/packages/app/src/editor/asset-dispatch/dispatcher.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import { dispatchAssetClick } from './dispatcher.ts';
import { AssetViewerRegistry, assetViewerRegistry } from './registry.ts';
import type { AssetClickContext } from './types.ts';
@@ -20,7 +20,7 @@ describe('dispatchAssetClick', () => {
});
test('empty registry + no desktop bridge → web fallback fires with url', async () => {
- const openUrl = mock((_: string) => {});
+ const openUrl = vi.fn((_: string) => {});
await dispatchAssetClick(ctx({ url: './meeting.pdf' }), {
desktopBridge: undefined,
openUrl,
@@ -30,8 +30,8 @@ describe('dispatchAssetClick', () => {
});
test('registered viewer for ext fires with the context', async () => {
- const openUrl = mock((_: string) => {});
- const viewer = { exts: ['pdf'] as const, render: mock(() => {}) };
+ const openUrl = vi.fn((_: string) => {});
+ const viewer = { exts: ['pdf'] as const, render: vi.fn(() => {}) };
const r = new AssetViewerRegistry();
r.register(viewer);
@@ -44,8 +44,8 @@ describe('dispatchAssetClick', () => {
});
test('Cmd/Ctrl+click bypasses a registered viewer (D-A6)', async () => {
- const openUrl = mock((_: string) => {});
- const viewer = { exts: ['pdf'] as const, render: mock(() => {}) };
+ const openUrl = vi.fn((_: string) => {});
+ const viewer = { exts: ['pdf'] as const, render: vi.fn(() => {}) };
const r = new AssetViewerRegistry();
r.register(viewer);
@@ -60,8 +60,8 @@ describe('dispatchAssetClick', () => {
});
test('desktop bridge present → openAsset fires with projectRelPath', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openUrl = mock((_: string) => {});
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openUrl = vi.fn((_: string) => {});
const desktopBridge = {
shell: { openAsset },
} as unknown as NonNullable<typeof window.okDesktop>;
@@ -77,8 +77,8 @@ describe('dispatchAssetClick', () => {
});
test('Cmd+click with desktop bridge present → openAsset still fires (Cmd only skips registry)', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const viewer = { exts: ['pdf'] as const, render: mock(() => {}) };
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const viewer = { exts: ['pdf'] as const, render: vi.fn(() => {}) };
const r = new AssetViewerRegistry();
r.register(viewer);
const desktopBridge = {
@@ -98,11 +98,11 @@ describe('dispatchAssetClick', () => {
// A blocked extension (html, svg, sh, ...) exists on disk but OK won't hand
// it to `shell.openPath`. The file is real, so reveal it rather than failing
// silently.
- const openAsset = mock(
+ const openAsset = vi.fn(
async (_: string) => ({ ok: false, reason: 'extension-blocked' }) as const,
);
- const revealAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openUrl = mock((_: string) => {});
+ const revealAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openUrl = vi.fn((_: string) => {});
const desktopBridge = {
shell: { openAsset, revealAsset },
} as unknown as NonNullable<typeof window.okDesktop>;
@@ -119,14 +119,14 @@ describe('dispatchAssetClick', () => {
});
test('non-blocked refusal (resolve-error) is logged, does not reveal or fall through to web', async () => {
- const openAsset = mock(async (_: string) => ({ ok: false, reason: 'resolve-error' }) as const);
- const revealAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openUrl = mock((_: string) => {});
+ const openAsset = vi.fn(async (_: string) => ({ ok: false, reason: 'resolve-error' }) as const);
+ const revealAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openUrl = vi.fn((_: string) => {});
const desktopBridge = {
shell: { openAsset, revealAsset },
} as unknown as NonNullable<typeof window.okDesktop>;
- const consoleWarn = mock((..._args: unknown[]) => {});
+ const consoleWarn = vi.fn((..._args: unknown[]) => {});
const origWarn = console.warn;
console.warn = consoleWarn as unknown as typeof console.warn;
try {
@@ -145,10 +145,10 @@ describe('dispatchAssetClick', () => {
});
test('dispatcher uses the module-level singleton registry when no deps passed', async () => {
- const viewer = { exts: ['pdf'] as const, render: mock(() => {}) };
+ const viewer = { exts: ['pdf'] as const, render: vi.fn(() => {}) };
assetViewerRegistry.register(viewer);
- const openUrl = mock((_: string) => {});
+ const openUrl = vi.fn((_: string) => {});
await dispatchAssetClick(ctx(), { desktopBridge: undefined, openUrl });
expect(viewer.render).toHaveBeenCalledTimes(1);
diff --git a/packages/app/src/editor/asset-dispatch/registry.test.ts b/packages/app/src/editor/asset-dispatch/registry.test.ts
index fd2a3ec1d..4ea7c1f11 100644
--- a/packages/app/src/editor/asset-dispatch/registry.test.ts
+++ b/packages/app/src/editor/asset-dispatch/registry.test.ts
@@ -1,11 +1,11 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { AssetViewerRegistry } from './registry.ts';
function makeViewer(exts: readonly string[]): {
exts: readonly string[];
- render: ReturnType<typeof mock>;
+ render: ReturnType<typeof vi.fn>;
} {
- return { exts, render: mock(() => {}) };
+ return { exts, render: vi.fn(() => {}) };
}
describe('AssetViewerRegistry', () => {
@@ -89,7 +89,7 @@ describe('AssetViewerRegistry', () => {
test('re-registering the same viewer instance is silent', () => {
const r = new AssetViewerRegistry();
const viewer = makeViewer(['pdf']);
- const consoleWarn = mock((..._args: unknown[]) => {});
+ const consoleWarn = vi.fn((..._args: unknown[]) => {});
const origWarn = console.warn;
console.warn = consoleWarn as unknown as typeof console.warn;
try {
@@ -117,7 +117,7 @@ describe('AssetViewerRegistry', () => {
const r = new AssetViewerRegistry();
const first = makeViewer(['pdf']);
const second = makeViewer(['pdf']);
- const consoleWarn = mock((..._args: unknown[]) => {});
+ const consoleWarn = vi.fn((..._args: unknown[]) => {});
const origWarn = console.warn;
console.warn = consoleWarn as unknown as typeof console.warn;
try {
diff --git a/packages/app/src/editor/awareness-user.test.ts b/packages/app/src/editor/awareness-user.test.ts
index 9874de083..111801290 100644
--- a/packages/app/src/editor/awareness-user.test.ts
+++ b/packages/app/src/editor/awareness-user.test.ts
@@ -1,10 +1,10 @@
-import { describe, expect, test } from 'bun:test';
import {
colorFromSeed,
HUMAN_COLORS,
type Identity,
type Principal,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { buildAwarenessUser } from './awareness-user';
const identity: Identity = {
diff --git a/packages/app/src/editor/binding-staleness-guard.test.ts b/packages/app/src/editor/binding-staleness-guard.test.ts
index be94a04a2..1e8f30733 100644
--- a/packages/app/src/editor/binding-staleness-guard.test.ts
+++ b/packages/app/src/editor/binding-staleness-guard.test.ts
@@ -42,13 +42,13 @@
* short-circuits); do not remove the restore.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { getSchema } from '@tiptap/core';
import { EditorState, Plugin, type PluginKey, Selection } from '@tiptap/pm/state';
import { EditorView } from '@tiptap/pm/view';
import { ySyncPluginKey, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { JSDOM } from 'jsdom';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
bindingStalenessGuardPlugin,
diff --git a/packages/app/src/editor/branch-invalidation.test.ts b/packages/app/src/editor/branch-invalidation.test.ts
index 9ed8592b5..2be98ce54 100644
--- a/packages/app/src/editor/branch-invalidation.test.ts
+++ b/packages/app/src/editor/branch-invalidation.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { BranchSwitchedClearFailedLogSchema, handleBranchSwitched } from './branch-invalidation';
import { ProviderPool } from './provider-pool';
@@ -52,8 +52,8 @@ describe('handleBranchSwitched', () => {
const p1 = await awaitAttachedPersistence(e1);
const p2 = await awaitAttachedPersistence(e2);
- const clear1 = mock(() => Promise.resolve());
- const clear2 = mock(() => Promise.resolve());
+ const clear1 = vi.fn(() => Promise.resolve());
+ const clear2 = vi.fn(() => Promise.resolve());
p1.clearData = clear1;
p2.clearData = clear2;
@@ -85,12 +85,12 @@ describe('handleBranchSwitched', () => {
resolve();
}, 20);
});
- p1.clearData = mock(() => clearPromise);
- p2.clearData = mock(() => Promise.resolve());
+ p1.clearData = vi.fn(() => clearPromise);
+ p2.clearData = vi.fn(() => Promise.resolve());
let recycleObservedClearResolved = false;
const originalRecycle = pool.recycleAllEntries.bind(pool);
- pool.recycleAllEntries = mock(() => {
+ pool.recycleAllEntries = vi.fn(() => {
recycleObservedClearResolved = clearResolved;
originalRecycle();
});
@@ -113,8 +113,8 @@ describe('handleBranchSwitched', () => {
const p1 = await awaitAttachedPersistence(e1);
const p2 = await awaitAttachedPersistence(e2);
- const clear1 = mock(() => Promise.resolve());
- const clear2 = mock(() => Promise.resolve());
+ const clear1 = vi.fn(() => Promise.resolve());
+ const clear2 = vi.fn(() => Promise.resolve());
p1.clearData = clear1;
p2.clearData = clear2;
@@ -148,15 +148,15 @@ describe('handleBranchSwitched', () => {
if (!e1) throw new Error('pool.open returned null');
const p1 = await awaitAttachedPersistence(e1);
- p1.clearData = mock(() => Promise.reject(new Error('simulated-idb-quota-exhausted')));
+ p1.clearData = vi.fn(() => Promise.reject(new Error('simulated-idb-quota-exhausted')));
const originalRecycle = pool.recycleAllEntries.bind(pool);
- const recycleSpy = mock(() => {
+ const recycleSpy = vi.fn(() => {
originalRecycle();
});
pool.recycleAllEntries = recycleSpy;
- const logSpy = mock((_msg: string) => {});
+ const logSpy = vi.fn((_msg: string) => {});
const originalWarn = console.warn;
console.warn = logSpy as unknown as typeof console.warn;
try {
@@ -176,7 +176,7 @@ describe('handleBranchSwitched', () => {
test('is a no-op when the pool has no entries', async () => {
pool = new ProviderPool(3, DUMMY_WS);
- const recycleSpy = mock(() => {});
+ const recycleSpy = vi.fn(() => {});
pool.recycleAllEntries = recycleSpy;
await handleBranchSwitched(pool, 'feature');
diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
index 57552a1c3..a81e2defd 100644
--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.dom.test.tsx
@@ -15,17 +15,17 @@
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Schema } from '@tiptap/pm/model';
import type { Editor } from '@tiptap/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';
import { subscribeToActiveTerminalInput } from '@/components/handoff/terminal-input-events';
import { setEditorDocName } from '../extensions/doc-context.ts';
-mock.module('sonner', () => ({ toast: { error: () => {}, success: () => {} } }));
+vi.doMock('sonner', () => ({ toast: { error: () => {}, success: () => {} } }));
// The click handler defers its action to the next animation frame; jsdom under
// bun does not always define rAF, so polyfill it to a microtask and flush via
diff --git a/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx b/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx
index 2f400808b..3d2fa3373 100644
--- a/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx
+++ b/packages/app/src/editor/bubble-menu/FootnoteBubbleButton.dom.test.tsx
@@ -18,9 +18,9 @@
* helpers — assert through queries on the rendered DOM after `render`.
*/
-import { describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
import type { Editor } from '@tiptap/react';
+import { describe, expect, test } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { FootnoteBubbleButton } from './FootnoteBubbleButton';
diff --git a/packages/app/src/editor/bubble-menu/ImageAlignButtons.test.ts b/packages/app/src/editor/bubble-menu/ImageAlignButtons.test.ts
index 9c5cf0ba0..c0f7ec1df 100644
--- a/packages/app/src/editor/bubble-menu/ImageAlignButtons.test.ts
+++ b/packages/app/src/editor/bubble-menu/ImageAlignButtons.test.ts
@@ -22,8 +22,8 @@
* landed).
*/
-import { describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/react';
+import { describe, expect, test } from 'vitest';
import { isImageNodeSelected } from './ImageAlignButtons';
/**
diff --git a/packages/app/src/editor/bubble-menu/LinkEditPopover.dom.test.tsx b/packages/app/src/editor/bubble-menu/LinkEditPopover.dom.test.tsx
index 3d9aeca17..079a38995 100644
--- a/packages/app/src/editor/bubble-menu/LinkEditPopover.dom.test.tsx
+++ b/packages/app/src/editor/bubble-menu/LinkEditPopover.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { isMacOS } from '@tiptap/core';
import type { Editor } from '@tiptap/react';
import { act } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import {
_resetPendingLinkEditForTest,
@@ -11,7 +11,7 @@ import {
import { markIdentityKey } from '../extensions/mark-identity';
import { emitOpenLinkEditPopover } from './link-edit-popover-events';
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({
folderPaths: new Set(['guides']),
loading: false,
@@ -70,10 +70,10 @@ function makeEditor({
// The claim reads the non-throwing `editorView` field (never the `view`
// throwing proxy); mirror the real Editor by exposing both.
editorView: { hasFocus: () => viewFocused },
- getAttributes: mock((name: string) => (name === 'link' ? { href } : {})),
- isActive: mock((name: string) => name === 'link' && active),
- on: mock(() => {}),
- off: mock(() => {}),
+ getAttributes: vi.fn((name: string) => (name === 'link' ? { href } : {})),
+ isActive: vi.fn((name: string) => name === 'link' && active),
+ on: vi.fn(() => {}),
+ off: vi.fn(() => {}),
chain: () => chain,
} as unknown as Editor;
}
@@ -97,7 +97,7 @@ function cmdKEvent(init: KeyboardEventInit = {}): KeyboardEvent {
}
function stubClipboardRead(impl: () => Promise<string>) {
- const readText = mock(impl);
+ const readText = vi.fn(impl);
const original = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
@@ -142,8 +142,8 @@ describe('LinkEditPopover', () => {
});
test('applies a trimmed URL with Enter and dismisses the input', () => {
- const setLink = mock((_attrs: { href: string }) => {});
- const unsetLink = mock(() => {});
+ const setLink = vi.fn((_attrs: { href: string }) => {});
+ const unsetLink = vi.fn(() => {});
renderPopover(makeEditor({ active: false, onSetLink: setLink, onUnsetLink: unsetLink }));
fireEvent.mouseDown(screen.getByRole('button', { name: 'Insert link' }));
@@ -157,8 +157,8 @@ describe('LinkEditPopover', () => {
});
test('submitting an empty active collapsed link unsets it', async () => {
- const setLink = mock((_attrs: { href: string }) => {});
- const unsetLink = mock(() => {});
+ const setLink = vi.fn((_attrs: { href: string }) => {});
+ const unsetLink = vi.fn(() => {});
renderPopover(
makeEditor({
href: '',
@@ -180,8 +180,8 @@ describe('LinkEditPopover', () => {
});
test('empty inactive input is a no-op and still dismisses', async () => {
- const setLink = mock((_attrs: { href: string }) => {});
- const unsetLink = mock(() => {});
+ const setLink = vi.fn((_attrs: { href: string }) => {});
+ const unsetLink = vi.fn(() => {});
renderPopover(makeEditor({ active: false, onSetLink: setLink, onUnsetLink: unsetLink }));
fireEvent.mouseDown(screen.getByRole('button', { name: 'Insert link' }));
@@ -272,7 +272,7 @@ describe('LinkEditPopover ⌘K dual-role claim', () => {
test('routes a caret inside a tracked link to the chip edit spine, not the popover', () => {
// Real mark-identity state needs a live PM view; stub the plugin state so
// the caret resolves to a stable id (same idiom as component-items tests).
- const getStateSpy = spyOn(markIdentityKey, 'getState').mockReturnValue({
+ const getStateSpy = vi.spyOn(markIdentityKey, 'getState').mockReturnValue({
byId: new Map([
[
'm7',
diff --git a/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsx b/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsx
index 88d84f310..49f376c97 100644
--- a/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsx
+++ b/packages/app/src/editor/bubble-menu/bubble-menu-clip.dom.test.tsx
@@ -16,9 +16,9 @@
* Invocation: `bun run test:dom` from `packages/app/`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
import type { Editor } from '@tiptap/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { TOOLBAR_HEIGHT } from '../extensions/frozen-table-headers';
import { deriveEditorClipOptions } from './bubble-menu-clip';
diff --git a/packages/app/src/editor/bubble-menu/bubble-menu-state.test.ts b/packages/app/src/editor/bubble-menu/bubble-menu-state.test.ts
index a855d978c..2f3e2c23a 100644
--- a/packages/app/src/editor/bubble-menu/bubble-menu-state.test.ts
+++ b/packages/app/src/editor/bubble-menu/bubble-menu-state.test.ts
@@ -7,11 +7,11 @@
* to the command palette.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { LinkFidelity } from '@inkeep/open-knowledge-core';
import { Editor, Extension } from '@tiptap/core';
import { TextSelection } from '@tiptap/pm/state';
import StarterKit from '@tiptap/starter-kit';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import { markIdentityKey, markIdentityPlugin } from '../extensions/mark-identity';
import { installDomGlobals } from '../walk-currency-test-harness';
import { resolveAddLinkShortcutAction } from './bubble-menu-state';
diff --git a/packages/app/src/editor/bubble-menu/link-edit-popover-events.test.ts b/packages/app/src/editor/bubble-menu/link-edit-popover-events.test.ts
index 81b1b6333..918d49ac7 100644
--- a/packages/app/src/editor/bubble-menu/link-edit-popover-events.test.ts
+++ b/packages/app/src/editor/bubble-menu/link-edit-popover-events.test.ts
@@ -4,7 +4,7 @@
* (the SSR-safe default target path is exercised by the dom suite).
*/
-import { expect, test } from 'bun:test';
+import { expect, test } from 'vitest';
import {
emitOpenLinkEditPopover,
subscribeToOpenLinkEditPopover,
diff --git a/packages/app/src/editor/client-persistence.test.ts b/packages/app/src/editor/client-persistence.test.ts
index f2b901e55..b56a3957c 100644
--- a/packages/app/src/editor/client-persistence.test.ts
+++ b/packages/app/src/editor/client-persistence.test.ts
@@ -12,8 +12,8 @@
* across a `bun test` process.
*/
-import { describe, expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import {
type ClientPersistenceProvider,
@@ -314,7 +314,7 @@ describe('createClientPersistence', () => {
req.onerror = () => reject(req.error);
});
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
// Kick off clearData without awaiting. The internal deleteDatabase
// request is blocked by `blocker` — onblocked fires, the request stays
diff --git a/packages/app/src/editor/clipboard/clipboard-line-structure.test.ts b/packages/app/src/editor/clipboard/clipboard-line-structure.test.ts
index 79d39097a..b66b31bb3 100644
--- a/packages/app/src/editor/clipboard/clipboard-line-structure.test.ts
+++ b/packages/app/src/editor/clipboard/clipboard-line-structure.test.ts
@@ -49,7 +49,6 @@
* could silently merge/corrupt the round-trip with nothing noticing.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { MarkdownManager } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
@@ -57,6 +56,7 @@ import { AllSelection, EditorState, type TextSelection } from '@tiptap/pm/state'
import { CellSelection, TableMap } from '@tiptap/pm/tables';
import { EditorView } from '@tiptap/pm/view';
import { JSDOM } from 'jsdom';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import { sharedExtensions } from '../extensions/shared';
import {
reflectCheckboxCheckedState,
diff --git a/packages/app/src/editor/clipboard/clipboard-sanitize.test.ts b/packages/app/src/editor/clipboard/clipboard-sanitize.test.ts
index 8796cc864..c220b397e 100644
--- a/packages/app/src/editor/clipboard/clipboard-sanitize.test.ts
+++ b/packages/app/src/editor/clipboard/clipboard-sanitize.test.ts
@@ -7,7 +7,7 @@
* Playwright.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
classifyUrlPortability,
convertCssColors,
diff --git a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts
index ff584e437..90dee1393 100644
--- a/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts
+++ b/packages/app/src/editor/clipboard/clipboard-walker-fallback-palette.test.ts
@@ -19,7 +19,7 @@
* - `TYPE_TO_TONE` shape pins the supported callout type set.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyUrlPortability } from './clipboard-sanitize.ts';
import {
PALETTE_DESCRIPTOR_NAMES,
diff --git a/packages/app/src/editor/clipboard/clipboard-walker.test.ts b/packages/app/src/editor/clipboard/clipboard-walker.test.ts
index 1c31b02ea..dbb7461e5 100644
--- a/packages/app/src/editor/clipboard/clipboard-walker.test.ts
+++ b/packages/app/src/editor/clipboard/clipboard-walker.test.ts
@@ -12,8 +12,8 @@
* in `clipboard-sanitize.ts` and are tested in `clipboard-sanitize.test.ts`.
*/
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
+import { describe, expect, test } from 'vitest';
import {
ATTR_BLOCKLIST,
applyUrlClassifierPostPass,
diff --git a/packages/app/src/editor/clipboard/detect-source.test.ts b/packages/app/src/editor/clipboard/detect-source.test.ts
index 754a464bf..c5cc64baa 100644
--- a/packages/app/src/editor/clipboard/detect-source.test.ts
+++ b/packages/app/src/editor/clipboard/detect-source.test.ts
@@ -6,7 +6,7 @@
* `.getData(key)`, so a plain object suffices.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { detectSource } from './detect-source.ts';
function fakeDT(data: Record<string, string>): DataTransfer {
diff --git a/packages/app/src/editor/clipboard/handle-drop.test.ts b/packages/app/src/editor/clipboard/handle-drop.test.ts
index a70f8cd14..b5977b376 100644
--- a/packages/app/src/editor/clipboard/handle-drop.test.ts
+++ b/packages/app/src/editor/clipboard/handle-drop.test.ts
@@ -14,19 +14,19 @@
* `dataTransfer.files.length > 0` so that path takes over.
*/
-import { afterEach, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
import * as actualCore from '@inkeep/open-knowledge-core';
import * as actualSonner from 'sonner';
+import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
-mock.module('@inkeep/open-knowledge-core', () => {
+vi.doMock('@inkeep/open-knowledge-core', () => {
return {
...actualCore,
- htmlToMdast: mock((_html: string) => ({ type: 'root', children: [] })),
- mdastToMarkdown: mock((_tree: unknown) => '**bold**'),
+ htmlToMdast: vi.fn((_html: string) => ({ type: 'root', children: [] })),
+ mdastToMarkdown: vi.fn((_tree: unknown) => '**bold**'),
};
});
-mock.module('sonner', () => ({ ...actualSonner, toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ ...actualSonner, toast: { error: vi.fn(() => {}) } }));
// The dispatcher imports the mocked `@inkeep/open-knowledge-core`; bind it after
// the mock is registered so the stubbed htmlToMdast/mdastToMarkdown take effect
@@ -59,7 +59,7 @@ function fakeDropEvent({ data, filesCount = 0, shiftKey = false }: FakeDropOptio
function fakeMdManager() {
return {
- parse: mock((_md: string) => ({
+ parse: vi.fn((_md: string) => ({
type: 'doc',
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'parsed' }] }],
})),
@@ -68,9 +68,9 @@ function fakeMdManager() {
// biome-ignore lint/suspicious/noExplicitAny: narrow fake view for unit test
function fakeView(opts: { inCodeBlock?: boolean } = {}): any {
- const dispatch = mock(() => {});
+ const dispatch = vi.fn(() => {});
const codeBlockType = {
- create: mock((_attrs: unknown, _content: unknown) => ({
+ create: vi.fn((_attrs: unknown, _content: unknown) => ({
slice: (_f: number, _t: number) => 'CODE-SLICE',
})),
};
@@ -91,16 +91,16 @@ function fakeView(opts: { inCodeBlock?: boolean } = {}): any {
}),
},
tr: {
- replaceSelectionWith: mock(function (this: unknown, _node: unknown) {
+ replaceSelectionWith: vi.fn(function (this: unknown, _node: unknown) {
return this;
}),
- replaceSelection: mock(function (this: unknown, _slice: unknown) {
+ replaceSelection: vi.fn(function (this: unknown, _slice: unknown) {
return this;
}),
- setMeta: mock(function (this: unknown, _key: unknown, _value: unknown) {
+ setMeta: vi.fn(function (this: unknown, _key: unknown, _value: unknown) {
return this;
}),
- scrollIntoView: mock(function (this: unknown) {
+ scrollIntoView: vi.fn(function (this: unknown) {
return this;
}),
},
diff --git a/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts b/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts
index 3f109b760..989d546e8 100644
--- a/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts
+++ b/packages/app/src/editor/clipboard/handle-paste.list-placement.test.ts
@@ -16,18 +16,18 @@
* strip×glue fix that ships separately).
*/
-import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { Editor, type JSONContent } from '@tiptap/core';
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
import { TextSelection } from '@tiptap/pm/state';
import * as actualSonner from 'sonner';
+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { installDomGlobals } from '../walk-currency-test-harness';
import { createClipboardTextSerializer } from './serialize';
// The dispatcher pulls the degrade-path toast (sonner) into its import graph;
// stub it so module load stays inert. The splice path never degrades.
-mock.module('sonner', () => ({ ...actualSonner, toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ ...actualSonner, toast: { error: vi.fn(() => {}) } }));
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
diff --git a/packages/app/src/editor/clipboard/handle-paste.test.ts b/packages/app/src/editor/clipboard/handle-paste.test.ts
index 5bd83f0ee..a50fe2fd6 100644
--- a/packages/app/src/editor/clipboard/handle-paste.test.ts
+++ b/packages/app/src/editor/clipboard/handle-paste.test.ts
@@ -25,27 +25,27 @@
* `state.tr.*`, `dispatch`).
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
import * as actualCore from '@inkeep/open-knowledge-core';
import { LinkFidelity, MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { Editor, type Extensions } from '@tiptap/core';
import StarterKit from '@tiptap/starter-kit';
import * as actualSonner from 'sonner';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
import { GfmAutolink } from '../gfm-autolink-plugin.ts';
import { flushMicrotasksAndTimers, installDomGlobals } from '../walk-currency-test-harness.ts';
// Mock the shared pipeline so tests don't exercise the full rehype stack.
-mock.module('@inkeep/open-knowledge-core', () => {
+vi.doMock('@inkeep/open-knowledge-core', () => {
return {
...actualCore,
- htmlToMdast: mock((_html: string) => ({ type: 'root', children: [] })),
- mdastToMarkdown: mock((_tree: unknown) => '**bold**'),
+ htmlToMdast: vi.fn((_html: string) => ({ type: 'root', children: [] })),
+ mdastToMarkdown: vi.fn((_tree: unknown) => '**bold**'),
};
});
// Mock sonner to no-op toasts — we don't assert on them here.
-mock.module('sonner', () => ({ ...actualSonner, toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ ...actualSonner, toast: { error: vi.fn(() => {}) } }));
// The dispatcher imports the mocked `@inkeep/open-knowledge-core`; bind it after
// the mock is registered so the stubbed htmlToMdast/mdastToMarkdown take effect
@@ -67,7 +67,7 @@ function fakeDT(data: Record<string, string>): ClipboardEvent {
function fakeMdManager() {
return {
- parse: mock((_md: string) => ({
+ parse: vi.fn((_md: string) => ({
type: 'doc',
content: [{ type: 'paragraph', content: [{ type: 'text', text: 'parsed' }] }],
})),
@@ -77,9 +77,9 @@ function fakeMdManager() {
// Fake PM view: only the fields the dispatcher reads.
// biome-ignore lint/suspicious/noExplicitAny: narrow fake view for unit test
function fakeView(opts: { inCodeBlock?: boolean } = {}): any {
- const dispatch = mock(() => {});
+ const dispatch = vi.fn(() => {});
const codeBlockType = {
- create: mock((_attrs: unknown, _content: unknown) => ({
+ create: vi.fn((_attrs: unknown, _content: unknown) => ({
slice: (_f: number, _t: number) => 'CODE-SLICE',
})),
};
@@ -109,16 +109,16 @@ function fakeView(opts: { inCodeBlock?: boolean } = {}): any {
}),
},
tr: {
- replaceSelectionWith: mock(function (this: unknown, _node: unknown) {
+ replaceSelectionWith: vi.fn(function (this: unknown, _node: unknown) {
return this;
}),
- replaceSelection: mock(function (this: unknown, _slice: unknown) {
+ replaceSelection: vi.fn(function (this: unknown, _slice: unknown) {
return this;
}),
- setMeta: mock(function (this: unknown, _key: unknown, _value: unknown) {
+ setMeta: vi.fn(function (this: unknown, _key: unknown, _value: unknown) {
return this;
}),
- scrollIntoView: mock(function (this: unknown) {
+ scrollIntoView: vi.fn(function (this: unknown) {
return this;
}),
},
@@ -232,7 +232,7 @@ describe('WYSIWYG paste dispatcher — branch routing', () => {
// continues) is as load-bearing as Branch A's. A narrowed/removed catch
// would lose the user's clipboard content with an uncaught throw.
const throwingMd = {
- parse: mock(() => {
+ parse: vi.fn(() => {
throw new Error('parse exploded');
}),
};
@@ -246,7 +246,7 @@ describe('WYSIWYG paste dispatcher — branch routing', () => {
test('lone-URL cursor paste: a throwing mdManager.parse falls through to plain insert', () => {
const throwingMd = {
- parse: mock(() => {
+ parse: vi.fn(() => {
throw new Error('parse exploded');
}),
};
diff --git a/packages/app/src/editor/clipboard/instrument.test.ts b/packages/app/src/editor/clipboard/instrument.test.ts
index a0e924fc8..d265558ec 100644
--- a/packages/app/src/editor/clipboard/instrument.test.ts
+++ b/packages/app/src/editor/clipboard/instrument.test.ts
@@ -15,8 +15,8 @@
* Both are fully testable in bun-test without a real DOM.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { ChunkedInsertError, HtmlPayloadTooLargeError } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
classifyError,
diff --git a/packages/app/src/editor/clipboard/is-markdown.test.ts b/packages/app/src/editor/clipboard/is-markdown.test.ts
index a8df2c469..c8db8c548 100644
--- a/packages/app/src/editor/clipboard/is-markdown.test.ts
+++ b/packages/app/src/editor/clipboard/is-markdown.test.ts
@@ -6,7 +6,7 @@
* scales with line count: min(3, floor(lineCount / 5)), floored at 1.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isMarkdown } from './is-markdown.ts';
describe('isMarkdown — signal-count heuristic', () => {
diff --git a/packages/app/src/editor/clipboard/lone-url.test.ts b/packages/app/src/editor/clipboard/lone-url.test.ts
index 0e8af361a..b6f60676b 100644
--- a/packages/app/src/editor/clipboard/lone-url.test.ts
+++ b/packages/app/src/editor/clipboard/lone-url.test.ts
@@ -9,7 +9,7 @@
* https-prepended.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { detectClipboardPrefillUrl, detectLoneGfmUrl, detectLoneTrustedUrl } from './lone-url.ts';
describe('detectLoneGfmUrl — cursor-paste policy (GFM shapes only)', () => {
diff --git a/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts b/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts
index 14bd0c328..d22fc6823 100644
--- a/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts
+++ b/packages/app/src/editor/clipboard/non-portable-render-source-fallback.test.ts
@@ -14,8 +14,8 @@
* 3. Edge cases — empty / missing / non-string props
*/
-import { describe, expect, test } from 'bun:test';
import type { Node as PmNode } from '@tiptap/pm/model';
+import { describe, expect, test } from 'vitest';
import { sourceFallbackFormFor } from './non-portable-render-source-fallback.ts';
/**
diff --git a/packages/app/src/editor/clipboard/paste-failure-toast.test.ts b/packages/app/src/editor/clipboard/paste-failure-toast.test.ts
index 6c76fbcad..5e46f3e43 100644
--- a/packages/app/src/editor/clipboard/paste-failure-toast.test.ts
+++ b/packages/app/src/editor/clipboard/paste-failure-toast.test.ts
@@ -8,12 +8,12 @@
* - The internal reset helper clears the throttle.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import * as actualSonner from 'sonner';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-type ToastFn = { error: ReturnType<typeof mock> };
-const toastMock: ToastFn = { error: mock(() => {}) };
-mock.module('sonner', () => ({ ...actualSonner, toast: toastMock }));
+type ToastFn = { error: ReturnType<typeof vi.fn> };
+const toastMock: ToastFn = { error: vi.fn(() => {}) };
+vi.doMock('sonner', () => ({ ...actualSonner, toast: toastMock }));
// biome-ignore lint/suspicious/noExplicitAny: test-scoped dynamic import
let mod: any;
diff --git a/packages/app/src/editor/clipboard/serialize.inline-image-range.test.ts b/packages/app/src/editor/clipboard/serialize.inline-image-range.test.ts
index a08ae1c4f..6451dbb0b 100644
--- a/packages/app/src/editor/clipboard/serialize.inline-image-range.test.ts
+++ b/packages/app/src/editor/clipboard/serialize.inline-image-range.test.ts
@@ -20,25 +20,21 @@
* nodes included), never an element-only index.
*
* `buildWalkerEnv` is intentionally private; the env is captured by
- * stubbing the walker entry point via `mock.module` and driving
+ * stubbing the walker entry point via `vi.doMock` and driving
* `serializeFragment` — the same public wiring production uses.
*
* The registered mock DELEGATES to the real implementation except inside
* an explicit capture window, so it stays behavior-transparent to every
- * other test file in the process. Bun's `mock.module` registry is
- * process-global and never truly un-mocks (oven-sh/bun#12823), and an
- * `afterAll` re-register's factory can observe the already-mocked
- * namespace — a restore built from a namespace spread leaked the stub to
- * later files on some runner file orders. Delegation avoids restore
- * semantics entirely; `realWalkLiveDom` is captured before the mock so it
- * is immune to in-place namespace mutation.
+ * other test file in the worker. Delegation avoids restore semantics
+ * entirely; `realWalkLiveDom` is captured before the mock so it remains
+ * independent from the mocked namespace.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
import type { Fragment } from '@tiptap/pm/model';
import { Schema } from '@tiptap/pm/model';
import type { EditorView } from '@tiptap/pm/view';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { SerializeResult, WalkerEnv } from './clipboard-walker.ts';
const actualWalker = await import('./clipboard-walker.ts');
@@ -47,7 +43,7 @@ const realWalkLiveDom = actualWalker.walkLiveDomToInlineStyledFragment;
let capturedEnv: WalkerEnv | null = null;
let captureActive = false;
-mock.module('./clipboard-walker.ts', () => ({
+vi.doMock('./clipboard-walker.ts', () => ({
...actualWalker,
walkLiveDomToInlineStyledFragment: (slice: unknown, view: unknown, env: WalkerEnv) => {
if (captureActive) {
@@ -64,7 +60,7 @@ mock.module('./clipboard-walker.ts', () => ({
const { createClipboardHtmlSerializer, findDescriptorRoot } = await import('./serialize.ts');
// ---------------------------------------------------------------------------
-// Fake live-DOM elements. bun-test has no DOM; these cover exactly the
+// Fake live-DOM elements. This test runs without a DOM; these cover exactly the
// surface the code under test touches (`classList.contains`,
// `hasAttribute`, `parentElement`, `childNodes`) with STABLE
// object identity so `parentElement ===` and `childNodes.indexOf(...)` work.
diff --git a/packages/app/src/editor/clipboard/shift-tracker.test.ts b/packages/app/src/editor/clipboard/shift-tracker.test.ts
index 92e6ace8e..153488dc3 100644
--- a/packages/app/src/editor/clipboard/shift-tracker.test.ts
+++ b/packages/app/src/editor/clipboard/shift-tracker.test.ts
@@ -15,7 +15,7 @@
* - `installShiftTracker()` is idempotent.
*/
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'vitest';
interface Listener {
type: string;
diff --git a/packages/app/src/editor/clipboard/source-clipboard-recovery.test.ts b/packages/app/src/editor/clipboard/source-clipboard-recovery.test.ts
index ad1dc2e08..c9a7b2e68 100644
--- a/packages/app/src/editor/clipboard/source-clipboard-recovery.test.ts
+++ b/packages/app/src/editor/clipboard/source-clipboard-recovery.test.ts
@@ -17,13 +17,13 @@
* Playwright E2E, not bun-test.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { ChunkedInsertError } from '@inkeep/open-knowledge-core';
import * as actualSonner from 'sonner';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-type ToastFn = { error: ReturnType<typeof mock> };
-const toastMock: ToastFn = { error: mock(() => {}) };
-mock.module('sonner', () => ({ ...actualSonner, toast: toastMock }));
+type ToastFn = { error: ReturnType<typeof vi.fn> };
+const toastMock: ToastFn = { error: vi.fn(() => {}) };
+vi.doMock('sonner', () => ({ ...actualSonner, toast: toastMock }));
// Imported AFTER the mock so the module picks up our stub.
// biome-ignore lint/suspicious/noExplicitAny: test-scoped dynamic import
@@ -48,13 +48,13 @@ interface DispatchCall {
}
function makeFakeView(docLength = 1_000_000): {
- dispatch: ReturnType<typeof mock>;
+ dispatch: ReturnType<typeof vi.fn>;
dispatches: DispatchCall[];
// biome-ignore lint/suspicious/noExplicitAny: fake view state for unit test
state: any;
} {
const dispatches: DispatchCall[] = [];
- const dispatch = mock((arg: { changes: DispatchCall }) => {
+ const dispatch = vi.fn((arg: { changes: DispatchCall }) => {
dispatches.push(arg.changes);
});
return {
@@ -225,7 +225,7 @@ describe('handleChunkedInsertFailure — Source-view recovery contract', () => {
});
test('dispatch throw during rollback is logged but does not prevent toast', () => {
- const throwingDispatch = mock(() => {
+ const throwingDispatch = vi.fn(() => {
throw new Error('view destroyed');
});
withSilencedWarn(() =>
@@ -253,7 +253,7 @@ describe('handleChunkedInsertFailure — Source-view recovery contract', () => {
// When dispatch throws (view destroyed by Activity-hidden unmount, Y.Doc
// GC'd, etc.), the user's selection is NOT restored. The toast must say
// so rather than claim a successful restoration.
- const throwingDispatch = mock(() => {
+ const throwingDispatch = vi.fn(() => {
throw new Error('view destroyed');
});
withSilencedWarn(() =>
@@ -282,7 +282,7 @@ describe('handleChunkedInsertFailure — Source-view recovery contract', () => {
test('non-ChunkedInsertError + dispatch throw: toast accurately states selection NOT restored', () => {
// Same regression for the generic-error path.
- const throwingDispatch = mock(() => {
+ const throwingDispatch = vi.fn(() => {
throw new Error('view destroyed');
});
withSilencedWarn(() =>
diff --git a/packages/app/src/editor/clipboard/source-clipboard.test.ts b/packages/app/src/editor/clipboard/source-clipboard.test.ts
index 43f95aeb2..dbbd5d7b8 100644
--- a/packages/app/src/editor/clipboard/source-clipboard.test.ts
+++ b/packages/app/src/editor/clipboard/source-clipboard.test.ts
@@ -23,7 +23,7 @@
* sanitizer-proxy fixture tests and the e2e copy tests.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { buildSourceModeHtml, handleCopyOrCut, handlePaste } from './source-clipboard.ts';
interface FakeElement {
diff --git a/packages/app/src/editor/components/Accordion.test.tsx b/packages/app/src/editor/components/Accordion.test.tsx
index 371a099aa..c1aafb08a 100644
--- a/packages/app/src/editor/components/Accordion.test.tsx
+++ b/packages/app/src/editor/components/Accordion.test.tsx
@@ -8,8 +8,8 @@
* `renderToString`.
*/
-import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { Accordion } from './Accordion.tsx';
describe('Accordion — chevron refactor', () => {
diff --git a/packages/app/src/editor/components/Callout.test.tsx b/packages/app/src/editor/components/Callout.test.tsx
index 4e54bdbce..2715258ff 100644
--- a/packages/app/src/editor/components/Callout.test.tsx
+++ b/packages/app/src/editor/components/Callout.test.tsx
@@ -10,8 +10,8 @@
* `renderToString`.
*/
-import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { Callout } from './Callout.tsx';
describe('Callout — chevron refactor (collapsible mode)', () => {
diff --git a/packages/app/src/editor/components/ColorPickerInput.test.ts b/packages/app/src/editor/components/ColorPickerInput.test.ts
index 751a6dcb3..45226715f 100644
--- a/packages/app/src/editor/components/ColorPickerInput.test.ts
+++ b/packages/app/src/editor/components/ColorPickerInput.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { nativePickerValue } from './ColorPickerInput.tsx';
describe('nativePickerValue', () => {
diff --git a/packages/app/src/editor/components/File.test.tsx b/packages/app/src/editor/components/File.test.tsx
index 3532f9771..5e377e739 100644
--- a/packages/app/src/editor/components/File.test.tsx
+++ b/packages/app/src/editor/components/File.test.tsx
@@ -13,7 +13,7 @@
* - Empty / undefined input → `''` (renderer falls back to "Untitled file")
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { basenameFromUrl } from './File.tsx';
describe('basenameFromUrl', () => {
diff --git a/packages/app/src/editor/components/Image.dom.test.tsx b/packages/app/src/editor/components/Image.dom.test.tsx
index a59ead453..da930b0bd 100644
--- a/packages/app/src/editor/components/Image.dom.test.tsx
+++ b/packages/app/src/editor/components/Image.dom.test.tsx
@@ -29,23 +29,24 @@
* defeats the infrastructure noise without changing what the Image component
* promises its callers.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
-mock.module('react-medium-image-zoom', () => ({
+vi.doMock('react-medium-image-zoom', () => ({
default: ({ children }: { children: React.ReactNode }) => children,
}));
const { Image } = await import('./Image');
describe('Image — loading-state placeholder (PRD-6638)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/editor/components/Math.test.tsx b/packages/app/src/editor/components/Math.test.tsx
index 1ec023157..c60cd41b6 100644
--- a/packages/app/src/editor/components/Math.test.tsx
+++ b/packages/app/src/editor/components/Math.test.tsx
@@ -9,8 +9,8 @@
* exercised via the Playwright visual-regression suite.
*/
-import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { MathView } from './Math.tsx';
describe('MathView — placeholder branch', () => {
diff --git a/packages/app/src/editor/components/Mermaid.dom.test.tsx b/packages/app/src/editor/components/Mermaid.dom.test.tsx
index 8d499d566..8eae8894a 100644
--- a/packages/app/src/editor/components/Mermaid.dom.test.tsx
+++ b/packages/app/src/editor/components/Mermaid.dom.test.tsx
@@ -5,8 +5,9 @@
* These tests mock them at the module boundary so the contract under test is
* the mounted toolbar behavior, filling preview layout, and Panzoom lifecycle.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
type WindowGlobals = { NodeFilter?: typeof NodeFilter };
@@ -28,33 +29,33 @@ if (globalWithDomShims.ResizeObserver === undefined) {
globalWithDomShims.ResizeObserver = NoopResizeObserver;
}
-const renderMermaid = mock(async (_id: string, _chart: string) => ({
+const renderMermaid = vi.fn(async (_id: string, _chart: string) => ({
svg: '<svg viewBox="0 0 100 100"><g><text>Graph</text></g></svg>',
}));
-const initializeMermaid = mock(() => {});
+const initializeMermaid = vi.fn(() => {});
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('mermaid', () => ({
+vi.doMock('mermaid', () => ({
default: {
initialize: initializeMermaid,
render: renderMermaid,
},
}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: React.ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
type MockPanzoomInstance = {
- zoomIn: ReturnType<typeof mock>;
- zoomOut: ReturnType<typeof mock>;
- pan: ReturnType<typeof mock>;
- reset: ReturnType<typeof mock>;
- destroy: ReturnType<typeof mock>;
- zoomWithWheel: ReturnType<typeof mock>;
+ zoomIn: ReturnType<typeof vi.fn>;
+ zoomOut: ReturnType<typeof vi.fn>;
+ pan: ReturnType<typeof vi.fn>;
+ reset: ReturnType<typeof vi.fn>;
+ destroy: ReturnType<typeof vi.fn>;
+ zoomWithWheel: ReturnType<typeof vi.fn>;
};
type MockPanzoomOptions = {
cursor?: string;
@@ -64,21 +65,21 @@ type MockPanzoomOptions = {
const panzoomInstances: MockPanzoomInstance[] = [];
const panzoomOptions: MockPanzoomOptions[] = [];
-const createPanzoom = mock((_element: SVGElement, options?: MockPanzoomOptions) => {
+const createPanzoom = vi.fn((_element: SVGElement, options?: MockPanzoomOptions) => {
const instance: MockPanzoomInstance = {
- zoomIn: mock(() => ({ scale: 1.25 })),
- zoomOut: mock(() => ({ scale: 0.75 })),
- pan: mock(() => ({ x: 0, y: 0, scale: 1 })),
- reset: mock(() => ({ x: 0, y: 0, scale: 1 })),
- destroy: mock(() => {}),
- zoomWithWheel: mock(() => ({ scale: 1 })),
+ zoomIn: vi.fn(() => ({ scale: 1.25 })),
+ zoomOut: vi.fn(() => ({ scale: 0.75 })),
+ pan: vi.fn(() => ({ x: 0, y: 0, scale: 1 })),
+ reset: vi.fn(() => ({ x: 0, y: 0, scale: 1 })),
+ destroy: vi.fn(() => {}),
+ zoomWithWheel: vi.fn(() => ({ scale: 1 })),
};
panzoomInstances.push(instance);
panzoomOptions.push(options ?? {});
return instance;
});
-mock.module('@panzoom/panzoom', () => ({
+vi.doMock('@panzoom/panzoom', () => ({
default: createPanzoom,
}));
@@ -196,7 +197,7 @@ describe('MermaidView controls', () => {
test('logs when Panzoom setup fails', async () => {
const originalWarn = console.warn;
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
console.warn = warn;
createPanzoom.mockImplementationOnce(() => {
throw new Error('panzoom unavailable');
diff --git a/packages/app/src/editor/components/Mermaid.test.tsx b/packages/app/src/editor/components/Mermaid.test.tsx
index 95eeca36d..738c253a2 100644
--- a/packages/app/src/editor/components/Mermaid.test.tsx
+++ b/packages/app/src/editor/components/Mermaid.test.tsx
@@ -11,12 +11,12 @@
* own test suite.
*/
-import { describe, expect, mock, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import * as actualLinguiReactMacro from '../../../tests/lingui-macro-shim';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiReactMacro,
Trans: ({ children }: { children: React.ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
diff --git a/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx b/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx
index 5c2fe51d6..2a44a9eea 100644
--- a/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx
+++ b/packages/app/src/editor/components/PreviewBlockedNotice.dom.test.tsx
@@ -11,8 +11,9 @@
* Lingui macros resolve through the English-passthrough shim; substrate is
* jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { PreviewBlockedNotice } from './PreviewBlockedNotice';
const DISMISS_NAME = 'Dismiss notice';
@@ -111,7 +112,7 @@ describe('PreviewBlockedNotice', () => {
});
test('the dismiss control is wired to onDismiss', () => {
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
render(
<PreviewBlockedNotice
blocked={[{ directive: 'img-src', uri: 'http://a/1.png' }]}
diff --git a/packages/app/src/editor/components/PropPanel.dom.test.tsx b/packages/app/src/editor/components/PropPanel.dom.test.tsx
index 6db282615..502986e75 100644
--- a/packages/app/src/editor/components/PropPanel.dom.test.tsx
+++ b/packages/app/src/editor/components/PropPanel.dom.test.tsx
@@ -13,9 +13,9 @@
* wiring requires a real DOM. Hence `.dom.test.tsx`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { ALLOWED_IMAGE_MIME_TYPES, type PropDef } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { JsxComponentDescriptor } from '../registry/types.ts';
// Radix Popover focus-trap reaches for these jsdom-missing pieces (the
@@ -59,7 +59,7 @@ const stubPageListValue = {
refetch: () => {},
addPage: () => {},
};
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => stubPageListValue,
useOptionalPageList: () => stubPageListValue,
}));
@@ -93,7 +93,7 @@ describe('PropPanel — Enter on a single-line string input dismisses', () => {
// string, no `accept` allowlist → renders as the plain `<Input>`
// branch. Pressing Enter inside it should hand control back to the
// owner so the popover closes.
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const d = makeDescriptor([
{ name: 'label', type: 'string', required: true, autoFocus: true, defaultValue: 'Tab' },
]);
@@ -132,7 +132,7 @@ describe('PropPanel — Enter on a single-line string input dismisses', () => {
// breaks Enter for every string prop marked `advanced: true` (e.g.
// `<Tab id>`). Mirror the common-tier guard above so regressions
// can't slip back in.
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const d = makeDescriptor([
{ name: 'label', type: 'string', required: true, defaultValue: 'Tab' },
{ name: 'id', type: 'string', required: false, advanced: true },
@@ -161,7 +161,7 @@ describe('PropPanel — Enter on a single-line string input dismisses', () => {
// Tab, Escape, ArrowDown, character keys, etc. should not reach
// onDismiss. Otherwise typing a label would close the popover after
// one keystroke.
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const d = makeDescriptor([
{ name: 'label', type: 'string', required: true, autoFocus: true, defaultValue: 'Tab' },
]);
@@ -186,7 +186,7 @@ describe('PropPanel — Enter on a single-line string input dismisses', () => {
// contract as the plain Input branch. Without this, Embed sizing
// props are an exception to the form-submit contract the rest of
// PropPanel honors.
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const d = makeDescriptor([
{ name: 'width', type: 'string', required: false, cssLengthInput: true },
]);
@@ -203,7 +203,7 @@ describe('PropPanel — Enter on a single-line string input dismisses', () => {
// Pins Enter parity on the number variant — same single-line
// contract. Without this, a user typing an Image width/height
// pixel value would press Enter and have nothing happen.
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const d = makeDescriptor([{ name: 'width', type: 'number', required: false }]);
const { container } = render(
<PropPanel descriptor={d} values={{}} onChange={() => {}} onDismiss={onDismiss} />,
@@ -227,7 +227,7 @@ describe('PropPanel — Enter on a single-line string input dismisses', () => {
// takes the `onSubmit` branch (highlighted-suggestion-pick wins
// over dismiss when the popover is open with items).
stubAssetPaths.clear();
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
const d = makeDescriptor([
{
name: 'src',
diff --git a/packages/app/src/editor/components/PropPanel.test.tsx b/packages/app/src/editor/components/PropPanel.test.tsx
index a66e82476..79f294c00 100644
--- a/packages/app/src/editor/components/PropPanel.test.tsx
+++ b/packages/app/src/editor/components/PropPanel.test.tsx
@@ -17,9 +17,9 @@
* (Tab cycle, Esc close) exercises the panel end-to-end.
*/
-import { describe, expect, test } from 'bun:test';
import { builtInComponents, type PropDef } from '@inkeep/open-knowledge-core';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import type { JsxComponentDescriptor } from '../registry/types.ts';
const { countAdvancedSet, PropPanel, persistAdvancedOpenState, readAdvancedOpenState } =
@@ -1161,7 +1161,7 @@ describe('PropPanel — colorPicker branch', () => {
// runUpload unit tests were removed — Bun on Linux fires its
// unhandled-rejection observer for any rejected promise constructed in
-// the same `mock.module()` scope (regardless of rejection shape: string,
+// the same `vi.doMock()` scope (regardless of rejection shape: string,
// object, Error, throw-inside-async-body, Promise.reject with synchronous
// .catch pre-attach, or process.on('unhandledRejection') absorbing
// handler — all five tried, all five failed). The observer's event
diff --git a/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx b/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx
index 2d26b6855..7b0e35c1a 100644
--- a/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx
+++ b/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx
@@ -24,9 +24,9 @@
* shims around).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { ALLOWED_IMAGE_MIME_TYPES } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Radix Popover focus-trap reaches for these jsdom-missing pieces.
type GlobalShims = typeof globalThis & {
@@ -73,7 +73,7 @@ const stubPageListValue = {
refetch: () => {},
addPage: () => {},
};
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => stubPageListValue,
useOptionalPageList: () => stubPageListValue,
}));
@@ -167,7 +167,7 @@ describe('SrcAutocomplete — open behavior', () => {
describe('SrcAutocomplete — selection contract', () => {
test('clicking a suggestion emits onChange with leading-slash server-absolute path', () => {
stubAssetPaths.add('assets/photo.png');
- const onChange = mock((_v: string) => {});
+ const onChange = vi.fn((_v: string) => {});
render(
<SrcAutocomplete
@@ -193,7 +193,7 @@ describe('SrcAutocomplete — selection contract', () => {
test('typing then Enter on the highlighted item emits onChange with the path', () => {
stubAssetPaths.add('assets/photo.png');
stubAssetPaths.add('assets/banner.png');
- const onChange = mock((_v: string) => {});
+ const onChange = vi.fn((_v: string) => {});
render(
<SrcAutocomplete
@@ -244,7 +244,7 @@ describe('SrcAutocomplete — keyboard handling', () => {
test('Enter with no matching suggestions does NOT call onChange (no phantom selection)', () => {
// No assets — popover stays closed; Enter must not invoke selectSuggestion.
- const onChange = mock((_v: string) => {});
+ const onChange = vi.fn((_v: string) => {});
render(
<SrcAutocomplete
@@ -267,7 +267,7 @@ describe('SrcAutocomplete — keyboard handling', () => {
// wiring, Enter is a silent no-op for any user who typed a fresh
// value and pressed Enter expecting "I'm done" acknowledgment —
// the rename gesture.
- const onSubmit = mock(() => {});
+ const onSubmit = vi.fn(() => {});
render(
<SrcAutocomplete
id="prop-src"
@@ -288,8 +288,8 @@ describe('SrcAutocomplete — keyboard handling', () => {
// confirming the autocomplete pill they highlighted, not asking
// the popover to close.
stubAssetPaths.add('assets/photo.png');
- const onChange = mock((_v: string) => {});
- const onSubmit = mock(() => {});
+ const onChange = vi.fn((_v: string) => {});
+ const onSubmit = vi.fn(() => {});
render(
<SrcAutocomplete
id="prop-src"
diff --git a/packages/app/src/editor/components/Tab.test.tsx b/packages/app/src/editor/components/Tab.test.tsx
index 3851b5c60..0c104388e 100644
--- a/packages/app/src/editor/components/Tab.test.tsx
+++ b/packages/app/src/editor/components/Tab.test.tsx
@@ -11,8 +11,8 @@
* `renderToString`.
*/
-import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { Tab } from './Tab.tsx';
describe('Tab — strip-label contract', () => {
diff --git a/packages/app/src/editor/components/Tabs.dom.test.tsx b/packages/app/src/editor/components/Tabs.dom.test.tsx
index 85d71f5ab..8277efe3d 100644
--- a/packages/app/src/editor/components/Tabs.dom.test.tsx
+++ b/packages/app/src/editor/components/Tabs.dom.test.tsx
@@ -25,8 +25,8 @@
* fixture style.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { findNthTabGearButton, readTabSlots } from './Tabs.tsx';
// `cleanup` satisfies the *.dom.test.tsx -> @testing-library/react value-import
diff --git a/packages/app/src/editor/components/TagDialog.test.tsx b/packages/app/src/editor/components/TagDialog.test.tsx
index fccc11a64..50a74f7fc 100644
--- a/packages/app/src/editor/components/TagDialog.test.tsx
+++ b/packages/app/src/editor/components/TagDialog.test.tsx
@@ -4,8 +4,9 @@
* exercised in Playwright E2E (the wiring at app scope mounts during
* editor bootstrap and only fires post-click).
*/
-import { describe, expect, test } from 'bun:test';
+
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { TagDialogBody } from './TagDialog.tsx';
describe('TagDialogBody', () => {
diff --git a/packages/app/src/editor/components/TagView.test.tsx b/packages/app/src/editor/components/TagView.test.tsx
index 60db40a61..de0516bf2 100644
--- a/packages/app/src/editor/components/TagView.test.tsx
+++ b/packages/app/src/editor/components/TagView.test.tsx
@@ -23,9 +23,9 @@
* its own focus / commit lifecycle).
*/
-import { describe, expect, test } from 'bun:test';
import type { NodeViewProps } from '@tiptap/core';
import { renderToString } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { TagView } from './TagView.tsx';
/**
diff --git a/packages/app/src/editor/components/Video.dom.test.tsx b/packages/app/src/editor/components/Video.dom.test.tsx
index 3a337d277..560ff0f8e 100644
--- a/packages/app/src/editor/components/Video.dom.test.tsx
+++ b/packages/app/src/editor/components/Video.dom.test.tsx
@@ -7,9 +7,10 @@
*
* Runs under `bun run test:dom` (jsdom substrate per precedent #43).
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, fireEvent, render } from '@testing-library/react';
import { useEffect, useRef } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
// `@u-wave/react-vimeo` wraps `@vimeo/player`, which fires an XHR oEmbed
// lookup on `componentDidMount`. jsdom's XHR surface is partial enough
@@ -23,7 +24,7 @@ import { useEffect, useRef } from 'react';
// `onReady` with a fake player whose `.element` points at that iframe,
// mirroring the real lib's lifecycle closely enough to exercise the
// VimeoEmbed component's title-sync effect.
-mock.module('@u-wave/react-vimeo', () => {
+vi.doMock('@u-wave/react-vimeo', () => {
type MockProps = Record<string, unknown> & {
onReady?: (player: { element: HTMLIFrameElement | null }) => void;
};
diff --git a/packages/app/src/editor/components/lucide-icon-allowlist.test.ts b/packages/app/src/editor/components/lucide-icon-allowlist.test.ts
index 4c3042b3f..6ea80044d 100644
--- a/packages/app/src/editor/components/lucide-icon-allowlist.test.ts
+++ b/packages/app/src/editor/components/lucide-icon-allowlist.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
LUCIDE_ICON_ALLOWLIST,
LUCIDE_ICON_ENTRIES,
diff --git a/packages/app/src/editor/components/pdf-layout.test.ts b/packages/app/src/editor/components/pdf-layout.test.ts
index 1cc767611..10c314a9f 100644
--- a/packages/app/src/editor/components/pdf-layout.test.ts
+++ b/packages/app/src/editor/components/pdf-layout.test.ts
@@ -7,7 +7,7 @@
* these base scales.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeBaseScale, type PdfPageInfo } from './pdf-layout.ts';
const A4: PdfPageInfo = { naturalWidth: 612, naturalHeight: 792 };
diff --git a/packages/app/src/editor/components/use-mirror-source.test.ts b/packages/app/src/editor/components/use-mirror-source.test.ts
index 1a3639a6d..9de8c4f48 100644
--- a/packages/app/src/editor/components/use-mirror-source.test.ts
+++ b/packages/app/src/editor/components/use-mirror-source.test.ts
@@ -7,7 +7,7 @@
* synthesis can't silently regress.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { findMirrorSource, renderMirrorSubtree } from './use-mirror-source.ts';
// Build a structurally-correct mdast subset for the tests. The hook's local
diff --git a/packages/app/src/editor/composer-mention/ComposerMentionMenu.dom.test.tsx b/packages/app/src/editor/composer-mention/ComposerMentionMenu.dom.test.tsx
index b5d7bee17..b8ed08c66 100644
--- a/packages/app/src/editor/composer-mention/ComposerMentionMenu.dom.test.tsx
+++ b/packages/app/src/editor/composer-mention/ComposerMentionMenu.dom.test.tsx
@@ -14,8 +14,9 @@
* signal, so they cannot be distinguished at this row (see the component's
* `mentionItemKind` note).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, screen, within } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { ComposerMentionMenu } from './ComposerMentionMenu';
import type { MentionItem } from './composer-mention';
diff --git a/packages/app/src/editor/composer-mention/composer-mention.test.ts b/packages/app/src/editor/composer-mention/composer-mention.test.ts
index 76c93e45f..2b61755d3 100644
--- a/packages/app/src/editor/composer-mention/composer-mention.test.ts
+++ b/packages/app/src/editor/composer-mention/composer-mention.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { PageItem } from '../extensions/wiki-link-suggestion';
import { createMentionCorpus, pageItemToPath } from './composer-mention';
diff --git a/packages/app/src/editor/edit-with-ai-selection.test.ts b/packages/app/src/editor/edit-with-ai-selection.test.ts
index 3b625a803..5326137ea 100644
--- a/packages/app/src/editor/edit-with-ai-selection.test.ts
+++ b/packages/app/src/editor/edit-with-ai-selection.test.ts
@@ -7,9 +7,9 @@
* names, so the real serialize pipeline handles the synthetic slice.
*/
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import type { Editor } from '@tiptap/react';
+import { describe, expect, test } from 'vitest';
import { serializeWysiwygSelection } from './edit-with-ai-selection.ts';
const schema = new Schema({
diff --git a/packages/app/src/editor/editor-cache.test.ts b/packages/app/src/editor/editor-cache.test.ts
index f5be00776..b6ea4518d 100644
--- a/packages/app/src/editor/editor-cache.test.ts
+++ b/packages/app/src/editor/editor-cache.test.ts
@@ -21,12 +21,12 @@
* code path without module reload).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { Compartment } from '@codemirror/state';
import type { EditorView } from '@codemirror/view';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Editor } from '@tiptap/core';
import { yUndoPluginKey } from '@tiptap/y-tiptap';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import {
__consumeRenameSnapshot,
@@ -490,7 +490,7 @@ describe('TipTap cache — lifecycle', () => {
factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
});
// Spy on ydoc.destroy
- const ydocDestroySpy = mock(h.ydoc.destroy.bind(h.ydoc));
+ const ydocDestroySpy = vi.fn(h.ydoc.destroy.bind(h.ydoc));
h.ydoc.destroy = ydocDestroySpy;
const result = evictTiptapEditor(h.docName);
@@ -1163,7 +1163,7 @@ describe('CM6 cache — lifecycle', () => {
container: h.container as unknown as HTMLElement,
factory: h.factory as unknown as (el: HTMLElement) => ReturnType<typeof h.factory>,
});
- const ydocDestroySpy = mock(h.ydoc.destroy.bind(h.ydoc));
+ const ydocDestroySpy = vi.fn(h.ydoc.destroy.bind(h.ydoc));
h.ydoc.destroy = ydocDestroySpy;
expect(evictCmEditor(h.docName)).toBe(true);
@@ -1943,15 +1943,15 @@ describe('telemetry marks', () => {
test('connect telemetry is mutually exclusive: reject emits connect-failed only (no preceding connect)', async () => {
const rejectingProvider = {
document: new Y.Doc(),
- destroy: mock(() => {}),
- connect: mock(() => Promise.reject(new Error('connect failed'))),
- disconnect: mock(() => {}),
+ destroy: vi.fn(() => {}),
+ connect: vi.fn(() => Promise.reject(new Error('connect failed'))),
+ disconnect: vi.fn(() => {}),
} as unknown as HocuspocusProvider;
const dom = makeNode();
const editor = {
editorView: { dom, scrollDOM: dom },
- commands: { focus: mock(() => {}) },
- destroy: mock(() => {}),
+ commands: { focus: vi.fn(() => {}) },
+ destroy: vi.fn(() => {}),
} as unknown as Editor;
const ytext = rejectingProvider.document.getText('source');
mountTiptapEditor({
diff --git a/packages/app/src/editor/editor-tabs.test.ts b/packages/app/src/editor/editor-tabs.test.ts
index 0a8e33a5c..59d51a611 100644
Binary files a/packages/app/src/editor/editor-tabs.test.ts and b/packages/app/src/editor/editor-tabs.test.ts differ
diff --git a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
index 96fbba163..b82f374f8 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.dom.test.tsx
@@ -9,10 +9,10 @@
* `srcdoc`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { Config } from '@inkeep/open-knowledge-core';
import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
import type { NodeViewProps } from '@tiptap/core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { subscribeToOpenAskAiComposer } from '@/components/ask-ai-composer-events';
import { subscribeToActiveTerminalInput } from '@/components/handoff/terminal-input-events';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
@@ -21,7 +21,7 @@ import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
// runs the full markdown pipeline against the selected slice. Testing that
// pipeline end-to-end is the fidelity suite's job; this file tests the
// click→dispatch contract, so stub the serializer to a fixed fenced body.
-mock.module('../edit-with-ai-selection', () => ({
+vi.doMock('../edit-with-ai-selection', () => ({
serializeWysiwygSelection: () => '```json\n{ "name": "sample" }\n```',
}));
diff --git a/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx b/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx
index b7c674c5a..b263bfabb 100644
--- a/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/ImageInlineZoomView.dom.test.tsx
@@ -5,7 +5,7 @@
* `Image.dom.test.tsx` pins the loading-skeleton contract for the
* descriptor renderer.
*
- * `@tiptap/react` is intentionally NOT module-mocked: `mock.module`
+ * `@tiptap/react` is intentionally NOT module-mocked: `vi.doMock`
* replaces the whole module and the patch survives Bun's `--isolate`
* across files in the same `bun test` invocation (oven-sh/bun#12823-class
* leakage). Sibling files lazily import `./image-inline-zoom` →
@@ -13,10 +13,11 @@
* The real `NodeViewWrapper` works fine in jsdom for standalone
* `render()` — the inline-`<span>` choice IS the assertion.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('react-medium-image-zoom', () => ({
+vi.doMock('react-medium-image-zoom', () => ({
default: ({
children,
wrapElement,
diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
index 63a472637..580fc0231 100644
--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { Editor } from '@tiptap/core';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
if (typeof globalThis.DOMRect === 'undefined') {
@@ -37,7 +37,7 @@ let currentMarkInfo: CurrentMarkInfo | null = {
to: 4,
};
-mock.module('../../components/PageListContext', () => ({
+vi.doMock('../../components/PageListContext', () => ({
usePageList: () => ({
addPage: () => {},
folderPaths: new Set<string>(),
@@ -46,11 +46,11 @@ mock.module('../../components/PageListContext', () => ({
}),
}));
-mock.module('./mark-interaction-bridge', () => ({
+vi.doMock('./mark-interaction-bridge', () => ({
getCurrentMarkInfo: () => currentMarkInfo,
}));
-mock.module('./use-headings', () => ({
+vi.doMock('./use-headings', () => ({
useHeadings: () => [],
}));
@@ -65,20 +65,20 @@ const loadHarness: { calls: number; result: LinkPreviewMetadata | null } = {
};
const configHarness = { enabled: false };
-mock.module('../link-preview/external-link-preview.ts', () => ({
+vi.doMock('../link-preview/external-link-preview.ts', () => ({
loadLinkPreview: (_url: string, _signal?: AbortSignal) => {
loadHarness.calls += 1;
return Promise.resolve(loadHarness.result);
},
}));
-mock.module('../../lib/config-provider', () => ({
+vi.doMock('../../lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalConfig: { linkPreviews: { enabled: configHarness.enabled } },
}),
}));
-mock.module('../../components/InteractionPropPanel', () => ({
+vi.doMock('../../components/InteractionPropPanel', () => ({
InteractionPropPanel: ({ children }: { children: ReactNode }) => (
<div data-testid="prop-panel">{children}</div>
),
@@ -172,8 +172,8 @@ describe('InternalLinkPropPanel', () => {
});
test('deletes the pending empty-href placeholder when the edit dialog is canceled', async () => {
- const deleteRange = mock((_range: { from: number; to: number }) => {});
- const onClose = mock(() => {});
+ const deleteRange = vi.fn((_range: { from: number; to: number }) => {});
+ const onClose = vi.fn(() => {});
setPendingLinkEdit('m1');
render(
@@ -199,9 +199,9 @@ describe('InternalLinkPropPanel', () => {
});
test('does not delete the pending mark when the edit dialog saves a URL', async () => {
- const deleteRange = mock((_range: { from: number; to: number }) => {});
- const onClose = mock(() => {});
- const updateAttributes = mock((_markType: string, attrs: Record<string, unknown>) => {
+ const deleteRange = vi.fn((_range: { from: number; to: number }) => {});
+ const onClose = vi.fn(() => {});
+ const updateAttributes = vi.fn((_markType: string, attrs: Record<string, unknown>) => {
if (!currentMarkInfo) return;
currentMarkInfo = {
...currentMarkInfo,
@@ -239,8 +239,8 @@ describe('InternalLinkPropPanel', () => {
});
test('closes without deleting when the pending mark was already removed remotely', async () => {
- const deleteRange = mock((_range: { from: number; to: number }) => {});
- const onClose = mock(() => {});
+ const deleteRange = vi.fn((_range: { from: number; to: number }) => {});
+ const onClose = vi.fn(() => {});
setPendingLinkEdit('m1');
render(
diff --git a/packages/app/src/editor/extensions/InternalLinkPropPanel.test.ts b/packages/app/src/editor/extensions/InternalLinkPropPanel.test.ts
index 8556e8e74..bfc060de5 100644
--- a/packages/app/src/editor/extensions/InternalLinkPropPanel.test.ts
+++ b/packages/app/src/editor/extensions/InternalLinkPropPanel.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { getMarkdownLinkEditMode } from './InternalLinkPropPanel';
describe('getMarkdownLinkEditMode', () => {
diff --git a/packages/app/src/editor/extensions/JsxComponentView.test.ts b/packages/app/src/editor/extensions/JsxComponentView.test.ts
index 21aebf73a..751f7f75f 100644
--- a/packages/app/src/editor/extensions/JsxComponentView.test.ts
+++ b/packages/app/src/editor/extensions/JsxComponentView.test.ts
@@ -21,10 +21,10 @@
* prop edits.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { extractPrimitiveProps, getElementJsxAttrs, stableHash } from './JsxComponentView.tsx';
/** Test helper: build a `ReadonlySet<string>` of reactnode-typed prop names.
diff --git a/packages/app/src/editor/extensions/RawMdxFallbackCMView.dom.test.tsx b/packages/app/src/editor/extensions/RawMdxFallbackCMView.dom.test.tsx
index fbbcb55ce..1bedacad2 100644
--- a/packages/app/src/editor/extensions/RawMdxFallbackCMView.dom.test.tsx
+++ b/packages/app/src/editor/extensions/RawMdxFallbackCMView.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { Config } from '@inkeep/open-knowledge-core';
import { cleanup, render, waitFor } from '@testing-library/react';
import type { NodeViewProps } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { RawMdxFallbackView } from './RawMdxFallbackCMView';
@@ -86,7 +86,7 @@ async function findCmContent(container: HTMLElement): Promise<HTMLElement> {
describe('RawMdxFallbackView word-wrap preference wiring', () => {
beforeEach(() => {
- globalThis.fetch = mock(async (input: RequestInfo | URL) => {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === '/api/pages') {
return Response.json({ pages: [] });
diff --git a/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts b/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts
index 966d599df..f715179a1 100644
--- a/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts
+++ b/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts
@@ -8,13 +8,13 @@
* (Precedent #31 "Selection state as typed PM PluginState").
*/
-import { describe, expect, test } from 'bun:test';
import { EditorState as CMEditorState } from '@codemirror/state';
import type { EditorView as CMEditorView } from '@codemirror/view';
import { sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import type { Node as PMNode } from '@tiptap/pm/model';
import { NodeSelection, TextSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import {
computeChange,
computeCMSelectionForwarding,
diff --git a/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx b/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx
index 31be264e6..63c423a51 100644
--- a/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx
+++ b/packages/app/src/editor/extensions/WikiLinkPropPanel.dom.test.tsx
@@ -12,10 +12,10 @@
* stubbed verdict. Lingui macros resolve to the English-passthrough shim.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import type { Editor } from '@tiptap/core';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { InternalDocPreview } from '../link-preview/internal-doc-preview.ts';
@@ -36,18 +36,18 @@ const previewHarness: { value: InternalDocPreview } = {
},
};
-mock.module('../link-preview/use-internal-doc-preview.ts', () => ({
+vi.doMock('../link-preview/use-internal-doc-preview.ts', () => ({
useInternalDocPreview: ({ docName }: { docName: string | null }) =>
docName ? previewHarness.value : null,
}));
-mock.module('../../components/InteractionPropPanel', () => ({
+vi.doMock('../../components/InteractionPropPanel', () => ({
InteractionPropPanel: ({ children }: { children: ReactNode }) => (
<div data-testid="prop-panel">{children}</div>
),
}));
-mock.module('../../components/PageListContext', () => ({
+vi.doMock('../../components/PageListContext', () => ({
usePageList: () => ({
addPage: () => {},
assetPaths: new Set<string>(),
diff --git a/packages/app/src/editor/extensions/autonomous-fragment-edit.test.ts b/packages/app/src/editor/extensions/autonomous-fragment-edit.test.ts
index ddfa1efb9..2d591b615 100644
--- a/packages/app/src/editor/extensions/autonomous-fragment-edit.test.ts
+++ b/packages/app/src/editor/extensions/autonomous-fragment-edit.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { autonomousFragmentEditAllowed } from './autonomous-fragment-edit.ts';
import { setEditorSourceMode } from './editor-mode-context.ts';
diff --git a/packages/app/src/editor/extensions/block-mover.test.ts b/packages/app/src/editor/extensions/block-mover.test.ts
index e6d1fe47d..c3575d171 100644
--- a/packages/app/src/editor/extensions/block-mover.test.ts
+++ b/packages/app/src/editor/extensions/block-mover.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, TextSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import { currentTopLevelBlock, moveBlockDown, moveBlockUp } from './block-mover';
const schema = new Schema({
diff --git a/packages/app/src/editor/extensions/bridge-id-plugin.test.ts b/packages/app/src/editor/extensions/bridge-id-plugin.test.ts
index cfb27e123..c65d8f3e4 100644
--- a/packages/app/src/editor/extensions/bridge-id-plugin.test.ts
+++ b/packages/app/src/editor/extensions/bridge-id-plugin.test.ts
@@ -16,9 +16,9 @@
* without spinning up a Hocuspocus client.
*/
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, NodeSelection, TextSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import {
assertBridgeIdInvariant,
BridgeIdPlugin,
diff --git a/packages/app/src/editor/extensions/cell-insertion-gate.test.ts b/packages/app/src/editor/extensions/cell-insertion-gate.test.ts
index 3ce5902de..ba48af4d3 100644
--- a/packages/app/src/editor/extensions/cell-insertion-gate.test.ts
+++ b/packages/app/src/editor/extensions/cell-insertion-gate.test.ts
@@ -14,20 +14,20 @@
* to a branch that would re-insert the refused content elsewhere.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
import { sharedExtensions as coreExtensions, MarkdownManager } from '@inkeep/open-knowledge-core';
import { Editor, type JSONContent } from '@tiptap/core';
import { Fragment, type Node as ProseMirrorNode, Slice } from '@tiptap/pm/model';
import { dropPoint, ReplaceAroundStep } from '@tiptap/pm/transform';
import { ySyncPluginKey } from '@tiptap/y-tiptap';
import * as actualSonner from 'sonner';
+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { installDomGlobals } from '../walk-currency-test-harness';
import { CellInsertionGate } from './cell-insertion-gate';
// The paste dispatcher pulls the degrade-path toast (sonner) into its import
// graph; stub it so module load stays inert in the jsdom env. The gate's no-op
// path never degrades, so the stub is never invoked.
-mock.module('sonner', () => ({ ...actualSonner, toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ ...actualSonner, toast: { error: vi.fn(() => {}) } }));
const mdManager = new MarkdownManager({ extensions: coreExtensions });
diff --git a/packages/app/src/editor/extensions/chunk-wrapper-decoration.test.ts b/packages/app/src/editor/extensions/chunk-wrapper-decoration.test.ts
index 4e28458df..250f26664 100644
--- a/packages/app/src/editor/extensions/chunk-wrapper-decoration.test.ts
+++ b/packages/app/src/editor/extensions/chunk-wrapper-decoration.test.ts
@@ -11,10 +11,10 @@
* no live editor or DOM mount required.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, type Plugin } from '@tiptap/pm/state';
import type { DecorationSet } from '@tiptap/pm/view';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetFirstEmitForTesting,
chunkWrapperDecorationKey,
diff --git a/packages/app/src/editor/extensions/code-block-languages.test.ts b/packages/app/src/editor/extensions/code-block-languages.test.ts
index a02da06e6..1a11a2be3 100644
--- a/packages/app/src/editor/extensions/code-block-languages.test.ts
+++ b/packages/app/src/editor/extensions/code-block-languages.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { CODE_BLOCK_LANGUAGES, normalizeCodeLanguage } from './code-block-languages';
describe('normalizeCodeLanguage', () => {
diff --git a/packages/app/src/editor/extensions/code-block-meta.test.ts b/packages/app/src/editor/extensions/code-block-meta.test.ts
index 032799109..e546d5a4f 100644
--- a/packages/app/src/editor/extensions/code-block-meta.test.ts
+++ b/packages/app/src/editor/extensions/code-block-meta.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
addMetaToken,
getMetaKeyValue,
diff --git a/packages/app/src/editor/extensions/code-block-preview-csp.test.ts b/packages/app/src/editor/extensions/code-block-preview-csp.test.ts
index c0fcd9af5..4438773ff 100644
--- a/packages/app/src/editor/extensions/code-block-preview-csp.test.ts
+++ b/packages/app/src/editor/extensions/code-block-preview-csp.test.ts
@@ -11,7 +11,7 @@
* was reviewed.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildPreviewIframeHeader } from './preview-iframe-header';
/** Pull the raw CSP string out of the `<meta>` tag (no `"` appears inside it). */
diff --git a/packages/app/src/editor/extensions/frozen-table-headers.test.ts b/packages/app/src/editor/extensions/frozen-table-headers.test.ts
index 5aafe32cc..6f8e14f64 100644
--- a/packages/app/src/editor/extensions/frozen-table-headers.test.ts
+++ b/packages/app/src/editor/extensions/frozen-table-headers.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'bun:test';
+import { describe, expect, it } from 'vitest';
import { buildShiftKeyframes, computeFreezeRange } from './frozen-table-headers.ts';
describe('computeFreezeRange (scroll-driven animation ranges)', () => {
diff --git a/packages/app/src/editor/extensions/internal-link.external-open.test.ts b/packages/app/src/editor/extensions/internal-link.external-open.test.ts
index 86bfa4951..376de8176 100644
--- a/packages/app/src/editor/extensions/internal-link.external-open.test.ts
+++ b/packages/app/src/editor/extensions/internal-link.external-open.test.ts
@@ -25,10 +25,10 @@
* the same per-file DOM install the other headless editor-plugin suites use.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
import { Editor } from '@tiptap/core';
import { TextSelection } from '@tiptap/pm/state';
import StarterKit from '@tiptap/starter-kit';
+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { getInteractionLayer } from '../interaction-layer-host';
import { installDomGlobals } from '../walk-currency-test-harness';
import { InternalLink } from './internal-link';
@@ -117,8 +117,8 @@ function mountWithExternalLink(url: string): {
describe('WYSIWYG external-link activation — desktop (bridge present)', () => {
test('bare click routes to the OS browser via okDesktop.shell.openExternal, NOT window.open', () => {
const url = 'https://youtube.com/watch?v=abc';
- const openExternal = mock(async (_url: string) => {});
- const openWindow = mock(() => null);
+ const openExternal = vi.fn(async (_url: string) => {});
+ const openWindow = vi.fn(() => null);
const w = testWindow();
w.okDesktop = { shell: { openExternal } };
w.open = openWindow as unknown as OpenExternalWindow['open'];
@@ -139,8 +139,8 @@ describe('WYSIWYG external-link activation — desktop (bridge present)', () =>
// External URLs must land in the OS browser on EVERY activation — bare or
// modifier-click. The modifier path must not fall back to window.open.
const url = 'https://example.com/path';
- const openExternal = mock(async (_url: string) => {});
- const openWindow = mock(() => null);
+ const openExternal = vi.fn(async (_url: string) => {});
+ const openWindow = vi.fn(() => null);
const w = testWindow();
w.okDesktop = { shell: { openExternal } };
w.open = openWindow as unknown as OpenExternalWindow['open'];
@@ -160,7 +160,7 @@ describe('WYSIWYG external-link activation — web (no bridge)', () => {
// the fix from regressing the web path to a no-op.
test('bare click falls back to window.open with the new-tab + noopener features', () => {
const url = 'https://example.com/web';
- const openWindow = mock(() => null);
+ const openWindow = vi.fn(() => null);
const w = testWindow();
delete w.okDesktop;
w.open = openWindow as unknown as OpenExternalWindow['open'];
diff --git a/packages/app/src/editor/extensions/link-edit-autoopen.test.ts b/packages/app/src/editor/extensions/link-edit-autoopen.test.ts
index 3d9d33d21..952d027e3 100644
--- a/packages/app/src/editor/extensions/link-edit-autoopen.test.ts
+++ b/packages/app/src/editor/extensions/link-edit-autoopen.test.ts
@@ -14,7 +14,7 @@
* double-consume a single flag. Mirrors `auto-open-flag.test.ts`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
_resetPendingLinkEditForTest,
consumePendingLinkEdit,
diff --git a/packages/app/src/editor/extensions/link-resolution-decoration.test.ts b/packages/app/src/editor/extensions/link-resolution-decoration.test.ts
index ccbe947da..30c0729af 100644
--- a/packages/app/src/editor/extensions/link-resolution-decoration.test.ts
+++ b/packages/app/src/editor/extensions/link-resolution-decoration.test.ts
@@ -12,10 +12,10 @@
* and `dispatch`).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { type Mark, Schema } from '@tiptap/pm/model';
import { EditorState, type Transaction } from '@tiptap/pm/state';
import type { DecorationSet, EditorView } from '@tiptap/pm/view';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetPageListCacheForTests,
type PageListCacheSnapshot,
diff --git a/packages/app/src/editor/extensions/link-resolution.test.ts b/packages/app/src/editor/extensions/link-resolution.test.ts
index 1896e80fd..92a0b54c7 100644
--- a/packages/app/src/editor/extensions/link-resolution.test.ts
+++ b/packages/app/src/editor/extensions/link-resolution.test.ts
@@ -12,8 +12,8 @@
* and produces a closure the decoration plugin can call many times.
*/
-import { describe, expect, test } from 'bun:test';
import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { buildPagesBySlugIndex, type PageListCacheSnapshot } from '../page-list-cache';
import {
computeLinkResolutionAttrs,
diff --git a/packages/app/src/editor/extensions/mark-identity-decoration.test.ts b/packages/app/src/editor/extensions/mark-identity-decoration.test.ts
index 86cf594f0..cef349616 100644
--- a/packages/app/src/editor/extensions/mark-identity-decoration.test.ts
+++ b/packages/app/src/editor/extensions/mark-identity-decoration.test.ts
@@ -8,10 +8,10 @@
* editor needed.
*/
-import { describe, expect, test } from 'bun:test';
import { type Mark, Schema } from '@tiptap/pm/model';
import { EditorState, type Plugin } from '@tiptap/pm/state';
import type { DecorationSet } from '@tiptap/pm/view';
+import { describe, expect, test } from 'vitest';
import { markIdentityPlugin } from './mark-identity';
import {
MARK_ID_DATA_ATTR,
diff --git a/packages/app/src/editor/extensions/mark-identity.test.ts b/packages/app/src/editor/extensions/mark-identity.test.ts
index f8e8b35ff..a9f6385c3 100644
--- a/packages/app/src/editor/extensions/mark-identity.test.ts
+++ b/packages/app/src/editor/extensions/mark-identity.test.ts
@@ -8,9 +8,9 @@
* (InternalLink port).
*/
-import { describe, expect, test } from 'bun:test';
import { type Mark, Schema } from '@tiptap/pm/model';
import { EditorState } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import {
computeMarkIdentity,
diffMarkIdentity,
diff --git a/packages/app/src/editor/extensions/mark-interaction-bridge.test.tsx b/packages/app/src/editor/extensions/mark-interaction-bridge.test.tsx
index 267e5c26b..2556c296f 100644
--- a/packages/app/src/editor/extensions/mark-interaction-bridge.test.tsx
+++ b/packages/app/src/editor/extensions/mark-interaction-bridge.test.tsx
@@ -14,10 +14,10 @@
* diffs) is already covered by mark-identity.test.ts.
*/
-import { describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/core';
import { type Mark, Schema } from '@tiptap/pm/model';
import { EditorState } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import {
type InteractionContext,
type InteractionLayerHandle,
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
index e36816931..4b615c3fd 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
@@ -6,12 +6,12 @@
* source the diagnostics were linted against).
*/
-import { describe, expect, test } from 'bun:test';
import {
sharedExtensions as coreExtensions,
type LintDiagnostic,
MarkdownManager,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
blockIndexForLine,
computeSourceBlockSpans,
diff --git a/packages/app/src/editor/extensions/media-render-props.test.ts b/packages/app/src/editor/extensions/media-render-props.test.ts
index 23c9763f8..d1ad96c11 100644
--- a/packages/app/src/editor/extensions/media-render-props.test.ts
+++ b/packages/app/src/editor/extensions/media-render-props.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { normalizeDocRelativeMediaRenderProps } from './media-render-props.ts';
describe('normalizeDocRelativeMediaRenderProps', () => {
diff --git a/packages/app/src/editor/extensions/nested-cm-extensions.test.ts b/packages/app/src/editor/extensions/nested-cm-extensions.test.ts
index 8a7b3290a..d553e13e9 100644
--- a/packages/app/src/editor/extensions/nested-cm-extensions.test.ts
+++ b/packages/app/src/editor/extensions/nested-cm-extensions.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { Compartment, EditorState } from '@codemirror/state';
import { EditorView } from '@codemirror/view';
+import { describe, expect, test } from 'vitest';
import { createNestedCMExtensions } from './nested-cm-extensions';
function hasLineWrapping(state: EditorState): boolean {
diff --git a/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts b/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts
index d489046f4..6ed9398c9 100644
--- a/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts
+++ b/packages/app/src/editor/extensions/preview-iframe-csp-violation.test.ts
@@ -14,7 +14,7 @@
* key that {@link parsePreviewCspViolationMessage} can read. The CSP itself is
* unchanged — `code-block-preview-csp.test.ts` continues to guard its bytes.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
buildPreviewIframeHeader,
PREVIEW_CSP_VIOLATION_SAMPLE_CAP,
@@ -40,7 +40,7 @@ function evalBootstrap() {
listeners[type] ||= [];
listeners[type].push(fn);
};
- const postMessage = mock((_msg: unknown, _origin?: string) => {});
+ const postMessage = vi.fn((_msg: unknown, _origin?: string) => {});
const documentStub = {
documentElement: { classList: { add() {}, remove() {} } },
readyState: 'complete',
@@ -80,7 +80,7 @@ function evalBootstrap() {
}
/** Pull the latest CSP-violation payload the bootstrap posted to the parent. */
-function latestCspReport(postMessage: ReturnType<typeof mock>) {
+function latestCspReport(postMessage: ReturnType<typeof vi.fn>) {
const calls = postMessage.mock.calls.filter(
(c) => parsePreviewCspViolationMessage(c[0]) !== null,
);
diff --git a/packages/app/src/editor/extensions/preview-iframe-theme.test.ts b/packages/app/src/editor/extensions/preview-iframe-theme.test.ts
index 5584eea14..ba1065583 100644
--- a/packages/app/src/editor/extensions/preview-iframe-theme.test.ts
+++ b/packages/app/src/editor/extensions/preview-iframe-theme.test.ts
@@ -11,8 +11,9 @@
* reporter present, and — load-bearing for the no-reload toggle — the two
* per-theme headers differing by exactly the baked initial-class statement.
*/
-import { describe, expect, test } from 'bun:test';
+
import { PREVIEW_THEME_TOKENS } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
buildPreviewIframeHeader,
buildPreviewThemeMessage,
diff --git a/packages/app/src/editor/extensions/raw-mdx-fallback.test.ts b/packages/app/src/editor/extensions/raw-mdx-fallback.test.ts
index 64c87dcb6..007196a04 100644
--- a/packages/app/src/editor/extensions/raw-mdx-fallback.test.ts
+++ b/packages/app/src/editor/extensions/raw-mdx-fallback.test.ts
@@ -17,11 +17,11 @@
* side matching `dir`.
*/
-import { describe, expect, test } from 'bun:test';
import { sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import type { Node as PMNode } from '@tiptap/pm/model';
import { EditorState, TextSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import { computeArrowIntoTargetAtBoundary } from './raw-mdx-fallback';
const schema = getSchema(sharedExtensions);
diff --git a/packages/app/src/editor/extensions/raw-mdx-nested-copy-version-pin.test.ts b/packages/app/src/editor/extensions/raw-mdx-nested-copy-version-pin.test.ts
index 45037ae80..5d1b7542f 100644
--- a/packages/app/src/editor/extensions/raw-mdx-nested-copy-version-pin.test.ts
+++ b/packages/app/src/editor/extensions/raw-mdx-nested-copy-version-pin.test.ts
@@ -32,10 +32,10 @@
* in the repo use.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
+import { describe, expect, test } from 'vitest';
/**
* Versions the nested-box copy behavior was verified working at. A resolved
diff --git a/packages/app/src/editor/extensions/selection-state-plugin.test.ts b/packages/app/src/editor/extensions/selection-state-plugin.test.ts
index 60ef2ae2b..2c1f0aa85 100644
--- a/packages/app/src/editor/extensions/selection-state-plugin.test.ts
+++ b/packages/app/src/editor/extensions/selection-state-plugin.test.ts
@@ -8,9 +8,9 @@
* is testable here because it's tr-meta-based.
*/
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState, NodeSelection, Plugin, TextSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import { bridgeIdPluginKey } from './bridge-id-plugin.ts';
import {
type BlockSelection,
diff --git a/packages/app/src/editor/extensions/shared.dom.test.tsx b/packages/app/src/editor/extensions/shared.dom.test.tsx
index d6be67712..4c042b2a6 100644
--- a/packages/app/src/editor/extensions/shared.dom.test.tsx
+++ b/packages/app/src/editor/extensions/shared.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup } from '@testing-library/react';
import { Editor } from '@tiptap/core';
import { NodeSelection } from '@tiptap/pm/state';
+import { afterEach, describe, expect, test } from 'vitest';
import { sharedExtensions } from './shared';
describe('sharedExtensions module graph', () => {
diff --git a/packages/app/src/editor/extensions/source-dirty-flip.dom.test.tsx b/packages/app/src/editor/extensions/source-dirty-flip.dom.test.tsx
index 4b093bb07..a52fb96a2 100644
--- a/packages/app/src/editor/extensions/source-dirty-flip.dom.test.tsx
+++ b/packages/app/src/editor/extensions/source-dirty-flip.dom.test.tsx
@@ -14,10 +14,11 @@
* (no prop change) so the pin isolates the `contentChanged` term specifically:
* reverting only that term turns this test red.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { sharedExtensions as coreExtensions, MarkdownManager } from '@inkeep/open-knowledge-core';
import { cleanup } from '@testing-library/react';
import { Editor, type JSONContent } from '@tiptap/core';
+import { afterEach, describe, expect, test } from 'vitest';
// The app extensions carry the SourceDirtyObserver plugin + jsxComponent
// NodeView; the mounted editor must use these, not core's (which omit the
// observer). Serialization still goes through core's MarkdownManager — the
diff --git a/packages/app/src/editor/extensions/source-dirty-fold-atomicity.dom.test.tsx b/packages/app/src/editor/extensions/source-dirty-fold-atomicity.dom.test.tsx
index bc2074ef5..011016467 100644
--- a/packages/app/src/editor/extensions/source-dirty-fold-atomicity.dom.test.tsx
+++ b/packages/app/src/editor/extensions/source-dirty-fold-atomicity.dom.test.tsx
@@ -24,13 +24,14 @@
* not vacuously counting one.
*
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { sharedExtensions as coreExtensions, MarkdownManager } from '@inkeep/open-knowledge-core';
import { type ObserverDispatchKind, setupServerObservers } from '@inkeep/open-knowledge-server';
import { cleanup } from '@testing-library/react';
import { Editor, getSchema, type JSONContent } from '@tiptap/core';
import Collaboration from '@tiptap/extension-collaboration';
import { updateYFragment } from '@tiptap/y-tiptap';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { sharedExtensions } from './shared';
diff --git a/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts b/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts
index a8139151f..1cafc9207 100644
--- a/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts
+++ b/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts
@@ -26,7 +26,7 @@
* property of the plugin itself — the multi-client integration harness
* would add orders of magnitude of wall time without adding signal.
*/
-import { describe, expect, test } from 'bun:test';
+
import { getSchema } from '@tiptap/core';
import { EditorState, type Plugin, type Transaction } from '@tiptap/pm/state';
// Same source as source-dirty-observer.ts (and bridge-id-plugin.ts +
@@ -36,6 +36,7 @@ import { EditorState, type Plugin, type Transaction } from '@tiptap/pm/state';
// never tag, causing the origin-guard test to assert the wrong behavior.
// Pinned by y-prosemirror-import-coverage.test.ts.
import { ySyncPluginKey } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from './shared';
import { SourceDirtyObserver, sourceDirtyPluginKey } from './source-dirty-observer';
diff --git a/packages/app/src/editor/extensions/source-dirty-serialize.test.ts b/packages/app/src/editor/extensions/source-dirty-serialize.test.ts
index 335cff09f..2be1e0e99 100644
--- a/packages/app/src/editor/extensions/source-dirty-serialize.test.ts
+++ b/packages/app/src/editor/extensions/source-dirty-serialize.test.ts
@@ -11,9 +11,10 @@
* - Dirty (sourceDirty:true) → reconstruction path emitted
* - effectiveDirty (descendant dirty) → parent reconstructs
*/
-import { describe, expect, test } from 'bun:test';
+
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
diff --git a/packages/app/src/editor/extensions/tab-focus-trap.test.ts b/packages/app/src/editor/extensions/tab-focus-trap.test.ts
index d93c82734..194615f8a 100644
--- a/packages/app/src/editor/extensions/tab-focus-trap.test.ts
+++ b/packages/app/src/editor/extensions/tab-focus-trap.test.ts
@@ -26,7 +26,7 @@
* accidental removal / priority bump / typo'd key name — that's structural.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from './shared';
import { TabFocusTrap } from './tab-focus-trap';
diff --git a/packages/app/src/editor/extensions/table-insert-commands.test.ts b/packages/app/src/editor/extensions/table-insert-commands.test.ts
index 85bba13d3..3cd1636ca 100644
--- a/packages/app/src/editor/extensions/table-insert-commands.test.ts
+++ b/packages/app/src/editor/extensions/table-insert-commands.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import { sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
import { EditorState } from '@tiptap/pm/state';
import { TableMap } from '@tiptap/pm/tables';
+import { describe, expect, test } from 'vitest';
import { appendTableColumn, appendTableRow } from './table-insert-commands';
// Build the schema from core's shared extensions (an app dependency) rather
diff --git a/packages/app/src/editor/extensions/tag-suggestion.test.ts b/packages/app/src/editor/extensions/tag-suggestion.test.ts
index bf94f9d6b..b497e580a 100644
--- a/packages/app/src/editor/extensions/tag-suggestion.test.ts
+++ b/packages/app/src/editor/extensions/tag-suggestion.test.ts
@@ -7,7 +7,7 @@
* and the case-sensitivity of the duplicate check.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildTagSuggestionItems, type TagSummaryEntry, tagMatcher } from './tag-suggestion.ts';
const tags = (entries: Array<[string, number]>): TagSummaryEntry[] =>
diff --git a/packages/app/src/editor/extensions/wiki-link-embed.test.ts b/packages/app/src/editor/extensions/wiki-link-embed.test.ts
index 5f8f4e8c6..ceecbce85 100644
--- a/packages/app/src/editor/extensions/wiki-link-embed.test.ts
+++ b/packages/app/src/editor/extensions/wiki-link-embed.test.ts
@@ -10,7 +10,7 @@
* `doc: Pick<Document, 'createElement'>` for exactly this purpose; we feed a
* stub element that records `setAttribute` calls.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { buildWikiLinkEmbedImageDom } from './wiki-link-embed.ts';
interface RecordingElement {
diff --git a/packages/app/src/editor/extensions/wiki-link-helpers.test.ts b/packages/app/src/editor/extensions/wiki-link-helpers.test.ts
index cf7257815..2df9333b3 100644
--- a/packages/app/src/editor/extensions/wiki-link-helpers.test.ts
+++ b/packages/app/src/editor/extensions/wiki-link-helpers.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildUnresolvedWikiLinkAttrs,
canUseTargetAsPathSegment,
diff --git a/packages/app/src/editor/extensions/wiki-link-icon.dom.test.tsx b/packages/app/src/editor/extensions/wiki-link-icon.dom.test.tsx
index 6e72ac221..e20952b42 100644
--- a/packages/app/src/editor/extensions/wiki-link-icon.dom.test.tsx
+++ b/packages/app/src/editor/extensions/wiki-link-icon.dom.test.tsx
@@ -10,8 +10,8 @@
* referencing it without a NodeView remount.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import type { PageListCacheSnapshot } from '../page-list-cache';
import { getWikiLinkIcon, syncWikiLinkIconSlot } from './wiki-link';
diff --git a/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts b/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts
index e2c1516f9..c8813fdfe 100644
--- a/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts
+++ b/packages/app/src/editor/extensions/wiki-link-suggestion.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { HeadingEntry } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { __resetDocumentListInflightForTests } from '@/lib/documents-fetch';
import {
autocompleteBoost,
@@ -309,7 +309,7 @@ describe('fetchPages', () => {
/** Stub `/api/pages` + `/api/documents` with caller-supplied JSON bodies. */
function stubFetch(pagesBody: unknown, documentsBody: unknown) {
- globalThis.fetch = mock(async (input: RequestInfo | URL) => {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input.toString();
const body = url.startsWith('/api/pages') ? pagesBody : documentsBody;
return new Response(JSON.stringify(body), {
@@ -622,7 +622,7 @@ describe('loadWikiLinkContext', () => {
forward?: { status?: number; body: unknown };
back?: { status?: number; body: unknown };
}) {
- globalThis.fetch = mock(async (input: RequestInfo | URL) => {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input.toString();
const route = url.startsWith('/api/forward-links')
? routes.forward
@@ -643,7 +643,7 @@ describe('loadWikiLinkContext', () => {
test('returns an empty context for a null docName without fetching', async () => {
let called = false;
- globalThis.fetch = mock(async () => {
+ globalThis.fetch = vi.fn(async () => {
called = true;
return new Response('{}', { status: 200 });
}) as typeof globalThis.fetch;
diff --git a/packages/app/src/editor/extensions/wiki-link.external-open.test.ts b/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
index e3bede9cf..b874a4bfa 100644
--- a/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
+++ b/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
@@ -14,10 +14,10 @@
* `window.open`).
*/
-import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
import { Editor } from '@tiptap/core';
import { TextSelection } from '@tiptap/pm/state';
import StarterKit from '@tiptap/starter-kit';
+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { getInteractionLayer } from '../interaction-layer-host';
import { installDomGlobals } from '../walk-currency-test-harness';
import { WikiLink } from './wiki-link';
@@ -94,8 +94,8 @@ function mountWithExternalWikiLink(url: string): {
describe('WYSIWYG wiki-link external activation — desktop (bridge present)', () => {
test('bare click routes to the OS browser via okDesktop.shell.openExternal, NOT window.open', () => {
const url = 'https://youtube.com/watch?v=abc';
- const openExternal = mock(async (_url: string) => {});
- const openWindow = mock(() => null);
+ const openExternal = vi.fn(async (_url: string) => {});
+ const openWindow = vi.fn(() => null);
const w = testWindow();
w.okDesktop = { shell: { openExternal } };
w.open = openWindow as unknown as OpenExternalWindow['open'];
@@ -113,7 +113,7 @@ describe('WYSIWYG wiki-link external activation — desktop (bridge present)', (
describe('WYSIWYG wiki-link external activation — web (no bridge)', () => {
test('bare click falls back to window.open with the new-tab + noopener features', () => {
const url = 'https://example.com/web';
- const openWindow = mock(() => null);
+ const openWindow = vi.fn(() => null);
const w = testWindow();
delete w.okDesktop;
w.open = openWindow as unknown as OpenExternalWindow['open'];
diff --git a/packages/app/src/editor/find-replace/literal-matcher.test.ts b/packages/app/src/editor/find-replace/literal-matcher.test.ts
index 5782578a0..22b7c4ca7 100644
--- a/packages/app/src/editor/find-replace/literal-matcher.test.ts
+++ b/packages/app/src/editor/find-replace/literal-matcher.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
+import { describe, expect, test } from 'vitest';
import { findLiteralMatchesInDoc, findLiteralMatchesInText } from './literal-matcher';
const schema = new Schema({
diff --git a/packages/app/src/editor/find-replace/tiptap-find-replace-extension.test.ts b/packages/app/src/editor/find-replace/tiptap-find-replace-extension.test.ts
index 542ec805c..f81b391f0 100644
--- a/packages/app/src/editor/find-replace/tiptap-find-replace-extension.test.ts
+++ b/packages/app/src/editor/find-replace/tiptap-find-replace-extension.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { Schema } from '@tiptap/pm/model';
import { EditorState } from '@tiptap/pm/state';
import type { DecorationSet } from '@tiptap/pm/view';
+import { describe, expect, test } from 'vitest';
import {
createReplaceAllFindMatchesTransaction,
findNextActiveIndexAfterReplacement,
diff --git a/packages/app/src/editor/gfm-autolink-plugin.test.ts b/packages/app/src/editor/gfm-autolink-plugin.test.ts
index 0e3d24dee..50a9202b1 100644
--- a/packages/app/src/editor/gfm-autolink-plugin.test.ts
+++ b/packages/app/src/editor/gfm-autolink-plugin.test.ts
@@ -19,9 +19,9 @@
* it, and follow-up typing never merges into the mark's undo step.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/core';
import { ySyncPluginKey } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
firstLinkAttrs,
diff --git a/packages/app/src/editor/gfm-link-detector.test.ts b/packages/app/src/editor/gfm-link-detector.test.ts
index f7da332e4..18ddb35c4 100644
--- a/packages/app/src/editor/gfm-link-detector.test.ts
+++ b/packages/app/src/editor/gfm-link-detector.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { MarkdownManager, SAFE_URL_SCHEMES, sharedExtensions } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { detectGfmLinkToken, type GfmLinkToken } from './gfm-link-detector';
// Real pipeline, shared with production — the parity oracle. Constructing one
diff --git a/packages/app/src/editor/image-upload/media-drop-shape-invariant.test.ts b/packages/app/src/editor/image-upload/media-drop-shape-invariant.test.ts
index 142a70cc1..503983819 100644
--- a/packages/app/src/editor/image-upload/media-drop-shape-invariant.test.ts
+++ b/packages/app/src/editor/image-upload/media-drop-shape-invariant.test.ts
@@ -31,8 +31,8 @@
* parser doesn't preserve.
*/
-import { describe, expect, test } from 'bun:test';
import { MarkdownManager } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from '../extensions/shared';
import { buildMediaJsxNodeData } from './index.ts';
diff --git a/packages/app/src/editor/image-upload/pickInsertShape.test.ts b/packages/app/src/editor/image-upload/pickInsertShape.test.ts
index 747f0e881..be9779594 100644
--- a/packages/app/src/editor/image-upload/pickInsertShape.test.ts
+++ b/packages/app/src/editor/image-upload/pickInsertShape.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { pickInsertShape } from './index';
// Emit-dispatch matrix: zero user-facing upload config. Dispatch reads
diff --git a/packages/app/src/editor/image-upload/shortestImageRef.test.ts b/packages/app/src/editor/image-upload/shortestImageRef.test.ts
index 66c7721ec..7e742e02d 100644
--- a/packages/app/src/editor/image-upload/shortestImageRef.test.ts
+++ b/packages/app/src/editor/image-upload/shortestImageRef.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { shortestImageRef } from './index.ts';
describe('shortestImageRef — F8 4-case rewrite', () => {
diff --git a/packages/app/src/editor/image-upload/upload-file.test.ts b/packages/app/src/editor/image-upload/upload-file.test.ts
index 87b2f9a48..f676f121f 100644
--- a/packages/app/src/editor/image-upload/upload-file.test.ts
+++ b/packages/app/src/editor/image-upload/upload-file.test.ts
@@ -6,7 +6,7 @@
* docName directly. No `globalThis.fetch =` mutation — the prior pattern
* proved flaky on Linux Bun. DI tests are platform-stable.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { uploadFile } from './upload-file.ts';
interface FetchCall {
diff --git a/packages/app/src/editor/inline-link-input-rule.test.ts b/packages/app/src/editor/inline-link-input-rule.test.ts
index 82006df3d..1d1a7b4ac 100644
--- a/packages/app/src/editor/inline-link-input-rule.test.ts
+++ b/packages/app/src/editor/inline-link-input-rule.test.ts
@@ -9,8 +9,8 @@
* never triggers a rule.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
firstLinkAttrs,
diff --git a/packages/app/src/editor/interaction-layer-host.test.ts b/packages/app/src/editor/interaction-layer-host.test.ts
index 6e852b106..fc82067f8 100644
--- a/packages/app/src/editor/interaction-layer-host.test.ts
+++ b/packages/app/src/editor/interaction-layer-host.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, it } from 'bun:test';
import type { Editor } from '@tiptap/core';
+import { describe, expect, it } from 'vitest';
import { __hasInteractionLayerForTests, getInteractionLayer } from './interaction-layer-host';
// Minimal Editor stub — the host only touches `on('destroy', cb)` and the
diff --git a/packages/app/src/editor/interaction-layer.test.ts b/packages/app/src/editor/interaction-layer.test.ts
index 262bdf017..aa8885f14 100644
--- a/packages/app/src/editor/interaction-layer.test.ts
+++ b/packages/app/src/editor/interaction-layer.test.ts
@@ -12,7 +12,7 @@
* transitions + event resolver walk semantics.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
createInteractionLayer,
type InteractionControls,
diff --git a/packages/app/src/editor/internal-link-helpers.test.ts b/packages/app/src/editor/internal-link-helpers.test.ts
index ea4112a5d..48b02094d 100644
--- a/packages/app/src/editor/internal-link-helpers.test.ts
+++ b/packages/app/src/editor/internal-link-helpers.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, mock } from 'bun:test';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
activateAssetLink,
handleChipLinkClick,
@@ -19,15 +19,15 @@ describe('handleChipLinkClick', () => {
return {
metaKey: false,
ctrlKey: false,
- preventDefault: mock(() => {}),
+ preventDefault: vi.fn(() => {}),
...overrides,
};
}
it('bare click: navigates same-tab, suppresses native nav, closes the panel', () => {
const event = makeEvent();
- const onNavigate = mock((_newTab: boolean) => true);
- const onClose = mock(() => {});
+ const onNavigate = vi.fn((_newTab: boolean) => true);
+ const onClose = vi.fn(() => {});
handleChipLinkClick(event, onNavigate, onClose);
@@ -39,8 +39,8 @@ describe('handleChipLinkClick', () => {
it('Cmd/Ctrl click: navigates new-tab, suppresses native nav, leaves panel open', () => {
for (const mod of [{ metaKey: true }, { ctrlKey: true }] as const) {
const event = makeEvent(mod);
- const onNavigate = mock((_newTab: boolean) => true);
- const onClose = mock(() => {});
+ const onNavigate = vi.fn((_newTab: boolean) => true);
+ const onClose = vi.fn(() => {});
handleChipLinkClick(event, onNavigate, onClose);
@@ -52,8 +52,8 @@ describe('handleChipLinkClick', () => {
it('handler declines (non-navigable / unsafe scheme): native <a href> proceeds, panel stays open', () => {
const event = makeEvent();
- const onNavigate = mock((_newTab: boolean) => false);
- const onClose = mock(() => {});
+ const onNavigate = vi.fn((_newTab: boolean) => false);
+ const onClose = vi.fn(() => {});
handleChipLinkClick(event, onNavigate, onClose);
@@ -80,8 +80,8 @@ describe('activateAssetLink', () => {
};
it('bare click navigates to the asset preview and does NOT OS-delegate', () => {
- const navigate = mock((_assetPath: string) => {});
- const dispatch = mock(async () => {});
+ const navigate = vi.fn((_assetPath: string) => {});
+ const dispatch = vi.fn(async () => {});
activateAssetLink({ ...params, newTab: false }, { navigate, dispatch });
@@ -91,8 +91,8 @@ describe('activateAssetLink', () => {
});
it('Cmd/Ctrl/middle-click OS-delegates (forceOsDelegation) and does NOT navigate', () => {
- const navigate = mock((_assetPath: string) => {});
- const dispatch = mock(async () => {});
+ const navigate = vi.fn((_assetPath: string) => {});
+ const dispatch = vi.fn(async () => {});
activateAssetLink({ ...params, newTab: true }, { navigate, dispatch });
@@ -122,7 +122,7 @@ describe('activateAssetLink', () => {
});
it('bare click with no injected deps assigns the canonical asset hash via the default navigate', () => {
- const assign = mock((_url: string) => {});
+ const assign = vi.fn((_url: string) => {});
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: { location: { assign } },
@@ -163,8 +163,8 @@ describe('navigateToMarkdownTarget — external routing', () => {
}
it('desktop (bridge present): routes through okDesktop.shell.openExternal, NOT window.open', () => {
- const openExternal = mock(async (_url: string) => {});
- const openWindow = mock(() => null);
+ const openExternal = vi.fn(async (_url: string) => {});
+ const openWindow = vi.fn(() => null);
stubWindow({ okDesktop: { shell: { openExternal } }, open: openWindow });
navigateToMarkdownTarget({ kind: 'external', url: 'https://example.com/watch' });
@@ -175,7 +175,7 @@ describe('navigateToMarkdownTarget — external routing', () => {
});
it('web (no bridge): falls back to window.open with the new-tab + noopener features', () => {
- const openWindow = mock(() => null);
+ const openWindow = vi.fn(() => null);
stubWindow({ okDesktop: undefined, open: openWindow });
navigateToMarkdownTarget({ kind: 'external', url: 'https://example.com/web' });
@@ -189,8 +189,8 @@ describe('navigateToMarkdownTarget — external routing', () => {
});
it('unsafe scheme is refused: neither the bridge nor window.open fires', () => {
- const openExternal = mock(async (_url: string) => {});
- const openWindow = mock(() => null);
+ const openExternal = vi.fn(async (_url: string) => {});
+ const openWindow = vi.fn(() => null);
stubWindow({ okDesktop: { shell: { openExternal } }, open: openWindow });
navigateToMarkdownTarget({ kind: 'external', url: 'javascript:alert(1)' });
diff --git a/packages/app/src/editor/link-path-suggestions.dom.test.tsx b/packages/app/src/editor/link-path-suggestions.dom.test.tsx
index e23ee6fb0..9403f7562 100644
--- a/packages/app/src/editor/link-path-suggestions.dom.test.tsx
+++ b/packages/app/src/editor/link-path-suggestions.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { useState } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import {
isLinkPathSuggestionPanelTarget,
diff --git a/packages/app/src/editor/link-path-suggestions.test.ts b/packages/app/src/editor/link-path-suggestions.test.ts
index 672576ac9..9c49ac8fe 100644
--- a/packages/app/src/editor/link-path-suggestions.test.ts
+++ b/packages/app/src/editor/link-path-suggestions.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildLinkPathSuggestions, isSlashPathSuggestionValue } from './link-path-suggestions-core';
describe('isSlashPathSuggestionValue', () => {
diff --git a/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx b/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx
index c4d1398a3..13a3cfdf6 100644
--- a/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx
+++ b/packages/app/src/editor/link-preview/ExternalLinkPreviewCard.dom.test.tsx
@@ -9,9 +9,9 @@
* card has no chrome strings, so assertions read the server-provided data.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { ExternalLinkPreviewCard } from './ExternalLinkPreviewCard';
afterEach(cleanup);
diff --git a/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx b/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx
index 894f570b4..331d6aef7 100644
--- a/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx
+++ b/packages/app/src/editor/link-preview/InternalDocPreviewCard.dom.test.tsx
@@ -9,8 +9,8 @@
* (`tests/lingui-macro-preload.ts`), so assertions read source-locale text.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { InternalDocPreviewCard } from './InternalDocPreviewCard';
import type { InternalDocPreview } from './internal-doc-preview.ts';
diff --git a/packages/app/src/editor/link-preview/doc-excerpt.test.ts b/packages/app/src/editor/link-preview/doc-excerpt.test.ts
index 6807a277c..4921741a7 100644
--- a/packages/app/src/editor/link-preview/doc-excerpt.test.ts
+++ b/packages/app/src/editor/link-preview/doc-excerpt.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { extractDocExcerpt } from './doc-excerpt.ts';
describe('extractDocExcerpt', () => {
diff --git a/packages/app/src/editor/link-preview/external-link-preview.test.ts b/packages/app/src/editor/link-preview/external-link-preview.test.ts
index 37648f07b..41a4d267f 100644
--- a/packages/app/src/editor/link-preview/external-link-preview.test.ts
+++ b/packages/app/src/editor/link-preview/external-link-preview.test.ts
@@ -9,8 +9,8 @@
* across cases.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { loadLinkPreview, SUCCESS_CACHE_MAX_ENTRIES } from './external-link-preview.ts';
const originalFetch = globalThis.fetch;
@@ -48,7 +48,7 @@ function uniqueUrl(): string {
describe('loadLinkPreview — success + cache', () => {
test('POSTs the URL as JSON and returns the parsed metadata', async () => {
const url = uniqueUrl();
- const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
+ const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(okResponse(META)),
);
globalThis.fetch = fetchMock as unknown as typeof fetch;
@@ -65,7 +65,7 @@ describe('loadLinkPreview — success + cache', () => {
test('a re-hover of a previewed URL is served from cache without re-fetching', async () => {
const url = uniqueUrl();
- const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) =>
+ const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
Promise.resolve(okResponse(META)),
);
globalThis.fetch = fetchMock as unknown as typeof fetch;
@@ -80,7 +80,7 @@ describe('loadLinkPreview — failures fall back to null and are not cached', ()
test('a guard-rejection envelope returns null and a later hover retries', async () => {
const url = uniqueUrl();
let call = 0;
- const fetchMock = mock((_input: RequestInfo | URL, _init?: RequestInit) => {
+ const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => {
call += 1;
return Promise.resolve(call === 1 ? failResponse('blocked') : okResponse(META));
});
@@ -94,7 +94,7 @@ describe('loadLinkPreview — failures fall back to null and are not cached', ()
test('a non-2xx response (gate/body rejection) returns null', async () => {
const url = uniqueUrl();
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response('{}', { status: 403 })),
) as unknown as typeof fetch;
expect(await loadLinkPreview(url)).toBeNull();
@@ -102,7 +102,7 @@ describe('loadLinkPreview — failures fall back to null and are not cached', ()
test('a thrown request (network/offline) returns null', async () => {
const url = uniqueUrl();
- globalThis.fetch = mock(() => Promise.reject(new Error('offline'))) as unknown as typeof fetch;
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('offline'))) as unknown as typeof fetch;
expect(await loadLinkPreview(url)).toBeNull();
});
});
@@ -111,7 +111,7 @@ describe('loadLinkPreview — bounded LRU success cache', () => {
/** Fetch stub that succeeds for every URL and records which URL each call was for. */
function countingFetch(): { calls: string[] } {
const calls: string[] = [];
- globalThis.fetch = mock((_input: RequestInfo | URL, init?: RequestInit) => {
+ globalThis.fetch = vi.fn((_input: RequestInfo | URL, init?: RequestInit) => {
calls.push((JSON.parse(String(init?.body)) as { url: string }).url);
return Promise.resolve(okResponse(META));
}) as unknown as typeof fetch;
@@ -153,7 +153,7 @@ describe('loadLinkPreview — single-flight + abort', () => {
test('concurrent identical hovers coalesce to a single request', async () => {
const url = uniqueUrl();
let resolveFetch!: (r: Response) => void;
- const fetchMock = mock(
+ const fetchMock = vi.fn(
() =>
new Promise<Response>((resolve) => {
resolveFetch = resolve;
@@ -173,7 +173,7 @@ describe('loadLinkPreview — single-flight + abort', () => {
test('aborting the caller signal resolves to null and caches nothing', async () => {
const url = uniqueUrl();
const controller = new AbortController();
- const abortingFetch = mock(
+ const abortingFetch = vi.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () =>
@@ -188,7 +188,7 @@ describe('loadLinkPreview — single-flight + abort', () => {
expect(await pending).toBeNull();
// Nothing cached from the aborted attempt: a fresh hover re-requests.
- globalThis.fetch = mock(() => Promise.resolve(okResponse(META))) as unknown as typeof fetch;
+ globalThis.fetch = vi.fn(() => Promise.resolve(okResponse(META))) as unknown as typeof fetch;
expect(await loadLinkPreview(url)).toEqual(META);
});
});
diff --git a/packages/app/src/editor/link-preview/internal-doc-preview.test.ts b/packages/app/src/editor/link-preview/internal-doc-preview.test.ts
index 96624fbf3..ee2dcb9f7 100644
--- a/packages/app/src/editor/link-preview/internal-doc-preview.test.ts
+++ b/packages/app/src/editor/link-preview/internal-doc-preview.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
CONTENT_CACHE_MAX_ENTRIES,
deriveContentFields,
@@ -79,7 +79,7 @@ function jsonResponse(payload: unknown): Response {
function countingFetch(): { docCalls: string[]; backlinkCalls: string[] } {
const docCalls: string[] = [];
const backlinkCalls: string[] = [];
- globalThis.fetch = mock((input: RequestInfo | URL) => {
+ globalThis.fetch = vi.fn((input: RequestInfo | URL) => {
const url = new URL(String(input), 'http://local');
if (url.pathname === '/api/document') {
const docName = url.searchParams.get('docName') ?? '';
diff --git a/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx b/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx
index 373c95bfa..8f446e8ab 100644
--- a/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx
+++ b/packages/app/src/editor/link-preview/use-internal-doc-preview.dom.test.tsx
@@ -12,18 +12,18 @@
* the hook itself run for real.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
const realDataLayer = await import('./internal-doc-preview.ts');
-mock.module('./internal-doc-preview.ts', () => ({
+vi.doMock('./internal-doc-preview.ts', () => ({
...realDataLayer,
loadDocContent: (docName: string) => Promise.resolve(`# Heading\n\nBody of ${docName}.`),
loadBacklinkCount: (docName: string) => Promise.resolve(docName === 'a.md' ? 3 : 5),
}));
-mock.module('../../components/PageListContext', () => ({
+vi.doMock('../../components/PageListContext', () => ({
usePageList: () => ({
pageTitles: new Map<string, string>([
['a.md', 'Doc A'],
diff --git a/packages/app/src/editor/list-boundary-merge.test.ts b/packages/app/src/editor/list-boundary-merge.test.ts
index a89c87009..c06180461 100644
--- a/packages/app/src/editor/list-boundary-merge.test.ts
+++ b/packages/app/src/editor/list-boundary-merge.test.ts
@@ -30,10 +30,10 @@
* Test scenarios credited to inkeep/open-knowledge#613 by @blokboy.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { Editor, Extension, type JSONContent } from '@tiptap/core';
import { Plugin, TextSelection } from '@tiptap/pm/state';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import { installDomGlobals } from './walk-currency-test-harness';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
diff --git a/packages/app/src/editor/math-input-rule.test.ts b/packages/app/src/editor/math-input-rule.test.ts
index 011f9a047..cc7161788 100644
--- a/packages/app/src/editor/math-input-rule.test.ts
+++ b/packages/app/src/editor/math-input-rule.test.ts
@@ -9,9 +9,9 @@
* never triggers a rule.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { MathInline } from '@inkeep/open-knowledge-core';
import type { Editor } from '@tiptap/core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { mountCollabEditor, mountLightEditor, readUndoManager } from './editor-rig.test-helper';
import { MathInputRule } from './math-input-rule';
diff --git a/packages/app/src/editor/mount-id-registry.test.ts b/packages/app/src/editor/mount-id-registry.test.ts
index ba04d6386..6773eaa80 100644
--- a/packages/app/src/editor/mount-id-registry.test.ts
+++ b/packages/app/src/editor/mount-id-registry.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__getMountIdRegistry,
__resetMountIdRegistry,
diff --git a/packages/app/src/editor/mount-promise.test.ts b/packages/app/src/editor/mount-promise.test.ts
index 544e2dbac..b31d1e88a 100644
--- a/packages/app/src/editor/mount-promise.test.ts
+++ b/packages/app/src/editor/mount-promise.test.ts
@@ -7,9 +7,10 @@
* (Bun test env has no DOM globals; we install a minimal `globalThis.document`
* stub before the suites that exercise the cache-MISS path).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Editor } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { getCollector, getHistogramSnapshot } from '../lib/perf/collector';
import { validatePerfMarkName } from '../lib/perf/mark';
diff --git a/packages/app/src/editor/no-runtime-import-cycle.test.ts b/packages/app/src/editor/no-runtime-import-cycle.test.ts
index bc0056586..4825870cb 100644
--- a/packages/app/src/editor/no-runtime-import-cycle.test.ts
+++ b/packages/app/src/editor/no-runtime-import-cycle.test.ts
@@ -25,10 +25,11 @@
* EVERY lib→editor value edge that closes a cycle is gone, so cutting just one edge of a
* multi-edge entanglement cannot green this test while a residual lib↔editor value cycle remains.
*/
-import { describe, expect, test } from 'bun:test';
+
import { dirname, join, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Project } from 'ts-morph';
+import { describe, expect, test } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url)); // packages/app/src/editor
const APP_SRC = dirname(HERE); // packages/app/src
diff --git a/packages/app/src/editor/observer-sync.test.ts b/packages/app/src/editor/observer-sync.test.ts
index 4166d0d78..ab378f415 100644
--- a/packages/app/src/editor/observer-sync.test.ts
+++ b/packages/app/src/editor/observer-sync.test.ts
@@ -5,11 +5,12 @@
* live in server-observers.test.ts and C1-C10 integration tests (server-authoritative
* architecture, precedent #14). This file covers client-side shimmer prevention only.
*/
-import { describe, expect, test } from 'bun:test';
+
import { setTimeout as wait } from 'node:timers/promises';
import { MarkdownManager } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { sharedExtensions } from './extensions/shared';
import { ORIGIN_TEXT_TO_TREE, ORIGIN_TREE_TO_TEXT, setupObservers } from './observers';
diff --git a/packages/app/src/editor/observers.test.ts b/packages/app/src/editor/observers.test.ts
index 92c5ae0cd..ab371894a 100644
--- a/packages/app/src/editor/observers.test.ts
+++ b/packages/app/src/editor/observers.test.ts
@@ -22,11 +22,11 @@
// in `packages/server/src/server-observers.test.ts`.
// ─────────────────────────────────────────────────────────────
-import { describe, expect, test } from 'bun:test';
import { setTimeout } from 'node:timers/promises';
import { MarkdownManager } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { sharedExtensions } from './extensions/shared';
import {
diff --git a/packages/app/src/editor/page-list-cache.test.ts b/packages/app/src/editor/page-list-cache.test.ts
index f3333ee4d..6d60f8e79 100644
--- a/packages/app/src/editor/page-list-cache.test.ts
+++ b/packages/app/src/editor/page-list-cache.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, it, mock } from 'bun:test';
import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import {
__resetPageListCacheForTests,
buildPageIconsIndex,
@@ -151,7 +151,7 @@ describe('setPageListCache', () => {
folderPaths: new Set(),
};
setPageListCache(snap);
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
subscribePageListCache(listener);
listener.mockClear();
setPageListCache(snap);
@@ -166,20 +166,20 @@ describe('subscribePageListCache', () => {
folderPaths: new Set(),
};
setPageListCache(snap);
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
subscribePageListCache(listener);
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith(snap);
});
it('does NOT fire immediately when cache is null at subscribe time', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
subscribePageListCache(listener);
expect(listener).not.toHaveBeenCalled();
});
it('fires on subsequent content-changing setPageListCache calls', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
subscribePageListCache(listener);
const first: PageListCacheSnapshot = {
pages: new Set(['a']),
@@ -198,7 +198,7 @@ describe('subscribePageListCache', () => {
});
it('does NOT fire on content-equal setPageListCache calls', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
subscribePageListCache(listener);
setPageListCache({ pages: new Set(['a']), folderPaths: new Set() });
listener.mockClear();
@@ -207,7 +207,7 @@ describe('subscribePageListCache', () => {
});
it('unsubscribe stops subsequent notifications', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsubscribe = subscribePageListCache(listener);
unsubscribe();
setPageListCache({ pages: new Set(['a']), folderPaths: new Set() });
@@ -216,7 +216,7 @@ describe('subscribePageListCache', () => {
it('is safe to unsubscribe inside a listener (no double-fire on next change)', () => {
let unsubscribe: (() => void) | null = null;
- const listener = mock(() => {
+ const listener = vi.fn(() => {
unsubscribe?.();
});
unsubscribe = subscribePageListCache(listener);
@@ -228,8 +228,8 @@ describe('subscribePageListCache', () => {
});
it('supports multiple independent subscribers', () => {
- const a = mock(() => {});
- const b = mock(() => {});
+ const a = vi.fn(() => {});
+ const b = vi.fn(() => {});
subscribePageListCache(a);
subscribePageListCache(b);
setPageListCache({ pages: new Set(['x']), folderPaths: new Set() });
@@ -244,10 +244,10 @@ describe('subscribePageListCache', () => {
captured.push(args);
};
try {
- const bad = mock(() => {
+ const bad = vi.fn(() => {
throw new Error('boom');
});
- const good = mock(() => {});
+ const good = vi.fn(() => {});
subscribePageListCache(bad);
subscribePageListCache(good);
setPageListCache({ pages: new Set(['x']), folderPaths: new Set() });
diff --git a/packages/app/src/editor/pattern-d-schema-identity.test.ts b/packages/app/src/editor/pattern-d-schema-identity.test.ts
index cc16a75db..657f96995 100644
--- a/packages/app/src/editor/pattern-d-schema-identity.test.ts
+++ b/packages/app/src/editor/pattern-d-schema-identity.test.ts
@@ -37,8 +37,8 @@
* `walk-currency-test-harness.ts` for the install/restore contract.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { Editor } from '@tiptap/core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
import { buildPatternDConstructorOptions } from './TiptapEditor';
import {
diff --git a/packages/app/src/editor/pattern-d-walk-currency.test.ts b/packages/app/src/editor/pattern-d-walk-currency.test.ts
index e0d3cd83d..00f5a52fb 100644
--- a/packages/app/src/editor/pattern-d-walk-currency.test.ts
+++ b/packages/app/src/editor/pattern-d-walk-currency.test.ts
@@ -43,10 +43,10 @@
* `walk-currency-test-harness.ts` for the install/restore contract.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { Editor } from '@tiptap/core';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type { Awareness } from 'y-protocols/awareness';
import type * as Y from 'yjs';
import { __resetCacheForTests, evictTiptapEditor } from './editor-cache';
diff --git a/packages/app/src/editor/plugins/asset-context-menu.test.ts b/packages/app/src/editor/plugins/asset-context-menu.test.ts
index 7c494f6b7..eef02aa88 100644
--- a/packages/app/src/editor/plugins/asset-context-menu.test.ts
+++ b/packages/app/src/editor/plugins/asset-context-menu.test.ts
@@ -4,7 +4,7 @@
* without mounting an editor.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyContextMenuTarget } from './asset-context-menu';
function makeEl(tag: string, attrs: Record<string, string> = {}): Element {
diff --git a/packages/app/src/editor/plugins/md-link-source.test.ts b/packages/app/src/editor/plugins/md-link-source.test.ts
index 3786e6c3e..be005593d 100644
--- a/packages/app/src/editor/plugins/md-link-source.test.ts
+++ b/packages/app/src/editor/plugins/md-link-source.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { toWikiLinkSlug } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { buildPagesBySlugIndex, type PageListCacheSnapshot } from '../page-list-cache';
import { markdownSourceLinkClass } from './md-link-source';
diff --git a/packages/app/src/editor/plugins/wiki-link-source.test.ts b/packages/app/src/editor/plugins/wiki-link-source.test.ts
index 0665f0aa4..54e1c3181 100644
--- a/packages/app/src/editor/plugins/wiki-link-source.test.ts
+++ b/packages/app/src/editor/plugins/wiki-link-source.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildKnownWikilinkTargetSet,
buildPageNameSet,
diff --git a/packages/app/src/editor/provider-pool.attach-boundary.test.ts b/packages/app/src/editor/provider-pool.attach-boundary.test.ts
index ce93bf302..ff704dc5b 100644
--- a/packages/app/src/editor/provider-pool.attach-boundary.test.ts
+++ b/packages/app/src/editor/provider-pool.attach-boundary.test.ts
@@ -14,9 +14,10 @@
* property of the source, not of any executable behavior a unit test
* could observe.
*/
-import { describe, expect, test } from 'bun:test';
+
import { join } from 'node:path';
import { Project, SyntaxKind } from 'ts-morph';
+import { describe, expect, test } from 'vitest';
const SANCTIONED_CALLERS = ['attachValidatedPersistence', 'open'] as const;
diff --git a/packages/app/src/editor/provider-pool.test.ts b/packages/app/src/editor/provider-pool.test.ts
index 060c1e897..e38f701a3 100644
--- a/packages/app/src/editor/provider-pool.test.ts
+++ b/packages/app/src/editor/provider-pool.test.ts
@@ -7,12 +7,13 @@
* the pool's LRU logic, Map management, and eviction ordering are all
* exercised without needing a running Hocuspocus server.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { setTimeout as wait } from 'node:timers/promises';
import { Compartment } from '@codemirror/state';
import { PROTOCOL_VERSION } from '@inkeep/open-knowledge-core';
import { parseHocuspocusAuthToken } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { buildAuthToken } from '../lib/auth-token';
import { __resetCardinalityWarnings, getCollector } from '../lib/perf/collector';
@@ -397,7 +398,7 @@ describe('ProviderPool onEvict subscription', () => {
});
// Suppress the warn so the test output stays clean.
const originalWarn = console.warn;
- console.warn = mock(() => {});
+ console.warn = vi.fn(() => {});
try {
pool.close('doc1');
} finally {
@@ -495,7 +496,7 @@ describe('ProviderPool dispose', () => {
});
describe('ProviderPool setupObservers init-throw recovery (S4)', () => {
- // Instead of mock.module (which leaks to other test files in the same bun test
+ // Instead of vi.doMock (which leaks to other test files in the same bun test
// process), we sabotage the provider's Y.Doc to force a throw inside the onSynced
// try block. Overriding doc.getXmlFragment to throw triggers the catch before
// setupObservers is called — same code path, same recovery behavior.
@@ -519,7 +520,7 @@ describe('ProviderPool setupObservers init-throw recovery (S4)', () => {
};
// Silence the expected console.error so test output stays readable
- const errorSpy = mock(() => {});
+ const errorSpy = vi.fn(() => {});
const origError = console.error;
console.error = errorSpy;
@@ -569,7 +570,7 @@ describe('ProviderPool setupObservers init-throw recovery (S4)', () => {
entry.provider.document.getXmlFragment = () => {
throw new Error('synthetic init failure');
};
- const errorSpy = mock(() => {});
+ const errorSpy = vi.fn(() => {});
const origError = console.error;
console.error = errorSpy;
entry.provider.emit('synced', { state: true });
@@ -1262,7 +1263,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
store.set(ENVELOPE_KEY, makeEnvelope(TEST_SERVER_INSTANCE_ID, { doc1: 'epoch-1' }));
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
const entry = pool.open('doc1');
@@ -1275,7 +1276,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
store.set(ENVELOPE_KEY, makeEnvelope(TEST_SERVER_INSTANCE_ID, { doc1: 'epoch-1' }));
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
// No setExpectedServerInstanceId — the envelope cannot be validated, and
// a lineage claim must never race the instance-unknown boot window.
@@ -1289,7 +1290,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
store.set(ENVELOPE_KEY, makeEnvelope('dead-instance', { doc1: 'epoch-1' }));
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
const entry = pool.open('doc1');
@@ -1302,7 +1303,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
store.set(ENVELOPE_KEY, makeEnvelope(TEST_SERVER_INSTANCE_ID, { doc1: 'epoch-1' }, 'feature'));
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
// Pool never observes a branch — its scope normalizes to `_unknown_`,
// which must not consume a `feature`-scoped envelope.
@@ -1316,7 +1317,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
const { stub, store } = makeStubStorage();
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
const docName = uniqueDocName('pp-lineage-record');
@@ -1340,7 +1341,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
// A fresh pool over the same storage (new tab) claims the epoch.
const pool2 = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
try {
pool2.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
@@ -1358,7 +1359,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
store.set(ENVELOPE_KEY, makeEnvelope(TEST_SERVER_INSTANCE_ID, { [docName]: 'epoch-dead' }));
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
const entry = pool.open(docName);
@@ -1367,7 +1368,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
expect(tokenOf(entry).expectedDocLineageEpoch).toBe('epoch-dead');
// Silence the expected structured recovery warn.
- const warnSpy = mock(() => {});
+ const warnSpy = vi.fn(() => {});
const origWarn = console.warn;
console.warn = warnSpy;
entry.provider.emit('authenticationFailed', { reason: 'doc-lineage-mismatch' });
@@ -1402,7 +1403,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
const { stub } = makeStubStorage();
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
const docName = uniqueDocName('pp-lineage-deferred');
@@ -1425,7 +1426,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
entry.provider.document.getMap('lifecycle').set('epoch', 'epoch-live');
entry.provider.emit('synced', { state: true });
- const warnSpy = mock(() => {});
+ const warnSpy = vi.fn(() => {});
const origWarn = console.warn;
console.warn = warnSpy;
// Learning the instance id triggers the deferred attach, whose guard
@@ -1472,7 +1473,7 @@ describe('ProviderPool doc-lineage epoch records', () => {
);
pool = new ProviderPool(3, DUMMY_WS, {
storage: stub,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
const renamedEntry = pool.open(renamedDoc);
@@ -1513,9 +1514,9 @@ describe('ProviderPool stored-state validation spine', () => {
function captureWarns(): {
lines: () => string[];
restore: () => void;
- spy: ReturnType<typeof spyOn>;
+ spy: ReturnType<typeof vi.spyOn>;
} {
- const spy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
return {
lines: () =>
spy.mock.calls
@@ -1529,10 +1530,10 @@ describe('ProviderPool stored-state validation spine', () => {
test('refuses stored rows whose in-band epoch differs from the live lineage', async () => {
const warns = captureWarns();
try {
- const peek = mock(async () => 'epoch-dead');
+ const peek = vi.fn(async () => 'epoch-dead');
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
peekStoredLineageEpoch: peek,
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
@@ -1572,10 +1573,10 @@ describe('ProviderPool stored-state validation spine', () => {
test('refuses stored epoch-bearing rows when the live doc carries no epoch post-sync', async () => {
const warns = captureWarns();
try {
- const peek = mock(async () => 'epoch-dead');
+ const peek = vi.fn(async () => 'epoch-dead');
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
- persistenceFactory: mock(makePersistenceStub),
+ persistenceFactory: vi.fn(makePersistenceStub),
peekStoredLineageEpoch: peek,
});
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
@@ -1607,8 +1608,8 @@ describe('ProviderPool stored-state validation spine', () => {
});
test('attaches when the stored epoch matches the live lineage, then backfills the cache', async () => {
- const flushSpy = mock(async () => {});
- const persistenceFactory = mock(
+ const flushSpy = vi.fn(async () => {});
+ const persistenceFactory = vi.fn(
() =>
({
whenSynced: Promise.resolve(undefined as never),
@@ -1618,7 +1619,7 @@ describe('ProviderPool stored-state validation spine', () => {
flushFullState: flushSpy,
}) as unknown as ClientPersistenceProvider,
);
- const peek = mock(async () => 'epoch-live');
+ const peek = vi.fn(async () => 'epoch-live');
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
persistenceFactory,
@@ -1640,8 +1641,8 @@ describe('ProviderPool stored-state validation spine', () => {
});
test('attaches immediately when the stored rows carry nothing to validate (null peek)', async () => {
- const persistenceFactory = mock(makePersistenceStub);
- const peek = mock(async () => null);
+ const persistenceFactory = vi.fn(makePersistenceStub);
+ const peek = vi.fn(async () => null);
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
persistenceFactory,
@@ -1660,8 +1661,8 @@ describe('ProviderPool stored-state validation spine', () => {
});
test('record-present entry that has not synced waits for sync before validating', async () => {
- const persistenceFactory = mock(makePersistenceStub);
- const peek = mock(async () => 'epoch-x');
+ const persistenceFactory = vi.fn(makePersistenceStub);
+ const peek = vi.fn(async () => 'epoch-x');
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
persistenceFactory,
@@ -1699,13 +1700,13 @@ describe('ProviderPool stored-state validation spine', () => {
test('a re-dispatch onto an entry with an in-flight spine run is a no-op (attach ownership)', async () => {
let resolvePeek: (value: string | null) => void = () => {};
- const peek = mock(
+ const peek = vi.fn(
() =>
new Promise<string | null>((resolve) => {
resolvePeek = resolve;
}),
);
- const persistenceFactory = mock(makePersistenceStub);
+ const persistenceFactory = vi.fn(makePersistenceStub);
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
persistenceFactory,
@@ -1730,8 +1731,8 @@ describe('ProviderPool stored-state validation spine', () => {
test('a rejecting peek leaves the entry cacheless and emits the attach-failed arm', async () => {
const warns = captureWarns();
try {
- const persistenceFactory = mock(makePersistenceStub);
- const peek = mock(async (): Promise<string | null> => {
+ const persistenceFactory = vi.fn(makePersistenceStub);
+ const peek = vi.fn(async (): Promise<string | null> => {
throw new Error('idb exploded');
});
pool = new ProviderPool(3, DUMMY_WS, {
@@ -1769,9 +1770,9 @@ describe('ProviderPool stored-state validation spine', () => {
test('a wedged peek decays into the attach-failed arm after the timeout', async () => {
const warns = captureWarns();
try {
- const persistenceFactory = mock(makePersistenceStub);
+ const persistenceFactory = vi.fn(makePersistenceStub);
// Never settles — the cross-tab-blocked-delete wedge shape.
- const peek = mock(() => new Promise<string | null>(() => {}));
+ const peek = vi.fn(() => new Promise<string | null>(() => {}));
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
persistenceFactory,
@@ -1805,8 +1806,8 @@ describe('ProviderPool stored-state validation spine', () => {
test('a throwing factory on the matched-epoch arm emits attach-failed and leaves the entry cacheless', async () => {
const warns = captureWarns();
try {
- const peek = mock(async () => 'epoch-live');
- const persistenceFactory = mock((): ClientPersistenceProvider => {
+ const peek = vi.fn(async () => 'epoch-live');
+ const persistenceFactory = vi.fn((): ClientPersistenceProvider => {
throw new Error('factory exploded');
});
pool = new ProviderPool(3, DUMMY_WS, {
@@ -1842,7 +1843,7 @@ describe('ProviderPool stored-state validation spine', () => {
test('a failing backfill emits the structured attach-failed event with phase backfill', async () => {
const warns = captureWarns();
try {
- const persistenceFactory = mock(
+ const persistenceFactory = vi.fn(
() =>
({
whenSynced: Promise.resolve(undefined as never),
@@ -1854,7 +1855,7 @@ describe('ProviderPool stored-state validation spine', () => {
},
}) as unknown as ClientPersistenceProvider,
);
- const peek = mock(async () => null);
+ const peek = vi.fn(async () => null);
pool = new ProviderPool(3, DUMMY_WS, {
storage: null,
persistenceFactory,
@@ -1982,7 +1983,7 @@ describe("ProviderPool authenticationFailed handling (US-002 / 'server-instance-
});
test('second mismatch event is a no-op after cache is cleared (idempotence)', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS, { storage: null });
pool.setExpectedServerInstanceId('server-old');
@@ -2040,7 +2041,7 @@ describe("ProviderPool authenticationFailed handling (US-002 / 'server-instance-
pool.setActive('doc1');
let resolveClear: () => void = () => {};
- persistence.clearData = mock(
+ persistence.clearData = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveClear = resolve;
@@ -2078,7 +2079,7 @@ describe("ProviderPool authenticationFailed handling (US-002 / 'server-instance-
});
test('active doc clearData failure exposes targeted recovery failure state', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS);
pool.setExpectedServerInstanceId('server-old');
@@ -2088,7 +2089,7 @@ describe("ProviderPool authenticationFailed handling (US-002 / 'server-instance-
const persistence = await awaitAttachedPersistence(entry);
pool.setActive('doc1');
const originalProvider = entry.provider;
- persistence.clearData = mock(() => Promise.reject(new Error('idb blocked')));
+ persistence.clearData = vi.fn(() => Promise.reject(new Error('idb blocked')));
entry.provider.emit('authenticationFailed', { reason: 'server-instance-mismatch' });
await wait(50);
@@ -2136,7 +2137,7 @@ describe("ProviderPool authenticationFailed handling (US-002 / 'server-instance-
});
test('active doc clearData timeout exposes targeted timeout state', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS, { clearDataTimeoutMs: 5 });
pool.setExpectedServerInstanceId('server-old');
@@ -2145,7 +2146,7 @@ describe("ProviderPool authenticationFailed handling (US-002 / 'server-instance-
if (!entry) throw new Error('expected entry');
const persistence = await awaitAttachedPersistence(entry);
pool.setActive('doc1');
- persistence.clearData = mock(() => new Promise<void>(() => {}));
+ persistence.clearData = vi.fn(() => new Promise<void>(() => {}));
entry.provider.emit('authenticationFailed', { reason: 'server-instance-mismatch' });
await wait(30);
@@ -2507,22 +2508,22 @@ describe('ProviderPool → V2 editor cache eviction coupling (Critical #2)', ()
const fakeCmDom = makeFakeNode();
const fakeEditor = {
editorView: { dom: fakeTipDom, scrollDOM: fakeTipDom },
- commands: { focus: mock(() => {}) },
- destroy: mock(() => {}),
+ commands: { focus: vi.fn(() => {}) },
+ destroy: vi.fn(() => {}),
} as unknown as import('@tiptap/core').Editor;
const fakeView = {
dom: fakeCmDom,
scrollDOM: fakeCmDom,
- focus: mock(() => {}),
- destroy: mock(() => {}),
+ focus: vi.fn(() => {}),
+ destroy: vi.fn(() => {}),
} as unknown as import('@codemirror/view').EditorView;
const makeProv = () =>
({
- destroy: mock(() => {}),
- document: { destroy: mock(() => {}) } as unknown as import('yjs').Doc,
+ destroy: vi.fn(() => {}),
+ document: { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc,
awareness: null,
}) as unknown as import('@hocuspocus/provider').HocuspocusProvider;
- const fakeYDoc = { destroy: mock(() => {}) } as unknown as import('yjs').Doc;
+ const fakeYDoc = { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc;
const fakeYText = { toString: () => '' } as unknown as import('yjs').Text;
cacheModule.mountTiptapEditor({
@@ -2571,22 +2572,22 @@ describe('ProviderPool → V2 editor cache eviction coupling (Critical #2)', ()
const fakeCmDom = makeFakeNode();
const fakeEditor = {
editorView: { dom: fakeTipDom, scrollDOM: fakeTipDom },
- commands: { focus: mock(() => {}) },
- destroy: mock(() => {}),
+ commands: { focus: vi.fn(() => {}) },
+ destroy: vi.fn(() => {}),
} as unknown as import('@tiptap/core').Editor;
const fakeView = {
dom: fakeCmDom,
scrollDOM: fakeCmDom,
- focus: mock(() => {}),
- destroy: mock(() => {}),
+ focus: vi.fn(() => {}),
+ destroy: vi.fn(() => {}),
} as unknown as import('@codemirror/view').EditorView;
const makeProv = () =>
({
- destroy: mock(() => {}),
- document: { destroy: mock(() => {}) } as unknown as import('yjs').Doc,
+ destroy: vi.fn(() => {}),
+ document: { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc,
awareness: null,
}) as unknown as import('@hocuspocus/provider').HocuspocusProvider;
- const fakeYDoc = { destroy: mock(() => {}) } as unknown as import('yjs').Doc;
+ const fakeYDoc = { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc;
const fakeYText = { toString: () => '' } as unknown as import('yjs').Text;
cacheModule.mountTiptapEditor({
docName: 'doc-recycle-regression',
@@ -2626,16 +2627,16 @@ describe('ProviderPool → V2 editor cache eviction coupling (Critical #2)', ()
cacheModule.__resetCacheForTests();
const makeProv = () =>
({
- destroy: mock(() => {}),
- document: { destroy: mock(() => {}) } as unknown as import('yjs').Doc,
+ destroy: vi.fn(() => {}),
+ document: { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc,
awareness: null,
}) as unknown as import('@hocuspocus/provider').HocuspocusProvider;
const makeFakeEditor = () => {
const dom = makeFakeNode();
return {
editorView: { dom, scrollDOM: dom },
- commands: { focus: mock(() => {}) },
- destroy: mock(() => {}),
+ commands: { focus: vi.fn(() => {}) },
+ destroy: vi.fn(() => {}),
} as unknown as import('@tiptap/core').Editor;
};
const fakeYText = { toString: () => '' } as unknown as import('yjs').Text;
@@ -2645,7 +2646,7 @@ describe('ProviderPool → V2 editor cache eviction coupling (Critical #2)', ()
container: makeFakeNode() as unknown as HTMLElement,
factory: () => ({
editor: makeFakeEditor(),
- ydoc: { destroy: mock(() => {}) } as unknown as import('yjs').Doc,
+ ydoc: { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc,
ytext: fakeYText,
provider: makeProv(),
}),
@@ -2655,7 +2656,7 @@ describe('ProviderPool → V2 editor cache eviction coupling (Critical #2)', ()
container: makeFakeNode() as unknown as HTMLElement,
factory: () => ({
editor: makeFakeEditor(),
- ydoc: { destroy: mock(() => {}) } as unknown as import('yjs').Doc,
+ ydoc: { destroy: vi.fn(() => {}) } as unknown as import('yjs').Doc,
ytext: fakeYText,
provider: makeProv(),
}),
@@ -2690,8 +2691,8 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
return {
whenSynced: Promise.resolve(undefined as never),
synced: true,
- destroy: mock(async () => {}),
- clearData: mock(async () => {}),
+ destroy: vi.fn(async () => {}),
+ clearData: vi.fn(async () => {}),
flushFullState: async () => {},
} as ClientPersistenceProvider;
}
@@ -2716,12 +2717,12 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
});
test('deferred persistence attach continues after one entry throws', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
const badDoc = uniqueDocName('pp-deferred-throw');
const goodDoc = uniqueDocName('pp-deferred-ok');
const goodPersistence = stubPersistence();
- const persistenceFactory = mock(({ docName }: { docName: string }) => {
+ const persistenceFactory = vi.fn(({ docName }: { docName: string }) => {
if (docName === badDoc) {
throw new Error('idb unavailable');
}
@@ -2781,7 +2782,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
const attached = await awaitAttachedPersistence(entry);
const order: string[] = [];
- const persistenceSpy = mock(async () => {
+ const persistenceSpy = vi.fn(async () => {
order.push('persistence');
});
attached.destroy = persistenceSpy;
@@ -2811,7 +2812,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
entry.observerCleanup = () => {};
const order: string[] = [];
- const persistenceSpy = mock(async () => {
+ const persistenceSpy = vi.fn(async () => {
order.push('persistence');
});
attached.destroy = persistenceSpy;
@@ -2847,7 +2848,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
if (!entry2) throw new Error('expected entry on doc2');
const attached2 = await awaitAttachedPersistence(entry2);
- const destroySpy = mock(async () => {});
+ const destroySpy = vi.fn(async () => {});
attached2.destroy = destroySpy;
// Opening doc3 at capacity evicts doc2 (doc1 is active + protected)
@@ -2868,8 +2869,8 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
const p1 = await awaitAttachedPersistence(e1);
const p2 = await awaitAttachedPersistence(e2);
- const spy1 = mock(async () => {});
- const spy2 = mock(async () => {});
+ const spy1 = vi.fn(async () => {});
+ const spy2 = vi.fn(async () => {});
p1.destroy = spy1;
p2.destroy = spy2;
@@ -2887,7 +2888,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
if (!entry) throw new Error('expected entry');
const attached = await awaitAttachedPersistence(entry);
- const clearSpy = mock(async () => {});
+ const clearSpy = vi.fn(async () => {});
attached.clearData = clearSpy;
await pool.closeAndClearPersistence(docName);
@@ -3035,8 +3036,8 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
pool.setActive(doc1);
e1.observerCleanup = () => {};
- const clearSpy1 = mock(async () => {});
- const clearSpy2 = mock(async () => {});
+ const clearSpy1 = vi.fn(async () => {});
+ const clearSpy2 = vi.fn(async () => {});
p1.clearData = clearSpy1;
p2.clearData = clearSpy2;
@@ -3086,9 +3087,9 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
const preProvider2 = e2.provider;
const preProvider3 = e3.provider;
- const clearOk1 = mock(async () => {});
- const clearFail = mock(() => Promise.reject(new Error('idb-clear-blocked')));
- const clearOk2 = mock(async () => {});
+ const clearOk1 = vi.fn(async () => {});
+ const clearFail = vi.fn(() => Promise.reject(new Error('idb-clear-blocked')));
+ const clearOk2 = vi.fn(async () => {});
p1.clearData = clearOk1;
p2.clearData = clearFail;
p3.clearData = clearOk2;
@@ -3137,8 +3138,8 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
ea.observerCleanup = () => {};
eb.observerCleanup = () => {};
- pa.clearData = mock(async () => {});
- pb.clearData = mock(() => new Promise<void>(() => {}));
+ pa.clearData = vi.fn(async () => {});
+ pb.clearData = vi.fn(() => new Promise<void>(() => {}));
ea.provider.emit('authenticationFailed', { reason: 'server-instance-mismatch' });
await wait(60);
@@ -3182,15 +3183,15 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
describe('pendingClears dedup + deferred-attach', () => {
interface ControllableStub {
stub: ClientPersistenceProvider;
- clearSpy: ReturnType<typeof mock>;
+ clearSpy: ReturnType<typeof vi.fn>;
}
function makeControllableStub(clearImpl: () => Promise<void>): ControllableStub {
- const clearSpy = mock(clearImpl);
+ const clearSpy = vi.fn(clearImpl);
const stub = {
whenSynced: Promise.resolve(undefined as never),
synced: true,
- destroy: mock(async () => {}),
+ destroy: vi.fn(async () => {}),
clearData: clearSpy,
flushFullState: async () => {},
} as unknown as ClientPersistenceProvider;
@@ -3213,8 +3214,8 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
resolveClear = resolve;
}),
);
- const persistenceFactory = mock(() => stub);
- const deleteDbSpy = spyOn(indexedDB, 'deleteDatabase');
+ const persistenceFactory = vi.fn(() => stub);
+ const deleteDbSpy = vi.spyOn(indexedDB, 'deleteDatabase');
pool = new ProviderPool(3, DUMMY_WS, { persistenceFactory, clearDataTimeoutMs: 30_000 });
pool.setObservedBranch('main');
@@ -3253,7 +3254,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
);
const fresh = makeControllableStub(async () => {});
let callCount = 0;
- const persistenceFactory = mock(() => {
+ const persistenceFactory = vi.fn(() => {
callCount += 1;
return callCount === 1 ? cleared.stub : fresh.stub;
});
@@ -3296,7 +3297,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
rejectClear = reject;
}),
);
- const persistenceFactory = mock(() => cleared.stub);
+ const persistenceFactory = vi.fn(() => cleared.stub);
pool = new ProviderPool(3, DUMMY_WS, { persistenceFactory, clearDataTimeoutMs: 30_000 });
pool.setExpectedServerInstanceId(TEST_SERVER_INSTANCE_ID);
@@ -3311,7 +3312,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
if (!entry2) throw new Error('expected entry2');
expect(entry2.persistence).toBeNull();
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
rejectClear(new Error('idb-clear-blocked'));
// closeAndClearPersistence's public API swallows the reject; the
@@ -3341,7 +3342,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
);
const fresh = makeControllableStub(async () => {});
let callCount = 0;
- const persistenceFactory = mock(() => {
+ const persistenceFactory = vi.fn(() => {
callCount += 1;
return callCount === 1 ? cleared.stub : fresh.stub;
});
@@ -3382,7 +3383,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
const ok2 = makeControllableStub(async () => {});
const stubs = [ok1.stub, fail.stub, ok2.stub];
let idx = 0;
- const persistenceFactory = mock(() => {
+ const persistenceFactory = vi.fn(() => {
const s = stubs[idx];
idx += 1;
return s;
@@ -3401,7 +3402,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
await awaitAttachedPersistence(entry);
}
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await Promise.all(docs.map((d) => pool.closeAndClearPersistence(d)));
// Each entry's clearData was attempted.
@@ -3425,7 +3426,7 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
const failedStub = makeControllableStub(() => Promise.reject(new Error('idb-blocked')));
const freshStub = makeControllableStub(async () => {});
let factoryCallCount = 0;
- const persistenceFactory = mock(() => {
+ const persistenceFactory = vi.fn(() => {
factoryCallCount += 1;
return factoryCallCount === 1 ? failedStub.stub : freshStub.stub;
});
@@ -3439,8 +3440,8 @@ describe('ProviderPool client-persistence attachment (US-003)', () => {
if (!entry1) throw new Error('expected entry1');
await awaitAttachedPersistence(entry1);
- const deleteDbSpy = spyOn(indexedDB, 'deleteDatabase');
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const deleteDbSpy = vi.spyOn(indexedDB, 'deleteDatabase');
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
const baselineDeleteCalls = deleteDbSpy.mock.calls.length;
@@ -3737,7 +3738,7 @@ describe('ProviderPool handleServerInstanceMismatch baseline-selection', () => {
// mid-drain duplication).
test('handleServerInstanceMismatch uses lastDiskAckedSV when present', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS);
pool.setExpectedServerInstanceId('server-old');
@@ -3828,7 +3829,7 @@ describe('ProviderPool handleServerInstanceMismatch baseline-selection', () => {
});
test('handleServerInstanceMismatch skips buffer replay when both watermark SVs are null', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS);
pool.setExpectedServerInstanceId('server-old');
@@ -3889,7 +3890,7 @@ describe('ProviderPool handleServerInstanceMismatch baseline-selection', () => {
*/
describe('ProviderPool structured mismatch telemetry', () => {
test('replay applies corrupt buffer emits ok-buffer-replay-failed with bounded fields', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS);
pool.setExpectedServerInstanceId('epoch-replay-telemetry');
@@ -3962,7 +3963,7 @@ describe('ProviderPool structured mismatch telemetry', () => {
});
test('epoch mismatch envelope uses active doc plus branch and stale instance claim', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
pool = new ProviderPool(3, DUMMY_WS);
pool.setExpectedServerInstanceId('stale-epoch-telemetry');
@@ -4237,7 +4238,7 @@ describe('ProviderPool authenticationFailed: rename-redirect / doc-deleted', ()
sendToken: () => Promise<void>;
emit: (e: string, p: unknown) => void;
};
- const sendTokenSpy = spyOn(provider, 'sendToken').mockResolvedValue();
+ const sendTokenSpy = vi.spyOn(provider, 'sendToken').mockResolvedValue();
// Discard any sendToken calls from the provider's own `onOpen` boot
// path so the assertion below only counts the close-handler-driven
// call. The pool's interest is in the handler's behavior, not the
@@ -4260,9 +4261,9 @@ describe('ProviderPool authenticationFailed: rename-redirect / doc-deleted', ()
sendToken: () => Promise<void>;
emit: (e: string, p: unknown) => void;
};
- const sendTokenSpy = spyOn(provider, 'sendToken').mockRejectedValue(
- new Error('synthetic transport-closed failure'),
- );
+ const sendTokenSpy = vi
+ .spyOn(provider, 'sendToken')
+ .mockRejectedValue(new Error('synthetic transport-closed failure'));
sendTokenSpy.mockClear();
const warns: string[] = [];
const originalWarn = console.warn;
@@ -4305,7 +4306,7 @@ describe('ProviderPool authenticationFailed: rename-redirect / doc-deleted', ()
// the synchronous burst behavior without racing against microtask
// resolution.
const neverResolve = new Promise<void>(() => {});
- const sendTokenSpy = spyOn(provider, 'sendToken').mockReturnValue(neverResolve);
+ const sendTokenSpy = vi.spyOn(provider, 'sendToken').mockReturnValue(neverResolve);
sendTokenSpy.mockClear();
provider.emit('close', { event: { code: 1000, reason: 'first' } });
provider.emit('close', { event: { code: 1000, reason: 'second' } });
diff --git a/packages/app/src/editor/registry/file-icons.test.ts b/packages/app/src/editor/registry/file-icons.test.ts
index f6f839b11..c73298c11 100644
--- a/packages/app/src/editor/registry/file-icons.test.ts
+++ b/packages/app/src/editor/registry/file-icons.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { FileText, Film, FolderOpen, Image, Volume2 } from 'lucide-react';
+import { describe, expect, test } from 'vitest';
import { getFileIcon, mentionPathToDescriptor } from './file-icons.ts';
/**
diff --git a/packages/app/src/editor/registry/lucide-svg.test.ts b/packages/app/src/editor/registry/lucide-svg.test.ts
index e5d383cd4..133e43d68 100644
--- a/packages/app/src/editor/registry/lucide-svg.test.ts
+++ b/packages/app/src/editor/registry/lucide-svg.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import {
File,
FileText,
@@ -12,6 +11,7 @@ import {
} from 'lucide-react';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, test } from 'vitest';
import { lucideIconToSvgString } from './lucide-svg.ts';
/**
diff --git a/packages/app/src/editor/registry/resolve-descriptor-placeholder.test.ts b/packages/app/src/editor/registry/resolve-descriptor-placeholder.test.ts
index 3890697cc..33528e52d 100644
--- a/packages/app/src/editor/registry/resolve-descriptor-placeholder.test.ts
+++ b/packages/app/src/editor/registry/resolve-descriptor-placeholder.test.ts
@@ -12,8 +12,9 @@
* fallback ladder: descriptor.placeholder.label || `Add ${displayName.toLowerCase()}`,
* and descriptor.placeholder.icon || descriptor.icon || Box.
*/
-import { describe, expect, test } from 'bun:test';
+
import { Box, Image } from 'lucide-react';
+import { describe, expect, test } from 'vitest';
import { getDescriptor } from './index.ts';
import {
resolveDescriptorPlaceholder,
diff --git a/packages/app/src/editor/safe-navigation-url.test.ts b/packages/app/src/editor/safe-navigation-url.test.ts
index b7f4c6b04..c260c8346 100644
--- a/packages/app/src/editor/safe-navigation-url.test.ts
+++ b/packages/app/src/editor/safe-navigation-url.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isSafeNavigationUrl } from './safe-navigation-url';
describe('isSafeNavigationUrl', () => {
diff --git a/packages/app/src/editor/selection-context.test.ts b/packages/app/src/editor/selection-context.test.ts
index cac14ddb9..e144bc824 100644
--- a/packages/app/src/editor/selection-context.test.ts
+++ b/packages/app/src/editor/selection-context.test.ts
@@ -5,9 +5,10 @@
* The source extractor reads only `view.state`, so a bare `EditorState` (no DOM)
* exercises it.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { EditorState } from '@codemirror/state';
import type { EditorView } from '@codemirror/view';
+import { afterEach, describe, expect, test } from 'vitest';
import {
getSelectionContext,
INLINE_SELECTION_MAX_CHARS,
diff --git a/packages/app/src/editor/selection-stats.test.ts b/packages/app/src/editor/selection-stats.test.ts
index 924ed0b1e..3ad9da7e7 100644
--- a/packages/app/src/editor/selection-stats.test.ts
+++ b/packages/app/src/editor/selection-stats.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import type { EditorView } from '@codemirror/view';
import type { Editor } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import {
getSelectionStats,
publishSelectionStats,
diff --git a/packages/app/src/editor/selection/entry-label.test.ts b/packages/app/src/editor/selection/entry-label.test.ts
index eede6e916..9bdd56d2b 100644
--- a/packages/app/src/editor/selection/entry-label.test.ts
+++ b/packages/app/src/editor/selection/entry-label.test.ts
@@ -3,7 +3,7 @@
* (shared by SelectionAnnouncer + future selection-consuming UI).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { BlockChainEntry } from '../extensions/selection-state-plugin.ts';
import { getEntryLabel } from './entry-label.ts';
diff --git a/packages/app/src/editor/sidebar-drop.test.ts b/packages/app/src/editor/sidebar-drop.test.ts
index dc6864d9e..865d73bbf 100644
--- a/packages/app/src/editor/sidebar-drop.test.ts
+++ b/packages/app/src/editor/sidebar-drop.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
OK_SIDEBAR_DRAG_MIME,
type SidebarDragPayload,
@@ -23,9 +23,9 @@ function dataTransfer(data: Record<string, string>): Pick<DataTransfer, 'types'
function dropEvent(data: Record<string, string>): {
event: DropEvent;
- preventDefault: ReturnType<typeof mock>;
+ preventDefault: ReturnType<typeof vi.fn>;
} {
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
return {
event: {
dataTransfer: dataTransfer(data),
@@ -38,8 +38,8 @@ function dropEvent(data: Record<string, string>): {
describe('createSidebarAwareHandleDrop', () => {
test('claims sidebar drags before generic clipboard drop handling', () => {
const payload: SidebarDragPayload = { v: 1, kind: 'doc', docName: 'notes/Intro', size: null };
- const clipboardDrop = mock((_view: DropView, _event: DragEvent) => false);
- const onSidebarDrop = mock((_payload: SidebarDragPayload) => {});
+ const clipboardDrop = vi.fn((_view: DropView, _event: DragEvent) => false);
+ const onSidebarDrop = vi.fn((_payload: SidebarDragPayload) => {});
const handleDrop = createSidebarAwareHandleDrop(clipboardDrop, onSidebarDrop);
const { event, preventDefault } = dropEvent({
[OK_SIDEBAR_DRAG_MIME]: serializeSidebarDragPayload(payload),
@@ -54,8 +54,8 @@ describe('createSidebarAwareHandleDrop', () => {
test('falls through to clipboard drop for non-sidebar drags', () => {
const view = {} as DropView;
- const clipboardDrop = mock((_view: DropView, _event: DragEvent) => false);
- const onSidebarDrop = mock((_payload: SidebarDragPayload) => {});
+ const clipboardDrop = vi.fn((_view: DropView, _event: DragEvent) => false);
+ const onSidebarDrop = vi.fn((_payload: SidebarDragPayload) => {});
const handleDrop = createSidebarAwareHandleDrop(clipboardDrop, onSidebarDrop);
const { event, preventDefault } = dropEvent({ 'text/plain': 'notes/Intro.md' });
@@ -73,7 +73,7 @@ describe('openSidebarDropPayload', () => {
pathname: '/app',
search: '?workspace=ok',
});
- const openTarget = mock(
+ const openTarget = vi.fn(
(_target: Parameters<SidebarOpenTarget>[0], _options: Parameters<SidebarOpenTarget>[1]) => {},
);
try {
@@ -90,14 +90,14 @@ describe('openSidebarDropPayload', () => {
});
});
-let fakeReplaceState = mock((_state: unknown, _unused: string, _url: string) => {});
+let fakeReplaceState = vi.fn((_state: unknown, _unused: string, _url: string) => {});
function installFakeWindow(location: {
hash: string;
pathname: string;
search: string;
}): () => void {
- fakeReplaceState = mock((_state: unknown, _unused: string, _url: string) => {});
+ fakeReplaceState = vi.fn((_state: unknown, _unused: string, _url: string) => {});
const global = globalThis as { window?: unknown };
const previous = global.window;
Object.defineProperty(globalThis, 'window', {
diff --git a/packages/app/src/editor/slash-command/auto-open-flag.test.ts b/packages/app/src/editor/slash-command/auto-open-flag.test.ts
index a64ef4fab..11c057f17 100644
--- a/packages/app/src/editor/slash-command/auto-open-flag.test.ts
+++ b/packages/app/src/editor/slash-command/auto-open-flag.test.ts
@@ -15,7 +15,7 @@
* double-consume a single flag.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
_resetPendingAutoOpenForTest,
consumeAutoOpen,
diff --git a/packages/app/src/editor/slash-command/cell-context-filter.test.ts b/packages/app/src/editor/slash-command/cell-context-filter.test.ts
index 0e5b4f0a2..693c1e83e 100644
--- a/packages/app/src/editor/slash-command/cell-context-filter.test.ts
+++ b/packages/app/src/editor/slash-command/cell-context-filter.test.ts
@@ -11,10 +11,10 @@
* production code, not re-implementations.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { sharedExtensions as coreExtensions, MarkdownManager } from '@inkeep/open-knowledge-core';
import { Editor, type JSONContent } from '@tiptap/core';
import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import { CellInsertionGate } from '../extensions/cell-insertion-gate';
import { SLASH_ITEM_SOURCES } from '../extensions/shared';
import { buildSlashMenuItems } from '../extensions/slash-command';
diff --git a/packages/app/src/editor/slash-command/component-items.test.ts b/packages/app/src/editor/slash-command/component-items.test.ts
index fc5bfbbd2..47036cd36 100644
--- a/packages/app/src/editor/slash-command/component-items.test.ts
+++ b/packages/app/src/editor/slash-command/component-items.test.ts
@@ -22,12 +22,12 @@
* auto-focused placeholder input handles the rest, no popover plumbing).
*/
-import { describe, expect, spyOn, test } from 'bun:test';
import {
builtInComponents,
getAgentCanonicalDescriptors,
getCanonicalDescriptors,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import {
_resetPendingLinkEditForTest,
consumePendingLinkEdit,
@@ -365,7 +365,7 @@ describe('getInlineComponentItems — inline-atom slash entries', () => {
// Stub the mark-identity plugin state so findLinkMarkIdAt resolves the
// freshly inserted link mark (spanning the insert position) to a stable
// id — exercising the production happy path without a live PM view.
- const getStateSpy = spyOn(markIdentityKey, 'getState').mockReturnValue({
+ const getStateSpy = vi.spyOn(markIdentityKey, 'getState').mockReturnValue({
byId: new Map([['m7', { id: 'm7', markType: 'link', from: 1, to: 5, attrs: { href: '' } }]]),
counter: 7,
} as never);
diff --git a/packages/app/src/editor/slash-command/embed-starter-items.test.ts b/packages/app/src/editor/slash-command/embed-starter-items.test.ts
index 42c99a82f..6279bfc89 100644
--- a/packages/app/src/editor/slash-command/embed-starter-items.test.ts
+++ b/packages/app/src/editor/slash-command/embed-starter-items.test.ts
@@ -8,9 +8,9 @@
* entries and the shared `PREVIEW_EMBED_STARTERS` set.
*/
-import { describe, expect, test } from 'bun:test';
import { PREVIEW_EMBED_STARTERS } from '@inkeep/open-knowledge-core';
import type { Editor } from '@tiptap/react';
+import { describe, expect, test } from 'vitest';
import { getEmbedStarterItems } from './embed-starter-items';
interface InsertedNode {
diff --git a/packages/app/src/editor/slash-command/focus-inserted-component.test.ts b/packages/app/src/editor/slash-command/focus-inserted-component.test.ts
index 6ba994b1c..a0b207f90 100644
--- a/packages/app/src/editor/slash-command/focus-inserted-component.test.ts
+++ b/packages/app/src/editor/slash-command/focus-inserted-component.test.ts
@@ -10,8 +10,8 @@
* exactly like the editable-props popover path.
*/
-import { afterEach, beforeAll, describe, expect, test } from 'bun:test';
import type { Editor } from '@tiptap/react';
+import { afterEach, beforeAll, describe, expect, test } from 'vitest';
import type { JsxComponentDescriptor } from '../registry/types';
import {
_resetPendingAutoOpenForTest,
diff --git a/packages/app/src/editor/slash-command/items.test.ts b/packages/app/src/editor/slash-command/items.test.ts
index 79cdf556c..dc3c11220 100644
--- a/packages/app/src/editor/slash-command/items.test.ts
+++ b/packages/app/src/editor/slash-command/items.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { filterItems, getSlashCommandItems, type SlashCommandItem } from './items';
describe('filterItems', () => {
diff --git a/packages/app/src/editor/source-editor-navigation.test.ts b/packages/app/src/editor/source-editor-navigation.test.ts
index 6ebaa3e18..94528caab 100644
--- a/packages/app/src/editor/source-editor-navigation.test.ts
+++ b/packages/app/src/editor/source-editor-navigation.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, setSystemTime, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
clearPendingSourceNavigation,
clearPendingSourceNavigationsForTest,
@@ -9,7 +9,7 @@ import {
afterEach(() => {
clearPendingSourceNavigationsForTest();
- setSystemTime();
+ vi.useRealTimers();
});
describe('source-editor-navigation', () => {
@@ -67,42 +67,46 @@ describe('pending-intent expiry', () => {
};
test('an intent older than 30 seconds is discarded at consume time', () => {
- setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
rememberPendingSourceNavigation('doc-a', lintNavigation);
- setSystemTime(new Date('2026-07-09T12:00:30.001Z'));
+ vi.setSystemTime(new Date('2026-07-09T12:00:30.001Z'));
expect(consumePendingSourceNavigation('doc-a')).toBeNull();
});
test('an intent aged exactly 30 seconds is still consumed', () => {
- setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
rememberPendingSourceNavigation('doc-a', lintNavigation);
- setSystemTime(new Date('2026-07-09T12:00:30.000Z'));
+ vi.setSystemTime(new Date('2026-07-09T12:00:30.000Z'));
expect(consumePendingSourceNavigation('doc-a')).toEqual(lintNavigation);
});
test('peek reports an expired intent as absent', () => {
- setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
rememberPendingSourceNavigation('doc-a', lintNavigation);
- setSystemTime(new Date('2026-07-09T12:01:00.000Z'));
+ vi.setSystemTime(new Date('2026-07-09T12:01:00.000Z'));
expect(peekPendingSourceNavigation('doc-a')).toBeNull();
});
test('re-remembering restarts the expiry clock', () => {
- setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-07-09T12:00:00.000Z'));
rememberPendingSourceNavigation('doc-a', {
kind: 'raw-mdx',
detail: { offset: 7 },
});
- setSystemTime(new Date('2026-07-09T12:00:20.000Z'));
+ vi.setSystemTime(new Date('2026-07-09T12:00:20.000Z'));
rememberPendingSourceNavigation('doc-a', lintNavigation);
// 40s after the first remember, 20s after the second — the refreshed
// timestamp keeps the intent alive.
- setSystemTime(new Date('2026-07-09T12:00:40.000Z'));
+ vi.setSystemTime(new Date('2026-07-09T12:00:40.000Z'));
expect(consumePendingSourceNavigation('doc-a')).toEqual(lintNavigation);
});
});
diff --git a/packages/app/src/editor/source-lint/markdown-lint-source.test.ts b/packages/app/src/editor/source-lint/markdown-lint-source.test.ts
index 0eb660a39..beec44921 100644
--- a/packages/app/src/editor/source-lint/markdown-lint-source.test.ts
+++ b/packages/app/src/editor/source-lint/markdown-lint-source.test.ts
@@ -4,7 +4,6 @@
* matching the source-polish convention of testing the pure builder directly.
*/
-import { describe, expect, test } from 'bun:test';
import { lintGutter } from '@codemirror/lint';
import { EditorState } from '@codemirror/state';
import {
@@ -12,6 +11,7 @@ import {
type LintDiagnostic,
type LintRange,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { createMarkdownLintExtension, mapLintDiagnostics } from './markdown-lint-source.ts';
const docOf = (text: string) => EditorState.create({ doc: text }).doc;
diff --git a/packages/app/src/editor/source-polish/broken-ref-field.test.ts b/packages/app/src/editor/source-polish/broken-ref-field.test.ts
index 9cca0f027..1bebdd4e3 100644
--- a/packages/app/src/editor/source-polish/broken-ref-field.test.ts
+++ b/packages/app/src/editor/source-polish/broken-ref-field.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { EditorState } from '@codemirror/state';
import { GFM } from '@lezer/markdown';
+import { describe, expect, test } from 'vitest';
import { scanBrokenRefs } from './broken-ref-field';
function createState(doc: string): EditorState {
diff --git a/packages/app/src/editor/source-polish/engine-invariants.test.ts b/packages/app/src/editor/source-polish/engine-invariants.test.ts
index 1fcfccc8a..56400f605 100644
--- a/packages/app/src/editor/source-polish/engine-invariants.test.ts
+++ b/packages/app/src/editor/source-polish/engine-invariants.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const SOURCE_POLISH_DIR = import.meta.dirname;
diff --git a/packages/app/src/editor/source-polish/view-plugin.test.ts b/packages/app/src/editor/source-polish/view-plugin.test.ts
index da265db76..89451e49e 100644
--- a/packages/app/src/editor/source-polish/view-plugin.test.ts
+++ b/packages/app/src/editor/source-polish/view-plugin.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { EditorState } from '@codemirror/state';
import { GFM } from '@lezer/markdown';
+import { describe, expect, test } from 'vitest';
import { buildDecorationsForRanges } from './view-plugin';
/**
diff --git a/packages/app/src/editor/sync-promise.test.ts b/packages/app/src/editor/sync-promise.test.ts
index b76d1a40d..f1396a002 100644
--- a/packages/app/src/editor/sync-promise.test.ts
+++ b/packages/app/src/editor/sync-promise.test.ts
@@ -5,8 +5,9 @@
* (same pattern as provider-pool.test.ts). The provider never connects,
* but emitting `synced` / `close` directly exercises the listener wiring.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { HocuspocusProvider } from '@hocuspocus/provider';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { getCollector, getHistogramSnapshot } from '../lib/perf/collector';
import { validatePerfMarkName } from '../lib/perf/mark';
import {
diff --git a/packages/app/src/editor/table-controls/useTableDragReorder.test.ts b/packages/app/src/editor/table-controls/useTableDragReorder.test.ts
index 4ac772f96..b8373876c 100644
--- a/packages/app/src/editor/table-controls/useTableDragReorder.test.ts
+++ b/packages/app/src/editor/table-controls/useTableDragReorder.test.ts
@@ -7,10 +7,10 @@
* exactly the kind of pure logic that regresses silently on a refactor.
*/
-import { describe, expect, test } from 'bun:test';
import { sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
+import { describe, expect, test } from 'vitest';
import { computeDragTarget, tableWithMovedColumn, tableWithMovedRow } from './useTableDragReorder';
diff --git a/packages/app/src/editor/typing-burst-detector.test.ts b/packages/app/src/editor/typing-burst-detector.test.ts
index cf02cfea0..3c44590b3 100644
--- a/packages/app/src/editor/typing-burst-detector.test.ts
+++ b/packages/app/src/editor/typing-burst-detector.test.ts
@@ -7,8 +7,9 @@
* the substrate behavior: per-burst settle, debounce semantics, mark
* + histogram emission, multiple-detector isolation.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { getCollector, getHistogramSnapshot } from '../lib/perf/collector';
import { resetPerfOverrideWarnings } from '../lib/perf/env-override';
import { attachTypingBurstDetector } from './typing-burst-detector';
diff --git a/packages/app/src/editor/undo-isolation.test.ts b/packages/app/src/editor/undo-isolation.test.ts
index 376fccf53..dd5fae890 100644
--- a/packages/app/src/editor/undo-isolation.test.ts
+++ b/packages/app/src/editor/undo-isolation.test.ts
@@ -8,8 +8,8 @@
* path where the `finally` matters — a try/catch refactor would break it).
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
import type { EditorView } from '@tiptap/pm/view';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import * as Y from 'yjs';
import { mountCollabEditor, readUndoManager } from './editor-rig.test-helper';
import { dispatchAsOwnUndoStep } from './undo-isolation';
diff --git a/packages/app/src/editor/use-editor-mode.test.ts b/packages/app/src/editor/use-editor-mode.test.ts
index feb158e6d..e842b008e 100644
--- a/packages/app/src/editor/use-editor-mode.test.ts
+++ b/packages/app/src/editor/use-editor-mode.test.ts
@@ -15,7 +15,7 @@
* surface so the Playwright tier focuses on user-facing behavior.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
EDITOR_MODE_VALUES,
type EditorModeValue,
@@ -30,30 +30,30 @@ import {
// ---------------------------------------------------------------------------
interface FakeStorage {
- getItem: ReturnType<typeof mock>;
- setItem: ReturnType<typeof mock>;
+ getItem: ReturnType<typeof vi.fn>;
+ setItem: ReturnType<typeof vi.fn>;
}
function storageWith(value: string | null): FakeStorage {
return {
- getItem: mock(() => value),
- setItem: mock(() => undefined),
+ getItem: vi.fn(() => value),
+ setItem: vi.fn(() => undefined),
};
}
function storageThatThrowsOnGet(err: Error = new Error('privacy mode')): FakeStorage {
return {
- getItem: mock(() => {
+ getItem: vi.fn(() => {
throw err;
}),
- setItem: mock(() => undefined),
+ setItem: vi.fn(() => undefined),
};
}
function storageThatThrowsOnSet(err: Error = new Error('quota exceeded')): FakeStorage {
return {
- getItem: mock(() => null),
- setItem: mock(() => {
+ getItem: vi.fn(() => null),
+ setItem: vi.fn(() => {
throw err;
}),
};
@@ -110,10 +110,10 @@ describe('isEditorModeValue — type guard', () => {
// ---------------------------------------------------------------------------
describe('readPersistedMode — localStorage read with validation', () => {
- let warnSpy: ReturnType<typeof spyOn> | undefined;
+ let warnSpy: ReturnType<typeof vi.spyOn> | undefined;
beforeEach(() => {
- warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
});
afterEach(() => {
@@ -195,9 +195,9 @@ describe('readInitialMode — precedence: window global > storage > default', ()
// `readPersistedMode` which now logs a bracket-prefix warn. Suppress
// it here so we don't leak warn output into CI logs; dedicated tests
// above verify the warn's message + shape.
- let warnSpy: ReturnType<typeof spyOn> | undefined;
+ let warnSpy: ReturnType<typeof vi.spyOn> | undefined;
beforeEach(() => {
- warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
});
afterEach(() => {
warnSpy?.mockRestore();
@@ -263,10 +263,10 @@ describe('readInitialMode — precedence: window global > storage > default', ()
// ---------------------------------------------------------------------------
describe('persistMode — localStorage write with error swallow + warn logging', () => {
- let warnSpy: ReturnType<typeof spyOn> | undefined;
+ let warnSpy: ReturnType<typeof vi.spyOn> | undefined;
beforeEach(() => {
- warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
});
afterEach(() => {
diff --git a/packages/app/src/editor/useDocDiagnostics.dom.test.tsx b/packages/app/src/editor/useDocDiagnostics.dom.test.tsx
index 70d84de3c..1b134fd31 100644
--- a/packages/app/src/editor/useDocDiagnostics.dom.test.tsx
+++ b/packages/app/src/editor/useDocDiagnostics.dom.test.tsx
@@ -4,10 +4,10 @@
* (the hook only touches `provider.document.getText('source')`).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';
import { cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { useDocDiagnostics } from './useDocDiagnostics';
diff --git a/packages/app/src/editor/utils/animate-align-change.test.ts b/packages/app/src/editor/utils/animate-align-change.test.ts
index 4181e370f..532769e27 100644
--- a/packages/app/src/editor/utils/animate-align-change.test.ts
+++ b/packages/app/src/editor/utils/animate-align-change.test.ts
@@ -8,7 +8,7 @@
* broken FLIP must not block the alignment change itself.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { runWithAlignAnimation } from './animate-align-change';
interface StubAnimation {
@@ -99,7 +99,7 @@ afterEach(() => {
describe('runWithAlignAnimation', () => {
test('runs mutate when wrapper is null (no DOM ref available)', () => {
- const mutate = mock(() => {});
+ const mutate = vi.fn(() => {});
runWithAlignAnimation(null, mutate);
expect(mutate).toHaveBeenCalledTimes(1);
});
@@ -110,7 +110,7 @@ describe('runWithAlignAnimation', () => {
// would swallow the alignment change.
const target = makeStubTarget(100);
const wrapper = makeStubWrapper(target);
- const mutate = mock(() => {});
+ const mutate = vi.fn(() => {});
runWithAlignAnimation(wrapper, mutate);
expect(mutate).toHaveBeenCalledTimes(1);
expect(target.animateCalls.length).toBe(0);
@@ -121,7 +121,7 @@ describe('runWithAlignAnimation', () => {
installReducedMotionWindow(true);
const target = makeStubTarget(100);
const wrapper = makeStubWrapper(target);
- const mutate = mock(() => {});
+ const mutate = vi.fn(() => {});
runWithAlignAnimation(wrapper, mutate);
expect(mutate).toHaveBeenCalledTimes(1);
flushRaf();
@@ -132,7 +132,7 @@ describe('runWithAlignAnimation', () => {
installRafStub();
installReducedMotionWindow(false);
const wrapper = makeStubWrapper(null);
- const mutate = mock(() => {});
+ const mutate = vi.fn(() => {});
runWithAlignAnimation(wrapper, mutate);
expect(mutate).toHaveBeenCalledTimes(1);
flushRaf();
@@ -186,8 +186,8 @@ describe('runWithAlignAnimation', () => {
installReducedMotionWindow(false);
const target = makeStubTarget(100);
const wrapper = makeStubWrapper(target);
- const inFlight: StubAnimation = { id: 'ok-image-align-flip', cancel: mock(() => {}) };
- const unrelated: StubAnimation = { id: 'some-other-anim', cancel: mock(() => {}) };
+ const inFlight: StubAnimation = { id: 'ok-image-align-flip', cancel: vi.fn(() => {}) };
+ const unrelated: StubAnimation = { id: 'some-other-anim', cancel: vi.fn(() => {}) };
// Patch getAnimations to return our seeded animations once, then
// whatever the production code appends after that.
let firstCall = true;
diff --git a/packages/app/src/editor/utils/editor-strings.test.ts b/packages/app/src/editor/utils/editor-strings.test.ts
index afe0ae5bf..a80d49eeb 100644
--- a/packages/app/src/editor/utils/editor-strings.test.ts
+++ b/packages/app/src/editor/utils/editor-strings.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { formatContainerAriaLabel, humanizePropName } from './editor-strings';
describe('formatContainerAriaLabel', () => {
diff --git a/packages/app/src/editor/utils/filter-assets-by-accept.test.ts b/packages/app/src/editor/utils/filter-assets-by-accept.test.ts
index 69d187883..5f8cda6cf 100644
--- a/packages/app/src/editor/utils/filter-assets-by-accept.test.ts
+++ b/packages/app/src/editor/utils/filter-assets-by-accept.test.ts
@@ -1,10 +1,10 @@
-import { describe, expect, test } from 'bun:test';
import {
ALLOWED_AUDIO_MIME_TYPES,
ALLOWED_IMAGE_MIME_TYPES,
ALLOWED_PDF_MIME_TYPES,
ALLOWED_VIDEO_MIME_TYPES,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { filterAssetsByAccept } from './filter-assets-by-accept.ts';
const PATHS = [
diff --git a/packages/app/src/editor/utils/sanitize-url.test.ts b/packages/app/src/editor/utils/sanitize-url.test.ts
index c4aebbb44..495f9bb7d 100644
--- a/packages/app/src/editor/utils/sanitize-url.test.ts
+++ b/packages/app/src/editor/utils/sanitize-url.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
isDangerousPropName,
isUrlPropName,
diff --git a/packages/app/src/editor/utils/severity.test.ts b/packages/app/src/editor/utils/severity.test.ts
index 81dbf0d86..3f0600ac7 100644
--- a/packages/app/src/editor/utils/severity.test.ts
+++ b/packages/app/src/editor/utils/severity.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifySeverity, SEVERITY_STYLES } from './severity';
describe('classifySeverity', () => {
diff --git a/packages/app/src/editor/utils/validate-css-length.test.ts b/packages/app/src/editor/utils/validate-css-length.test.ts
index 9ca1d64a8..a04f935ed 100644
--- a/packages/app/src/editor/utils/validate-css-length.test.ts
+++ b/packages/app/src/editor/utils/validate-css-length.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { cssLengthValidationMessage, validateCssLength } from './validate-css-length.ts';
describe('validateCssLength', () => {
diff --git a/packages/app/src/editor/utils/validate-media-url.test.ts b/packages/app/src/editor/utils/validate-media-url.test.ts
index 43b757146..b53b53b47 100644
--- a/packages/app/src/editor/utils/validate-media-url.test.ts
+++ b/packages/app/src/editor/utils/validate-media-url.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
mediaKindForAccept,
mediaUrlPlaceholder,
diff --git a/packages/app/src/editor/walk-currency-extension.test.ts b/packages/app/src/editor/walk-currency-extension.test.ts
index 2b859602a..8f4f18af3 100644
--- a/packages/app/src/editor/walk-currency-extension.test.ts
+++ b/packages/app/src/editor/walk-currency-extension.test.ts
@@ -22,12 +22,12 @@
* `walk-currency-test-harness.ts` for the install/restore contract.
*/
-import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { Editor, Extension, getSchema } from '@tiptap/core';
import { Plugin, type PluginKey } from '@tiptap/pm/state';
import { initProseMirrorDoc, ySyncPluginKey } from '@tiptap/y-tiptap';
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
import { __resetCacheForTests, evictTiptapEditor } from './editor-cache';
diff --git a/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.dom.test.tsx b/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.dom.test.tsx
index 4c4ab8eb3..c00a5b3bf 100644
--- a/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.dom.test.tsx
+++ b/packages/app/src/editor/wiki-link-suggestion/WikiLinkSuggestionMenu.dom.test.tsx
@@ -14,8 +14,9 @@
* folder affordance is not assertable here. Symlinks are
* likewise not represented in the item shape.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import type { WikiLinkSuggestionItem } from '../extensions/wiki-link-suggestion';
import { WikiLinkSuggestionMenu } from './WikiLinkSuggestionMenu';
diff --git a/packages/app/src/globals.alpha-aware.test.ts b/packages/app/src/globals.alpha-aware.test.ts
index 8f3b56464..673256036 100644
--- a/packages/app/src/globals.alpha-aware.test.ts
+++ b/packages/app/src/globals.alpha-aware.test.ts
@@ -22,9 +22,9 @@
* making `sidebar-inset` alpha-aware regresses the depth-cue contract).
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const CSS = readFileSync(join(__dirname, 'globals.css'), 'utf8');
diff --git a/packages/app/src/globals.image-zoom-dark.test.ts b/packages/app/src/globals.image-zoom-dark.test.ts
index e11cae759..423432d12 100644
--- a/packages/app/src/globals.image-zoom-dark.test.ts
+++ b/packages/app/src/globals.image-zoom-dark.test.ts
@@ -7,9 +7,9 @@
* block already in globals.css.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const CSS = readFileSync(join(__dirname, 'globals.css'), 'utf8');
diff --git a/packages/app/src/globals.reduced-transparency.test.ts b/packages/app/src/globals.reduced-transparency.test.ts
index 48507f635..28fb632bc 100644
--- a/packages/app/src/globals.reduced-transparency.test.ts
+++ b/packages/app/src/globals.reduced-transparency.test.ts
@@ -18,9 +18,9 @@
* opaque always; the @media query has no business there.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const CSS_PATH = join(__dirname, 'globals.css');
const CSS = readFileSync(CSS_PATH, 'utf-8');
diff --git a/packages/app/src/globals.test.ts b/packages/app/src/globals.test.ts
index de7bd6ae9..a2d770549 100644
--- a/packages/app/src/globals.test.ts
+++ b/packages/app/src/globals.test.ts
@@ -16,9 +16,10 @@
* tier. A Playwright Electron e2e (open Sync popover, click EditorHeader,
* assert popover closed) is the right follow-up.
*/
-import { describe, expect, test } from 'bun:test';
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const SRC_PATH = join(__dirname, 'globals.css');
const src = readFileSync(SRC_PATH, 'utf-8');
diff --git a/packages/app/src/hooks/use-conflict-footer-height.dom.test.tsx b/packages/app/src/hooks/use-conflict-footer-height.dom.test.tsx
index 617c90135..f496597a9 100644
--- a/packages/app/src/hooks/use-conflict-footer-height.dom.test.tsx
+++ b/packages/app/src/hooks/use-conflict-footer-height.dom.test.tsx
@@ -8,8 +8,9 @@
* every published value is '0px' — these are lifecycle/ownership pins, not
* geometry assertions (real heights are covered by the browser).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { useConflictFooterHeightVar } from './use-conflict-footer-height';
function Footer({ enabled = true }: { enabled?: boolean }) {
diff --git a/packages/app/src/hooks/use-conflicts.dom.test.tsx b/packages/app/src/hooks/use-conflicts.dom.test.tsx
index 22fd766e2..6f4d01d0a 100644
--- a/packages/app/src/hooks/use-conflicts.dom.test.tsx
+++ b/packages/app/src/hooks/use-conflicts.dom.test.tsx
@@ -11,8 +11,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { useConflicts } from './use-conflicts';
interface CapturedFetch {
diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx
index b2456c07a..f2422dafd 100644
--- a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx
+++ b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { act, cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
useLingui: () => ({
t: (strings: TemplateStringsArray, ...values: unknown[]) =>
@@ -12,7 +12,7 @@ mock.module('@lingui/react/macro', () => ({
}));
const toastErrors: string[] = [];
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (message: string) => toastErrors.push(message),
},
@@ -25,7 +25,7 @@ let projectBinding: null | {
patch: (patch: unknown) => { ok: true } | { ok: false; error: unknown };
} = null;
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({ projectBinding, projectLocalBinding }),
}));
@@ -70,7 +70,7 @@ function DefaultWriterProbe() {
}
describe('useEnableSyncWithConfirm runtime behavior', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
afterEach(() => {
cleanup();
@@ -131,7 +131,7 @@ describe('useEnableSyncWithConfirm runtime behavior', () => {
test('confirm keeps the dialog open when enabling fails', async () => {
await loadHooks();
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const writer: Writer = () => ({ ok: false, error: 'branch is protected' });
render(<ConfirmProbe writer={writer} />);
@@ -163,7 +163,7 @@ describe('useEnableSyncWithConfirm runtime behavior', () => {
test('does not fire opts.onEnabled when the enable write fails', async () => {
await loadHooks();
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
let enabledCalls = 0;
const writer: Writer = () => ({ ok: false, error: 'branch is protected' });
render(<ConfirmProbe writer={writer} onEnabled={() => enabledCalls++} />);
diff --git a/packages/app/src/hooks/use-installed-clis.dom.test.tsx b/packages/app/src/hooks/use-installed-clis.dom.test.tsx
index aa9609a7e..b79ec9229 100644
--- a/packages/app/src/hooks/use-installed-clis.dom.test.tsx
+++ b/packages/app/src/hooks/use-installed-clis.dom.test.tsx
@@ -6,8 +6,9 @@
* (resolved map surfaces), and the `.catch` degradation (a rejected probe leaves
* the map empty and warns, so the resolver falls back to the claude default).
*/
-import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+
import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { useInstalledClis } from './use-installed-clis';
function Probe() {
@@ -60,7 +61,7 @@ describe('useInstalledClis', () => {
});
test('degradation: a rejected probe leaves the map empty and warns', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
setBridge({
terminal: {
cliInstalledMap: async () => {
diff --git a/packages/app/src/hooks/use-is-embedded.test.ts b/packages/app/src/hooks/use-is-embedded.test.ts
index 2e06e4d09..51079e7de 100644
--- a/packages/app/src/hooks/use-is-embedded.test.ts
+++ b/packages/app/src/hooks/use-is-embedded.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('use-is-embedded module', () => {
test('exports useIsEmbedded as a function', async () => {
diff --git a/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx b/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx
index 335903e27..ff2489859 100644
--- a/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx
+++ b/packages/app/src/hooks/use-lifecycle-status.dom.test.tsx
@@ -9,13 +9,14 @@
* its export surface — we don't need the full provider-pool machinery for
* a hook that only reads `poolEntries`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
let mockPoolEntries: Array<{ docName: string; provider: { document: Y.Doc } }> = [];
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({
poolEntries: mockPoolEntries,
}),
diff --git a/packages/app/src/hooks/use-no-push-permission-toast.dom.test.tsx b/packages/app/src/hooks/use-no-push-permission-toast.dom.test.tsx
index dfa18d58d..1d0a4acbb 100644
--- a/packages/app/src/hooks/use-no-push-permission-toast.dom.test.tsx
+++ b/packages/app/src/hooks/use-no-push-permission-toast.dom.test.tsx
@@ -10,9 +10,10 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { act, cleanup, fireEvent, render } from '@testing-library/react';
import { useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Spy on the toast surface. Pre-import-mock — sets up before the hook
// module evaluates its `import { toast } from 'sonner'`.
@@ -20,7 +21,7 @@ const toastInfoCalls: string[] = [];
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
info: (msg: string) => {
toastInfoCalls.push(msg);
@@ -35,7 +36,7 @@ mock.module('sonner', () => ({
// provide. Stub the macro so `t\`...\`` evaluates to the literal English
// (the macro normally compiles the template into a `t(...)` call wrapping
// the source string + a hash; the stub keeps things readable in assertions).
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
useLingui: () => ({
t: (strings: TemplateStringsArray) => strings.join(''),
diff --git a/packages/app/src/hooks/use-onboarding-card-visible.dom.test.tsx b/packages/app/src/hooks/use-onboarding-card-visible.dom.test.tsx
index 8267fa7f4..759c25f64 100644
--- a/packages/app/src/hooks/use-onboarding-card-visible.dom.test.tsx
+++ b/packages/app/src/hooks/use-onboarding-card-visible.dom.test.tsx
@@ -1,5 +1,5 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
createOnboardingCardStore,
type OnboardingCardStorage,
@@ -31,7 +31,7 @@ function clearDesktopHost(): void {
}
function mockDocuments(documents: unknown[]): void {
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents }), { status: 200 })),
) as never;
}
@@ -54,7 +54,7 @@ afterEach(() => {
describe('useOnboardingCardVisible', () => {
test('no desktop host → never visible, never activates', async () => {
clearDesktopHost();
- const fetchMock = mock(() =>
+ const fetchMock = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
);
globalThis.fetch = fetchMock as never;
@@ -78,7 +78,7 @@ describe('useOnboardingCardVisible', () => {
});
test('established session (other project present) → stays hidden', async () => {
- const listRecent = mock(() => Promise.resolve([{ path: CURRENT_PATH }, { path: '/other' }]));
+ const listRecent = vi.fn(() => Promise.resolve([{ path: CURRENT_PATH }, { path: '/other' }]));
(window as unknown as { okDesktop: unknown }).okDesktop = {
project: { listRecent },
config: { projectPath: CURRENT_PATH },
@@ -95,7 +95,7 @@ describe('useOnboardingCardVisible', () => {
});
test('dismissed store → hidden and skips evaluation', async () => {
- const fetchMock = mock(() =>
+ const fetchMock = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
);
globalThis.fetch = fetchMock as never;
@@ -125,7 +125,7 @@ describe('useOnboardingCardVisible', () => {
});
test('completed store → hidden forever', async () => {
- const fetchMock = mock(() =>
+ const fetchMock = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
);
globalThis.fetch = fetchMock as never;
@@ -143,7 +143,7 @@ describe('useOnboardingCardVisible', () => {
// cleanup sets `cancelled`, so a resolution after unmount must NOT activate —
// otherwise it would latch a card for a project the user already left.
let resolveRecents!: (r: Array<{ path: string }>) => void;
- const listRecent = mock(
+ const listRecent = vi.fn(
() =>
new Promise<Array<{ path: string }>>((res) => {
resolveRecents = res;
diff --git a/packages/app/src/hooks/use-onboarding-card-visible.test.ts b/packages/app/src/hooks/use-onboarding-card-visible.test.ts
index fc0cde1bd..f6ea94c5b 100644
--- a/packages/app/src/hooks/use-onboarding-card-visible.test.ts
+++ b/packages/app/src/hooks/use-onboarding-card-visible.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { evaluateFreshProject } from './use-onboarding-card-visible';
@@ -22,7 +22,7 @@ function rejectingBridge(): OkDesktopBridge {
}
function mockDocumentsResponse(body: unknown, status = 200): void {
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify(body), { status })),
) as never;
}
@@ -49,7 +49,7 @@ describe('evaluateFreshProject', () => {
});
test('a second switchable project → null (does not fetch documents)', async () => {
- const fetchSpy = mock(() => Promise.resolve(new Response('{}', { status: 200 })));
+ const fetchSpy = vi.fn(() => Promise.resolve(new Response('{}', { status: 200 })));
globalThis.fetch = fetchSpy as never;
expect(
await evaluateFreshProject(bridgeWith([{ path: CURRENT_PATH }, { path: '/other/project' }])),
@@ -85,7 +85,7 @@ describe('evaluateFreshProject', () => {
});
test('freshly created but a second project exists → null (hasOtherProject wins)', async () => {
- const fetchSpy = mock(() => Promise.resolve(new Response('{}', { status: 200 })));
+ const fetchSpy = vi.fn(() => Promise.resolve(new Response('{}', { status: 200 })));
globalThis.fetch = fetchSpy as never;
expect(
await evaluateFreshProject(
diff --git a/packages/app/src/hooks/use-onboarding-file-completion.dom.test.tsx b/packages/app/src/hooks/use-onboarding-file-completion.dom.test.tsx
index 1bd77e0c1..a40fd0453 100644
--- a/packages/app/src/hooks/use-onboarding-file-completion.dom.test.tsx
+++ b/packages/app/src/hooks/use-onboarding-file-completion.dom.test.tsx
@@ -1,5 +1,5 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { emitDocumentsChanged } from '@/lib/documents-events';
import {
createOnboardingCardStore,
@@ -20,7 +20,7 @@ function freshStore(): OnboardingCardStore {
}
function mockDocuments(documents: unknown[]): void {
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents }), { status: 200 })),
) as never;
}
@@ -54,7 +54,7 @@ describe('useOnboardingFileCompletion', () => {
});
test('ignores non-files channels — no extra fetch on graph/backlinks updates', async () => {
- const fetchMock = mock(() =>
+ const fetchMock = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
);
globalThis.fetch = fetchMock as never;
@@ -80,7 +80,7 @@ describe('useOnboardingFileCompletion', () => {
});
test('does not mark the step while the project stays empty', async () => {
- const fetchMock = mock(() =>
+ const fetchMock = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
);
globalThis.fetch = fetchMock as never;
@@ -97,7 +97,7 @@ describe('useOnboardingFileCompletion', () => {
});
test('skips subscribing and fetching when the file step is already complete', async () => {
- const fetchMock = mock(() =>
+ const fetchMock = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents: [] }), { status: 200 })),
);
globalThis.fetch = fetchMock as never;
diff --git a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
index 575f36d10..5481d19c7 100644
--- a/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
+++ b/packages/app/src/hooks/use-reconcile-skill-tabs.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { skillLiveDocName } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { computeSkillTabReconcile, parseSkillTabDocName } from './use-reconcile-skill-tabs';
/**
diff --git a/packages/app/src/hooks/use-selection-context.dom.test.tsx b/packages/app/src/hooks/use-selection-context.dom.test.tsx
index d77effe88..d9aa68eab 100644
--- a/packages/app/src/hooks/use-selection-context.dom.test.tsx
+++ b/packages/app/src/hooks/use-selection-context.dom.test.tsx
@@ -8,9 +8,9 @@
* DOM Range over a static value display.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { act, cleanup, render } from '@testing-library/react';
import { useRef } from 'react';
+import { afterEach, describe, expect, test } from 'vitest';
import { getSelectionContext, publishSelectionContext } from '@/editor/selection-context';
import { usePublishFrontmatterSelection } from './use-selection-context';
diff --git a/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx b/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx
index 80e81d0c7..41f5ffb95 100644
--- a/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx
+++ b/packages/app/src/hooks/use-terminal-enabled.dom.test.tsx
@@ -7,19 +7,20 @@
* project-local layer, and routing grant/revoke to `terminal.enabled` via the
* binding's `patch` (the human-only write path).
*/
-import { afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+
import type { Config, ConfigBinding, ConfigPatch } from '@inkeep/open-knowledge-core';
import { cleanup, render } from '@testing-library/react';
+import { afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import type { TerminalConsentState, TerminalEnabledWriter } from './use-terminal-enabled';
const consentGrants: true[] = [];
-mock.module('@/lib/terminal-telemetry', () => ({
+vi.doMock('@/lib/terminal-telemetry', () => ({
recordShellConsentGranted: () => consentGrants.push(true),
recordTerminalOpened: () => undefined,
}));
-// Load the hooks AFTER the mock registers — `mock.module` is not hoisted, but a
+// Load the hooks AFTER the mock registers — `vi.doMock` is not hoisted, but a
// static import is, so a static import of the subject would bind the real
// telemetry module before the mock takes effect.
let useTerminalConsentState: typeof import('./use-terminal-enabled').useTerminalConsentState;
diff --git a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
index 9561ed0f7..160512d53 100644
--- a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
+++ b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
@@ -5,26 +5,12 @@
* (precedent #43); invocation via `bun run test:dom`. Pairs with the
* verbatim user-intent contract documented in precedent #40(a).
*
- * # Root cause of the prior Linux-CI failure (resolved)
- *
- * Bun's `mock.module(...)` patches a module in-place for the lifetime of
- * the `bun test` invocation — the mock persists across sibling test files
- * (oven-sh/bun#12823). Sibling `src/lib/config-provider.dom.test.tsx`
- * declares `mock.module('@/hooks/use-theme-bridge', () => ({
- * useThemeBridge: () => {} }))` at module level. On Linux CI, filesystem
- * iteration ordered `src/lib/...` before `src/hooks/...`, so by the time
- * this file ran the hook had already been replaced with a no-op; the
- * `<HookProbe>` rendered, the (no-op) effect "fired", but nothing pushed
- * onto `setThemeSourceCalls` — exactly the `Received: 0` mode. On macOS
- * inode iteration happened to order this file before `config-provider`,
- * so the leak couldn't surface locally.
- *
- * The fix is one line in `scripts/run-test-dom.sh`: pass `--isolate` so
- * each test file gets a fresh global object and `mock.module` patches
- * don't bleed across files. Documented in the script's preamble.
+ * The DOM Vitest project keeps `isolate: true` so the module mock in the
+ * sibling config-provider suite cannot replace this hook's real implementation.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { useThemeBridge } from './use-theme-bridge';
@@ -140,12 +126,12 @@ function installControllableMatchMedia(initialMatches: boolean) {
}
describe('useThemeBridge (Tier-3 mount)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/hooks/use-theme-bridge.test.ts b/packages/app/src/hooks/use-theme-bridge.test.ts
index 9ee3832ea..1ae90f4db 100644
--- a/packages/app/src/hooks/use-theme-bridge.test.ts
+++ b/packages/app/src/hooks/use-theme-bridge.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('useThemeBridge — module surface', () => {
test('exports the useThemeBridge hook', async () => {
diff --git a/packages/app/src/hooks/use-update-channel.dom.test.tsx b/packages/app/src/hooks/use-update-channel.dom.test.tsx
index 14238ae27..1d2be05ad 100644
--- a/packages/app/src/hooks/use-update-channel.dom.test.tsx
+++ b/packages/app/src/hooks/use-update-channel.dom.test.tsx
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { useUpdateChannel } from './use-update-channel';
diff --git a/packages/app/src/hooks/use-update-channel.test.ts b/packages/app/src/hooks/use-update-channel.test.ts
index d465c074b..68721cdb5 100644
--- a/packages/app/src/hooks/use-update-channel.test.ts
+++ b/packages/app/src/hooks/use-update-channel.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('useUpdateChannel module', () => {
test('exports the hook + the UpdateChannel union', async () => {
diff --git a/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx b/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx
index 90180bc09..7b354554c 100644
--- a/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx
+++ b/packages/app/src/hooks/use-worktree-autosync-notice.dom.test.tsx
@@ -1,15 +1,15 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
-const toast = mock((_node: unknown) => {});
-mock.module('sonner', () => ({ toast }));
+const toast = vi.fn((_node: unknown) => {});
+vi.doMock('sonner', () => ({ toast }));
let ctx: {
projectLocalConfig: unknown;
projectLocalSynced: boolean;
- projectLocalBinding: { patch: ReturnType<typeof mock> } | null;
+ projectLocalBinding: { patch: ReturnType<typeof vi.fn> } | null;
};
-mock.module('@/lib/config-provider', () => ({ useConfigContext: () => ctx }));
+vi.doMock('@/lib/config-provider', () => ({ useConfigContext: () => ctx }));
// Import the hook AFTER the mocks register so it binds to the mocked
// config-provider / sonner rather than the real modules.
@@ -20,7 +20,7 @@ function Probe() {
return null;
}
-const patch = mock(() => ({ ok: true }));
+const patch = vi.fn(() => ({ ok: true }));
beforeEach(() => {
cleanup();
diff --git a/packages/app/src/lib/agent-presence.test.ts b/packages/app/src/lib/agent-presence.test.ts
index e58b7e01a..34eee3f70 100644
--- a/packages/app/src/lib/agent-presence.test.ts
+++ b/packages/app/src/lib/agent-presence.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { AgentPresenceEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
AGENT_PRESENCE_STALE_MS,
type AgentPresenceAwareness,
diff --git a/packages/app/src/lib/api-config.test.ts b/packages/app/src/lib/api-config.test.ts
index 73166de71..aaf395394 100644
--- a/packages/app/src/lib/api-config.test.ts
+++ b/packages/app/src/lib/api-config.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { fetchApiConfig } from './api-config';
type FetchFn = typeof globalThis.fetch;
diff --git a/packages/app/src/lib/auth-state-cache.test.ts b/packages/app/src/lib/auth-state-cache.test.ts
index 26835c8bd..eb0a2a553 100644
--- a/packages/app/src/lib/auth-state-cache.test.ts
+++ b/packages/app/src/lib/auth-state-cache.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { getLastKnownSignedIn, setLastKnownSignedIn } from './auth-state-cache';
describe('auth-state-cache', () => {
diff --git a/packages/app/src/lib/cc1.test.ts b/packages/app/src/lib/cc1.test.ts
index 55ce0d1a1..bab74a43f 100644
--- a/packages/app/src/lib/cc1.test.ts
+++ b/packages/app/src/lib/cc1.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
CC1_CHANNEL_BRANCH_SWITCHED,
CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,
@@ -409,7 +409,7 @@ describe('parseCC1ConfigValidationRejected', () => {
});
test('dispatchCC1Stateless routes config-validation-rejected to its handler', () => {
- const handler = mock(() => {});
+ const handler = vi.fn(() => {});
dispatchCC1Stateless(
JSON.stringify({
v: CC1_CONTRACT_VERSION,
@@ -533,7 +533,7 @@ describe('parseCC1ConfigIgnoreNestedError', () => {
});
test('dispatchCC1Stateless routes config-ignore-nested-error to its handler', () => {
- const handler = mock(() => {});
+ const handler = vi.fn(() => {});
dispatchCC1Stateless(
JSON.stringify({
v: CC1_CONTRACT_VERSION,
@@ -548,8 +548,8 @@ describe('parseCC1ConfigIgnoreNestedError', () => {
});
test('config-ignore-nested-error is mutually exclusive with config-validation-rejected', () => {
- const nested = mock(() => {});
- const rejected = mock(() => {});
+ const nested = vi.fn(() => {});
+ const rejected = vi.fn(() => {});
dispatchCC1Stateless(
JSON.stringify({
v: CC1_CONTRACT_VERSION,
diff --git a/packages/app/src/lib/client-fetch.test.ts b/packages/app/src/lib/client-fetch.test.ts
index 0764d2105..52e3050d7 100644
--- a/packages/app/src/lib/client-fetch.test.ts
+++ b/packages/app/src/lib/client-fetch.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
import { installClientFetchWrapper } from './client-fetch';
/**
@@ -38,7 +38,7 @@ type Recorded = { input: RequestInfo | URL; init?: RequestInit };
function stubWindowFetch() {
const calls: Array<Recorded> = [];
- const fetchStub = mock((input: RequestInfo | URL, init?: RequestInit) => {
+ const fetchStub = vi.fn((input: RequestInfo | URL, init?: RequestInit) => {
calls.push({ input, init });
return Promise.resolve(new Response('{"ok":true}', { status: 200 }));
});
diff --git a/packages/app/src/lib/client-version.test.ts b/packages/app/src/lib/client-version.test.ts
index 992180fb2..4f73ec420 100644
--- a/packages/app/src/lib/client-version.test.ts
+++ b/packages/app/src/lib/client-version.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
BROWSER_RUNTIME_VERSION,
browserClientVersionHeaders,
diff --git a/packages/app/src/lib/color-themes.test.ts b/packages/app/src/lib/color-themes.test.ts
index 97461d1cb..f0e4a77e9 100644
--- a/packages/app/src/lib/color-themes.test.ts
+++ b/packages/app/src/lib/color-themes.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { ConfigSchema, resolveLeafSchema } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { getEnumOptions } from '../components/settings/schema-walker';
import {
buildCustomThemeCss,
diff --git a/packages/app/src/lib/command-menu-parity.test.ts b/packages/app/src/lib/command-menu-parity.test.ts
index 3b6f3092c..6f5177c73 100644
--- a/packages/app/src/lib/command-menu-parity.test.ts
+++ b/packages/app/src/lib/command-menu-parity.test.ts
@@ -15,10 +15,10 @@
* both platform branches is classified palette-command / OS-role / reserved.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { COMMAND_IDENTITIES, type MenuPlatform } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { PALETTE_COMMANDS } from '@/components/command-palette-commands';
import { APP_RESERVED_IDS, PALETTE_COMMAND_IDS } from '@/lib/command-menu-parity.test-helper';
import { formatShortcut, type KeyboardShortcutId } from '@/lib/keyboard-shortcuts';
diff --git a/packages/app/src/lib/config-context.dom.test.tsx b/packages/app/src/lib/config-context.dom.test.tsx
index 4aacbf08b..8c6c2667d 100644
--- a/packages/app/src/lib/config-context.dom.test.tsx
+++ b/packages/app/src/lib/config-context.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import type { Config } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { ConfigContext, type ConfigContextValue, useConfigContext } from './config-context';
function makeContextValue(): ConfigContextValue {
@@ -26,10 +26,10 @@ function Consumer() {
}
describe('useConfigContext runtime guard', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/lib/config-ignore-nested-error-events.test.ts b/packages/app/src/lib/config-ignore-nested-error-events.test.ts
index 4472811c0..15cdc2ffa 100644
--- a/packages/app/src/lib/config-ignore-nested-error-events.test.ts
+++ b/packages/app/src/lib/config-ignore-nested-error-events.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
emitConfigIgnoreNestedError,
subscribeToConfigIgnoreNestedError,
@@ -14,7 +14,7 @@ const SAMPLE_PAYLOAD = {
describe('config-ignore-nested-error-events pubsub', () => {
test('subscribed listener fires on emit', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsub = subscribeToConfigIgnoreNestedError(listener);
emitConfigIgnoreNestedError(SAMPLE_PAYLOAD);
expect(listener).toHaveBeenCalledTimes(1);
@@ -23,7 +23,7 @@ describe('config-ignore-nested-error-events pubsub', () => {
});
test('unsubscribe stops the listener', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsub = subscribeToConfigIgnoreNestedError(listener);
unsub();
emitConfigIgnoreNestedError(SAMPLE_PAYLOAD);
@@ -31,8 +31,8 @@ describe('config-ignore-nested-error-events pubsub', () => {
});
test('multiple subscribers all fire', () => {
- const a = mock(() => {});
- const b = mock(() => {});
+ const a = vi.fn(() => {});
+ const b = vi.fn(() => {});
const ua = subscribeToConfigIgnoreNestedError(a);
const ub = subscribeToConfigIgnoreNestedError(b);
emitConfigIgnoreNestedError(SAMPLE_PAYLOAD);
@@ -43,10 +43,10 @@ describe('config-ignore-nested-error-events pubsub', () => {
});
test('listener exception is caught; other listeners still fire', () => {
- const thrower = mock(() => {
+ const thrower = vi.fn(() => {
throw new Error('boom');
});
- const ok = mock(() => {});
+ const ok = vi.fn(() => {});
const u1 = subscribeToConfigIgnoreNestedError(thrower);
const u2 = subscribeToConfigIgnoreNestedError(ok);
expect(() => emitConfigIgnoreNestedError(SAMPLE_PAYLOAD)).not.toThrow();
diff --git a/packages/app/src/lib/config-provider.dom.test.tsx b/packages/app/src/lib/config-provider.dom.test.tsx
index 545e5b3cc..bff94f03d 100644
--- a/packages/app/src/lib/config-provider.dom.test.tsx
+++ b/packages/app/src/lib/config-provider.dom.test.tsx
@@ -4,11 +4,12 @@
* React Context API surface under the jsdom substrate (precedent #43);
* invocation via `bun run test:dom`.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-// `mock.module(...)` is module-level and is NOT reset by Bun's `mock.restore()`
-// — it persists for the lifetime of this file. Both `describe` blocks below
+// `vi.doMock(...)` is module-level and is not reset by `vi.restoreAllMocks()`;
+// it persists for the lifetime of this file. Both `describe` blocks below
// share the mocked `useThemeBridge` surface. That's intentional here because
// every test in this file exercises the `collabUrl: null` cold-start path (the
// prop is passed as null below) where the real provider early-returns before
@@ -16,7 +17,7 @@ import { cleanup, render, screen } from '@testing-library/react';
// needs to exercise the REAL seam (e.g. asserting that ConfigProvider calls
// useThemeBridge with `themeValue ?? 'system'`), start a sibling `*.dom.test.tsx`
// file rather than fighting these module-level mocks.
-mock.module('@/hooks/use-theme-bridge', () => ({
+vi.doMock('@/hooks/use-theme-bridge', () => ({
useThemeBridge: () => {},
}));
@@ -72,10 +73,10 @@ describe('ConfigProvider runtime (Tier-3)', () => {
});
describe('useConfigContext outside provider', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/app/src/lib/config-provider.test.tsx b/packages/app/src/lib/config-provider.test.tsx
index 8052bac71..ee06ad19e 100644
--- a/packages/app/src/lib/config-provider.test.tsx
+++ b/packages/app/src/lib/config-provider.test.tsx
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
describe('ConfigProvider module surface', () => {
test('exports ConfigProvider component and useConfigContext hook', async () => {
diff --git a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx b/packages/app/src/lib/config-provider.user-synced.dom.test.tsx
index 369ecd4e6..6fd1aa577 100644
--- a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx
+++ b/packages/app/src/lib/config-provider.user-synced.dom.test.tsx
@@ -19,9 +19,9 @@
* `test:dom` keeps the mock graphs independent per file).
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import type { ConfigBinding, OkignoreBinding, WriteScope } from '@inkeep/open-knowledge-core';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { __resetServerInstanceStoreForTests, setServerInstanceId } from './server-instance-store';
// One captured listener per binding scope so the test can fire the synced
@@ -114,7 +114,7 @@ function makeFakeOkignoreBinding(): OkignoreBinding {
} as unknown as OkignoreBinding;
}
-mock.module('@/hooks/use-theme-bridge', () => ({
+vi.doMock('@/hooks/use-theme-bridge', () => ({
useThemeBridge: (bridge: unknown, theme: string) => {
useThemeBridgeCalls.push([bridge, theme]);
},
@@ -124,7 +124,7 @@ mock.module('@/hooks/use-theme-bridge', () => ({
// inside ConfigProvider's effect. Provide a no-op shim so the effect's
// `setTheme(themeValue)` call inside the merged-config bridge does not
// throw when run outside a `ThemeProvider`.
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({
setTheme: (theme: string) => {
setThemeCalls.push(theme);
@@ -138,7 +138,7 @@ mock.module('next-themes', () => ({
// to control deterministically). The fake captures the okignore
// 'synced' handler so test cases can drive it directly; ConfigBinding
// 'synced' wiring is captured via the bindConfigDoc mock below.
-mock.module('@hocuspocus/provider', () => {
+vi.doMock('@hocuspocus/provider', () => {
class FakeHocuspocusProvider {
private readonly record: ProviderRecord;
@@ -162,7 +162,7 @@ mock.module('@hocuspocus/provider', () => {
return { HocuspocusProvider: FakeHocuspocusProvider };
});
-mock.module('@/lib/auth-token', () => ({
+vi.doMock('@/lib/auth-token', () => ({
buildAuthToken: (...args: readonly unknown[]) => {
buildAuthTokenCalls.push(args);
return 'test-auth-token';
@@ -173,7 +173,7 @@ mock.module('@/lib/auth-token', () => ({
// calls to produce the binding objects it then subscribes to. The fakes
// return ConfigBindings whose `subscribeSynced` listener is captured per
// scope so the test can trigger the false→true transition by hand.
-mock.module('@inkeep/open-knowledge-core', () => ({
+vi.doMock('@inkeep/open-knowledge-core', () => ({
bindConfigDoc: (_provider: unknown, scope: WriteScope) =>
makeFakeConfigBinding(scope, scope === 'user' ? userHasSyncedSeed : false),
bindOkignoreDoc: () => makeFakeOkignoreBinding(),
@@ -199,7 +199,7 @@ mock.module('@inkeep/open-knowledge-core', () => ({
}));
// Module-level toggle for the second case (mount-time pre-synced seed).
-// Bun module mocks resolve once at import time, but the factory closes
+// Vitest module mocks resolve once at import time, but the factory closes
// over this variable so each test can flip the value via the helper
// before the dynamic import below.
let userHasSyncedSeed = false;
@@ -230,14 +230,14 @@ function ConfigContextProbe() {
}
describe('ConfigProvider — userSynced behavioral wiring (Tier-3)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
resetCaptures();
lastContext = null;
userHasSyncedSeed = false;
__resetServerInstanceStoreForTests();
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
@@ -394,7 +394,7 @@ describe('ConfigProvider — userSynced behavioral wiring (Tier-3)', () => {
});
test('provider disconnect and close callbacks emit structured role logs', async () => {
- const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
render(
<ConfigProvider collabUrl="ws://test.invalid">
diff --git a/packages/app/src/lib/config-validation-events.test.ts b/packages/app/src/lib/config-validation-events.test.ts
index 85023017b..254970754 100644
--- a/packages/app/src/lib/config-validation-events.test.ts
+++ b/packages/app/src/lib/config-validation-events.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
emitConfigValidationRejected,
subscribeToConfigValidationRejected,
@@ -14,7 +14,7 @@ const SAMPLE_PAYLOAD = {
describe('config-validation-events pubsub', () => {
test('subscribed listener fires on emit', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsub = subscribeToConfigValidationRejected(listener);
emitConfigValidationRejected(SAMPLE_PAYLOAD);
expect(listener).toHaveBeenCalledTimes(1);
@@ -23,7 +23,7 @@ describe('config-validation-events pubsub', () => {
});
test('unsubscribe stops the listener', () => {
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsub = subscribeToConfigValidationRejected(listener);
unsub();
emitConfigValidationRejected(SAMPLE_PAYLOAD);
@@ -31,8 +31,8 @@ describe('config-validation-events pubsub', () => {
});
test('multiple subscribers all fire', () => {
- const a = mock(() => {});
- const b = mock(() => {});
+ const a = vi.fn(() => {});
+ const b = vi.fn(() => {});
const ua = subscribeToConfigValidationRejected(a);
const ub = subscribeToConfigValidationRejected(b);
emitConfigValidationRejected(SAMPLE_PAYLOAD);
@@ -43,10 +43,10 @@ describe('config-validation-events pubsub', () => {
});
test('listener exception is caught; other listeners still fire', () => {
- const thrower = mock(() => {
+ const thrower = vi.fn(() => {
throw new Error('boom');
});
- const ok = mock(() => {});
+ const ok = vi.fn(() => {});
const u1 = subscribeToConfigValidationRejected(thrower);
const u2 = subscribeToConfigValidationRejected(ok);
expect(() => emitConfigValidationRejected(SAMPLE_PAYLOAD)).not.toThrow();
diff --git a/packages/app/src/lib/consent-store.test.ts b/packages/app/src/lib/consent-store.test.ts
index bf3e388a1..4714563e6 100644
--- a/packages/app/src/lib/consent-store.test.ts
+++ b/packages/app/src/lib/consent-store.test.ts
@@ -3,7 +3,7 @@
* flows. Mirrors `mcp-consent-store.test.ts` shape — no @testing-library/react,
* exercises the store via the module API directly.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { createConsentStore } from './consent-store';
import type {
OkDesktopBridge,
@@ -13,11 +13,11 @@ import type {
interface MockBridgeShape {
onboarding: {
- onShow: ReturnType<typeof mock>;
- signalReady: ReturnType<typeof mock>;
- confirm: ReturnType<typeof mock>;
- cancel: ReturnType<typeof mock>;
- probeContent: ReturnType<typeof mock>;
+ onShow: ReturnType<typeof vi.fn>;
+ signalReady: ReturnType<typeof vi.fn>;
+ confirm: ReturnType<typeof vi.fn>;
+ cancel: ReturnType<typeof vi.fn>;
+ probeContent: ReturnType<typeof vi.fn>;
};
fireShow: (payload: OkOnboardingShowPayload) => void;
unsubscribeCalls: number;
@@ -35,23 +35,23 @@ function makeBridge(
handler: null as ((payload: OkOnboardingShowPayload) => void) | null,
unsubscribeCalls: 0,
};
- const onShow = mock((cb: (payload: OkOnboardingShowPayload) => void) => {
+ const onShow = vi.fn((cb: (payload: OkOnboardingShowPayload) => void) => {
state.handler = cb;
- return mock(() => {
+ return vi.fn(() => {
state.handler = null;
state.unsubscribeCalls += 1;
});
});
- const signalReady = mock(() => {});
- const confirm = mock(() => {
+ const signalReady = vi.fn(() => {});
+ const confirm = vi.fn(() => {
if (opts.confirmThrows) return Promise.reject(new Error('confirm-boom'));
return Promise.resolve(opts.confirmResult ?? { ok: true });
});
- const cancel = mock(() => {
+ const cancel = vi.fn(() => {
if (opts.cancelThrows) return Promise.reject(new Error('cancel-boom'));
return Promise.resolve(opts.cancelResult ?? { ok: true });
});
- const probeContent = mock(() =>
+ const probeContent = vi.fn(() =>
Promise.resolve({ ok: true, count: 0, sample: [], truncated: false }),
);
diff --git a/packages/app/src/lib/crash-invite-store.test.ts b/packages/app/src/lib/crash-invite-store.test.ts
index 8c64a4b74..8f403e440 100644
--- a/packages/app/src/lib/crash-invite-store.test.ts
+++ b/packages/app/src/lib/crash-invite-store.test.ts
@@ -1,6 +1,5 @@
-import { describe, expect, mock, test } from 'bun:test';
-
import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
@@ -86,7 +85,7 @@ describe('createCrashInviteStore — invitation delivery', () => {
const fb = fakeBridge();
const store = createCrashInviteStore();
store.install({ bridge: fb.bridge });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
fb.emit(crashEvent);
@@ -99,7 +98,7 @@ describe('createCrashInviteStore — invitation delivery', () => {
const store = createCrashInviteStore();
store.install({ bridge: fb.bridge });
fb.emit(crashEvent);
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
store.dismiss();
diff --git a/packages/app/src/lib/create-file-events.test.ts b/packages/app/src/lib/create-file-events.test.ts
index 86b45715e..ddcdfaf77 100644
--- a/packages/app/src/lib/create-file-events.test.ts
+++ b/packages/app/src/lib/create-file-events.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { emitCreateTopLevelFile, subscribeToCreateTopLevelFile } from './create-file-events';
const originalWindow = globalThis.window;
diff --git a/packages/app/src/lib/create-page.test.ts b/packages/app/src/lib/create-page.test.ts
index 3cf1128f1..34c1a1010 100644
--- a/packages/app/src/lib/create-page.test.ts
+++ b/packages/app/src/lib/create-page.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createPagePathFromSeed } from './create-page';
describe('createPagePathFromSeed', () => {
diff --git a/packages/app/src/lib/current-branch-store.test.ts b/packages/app/src/lib/current-branch-store.test.ts
index f599ae637..2f97a8912 100644
--- a/packages/app/src/lib/current-branch-store.test.ts
+++ b/packages/app/src/lib/current-branch-store.test.ts
@@ -3,7 +3,7 @@
* isolate the cache + listener machinery from the production singleton's
* window-scoped event channel.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { createBranchStore } from './current-branch-store';
function makeEventStub(): {
@@ -34,10 +34,10 @@ describe('createBranchStore', () => {
test('first subscribe triggers exactly one bootstrap fetch', async () => {
const events = makeEventStub();
- const fetchBranch = mock(() => Promise.resolve('main'));
+ const fetchBranch = vi.fn(() => Promise.resolve('main'));
const store = createBranchStore({ fetchBranch, subscribeToEvent: events.subscribeToEvent });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
store.subscribe(listener);
store.subscribe(listener);
@@ -54,7 +54,7 @@ describe('createBranchStore', () => {
fetchBranch: () => Promise.resolve(null),
subscribeToEvent: events.subscribeToEvent,
});
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
events.emit('feature-x');
@@ -68,7 +68,7 @@ describe('createBranchStore', () => {
fetchBranch: () => Promise.resolve(null),
subscribeToEvent: events.subscribeToEvent,
});
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
events.emit('main');
@@ -83,7 +83,7 @@ describe('createBranchStore', () => {
fetchBranch: () => Promise.resolve(null),
subscribeToEvent: events.subscribeToEvent,
});
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsub = store.subscribe(listener);
events.emit('first');
diff --git a/packages/app/src/lib/default-cli-resolver.test.ts b/packages/app/src/lib/default-cli-resolver.test.ts
index b94f8e87f..d1f5b4920 100644
--- a/packages/app/src/lib/default-cli-resolver.test.ts
+++ b/packages/app/src/lib/default-cli-resolver.test.ts
@@ -10,8 +10,8 @@
* 3. else 'claude'.
*/
-import { describe, expect, test } from 'bun:test';
import { TERMINAL_CLI_IDS, type TerminalCli } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { resolveDefaultCli } from './default-cli-resolver';
import { TERMINAL_CLI_ID, terminalCliId } from './unified-agent-store';
diff --git a/packages/app/src/lib/doc-hash.test.ts b/packages/app/src/lib/doc-hash.test.ts
index 032dbe9c2..fc57ccada 100644
--- a/packages/app/src/lib/doc-hash.test.ts
+++ b/packages/app/src/lib/doc-hash.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
anchorFromHash,
assetPathFromHash,
diff --git a/packages/app/src/lib/doc-panel-width-store.test.ts b/packages/app/src/lib/doc-panel-width-store.test.ts
index 129bd7a42..83876416a 100644
--- a/packages/app/src/lib/doc-panel-width-store.test.ts
+++ b/packages/app/src/lib/doc-panel-width-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
DEFAULT_DOC_PANEL_WIDTH,
DOC_PANEL_WIDTH_KEY,
diff --git a/packages/app/src/lib/doc-paths.test.ts b/packages/app/src/lib/doc-paths.test.ts
index 6e2eac4b1..09d37fb28 100644
--- a/packages/app/src/lib/doc-paths.test.ts
+++ b/packages/app/src/lib/doc-paths.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { docNameToDialogSeed, docNameToMarkdownPath, normalizeDocNameInput } from './doc-paths';
describe('normalizeDocNameInput', () => {
diff --git a/packages/app/src/lib/document-stats.test.ts b/packages/app/src/lib/document-stats.test.ts
index e2bc610a1..c3a3ef83e 100644
--- a/packages/app/src/lib/document-stats.test.ts
+++ b/packages/app/src/lib/document-stats.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeBodyStats, computeSelectionStats, EMPTY_STATS } from './document-stats';
describe('computeBodyStats', () => {
diff --git a/packages/app/src/lib/documents-events.test.ts b/packages/app/src/lib/documents-events.test.ts
index 224873581..a296da2aa 100644
--- a/packages/app/src/lib/documents-events.test.ts
+++ b/packages/app/src/lib/documents-events.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { emitDocumentsChanged, subscribeToDocumentsChanged } from './documents-events';
const originalWindow = globalThis.window;
diff --git a/packages/app/src/lib/documents-fetch.test.ts b/packages/app/src/lib/documents-fetch.test.ts
index 11e19d7cd..e22e491fc 100644
--- a/packages/app/src/lib/documents-fetch.test.ts
+++ b/packages/app/src/lib/documents-fetch.test.ts
@@ -4,7 +4,7 @@
* result cache — sequential calls refetch), that a rejection releases the slot,
* and the `{ ok, status, body }` shaping (including the not-JSON → null path).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { __resetDocumentListInflightForTests, fetchDocumentListShared } from './documents-fetch';
const realFetch = globalThis.fetch;
diff --git a/packages/app/src/lib/external-link.test.ts b/packages/app/src/lib/external-link.test.ts
index 91f66165f..ec8fb86fb 100644
--- a/packages/app/src/lib/external-link.test.ts
+++ b/packages/app/src/lib/external-link.test.ts
@@ -11,13 +11,13 @@
* `window.open(url, '_blank', 'noopener,noreferrer')`.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { openExternalUrl } from './external-link.ts';
describe('openExternalUrl — Electron host', () => {
test('routes through okDesktop.shell.openExternal and does NOT open a new window', () => {
- const openExternal = mock(async () => {});
- const openWindow = mock(() => null);
+ const openExternal = vi.fn(async () => {});
+ const openWindow = vi.fn(() => null);
openExternalUrl('https://youtube.com/watch?v=abc', {
okDesktop: { shell: { openExternal } },
openWindow,
@@ -30,14 +30,14 @@ describe('openExternalUrl — Electron host', () => {
describe('openExternalUrl — web host (no bridge)', () => {
test('falls back to window.open with the new-tab + noopener features', () => {
- const openWindow = mock(() => null);
+ const openWindow = vi.fn(() => null);
openExternalUrl('https://example.com', { okDesktop: undefined, openWindow });
expect(openWindow).toHaveBeenCalledTimes(1);
expect(openWindow).toHaveBeenCalledWith('https://example.com', '_blank', 'noopener,noreferrer');
});
test('falls back to window.open when the bridge has no openExternal', () => {
- const openWindow = mock(() => null);
+ const openWindow = vi.fn(() => null);
openExternalUrl('https://example.com', { okDesktop: { shell: {} }, openWindow });
expect(openWindow).toHaveBeenCalledTimes(1);
expect(openWindow).toHaveBeenCalledWith('https://example.com', '_blank', 'noopener,noreferrer');
@@ -46,14 +46,14 @@ describe('openExternalUrl — web host (no bridge)', () => {
describe('openExternalUrl — structural scheme gate (internal)', () => {
test('an unsafe scheme is refused on the web path — never reaches window.open', () => {
- const openWindow = mock(() => null);
+ const openWindow = vi.fn(() => null);
// biome-ignore lint/suspicious/noExplicitAny: exercising the security gate with a hostile scheme
openExternalUrl('javascript:alert(1)' as any, { okDesktop: undefined, openWindow });
expect(openWindow).not.toHaveBeenCalled();
});
test('an unsafe scheme is refused on the desktop path — never reaches the bridge', () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
// biome-ignore lint/suspicious/noExplicitAny: exercising the security gate with a hostile scheme
openExternalUrl('javascript:alert(1)' as any, { okDesktop: { shell: { openExternal } } });
expect(openExternal).not.toHaveBeenCalled();
diff --git a/packages/app/src/lib/file-menu-target-resolvers.test.ts b/packages/app/src/lib/file-menu-target-resolvers.test.ts
index 123c80944..4a06beaf4 100644
--- a/packages/app/src/lib/file-menu-target-resolvers.test.ts
+++ b/packages/app/src/lib/file-menu-target-resolvers.test.ts
@@ -10,7 +10,7 @@
* project / asset) doesn't silently land the menu pick on the wrong path.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildSendToAiInputForActiveTarget,
resolveActiveTargetAbsPath,
diff --git a/packages/app/src/lib/file-protocol-page.test.ts b/packages/app/src/lib/file-protocol-page.test.ts
index 657c456ea..bf7a6cdf8 100644
--- a/packages/app/src/lib/file-protocol-page.test.ts
+++ b/packages/app/src/lib/file-protocol-page.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isFileProtocolPage } from './file-protocol-page';
describe('isFileProtocolPage', () => {
diff --git a/packages/app/src/lib/file-tree-menu-action-events.test.ts b/packages/app/src/lib/file-tree-menu-action-events.test.ts
index 581ae65d8..30483face 100644
--- a/packages/app/src/lib/file-tree-menu-action-events.test.ts
+++ b/packages/app/src/lib/file-tree-menu-action-events.test.ts
@@ -7,7 +7,7 @@
* breaks either side from silently making File → Move to Trash a no-op.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
import {
emitFileTreeMenuActionDelete,
diff --git a/packages/app/src/lib/handoff/cowork-skill-install.test.ts b/packages/app/src/lib/handoff/cowork-skill-install.test.ts
index 83c4d8a9d..eb8b0e7bc 100644
--- a/packages/app/src/lib/handoff/cowork-skill-install.test.ts
+++ b/packages/app/src/lib/handoff/cowork-skill-install.test.ts
@@ -7,7 +7,7 @@
* `skill-installer.test.ts`. This file covers the guard policy.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
buildCoworkSkillGuardKey,
type EnsureCoworkSkillDeps,
@@ -34,7 +34,7 @@ function memoryStorage(initial: Record<string, string> = {}): SkillInstallStorag
}
function fakeInstaller(result: SkillInstallResult): SkillInstaller {
- return { install: mock(async () => result) };
+ return { install: vi.fn(async () => result) };
}
function deps(overrides: Partial<EnsureCoworkSkillDeps> = {}): EnsureCoworkSkillDeps {
diff --git a/packages/app/src/lib/handoff/dispatch.test.ts b/packages/app/src/lib/handoff/dispatch.test.ts
index 9d1fc7fc9..68a2abc77 100644
--- a/packages/app/src/lib/handoff/dispatch.test.ts
+++ b/packages/app/src/lib/handoff/dispatch.test.ts
@@ -10,8 +10,8 @@
* (e) exhaustiveness guard fires for unknown targets at runtime
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { HandoffPayload, HandoffTarget } from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import { dispatchHandoff } from './dispatch.ts';
const BASE_PAYLOAD = {
@@ -21,7 +21,7 @@ const BASE_PAYLOAD = {
} as const;
function makeFetch(status: number, bodyJson?: unknown) {
- const fetchImpl = mock(async (..._args: Parameters<typeof globalThis.fetch>) => {
+ const fetchImpl = vi.fn(async (..._args: Parameters<typeof globalThis.fetch>) => {
return new Response(JSON.stringify(bodyJson ?? {}), {
status,
headers: { 'Content-Type': 'application/json' },
@@ -153,7 +153,7 @@ describe('dispatchHandoff — HTTP failure mapping', () => {
});
test('network error (fetch throws) → dispatch-error with detail', async () => {
- const fetchImpl = mock(async () => {
+ const fetchImpl = vi.fn(async () => {
throw new Error('NetworkError when attempting to fetch resource.');
}) as unknown as typeof globalThis.fetch;
const payload: HandoffPayload = { ...BASE_PAYLOAD, target: 'codex' };
diff --git a/packages/app/src/lib/handoff/install-detect.test.ts b/packages/app/src/lib/handoff/install-detect.test.ts
index f3238dadb..08094b570 100644
--- a/packages/app/src/lib/handoff/install-detect.test.ts
+++ b/packages/app/src/lib/handoff/install-detect.test.ts
@@ -18,7 +18,7 @@
* injectable `now()` drives the clock; `probe` is a test-harness function.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createProbeCoordinator,
DEFAULT_THROTTLE_MS,
diff --git a/packages/app/src/lib/handoff/open-external.test.ts b/packages/app/src/lib/handoff/open-external.test.ts
index 343dd0a24..eaefc8bdf 100644
--- a/packages/app/src/lib/handoff/open-external.test.ts
+++ b/packages/app/src/lib/handoff/open-external.test.ts
@@ -10,12 +10,12 @@
* `dispatch-error` with detail `'no DOM available'` rather than throwing.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { openExternal } from './open-external.ts';
function makeElectron(openImpl: (url: string) => Promise<void>) {
return {
- shell: { openExternal: mock(openImpl) },
+ shell: { openExternal: vi.fn(openImpl) },
};
}
@@ -52,15 +52,15 @@ describe('openExternal — Electron host', () => {
describe('openExternal — web host (anchor-click)', () => {
function makeFakeDoc(): Document {
- const body: { appendChild: ReturnType<typeof mock> } = { appendChild: mock(() => {}) };
+ const body: { appendChild: ReturnType<typeof vi.fn> } = { appendChild: vi.fn(() => {}) };
const anchor = {
href: '',
rel: '',
- click: mock(() => {}),
- remove: mock(() => {}),
+ click: vi.fn(() => {}),
+ remove: vi.fn(() => {}),
};
const doc = {
- createElement: mock((_tag: string) => anchor),
+ createElement: vi.fn((_tag: string) => anchor),
body,
__anchor: anchor,
};
@@ -83,10 +83,10 @@ describe('openExternal — web host (anchor-click)', () => {
const anchor = {
href: '',
rel: '',
- click: mock(() => {
+ click: vi.fn(() => {
throw new Error('browser-blocked');
}),
- remove: mock(() => {}),
+ remove: vi.fn(() => {}),
};
const doc = {
createElement: () => anchor,
@@ -104,7 +104,7 @@ describe('openExternal — host selection', () => {
test('Electron path takes precedence when okDesktop is provided (doc is ignored)', async () => {
const okDesktop = makeElectron(async () => {});
const doc = {
- createElement: mock(() => {
+ createElement: vi.fn(() => {
throw new Error('should-not-be-called');
}),
body: { appendChild: () => {} },
diff --git a/packages/app/src/lib/handoff/skill-installer.test.ts b/packages/app/src/lib/handoff/skill-installer.test.ts
index 9fca70906..97b01428f 100644
--- a/packages/app/src/lib/handoff/skill-installer.test.ts
+++ b/packages/app/src/lib/handoff/skill-installer.test.ts
@@ -10,7 +10,7 @@
* surfaced as ok-false with diagnostic reason codes.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
type ElectronSkillBridge,
electronSkillInstaller,
@@ -20,7 +20,7 @@ import {
describe('electronSkillInstaller', () => {
test('bridge ok: returns ok with path', async () => {
const bridge: ElectronSkillBridge = {
- buildAndOpen: mock(async () => ({ ok: true, path: '/tmp/skill' })),
+ buildAndOpen: vi.fn(async () => ({ ok: true, path: '/tmp/skill' })),
};
const installer = electronSkillInstaller(bridge);
@@ -30,7 +30,7 @@ describe('electronSkillInstaller', () => {
test('bridge fails: returns ok-false with reason + message', async () => {
const bridge: ElectronSkillBridge = {
- buildAndOpen: mock(async () => ({
+ buildAndOpen: vi.fn(async () => ({
ok: false,
reason: 'build-failed',
message: 'no SKILL.md',
@@ -47,7 +47,7 @@ describe('electronSkillInstaller', () => {
test('bridge throws: ok-false with bridge-error reason (IPC channel broken)', async () => {
const bridge: ElectronSkillBridge = {
- buildAndOpen: mock(async () => {
+ buildAndOpen: vi.fn(async () => {
throw new Error('IPC channel closed');
}),
};
@@ -68,7 +68,7 @@ describe('httpSkillInstaller', () => {
body?: unknown;
throwError?: Error;
}): typeof fetch {
- return mock(async () => {
+ return vi.fn(async () => {
if (response.throwError) throw response.throwError;
return {
ok: response.ok ?? true,
@@ -84,7 +84,7 @@ describe('httpSkillInstaller', () => {
await installer.install();
- const [url, init] = (fetchSpy as unknown as ReturnType<typeof mock>).mock.calls[0] as [
+ const [url, init] = (fetchSpy as unknown as ReturnType<typeof vi.fn>).mock.calls[0] as [
string,
RequestInit,
];
@@ -100,7 +100,7 @@ describe('httpSkillInstaller', () => {
await installer.install();
- const [url] = (fetchSpy as unknown as ReturnType<typeof mock>).mock.calls[0] as [string];
+ const [url] = (fetchSpy as unknown as ReturnType<typeof vi.fn>).mock.calls[0] as [string];
expect(url).toBe('http://localhost:5173/api/install-skill');
});
@@ -148,7 +148,7 @@ describe('httpSkillInstaller', () => {
test('non-2xx HTTP response with no body: ok-false falls back to HTTP <status>', async () => {
const installer = httpSkillInstaller({
- fetch: mock(
+ fetch: vi.fn(
async () =>
({
ok: false,
@@ -243,7 +243,7 @@ describe('httpSkillInstaller', () => {
test('response.json() throws: ok-false with parse-error (malformed body)', async () => {
const installer = httpSkillInstaller({
- fetch: mock(
+ fetch: vi.fn(
async () =>
({
ok: true,
diff --git a/packages/app/src/lib/handoff/targets.test.ts b/packages/app/src/lib/handoff/targets.test.ts
index 905f97078..88a346227 100644
--- a/packages/app/src/lib/handoff/targets.test.ts
+++ b/packages/app/src/lib/handoff/targets.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { KNOWN_TARGETS, VISIBLE_TARGETS } from './targets.ts';
describe('KNOWN_TARGETS', () => {
diff --git a/packages/app/src/lib/handoff/telemetry.test.ts b/packages/app/src/lib/handoff/telemetry.test.ts
index 3814c2e4b..d7a6498d7 100644
--- a/packages/app/src/lib/handoff/telemetry.test.ts
+++ b/packages/app/src/lib/handoff/telemetry.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type HandoffStatsLine, recordHandoff } from './telemetry.ts';
const sampleLine: HandoffStatsLine = {
diff --git a/packages/app/src/lib/handoff/use-claude-desktop-integration.test.ts b/packages/app/src/lib/handoff/use-claude-desktop-integration.test.ts
index caafdffbf..13a885a7d 100644
--- a/packages/app/src/lib/handoff/use-claude-desktop-integration.test.ts
+++ b/packages/app/src/lib/handoff/use-claude-desktop-integration.test.ts
@@ -5,7 +5,7 @@
* hook gets a surface-only smoke test.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
createDefaultFetchSnapshot,
type ProbeDeps,
@@ -147,8 +147,8 @@ describe('probeClaudeDesktopIntegration — failure modes', () => {
describe('runIntegrationProbe — cache + subscriber coalescing', () => {
test('every subscriber fires when the probe resolves (useSyncExternalStore contract: no-args)', async () => {
- const a = mock();
- const b = mock();
+ const a = vi.fn();
+ const b = vi.fn();
const unsubA = subscribeClaudeDesktopIntegration(a);
const unsubB = subscribeClaudeDesktopIntegration(b);
try {
@@ -198,7 +198,7 @@ describe('runIntegrationProbe — cache + subscriber coalescing', () => {
});
test('subscriber unsubscribe stops further notifications', async () => {
- const a = mock();
+ const a = vi.fn();
const unsub = subscribeClaudeDesktopIntegration(a);
await runIntegrationProbe(deps({ fetchSnapshot: async () => okSnapshot('6.0.0') }));
expect(a).toHaveBeenCalledTimes(1);
diff --git a/packages/app/src/lib/has-valid-prompt-input.test.ts b/packages/app/src/lib/has-valid-prompt-input.test.ts
index e03731a3c..5134f8f89 100644
--- a/packages/app/src/lib/has-valid-prompt-input.test.ts
+++ b/packages/app/src/lib/has-valid-prompt-input.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { hasValidPromptInput } from './has-valid-prompt-input';
describe('hasValidPromptInput', () => {
diff --git a/packages/app/src/lib/install-client-log-forwarder.test.ts b/packages/app/src/lib/install-client-log-forwarder.test.ts
index d43d85e55..0b4cb8ab9 100644
--- a/packages/app/src/lib/install-client-log-forwarder.test.ts
+++ b/packages/app/src/lib/install-client-log-forwarder.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import {
RENDERER_LOG_MAX_BATCH_BYTES,
RENDERER_LOG_MAX_ENTRIES,
} from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
type ClientLogForwarderHandle,
installClientLogForwarder,
@@ -71,7 +71,7 @@ function makeFakeDocument(visibilityState = 'visible') {
}
function makeFetchSpy() {
- return mock((_url: string, _init?: RequestInit) =>
+ return vi.fn((_url: string, _init?: RequestInit) =>
Promise.resolve(new Response(null, { status: 200 })),
);
}
@@ -160,7 +160,7 @@ describe('installClientLogForwarder', () => {
test('re-entrancy guard: a console call during flush does not recurse', () => {
let conRef: ConsoleLike | undefined;
- const fetchSpy = mock((_url: string, _init?: RequestInit) => {
+ const fetchSpy = vi.fn((_url: string, _init?: RequestInit) => {
conRef?.error('error raised while flushing'); // transitive console during flush
return Promise.resolve(new Response(null, { status: 200 }));
});
@@ -230,7 +230,7 @@ describe('installClientLogForwarder', () => {
test('a failed POST is counted and carried as droppedSinceLastFlush on the next batch', async () => {
let failNext = true;
- const fetchSpy = mock((_url: string, _init?: RequestInit) =>
+ const fetchSpy = vi.fn((_url: string, _init?: RequestInit) =>
failNext
? Promise.reject(new Error('network down'))
: Promise.resolve(new Response(null, { status: 200 })),
@@ -253,7 +253,7 @@ describe('installClientLogForwarder', () => {
test('a non-2xx response counts the batch as dropped', async () => {
let reject = true;
- const fetchSpy = mock((_url: string, _init?: RequestInit) =>
+ const fetchSpy = vi.fn((_url: string, _init?: RequestInit) =>
Promise.resolve(new Response(null, { status: reject ? 500 : 200 })),
);
const { con } = install(fetchSpy);
@@ -278,7 +278,7 @@ describe('installClientLogForwarder', () => {
// exercised here: the flush-at-cap drains the queue at exactly the cap, so it
// never grows past it — the failed-POST path is the real bound.)
let failNext = true;
- const fetchSpy = mock((_url: string, _init?: RequestInit) =>
+ const fetchSpy = vi.fn((_url: string, _init?: RequestInit) =>
failNext
? Promise.reject(new Error('network down'))
: Promise.resolve(new Response(null, { status: 200 })),
@@ -299,7 +299,7 @@ describe('installClientLogForwarder', () => {
test('drop count resets after a delivered batch (field absent when zero)', async () => {
let failNext = true;
- const fetchSpy = mock((_url: string, _init?: RequestInit) =>
+ const fetchSpy = vi.fn((_url: string, _init?: RequestInit) =>
failNext
? Promise.reject(new Error('network down'))
: Promise.resolve(new Response(null, { status: 200 })),
diff --git a/packages/app/src/lib/install-deep-link-listener.test.ts b/packages/app/src/lib/install-deep-link-listener.test.ts
index d49a0ef21..fbdf21800 100644
--- a/packages/app/src/lib/install-deep-link-listener.test.ts
+++ b/packages/app/src/lib/install-deep-link-listener.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { normalizeTargetPath } from '@/components/navigation-targets';
import { missDialogStore } from '@/lib/share/miss-dialog-store';
import { pendingReceiveNavStore } from '@/lib/share/pending-receive-nav-store';
@@ -25,27 +25,27 @@ function makeBridge(overrides: Partial<OkDesktopBridge> = {}): OkDesktopBridge &
projectName: 'project',
mode: 'editor',
} as OkDesktopConfig,
- onProjectSwitched: mock(() => () => {}),
- onMenuAction: mock(() => () => {}),
- onDeepLink: mock((cb: (evt: DeepLinkPayload) => void) => {
+ onProjectSwitched: vi.fn(() => () => {}),
+ onMenuAction: vi.fn(() => () => {}),
+ onDeepLink: vi.fn((cb: (evt: DeepLinkPayload) => void) => {
handler = cb;
- return mock(() => {
+ return vi.fn(() => {
handler = null;
});
}),
dialog: {
- openFolder: mock(() => Promise.resolve(null)),
+ openFolder: vi.fn(() => Promise.resolve(null)),
},
shell: {
- openExternal: mock(() => Promise.resolve()),
+ openExternal: vi.fn(() => Promise.resolve()),
},
clipboard: {
- writeText: mock(() => Promise.resolve()),
+ writeText: vi.fn(() => Promise.resolve()),
},
project: {
- listRecent: mock(() => Promise.resolve([])),
- removeRecent: mock(() => Promise.resolve()),
- getSessionState: mock(() =>
+ listRecent: vi.fn(() => Promise.resolve([])),
+ removeRecent: vi.fn(() => Promise.resolve()),
+ getSessionState: vi.fn(() =>
Promise.resolve({
openTabs: [],
pinnedTabIds: [],
@@ -54,9 +54,9 @@ function makeBridge(overrides: Partial<OkDesktopBridge> = {}): OkDesktopBridge &
updatedAt: null,
}),
),
- setSessionState: mock(() => Promise.resolve()),
- open: mock(() => Promise.resolve()),
- close: mock(() => Promise.resolve()),
+ setSessionState: vi.fn(() => Promise.resolve()),
+ open: vi.fn(() => Promise.resolve()),
+ close: vi.fn(() => Promise.resolve()),
},
platform: 'darwin',
appVersion: '0.0.0',
@@ -69,7 +69,7 @@ function makeBridge(overrides: Partial<OkDesktopBridge> = {}): OkDesktopBridge &
describe('installDeepLinkListener (M4 US-007)', () => {
test('no-op when bridge is undefined (web / CLI distribution)', () => {
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
const result = installDeepLinkListener({ bridge: undefined, setHash });
expect(result).toBeUndefined();
expect(setHash.mock.calls.length).toBe(0);
@@ -77,16 +77,16 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('registers onDeepLink when bridge is present', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
const unsubscribe = installDeepLinkListener({ bridge, setHash });
expect(unsubscribe).toBeDefined();
- expect((bridge.onDeepLink as ReturnType<typeof mock>).mock.calls.length).toBe(1);
+ expect((bridge.onDeepLink as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1);
expect(setHash.mock.calls.length).toBe(0);
});
test('updates hash to #/<doc> on deep-link event', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'intro.md' });
expect(setHash.mock.calls[0]).toEqual(['#/intro.md']);
@@ -94,7 +94,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('URL-encodes doc names with spaces / unicode', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'My Doc — 2026.md' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/My%20Doc%20%E2%80%94%202026.md');
@@ -107,18 +107,18 @@ describe('installDeepLinkListener (M4 US-007)', () => {
// consumer `docNameFromHash` (packages/app/src/lib/doc-hash.ts) splits on
// `/` then decodes each segment, reconstructing `docs/a` cleanly.
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'notes/meeting-2026' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/notes%2Fmeeting-2026');
});
test('returns bridge unsubscribe so callers can detach on teardown', () => {
- const detach = mock(() => {});
+ const detach = vi.fn(() => {});
const bridge = makeBridge({
- onDeepLink: mock(() => detach),
+ onDeepLink: vi.fn(() => detach),
});
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
const unsubscribe = installDeepLinkListener({ bridge, setHash });
unsubscribe?.();
expect(detach.mock.calls.length).toBe(1);
@@ -126,7 +126,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('appends ?branch=<encoded> when branch is present in payload', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'intro.md', branch: 'main' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/intro.md?branch=main');
@@ -134,7 +134,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('URL-encodes slashed branch names like feat/foo', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'docs/page.md', branch: 'feat/foo' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/docs%2Fpage.md?branch=feat%2Ffoo');
@@ -142,7 +142,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('treats null branch identically to absent branch (back-compat)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'intro.md', branch: null });
expect(setHash.mock.calls[0]?.[0]).toBe('#/intro.md');
@@ -150,7 +150,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('treats undefined branch identically to absent branch (back-compat)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'intro.md', branch: undefined });
expect(setHash.mock.calls[0]?.[0]).toBe('#/intro.md');
@@ -161,7 +161,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
// `branch` at all (the field is genuinely missing, not just undefined)
// must produce the unchanged `#/<doc>` hash.
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
const legacyPayload = { doc: 'intro.md' } as { doc: string; branch?: string | null };
bridge.fireDeepLink(legacyPayload);
@@ -170,7 +170,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('encodes branch with unicode characters', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'page.md', branch: '日本語' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/page.md?branch=%E6%97%A5%E6%9C%AC%E8%AA%9E');
@@ -178,7 +178,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
test('explicit kind:doc behaves identically to legacy (omitted kind)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'intro.md', kind: 'doc', branch: 'main' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/intro.md?branch=main');
@@ -188,7 +188,7 @@ describe('installDeepLinkListener (M4 US-007)', () => {
describe('installDeepLinkListener — folder + content-root shares (US-010)', () => {
test('folder event navigates to the trailing-slash folder hash', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/docs/sub/');
@@ -196,7 +196,7 @@ describe('installDeepLinkListener — folder + content-root shares (US-010)', ()
test('content-root folder event (empty doc) navigates to the root hash #/', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: '', kind: 'folder' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/');
@@ -204,7 +204,7 @@ describe('installDeepLinkListener — folder + content-root shares (US-010)', ()
test('folder event does NOT append ?branch= (branch resolved upstream)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder', branch: 'feat/x' });
expect(setHash.mock.calls[0]?.[0]).toBe('#/docs/sub/');
@@ -219,7 +219,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
test('arms the miss guard before navigating a doc share', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'notes/plan', branch: 'feature' });
// Path is the resolver's normalized form so it matches the missing
@@ -233,7 +233,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
test('arms with a null branch for a branch-less legacy doc share', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'intro' });
expect(pendingReceiveNavStore.getSnapshot()?.branch).toBeNull();
@@ -241,7 +241,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
test('arms with the folder kind for a folder share', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder' });
expect(pendingReceiveNavStore.getSnapshot()?.kind).toBe('folder');
@@ -253,7 +253,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
// path. The in-tab pendingReceiveNav panel is not armed on this leg.
test('arms the miss dialog without navigating when main flags the target missing', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'notes/plan', branch: 'feature', targetMissing: true });
expect(setHash.mock.calls.length).toBe(0);
@@ -267,7 +267,7 @@ describe('installDeepLinkListener — share-receive miss guard arming', () => {
test('arms the miss dialog for a missing folder target without navigating', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
+ const setHash = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash });
bridge.fireDeepLink({ doc: 'docs/sub', kind: 'folder', targetMissing: true });
expect(setHash.mock.calls.length).toBe(0);
@@ -340,8 +340,8 @@ describe('deriveShareReceiveToast (FR9)', () => {
describe('installDeepLinkListener — FR9 toast emission', () => {
test('emits toast with branch + path when share is multi-candidate', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
- const emitToast = mock(() => {});
+ const setHash = vi.fn(() => {});
+ const emitToast = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash, emitToast });
bridge.fireDeepLink({ doc: 'docs/x.md', branch: 'feat-bar', multiCandidate: true });
expect(emitToast.mock.calls).toHaveLength(1);
@@ -354,8 +354,8 @@ describe('installDeepLinkListener — FR9 toast emission', () => {
test('suppresses toast when share has no branch (legacy)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
- const emitToast = mock(() => {});
+ const setHash = vi.fn(() => {});
+ const emitToast = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash, emitToast });
bridge.fireDeepLink({ doc: 'docs/x.md' });
expect(emitToast.mock.calls).toHaveLength(0);
@@ -363,8 +363,8 @@ describe('installDeepLinkListener — FR9 toast emission', () => {
test('suppresses toast for single-clone (P4) — multiCandidate is false', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
- const emitToast = mock(() => {});
+ const setHash = vi.fn(() => {});
+ const emitToast = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash, emitToast });
bridge.fireDeepLink({ doc: 'docs/x.md', branch: 'feat-bar', multiCandidate: false });
expect(emitToast.mock.calls).toHaveLength(0);
@@ -372,8 +372,8 @@ describe('installDeepLinkListener — FR9 toast emission', () => {
test('suppresses toast when multiCandidate is absent (legacy emitter)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
- const emitToast = mock(() => {});
+ const setHash = vi.fn(() => {});
+ const emitToast = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash, emitToast });
bridge.fireDeepLink({ doc: 'docs/x.md', branch: 'feat-bar' });
expect(emitToast.mock.calls).toHaveLength(0);
@@ -381,8 +381,8 @@ describe('installDeepLinkListener — FR9 toast emission', () => {
test('suppresses the confirmation toast on a known-missing target (miss dialog is the surface)', () => {
const bridge = makeBridge();
- const setHash = mock(() => {});
- const emitToast = mock(() => {});
+ const setHash = vi.fn(() => {});
+ const emitToast = vi.fn(() => {});
installDeepLinkListener({ bridge, setHash, emitToast });
// multiCandidate would normally emit "Opened on branch X"; a missing target
// shows the verdict dialog without navigating, so the confirmation is
diff --git a/packages/app/src/lib/install-recent-removed-listener.test.ts b/packages/app/src/lib/install-recent-removed-listener.test.ts
index 9beb58937..e5979bd53 100644
--- a/packages/app/src/lib/install-recent-removed-listener.test.ts
+++ b/packages/app/src/lib/install-recent-removed-listener.test.ts
@@ -1,18 +1,18 @@
-import { beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
import * as actualSonner from 'sonner';
+import { beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
// Capture the plain `toast(...)` call so we can assert the wiring without a DOM.
-const toastPlain = mock((_msg: string) => 'toast-id');
-mock.module('sonner', () => ({
+const toastPlain = vi.fn((_msg: string) => 'toast-id');
+vi.doMock('sonner', () => ({
...actualSonner,
toast: Object.assign(toastPlain, {
- warning: mock(() => 'w'),
- success: mock(() => 's'),
- error: mock(() => 'e'),
- dismiss: mock(() => {}),
- custom: mock(() => 'c'),
- loading: mock(() => 'l'),
+ warning: vi.fn(() => 'w'),
+ success: vi.fn(() => 's'),
+ error: vi.fn(() => 'e'),
+ dismiss: vi.fn(() => {}),
+ custom: vi.fn(() => 'c'),
+ loading: vi.fn(() => 'l'),
}),
}));
@@ -45,9 +45,9 @@ describe('installRecentRemovedListener', () => {
test('subscribes once and toasts the project name when the event fires', () => {
let captured: ((info: { path: string; projectName: string }) => void) | null = null;
- const unsubscribe = mock(() => {});
+ const unsubscribe = vi.fn(() => {});
const bridge = {
- onRecentRemovedMissing: mock((cb: (info: { path: string; projectName: string }) => void) => {
+ onRecentRemovedMissing: vi.fn((cb: (info: { path: string; projectName: string }) => void) => {
captured = cb;
return unsubscribe;
}),
diff --git a/packages/app/src/lib/install-server-drift-listener.test.ts b/packages/app/src/lib/install-server-drift-listener.test.ts
index 1c14cdc39..947289c87 100644
--- a/packages/app/src/lib/install-server-drift-listener.test.ts
+++ b/packages/app/src/lib/install-server-drift-listener.test.ts
@@ -1,5 +1,5 @@
-import { beforeAll, describe, expect, mock, test } from 'bun:test';
import * as actualSonner from 'sonner';
+import { beforeAll, describe, expect, test, vi } from 'vitest';
import type {
OkDesktopBridge,
OkServerRestartOutcome,
@@ -7,16 +7,16 @@ import type {
} from '@/lib/desktop-bridge-types';
// Capture sonner calls so we can assert the toast wiring without a DOM.
-const toastWarning = mock((_msg: string, _opts?: unknown) => 'warn-id');
-const toastSuccess = mock((_msg: string) => 'success-id');
-const toastLoading = mock((_msg: string, _opts?: unknown) => 'loading-id');
-const toastError = mock((_msg: string, _opts?: unknown) => 'error-id');
-const toastDismiss = mock((_id?: unknown) => {});
-const toastCustom = mock((_render: (id: unknown) => unknown, _opts?: unknown) => 'custom-id');
-mock.module('sonner', () => ({
+const toastWarning = vi.fn((_msg: string, _opts?: unknown) => 'warn-id');
+const toastSuccess = vi.fn((_msg: string) => 'success-id');
+const toastLoading = vi.fn((_msg: string, _opts?: unknown) => 'loading-id');
+const toastError = vi.fn((_msg: string, _opts?: unknown) => 'error-id');
+const toastDismiss = vi.fn((_id?: unknown) => {});
+const toastCustom = vi.fn((_render: (id: unknown) => unknown, _opts?: unknown) => 'custom-id');
+vi.doMock('sonner', () => ({
...actualSonner,
toast: Object.assign(
- mock(() => {}),
+ vi.fn(() => {}),
{
warning: toastWarning,
success: toastSuccess,
@@ -59,15 +59,15 @@ function makeBridge(opts?: { restartOutcome?: OkServerRestartOutcome; restartRej
bridge: OkDesktopBridge;
fireDrift: (info: OkServerVersionDriftInfo) => void;
fireRestarted: (appRuntime: string) => void;
- restartServer: ReturnType<typeof mock>;
- unsubDrift: ReturnType<typeof mock>;
- unsubRestarted: ReturnType<typeof mock>;
+ restartServer: ReturnType<typeof vi.fn>;
+ unsubDrift: ReturnType<typeof vi.fn>;
+ unsubRestarted: ReturnType<typeof vi.fn>;
} {
let driftCb: ((info: OkServerVersionDriftInfo) => void) | null = null;
let restartedCb: ((info: { appRuntime: string }) => void) | null = null;
- const unsubDrift = mock(() => {});
- const unsubRestarted = mock(() => {});
- const restartServer = mock(async () => {
+ const unsubDrift = vi.fn(() => {});
+ const unsubRestarted = vi.fn(() => {});
+ const restartServer = vi.fn(async () => {
if (opts?.restartReject) throw new Error('channel closed');
return opts?.restartOutcome ?? { ok: true };
});
diff --git a/packages/app/src/lib/keyboard-shortcuts.test.ts b/packages/app/src/lib/keyboard-shortcuts.test.ts
index acbe2b187..44c9bb2bf 100644
--- a/packages/app/src/lib/keyboard-shortcuts.test.ts
+++ b/packages/app/src/lib/keyboard-shortcuts.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
formatShortcut,
formatShortcutBindingLabel,
diff --git a/packages/app/src/lib/lazy-with-preload.test.ts b/packages/app/src/lib/lazy-with-preload.test.ts
index b1a11bd03..e2d64df3c 100644
--- a/packages/app/src/lib/lazy-with-preload.test.ts
+++ b/packages/app/src/lib/lazy-with-preload.test.ts
@@ -17,8 +17,8 @@
* promise — both pre- and post-resolution).
*/
-import { describe, expect, test } from 'bun:test';
import type { ComponentType } from 'react';
+import { describe, expect, test } from 'vitest';
import { lazyWithPreload } from './lazy-with-preload';
// The component is never mounted — these tests exercise the preload
diff --git a/packages/app/src/lib/local-menu-action-bus.test.ts b/packages/app/src/lib/local-menu-action-bus.test.ts
index 7162628a8..959ff6b42 100644
--- a/packages/app/src/lib/local-menu-action-bus.test.ts
+++ b/packages/app/src/lib/local-menu-action-bus.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkMenuAction } from './desktop-bridge-types';
import {
__resetLocalMenuActionBusForTests,
@@ -12,8 +12,8 @@ describe('local menu-action bus', () => {
});
test('emit reaches every subscriber exactly once (no double-fire)', () => {
- const a = mock(() => {});
- const b = mock(() => {});
+ const a = vi.fn(() => {});
+ const b = vi.fn(() => {});
subscribeLocalMenuAction(a);
subscribeLocalMenuAction(b);
@@ -26,7 +26,7 @@ describe('local menu-action bus', () => {
});
test('the same handler subscribed once fires once per emit', () => {
- const handler = mock(() => {});
+ const handler = vi.fn(() => {});
subscribeLocalMenuAction(handler);
emitLocalMenuAction('new-terminal');
@@ -36,8 +36,8 @@ describe('local menu-action bus', () => {
});
test('unsubscribe stops delivery to that handler only', () => {
- const kept = mock(() => {});
- const dropped = mock(() => {});
+ const kept = vi.fn(() => {});
+ const dropped = vi.fn(() => {});
subscribeLocalMenuAction(kept);
const unsubscribe = subscribeLocalMenuAction(dropped);
@@ -51,11 +51,11 @@ describe('local menu-action bus', () => {
test('a handler that unsubscribes itself mid-dispatch still lets siblings run', () => {
const order: string[] = [];
let unsub: (() => void) | null = null;
- const first = mock(() => {
+ const first = vi.fn(() => {
order.push('first');
unsub?.();
});
- const second = mock(() => {
+ const second = vi.fn(() => {
order.push('second');
});
unsub = subscribeLocalMenuAction(first);
@@ -69,7 +69,7 @@ describe('local menu-action bus', () => {
test('a throwing subscriber does not block delivery to later subscribers', () => {
const originalConsoleError = console.error;
- const errorSpy = mock(() => {});
+ const errorSpy = vi.fn(() => {});
console.error = errorSpy;
try {
const order: string[] = [];
@@ -122,7 +122,7 @@ describe('local menu-action bus — bridge forwarder', () => {
},
});
- const handler = mock(() => {});
+ const handler = vi.fn(() => {});
subscribeLocalMenuAction(handler);
// The forwarder installed exactly one bridge listener.
expect(inbound).not.toBeNull();
@@ -134,7 +134,7 @@ describe('local menu-action bus — bridge forwarder', () => {
test('the forwarder installs once (ref-counted) and tears down when the last subscriber leaves', () => {
let installs = 0;
- const unsubscribe = mock(() => {});
+ const unsubscribe = vi.fn(() => {});
setDesktop({
onMenuAction: () => {
installs += 1;
@@ -154,7 +154,7 @@ describe('local menu-action bus — bridge forwarder', () => {
test('a partial bridge without onMenuAction never throws; direct emits still deliver', () => {
setDesktop({}); // truthy-but-thin host (session-only / test stub)
- const handler = mock(() => {});
+ const handler = vi.fn(() => {});
expect(() => subscribeLocalMenuAction(handler)).not.toThrow();
emitLocalMenuAction('rename');
expect(handler).toHaveBeenCalledTimes(1);
diff --git a/packages/app/src/lib/lru-string-cache.test.ts b/packages/app/src/lib/lru-string-cache.test.ts
index 6bab0f0ff..b56dbb99c 100644
--- a/packages/app/src/lib/lru-string-cache.test.ts
+++ b/packages/app/src/lib/lru-string-cache.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { LruStringCache } from './lru-string-cache';
describe('LruStringCache', () => {
diff --git a/packages/app/src/lib/mcp-consent-store.test.ts b/packages/app/src/lib/mcp-consent-store.test.ts
index 5bfe9e776..c99542976 100644
--- a/packages/app/src/lib/mcp-consent-store.test.ts
+++ b/packages/app/src/lib/mcp-consent-store.test.ts
@@ -3,7 +3,7 @@
* Repo convention is no @testing-library/react; tests exercise the store via
* the module API directly and assert bridge-call counters + snapshot deltas.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import type {
OkDesktopBridge,
OkMcpWiringEditorId,
@@ -13,10 +13,10 @@ import { createMcpConsentStore } from './mcp-consent-store';
interface MockBridgeShape {
mcpWiring: {
- onShow: ReturnType<typeof mock>;
- signalReady: ReturnType<typeof mock>;
- confirm: ReturnType<typeof mock>;
- skip: ReturnType<typeof mock>;
+ onShow: ReturnType<typeof vi.fn>;
+ signalReady: ReturnType<typeof vi.fn>;
+ confirm: ReturnType<typeof vi.fn>;
+ skip: ReturnType<typeof vi.fn>;
};
fireShow: (payload: OkMcpWiringShowPayload) => void;
unsubscribeCalls: number;
@@ -34,19 +34,19 @@ function makeBridge(
handler: null as ((payload: OkMcpWiringShowPayload) => void) | null,
unsubscribeCalls: 0,
};
- const onShow = mock((cb: (payload: OkMcpWiringShowPayload) => void) => {
+ const onShow = vi.fn((cb: (payload: OkMcpWiringShowPayload) => void) => {
state.handler = cb;
- return mock(() => {
+ return vi.fn(() => {
state.handler = null;
state.unsubscribeCalls += 1;
});
});
- const signalReady = mock(() => {});
- const confirm = mock(() => {
+ const signalReady = vi.fn(() => {});
+ const confirm = vi.fn(() => {
if (opts.confirmThrows) return Promise.reject(new Error('confirm-boom'));
return Promise.resolve(opts.confirmResult ?? { ok: true });
});
- const skip = mock(() => {
+ const skip = vi.fn(() => {
if (opts.skipThrows) return Promise.reject(new Error('skip-boom'));
return Promise.resolve(opts.skipResult ?? { ok: true });
});
@@ -119,7 +119,7 @@ describe('createMcpConsentStore — onShow propagation', () => {
const store = createMcpConsentStore();
const bridge = makeBridge();
store.install({ bridge });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
bridge.fireShow(sampleShowPayload);
@@ -131,7 +131,7 @@ describe('createMcpConsentStore — onShow propagation', () => {
const store = createMcpConsentStore();
const bridge = makeBridge();
store.install({ bridge });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
const unsub = store.subscribe(listener);
unsub();
bridge.fireShow(sampleShowPayload);
@@ -257,7 +257,7 @@ describe('createMcpConsentStore — dismiss', () => {
const store = createMcpConsentStore();
const bridge = makeBridge();
store.install({ bridge });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
store.dismiss();
diff --git a/packages/app/src/lib/menu-label-parity.test.ts b/packages/app/src/lib/menu-label-parity.test.ts
index b24f516e3..065f1fce5 100644
--- a/packages/app/src/lib/menu-label-parity.test.ts
+++ b/packages/app/src/lib/menu-label-parity.test.ts
@@ -1,7 +1,7 @@
-import { beforeAll, describe, expect, it } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { COMMAND_IDENTITIES, MENU_LABELS } from '@inkeep/open-knowledge-core';
+import { beforeAll, describe, expect, it } from 'vitest';
import {
PALETTE_COMMAND_LABELS,
type PaletteLabelKey,
diff --git a/packages/app/src/lib/onboarding-card-store.test.ts b/packages/app/src/lib/onboarding-card-store.test.ts
index 7e06fddc7..a9a14fab0 100644
--- a/packages/app/src/lib/onboarding-card-store.test.ts
+++ b/packages/app/src/lib/onboarding-card-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createOnboardingCardStore,
DEFAULT_ONBOARDING_CARD_STATE,
diff --git a/packages/app/src/lib/onboarding-document-count.test.ts b/packages/app/src/lib/onboarding-document-count.test.ts
index 9ab4e77bf..baeb14dce 100644
--- a/packages/app/src/lib/onboarding-document-count.test.ts
+++ b/packages/app/src/lib/onboarding-document-count.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { DocumentListSuccess } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { countVisibleEntries } from './onboarding-document-count';
type Entry = DocumentListSuccess['documents'][number];
diff --git a/packages/app/src/lib/onboarding-signals.test.ts b/packages/app/src/lib/onboarding-signals.test.ts
index 96e2367a0..012709762 100644
--- a/packages/app/src/lib/onboarding-signals.test.ts
+++ b/packages/app/src/lib/onboarding-signals.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
createOnboardingCardStore,
type OnboardingCardStorage,
@@ -18,7 +18,7 @@ function freshStore(): OnboardingCardStore {
}
function mockDocuments(documents: unknown[], status = 200): void {
- globalThis.fetch = mock(() =>
+ globalThis.fetch = vi.fn(() =>
Promise.resolve(new Response(JSON.stringify({ documents }), { status })),
) as never;
}
@@ -91,7 +91,7 @@ describe('recordOnboardingFileStep', () => {
});
test('no-op when onboarding is not active (file created by an established user)', async () => {
- const fetchSpy = mock(() => Promise.resolve(new Response('{}', { status: 200 })));
+ const fetchSpy = vi.fn(() => Promise.resolve(new Response('{}', { status: 200 })));
globalThis.fetch = fetchSpy as never;
const store = freshStore();
await recordOnboardingFileStep(store);
@@ -100,7 +100,7 @@ describe('recordOnboardingFileStep', () => {
});
test('is a no-op (no fetch) when the step is already complete', async () => {
- const fetchSpy = mock(() => Promise.resolve(new Response('{}', { status: 200 })));
+ const fetchSpy = vi.fn(() => Promise.resolve(new Response('{}', { status: 200 })));
globalThis.fetch = fetchSpy as never;
const store = freshStore();
// activate() first so `initialized` is true — otherwise the guard's
diff --git a/packages/app/src/lib/parse-api-error.test.ts b/packages/app/src/lib/parse-api-error.test.ts
index 67069dc1a..33063163c 100644
--- a/packages/app/src/lib/parse-api-error.test.ts
+++ b/packages/app/src/lib/parse-api-error.test.ts
@@ -6,7 +6,7 @@
* each branch independently of any specific consumer.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseApiError } from './parse-api-error.ts';
describe('parseApiError', () => {
diff --git a/packages/app/src/lib/parse-server-response.test.ts b/packages/app/src/lib/parse-server-response.test.ts
index 5539a6f8d..5b0013d7f 100644
--- a/packages/app/src/lib/parse-server-response.test.ts
+++ b/packages/app/src/lib/parse-server-response.test.ts
@@ -8,7 +8,7 @@
* the contract deserves dedicated coverage.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { z } from 'zod';
import { parseServerResponse, parseSuccessOrWarn } from './parse-server-response.ts';
diff --git a/packages/app/src/lib/perf/circular-buffer.test.ts b/packages/app/src/lib/perf/circular-buffer.test.ts
index 9fbf513b2..b08dad45b 100644
--- a/packages/app/src/lib/perf/circular-buffer.test.ts
+++ b/packages/app/src/lib/perf/circular-buffer.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { CircularBuffer } from './circular-buffer';
describe('CircularBuffer', () => {
diff --git a/packages/app/src/lib/perf/cold-mount-instrumentation.test.ts b/packages/app/src/lib/perf/cold-mount-instrumentation.test.ts
index cee03f87b..6a5b186bf 100644
--- a/packages/app/src/lib/perf/cold-mount-instrumentation.test.ts
+++ b/packages/app/src/lib/perf/cold-mount-instrumentation.test.ts
@@ -7,8 +7,8 @@
* `tests/perf/scenarios/g4-profile-decomposition.ts`.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { Extension } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
shouldInstallColdMountInstrumentation,
wrapExtensionsWithTiming,
diff --git a/packages/app/src/lib/perf/collector.test.ts b/packages/app/src/lib/perf/collector.test.ts
index 1d6cce357..3370ab7aa 100644
--- a/packages/app/src/lib/perf/collector.test.ts
+++ b/packages/app/src/lib/perf/collector.test.ts
@@ -1,4 +1,4 @@
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import { getCollector, recordMark, recordVital } from './collector';
// Bun's test runner doesn't provide a DOM (env-override.test.ts shares
diff --git a/packages/app/src/lib/perf/env-override.test.ts b/packages/app/src/lib/perf/env-override.test.ts
index eb22847ed..67b98305f 100644
--- a/packages/app/src/lib/perf/env-override.test.ts
+++ b/packages/app/src/lib/perf/env-override.test.ts
@@ -1,13 +1,4 @@
-import {
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- describe,
- expect,
- spyOn,
- test,
-} from 'bun:test';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
import { readNumericOverride, resetPerfOverrideWarnings } from './env-override';
// Bun's test runner doesn't provide a DOM (repo convention — see
@@ -18,7 +9,7 @@ const hadWindow = typeof (globalThis as { window?: unknown }).window !== 'undefi
describe('readNumericOverride', () => {
const originalEnv = { ...import.meta.env };
- let warnSpy: ReturnType<typeof spyOn>;
+ let warnSpy: ReturnType<typeof vi.spyOn>;
beforeAll(() => {
if (!hadWindow) {
@@ -44,7 +35,7 @@ describe('readNumericOverride', () => {
delete (import.meta.env as Record<string, unknown>)[key];
}
}
- warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
});
afterEach(() => {
diff --git a/packages/app/src/lib/perf/get-pm-stats.test.ts b/packages/app/src/lib/perf/get-pm-stats.test.ts
index 52b5643f7..d6fab5c6b 100644
--- a/packages/app/src/lib/perf/get-pm-stats.test.ts
+++ b/packages/app/src/lib/perf/get-pm-stats.test.ts
@@ -7,10 +7,10 @@
* unit tests don't need a live `Editor` mount with DOM.
*/
-import { describe, expect, test } from 'bun:test';
import { type Mark, Schema } from '@tiptap/pm/model';
import { EditorState, Plugin, PluginKey } from '@tiptap/pm/state';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import { describe, expect, test } from 'vitest';
import { getPmStats, type PmStats } from './get-pm-stats';
// ---------------------------------------------------------------------------
diff --git a/packages/app/src/lib/perf/hdr-histogram.test.ts b/packages/app/src/lib/perf/hdr-histogram.test.ts
index ff0c602a4..594017e77 100644
--- a/packages/app/src/lib/perf/hdr-histogram.test.ts
+++ b/packages/app/src/lib/perf/hdr-histogram.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { HDR_HISTOGRAM_SENTINEL, Histogram } from './hdr-histogram';
/**
diff --git a/packages/app/src/lib/perf/mark.test.ts b/packages/app/src/lib/perf/mark.test.ts
index 33a58d092..ea1ce5cca 100644
--- a/packages/app/src/lib/perf/mark.test.ts
+++ b/packages/app/src/lib/perf/mark.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { __resetCardinalityWarnings, getCollector, getHistogramSnapshot } from './collector';
import { mark, validatePerfMarkName } from './mark';
@@ -126,7 +126,7 @@ describe('mark.count', () => {
});
test('warns once when prop key cardinality exceeds 100 distinct values', () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
// Up to 100 distinct values stays quiet.
for (let i = 0; i < 100; i += 1) {
@@ -151,7 +151,7 @@ describe('mark.count', () => {
});
test('warns in dev when name fails the regex', () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
mark.count('Bad/Name/Here');
const found = warnSpy.mock.calls.some((args) => String(args[0]).includes('mark.count name'));
@@ -194,7 +194,7 @@ describe('mark.histogram', () => {
});
test('warns in dev when name fails the regex', () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => undefined);
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
mark.histogram('Bad/Name', {}, 1);
const found = warnSpy.mock.calls.some((args) =>
diff --git a/packages/app/src/lib/perf/otel-spans.test.ts b/packages/app/src/lib/perf/otel-spans.test.ts
index 31d62b2db..b38486005 100644
--- a/packages/app/src/lib/perf/otel-spans.test.ts
+++ b/packages/app/src/lib/perf/otel-spans.test.ts
@@ -9,7 +9,7 @@
* Uses InMemorySpanExporter purely for assertions — production wiring
* runs via the lazy-loaded sdk-trace-web in telemetry-impl.ts.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { context, metrics, trace } from '@opentelemetry/api';
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
import {
@@ -18,6 +18,7 @@ import {
type ReadableSpan,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__coldMountSpanCount,
__resetColdMountSpans,
diff --git a/packages/app/src/lib/perf/profiler-boundary.test.tsx b/packages/app/src/lib/perf/profiler-boundary.test.tsx
index bc1c26c1a..dcc44acc6 100644
--- a/packages/app/src/lib/perf/profiler-boundary.test.tsx
+++ b/packages/app/src/lib/perf/profiler-boundary.test.tsx
@@ -1,5 +1,5 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { beforeEach, describe, expect, test } from 'vitest';
import { getCollector } from './collector';
import { ProfilerBoundary } from './profiler-boundary';
diff --git a/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts b/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts
index 96af06890..4e4d00779 100644
--- a/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts
+++ b/packages/app/src/lib/perf/scheduler-polyfill-shim.test.ts
@@ -8,7 +8,7 @@
// './scheduler-polyfill-shim'`, the consumer (mount-promise.ts at the
// construction-mount yield-point) sees a callable `scheduler.yield()`.
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import './scheduler-polyfill-shim';
describe('scheduler-polyfill-shim install side-effect', () => {
diff --git a/packages/app/src/lib/perf/startup-marks.test.ts b/packages/app/src/lib/perf/startup-marks.test.ts
index d6d014ce9..2c6f89ba1 100644
--- a/packages/app/src/lib/perf/startup-marks.test.ts
+++ b/packages/app/src/lib/perf/startup-marks.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetStartupMarksForTest,
firstContent,
diff --git a/packages/app/src/lib/perf/web-vitals.test.ts b/packages/app/src/lib/perf/web-vitals.test.ts
index ffd844553..b14d0cec4 100644
--- a/packages/app/src/lib/perf/web-vitals.test.ts
+++ b/packages/app/src/lib/perf/web-vitals.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { getCollector } from './collector';
import { __resetWebVitalsForTests, initWebVitals } from './web-vitals';
diff --git a/packages/app/src/lib/preferred-agent-store.test.ts b/packages/app/src/lib/preferred-agent-store.test.ts
index 4a2cf8bf0..ab78e4bb8 100644
--- a/packages/app/src/lib/preferred-agent-store.test.ts
+++ b/packages/app/src/lib/preferred-agent-store.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
PREFERRED_AGENT_KEY,
type PreferredAgentStorage,
diff --git a/packages/app/src/lib/project-paths.test.ts b/packages/app/src/lib/project-paths.test.ts
index 13d5c8f4a..7190afa8e 100644
--- a/packages/app/src/lib/project-paths.test.ts
+++ b/packages/app/src/lib/project-paths.test.ts
@@ -1,7 +1,7 @@
/**
* Behavioral coverage for the two pure path helpers.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isContentDirSafe, relativeToProject } from './project-paths';
describe('isContentDirSafe', () => {
diff --git a/packages/app/src/lib/refresh-scheduler.test.ts b/packages/app/src/lib/refresh-scheduler.test.ts
index 2159535ed..e97f48e17 100644
--- a/packages/app/src/lib/refresh-scheduler.test.ts
+++ b/packages/app/src/lib/refresh-scheduler.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { setImmediate } from 'node:timers/promises';
+import { describe, expect, test } from 'vitest';
import { createRefreshScheduler } from './refresh-scheduler';
describe('createRefreshScheduler', () => {
diff --git a/packages/app/src/lib/relaunch-store.test.ts b/packages/app/src/lib/relaunch-store.test.ts
index a2aae1652..dae850c23 100644
--- a/packages/app/src/lib/relaunch-store.test.ts
+++ b/packages/app/src/lib/relaunch-store.test.ts
@@ -1,11 +1,10 @@
/**
* Runtime guards for `relaunch-store.ts`. The store is a module-level
* singleton, so this file owns one fake `window.okDesktop` bridge and avoids
- * `mock.module(...)` (Bun module mocks are process-global and can leak into
- * later module-load tests). Mirrors `update-notices-store.test.ts`.
+ * module mocking. Mirrors `update-notices-store.test.ts`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
const store = await import('./relaunch-store');
@@ -16,14 +15,14 @@ function makeBridge() {
let relaunching: RelaunchingCb = () => {};
let relaunchFailed: RelaunchFailedCb = () => {};
const bridge = {
- onUpdateRelaunching: mock((cb: RelaunchingCb) => {
+ onUpdateRelaunching: vi.fn((cb: RelaunchingCb) => {
relaunching = cb;
// Real unsubscribe: detach severs the callback so later fires are no-ops.
return () => {
relaunching = () => {};
};
}),
- onUpdateRelaunchFailed: mock((cb: RelaunchFailedCb) => {
+ onUpdateRelaunchFailed: vi.fn((cb: RelaunchFailedCb) => {
relaunchFailed = cb;
return () => {
relaunchFailed = () => {};
diff --git a/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts b/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts
index 5892228b4..bcbb17841 100644
--- a/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts
+++ b/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts
@@ -5,9 +5,9 @@
* asserts the resulting block/mark ranges.
*/
-import { describe, expect, test } from 'bun:test';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import {
buildRenderedDiff,
RENDERED_DIFF_SIZE_CEILING,
diff --git a/packages/app/src/lib/restart-collab-server.test.ts b/packages/app/src/lib/restart-collab-server.test.ts
index 40523876d..a1fb0b359 100644
--- a/packages/app/src/lib/restart-collab-server.test.ts
+++ b/packages/app/src/lib/restart-collab-server.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { restartCollabServer, restartServerFailureMessage } from './restart-collab-server';
@@ -19,9 +19,9 @@ describe('restartServerFailureMessage', () => {
describe('restartCollabServer', () => {
function makeBridge(outcome: Awaited<ReturnType<OkDesktopBridge['restartServer']>>): {
bridge: Pick<OkDesktopBridge, 'restartServer' | 'config'>;
- restartServer: ReturnType<typeof mock>;
+ restartServer: ReturnType<typeof vi.fn>;
} {
- const restartServer = mock(async () => outcome);
+ const restartServer = vi.fn(async () => outcome);
return {
bridge: {
restartServer,
diff --git a/packages/app/src/lib/self-scheduling-poll.test.ts b/packages/app/src/lib/self-scheduling-poll.test.ts
index a7ef3b92b..96401986d 100644
--- a/packages/app/src/lib/self-scheduling-poll.test.ts
+++ b/packages/app/src/lib/self-scheduling-poll.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createSelfSchedulingPoll, type PollOutcome } from './self-scheduling-poll.ts';
// Injectable fake timer — records scheduled callbacks; `runPending` fires the
diff --git a/packages/app/src/lib/server-info-refresh.test.ts b/packages/app/src/lib/server-info-refresh.test.ts
index 0ad0c02db..e45c27a0e 100644
--- a/packages/app/src/lib/server-info-refresh.test.ts
+++ b/packages/app/src/lib/server-info-refresh.test.ts
@@ -17,7 +17,7 @@
* directly.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createSyncedReconnectGate } from './server-info-refresh';
describe('createSyncedReconnectGate', () => {
diff --git a/packages/app/src/lib/server-instance-store.test.ts b/packages/app/src/lib/server-instance-store.test.ts
index bcdb462d2..15ec7b097 100644
--- a/packages/app/src/lib/server-instance-store.test.ts
+++ b/packages/app/src/lib/server-instance-store.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetServerInstanceStoreForTests,
getServerInstanceId,
diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.ts
index e734964b4..6a89f38bd 100644
--- a/packages/app/src/lib/share/branch-switch-flow.test.ts
+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts
@@ -1,6 +1,5 @@
-import { describe, expect, test } from 'bun:test';
-
import { type BranchInfoResponse, BranchInfoResponseSchema } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
applyBranchInfo,
diff --git a/packages/app/src/lib/share/clipboard-adapter.test.ts b/packages/app/src/lib/share/clipboard-adapter.test.ts
index 2e39583e3..a47565411 100644
--- a/packages/app/src/lib/share/clipboard-adapter.test.ts
+++ b/packages/app/src/lib/share/clipboard-adapter.test.ts
@@ -3,7 +3,7 @@
* `navigator.clipboard.writeText` fallback.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { isPermissionsPolicyRefusal, scheduleClipboardWrite } from './clipboard-adapter';
interface MockableGlobals {
@@ -72,7 +72,7 @@ describe('scheduleClipboardWrite — Electron IPC bridge path (preferred when av
});
test('does NOT touch navigator.clipboard when okDesktop bridge is available', async () => {
- const navWriteText = mock(async () => undefined);
+ const navWriteText = vi.fn(async () => undefined);
setGlobals({
windowOkDesktop: {
clipboard: { writeText: async () => undefined },
diff --git a/packages/app/src/lib/share/clone-controller.test.ts b/packages/app/src/lib/share/clone-controller.test.ts
index c086a2f52..8b31eff41 100644
--- a/packages/app/src/lib/share/clone-controller.test.ts
+++ b/packages/app/src/lib/share/clone-controller.test.ts
@@ -7,47 +7,44 @@
* the raw git message as `detail` for the dialog to render.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualSonner from 'sonner';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkLocalOpCloneEvent } from '@/lib/desktop-bridge-types';
const toast = {
- loading: mock((_message: string, _opts?: unknown) => 'toast-id'),
- success: mock((_message: string, _opts?: unknown) => {}),
- error: mock((_message: string, _opts?: unknown) => {}),
- info: mock((_message: string, _opts?: unknown) => {}),
- dismiss: mock((_id?: unknown) => {}),
+ loading: vi.fn((_message: string, _opts?: unknown) => 'toast-id'),
+ success: vi.fn((_message: string, _opts?: unknown) => {}),
+ error: vi.fn((_message: string, _opts?: unknown) => {}),
+ info: vi.fn((_message: string, _opts?: unknown) => {}),
+ dismiss: vi.fn((_id?: unknown) => {}),
};
-// Spread the real module so unmocked sonner exports stay bound for any test
-// file that loads after this one in the shared bun-test process.
-mock.module('sonner', () => ({ ...actualSonner, toast }));
+// Spread the real module so unmocked sonner exports remain available in this
+// test's module graph.
+vi.doMock('sonner', () => ({ ...actualSonner, toast }));
-// NOTE: do not mock.module('@lingui/core/macro') here. bunfig's `[test] preload`
-// (tests/lingui-macro-preload.ts) already shims the macro to an English
-// passthrough for the whole process. A per-file mock.module override leaks into
-// every test file that runs after this one in the shared `bun test` process and
-// breaks their `t`-derived assertions (e.g. component-items.test.ts).
+// The Vitest config already aliases Lingui macros to the English passthrough;
+// keep this test on that shared resolver contract.
type CloneEvent = OkLocalOpCloneEvent | { type: 'complete'; port: number; dir: string };
function makeDeps(events: CloneEvent[]) {
return {
bridge: {
- dialog: { openFolder: mock(() => Promise.resolve('/parent')) },
+ dialog: { openFolder: vi.fn(() => Promise.resolve('/parent')) },
},
authQueryTransport: {
- status: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ status: vi.fn(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
},
cloneTransport: {
- start: mock(() => ({
+ start: vi.fn(() => ({
events: (async function* () {
for (const event of events) yield event;
})(),
cancel: () => {},
})),
},
- openSignIn: mock(() => Promise.resolve(null)),
+ openSignIn: vi.fn(() => Promise.resolve(null)),
};
}
@@ -74,7 +71,7 @@ describe('createCloneController().runClone failure handling', () => {
test('cancelled folder picker returns cancelled without starting a clone', async () => {
const { createCloneController } = await import('./clone-controller');
const deps = makeDeps([]);
- deps.bridge.dialog.openFolder = mock(() => Promise.resolve(null));
+ deps.bridge.dialog.openFolder = vi.fn(() => Promise.resolve(null));
const controller = createCloneController(deps as never);
const result = await controller.runClone({ url: 'https://github.com/o/r.git' });
@@ -110,7 +107,7 @@ describe('createCloneController().runClone failure handling', () => {
const deps = {
...makeDeps([]),
cloneTransport: {
- start: mock(() => ({
+ start: vi.fn(() => ({
// Async iterable whose first .next() rejects — models a transport
// whose stream throws instead of emitting a typed error event. (Not a
// generator: a generator with only a throw trips biome's useYield.)
@@ -137,7 +134,7 @@ describe('createCloneController().runClone failure handling', () => {
const deps = {
...makeDeps([]),
cloneTransport: {
- start: mock(() => {
+ start: vi.fn(() => {
throw new Error('clone IPC handler not registered');
}),
},
diff --git a/packages/app/src/lib/share/consent-flow.test.ts b/packages/app/src/lib/share/consent-flow.test.ts
index 4b48f99bb..d48da7ea1 100644
--- a/packages/app/src/lib/share/consent-flow.test.ts
+++ b/packages/app/src/lib/share/consent-flow.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
applyOkInitOutcome,
applyOpenOutcome,
diff --git a/packages/app/src/lib/share/pending-receive-nav-store.test.ts b/packages/app/src/lib/share/pending-receive-nav-store.test.ts
index e443d520e..36be73b55 100644
--- a/packages/app/src/lib/share/pending-receive-nav-store.test.ts
+++ b/packages/app/src/lib/share/pending-receive-nav-store.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { ResolvedNavigationTarget } from '@/components/navigation-targets';
import {
createPendingReceiveNavStore,
diff --git a/packages/app/src/lib/share/publish-wizard.test.ts b/packages/app/src/lib/share/publish-wizard.test.ts
index 0538fb172..ce6a2a1a7 100644
--- a/packages/app/src/lib/share/publish-wizard.test.ts
+++ b/packages/app/src/lib/share/publish-wizard.test.ts
@@ -6,8 +6,8 @@
* and the `share/publish.test.ts` shape.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { SharePublishOwner } from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import {
buildSamlSsoAuthorizeUrl,
canSubmitPublish,
@@ -147,7 +147,7 @@ describe('presentPublishError', () => {
describe('fetchPublishOwners', () => {
test('parses a happy-path body and returns owners array', async () => {
- const fakeFetch = mock(async () =>
+ const fakeFetch = vi.fn(async () =>
makeJsonResponse({
ok: true,
owners: [
@@ -170,7 +170,7 @@ describe('fetchPublishOwners', () => {
});
test('parses an auth-required error body', async () => {
- const fakeFetch = mock(async () =>
+ const fakeFetch = vi.fn(async () =>
makeJsonResponse({ ok: false, error: 'auth-required' }),
) as unknown as typeof fetch;
@@ -179,13 +179,13 @@ describe('fetchPublishOwners', () => {
});
test('throws on non-2xx transport status', async () => {
- const fakeFetch = mock(async () => makeJsonResponse({}, 500)) as unknown as typeof fetch;
+ const fakeFetch = vi.fn(async () => makeJsonResponse({}, 500)) as unknown as typeof fetch;
await expect(fetchPublishOwners(fakeFetch)).rejects.toThrow('owners transport 500');
});
test('throws on response shape mismatch', async () => {
- const fakeFetch = mock(async () =>
+ const fakeFetch = vi.fn(async () =>
makeJsonResponse({ ok: true, owners: 'not-an-array' }),
) as unknown as typeof fetch;
@@ -196,7 +196,7 @@ describe('fetchPublishOwners', () => {
describe('fetchPublishNameCheck', () => {
test('builds URL with URL-encoded query params and returns body', async () => {
let capturedUrl: string | null = null;
- const fakeFetch = mock(async (url: string) => {
+ const fakeFetch = vi.fn(async (url: string) => {
capturedUrl = url;
return makeJsonResponse({ ok: true, available: true });
}) as unknown as typeof fetch;
@@ -207,7 +207,7 @@ describe('fetchPublishNameCheck', () => {
});
test('parses taken response', async () => {
- const fakeFetch = mock(async () =>
+ const fakeFetch = vi.fn(async () =>
makeJsonResponse({ ok: true, available: false }),
) as unknown as typeof fetch;
@@ -216,7 +216,7 @@ describe('fetchPublishNameCheck', () => {
});
test('throws on non-2xx transport status', async () => {
- const fakeFetch = mock(async () => makeJsonResponse({}, 503)) as unknown as typeof fetch;
+ const fakeFetch = vi.fn(async () => makeJsonResponse({}, 503)) as unknown as typeof fetch;
await expect(fetchPublishNameCheck('me', 'x', fakeFetch)).rejects.toThrow(
'name-check transport 503',
@@ -326,7 +326,7 @@ describe('canSubmitPublish', () => {
describe('submitPublishRequest', () => {
test('POSTs JSON body and returns happy-path response', async () => {
let capturedInit: RequestInit | undefined;
- const fakeFetch = mock(async (_url: string, init?: RequestInit) => {
+ const fakeFetch = vi.fn(async (_url: string, init?: RequestInit) => {
capturedInit = init;
return makeJsonResponse({
ok: true,
@@ -370,7 +370,7 @@ describe('submitPublishRequest', () => {
'no-project',
] as const;
for (const error of codes) {
- const fakeFetch = mock(async () =>
+ const fakeFetch = vi.fn(async () =>
makeJsonResponse({ ok: false, error }),
) as unknown as typeof fetch;
@@ -387,7 +387,7 @@ describe('submitPublishRequest', () => {
});
test('throws on non-2xx transport status', async () => {
- const fakeFetch = mock(async () => makeJsonResponse({}, 502)) as unknown as typeof fetch;
+ const fakeFetch = vi.fn(async () => makeJsonResponse({}, 502)) as unknown as typeof fetch;
await expect(
submitPublishRequest({ owner: 'me', name: 'x', visibility: 'private' }, fakeFetch),
@@ -395,7 +395,7 @@ describe('submitPublishRequest', () => {
});
test('throws on response shape mismatch', async () => {
- const fakeFetch = mock(async () =>
+ const fakeFetch = vi.fn(async () =>
makeJsonResponse({ ok: true /* missing other fields */ }),
) as unknown as typeof fetch;
diff --git a/packages/app/src/lib/share/receive-store.test.ts b/packages/app/src/lib/share/receive-store.test.ts
index 87b3ba58b..6f2b49da4 100644
--- a/packages/app/src/lib/share/receive-store.test.ts
+++ b/packages/app/src/lib/share/receive-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge, OkShareReceivedPayload } from '@/lib/desktop-bridge-types';
@@ -66,7 +66,7 @@ describe('createShareReceiveStore — payload delivery', () => {
const fb = fakeBridge();
const store = createShareReceiveStore();
store.install({ bridge: fb.bridge });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
fb.emit(sharePayload);
expect(store.getSnapshot()).toEqual(sharePayload);
@@ -86,8 +86,8 @@ describe('createShareReceiveStore — payload delivery', () => {
const fb = fakeBridge();
const store = createShareReceiveStore();
store.install({ bridge: fb.bridge });
- const a = mock(() => {});
- const b = mock(() => {});
+ const a = vi.fn(() => {});
+ const b = vi.fn(() => {});
store.subscribe(a);
store.subscribe(b);
fb.emit(sharePayload);
@@ -99,7 +99,7 @@ describe('createShareReceiveStore — payload delivery', () => {
const fb = fakeBridge();
const store = createShareReceiveStore();
store.install({ bridge: fb.bridge });
- const a = mock(() => {});
+ const a = vi.fn(() => {});
const unsub = store.subscribe(a);
unsub();
fb.emit(sharePayload);
@@ -113,7 +113,7 @@ describe('createShareReceiveStore — dismiss', () => {
const store = createShareReceiveStore();
store.install({ bridge: fb.bridge });
fb.emit(sharePayload);
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
store.dismiss();
expect(store.getSnapshot()).toBeNull();
@@ -124,7 +124,7 @@ describe('createShareReceiveStore — dismiss', () => {
const fb = fakeBridge();
const store = createShareReceiveStore();
store.install({ bridge: fb.bridge });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
store.dismiss();
expect(listener).toHaveBeenCalledTimes(0);
diff --git a/packages/app/src/lib/share/run-share-action.test.ts b/packages/app/src/lib/share/run-share-action.test.ts
index f41de9f56..a24b2e159 100644
--- a/packages/app/src/lib/share/run-share-action.test.ts
+++ b/packages/app/src/lib/share/run-share-action.test.ts
@@ -6,11 +6,11 @@
* suite exercises the full decision tree without spinning up React.
*/
-import { describe, expect, test } from 'bun:test';
import type {
ShareConstructUrlErrorCode,
ShareConstructUrlResponse,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { mapShareErrorToToast, requestShareConstructUrl, runShareAction } from './run-share-action';
interface MockDeps {
diff --git a/packages/app/src/lib/show-all-stream.test.ts b/packages/app/src/lib/show-all-stream.test.ts
index 4ebdaad90..5abc64b34 100644
--- a/packages/app/src/lib/show-all-stream.test.ts
+++ b/packages/app/src/lib/show-all-stream.test.ts
@@ -7,7 +7,7 @@
* without sinking the listing. `isNdjsonResponse` gates streaming vs the
* buffered JSON fallback.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
consumeShowAllStream,
isNdjsonResponse,
diff --git a/packages/app/src/lib/sidebar-drag.test.ts b/packages/app/src/lib/sidebar-drag.test.ts
index 8f34dc16c..98df6e965 100644
--- a/packages/app/src/lib/sidebar-drag.test.ts
+++ b/packages/app/src/lib/sidebar-drag.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
navigationForSidebarDragPayload,
OK_SIDEBAR_DRAG_MIME,
diff --git a/packages/app/src/lib/sidebar-partition.test.ts b/packages/app/src/lib/sidebar-partition.test.ts
index 1b1ba6d3b..7dec7db3d 100644
--- a/packages/app/src/lib/sidebar-partition.test.ts
+++ b/packages/app/src/lib/sidebar-partition.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
LEFT_COLLAPSE_THRESHOLD,
RIGHT_COLLAPSE_THRESHOLD,
diff --git a/packages/app/src/lib/sidebar-pin-store.test.ts b/packages/app/src/lib/sidebar-pin-store.test.ts
index bda98d084..6bb762a92 100644
--- a/packages/app/src/lib/sidebar-pin-store.test.ts
+++ b/packages/app/src/lib/sidebar-pin-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
applyToggle,
type PinStorage,
diff --git a/packages/app/src/lib/single-file-initial-doc.test.ts b/packages/app/src/lib/single-file-initial-doc.test.ts
index b52936b17..dcadaba3f 100644
--- a/packages/app/src/lib/single-file-initial-doc.test.ts
+++ b/packages/app/src/lib/single-file-initial-doc.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { seedInitialDocHash, seedInitialDocHashFromWindow } from './single-file-initial-doc';
/**
diff --git a/packages/app/src/lib/single-file-mode.dom.test.tsx b/packages/app/src/lib/single-file-mode.dom.test.tsx
index 641ac40ce..ff408dda1 100644
--- a/packages/app/src/lib/single-file-mode.dom.test.tsx
+++ b/packages/app/src/lib/single-file-mode.dom.test.tsx
@@ -9,8 +9,9 @@
* Runs under `bun run test:dom` (jsdom). Asserts rendered DOM (a probe shows the
* resolved boolean), never source text.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { SingleFileModeProvider, useSingleFileMode } from './single-file-mode.tsx';
function Probe() {
@@ -22,7 +23,7 @@ const originalDesktop = (globalThis as { window?: { okDesktop?: unknown } }).win
afterEach(() => {
cleanup();
- mock.restore();
+ vi.restoreAllMocks();
// Restore any okDesktop we stubbed so cross-test state doesn't leak.
if (typeof window !== 'undefined') {
(window as { okDesktop?: unknown }).okDesktop = originalDesktop;
@@ -44,7 +45,7 @@ describe('SingleFileModeProvider — desktop bridge channel', () => {
});
test('reads singleFile synchronously from the bridge config (no fetch)', () => {
- const fetchSpy = spyOn(globalThis, 'fetch');
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
render(
<SingleFileModeProvider>
<Probe />
@@ -62,7 +63,7 @@ describe('SingleFileModeProvider — browser /api/config channel', () => {
});
test('resolves singleFile:true from /api/config', async () => {
- spyOn(globalThis, 'fetch').mockResolvedValue(
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({
collabUrl: null,
@@ -87,7 +88,7 @@ describe('SingleFileModeProvider — browser /api/config channel', () => {
});
test('stays project mode when /api/config reports singleFile:false', async () => {
- spyOn(globalThis, 'fetch').mockResolvedValue(
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({
collabUrl: null,
@@ -111,7 +112,7 @@ describe('SingleFileModeProvider — browser /api/config channel', () => {
});
test('a /api/config error leaves project mode (no chrome stripped on a flaky endpoint)', async () => {
- spyOn(globalThis, 'fetch').mockResolvedValue(new Response('nope', { status: 500 }));
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('nope', { status: 500 }));
render(
<SingleFileModeProvider>
<Probe />
diff --git a/packages/app/src/lib/subscribe-card-store.test.ts b/packages/app/src/lib/subscribe-card-store.test.ts
index 5c04c5a94..3e3776d96 100644
--- a/packages/app/src/lib/subscribe-card-store.test.ts
+++ b/packages/app/src/lib/subscribe-card-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createSubscribeCardStore,
DEFAULT_SUBSCRIBE_CARD_STATE,
diff --git a/packages/app/src/lib/terminal-dock-store.test.ts b/packages/app/src/lib/terminal-dock-store.test.ts
index 8a8b8e0b4..a2f4eeff1 100644
--- a/packages/app/src/lib/terminal-dock-store.test.ts
+++ b/packages/app/src/lib/terminal-dock-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
DEFAULT_TERMINAL_DOCK,
type DockStorage,
diff --git a/packages/app/src/lib/terminal-height-store.test.ts b/packages/app/src/lib/terminal-height-store.test.ts
index a78df4ea1..a6dfccddb 100644
--- a/packages/app/src/lib/terminal-height-store.test.ts
+++ b/packages/app/src/lib/terminal-height-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
DEFAULT_TERMINAL_HEIGHT,
type HeightStorage,
diff --git a/packages/app/src/lib/terminal-new-tab-store.test.ts b/packages/app/src/lib/terminal-new-tab-store.test.ts
index 70bad064d..23b4b1922 100644
--- a/packages/app/src/lib/terminal-new-tab-store.test.ts
+++ b/packages/app/src/lib/terminal-new-tab-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
readPreferBareTerminal,
TERMINAL_NEW_TAB_BARE_KEY,
diff --git a/packages/app/src/lib/terminal-telemetry.test.ts b/packages/app/src/lib/terminal-telemetry.test.ts
index b852d8f14..8d7524fe7 100644
--- a/packages/app/src/lib/terminal-telemetry.test.ts
+++ b/packages/app/src/lib/terminal-telemetry.test.ts
@@ -6,13 +6,14 @@
* surface as a UI crash.
*
* The OTel boundary is faked with `spyOn(trace, 'getTracer')` rather than
- * `mock.module('@opentelemetry/api')`: a module mock persists in the shared
+ * `vi.doMock('@opentelemetry/api')`: a module mock persists in the shared
* unit-test module registry and would clobber the real provider that
* `lib/perf/otel-spans.test.ts` registers. The spy is installed per-test and
* restored in `afterEach`, so nothing bleeds into another file's tracer.
*/
-import { afterEach, beforeEach, describe, expect, type Mock, spyOn, test } from 'bun:test';
+
import { type Tracer, trace } from '@opentelemetry/api';
+import { afterEach, beforeEach, describe, expect, type Mock, test, vi } from 'vitest';
import { recordShellConsentGranted, recordTerminalOpened } from './terminal-telemetry';
const spanNames: string[] = [];
@@ -22,7 +23,7 @@ let getTracerSpy: Mock<typeof trace.getTracer>;
beforeEach(() => {
spanNames.length = 0;
startSpanThrows = false;
- getTracerSpy = spyOn(trace, 'getTracer').mockImplementation(
+ getTracerSpy = vi.spyOn(trace, 'getTracer').mockImplementation(
() =>
({
startSpan: (name: string) => {
diff --git a/packages/app/src/lib/terminal-width-store.test.ts b/packages/app/src/lib/terminal-width-store.test.ts
index debdaedfb..fedea51c1 100644
--- a/packages/app/src/lib/terminal-width-store.test.ts
+++ b/packages/app/src/lib/terminal-width-store.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
DEFAULT_TERMINAL_WIDTH,
MIN_TERMINAL_WIDTH,
diff --git a/packages/app/src/lib/transports/buffered-async-stream.test.ts b/packages/app/src/lib/transports/buffered-async-stream.test.ts
index 76264ad25..8d184fb6a 100644
--- a/packages/app/src/lib/transports/buffered-async-stream.test.ts
+++ b/packages/app/src/lib/transports/buffered-async-stream.test.ts
@@ -4,7 +4,7 @@
* producer (waiter), terminal-event-aborts-signal, external-cancel-aborts-
* signal, and idempotent cancel.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createBufferedAsyncStream } from './buffered-async-stream';
type TestEvent =
diff --git a/packages/app/src/lib/transports/clone-transport.test.ts b/packages/app/src/lib/transports/clone-transport.test.ts
index 861a02080..57d2e5613 100644
--- a/packages/app/src/lib/transports/clone-transport.test.ts
+++ b/packages/app/src/lib/transports/clone-transport.test.ts
@@ -12,7 +12,7 @@
* Without this symmetry, opening a share link
* in the Navigator silently drops branch + the fallback signal.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { OkDesktopBridge, OkLocalOpCloneEvent } from '@/lib/desktop-bridge-types';
import { ipcCloneTransport } from './clone-transport';
diff --git a/packages/app/src/lib/update-notices-store.test.ts b/packages/app/src/lib/update-notices-store.test.ts
index 8b811904e..a6149e5bd 100644
--- a/packages/app/src/lib/update-notices-store.test.ts
+++ b/packages/app/src/lib/update-notices-store.test.ts
@@ -1,11 +1,10 @@
/**
* Runtime guards for `update-notices-store.ts`. The store is a module-level
* singleton, so this file owns one fake `window.okDesktop` bridge and avoids
- * `mock.module(...)` entirely. Bun module mocks are process-global and can
- * leak into later module-load tests.
+ * module mocking entirely.
*/
-import { afterAll, describe, expect, mock, test } from 'bun:test';
+import { afterAll, describe, expect, test, vi } from 'vitest';
const store = await import('./update-notices-store');
@@ -16,7 +15,7 @@ afterAll(() => {
describe('update-notices-store install-time runtime wiring', () => {
test('installs subscribers once and surfaces boot schema-incompatibility state through the store', async () => {
- const queryMock = mock(() =>
+ const queryMock = vi.fn(() =>
Promise.resolve({
channel: 'latest',
schemaIncompatibility: {
@@ -26,28 +25,28 @@ describe('update-notices-store install-time runtime wiring', () => {
},
}),
);
- const downloadedUnsub = mock(() => {});
- const relaunchingUnsub = mock(() => {});
- const relaunchFailedUnsub = mock(() => {});
- const whatsNewUnsub = mock(() => {});
- const whatsNewDismissedUnsub = mock(() => {});
- const stuckHintUnsub = mock(() => {});
+ const downloadedUnsub = vi.fn(() => {});
+ const relaunchingUnsub = vi.fn(() => {});
+ const relaunchFailedUnsub = vi.fn(() => {});
+ const whatsNewUnsub = vi.fn(() => {});
+ const whatsNewDismissedUnsub = vi.fn(() => {});
+ const stuckHintUnsub = vi.fn(() => {});
const bridge = {
- onUpdateDownloaded: mock(() => downloadedUnsub),
- onUpdateRelaunching: mock(() => relaunchingUnsub),
- onUpdateRelaunchFailed: mock(() => relaunchFailedUnsub),
- onWhatsNew: mock(() => whatsNewUnsub),
- onWhatsNewDismissed: mock(() => whatsNewDismissedUnsub),
- onUpdateStuckHint: mock(() => stuckHintUnsub),
+ onUpdateDownloaded: vi.fn(() => downloadedUnsub),
+ onUpdateRelaunching: vi.fn(() => relaunchingUnsub),
+ onUpdateRelaunchFailed: vi.fn(() => relaunchFailedUnsub),
+ onWhatsNew: vi.fn(() => whatsNewUnsub),
+ onWhatsNewDismissed: vi.fn(() => whatsNewDismissedUnsub),
+ onUpdateStuckHint: vi.fn(() => stuckHintUnsub),
update: {
- relaunchNow: mock(() => Promise.resolve(undefined)),
- dismissWhatsNew: mock(() => Promise.resolve(undefined)),
+ relaunchNow: vi.fn(() => Promise.resolve(undefined)),
+ dismissWhatsNew: vi.fn(() => Promise.resolve(undefined)),
},
state: {
query: queryMock,
- resetIncompatible: mock(() => Promise.resolve(undefined)),
+ resetIncompatible: vi.fn(() => Promise.resolve(undefined)),
},
- shell: { openExternal: mock(() => Promise.resolve(undefined)) },
+ shell: { openExternal: vi.fn(() => Promise.resolve(undefined)) },
};
const testWindow = {} as Window & typeof globalThis;
Object.defineProperty(globalThis, 'window', {
diff --git a/packages/app/src/lib/use-activity-panel.test.ts b/packages/app/src/lib/use-activity-panel.test.ts
index 8595b32e0..ecbcf66c6 100644
--- a/packages/app/src/lib/use-activity-panel.test.ts
+++ b/packages/app/src/lib/use-activity-panel.test.ts
@@ -9,8 +9,8 @@
* prefix-normalization and presence-shape filtering.
*/
-import { describe, expect, test } from 'bun:test';
import type { AgentPresenceEntry } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { computeWritingDocs } from './use-activity-panel';
type AgentPresenceMap = Record<string, AgentPresenceEntry>;
diff --git a/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx b/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx
index db956171a..626bedf04 100644
--- a/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx
+++ b/packages/app/src/lib/use-apply-config-color-theme.dom.test.tsx
@@ -1,5 +1,5 @@
-import { afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
+import { afterEach, beforeAll, describe, expect, test } from 'vitest';
import {
applyColorThemeToDom,
COLOR_THEME_ATTRIBUTE,
diff --git a/packages/app/src/lib/use-apply-config-theme.dom.test.tsx b/packages/app/src/lib/use-apply-config-theme.dom.test.tsx
index 039ef96b1..0c7b7cc68 100644
--- a/packages/app/src/lib/use-apply-config-theme.dom.test.tsx
+++ b/packages/app/src/lib/use-apply-config-theme.dom.test.tsx
@@ -10,10 +10,11 @@
* `localStorage`; the preload only puts it on `window`, so each test exposes it
* globally to exercise the cross-window channel faithfully.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { act, cleanup, render } from '@testing-library/react';
import { ThemeProvider } from 'next-themes';
import type { ReactElement } from 'react';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { useApplyConfigTheme } from './use-apply-config-theme';
function ConfigThemeHarness({ themeValue }: { themeValue: string | undefined }) {
diff --git a/packages/app/src/lib/use-collab-url.test.ts b/packages/app/src/lib/use-collab-url.test.ts
index 26aa1de69..997ad87be 100644
--- a/packages/app/src/lib/use-collab-url.test.ts
+++ b/packages/app/src/lib/use-collab-url.test.ts
@@ -14,8 +14,9 @@
* Uses a manual scheduler + virtual clock (same pattern as idle-shutdown
* and ui safety-net) so tests are deterministic — no real wall-clock waits.
*/
-import { describe, expect, test } from 'bun:test';
+
import { setTimeout as wait } from 'node:timers/promises';
+import { describe, expect, test } from 'vitest';
import type { FetchApiConfigResult } from './api-config';
import { runCollabUrlPoll, TERMINAL_AFTER_MS } from './use-collab-url';
diff --git a/packages/app/src/lib/use-server-keepalive.dom.test.tsx b/packages/app/src/lib/use-server-keepalive.dom.test.tsx
index 7eae570bf..16ef5a854 100644
--- a/packages/app/src/lib/use-server-keepalive.dom.test.tsx
+++ b/packages/app/src/lib/use-server-keepalive.dom.test.tsx
@@ -6,9 +6,10 @@
* discipline: we assert what the hook does (start/skip/close, resolver output),
* never its source text.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import type { KeepaliveHandle, KeepaliveOptions } from '@inkeep/open-knowledge-core/keepalive';
import { act, cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import { type UseServerKeepaliveOptions, useServerKeepalive } from './use-server-keepalive';
const ASYNC_EFFECT_TIMEOUT_MS = 1000;
diff --git a/packages/app/src/lib/use-server-keepalive.test.ts b/packages/app/src/lib/use-server-keepalive.test.ts
index baafb691b..792fd1374 100644
--- a/packages/app/src/lib/use-server-keepalive.test.ts
+++ b/packages/app/src/lib/use-server-keepalive.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { keepaliveBaseFromCollabUrl } from './use-server-keepalive';
describe('keepaliveBaseFromCollabUrl', () => {
diff --git a/packages/app/src/lib/use-settings-route.dom.test.tsx b/packages/app/src/lib/use-settings-route.dom.test.tsx
index f7824d49d..b2233519a 100644
--- a/packages/app/src/lib/use-settings-route.dom.test.tsx
+++ b/packages/app/src/lib/use-settings-route.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import * as React from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
const realStartTransition = React.startTransition;
-const startTransitionMock = mock((callback: React.TransitionFunction) => {
+const startTransitionMock = vi.fn((callback: React.TransitionFunction) => {
realStartTransition(callback);
});
-mock.module('react', () => ({
+vi.doMock('react', () => ({
...React,
startTransition: startTransitionMock,
}));
diff --git a/packages/app/src/lib/use-timeline-entry-diff.test.ts b/packages/app/src/lib/use-timeline-entry-diff.test.ts
index 9ff14c349..6fc267e1a 100644
--- a/packages/app/src/lib/use-timeline-entry-diff.test.ts
+++ b/packages/app/src/lib/use-timeline-entry-diff.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeTimelineDiff, timelineEntryCacheKey } from './use-timeline-entry-diff';
describe('timelineEntryCacheKey', () => {
diff --git a/packages/app/src/lib/use-workspace.test.ts b/packages/app/src/lib/use-workspace.test.ts
index 597e1ff72..194daeb77 100644
--- a/packages/app/src/lib/use-workspace.test.ts
+++ b/packages/app/src/lib/use-workspace.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveSyncWorkspace } from './use-workspace';
describe('resolveSyncWorkspace', () => {
diff --git a/packages/app/src/lib/view-menu-state-store.dom.test.tsx b/packages/app/src/lib/view-menu-state-store.dom.test.tsx
index 0bac87da1..ca47330b0 100644
--- a/packages/app/src/lib/view-menu-state-store.dom.test.tsx
+++ b/packages/app/src/lib/view-menu-state-store.dom.test.tsx
@@ -1,5 +1,5 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { act, cleanup, renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetViewMenuStateForTests,
setViewMenuState,
diff --git a/packages/app/src/lib/workspace-paths.test.ts b/packages/app/src/lib/workspace-paths.test.ts
index a93f3176d..ae8797a26 100644
--- a/packages/app/src/lib/workspace-paths.test.ts
+++ b/packages/app/src/lib/workspace-paths.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { docNameToRelativePath, joinWorkspacePath } from './workspace-paths';
describe('joinWorkspacePath', () => {
diff --git a/packages/app/src/lib/worktree-store.test.ts b/packages/app/src/lib/worktree-store.test.ts
index 98298554f..35fb57088 100644
--- a/packages/app/src/lib/worktree-store.test.ts
+++ b/packages/app/src/lib/worktree-store.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, mock, test } from 'bun:test';
import type { WorktreeSelectorModel } from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import { createWorktreeStore } from './worktree-store.ts';
function model(mainRoot: string): WorktreeSelectorModel {
@@ -10,7 +10,7 @@ const flush = () => new Promise((r) => setTimeout(r, 0));
describe('createWorktreeStore', () => {
test('fetches once on first subscribe and caches the snapshot', async () => {
- const fetchModel = mock(() => Promise.resolve(model('/repo')));
+ const fetchModel = vi.fn(() => Promise.resolve(model('/repo')));
const store = createWorktreeStore({ fetchModel });
expect(store.getSnapshot()).toBeNull();
@@ -27,9 +27,9 @@ describe('createWorktreeStore', () => {
});
test('notifies subscribers when the model arrives', async () => {
- const fetchModel = mock(() => Promise.resolve(model('/repo')));
+ const fetchModel = vi.fn(() => Promise.resolve(model('/repo')));
const store = createWorktreeStore({ fetchModel });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
await flush();
expect(listener).toHaveBeenCalled();
@@ -37,7 +37,7 @@ describe('createWorktreeStore', () => {
test('refresh re-fetches and updates the snapshot', async () => {
let next = model('/repo');
- const fetchModel = mock(() => Promise.resolve(next));
+ const fetchModel = vi.fn(() => Promise.resolve(next));
const store = createWorktreeStore({ fetchModel });
store.subscribe(() => {});
await flush();
@@ -52,7 +52,7 @@ describe('createWorktreeStore', () => {
test('keeps the prior cache when a fetch resolves null (transient failure)', async () => {
let result: WorktreeSelectorModel | null = model('/repo');
- const fetchModel = mock(() => Promise.resolve(result));
+ const fetchModel = vi.fn(() => Promise.resolve(result));
const store = createWorktreeStore({ fetchModel });
store.subscribe(() => {});
await flush();
@@ -68,7 +68,7 @@ describe('createWorktreeStore', () => {
test('coalesces a refresh that arrives while the initial load is still in-flight', async () => {
let resolveFirst: ((m: WorktreeSelectorModel) => void) | null = null;
let call = 0;
- const fetchModel = mock(() => {
+ const fetchModel = vi.fn(() => {
call += 1;
if (call === 1) {
// Hold the bootstrap load open so refresh() lands mid-flight.
@@ -93,7 +93,7 @@ describe('createWorktreeStore', () => {
test('a rejected fetch keeps the prior snapshot', async () => {
let shouldThrow = false;
- const fetchModel = mock(() =>
+ const fetchModel = vi.fn(() =>
shouldThrow ? Promise.reject(new Error('ipc down')) : Promise.resolve(model('/repo')),
);
const store = createWorktreeStore({ fetchModel });
@@ -107,18 +107,18 @@ describe('createWorktreeStore', () => {
test('revalidation re-fetches so an out-of-band worktree surfaces without a refresh() call', async () => {
let next = model('/repo');
- const fetchModel = mock(() => Promise.resolve(next));
+ const fetchModel = vi.fn(() => Promise.resolve(next));
// Capture the store's revalidation callback so the test can fire a
// focus/visible signal by hand (no DOM).
let fireRevalidate: (() => void) | null = null;
- const subscribeRevalidate = mock((onRevalidate: () => void) => {
+ const subscribeRevalidate = vi.fn((onRevalidate: () => void) => {
fireRevalidate = onRevalidate;
return () => {
fireRevalidate = null;
};
});
const store = createWorktreeStore({ fetchModel, subscribeRevalidate });
- const listener = mock(() => {});
+ const listener = vi.fn(() => {});
store.subscribe(listener);
await flush();
expect(fetchModel).toHaveBeenCalledTimes(1);
@@ -134,10 +134,10 @@ describe('createWorktreeStore', () => {
});
test('attaches the revalidation trigger once and detaches it when the last subscriber leaves', async () => {
- const fetchModel = mock(() => Promise.resolve(model('/repo')));
+ const fetchModel = vi.fn(() => Promise.resolve(model('/repo')));
let attached = 0;
let detached = 0;
- const subscribeRevalidate = mock((_onRevalidate: () => void) => {
+ const subscribeRevalidate = vi.fn((_onRevalidate: () => void) => {
attached += 1;
return () => {
detached += 1;
@@ -164,9 +164,9 @@ describe('createWorktreeStore', () => {
});
test('re-attaches the revalidation trigger when a new subscriber arrives after the store went quiet', async () => {
- const fetchModel = mock(() => Promise.resolve(model('/repo')));
+ const fetchModel = vi.fn(() => Promise.resolve(model('/repo')));
let attached = 0;
- const subscribeRevalidate = mock((_onRevalidate: () => void) => {
+ const subscribeRevalidate = vi.fn((_onRevalidate: () => void) => {
attached += 1;
return () => {};
});
@@ -185,7 +185,7 @@ describe('createWorktreeStore', () => {
test('a revalidation firing mid-flight is coalesced into one follow-up load', async () => {
let resolveFirst: ((m: WorktreeSelectorModel) => void) | null = null;
let call = 0;
- const fetchModel = mock(() => {
+ const fetchModel = vi.fn(() => {
call += 1;
if (call === 1) {
return new Promise<WorktreeSelectorModel>((r) => {
@@ -195,7 +195,7 @@ describe('createWorktreeStore', () => {
return Promise.resolve(model('/repo-revalidated'));
});
let fireRevalidate: (() => void) | null = null;
- const subscribeRevalidate = mock((onRevalidate: () => void) => {
+ const subscribeRevalidate = vi.fn((onRevalidate: () => void) => {
fireRevalidate = onRevalidate;
return () => {};
});
diff --git a/packages/app/src/presence/PresenceBar-avatar-click.test.tsx b/packages/app/src/presence/PresenceBar-avatar-click.test.tsx
index fde0f76de..8b0ef26d4 100644
--- a/packages/app/src/presence/PresenceBar-avatar-click.test.tsx
+++ b/packages/app/src/presence/PresenceBar-avatar-click.test.tsx
@@ -3,7 +3,7 @@
*
* PresenceBar's top-level component needs DocumentContext + a real
* HocuspocusProvider to exercise, so we target AgentAvatar indirectly by
- * rendering PresenceBar with stubbed hooks via `mock.module`. Static
+ * rendering PresenceBar with stubbed hooks via `vi.doMock`. Static
* markup inspection verifies the aria-label + data attributes + the click
* event wires through to the mocked openActivityPanel.
*
@@ -11,9 +11,9 @@
* lives in Playwright.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { AgentPresenceEntry } from '@inkeep/open-knowledge-core';
import { renderToString } from 'react-dom/server';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import * as actualDocumentContext from '@/editor/DocumentContext';
import type { AgentParticipant } from './use-presence';
@@ -32,7 +32,7 @@ let crossDocAgents: AgentParticipant[] = [];
// `interactive` OR — a sentinel agent must stay clickable when a doc is open.
let mockActiveDocName: string | null = null;
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
...actualDocumentContext,
useDocumentContext: () => ({
activeProvider: null,
@@ -52,17 +52,17 @@ mock.module('@/editor/DocumentContext', () => ({
// DocumentContext factory here detonated EditorArea.test.ts's module-load
// smoke on order-unlucky CI runners; see
// tests/integration/mock-module-completeness.test.ts).
-mock.module('./use-presence', () => ({
+vi.doMock('./use-presence', () => ({
...actualUsePresence,
usePresence: () => ({ current: currentAgents, crossDoc: crossDocAgents }),
}));
-mock.module('./use-sync-status', () => ({
+vi.doMock('./use-sync-status', () => ({
...actualUseSyncStatus,
useSyncStatus: () => ({ state: 'clean' }),
}));
-mock.module('./use-sync-toasts', () => ({
+vi.doMock('./use-sync-toasts', () => ({
...actualUseSyncToasts,
useSyncToasts: () => {},
}));
diff --git a/packages/app/src/presence/PresenceBar.test.ts b/packages/app/src/presence/PresenceBar.test.ts
index b643d8639..2cf3e73bc 100644
--- a/packages/app/src/presence/PresenceBar.test.ts
+++ b/packages/app/src/presence/PresenceBar.test.ts
@@ -15,7 +15,7 @@
* this test fails.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { ANIMAL_ICON_NAMES, pickHumanAvatarKind, WRITING_PULSE_MIN_MS } from './PresenceBar';
describe('WRITING_PULSE_MIN_MS', () => {
diff --git a/packages/app/src/presence/use-presence.dom.test.tsx b/packages/app/src/presence/use-presence.dom.test.tsx
index 40eeea487..ae63bdecf 100644
--- a/packages/app/src/presence/use-presence.dom.test.tsx
+++ b/packages/app/src/presence/use-presence.dom.test.tsx
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { AgentPresenceEntry } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
import type { AwarenessUser } from './identity';
import { usePresence } from './use-presence';
diff --git a/packages/app/src/presence/use-presence.test.ts b/packages/app/src/presence/use-presence.test.ts
index e019a64f3..f074b25a5 100644
--- a/packages/app/src/presence/use-presence.test.ts
+++ b/packages/app/src/presence/use-presence.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
dedupeHumansByPrincipalId,
type HumanParticipant,
diff --git a/packages/app/src/presence/use-sync-toasts.test.ts b/packages/app/src/presence/use-sync-toasts.test.ts
index c919c8044..c1c51b2d0 100644
--- a/packages/app/src/presence/use-sync-toasts.test.ts
+++ b/packages/app/src/presence/use-sync-toasts.test.ts
@@ -1,12 +1,12 @@
-import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { toast } from 'sonner';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { restartServerFailureMessage } from '@/lib/restart-collab-server';
import { runDisconnectRestart } from './use-sync-toasts';
-// spyOn (not mock.module) so the sonner mock can't leak into sibling test
+// spyOn (not vi.doMock) so the sonner mock can't leak into sibling test
// files in the same `bun test` run.
-const errorSpy = spyOn(toast, 'error').mockImplementation((() => 'err-id') as never);
+const errorSpy = vi.spyOn(toast, 'error').mockImplementation((() => 'err-id') as never);
afterEach(() => {
errorSpy.mockClear();
@@ -14,9 +14,9 @@ afterEach(() => {
function makeBridge(outcome: Awaited<ReturnType<OkDesktopBridge['restartServer']>>): {
bridge: Pick<OkDesktopBridge, 'restartServer' | 'config'>;
- restartServer: ReturnType<typeof mock>;
+ restartServer: ReturnType<typeof vi.fn>;
} {
- const restartServer = mock(async () => outcome);
+ const restartServer = vi.fn(async () => outcome);
return {
bridge: {
restartServer,
@@ -49,7 +49,7 @@ describe('runDisconnectRestart', () => {
});
test('swallows a thrown invoke (window torn down mid-restart) — no error toast', async () => {
- const restartServer = mock(async () => {
+ const restartServer = vi.fn(async () => {
throw new Error('channel closed');
});
const bridge = {
diff --git a/packages/app/src/server/agent-flow.test.ts b/packages/app/src/server/agent-flow.test.ts
index 217a1f59d..210d623f4 100644
--- a/packages/app/src/server/agent-flow.test.ts
+++ b/packages/app/src/server/agent-flow.test.ts
@@ -11,11 +11,12 @@
* without requiring a browser. The CRDT layer (Yjs) and the unified + remark
* serialization layer (MarkdownManager) are the same in both environments.
*/
-import { describe, expect, test } from 'bun:test';
+
import { Hocuspocus } from '@hocuspocus/server';
import { MarkdownManager } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { sharedExtensions } from '../editor/extensions/shared';
diff --git a/packages/app/src/server/api-config-handler.test.ts b/packages/app/src/server/api-config-handler.test.ts
index 087554488..c33488df7 100644
--- a/packages/app/src/server/api-config-handler.test.ts
+++ b/packages/app/src/server/api-config-handler.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeDevApiConfigResponse } from './api-config-handler.ts';
describe('computeDevApiConfigResponse', () => {
diff --git a/packages/app/src/server/hocuspocus-plugin.test.ts b/packages/app/src/server/hocuspocus-plugin.test.ts
index 4bba459dd..5c4cbcf7b 100644
--- a/packages/app/src/server/hocuspocus-plugin.test.ts
+++ b/packages/app/src/server/hocuspocus-plugin.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { EventEmitter } from 'node:events';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import * as actualServerPkg from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { resolveContentConfig } from './hocuspocus-plugin.ts';
const createdDirs: string[] = [];
@@ -72,13 +72,13 @@ describe('hocuspocusPlugin.configureServer middleware ordering', () => {
afterEach(() => {
if (origEnv !== undefined) process.env.OK_TEST_CONTENT_DIR = origEnv;
else delete process.env.OK_TEST_CONTENT_DIR;
- // `mock.module(...)` writes process-global module state in bun:test and
+ // `vi.doMock(...)` writes process-global module state in bun:test and
// does NOT auto-restore between test files. Sibling tests in this codebase
// document the leak explicitly (`server-factory.test.ts`,
// `agent-presence.test.ts`, `provider-pool.test.ts`,
// `local-op-security.test.ts`). Restore to keep the global module table
// clean for any test that may later import `@inkeep/open-knowledge-server`.
- mock.restore();
+ vi.restoreAllMocks();
});
test('registers asset + api middlewares synchronously, no post-hook returned', async () => {
@@ -96,9 +96,9 @@ describe('hocuspocusPlugin.configureServer middleware ordering', () => {
const innerAssetFn = (..._args: unknown[]) => {
innerAssetCalls += 1;
};
- const createAssetServeMiddlewareSpy = mock(() => innerAssetFn);
+ const createAssetServeMiddlewareSpy = vi.fn(() => innerAssetFn);
- mock.module('@inkeep/open-knowledge-server', () => ({
+ vi.doMock('@inkeep/open-knowledge-server', () => ({
...actualServerPkg,
createAssetServeMiddleware: createAssetServeMiddlewareSpy,
createServer: () => ({
diff --git a/packages/app/src/test-utils/visual-contract.ts b/packages/app/src/test-utils/visual-contract.ts
index 26cb909ed..59f008462 100644
--- a/packages/app/src/test-utils/visual-contract.ts
+++ b/packages/app/src/test-utils/visual-contract.ts
@@ -1,4 +1,4 @@
-import { expect } from 'bun:test';
+import { expect } from 'vitest';
// Visual contract guard: jsdom exposes Tailwind tokens only as class strings,
// so use this helper only for CSS behavior jsdom cannot execute directly.
diff --git a/packages/app/tests/conversion/conversion-fidelity.test.ts b/packages/app/tests/conversion/conversion-fidelity.test.ts
index 71554770d..515f5b52d 100644
--- a/packages/app/tests/conversion/conversion-fidelity.test.ts
+++ b/packages/app/tests/conversion/conversion-fidelity.test.ts
@@ -11,11 +11,11 @@
* Documents which constructs are stable vs which normalize.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from '../integration/harness-boot-timeout';
import {
diff --git a/packages/app/tests/dom/jsx-interior-input-rule-suppression.dom.test.tsx b/packages/app/tests/dom/jsx-interior-input-rule-suppression.dom.test.tsx
index 7e5e2e73e..73f10e90f 100644
--- a/packages/app/tests/dom/jsx-interior-input-rule-suppression.dom.test.tsx
+++ b/packages/app/tests/dom/jsx-interior-input-rule-suppression.dom.test.tsx
@@ -23,11 +23,12 @@
* making `listItem` accept a non-paragraph first child reddens (2).
*
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { cleanup } from '@testing-library/react';
import { Editor, type JSONContent } from '@tiptap/core';
import type { Node as PMNode } from '@tiptap/pm/model';
import type { EditorView } from '@tiptap/pm/view';
+import { afterEach, describe, expect, test } from 'vitest';
import { sharedExtensions } from '../../src/editor/extensions/shared';
type TextInputHandler = (view: EditorView, from: number, to: number, text: string) => boolean;
diff --git a/packages/app/tests/dom/source-mode-suggestion-gating.dom.test.tsx b/packages/app/tests/dom/source-mode-suggestion-gating.dom.test.tsx
index 0f5440713..4302497fd 100644
--- a/packages/app/tests/dom/source-mode-suggestion-gating.dom.test.tsx
+++ b/packages/app/tests/dom/source-mode-suggestion-gating.dom.test.tsx
@@ -20,7 +20,7 @@
* requires `document` and `window`; the integration tier substrate
* deliberately omits jsdom, so Tiptap-mount tests live here.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
// `cleanup` is imported to satisfy the dom-test-filename-stop-rule
// contract (every `*.dom.test.tsx` file must value-import from
// `@testing-library/react`). It is invoked in `afterEach` so any
@@ -29,6 +29,7 @@ import { afterEach, describe, expect, test } from 'bun:test';
// render through RTL.
import { cleanup } from '@testing-library/react';
import { Editor } from '@tiptap/core';
+import { afterEach, describe, expect, test } from 'vitest';
import { setEditorSourceMode } from '../../src/editor/extensions/editor-mode-context';
import { sharedExtensions } from '../../src/editor/extensions/shared';
diff --git a/packages/app/tests/integration/activity-log.test.ts b/packages/app/tests/integration/activity-log.test.ts
index 55e31853a..0b13d7223 100644
--- a/packages/app/tests/integration/activity-log.test.ts
+++ b/packages/app/tests/integration/activity-log.test.ts
@@ -5,9 +5,10 @@
* entries, that the ring-buffer eviction caps at 50 entries, and that concurrent
* sessions produce distinct per-session entries.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import type { EffectValue } from '../../../../packages/server/src/activity-log.ts';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/advisory-warnings.test.ts b/packages/app/tests/integration/advisory-warnings.test.ts
index 49865caea..186ffeb35 100644
--- a/packages/app/tests/integration/advisory-warnings.test.ts
+++ b/packages/app/tests/integration/advisory-warnings.test.ts
@@ -7,8 +7,8 @@
* `warning` field never carries render entries.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import type { AdvisoryWarning } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, getServerState, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/agent-focus-wiring.test.ts b/packages/app/tests/integration/agent-focus-wiring.test.ts
index a06c8cd1b..d9b7c32ed 100644
--- a/packages/app/tests/integration/agent-focus-wiring.test.ts
+++ b/packages/app/tests/integration/agent-focus-wiring.test.ts
@@ -9,10 +9,11 @@
* The `hints` array in the write response surfaces hub candidates
* for orphaned writes; absent when the doc has backlinks or no hub exists.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentPatch,
diff --git a/packages/app/tests/integration/agent-undo.test.ts b/packages/app/tests/integration/agent-undo.test.ts
index 06ff3f750..c4842b11e 100644
--- a/packages/app/tests/integration/agent-undo.test.ts
+++ b/packages/app/tests/integration/agent-undo.test.ts
@@ -10,8 +10,8 @@
* @see packages/server/src/agent-sessions.ts applyAgentUndo
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import type { TestServer } from './test-harness';
import { assertBridgeInvariant, createTestClient, createTestServer } from './test-harness';
diff --git a/packages/app/tests/integration/agent-write-during-restart.test.ts b/packages/app/tests/integration/agent-write-during-restart.test.ts
index 5b9a3477f..e7f77ac77 100644
--- a/packages/app/tests/integration/agent-write-during-restart.test.ts
+++ b/packages/app/tests/integration/agent-write-during-restart.test.ts
@@ -21,9 +21,10 @@
* browser client's Y.Doc — any reintroduction of the duplication path
* trips it red.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/api-error-envelope/agent-activity.test.ts b/packages/app/tests/integration/api-error-envelope/agent-activity.test.ts
index 24c042457..f5f478a6d 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-activity.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-activity.test.ts
@@ -10,8 +10,8 @@
* - method-not-allowed on POST → 405 `urn:ok:error:method-not-allowed`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { AgentActivitySuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts b/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts
index f49bcac16..3d134b10c 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts
@@ -16,8 +16,8 @@
* synthesizer); duplicating that setup here is over-coverage.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts b/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts
index 2f43bddca..e9ff2a3a5 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-patch.test.ts
@@ -11,8 +11,8 @@
* - reserved docname → 400 `urn:ok:error:reserved-doc-name` (post-identity)
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { AgentPatchSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { agentWriteMd, createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/agent-undo.test.ts b/packages/app/tests/integration/api-error-envelope/agent-undo.test.ts
index e247a6f7c..1d0900c03 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-undo.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-undo.test.ts
@@ -10,8 +10,8 @@
* - reserved docname → 400 `urn:ok:error:reserved-doc-name` (post-identity).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { AgentUndoSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { agentWriteMd, createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/agent-write-md.test.ts b/packages/app/tests/integration/api-error-envelope/agent-write-md.test.ts
index 94fa449b0..8bdac0c7b 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-write-md.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-write-md.test.ts
@@ -10,8 +10,8 @@
* - reserved docname → `urn:ok:error:reserved-doc-name` (post-identity semantic).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { AgentWriteMdSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/agent-write.test.ts b/packages/app/tests/integration/api-error-envelope/agent-write.test.ts
index 57c2c4223..3cd95c4ac 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-write.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-write.test.ts
@@ -13,8 +13,8 @@
* test-harness boundary.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { AgentWriteSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/auth-query-transport-signout.test.ts b/packages/app/tests/integration/api-error-envelope/auth-query-transport-signout.test.ts
index 55fe89141..a2d97c495 100644
--- a/packages/app/tests/integration/api-error-envelope/auth-query-transport-signout.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/auth-query-transport-signout.test.ts
@@ -5,7 +5,7 @@
* `/api/local-op/auth/signout` error envelope rather than a hand-mocked body.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { httpAuthQueryTransport } from '@/lib/transports/auth-query-transport';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/backlink-counts.test.ts b/packages/app/tests/integration/api-error-envelope/backlink-counts.test.ts
index c834a4c8b..31ef9a3a2 100644
--- a/packages/app/tests/integration/api-error-envelope/backlink-counts.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/backlink-counts.test.ts
@@ -9,8 +9,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { BacklinkCountsSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/backlinks.test.ts b/packages/app/tests/integration/api-error-envelope/backlinks.test.ts
index 754b415f9..c6705f576 100644
--- a/packages/app/tests/integration/api-error-envelope/backlinks.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/backlinks.test.ts
@@ -10,8 +10,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { BacklinksSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/create-folder.test.ts b/packages/app/tests/integration/api-error-envelope/create-folder.test.ts
index 925fd5386..7a1d7d4ba 100644
--- a/packages/app/tests/integration/api-error-envelope/create-folder.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/create-folder.test.ts
@@ -12,8 +12,8 @@
* - method-not-allowed on GET emits `urn:ok:error:method-not-allowed`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { CreateFolderSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/create-page.test.ts b/packages/app/tests/integration/api-error-envelope/create-page.test.ts
index 43979ebb4..cdfd25822 100644
--- a/packages/app/tests/integration/api-error-envelope/create-page.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/create-page.test.ts
@@ -12,10 +12,10 @@
* - method-not-allowed on GET emits `urn:ok:error:method-not-allowed`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { CreatePageSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/dead-links.test.ts b/packages/app/tests/integration/api-error-envelope/dead-links.test.ts
index 7685ac9ab..92809dda2 100644
--- a/packages/app/tests/integration/api-error-envelope/dead-links.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/dead-links.test.ts
@@ -9,8 +9,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { DeadLinksSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/delete-path.test.ts b/packages/app/tests/integration/api-error-envelope/delete-path.test.ts
index 8a4f3429d..a74a4dffe 100644
--- a/packages/app/tests/integration/api-error-envelope/delete-path.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/delete-path.test.ts
@@ -9,8 +9,8 @@
* - method-not-allowed on GET emits `urn:ok:error:method-not-allowed`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { DeletePathSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/document-list.test.ts b/packages/app/tests/integration/api-error-envelope/document-list.test.ts
index f5c914d00..4fac94420 100644
--- a/packages/app/tests/integration/api-error-envelope/document-list.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/document-list.test.ts
@@ -9,8 +9,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { DocumentListSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/document-read.test.ts b/packages/app/tests/integration/api-error-envelope/document-read.test.ts
index d47a791b8..991e295c4 100644
--- a/packages/app/tests/integration/api-error-envelope/document-read.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/document-read.test.ts
@@ -10,8 +10,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { DocumentReadSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/folder-config.test.ts b/packages/app/tests/integration/api-error-envelope/folder-config.test.ts
index f7ef36959..861623e1f 100644
--- a/packages/app/tests/integration/api-error-envelope/folder-config.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/folder-config.test.ts
@@ -10,12 +10,12 @@
* - method-not-allowed on DELETE emits 405 + `Allow: GET, PUT` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
FolderConfigGetSuccessSchema,
FolderConfigPutSuccessSchema,
ProblemDetailsSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/forward-links.test.ts b/packages/app/tests/integration/api-error-envelope/forward-links.test.ts
index 91991820f..0461e697a 100644
--- a/packages/app/tests/integration/api-error-envelope/forward-links.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/forward-links.test.ts
@@ -10,8 +10,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ForwardLinksSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/history-version.test.ts b/packages/app/tests/integration/api-error-envelope/history-version.test.ts
index ee10fee46..b8c6bbdbf 100644
--- a/packages/app/tests/integration/api-error-envelope/history-version.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/history-version.test.ts
@@ -11,13 +11,13 @@
* + `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { join } from 'node:path';
import {
HistoryVersionSuccessSchema,
ProblemDetailsSchema,
SaveVersionSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, pollDiskContentStable, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/history.test.ts b/packages/app/tests/integration/api-error-envelope/history.test.ts
index b9e7cb6d6..664761478 100644
--- a/packages/app/tests/integration/api-error-envelope/history.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/history.test.ts
@@ -10,8 +10,8 @@
* + `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { HistorySuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/hubs.test.ts b/packages/app/tests/integration/api-error-envelope/hubs.test.ts
index 7fd2cf9c0..d4dc121bc 100644
--- a/packages/app/tests/integration/api-error-envelope/hubs.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/hubs.test.ts
@@ -8,8 +8,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { HubsSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/installed-agents.test.ts b/packages/app/tests/integration/api-error-envelope/installed-agents.test.ts
index e6ee77160..57466b9a9 100644
--- a/packages/app/tests/integration/api-error-envelope/installed-agents.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/installed-agents.test.ts
@@ -16,8 +16,8 @@
* `/api/*` Origin gate (`urn:ok:error:invalid-origin`).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { InstalledAgentsSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/link-graph.test.ts b/packages/app/tests/integration/api-error-envelope/link-graph.test.ts
index e308d078f..5fd0b383e 100644
--- a/packages/app/tests/integration/api-error-envelope/link-graph.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/link-graph.test.ts
@@ -12,8 +12,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { LinkGraphSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/local-op-auth-login.test.ts b/packages/app/tests/integration/api-error-envelope/local-op-auth-login.test.ts
index 8963861b4..3d55db7e0 100644
--- a/packages/app/tests/integration/api-error-envelope/local-op-auth-login.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/local-op-auth-login.test.ts
@@ -7,8 +7,8 @@
* head is committed before the spawn's `child.on('error')` fires.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, StreamingProblemEventSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/local-op-auth-repos.test.ts b/packages/app/tests/integration/api-error-envelope/local-op-auth-repos.test.ts
index 2984b5fd3..49a807732 100644
--- a/packages/app/tests/integration/api-error-envelope/local-op-auth-repos.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/local-op-auth-repos.test.ts
@@ -6,8 +6,8 @@
* spawn deterministically triggers the mid-stream path.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, StreamingProblemEventSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/local-op-auth-set-identity.test.ts b/packages/app/tests/integration/api-error-envelope/local-op-auth-set-identity.test.ts
index a1b50a392..64fa1c284 100644
--- a/packages/app/tests/integration/api-error-envelope/local-op-auth-set-identity.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/local-op-auth-set-identity.test.ts
@@ -4,8 +4,8 @@
* only name/email rejection), and the happy-path empty success body.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { LocalOpAuthEmptySuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/local-op-auth-signout.test.ts b/packages/app/tests/integration/api-error-envelope/local-op-auth-signout.test.ts
index 8418b3b13..138baeac1 100644
--- a/packages/app/tests/integration/api-error-envelope/local-op-auth-signout.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/local-op-auth-signout.test.ts
@@ -4,8 +4,8 @@
* happy-path empty success body (no `ok: true` wrapper).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { LocalOpAuthEmptySuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/local-op-auth-status.test.ts b/packages/app/tests/integration/api-error-envelope/local-op-auth-status.test.ts
index dbe363bce..107f8a823 100644
--- a/packages/app/tests/integration/api-error-envelope/local-op-auth-status.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/local-op-auth-status.test.ts
@@ -5,8 +5,8 @@
* `LocalOpAuthStatusSuccessSchema` (`.loose()` accepts CLI-emitted extras).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { LocalOpAuthStatusSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/local-op-clone.test.ts b/packages/app/tests/integration/api-error-envelope/local-op-clone.test.ts
index 202854780..f5205bdf5 100644
--- a/packages/app/tests/integration/api-error-envelope/local-op-clone.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/local-op-clone.test.ts
@@ -14,9 +14,9 @@
* every mid-stream test — no real `git clone` runs, no network access.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { homedir } from 'node:os';
import { ProblemDetailsSchema, StreamingProblemEventSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/metrics-agent-effects.test.ts b/packages/app/tests/integration/api-error-envelope/metrics-agent-effects.test.ts
index c44e16182..a53d26d5e 100644
--- a/packages/app/tests/integration/api-error-envelope/metrics-agent-effects.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/metrics-agent-effects.test.ts
@@ -19,11 +19,11 @@
* with `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
MetricsAgentEffectsSuccessSchema,
ProblemDetailsSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { fetchWithHostHeader } from '../host-header-request.test-helper';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/metrics-agent-presence.test.ts b/packages/app/tests/integration/api-error-envelope/metrics-agent-presence.test.ts
index 9f39fadf7..baf0c6e57 100644
--- a/packages/app/tests/integration/api-error-envelope/metrics-agent-presence.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/metrics-agent-presence.test.ts
@@ -16,11 +16,11 @@
* with `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
MetricsAgentPresenceSuccessSchema,
ProblemDetailsSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { fetchWithHostHeader } from '../host-header-request.test-helper';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/metrics-parse-health.test.ts b/packages/app/tests/integration/api-error-envelope/metrics-parse-health.test.ts
index 5b14d2bf2..b89c6c854 100644
--- a/packages/app/tests/integration/api-error-envelope/metrics-parse-health.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/metrics-parse-health.test.ts
@@ -11,8 +11,8 @@
* with `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { MetricsParseHealthSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/metrics-reconciliation.test.ts b/packages/app/tests/integration/api-error-envelope/metrics-reconciliation.test.ts
index ceb018b31..86ad28b29 100644
--- a/packages/app/tests/integration/api-error-envelope/metrics-reconciliation.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/metrics-reconciliation.test.ts
@@ -12,11 +12,11 @@
* with `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
MetricsReconciliationSuccessSchema,
ProblemDetailsSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/orphans.test.ts b/packages/app/tests/integration/api-error-envelope/orphans.test.ts
index f0a1d7bf9..ce900b53b 100644
--- a/packages/app/tests/integration/api-error-envelope/orphans.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/orphans.test.ts
@@ -9,8 +9,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { OrphansSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/page-headings.test.ts b/packages/app/tests/integration/api-error-envelope/page-headings.test.ts
index 324e4e3e4..9f02cca29 100644
--- a/packages/app/tests/integration/api-error-envelope/page-headings.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/page-headings.test.ts
@@ -10,8 +10,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PageHeadingsSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/pages.test.ts b/packages/app/tests/integration/api-error-envelope/pages.test.ts
index 73f3b8514..4c845196e 100644
--- a/packages/app/tests/integration/api-error-envelope/pages.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/pages.test.ts
@@ -8,8 +8,8 @@
* + `Allow: GET` header before the body is consumed.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PagesSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/principal.test.ts b/packages/app/tests/integration/api-error-envelope/principal.test.ts
index 2d2212d6e..6bfa1be6c 100644
--- a/packages/app/tests/integration/api-error-envelope/principal.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/principal.test.ts
@@ -7,8 +7,8 @@
* - method-not-allowed on POST → `urn:ok:error:method-not-allowed`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PrincipalSuccessSchema, ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { fetchWithHostHeader } from '../host-header-request.test-helper';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/rename-path.test.ts b/packages/app/tests/integration/api-error-envelope/rename-path.test.ts
index 296ce0dc5..b94bd2ac3 100644
--- a/packages/app/tests/integration/api-error-envelope/rename-path.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/rename-path.test.ts
@@ -10,8 +10,8 @@
* - method-not-allowed on GET emits `urn:ok:error:method-not-allowed`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, RenamePathSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/rescue-list.test.ts b/packages/app/tests/integration/api-error-envelope/rescue-list.test.ts
index 2244b6ded..577db3a50 100644
--- a/packages/app/tests/integration/api-error-envelope/rescue-list.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/rescue-list.test.ts
@@ -7,8 +7,8 @@
* + `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, RescueListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/rollback.test.ts b/packages/app/tests/integration/api-error-envelope/rollback.test.ts
index 1b545d58d..b72b94641 100644
--- a/packages/app/tests/integration/api-error-envelope/rollback.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/rollback.test.ts
@@ -13,8 +13,8 @@
* gitEnabled. This smoke test stays narrow to the wire-shape contract.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/save-version.test.ts b/packages/app/tests/integration/api-error-envelope/save-version.test.ts
index a1d1d87e2..6b7dd86c3 100644
--- a/packages/app/tests/integration/api-error-envelope/save-version.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/save-version.test.ts
@@ -10,8 +10,8 @@
* + `Allow: POST` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SaveVersionSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/search.test.ts b/packages/app/tests/integration/api-error-envelope/search.test.ts
index 684f9e8f4..1331dd071 100644
--- a/packages/app/tests/integration/api-error-envelope/search.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/search.test.ts
@@ -9,8 +9,8 @@
* - method-not-allowed on PATCH emits 405 + `Allow: GET, POST`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SearchSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/seed-apply.test.ts b/packages/app/tests/integration/api-error-envelope/seed-apply.test.ts
index ccb909ad2..06286100b 100644
--- a/packages/app/tests/integration/api-error-envelope/seed-apply.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/seed-apply.test.ts
@@ -2,8 +2,8 @@
* Per-handler narrow-integration smoke test for `handleSeedApply`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/seed-plan.test.ts b/packages/app/tests/integration/api-error-envelope/seed-plan.test.ts
index b2a4ca32d..3b808f04b 100644
--- a/packages/app/tests/integration/api-error-envelope/seed-plan.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/seed-plan.test.ts
@@ -2,8 +2,8 @@
* Per-handler narrow-integration smoke test for `handleSeedPlan`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SeedPlanSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/server-info.test.ts b/packages/app/tests/integration/api-error-envelope/server-info.test.ts
index 57ba9d762..33929734f 100644
--- a/packages/app/tests/integration/api-error-envelope/server-info.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/server-info.test.ts
@@ -8,12 +8,12 @@
* - the optional `boot` timings block round-trips through the schema.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
ProblemDetailsSchema,
ServerInfoBootSchema,
ServerInfoSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts b/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts
index 59570430a..f95b40bac 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-builtin-readonly.test.ts
@@ -15,7 +15,6 @@
* - a refused DELETE leaves the on-disk file intact.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import {
@@ -23,6 +22,7 @@ import {
SkillGetSuccessSchema,
SkillsListSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
index 322707481..928cb2940 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-cross-scope-move-uninstall.test.ts
@@ -17,10 +17,10 @@
* live under `<home>/.{host}/skills/`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-install-state.test.ts b/packages/app/tests/integration/api-error-envelope/skill-install-state.test.ts
index 114233caf..1df06de7d 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-install-state.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-install-state.test.ts
@@ -9,8 +9,8 @@
* /api/* origin gate fires before the handler).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SkillInstallStateSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-install.test.ts b/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
index 9106d50ba..e472e4218 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-install.test.ts
@@ -10,10 +10,10 @@
* pre-install validity gate (reserved name, conflict markers).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ProblemDetailsSchema, SkillInstallSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
index 73556c726..c9b102d17 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-personal-scope.test.ts
@@ -10,7 +10,6 @@
* `$HOME`, so an env override wouldn't work — the seam is threaded explicitly.)
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -19,6 +18,7 @@ import {
SkillGetSuccessSchema,
SkillsListSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts b/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
index cd327d501..c4fbc5463 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-restore.test.ts
@@ -8,12 +8,12 @@
* and committed to the shadow repo (anonymous writes record nothing).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
HistorySuccessSchema,
SkillGetSuccessSchema,
SkillRestoreSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
// Project skills are content docs, so their version history comes from the
// unified document-history path (`/api/history?docName=.ok/skills/<name>/SKILL`),
diff --git a/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
index ea6784164..a7973e80a 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-scope-move.test.ts
@@ -24,11 +24,11 @@
* Hermetic global home via `configHomedirOverride`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SkillsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, pollUntil, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts b/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
index fbbd32149..9e3f6c349 100644
--- a/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill-targets.test.ts
@@ -8,13 +8,13 @@
* server (`projectDir === contentDir`).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import {
SkillTargetsGetSuccessSchema,
SkillTargetsPutSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/skill.test.ts b/packages/app/tests/integration/api-error-envelope/skill.test.ts
index eff84504f..b4e7ceb38 100644
--- a/packages/app/tests/integration/api-error-envelope/skill.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/skill.test.ts
@@ -14,7 +14,6 @@
* - method-not-allowed on PATCH → 405 + `Allow: GET, PUT, POST, DELETE`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
ProblemDetailsSchema,
SkillDeleteSuccessSchema,
@@ -23,6 +22,7 @@ import {
SkillPutSuccessSchema,
SkillsListSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/suggest-links.test.ts b/packages/app/tests/integration/api-error-envelope/suggest-links.test.ts
index b22e89fa3..d32bf2169 100644
--- a/packages/app/tests/integration/api-error-envelope/suggest-links.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/suggest-links.test.ts
@@ -15,8 +15,8 @@
* sufficient to catch wire-shape regressions.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/sync-conflict-content.test.ts b/packages/app/tests/integration/api-error-envelope/sync-conflict-content.test.ts
index 527feb9e6..192df30c5 100644
--- a/packages/app/tests/integration/api-error-envelope/sync-conflict-content.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/sync-conflict-content.test.ts
@@ -2,8 +2,8 @@
* Per-handler narrow-integration smoke test for `handleSyncConflictContent`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/sync-conflicts.test.ts b/packages/app/tests/integration/api-error-envelope/sync-conflicts.test.ts
index a58852588..64e2a9dbd 100644
--- a/packages/app/tests/integration/api-error-envelope/sync-conflicts.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/sync-conflicts.test.ts
@@ -5,8 +5,8 @@
* in the test harness.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SyncConflictsSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts b/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts
index 9c32e47fd..282d7826f 100644
--- a/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/sync-resolve-conflict.test.ts
@@ -6,8 +6,8 @@
* happy-path body validation, body-shape errors, and method gating.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/sync-status.test.ts b/packages/app/tests/integration/api-error-envelope/sync-status.test.ts
index 01b5990a7..d93287c58 100644
--- a/packages/app/tests/integration/api-error-envelope/sync-status.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/sync-status.test.ts
@@ -9,8 +9,8 @@
* with `Allow: GET`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SyncStatusSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/sync-trigger.test.ts b/packages/app/tests/integration/api-error-envelope/sync-trigger.test.ts
index eb7d309dc..7aedcfa7f 100644
--- a/packages/app/tests/integration/api-error-envelope/sync-trigger.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/sync-trigger.test.ts
@@ -10,8 +10,8 @@
* - method-not-allowed on GET → 405 with `Allow: POST`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, SyncTriggerSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/tags-for-name.test.ts b/packages/app/tests/integration/api-error-envelope/tags-for-name.test.ts
index 657b2ffac..7d3cde78b 100644
--- a/packages/app/tests/integration/api-error-envelope/tags-for-name.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/tags-for-name.test.ts
@@ -8,8 +8,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, TagsForNameSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/tags-list.test.ts b/packages/app/tests/integration/api-error-envelope/tags-list.test.ts
index 2eadf98f8..237a3e33d 100644
--- a/packages/app/tests/integration/api-error-envelope/tags-list.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/tags-list.test.ts
@@ -8,8 +8,8 @@
* `Allow: GET` header.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, TagsListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/template-import.test.ts b/packages/app/tests/integration/api-error-envelope/template-import.test.ts
index 4d1430baf..29878c57d 100644
--- a/packages/app/tests/integration/api-error-envelope/template-import.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/template-import.test.ts
@@ -13,10 +13,10 @@
* - Missing source → 404 + `urn:ok:error:doc-not-found`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { ProblemDetailsSchema, TemplateImportSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer, wait } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/template.test.ts b/packages/app/tests/integration/api-error-envelope/template.test.ts
index 66b8db774..17dd1db8a 100644
--- a/packages/app/tests/integration/api-error-envelope/template.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/template.test.ts
@@ -11,12 +11,12 @@
* - method-not-allowed on PATCH emits 405 + `Allow: GET, PUT, POST, DELETE`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
ProblemDetailsSchema,
TemplateDeleteSuccessSchema,
TemplatePutSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/templates-list.test.ts b/packages/app/tests/integration/api-error-envelope/templates-list.test.ts
index 934828139..97263f8f8 100644
--- a/packages/app/tests/integration/api-error-envelope/templates-list.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/templates-list.test.ts
@@ -11,8 +11,8 @@
* - method-not-allowed on POST emits 405.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { TemplatesListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/test-flush-git.test.ts b/packages/app/tests/integration/api-error-envelope/test-flush-git.test.ts
index 79001eab6..68313f840 100644
--- a/packages/app/tests/integration/api-error-envelope/test-flush-git.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/test-flush-git.test.ts
@@ -13,8 +13,8 @@
* with `Allow: POST`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, TestFlushGitSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/test-rescan-backlinks.test.ts b/packages/app/tests/integration/api-error-envelope/test-rescan-backlinks.test.ts
index 7d9a0cfc9..14d11fabf 100644
--- a/packages/app/tests/integration/api-error-envelope/test-rescan-backlinks.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/test-rescan-backlinks.test.ts
@@ -14,11 +14,11 @@
* `BacklinkIndex`); covered by `packages/server/src/api-backlinks.test.ts`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
ProblemDetailsSchema,
TestRescanBacklinksSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/test-rescan-files.test.ts b/packages/app/tests/integration/api-error-envelope/test-rescan-files.test.ts
index 50c5a9b18..5f2a9488a 100644
--- a/packages/app/tests/integration/api-error-envelope/test-rescan-files.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/test-rescan-files.test.ts
@@ -15,8 +15,8 @@
* `packages/server/src/api-test-rescan-files.test.ts`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, TestRescanFilesSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/test-reset.test.ts b/packages/app/tests/integration/api-error-envelope/test-reset.test.ts
index 294c7db27..cb3057af8 100644
--- a/packages/app/tests/integration/api-error-envelope/test-reset.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/test-reset.test.ts
@@ -11,8 +11,8 @@
* with `Allow: POST`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, TestResetSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/unmatched-route.test.ts b/packages/app/tests/integration/api-error-envelope/unmatched-route.test.ts
index f62789803..c391d9387 100644
--- a/packages/app/tests/integration/api-error-envelope/unmatched-route.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/unmatched-route.test.ts
@@ -13,8 +13,8 @@
* floor.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/upload-asset.test.ts b/packages/app/tests/integration/api-error-envelope/upload-asset.test.ts
index 636f557f6..3b9ca0647 100644
--- a/packages/app/tests/integration/api-error-envelope/upload-asset.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/upload-asset.test.ts
@@ -12,10 +12,10 @@
* test-harness boundary (Hocuspocus server, contentDir tempdir).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ProblemDetailsSchema, UploadAssetSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/api-error-envelope/workspace.test.ts b/packages/app/tests/integration/api-error-envelope/workspace.test.ts
index 85cc0713c..5713abb0c 100644
--- a/packages/app/tests/integration/api-error-envelope/workspace.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/workspace.test.ts
@@ -6,8 +6,8 @@
* + method-not-allowed paths and the loose-shape success body.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { ProblemDetailsSchema, WorkspaceSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';
import { fetchWithHostHeader } from '../host-header-request.test-helper';
import { createTestServer, type TestServer } from '../test-harness';
diff --git a/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts b/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts
index 206cd06a6..ed14148c8 100644
--- a/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts
+++ b/packages/app/tests/integration/asset-move-rerenders-embeds.test.ts
@@ -26,13 +26,13 @@
* has nothing to detect, so we exercise the asset-event path in isolation.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { ensureProjectGit } from '@inkeep/open-knowledge-server';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import { createRestartableServer, getServerState, pollUntil, schema } from './test-harness';
diff --git a/packages/app/tests/integration/backlinks.test.ts b/packages/app/tests/integration/backlinks.test.ts
index 0bec9f598..a3f9008cf 100644
--- a/packages/app/tests/integration/backlinks.test.ts
+++ b/packages/app/tests/integration/backlinks.test.ts
@@ -1,6 +1,6 @@
-import { test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { test } from 'vitest';
import {
awaitBacklinkIndexed,
createTestClient,
diff --git a/packages/app/tests/integration/branch-switch-live-client.test.ts b/packages/app/tests/integration/branch-switch-live-client.test.ts
index 9d9ded88c..11ee78f54 100644
--- a/packages/app/tests/integration/branch-switch-live-client.test.ts
+++ b/packages/app/tests/integration/branch-switch-live-client.test.ts
@@ -19,7 +19,7 @@
* clientID, different items at same clocks would conflict but not duplicate;
* different clocks would duplicate.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { execSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -27,6 +27,7 @@ import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { ensureProjectGit } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { handleBranchSwitched } from '../../src/editor/branch-invalidation';
import { ProviderPool } from '../../src/editor/provider-pool';
diff --git a/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts b/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts
index 086b287f3..bcb851b1e 100644
--- a/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts
+++ b/packages/app/tests/integration/branch-switched-with-stale-embed-resolution.test.ts
@@ -34,7 +34,6 @@
* @see packages/app/tests/integration/restart-with-embed-doc.test.ts
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -42,6 +41,7 @@ import { dirname, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { ensureProjectGit } from '@inkeep/open-knowledge-server';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import { createRestartableServer, getServerState, pollUntil, schema } from './test-harness';
diff --git a/packages/app/tests/integration/bridge-cold-load-corpus.test.ts b/packages/app/tests/integration/bridge-cold-load-corpus.test.ts
index 09655bedd..2c96e8889 100644
--- a/packages/app/tests/integration/bridge-cold-load-corpus.test.ts
+++ b/packages/app/tests/integration/bridge-cold-load-corpus.test.ts
@@ -37,11 +37,11 @@
* `createTestServer` doing exactly the cold-load path the bug reproduced on.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { copyFileSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createTestClient, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/bridge-convergence-regression.test.ts b/packages/app/tests/integration/bridge-convergence-regression.test.ts
index ca79c667c..384dbe4a4 100644
--- a/packages/app/tests/integration/bridge-convergence-regression.test.ts
+++ b/packages/app/tests/integration/bridge-convergence-regression.test.ts
@@ -9,11 +9,11 @@
* CONTROL: peer+peer XmlFragment edits
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/bridge-matrix.test.ts b/packages/app/tests/integration/bridge-matrix.test.ts
index 8a4268812..94be472e0 100644
--- a/packages/app/tests/integration/bridge-matrix.test.ts
+++ b/packages/app/tests/integration/bridge-matrix.test.ts
@@ -13,11 +13,11 @@
* Each test uses a per-test unique docName via createTestClient(port).
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { markUserTyping } from '../../src/editor/observers';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
diff --git a/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts b/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts
index 54043156f..b87d66576 100644
--- a/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts
+++ b/packages/app/tests/integration/bridge-watchdog-multi-peer-drain.test.ts
@@ -22,8 +22,8 @@
* Explicit `skipInvariantWatcher: false` here for documentation.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts b/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts
index b8fecf58d..ae5230605 100644
--- a/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts
+++ b/packages/app/tests/integration/bug-a-mechanism-isolation.test.ts
@@ -14,9 +14,9 @@
* Iron Law: NO production code modified.
*/
-import { describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import {
agentWriteMd,
createTestClient,
diff --git a/packages/app/tests/integration/bug-c-real-reachability.test.ts b/packages/app/tests/integration/bug-c-real-reachability.test.ts
index 685e27a61..39ae592b6 100644
--- a/packages/app/tests/integration/bug-c-real-reachability.test.ts
+++ b/packages/app/tests/integration/bug-c-real-reachability.test.ts
@@ -16,10 +16,10 @@
* Iron Law: NO production code modified.
*/
-import { describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
createTestClient,
diff --git a/packages/app/tests/integration/bug-d-v0-14-agent-undo-under-concurrent-typing.test.ts b/packages/app/tests/integration/bug-d-v0-14-agent-undo-under-concurrent-typing.test.ts
index 8e4063d83..f30d42ed4 100644
--- a/packages/app/tests/integration/bug-d-v0-14-agent-undo-under-concurrent-typing.test.ts
+++ b/packages/app/tests/integration/bug-d-v0-14-agent-undo-under-concurrent-typing.test.ts
@@ -18,9 +18,9 @@
* destroys new user XmlFragment keystroke.
*/
-import { describe, expect, test } from 'bun:test';
import { prependFrontmatter, stripFrontmatter } from '@inkeep/open-knowledge-core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { mdManager, schema } from './test-harness';
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index c18788593..ad11acbe8 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -21,11 +21,11 @@
*
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/c1-concurrent-wysiwyg.test.ts b/packages/app/tests/integration/c1-concurrent-wysiwyg.test.ts
index 042ef322c..4a29b32b3 100644
--- a/packages/app/tests/integration/c1-concurrent-wysiwyg.test.ts
+++ b/packages/app/tests/integration/c1-concurrent-wysiwyg.test.ts
@@ -10,8 +10,8 @@
* Client lifecycle in try/finally (not afterEach).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c10-server-restart.test.ts b/packages/app/tests/integration/c10-server-restart.test.ts
index 63c783d2d..6d680ee1a 100644
--- a/packages/app/tests/integration/c10-server-restart.test.ts
+++ b/packages/app/tests/integration/c10-server-restart.test.ts
@@ -46,10 +46,10 @@
* Per-test docName isolation. Client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
assertBridgeInvariant,
diff --git a/packages/app/tests/integration/c11-activity-panel-undo.test.ts b/packages/app/tests/integration/c11-activity-panel-undo.test.ts
index 7a30191ca..25cd804ac 100644
--- a/packages/app/tests/integration/c11-activity-panel-undo.test.ts
+++ b/packages/app/tests/integration/c11-activity-panel-undo.test.ts
@@ -13,8 +13,9 @@
* shadow-repo git commit. The CC1 sub-test creates its own server with
* gitEnabled: true + commitDebounceMs: 200 so the commit fires quickly.
*/
-import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';
+
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
import { listAgentActivity } from '../../../../packages/server/src/agent-activity.ts';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import type { TestServer } from './test-harness';
@@ -174,7 +175,7 @@ describe('C11 — Activity Panel undo isolation + CC1 signal', () => {
try {
const broadcaster = ccServer.instance.cc1Broadcaster;
if (!broadcaster) throw new Error('cc1Broadcaster unexpectedly null');
- const spy = spyOn(broadcaster, 'signal');
+ const spy = vi.spyOn(broadcaster, 'signal');
const docName = `test-c11-cc1-${crypto.randomUUID()}`;
const agentSuffix = `cc1-${crypto.randomUUID().slice(0, 8)}`;
diff --git a/packages/app/tests/integration/c12-nested-frontmatter.test.ts b/packages/app/tests/integration/c12-nested-frontmatter.test.ts
index 4e6e06cf2..2773543c2 100644
--- a/packages/app/tests/integration/c12-nested-frontmatter.test.ts
+++ b/packages/app/tests/integration/c12-nested-frontmatter.test.ts
@@ -20,7 +20,6 @@
* Client lifecycle in try/finally (not afterEach).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import {
bindFrontmatterDoc,
@@ -31,6 +30,7 @@ import {
readFmMap,
stripFrontmatter,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c13-pathb-doc-boundary.test.ts b/packages/app/tests/integration/c13-pathb-doc-boundary.test.ts
index d04fca7e6..8ce69a261 100644
--- a/packages/app/tests/integration/c13-pathb-doc-boundary.test.ts
+++ b/packages/app/tests/integration/c13-pathb-doc-boundary.test.ts
@@ -23,8 +23,8 @@
* Per-test docName isolation; client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c14-indented-jsx-concurrent.test.ts b/packages/app/tests/integration/c14-indented-jsx-concurrent.test.ts
index cb414c9f7..555853127 100644
--- a/packages/app/tests/integration/c14-indented-jsx-concurrent.test.ts
+++ b/packages/app/tests/integration/c14-indented-jsx-concurrent.test.ts
@@ -14,8 +14,8 @@
* Per-test docName isolation; client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c15-dual-embed-divergence.test.ts b/packages/app/tests/integration/c15-dual-embed-divergence.test.ts
index e5cc5d3a0..aa24b61c0 100644
--- a/packages/app/tests/integration/c15-dual-embed-divergence.test.ts
+++ b/packages/app/tests/integration/c15-dual-embed-divergence.test.ts
@@ -17,8 +17,8 @@
* Per-test docName isolation; client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c16-lazy-continuation.test.ts b/packages/app/tests/integration/c16-lazy-continuation.test.ts
index 2f7b1c392..a58bc7053 100644
--- a/packages/app/tests/integration/c16-lazy-continuation.test.ts
+++ b/packages/app/tests/integration/c16-lazy-continuation.test.ts
@@ -22,9 +22,9 @@
* Client lifecycle in try/finally (not afterEach) per R8a.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { BridgeInvariantViolationError } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c2-concurrent-source.test.ts b/packages/app/tests/integration/c2-concurrent-source.test.ts
index ac8929c66..95db42b05 100644
--- a/packages/app/tests/integration/c2-concurrent-source.test.ts
+++ b/packages/app/tests/integration/c2-concurrent-source.test.ts
@@ -10,8 +10,8 @@
* Client lifecycle in try/finally (not afterEach).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
assertBridgeInvariant,
diff --git a/packages/app/tests/integration/c3-mixed-mode.test.ts b/packages/app/tests/integration/c3-mixed-mode.test.ts
index d54c89d98..0e64fd180 100644
--- a/packages/app/tests/integration/c3-mixed-mode.test.ts
+++ b/packages/app/tests/integration/c3-mixed-mode.test.ts
@@ -11,8 +11,8 @@
* Client lifecycle in try/finally (not afterEach).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts b/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
index 0589ce70d..4735f588d 100644
--- a/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
+++ b/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
@@ -12,8 +12,8 @@
* Client lifecycle in try/finally (not afterEach).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c5-agent-plus-source.test.ts b/packages/app/tests/integration/c5-agent-plus-source.test.ts
index da7cbb2d0..f390de258 100644
--- a/packages/app/tests/integration/c5-agent-plus-source.test.ts
+++ b/packages/app/tests/integration/c5-agent-plus-source.test.ts
@@ -12,8 +12,8 @@
* Client lifecycle in try/finally (not afterEach).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts b/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts
index a7764755f..5768b92c1 100644
--- a/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts
+++ b/packages/app/tests/integration/c6-mode-switch-mid-debounce.test.ts
@@ -16,8 +16,8 @@
* Per-test docName isolation. Client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts b/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts
index e09097cb3..9b0b8cf87 100644
--- a/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts
+++ b/packages/app/tests/integration/c7-disconnect-reconnect-burst.test.ts
@@ -10,8 +10,8 @@
* Per-test docName isolation. Client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c8-triple-concurrent.test.ts b/packages/app/tests/integration/c8-triple-concurrent.test.ts
index 518366b86..1abaafcd4 100644
--- a/packages/app/tests/integration/c8-triple-concurrent.test.ts
+++ b/packages/app/tests/integration/c8-triple-concurrent.test.ts
@@ -14,10 +14,10 @@
* Per-test docName isolation. Client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/c9-join-mid-debounce.test.ts b/packages/app/tests/integration/c9-join-mid-debounce.test.ts
index 7ddf18c07..b0e2871ba 100644
--- a/packages/app/tests/integration/c9-join-mid-debounce.test.ts
+++ b/packages/app/tests/integration/c9-join-mid-debounce.test.ts
@@ -10,8 +10,8 @@
* Per-test docName isolation. Client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/cc1-broadcast.test.ts b/packages/app/tests/integration/cc1-broadcast.test.ts
index c2e80a70e..00bc80b77 100644
--- a/packages/app/tests/integration/cc1-broadcast.test.ts
+++ b/packages/app/tests/integration/cc1-broadcast.test.ts
@@ -1,4 +1,3 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
@@ -10,6 +9,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { applyExternalChange, BacklinkIndex, reconcile } from '@inkeep/open-knowledge-server';
import * as encoding from 'lib0/encoding';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, pollUntil, type TestServer, waitForSync } from './test-harness';
diff --git a/packages/app/tests/integration/classify-final-state.test.ts b/packages/app/tests/integration/classify-final-state.test.ts
index 3dd2bc67b..81e3d544d 100644
--- a/packages/app/tests/integration/classify-final-state.test.ts
+++ b/packages/app/tests/integration/classify-final-state.test.ts
@@ -6,7 +6,7 @@
* pinned here against hand-built client states: a future inversion of the
* pass/fail decision reddens reliably instead of probabilistically.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { classifyFinalState, serializeFragment } from './test-harness';
diff --git a/packages/app/tests/integration/client-logs-endpoint.test.ts b/packages/app/tests/integration/client-logs-endpoint.test.ts
index 902cb33db..2c2d1f1ce 100644
--- a/packages/app/tests/integration/client-logs-endpoint.test.ts
+++ b/packages/app/tests/integration/client-logs-endpoint.test.ts
@@ -10,8 +10,8 @@
* `packages/core/src/schemas/api/client-logs.test.ts`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { RENDERER_LOG_MAX_ENTRIES } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { fetchWithHostHeader } from './host-header-request.test-helper';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/client-version-no-regression.test.ts b/packages/app/tests/integration/client-version-no-regression.test.ts
index c789e98ab..171c7b156 100644
--- a/packages/app/tests/integration/client-version-no-regression.test.ts
+++ b/packages/app/tests/integration/client-version-no-regression.test.ts
@@ -1,6 +1,6 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { clientVersionHeaders } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { buildAuthToken } from '../../src/lib/auth-token';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
diff --git a/packages/app/tests/integration/clipboard-cross-app-sanitizer-proxy.test.ts b/packages/app/tests/integration/clipboard-cross-app-sanitizer-proxy.test.ts
index 30c390f93..154150972 100644
--- a/packages/app/tests/integration/clipboard-cross-app-sanitizer-proxy.test.ts
+++ b/packages/app/tests/integration/clipboard-cross-app-sanitizer-proxy.test.ts
@@ -16,7 +16,7 @@
* Runs in `bun test`.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
// ---------------------------------------------------------------------------
// Walker output fixtures (one per descriptor) — what the walker would emit
diff --git a/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts b/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts
index 89b422775..2b428f516 100644
--- a/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts
+++ b/packages/app/tests/integration/clipboard-dispatcher-reorder.test.ts
@@ -13,12 +13,12 @@
* — CM6 `EditorView.domEventHandlers` wiring requires a real DOM.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { mdManager, schema } from './test-harness.ts';
// Mock sonner so toast.error doesn't throw in node.
-mock.module('sonner', () => ({ toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ toast: { error: vi.fn(() => {}) } }));
// Imported after the mock so the dispatcher module picks up the stub.
let createHandlePaste: typeof import('../../src/editor/clipboard/handle-paste.ts').createHandlePaste;
diff --git a/packages/app/tests/integration/clipboard-walker-integration.test.ts b/packages/app/tests/integration/clipboard-walker-integration.test.ts
index cbb48ca96..544daa85d 100644
--- a/packages/app/tests/integration/clipboard-walker-integration.test.ts
+++ b/packages/app/tests/integration/clipboard-walker-integration.test.ts
@@ -14,13 +14,13 @@
* interface (has `serializeFragment`).
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { createClipboardHtmlSerializer } from '../../src/editor/clipboard/serialize.ts';
function fakeMdManager() {
return {
- serialize: mock(() => '# heading\n'),
- parse: mock(() => ({ type: 'doc', content: [] })),
+ serialize: vi.fn(() => '# heading\n'),
+ parse: vi.fn(() => ({ type: 'doc', content: [] })),
};
}
diff --git a/packages/app/tests/integration/cold-start-empty-idb.test.ts b/packages/app/tests/integration/cold-start-empty-idb.test.ts
index d0401b9a2..537d728c2 100644
--- a/packages/app/tests/integration/cold-start-empty-idb.test.ts
+++ b/packages/app/tests/integration/cold-start-empty-idb.test.ts
@@ -17,10 +17,11 @@
* 4. Disk content is stable and still matches the seeded markdown.
*
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
assertIDBEmpty,
diff --git a/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts b/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts
index 79c0b74dd..42bbc8521 100644
--- a/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts
+++ b/packages/app/tests/integration/config-doc-server-instance-recovery.test.ts
@@ -23,12 +23,12 @@
* simply never merged.)
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { CONFIG_DOC_NAME_OKIGNORE } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { buildAuthToken } from '../../src/lib/auth-token';
import { createRestartableServer, pollUntil, waitForSync } from './test-harness';
diff --git a/packages/app/tests/integration/config-hot-apply-without-watcher-echo.test.ts b/packages/app/tests/integration/config-hot-apply-without-watcher-echo.test.ts
index 9824b62bb..938b504af 100644
--- a/packages/app/tests/integration/config-hot-apply-without-watcher-echo.test.ts
+++ b/packages/app/tests/integration/config-hot-apply-without-watcher-echo.test.ts
@@ -23,10 +23,10 @@
* not on how the notification is delivered.
*/
-import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
import { EventEmitter } from 'node:events';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
// Register BEFORE the server's dynamic `await import('chokidar')` runs. The
// watcher fires `ready` (chokidar's post-initial-scan signal) then swallows
@@ -45,24 +45,18 @@ class SwallowingWatcher extends EventEmitter {
}
async close(): Promise<void> {}
}
-// `mock.module` replaces chokidar for the WHOLE bun-test process, not just this
-// file — sibling test files in the same shard would inherit the swallowed
-// watcher and silently starve on filesystem events (observed: managed-artifact
-// reconcile timing out in the same shard). Confine the fault injection to this
-// file: swallow only while this file's suites run, then delegate to the real
-// implementation.
+// Keep the fault injection bounded to this suite: swallow events while its
+// cases run, then delegate any late imports to the real implementation.
//
// The delegation target MUST be a destructured function reference captured
-// BEFORE mock.module runs: when the module was already imported earlier in the
-// process, bun patches the existing namespace's live bindings, so delegating
-// through a captured namespace object would call the mock itself (infinite
-// recursion). A destructured const keeps pointing at the real function.
+// BEFORE vi.doMock runs so the factory can delegate through a stable function
+// reference without recursing through its own mocked namespace.
const { watch: realChokidarWatch } = await import('chokidar');
let swallowChokidarEvents = true;
afterAll(() => {
swallowChokidarEvents = false;
});
-mock.module('chokidar', () => ({
+vi.doMock('chokidar', () => ({
watch: (...args: Parameters<typeof realChokidarWatch>) =>
swallowChokidarEvents
? (new SwallowingWatcher() as unknown as ReturnType<typeof realChokidarWatch>)
diff --git a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
index 735359047..d2c985b06 100644
--- a/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
+++ b/packages/app/tests/integration/conflict-resolution-delete-modify.test.ts
@@ -48,13 +48,14 @@
* to remove the redundant guard (TS narrows via the earlier throw) —
* assertions below confirm the misleading message no longer fires.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { execFile } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, pollUntil, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/conflict-resolver-deletion-coverage.test.ts b/packages/app/tests/integration/conflict-resolver-deletion-coverage.test.ts
index fb873cf41..6b1b8ee1b 100644
--- a/packages/app/tests/integration/conflict-resolver-deletion-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-resolver-deletion-coverage.test.ts
@@ -12,9 +12,10 @@
* `ConflictResolver` symbol or the `onOpenConflictResolver` /
* `onOpenResolver` prop names.
*/
-import { describe, expect, test } from 'bun:test';
+
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const APP_SRC = join(import.meta.dir, '..', '..', 'src');
const RESOLVER_PATH = join(APP_SRC, 'components', 'ConflictResolver.tsx');
diff --git a/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts b/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts
index 0d7f50e37..228ac174f 100644
--- a/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts
+++ b/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts
@@ -40,7 +40,7 @@
* resume the server fragment holds two copies of the Step subtree and the
* authoritative Y.Text duplicates the typed body line.
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/create-page.test.ts b/packages/app/tests/integration/create-page.test.ts
index 69bacd089..3c4a5f5b0 100644
--- a/packages/app/tests/integration/create-page.test.ts
+++ b/packages/app/tests/integration/create-page.test.ts
@@ -16,9 +16,9 @@
* - `.md` suffix is required (server's hard contract)
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/cross-doc-stale-cache.test.ts b/packages/app/tests/integration/cross-doc-stale-cache.test.ts
index 686809f2c..2f1115b93 100644
--- a/packages/app/tests/integration/cross-doc-stale-cache.test.ts
+++ b/packages/app/tests/integration/cross-doc-stale-cache.test.ts
@@ -1,8 +1,8 @@
import './idb-preload';
-import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import * as clientPersistence from '../../src/editor/client-persistence';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
@@ -85,12 +85,12 @@ describe('Cross-document stale cache (epoch-scoped IDB)', () => {
typeof clientPersistence.createClientPersistence
>[0][] = [];
const originalCreate = clientPersistence.createClientPersistence.bind(clientPersistence);
- const createSpy = spyOn(clientPersistence, 'createClientPersistence').mockImplementation(
- (args) => {
+ const createSpy = vi
+ .spyOn(clientPersistence, 'createClientPersistence')
+ .mockImplementation((args) => {
persistenceCreateCalls.push(args);
return originalCreate(args);
- },
- );
+ });
cleanups.push(() => createSpy.mockRestore());
const secondPool = new ProviderPool(3, `ws://127.0.0.1:${server.port}/collab`);
diff --git a/packages/app/tests/integration/delete-durability.test.ts b/packages/app/tests/integration/delete-durability.test.ts
index 134463a39..15145ed4e 100644
--- a/packages/app/tests/integration/delete-durability.test.ts
+++ b/packages/app/tests/integration/delete-durability.test.ts
@@ -25,12 +25,12 @@
* (on-disk file state). Per-test docNames via randomUUID (STOP rule).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { HocuspocusProvider } from '@hocuspocus/provider';
import { parseAuthRejectionWire } from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/disk-ack-missed-frame.test.ts b/packages/app/tests/integration/disk-ack-missed-frame.test.ts
index 607fcec68..7b8df9a13 100644
--- a/packages/app/tests/integration/disk-ack-missed-frame.test.ts
+++ b/packages/app/tests/integration/disk-ack-missed-frame.test.ts
@@ -38,10 +38,11 @@
* Expected: PASS. Both client and disk show the marker exactly once
* after the recycle.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import { refreshServerInfo } from '../../src/lib/server-info-refresh';
import {
diff --git a/packages/app/tests/integration/disk-authority-reconcile.test.ts b/packages/app/tests/integration/disk-authority-reconcile.test.ts
index e2502885b..6d9309cbf 100644
--- a/packages/app/tests/integration/disk-authority-reconcile.test.ts
+++ b/packages/app/tests/integration/disk-authority-reconcile.test.ts
@@ -24,10 +24,11 @@
* The file-watcher loses the reconcile race deterministically in this timing,
* so L1 — not the watcher — is what preserves both edits.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
agentPatch,
agentWriteMd,
diff --git a/packages/app/tests/integration/disk-divergence-backstop.test.ts b/packages/app/tests/integration/disk-divergence-backstop.test.ts
index 95ae71a63..22dce67c7 100644
--- a/packages/app/tests/integration/disk-divergence-backstop.test.ts
+++ b/packages/app/tests/integration/disk-divergence-backstop.test.ts
@@ -18,8 +18,9 @@
* client/browser store path reaches — so the exclusion is structural, and the
* exclusion test pins it behaviorally.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
+import { afterEach, describe, expect, test } from 'vitest';
import {
agentWriteMd,
awaitDocQuiescence,
diff --git a/packages/app/tests/integration/document-list-depth1.test.ts b/packages/app/tests/integration/document-list-depth1.test.ts
index 9fbb307df..7c3ccf25d 100644
--- a/packages/app/tests/integration/document-list-depth1.test.ts
+++ b/packages/app/tests/integration/document-list-depth1.test.ts
@@ -6,11 +6,12 @@
* the subtree. This is the server half of collapsing the FileTree retained set
* from the whole tree to the on-screen working set.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { awaitFileWatcherIndexed, createTestServer, type TestServer } from './test-harness';
let server: TestServer;
diff --git a/packages/app/tests/integration/document-list-showall-cap.test.ts b/packages/app/tests/integration/document-list-showall-cap.test.ts
index a7fc44d94..6f678d8c6 100644
--- a/packages/app/tests/integration/document-list-showall-cap.test.ts
+++ b/packages/app/tests/integration/document-list-showall-cap.test.ts
@@ -3,11 +3,12 @@
* pointed at a large tree must not accumulate unbounded entries — the walk
* stops at `OK_SHOWALL_MAX_ENTRIES` and the response reports `truncated`.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { awaitFileWatcherIndexed, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts b/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts
index 9f77c40e1..c3cfda2b2 100644
--- a/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts
+++ b/packages/app/tests/integration/dom-test-filename-stop-rule.test.ts
@@ -31,9 +31,9 @@
* (b) remove the RTL value import (keeping `import type` is fine).
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
const PACKAGE_APP_ROOT = resolve(import.meta.dir, '../..');
const SCAN_ROOTS = ['src', 'tests'] as const;
diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.ts
index 4ae9f4a4e..32533501d 100644
--- a/packages/app/tests/integration/e2e-stop-rules.test.ts
+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts
@@ -29,10 +29,10 @@
* easing token
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { DEV_GATED_WINDOW_WRITERS } from './dev-gate-allowlist';
const __dirname = dirname(fileURLToPath(import.meta.url));
diff --git a/packages/app/tests/integration/editor-area-conflict-swap.test.ts b/packages/app/tests/integration/editor-area-conflict-swap.test.ts
index 7666edb1b..246d5fb51 100644
--- a/packages/app/tests/integration/editor-area-conflict-swap.test.ts
+++ b/packages/app/tests/integration/editor-area-conflict-swap.test.ts
@@ -18,9 +18,10 @@
* endpoint — requires a real `git merge` in progress and is covered by the
* sync-engine boundary tests, not here.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTestClient, createTestServer, pollUntil, type TestServer } from './test-harness';
const BASE_CONTENT = '# Base\n\nBase paragraph.\n';
diff --git a/packages/app/tests/integration/empty-folder-visibility.test.ts b/packages/app/tests/integration/empty-folder-visibility.test.ts
index 452c8a7a0..bd995a5f8 100644
--- a/packages/app/tests/integration/empty-folder-visibility.test.ts
+++ b/packages/app/tests/integration/empty-folder-visibility.test.ts
@@ -10,11 +10,11 @@
* file-watcher.test.ts).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer, wait } from './test-harness';
diff --git a/packages/app/tests/integration/exhaustiveness-coverage.test.ts b/packages/app/tests/integration/exhaustiveness-coverage.test.ts
index cb2a72be9..987b8f94a 100644
--- a/packages/app/tests/integration/exhaustiveness-coverage.test.ts
+++ b/packages/app/tests/integration/exhaustiveness-coverage.test.ts
@@ -19,7 +19,7 @@
* least one case label must be unique to this DU — disambiguates from other
* DUs that share kind names like `'doc'`).
*/
-import { describe, expect, test } from 'bun:test';
+
import { join, relative, resolve } from 'node:path';
import { ProblemTypeSchema } from '@inkeep/open-knowledge-core';
import {
@@ -31,6 +31,7 @@ import {
type SwitchStatement,
SyntaxKind,
} from 'ts-morph';
+import { describe, expect, test } from 'vitest';
// All ProblemType URN tokens are unique to ProblemType (every member starts
// with `urn:ok:error:`), so variantLabels and uniqueLabels are the same set.
diff --git a/packages/app/tests/integration/external-change-stale-anchor-interleave.test.ts b/packages/app/tests/integration/external-change-stale-anchor-interleave.test.ts
index 47cf47134..c39adc41c 100644
--- a/packages/app/tests/integration/external-change-stale-anchor-interleave.test.ts
+++ b/packages/app/tests/integration/external-change-stale-anchor-interleave.test.ts
@@ -18,11 +18,11 @@
* Per-test docName isolation; client lifecycle in try/finally.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { applyExternalChange } from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/external-edit-stale-client.test.ts b/packages/app/tests/integration/external-edit-stale-client.test.ts
index 8f5f3edb3..075077d8a 100644
--- a/packages/app/tests/integration/external-edit-stale-client.test.ts
+++ b/packages/app/tests/integration/external-edit-stale-client.test.ts
@@ -24,10 +24,10 @@
* trips this red.
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
clientIdsInDoc,
diff --git a/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts b/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts
index 51f9a0b89..77c594dfa 100644
--- a/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts
+++ b/packages/app/tests/integration/fullscreen-overlay-safe-area-coverage.test.ts
@@ -36,9 +36,9 @@
* scanners. Fast, no I/O beyond filesystem walk, deterministic in headless CI.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const APP_SRC = join(import.meta.dir, '..', '..', 'src');
const REPO_RELATIVE_PREFIX = 'packages/app/src';
diff --git a/packages/app/tests/integration/global-skill-bundle-graph.test.ts b/packages/app/tests/integration/global-skill-bundle-graph.test.ts
index ee97b83fa..103ccd1f9 100644
--- a/packages/app/tests/integration/global-skill-bundle-graph.test.ts
+++ b/packages/app/tests/integration/global-skill-bundle-graph.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createTestServer, type TestServer } from './test-harness.ts';
/**
diff --git a/packages/app/tests/integration/hook-timeout-stop-rules.test.ts b/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
index b3d13e886..f95ead4a6 100644
--- a/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
+++ b/packages/app/tests/integration/hook-timeout-stop-rules.test.ts
@@ -39,10 +39,10 @@
*
*/
-import { describe, expect, test } from 'bun:test';
import { type Dirent, readdirSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import ts from 'typescript';
+import { describe, expect, test } from 'vitest';
const REPO_ROOT = join(import.meta.dirname, '..', '..', '..', '..');
const SCANNED_DIRS = [import.meta.dirname, join(import.meta.dirname, '..', 'conversion')];
diff --git a/packages/app/tests/integration/idb-preload.ts b/packages/app/tests/integration/idb-preload.ts
index d7f2373c5..07256e26b 100644
--- a/packages/app/tests/integration/idb-preload.ts
+++ b/packages/app/tests/integration/idb-preload.ts
@@ -1,5 +1,5 @@
import 'fake-indexeddb/auto';
-import { afterEach } from 'bun:test';
+import { afterEach } from 'vitest';
// Global afterEach hook: wipe every `ok-ydoc:` IDB database after each
// test. fake-indexeddb persists state across tests within a single bun
diff --git a/packages/app/tests/integration/idle-shutdown-multi-client.test.ts b/packages/app/tests/integration/idle-shutdown-multi-client.test.ts
index 987727a2a..54da3d709 100644
--- a/packages/app/tests/integration/idle-shutdown-multi-client.test.ts
+++ b/packages/app/tests/integration/idle-shutdown-multi-client.test.ts
@@ -6,7 +6,6 @@
* deferred to process exit).
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -27,6 +26,7 @@ import {
ConfigSchema,
ensureProjectGit,
} from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { waitForSync } from './test-harness.ts';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 74ff661c4..5fa0a814f 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -20,9 +20,9 @@
*
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/ipc-exhaustiveness-coverage.test.ts b/packages/app/tests/integration/ipc-exhaustiveness-coverage.test.ts
index 63247b3b5..a8116e457 100644
--- a/packages/app/tests/integration/ipc-exhaustiveness-coverage.test.ts
+++ b/packages/app/tests/integration/ipc-exhaustiveness-coverage.test.ts
@@ -41,7 +41,6 @@
* Future IPC DU additions extend the REGISTRY here.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import {
@@ -53,6 +52,7 @@ import {
type SwitchStatement,
SyntaxKind,
} from 'ts-morph';
+import { describe, expect, test } from 'vitest';
const REPO_ROOT = resolve(import.meta.dirname, '../../../..');
const SCAN_ROOTS = [join(REPO_ROOT, 'packages/core/src'), join(REPO_ROOT, 'packages/app/src')];
diff --git a/packages/app/tests/integration/ipc-log-coverage.test.ts b/packages/app/tests/integration/ipc-log-coverage.test.ts
index 2d54dc6d9..c15fc0b6e 100644
--- a/packages/app/tests/integration/ipc-log-coverage.test.ts
+++ b/packages/app/tests/integration/ipc-log-coverage.test.ts
@@ -32,7 +32,6 @@
* to a boundary handler that owns the structured-log emission.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import {
@@ -43,6 +42,7 @@ import {
type SourceFile,
SyntaxKind,
} from 'ts-morph';
+import { describe, expect, test } from 'vitest';
const REPO_ROOT = resolve(import.meta.dirname, '../../../..');
const MAIN_ROOT = join(REPO_ROOT, 'packages/desktop/src/main');
diff --git a/packages/app/tests/integration/jsx-interior-paste.test.ts b/packages/app/tests/integration/jsx-interior-paste.test.ts
index 67c4f0e97..293d897f0 100644
--- a/packages/app/tests/integration/jsx-interior-paste.test.ts
+++ b/packages/app/tests/integration/jsx-interior-paste.test.ts
@@ -28,13 +28,13 @@
* works around).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { EditorState, TextSelection, type Transaction } from '@tiptap/pm/state';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { mdManager, schema } from './test-harness';
// paste-failure-toast pulls in sonner; stub it so module load + any
// degradation path is inert in the node test runtime.
-mock.module('sonner', () => ({ toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ toast: { error: vi.fn(() => {}) } }));
// Imported after the sonner mock so the dispatcher's transitive sonner import
// resolves to the stub.
diff --git a/packages/app/tests/integration/jsx-isolating-join.test.ts b/packages/app/tests/integration/jsx-isolating-join.test.ts
index 8da10bb74..e284890b2 100644
--- a/packages/app/tests/integration/jsx-isolating-join.test.ts
+++ b/packages/app/tests/integration/jsx-isolating-join.test.ts
@@ -21,7 +21,6 @@
* command directly removes that confound.
*/
-import { describe, expect, test } from 'bun:test';
import {
joinBackward,
joinForward,
@@ -29,6 +28,7 @@ import {
selectNodeForward,
} from '@tiptap/pm/commands';
import { EditorState, NodeSelection, TextSelection } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import { mdManager, schema } from './test-harness';
type PmCommand = (state: EditorState, dispatch?: (tr: EditorState['tr']) => void) => boolean;
diff --git a/packages/app/tests/integration/jsx-schema-narrowing-safety.test.ts b/packages/app/tests/integration/jsx-schema-narrowing-safety.test.ts
index 638f0c6aa..e899ff213 100644
--- a/packages/app/tests/integration/jsx-schema-narrowing-safety.test.ts
+++ b/packages/app/tests/integration/jsx-schema-narrowing-safety.test.ts
@@ -17,8 +17,8 @@
* stale pre-widening / pre-narrowing shapes present.
*/
-import { describe, expect, test } from 'bun:test';
import { initProseMirrorDoc } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { schema } from './test-harness';
diff --git a/packages/app/tests/integration/jsx-undo-roundtrip.test.ts b/packages/app/tests/integration/jsx-undo-roundtrip.test.ts
index cb0d2a475..2016539ba 100644
--- a/packages/app/tests/integration/jsx-undo-roundtrip.test.ts
+++ b/packages/app/tests/integration/jsx-undo-roundtrip.test.ts
@@ -16,9 +16,9 @@
* so writes are spaced >500ms apart to land as distinct StackItems.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentUndo,
diff --git a/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts b/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts
index c6090e9fe..c8922e68b 100644
--- a/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts
+++ b/packages/app/tests/integration/jsx-unregistered-cell-flatten-loss.test.ts
@@ -33,10 +33,10 @@
* the paste runs the production dispatcher into the gate's filterTransaction.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
import { sharedExtensions } from '@inkeep/open-knowledge-core';
import { Editor, type JSONContent } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
import { CellInsertionGate } from '../../src/editor/extensions/cell-insertion-gate';
import { installDomGlobals } from '../../src/editor/walk-currency-test-harness';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
@@ -47,7 +47,7 @@ import { mdManager, schema } from './test-harness';
// degrades, so the stub is never invoked. The dispatcher factory is
// dynamic-imported in beforeAll so the stub is registered before its module
// graph evaluates.
-mock.module('sonner', () => ({ toast: { error: mock(() => {}) } }));
+vi.doMock('sonner', () => ({ toast: { error: vi.fn(() => {}) } }));
// Bound by the beforeAll dynamic import, after the sonner stub is registered.
let createHandlePaste: typeof import('../../src/editor/clipboard/handle-paste.ts').createHandlePaste;
diff --git a/packages/app/tests/integration/jsx-unregistered-rawbox-undo-characterization.test.ts b/packages/app/tests/integration/jsx-unregistered-rawbox-undo-characterization.test.ts
index e02efac08..e652c8b8d 100644
--- a/packages/app/tests/integration/jsx-unregistered-rawbox-undo-characterization.test.ts
+++ b/packages/app/tests/integration/jsx-unregistered-rawbox-undo-characterization.test.ts
@@ -34,8 +34,8 @@
* agent undo neither reverts it nor corrupts it.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { agentUndo, agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/jsx-unregistered-redo-characterization.test.ts b/packages/app/tests/integration/jsx-unregistered-redo-characterization.test.ts
index 8f089704c..1fd29a12e 100644
--- a/packages/app/tests/integration/jsx-unregistered-redo-characterization.test.ts
+++ b/packages/app/tests/integration/jsx-unregistered-redo-characterization.test.ts
@@ -21,9 +21,9 @@
* call `um.redo()`; that is the finding this test records.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentUndo,
diff --git a/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts b/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts
index 778a1abd3..67904fec4 100644
--- a/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts
+++ b/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts
@@ -33,9 +33,9 @@
* canonical home for block-level keyboard contract).
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
const KEYBOARD_NAV_PATH = resolve(import.meta.dirname, '../../src/editor/block-ux/keyboard-nav.ts');
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index db210a2a7..aa0ea2a3d 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -28,9 +28,9 @@
*
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/keystroke-granularity.test.ts b/packages/app/tests/integration/keystroke-granularity.test.ts
index e759d0f79..09b28f85f 100644
--- a/packages/app/tests/integration/keystroke-granularity.test.ts
+++ b/packages/app/tests/integration/keystroke-granularity.test.ts
@@ -19,8 +19,8 @@
* suites settle exactly once.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/lazy-continuation-tolerance.test.ts b/packages/app/tests/integration/lazy-continuation-tolerance.test.ts
index b08f3e333..608ffc192 100644
--- a/packages/app/tests/integration/lazy-continuation-tolerance.test.ts
+++ b/packages/app/tests/integration/lazy-continuation-tolerance.test.ts
@@ -13,8 +13,9 @@
* split-brain telemetry; the fuzz harness classified it `stalled`; a
* cross-generation merge could even DUPLICATE the residual block).
*/
-import { describe, expect, test } from 'bun:test';
+
import { setTimeout as wait } from 'node:timers/promises';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/link-authoring-contract.test.ts b/packages/app/tests/integration/link-authoring-contract.test.ts
index f1914d20c..a993a9fea 100644
--- a/packages/app/tests/integration/link-authoring-contract.test.ts
+++ b/packages/app/tests/integration/link-authoring-contract.test.ts
@@ -8,10 +8,11 @@
* BacklinkIndex — so the assertions deliberately read the write response
* directly with no quiescence flush (freshness).
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { awaitFileWatcherIndexed, createTestServer, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/link-graph-metadata.test.ts b/packages/app/tests/integration/link-graph-metadata.test.ts
index 26cd3a1fb..f65dcb9da 100644
--- a/packages/app/tests/integration/link-graph-metadata.test.ts
+++ b/packages/app/tests/integration/link-graph-metadata.test.ts
@@ -3,11 +3,11 @@
* on doc nodes when present.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/lint-config-cascade.test.ts b/packages/app/tests/integration/lint-config-cascade.test.ts
index 7f6ef3ff8..81273376e 100644
--- a/packages/app/tests/integration/lint-config-cascade.test.ts
+++ b/packages/app/tests/integration/lint-config-cascade.test.ts
@@ -7,10 +7,10 @@
* config.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { DEFAULT_MARKDOWNLINT_CONFIG } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/lint-http.test.ts b/packages/app/tests/integration/lint-http.test.ts
index 469fd83ee..70407a7db 100644
--- a/packages/app/tests/integration/lint-http.test.ts
+++ b/packages/app/tests/integration/lint-http.test.ts
@@ -9,7 +9,6 @@
* effect) — the write/read internals are free to evolve underneath.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import {
@@ -22,6 +21,7 @@ import {
type LintFixResult,
LintFixResultSchema,
} from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/lint-symlink-escape.test.ts b/packages/app/tests/integration/lint-symlink-escape.test.ts
index 8c11881c2..cdb043e37 100644
--- a/packages/app/tests/integration/lint-symlink-escape.test.ts
+++ b/packages/app/tests/integration/lint-symlink-escape.test.ts
@@ -7,10 +7,10 @@
* `?doc=` accepts an extension-carrying docName.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts b/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts
index a656df1ba..8314ffe47 100644
--- a/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts
+++ b/packages/app/tests/integration/local-op-auth-login-cancel-reopen.test.ts
@@ -21,10 +21,10 @@
* window; the slow-die child makes the defect deterministic.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTestServer, pollUntil, type TestServer, wait } from './test-harness';
// Fake device-flow CLI: ignores the appended `auth login --json --host ...`
diff --git a/packages/app/tests/integration/loopback-bind-discipline.test.ts b/packages/app/tests/integration/loopback-bind-discipline.test.ts
index 7a1dfae4c..24f7ea3d4 100644
--- a/packages/app/tests/integration/loopback-bind-discipline.test.ts
+++ b/packages/app/tests/integration/loopback-bind-discipline.test.ts
@@ -31,10 +31,10 @@
* test cache invalidates with its own sources.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { basename, dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PACKAGE_ROOT = join(__dirname, '..', '..');
diff --git a/packages/app/tests/integration/loopback-exclusivity.test.ts b/packages/app/tests/integration/loopback-exclusivity.test.ts
index 236cf6a29..c243ecd88 100644
--- a/packages/app/tests/integration/loopback-exclusivity.test.ts
+++ b/packages/app/tests/integration/loopback-exclusivity.test.ts
@@ -26,8 +26,8 @@
* packages/server/src/rig-loopback-exclusivity.test.ts.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { createServer } from 'node:http';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTestServer } from './test-harness';
diff --git a/packages/app/tests/integration/managed-artifact-doc.test.ts b/packages/app/tests/integration/managed-artifact-doc.test.ts
index 546850ed0..a061803a5 100644
--- a/packages/app/tests/integration/managed-artifact-doc.test.ts
+++ b/packages/app/tests/integration/managed-artifact-doc.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createTestClient, createTestServer, type TestServer } from './test-harness.ts';
/**
diff --git a/packages/app/tests/integration/managed-rename-crash-recovery.test.ts b/packages/app/tests/integration/managed-rename-crash-recovery.test.ts
index 514b031d0..ba15f40db 100644
--- a/packages/app/tests/integration/managed-rename-crash-recovery.test.ts
+++ b/packages/app/tests/integration/managed-rename-crash-recovery.test.ts
@@ -20,10 +20,11 @@
* 5. Assert: source docs restored, dest docs removed, empty ancestor dirs
* pruned, journal cleared, sibling-source backlinks unchanged.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
createManagedRenameRecoveryJournal,
managedRenameJournalPath,
diff --git a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
index e33256b9b..77f5dd417 100644
--- a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
+++ b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
@@ -12,10 +12,11 @@
* - bridge invariant holds (Y.Text and XmlFragment converge through the
* server-authoritative observer A path; precedent #14)
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { createMultiClientContext, createRestartableServer, pollUntil } from './test-harness';
const cleanups: Array<() => Promise<void> | void> = [];
diff --git a/packages/app/tests/integration/managed-rename-populated-target.test.ts b/packages/app/tests/integration/managed-rename-populated-target.test.ts
index fda750e79..e9fa2a9ba 100644
--- a/packages/app/tests/integration/managed-rename-populated-target.test.ts
+++ b/packages/app/tests/integration/managed-rename-populated-target.test.ts
@@ -16,10 +16,11 @@
*
* Expected: PASS. API returns 409; no content mutation on either client.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { createMultiClientContext, createRestartableServer, pollUntil } from './test-harness';
const SOURCE_CONTENT = `# Source Doc
diff --git a/packages/app/tests/integration/map-driven-observer-a-crdt.test.ts b/packages/app/tests/integration/map-driven-observer-a-crdt.test.ts
index 57d7930d1..e4e6f8e58 100644
--- a/packages/app/tests/integration/map-driven-observer-a-crdt.test.ts
+++ b/packages/app/tests/integration/map-driven-observer-a-crdt.test.ts
@@ -11,8 +11,8 @@
* (no client's splice clobbers the other's).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/mcp-http.test.ts b/packages/app/tests/integration/mcp-http.test.ts
index 6efbe6f60..f0f1ad1e2 100644
--- a/packages/app/tests/integration/mcp-http.test.ts
+++ b/packages/app/tests/integration/mcp-http.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test';
+import { expect, test } from 'vitest';
import { createTestServer } from './test-harness';
const MCP_PROTOCOL_VERSION = '2025-06-18';
diff --git a/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
index 892e055da..bbbbda1cd 100644
--- a/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
+++ b/packages/app/tests/integration/mcp-move-real-roundtrip.test.ts
@@ -19,10 +19,11 @@
* response carries the renamed[] / rewrittenDocs[] / previewUrls{}
* (folder) or previewUrl (file) shape consumers depend on.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ConfigSchema } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { register as registerMove } from '../../../server/src/mcp/tools/move';
import type { ServerInstance } from '../../../server/src/mcp/tools/shared';
import { awaitFileWatcherIndexed, createRestartableServer } from './test-harness';
diff --git a/packages/app/tests/integration/mcp-session-identity.test.ts b/packages/app/tests/integration/mcp-session-identity.test.ts
index 201cf0905..3331e399d 100644
--- a/packages/app/tests/integration/mcp-session-identity.test.ts
+++ b/packages/app/tests/integration/mcp-session-identity.test.ts
@@ -18,10 +18,10 @@
* to that model.
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { setTimeout as wait } from 'node:timers/promises';
import { toBroadcasterKey } from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import type { EffectValue } from '../../../../packages/server/src/activity-log.ts';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestClient, createTestServer, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/mcp-write-extension.test.ts b/packages/app/tests/integration/mcp-write-extension.test.ts
index 3381dbb30..6d997669d 100644
--- a/packages/app/tests/integration/mcp-write-extension.test.ts
+++ b/packages/app/tests/integration/mcp-write-extension.test.ts
@@ -9,10 +9,11 @@
* declared `extension` field reaches disk, and that it wins over a suffix typed
* into `path`.
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
diff --git a/packages/app/tests/integration/mdx-extension.test.ts b/packages/app/tests/integration/mdx-extension.test.ts
index 50f3c9055..a039287e7 100644
--- a/packages/app/tests/integration/mdx-extension.test.ts
+++ b/packages/app/tests/integration/mdx-extension.test.ts
@@ -8,10 +8,11 @@
* would be invisible to the watcher, and a write-back would create a sibling
* `.md` file instead of updating the `.mdx` source.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/microcopy-ellipsis.test.ts b/packages/app/tests/integration/microcopy-ellipsis.test.ts
index b170b2e08..d55b47b88 100644
--- a/packages/app/tests/integration/microcopy-ellipsis.test.ts
+++ b/packages/app/tests/integration/microcopy-ellipsis.test.ts
@@ -21,9 +21,9 @@
* interface (`biome check`) → observable outcome (diagnostic count).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';
// __dirname → packages/app/tests/integration/. Repo root is 4 levels up.
diff --git a/packages/app/tests/integration/mid-drain-restart.test.ts b/packages/app/tests/integration/mid-drain-restart.test.ts
index c7da748be..4aa26bf6f 100644
--- a/packages/app/tests/integration/mid-drain-restart.test.ts
+++ b/packages/app/tests/integration/mid-drain-restart.test.ts
@@ -21,10 +21,11 @@
* Expected: PASS. Content durable on disk; client Y.Doc reflects content
* once after reconnect.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/mock-module-completeness.test.ts b/packages/app/tests/integration/mock-module-completeness.test.ts
index bd1d2d453..326c8ca14 100644
--- a/packages/app/tests/integration/mock-module-completeness.test.ts
+++ b/packages/app/tests/integration/mock-module-completeness.test.ts
@@ -1,22 +1,17 @@
/**
- * Meta-test: every `mock.module` factory in a plain (non-.dom) app test file
+ * Meta-test: every `vi.doMock` factory in a plain (non-.dom) app test file
* must spread the real module (`...actual`) or carry an explicit allowlist
* entry below.
*
- * Bun's `mock.module` registry is process-global and never restored between
- * test files (oven-sh/bun#12823 closed-as-intended). When a factory registers
- * BEFORE the real module loads, the registry entry's export table contains
- * ONLY the factory's keys — any later file importing an omitted export hits a
- * link error naming the REAL file path. Failure order follows the runner
- * filesystem's readdir order: deterministic per job (defeating fresh-process
- * flake retries), re-rolled per runner. Detonation case: a partial
+ * When a factory registers before the real module loads, its export table
+ * contains only the factory's keys. A later import of an omitted export within
+ * the same test module graph then fails during linking. Detonation case: a partial
* `@/editor/DocumentContext` mock (1 of its exports) broke
* `EditorArea.test.ts`'s module-load smoke on two PR runs while passing
* everywhere else.
*
- * The spread-real pattern fixes both halves: the static import pre-loads the
- * real module (so bun mutates the namespace in place instead of synthesizing
- * a partial one), and the spread keeps every unmocked export bound.
+ * The spread-real pattern keeps every unmocked export bound while preserving
+ * the targeted override.
*
* Scope: plain `*.test.ts(x)` under src/ — the files sharing the unit-task
* process. `*.dom.test.tsx` files run in the separate test:dom process and
@@ -24,9 +19,9 @@
* tracked (App.dom.test.tsx alone holds ~23 factories).
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
+import { describe, expect, test } from 'vitest';
const APP_ROOT = join(import.meta.dir, '..', '..');
@@ -43,13 +38,13 @@ const ALLOWLIST: Record<string, string> = {
'value export consumed by plain tests in this process.',
};
-function extractMockModuleCalls(src: string): Array<{ specifier: string; factory: string }> {
+function extractDoMockCalls(src: string): Array<{ specifier: string; factory: string }> {
const calls: Array<{ specifier: string; factory: string }> = [];
- const re = /mock\.module\(\s*(['"])([^'"]+)\1\s*,/g;
+ const re = /vi\.doMock\(\s*(['"])([^'"]+)\1\s*,/g;
let m: RegExpExecArray | null = re.exec(src);
while (m !== null) {
// Capture the factory body: scan forward to the matching close of the
- // mock.module(...) call by paren depth. Good enough for the repo's
+ // vi.doMock(...) call by paren depth. Good enough for the repo's
// factory shapes (object-literal arrow functions).
let depth = 1;
let i = re.lastIndex;
@@ -75,7 +70,7 @@ function factoryHasActualSpread(factory: string): boolean {
return /\.\.\.\s*actual[A-Za-z_$]?[\w$]*/.test(factory);
}
-describe('mock.module factory completeness (process-global leak guard)', () => {
+describe('vi.doMock factory completeness', () => {
test('every plain-test factory spreads the real module or is allowlisted', async () => {
const glob = new Bun.Glob('src/**/*.test.{ts,tsx}');
const violations: string[] = [];
@@ -84,8 +79,8 @@ describe('mock.module factory completeness (process-global leak guard)', () => {
const abs = join(APP_ROOT, file);
const rel = relative(APP_ROOT, abs);
const src = readFileSync(abs, 'utf-8');
- if (!src.includes('mock.module(')) continue;
- for (const call of extractMockModuleCalls(src)) {
+ if (!src.includes('vi.doMock(')) continue;
+ for (const call of extractDoMockCalls(src)) {
const hasSpread = factoryHasActualSpread(call.factory);
const allowKey = `${rel}::${call.specifier}`;
if (!hasSpread && !(allowKey in ALLOWLIST)) {
@@ -108,16 +103,16 @@ describe('guard self-test (bidirectional + planted-positive)', () => {
// over-fire (adjacent negatives), exercising the SAME functions the guard
// uses so the two cannot drift apart.
- test('extractMockModuleCalls: finds every call (planted-positive), nothing in clean source', () => {
+ test('extractDoMockCalls: finds every call (planted-positive), nothing in clean source', () => {
const twoCalls = [
- "mock.module('sonner', () => ({ toast }));",
- "mock.module('@/editor/DocumentContext', () => ({ useDocumentContext: () => ({}) }));",
+ "vi.doMock('sonner', () => ({ toast }));",
+ "vi.doMock('@/editor/DocumentContext', () => ({ useDocumentContext: () => ({}) }));",
].join('\n');
- expect(extractMockModuleCalls(twoCalls).map((c) => c.specifier)).toEqual([
+ expect(extractDoMockCalls(twoCalls).map((c) => c.specifier)).toEqual([
'sonner',
'@/editor/DocumentContext',
]);
- expect(extractMockModuleCalls('const x = 1; await import("./y");')).toEqual([]);
+ expect(extractDoMockCalls('const x = 1; await import("./y");')).toEqual([]);
});
test('factoryHasActualSpread: accepts ...actual* spreads (must-fire-true)', () => {
@@ -141,10 +136,10 @@ describe('guard self-test (bidirectional + planted-positive)', () => {
test('end-to-end: a partial factory is flagged, an ...actual factory is not', () => {
const flagged = (src: string) =>
- extractMockModuleCalls(src).filter((c) => !factoryHasActualSpread(c.factory)).length;
- expect(flagged("mock.module('sonner', () => ({ toast: { error() {} } }));")).toBe(1);
+ extractDoMockCalls(src).filter((c) => !factoryHasActualSpread(c.factory)).length;
+ expect(flagged("vi.doMock('sonner', () => ({ toast: { error() {} } }));")).toBe(1);
expect(
- flagged("mock.module('sonner', () => ({ ...actualSonner, toast: { error() {} } }));"),
+ flagged("vi.doMock('sonner', () => ({ ...actualSonner, toast: { error() {} } }));"),
).toBe(0);
});
});
diff --git a/packages/app/tests/integration/multi-agent-presence.test.ts b/packages/app/tests/integration/multi-agent-presence.test.ts
index b5597dd39..669e1c6b3 100644
--- a/packages/app/tests/integration/multi-agent-presence.test.ts
+++ b/packages/app/tests/integration/multi-agent-presence.test.ts
@@ -18,12 +18,12 @@
* pre-existing gap where the simple handler did not populate presence
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
// toBroadcasterKey is the canonical raw-id → map-key transform; importing
// from the server package rather than re-declaring it locally keeps this
// test aligned with the production `extractAgentIdentity` contract. If
// the server ever changes the prefix, this test follows automatically.
import { toBroadcasterKey } from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { fetchWithHostHeader } from './host-header-request.test-helper';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts b/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts
index 9fd276cf1..2611bd868 100644
--- a/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts
+++ b/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts
@@ -11,7 +11,7 @@
* the no-edit control pins the byte-sacred write path itself.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/no-sync-set-enabled-references.test.ts b/packages/app/tests/integration/no-sync-set-enabled-references.test.ts
index 3ee0e580b..5da69de1a 100644
--- a/packages/app/tests/integration/no-sync-set-enabled-references.test.ts
+++ b/packages/app/tests/integration/no-sync-set-enabled-references.test.ts
@@ -13,9 +13,9 @@
* the filesystem walk.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const APP_SRC = join(import.meta.dir, '..', '..', 'src');
diff --git a/packages/app/tests/integration/no-unportaled-editor-content.test.ts b/packages/app/tests/integration/no-unportaled-editor-content.test.ts
index 0e1e6f03f..ad0758506 100644
--- a/packages/app/tests/integration/no-unportaled-editor-content.test.ts
+++ b/packages/app/tests/integration/no-unportaled-editor-content.test.ts
@@ -18,9 +18,9 @@
* interface (`biome check`) → observable outcome (diagnostic count).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';
// __dirname → packages/app/tests/integration/. Repo root is 4 levels up.
diff --git a/packages/app/tests/integration/per-session-um-perf.test.ts b/packages/app/tests/integration/per-session-um-perf.test.ts
index c2d187ed7..79b0233e5 100644
--- a/packages/app/tests/integration/per-session-um-perf.test.ts
+++ b/packages/app/tests/integration/per-session-um-perf.test.ts
@@ -10,7 +10,7 @@
* `bunx turbo run test:perf:sessions`. Not part of `bun run check` (tier 1).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import type { TestServer } from './test-harness';
import { createTestServer } from './test-harness';
diff --git a/packages/app/tests/integration/perf-substrate-canary.test.ts b/packages/app/tests/integration/perf-substrate-canary.test.ts
index f43fbe8bc..87702bbc2 100644
--- a/packages/app/tests/integration/perf-substrate-canary.test.ts
+++ b/packages/app/tests/integration/perf-substrate-canary.test.ts
@@ -18,7 +18,7 @@
* pins them so any regression fails CI in seconds rather
* than waiting for a perf run.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { mark } from '../../src/lib/perf';
import {
__resetCardinalityWarnings,
diff --git a/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts b/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts
index e00d1668c..d73127660 100644
--- a/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts
+++ b/packages/app/tests/integration/persistence-failure-surfacing-handlers.test.ts
@@ -9,8 +9,9 @@
* surfacing path through the production server boot. Sibling of
* `persistence-failure-surfacing.test.ts` (which covers agent-write-md).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
+import { afterEach, describe, expect, test } from 'vitest';
import {
agentPatch,
agentWriteMd,
diff --git a/packages/app/tests/integration/persistence-failure-surfacing.test.ts b/packages/app/tests/integration/persistence-failure-surfacing.test.ts
index 3b6aeefa9..9ea71407b 100644
--- a/packages/app/tests/integration/persistence-failure-surfacing.test.ts
+++ b/packages/app/tests/integration/persistence-failure-surfacing.test.ts
@@ -12,8 +12,9 @@
* separate validation concern), exercising the real persistence → flush →
* surfacing path through the production server boot.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTestServer, type TestServer } from './test-harness.ts';
let server: TestServer | undefined;
diff --git a/packages/app/tests/integration/persistence-fan-out.test.ts b/packages/app/tests/integration/persistence-fan-out.test.ts
index 652241c1d..e1d1efede 100644
--- a/packages/app/tests/integration/persistence-fan-out.test.ts
+++ b/packages/app/tests/integration/persistence-fan-out.test.ts
@@ -10,7 +10,6 @@
* compiled artifact surface at integration tier (not just server unit tier).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -23,6 +22,7 @@ import {
shadowGit,
swapContributors,
} from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
describe('persistence L2 fan-out integration (US-014, FR-7)', () => {
diff --git a/packages/app/tests/integration/populated-idb-stale-server.test.ts b/packages/app/tests/integration/populated-idb-stale-server.test.ts
index cf09e6829..f299eb5b1 100644
--- a/packages/app/tests/integration/populated-idb-stale-server.test.ts
+++ b/packages/app/tests/integration/populated-idb-stale-server.test.ts
@@ -21,10 +21,11 @@
* open, newly populated with only the current server's state.
*
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { ProviderPool } from '../../src/editor/provider-pool';
import { createRestartableServer, pollUntil, seedClientPersistenceState } from './test-harness';
diff --git a/packages/app/tests/integration/presence-multi-tab.test.ts b/packages/app/tests/integration/presence-multi-tab.test.ts
index 1b0643eff..c0c8ed174 100644
--- a/packages/app/tests/integration/presence-multi-tab.test.ts
+++ b/packages/app/tests/integration/presence-multi-tab.test.ts
@@ -10,8 +10,8 @@
* conventions. Never hardcodes 'test-doc' — every docName is a random UUID.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import type { HocuspocusProvider } from '@hocuspocus/provider';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import type { AwarenessUser } from '../../src/presence/identity';
import {
dedupeHumansByPrincipalId,
diff --git a/packages/app/tests/integration/principal-endpoint.test.ts b/packages/app/tests/integration/principal-endpoint.test.ts
index ef641785b..12113f5b1 100644
--- a/packages/app/tests/integration/principal-endpoint.test.ts
+++ b/packages/app/tests/integration/principal-endpoint.test.ts
@@ -21,8 +21,8 @@
* produces a principal at boot.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PrincipalSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { fetchWithHostHeader } from './host-header-request.test-helper';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 8bb2273a6..9b407c113 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -15,9 +15,9 @@
*
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/provider-pool-buffer-replay.test.ts b/packages/app/tests/integration/provider-pool-buffer-replay.test.ts
index 20f4325ea..6b78a4eef 100644
--- a/packages/app/tests/integration/provider-pool-buffer-replay.test.ts
+++ b/packages/app/tests/integration/provider-pool-buffer-replay.test.ts
@@ -20,10 +20,10 @@
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { captureStateVector, computeUnsyncedUpdate } from '../../src/editor/client-persistence';
import { ProviderPool } from '../../src/editor/provider-pool';
import { createRestartableServer, pollUntil, seedPoolServerInstanceId } from './test-harness';
diff --git a/packages/app/tests/integration/provider-pool-multi-client-restart.test.ts b/packages/app/tests/integration/provider-pool-multi-client-restart.test.ts
index 796bf8a12..4d2b289b0 100644
--- a/packages/app/tests/integration/provider-pool-multi-client-restart.test.ts
+++ b/packages/app/tests/integration/provider-pool-multi-client-restart.test.ts
@@ -16,10 +16,10 @@
* reintroduction of the multi-client restart duplication trips this red.
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import {
assertNoClientIdDrift,
clientIdsInDoc,
diff --git a/packages/app/tests/integration/provider-pool-reconnect.test.ts b/packages/app/tests/integration/provider-pool-reconnect.test.ts
index 120c5cb29..9825e06c7 100644
--- a/packages/app/tests/integration/provider-pool-reconnect.test.ts
+++ b/packages/app/tests/integration/provider-pool-reconnect.test.ts
@@ -1,8 +1,8 @@
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
assertNoClientIdDrift,
diff --git a/packages/app/tests/integration/raw-mdx-fallback-multi-client.test.ts b/packages/app/tests/integration/raw-mdx-fallback-multi-client.test.ts
index af7892d78..9f2777840 100644
--- a/packages/app/tests/integration/raw-mdx-fallback-multi-client.test.ts
+++ b/packages/app/tests/integration/raw-mdx-fallback-multi-client.test.ts
@@ -21,10 +21,10 @@
* suspended until the content becomes valid again. This is by design.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/removal-phantom-resurrection.test.ts b/packages/app/tests/integration/removal-phantom-resurrection.test.ts
index 154bc8466..4e6a3e343 100644
--- a/packages/app/tests/integration/removal-phantom-resurrection.test.ts
+++ b/packages/app/tests/integration/removal-phantom-resurrection.test.ts
@@ -32,7 +32,6 @@
* concurrently within a process, shared docNames cross-pollinate).
*/
-import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -49,6 +48,7 @@ import {
parseAuthRejectionWire,
resetMetrics,
} from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/rename-history.test.ts b/packages/app/tests/integration/rename-history.test.ts
index 4ba2598bc..c0cfb4f1a 100644
--- a/packages/app/tests/integration/rename-history.test.ts
+++ b/packages/app/tests/integration/rename-history.test.ts
@@ -15,10 +15,11 @@
* `packages/server/src/api-rename-crash-injection.test.ts` — they exercise
* the exact ordering invariant + boot recovery + sweepLazyPopOrphans path.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { resolveShadowDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { afterEach, describe, expect, test } from 'vitest';
import {
loadRenameLogIndex,
type RenameLogEntry,
diff --git a/packages/app/tests/integration/rename-write-amplification.test.ts b/packages/app/tests/integration/rename-write-amplification.test.ts
index 8c95fb25b..c13e5b5a6 100644
--- a/packages/app/tests/integration/rename-write-amplification.test.ts
+++ b/packages/app/tests/integration/rename-write-amplification.test.ts
@@ -39,7 +39,6 @@
* for the same cross-file leak class.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { getMetrics, resetMetrics } from '@inkeep/open-knowledge-server';
@@ -50,6 +49,7 @@ import {
type ReadableSpan,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
awaitFileWatcherIndexed,
createTestClient,
diff --git a/packages/app/tests/integration/restart-with-embed-doc.test.ts b/packages/app/tests/integration/restart-with-embed-doc.test.ts
index a0012d16e..d0738a40c 100644
--- a/packages/app/tests/integration/restart-with-embed-doc.test.ts
+++ b/packages/app/tests/integration/restart-with-embed-doc.test.ts
@@ -30,12 +30,12 @@
* sequence; this file disambiguates via descriptive `describe()` label.)
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
createRestartableServer,
diff --git a/packages/app/tests/integration/rollback-multi-client.test.ts b/packages/app/tests/integration/rollback-multi-client.test.ts
index ab921804d..ec0078175 100644
--- a/packages/app/tests/integration/rollback-multi-client.test.ts
+++ b/packages/app/tests/integration/rollback-multi-client.test.ts
@@ -17,10 +17,11 @@
* If this test FAILS, the hypothesis that structural-diff paths are safe is
* wrong, and the fix scope expands to cover ROLLBACK_ORIGIN + MANAGED_RENAME_ORIGIN.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import {
agentWriteMd,
clientIdsInDoc,
diff --git a/packages/app/tests/integration/selection-state.test.ts b/packages/app/tests/integration/selection-state.test.ts
index f32423093..80b8d9e46 100644
--- a/packages/app/tests/integration/selection-state.test.ts
+++ b/packages/app/tests/integration/selection-state.test.ts
@@ -21,10 +21,10 @@
* convention).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { EditorState, NodeSelection, Plugin, TextSelection } from '@tiptap/pm/state';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import {
type BlockSelection,
deriveBlockSelection,
diff --git a/packages/app/tests/integration/server-observer-feedback-loop.test.ts b/packages/app/tests/integration/server-observer-feedback-loop.test.ts
index 8c700fd86..f8c493f8e 100644
--- a/packages/app/tests/integration/server-observer-feedback-loop.test.ts
+++ b/packages/app/tests/integration/server-observer-feedback-loop.test.ts
@@ -33,9 +33,9 @@
* HTTP agent-write, real Hocuspocus persistence. No mocking.
*/
-import { afterEach, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { getMetrics, resetMetrics } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/session-cleanup.test.ts b/packages/app/tests/integration/session-cleanup.test.ts
index e8aeff0f3..6129174a3 100644
--- a/packages/app/tests/integration/session-cleanup.test.ts
+++ b/packages/app/tests/integration/session-cleanup.test.ts
@@ -8,9 +8,9 @@
* @see packages/server/src/agent-sessions.ts — closeAllForAgent
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { swapContributors } from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import type { TestServer } from './test-harness';
import { agentWriteMd, createTestServer } from './test-harness';
diff --git a/packages/app/tests/integration/session-undo-manager.test.ts b/packages/app/tests/integration/session-undo-manager.test.ts
index ea63a1b52..49202b06d 100644
--- a/packages/app/tests/integration/session-undo-manager.test.ts
+++ b/packages/app/tests/integration/session-undo-manager.test.ts
@@ -6,7 +6,7 @@
* 2. One transact() touching Y.Text + flashMap = one undo step.
* 3. closeSession() destroys the UM (no longer tracks new writes after destroy).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/showall-single-flight.test.ts b/packages/app/tests/integration/showall-single-flight.test.ts
index 83870d79e..aee32c3e4 100644
--- a/packages/app/tests/integration/showall-single-flight.test.ts
+++ b/packages/app/tests/integration/showall-single-flight.test.ts
@@ -11,7 +11,7 @@
* one `@inkeep/open-knowledge-server` module instance, so the counter is the
* same object the handler increments.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -20,6 +20,7 @@ import {
__getShowAllWalkStatsForTesting,
__resetShowAllWalkStatsForTesting,
} from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { createTestServer, pollUntil, type TestServer } from './test-harness';
// The fixture is intentionally large AND deep so one walk spans many event-loop
diff --git a/packages/app/tests/integration/showall-streaming.test.ts b/packages/app/tests/integration/showall-streaming.test.ts
index 24dfa537a..b713c2ccd 100644
--- a/packages/app/tests/integration/showall-streaming.test.ts
+++ b/packages/app/tests/integration/showall-streaming.test.ts
@@ -7,11 +7,12 @@
* single-flight JSON response unchanged (back-compatible coexistence). The cap
* propagates as `truncated` on the terminal line.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { consumeShowAllStream, isNdjsonResponse } from '../../src/lib/show-all-stream';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/showok-reveal.test.ts b/packages/app/tests/integration/showok-reveal.test.ts
index 0be493122..e7a3039a0 100644
--- a/packages/app/tests/integration/showok-reveal.test.ts
+++ b/packages/app/tests/integration/showok-reveal.test.ts
@@ -6,11 +6,12 @@
* must stay `.ok`-free (reveal is a per-request view, never an index rescope),
* and a plain showAll request keeps today's `.ok`-less listing.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema, SearchSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { createTestServer, type TestServer } from './test-harness';
// Unique body/name tokens so the search-corpus assertions can't false-pass on
diff --git a/packages/app/tests/integration/sidebar-assets.test.ts b/packages/app/tests/integration/sidebar-assets.test.ts
index 392b63f8b..664520f6d 100644
--- a/packages/app/tests/integration/sidebar-assets.test.ts
+++ b/packages/app/tests/integration/sidebar-assets.test.ts
@@ -1,8 +1,8 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { awaitFileWatcherIndexed, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/sidebar-show-all-files.test.ts b/packages/app/tests/integration/sidebar-show-all-files.test.ts
index 87068d8a3..4b62513e2 100644
--- a/packages/app/tests/integration/sidebar-show-all-files.test.ts
+++ b/packages/app/tests/integration/sidebar-show-all-files.test.ts
@@ -17,11 +17,12 @@
* fileIndex stays populated with the filtered set; `?showAll=true` is
* per-request only.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DocumentListSuccessSchema } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { awaitFileWatcherIndexed, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/single-client-paste-duplication.test.ts b/packages/app/tests/integration/single-client-paste-duplication.test.ts
index 5bd2850eb..059b1f690 100644
--- a/packages/app/tests/integration/single-client-paste-duplication.test.ts
+++ b/packages/app/tests/integration/single-client-paste-duplication.test.ts
@@ -11,7 +11,7 @@
* paragraphs into the fragment) to pin the server/bridge contract independent
* of any editor surface.
*/
-import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { afterAll, beforeAll, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/single-file-mode.test.ts b/packages/app/tests/integration/single-file-mode.test.ts
index e84424e0d..e86fd85a5 100644
--- a/packages/app/tests/integration/single-file-mode.test.ts
+++ b/packages/app/tests/integration/single-file-mode.test.ts
@@ -18,7 +18,6 @@
* (the realpath-before-detection + dedup logic is not a server concern).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import {
mkdirSync,
mkdtempSync,
@@ -31,6 +30,7 @@ import {
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { fetchWithHostHeader } from './host-header-request.test-helper';
import { createTestClient, createTestServer, pollUntil, wait } from './test-harness';
diff --git a/packages/app/tests/integration/skill-bundle-files.test.ts b/packages/app/tests/integration/skill-bundle-files.test.ts
index cce70a688..5a9dc324f 100644
--- a/packages/app/tests/integration/skill-bundle-files.test.ts
+++ b/packages/app/tests/integration/skill-bundle-files.test.ts
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
/**
diff --git a/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts b/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
index dc647cdd2..fe4d96a8e 100644
--- a/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
+++ b/packages/app/tests/integration/skill-bundle-inbound-backlink.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createTestServer, pollUntil, type TestServer } from './test-harness.ts';
/**
diff --git a/packages/app/tests/integration/slash-command-extension.test.ts b/packages/app/tests/integration/slash-command-extension.test.ts
index 7a56696dd..014312324 100644
--- a/packages/app/tests/integration/slash-command-extension.test.ts
+++ b/packages/app/tests/integration/slash-command-extension.test.ts
@@ -9,8 +9,8 @@
* (Level-2: real component, no DOM — TipTap's Editor requires `window`).
*/
-import { describe, expect, test } from 'bun:test';
import { Minus } from 'lucide-react';
+import { describe, expect, test } from 'vitest';
import { SlashCommand, type SlashCommandOptions } from '../../src/editor/extensions/slash-command';
import {
filterItems,
diff --git a/packages/app/tests/integration/stale-idb-doc-reload.test.ts b/packages/app/tests/integration/stale-idb-doc-reload.test.ts
index 7257d82d9..03f5cd407 100644
--- a/packages/app/tests/integration/stale-idb-doc-reload.test.ts
+++ b/packages/app/tests/integration/stale-idb-doc-reload.test.ts
@@ -39,9 +39,9 @@
* any other shape — is deliberately not pinned here.
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
createClientPersistence,
diff --git a/packages/app/tests/integration/stale-idb-lineage-doors.test.ts b/packages/app/tests/integration/stale-idb-lineage-doors.test.ts
index 0e98aa868..e26e8936d 100644
--- a/packages/app/tests/integration/stale-idb-lineage-doors.test.ts
+++ b/packages/app/tests/integration/stale-idb-lineage-doors.test.ts
@@ -40,9 +40,9 @@
* either door gets fenced — is deliberately not pinned.
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
createClientPersistence,
diff --git a/packages/app/tests/integration/stale-idb-lineage-record-absent-doors.test.ts b/packages/app/tests/integration/stale-idb-lineage-record-absent-doors.test.ts
index 213a54565..48c762788 100644
--- a/packages/app/tests/integration/stale-idb-lineage-record-absent-doors.test.ts
+++ b/packages/app/tests/integration/stale-idb-lineage-record-absent-doors.test.ts
@@ -49,9 +49,9 @@
* leaves field occurrences of this corruption class invisible.
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
createClientPersistence,
diff --git a/packages/app/tests/integration/structural-freshness-real-docs.test.ts b/packages/app/tests/integration/structural-freshness-real-docs.test.ts
index 53f167cf6..d102c4a62 100644
--- a/packages/app/tests/integration/structural-freshness-real-docs.test.ts
+++ b/packages/app/tests/integration/structural-freshness-real-docs.test.ts
@@ -14,10 +14,10 @@
* tags and is listed in DEFAULT_TEST_EXCLUDE_GLOBS.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { createStructuralFreshnessChecker, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { mdManager } from './test-harness';
type PmNodeJson = {
diff --git a/packages/app/tests/integration/symlink-alias.test.ts b/packages/app/tests/integration/symlink-alias.test.ts
index ce0c34cf6..dd1768e32 100644
--- a/packages/app/tests/integration/symlink-alias.test.ts
+++ b/packages/app/tests/integration/symlink-alias.test.ts
@@ -1,4 +1,3 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import {
lstatSync,
mkdtempSync,
@@ -10,6 +9,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { agentPatch, agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
index 841903640..db25c1e96 100644
--- a/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
+++ b/packages/app/tests/integration/sync-conflict-resolution-crdt.test.ts
@@ -20,11 +20,12 @@
* - Persistence's debounce window is bounded by `maxDebounce: 500` so the
* test can wait deterministically.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTestClient, createTestServer, pollUntil, type TestServer } from './test-harness';
const BASE_CONTENT = '# Base\n\nBase paragraph.\n';
diff --git a/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts b/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts
index d599072e6..32f65a70b 100644
--- a/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts
+++ b/packages/app/tests/integration/sync-engine-dot-dir-symmetry.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createContentFilter } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { SyncEngine } from '../../../server/src/sync-engine.ts';
const tmpRoots: string[] = [];
diff --git a/packages/app/tests/integration/test-harness-origins.test.ts b/packages/app/tests/integration/test-harness-origins.test.ts
index 9fe3f1d52..15ae64fe8 100644
--- a/packages/app/tests/integration/test-harness-origins.test.ts
+++ b/packages/app/tests/integration/test-harness-origins.test.ts
@@ -6,9 +6,9 @@
* predicate, not identity-based Set membership with AGENT_WRITE_ORIGIN.
*/
-import { describe, expect, test } from 'bun:test';
import type { LocalTransactionOrigin } from '@hocuspocus/server';
import { isPairedWriteOrigin } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { attachBridgeInvariantWatcher } from './test-harness';
diff --git a/packages/app/tests/integration/test-harness.test.ts b/packages/app/tests/integration/test-harness.test.ts
index 5787c5b95..fc37d0874 100644
--- a/packages/app/tests/integration/test-harness.test.ts
+++ b/packages/app/tests/integration/test-harness.test.ts
@@ -7,7 +7,7 @@
* stop polling.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { pollUntil } from './test-harness';
diff --git a/packages/app/tests/integration/test-script-invariants.test.ts b/packages/app/tests/integration/test-script-invariants.test.ts
index 9843bfd24..3de2d5756 100644
--- a/packages/app/tests/integration/test-script-invariants.test.ts
+++ b/packages/app/tests/integration/test-script-invariants.test.ts
@@ -37,9 +37,9 @@
* `bun test --isolate` flag provided (oven-sh/bun#12823).
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { appVitestConfig } from '../../vitest.config.ts';
import { appDomVitestConfig } from '../../vitest.dom.config.ts';
@@ -107,14 +107,9 @@ describe('Tier-3 substrate-additive contract — package.json + vitest config in
expect(appDomVitestConfig.test.include).toEqual(['**/*.dom.test.tsx']);
});
- test('dom project sets isolate:true (per-file fresh module registry, oven-sh/bun#12823)', () => {
- // Bun's mock.module is in-place: a mock declared at module level in one
- // .dom.test.tsx file persists into sibling files run in one invocation. Linux
- // CI's filesystem iteration ordered config-provider.dom.test.tsx (which mocks
- // '@/hooks/use-theme-bridge' to a no-op) BEFORE use-theme-bridge.dom.test.tsx,
- // replacing the real hook globally and producing the Received: 0 mode the
- // substrate hit on PR #853. `isolate: true` gives each file a fresh module
- // registry so mocks don't bleed. Removing it would re-open the leak class.
+ test('dom project sets isolate:true for a fresh per-file module registry', () => {
+ // Several DOM suites register module-level vi.doMock factories. Per-file
+ // isolation keeps those replacements from changing sibling suites.
expect(appDomVitestConfig.test.isolate).toBe(true);
});
});
diff --git a/packages/app/tests/integration/trailing-hard-break-bridge.test.ts b/packages/app/tests/integration/trailing-hard-break-bridge.test.ts
index 8c8bbbe62..88cb78adb 100644
--- a/packages/app/tests/integration/trailing-hard-break-bridge.test.ts
+++ b/packages/app/tests/integration/trailing-hard-break-bridge.test.ts
@@ -8,8 +8,9 @@
* hardBreak node in the fragment and the next Observer A drain re-emitted it,
* masked from the watchdog by parse-equivalence tolerance.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { updateYFragment } from '@tiptap/y-tiptap';
+import { afterEach, describe, expect, test } from 'vitest';
import {
awaitDocQuiescence,
createTestClient,
diff --git a/packages/app/tests/integration/urn-ipc-registry-coverage.test.ts b/packages/app/tests/integration/urn-ipc-registry-coverage.test.ts
index 1d50a5ede..cd6f878d0 100644
--- a/packages/app/tests/integration/urn-ipc-registry-coverage.test.ts
+++ b/packages/app/tests/integration/urn-ipc-registry-coverage.test.ts
@@ -18,8 +18,8 @@
* map without removing the original.
*/
-import { describe, expect, test } from 'bun:test';
import { ProblemTypeSchema, URN_HTTP_ONLY, URN_IPC_REGISTRY } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
describe('URN → IPC registry coverage', () => {
test('every URN in ProblemTypeSchema is either mapped to ≥1 channel or in URN_HTTP_ONLY', () => {
diff --git a/packages/app/tests/integration/vite-dedupe-parity.test.ts b/packages/app/tests/integration/vite-dedupe-parity.test.ts
index be129954b..61289bd64 100644
--- a/packages/app/tests/integration/vite-dedupe-parity.test.ts
+++ b/packages/app/tests/integration/vite-dedupe-parity.test.ts
@@ -24,9 +24,9 @@
* only the renderer's source imports.
*/
-import { describe, expect, test } from 'bun:test';
import { resolve } from 'node:path';
import { Project, SyntaxKind } from 'ts-morph';
+import { describe, expect, test } from 'vitest';
import { RENDERER_DEDUPE } from '../../vite.dedupe';
const REPO_ROOT = resolve(import.meta.dirname, '../../../..');
diff --git a/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts b/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts
index e946b8157..34bc809b2 100644
--- a/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts
+++ b/packages/app/tests/integration/vite-worker-cachedir-isolation.test.ts
@@ -59,10 +59,10 @@
* the `RENDERER_DEDUPE` cross-config invariant the same way.
*/
-import { describe, expect, test } from 'bun:test';
import { resolve } from 'node:path';
import { type Node, Project, SyntaxKind } from 'ts-morph';
import { loadConfigFromFile } from 'vite';
+import { describe, expect, test } from 'vitest';
const APP_PACKAGE_ROOT = resolve(import.meta.dirname, '../..');
const APP_VITE_CONFIG = resolve(APP_PACKAGE_ROOT, 'vite.config.ts');
diff --git a/packages/app/tests/integration/walker-symmetry.test.ts b/packages/app/tests/integration/walker-symmetry.test.ts
index f1f6c549d..fc03a294c 100644
--- a/packages/app/tests/integration/walker-symmetry.test.ts
+++ b/packages/app/tests/integration/walker-symmetry.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createContentFilter } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { SyncEngine } from '../../../server/src/sync-engine.ts';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/workspace-endpoint.test.ts b/packages/app/tests/integration/workspace-endpoint.test.ts
index f6365ac23..b757401ab 100644
--- a/packages/app/tests/integration/workspace-endpoint.test.ts
+++ b/packages/app/tests/integration/workspace-endpoint.test.ts
@@ -27,9 +27,9 @@
* here and is the more realistic DNS-rebinding attack shape.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { rmSync } from 'node:fs';
import { sep } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { fetchWithHostHeader } from './host-header-request.test-helper';
import { createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts b/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts
index e212a06d4..6c67c7c2f 100644
--- a/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts
+++ b/packages/app/tests/integration/worktree-cleanup-and-stale-pointer.test.ts
@@ -8,12 +8,12 @@
* downstream in `mkdirSync`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { bootServer, ConfigSchema } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { createLinkedWorktree, type LinkedWorktreeHandle } from './worktree-test-harness.ts';
const TEST_CONFIG = ConfigSchema.parse({});
diff --git a/packages/app/tests/integration/worktree-concurrent.test.ts b/packages/app/tests/integration/worktree-concurrent.test.ts
index c944c3709..2ecaae989 100644
--- a/packages/app/tests/integration/worktree-concurrent.test.ts
+++ b/packages/app/tests/integration/worktree-concurrent.test.ts
@@ -6,11 +6,11 @@
* isolation contract.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { bootServer, ConfigSchema } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { createLinkedWorktree, type LinkedWorktreeHandle } from './worktree-test-harness.ts';
const TEST_CONFIG = ConfigSchema.parse({});
diff --git a/packages/app/tests/integration/worktree-init.test.ts b/packages/app/tests/integration/worktree-init.test.ts
index 0c5da79aa..cd778555e 100644
--- a/packages/app/tests/integration/worktree-init.test.ts
+++ b/packages/app/tests/integration/worktree-init.test.ts
@@ -8,10 +8,10 @@
* no-op for `config.yml`. After init, the same worktree must boot cleanly.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { bootServer, ConfigSchema, initContent } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { createLinkedWorktree, type LinkedWorktreeHandle } from './worktree-test-harness.ts';
const TEST_CONFIG = ConfigSchema.parse({});
diff --git a/packages/app/tests/integration/writer-splice-same-block-preservation.test.ts b/packages/app/tests/integration/writer-splice-same-block-preservation.test.ts
index 3c63af19f..bbf994126 100644
--- a/packages/app/tests/integration/writer-splice-same-block-preservation.test.ts
+++ b/packages/app/tests/integration/writer-splice-same-block-preservation.test.ts
@@ -14,8 +14,8 @@
* so remote-peer divergence is covered, not just local echo.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import {
diff --git a/packages/app/tests/integration/wysiwyg-x20-cold-reopen.test.ts b/packages/app/tests/integration/wysiwyg-x20-cold-reopen.test.ts
index 24348f1e0..1d02a30d9 100644
--- a/packages/app/tests/integration/wysiwyg-x20-cold-reopen.test.ts
+++ b/packages/app/tests/integration/wysiwyg-x20-cold-reopen.test.ts
@@ -17,12 +17,11 @@
* drop `sourceRaw` and corrupt the disk bytes on the next serialize).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterEach, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
import {
agentWriteMd,
diff --git a/packages/app/tests/integration/y-prosemirror-import-coverage.test.ts b/packages/app/tests/integration/y-prosemirror-import-coverage.test.ts
index c2c4cb10e..fe5edde1f 100644
--- a/packages/app/tests/integration/y-prosemirror-import-coverage.test.ts
+++ b/packages/app/tests/integration/y-prosemirror-import-coverage.test.ts
@@ -28,9 +28,9 @@
* the surface this test scans.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
const REPO_ROOT = resolve(import.meta.dirname, '../../../..');
const RENDERER_ROOT = join(REPO_ROOT, 'packages/app/src');
diff --git a/packages/app/tests/integration/y-tiptap-schema-throw-substitution.test.ts b/packages/app/tests/integration/y-tiptap-schema-throw-substitution.test.ts
index c53588aaf..1d79736f3 100644
--- a/packages/app/tests/integration/y-tiptap-schema-throw-substitution.test.ts
+++ b/packages/app/tests/integration/y-tiptap-schema-throw-substitution.test.ts
@@ -38,9 +38,9 @@
* or WebSocket plumbing.
*/
-import { describe, expect, test } from 'bun:test';
import type { Node as PmNode } from '@tiptap/pm/model';
import { initProseMirrorDoc } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { schema } from './test-harness';
diff --git a/packages/app/tests/integration/ytext-source-mode-restart.test.ts b/packages/app/tests/integration/ytext-source-mode-restart.test.ts
index 74ab883cc..0a935f553 100644
--- a/packages/app/tests/integration/ytext-source-mode-restart.test.ts
+++ b/packages/app/tests/integration/ytext-source-mode-restart.test.ts
@@ -17,10 +17,10 @@
* restart. Post-fix, neither surface duplicates and the two stay in sync.
*/
import './idb-preload';
-import { afterEach, describe, expect, test } from 'bun:test';
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, describe, expect, test } from 'vitest';
import { ProviderPool } from '../../src/editor/provider-pool';
import {
assertBridgeInvariant,
diff --git a/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts b/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts
index fcbc4f154..e7c36b681 100644
--- a/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts
+++ b/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts
@@ -23,10 +23,10 @@
* guard can never silently cover a stale subset.
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';
// __dirname → packages/app/tests/lint-plugins/. OK subtree root is 4 levels up.
diff --git a/packages/app/tests/lint-plugins/no-raw-html-interactive-element.test.ts b/packages/app/tests/lint-plugins/no-raw-html-interactive-element.test.ts
index bc0b900a9..33298c7dd 100644
--- a/packages/app/tests/lint-plugins/no-raw-html-interactive-element.test.ts
+++ b/packages/app/tests/lint-plugins/no-raw-html-interactive-element.test.ts
@@ -23,9 +23,9 @@
* to root plugins) or scope-narrowing (the exemptions missing) fails CI.
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';
// __dirname → packages/app/tests/lint-plugins/. Repo root is 4 levels up.
diff --git a/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts b/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts
index efe0fb6db..bcffb2f46 100644
--- a/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts
+++ b/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts
@@ -22,9 +22,9 @@
* (a negative starts firing, rising above 10).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';
// __dirname → packages/app/tests/lint-plugins/. Repo root is 4 levels up.
diff --git a/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts b/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts
index 8b90ab6f8..e77a8b6e3 100644
--- a/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts
+++ b/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts
@@ -19,9 +19,9 @@
* and false-positive widenings (above 3).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';
// __dirname → packages/app/tests/lint-plugins/. Repo root is 4 levels up.
diff --git a/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts b/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts
index 49da76939..0ff14a0a2 100644
--- a/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts
+++ b/packages/app/tests/meta/getfileindex-allfiles-coverage.test.ts
@@ -18,9 +18,10 @@
* for the dangerous call, walk back to the enclosing function, require either
* allowlist OR a structural guard in the local window.
*/
-import { describe, expect, test } from 'bun:test';
+
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const SERVER_SRC_ROOT = join(import.meta.dirname, '../../../server/src');
const API_EXT_PATH = join(SERVER_SRC_ROOT, 'api-extension.ts');
diff --git a/packages/app/tests/meta/lingui-macro-shim.test.ts b/packages/app/tests/meta/lingui-macro-shim.test.ts
index d81543bf2..903abf7fd 100644
--- a/packages/app/tests/meta/lingui-macro-shim.test.ts
+++ b/packages/app/tests/meta/lingui-macro-shim.test.ts
@@ -11,7 +11,7 @@
* from `lingui extract` (see `lingui.config.ts`), so the macro-looking calls
* below never reach the real catalog.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { msg, Plural, plural, Select, select, Trans, t, useLingui } from '../lingui-macro-shim';
describe('lingui-macro-shim — @lingui/core/macro', () => {
diff --git a/packages/app/tests/meta/showok-caller-coverage.test.ts b/packages/app/tests/meta/showok-caller-coverage.test.ts
index 659da2b70..eec2fee10 100644
--- a/packages/app/tests/meta/showok-caller-coverage.test.ts
+++ b/packages/app/tests/meta/showok-caller-coverage.test.ts
@@ -15,9 +15,10 @@
* flag legitimately appears in nested helpers and local consts whose names
* are incidental.
*/
-import { describe, expect, test } from 'bun:test';
+
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const SERVER_SRC_ROOT = join(import.meta.dirname, '../../../server/src');
const CLI_SRC_ROOT = join(import.meta.dirname, '../../../cli/src');
diff --git a/packages/app/tests/meta/substrate-vocabulary-drift.test.ts b/packages/app/tests/meta/substrate-vocabulary-drift.test.ts
index 5dd343d0a..4d52c1107 100644
--- a/packages/app/tests/meta/substrate-vocabulary-drift.test.ts
+++ b/packages/app/tests/meta/substrate-vocabulary-drift.test.ts
@@ -18,9 +18,9 @@
* a per-entry comment explaining intent. The list is bounded by review.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, type Stats, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { getRegisteredDescriptors } from '../../src/editor/registry/index.ts';
// Resolve paths against this file's location, not cwd. Matches the
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts
index a11ab89f7..a4fc9fbb7 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
buildCalibrationReport,
classifyContentBytes,
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/fixtures.test.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/fixtures.test.ts
index cca833220..5407f1c4a 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/fixtures.test.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/fixtures.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { ASYMMETRIC_CYCLE_DURATION_MS, asymmetricFixture } from './asymmetric.ts';
import { BROAD_CYCLE_DURATION_MS, broadFixture } from './broad.ts';
import { TIGHT_CYCLE_DURATION_MS, tightFixture } from './tight.ts';
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.test.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.test.ts
index 75d880fed..2443e51e0 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.test.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildCorpus,
buildDocSpec,
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts
index 494519570..d1ae33f1d 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { createHash } from 'node:crypto';
+import { describe, expect, test } from 'vitest';
import { buildCorpus } from './generator.ts';
import { SIZE_ENVELOPES, totalDocsInMix } from './types.ts';
import { VAULT_MIX, VAULT_NAME_PREFIX, VAULT_SEED, vault } from './vault.ts';
diff --git a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
index 5277995b0..d49567789 100644
--- a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
+++ b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
@@ -9,10 +9,10 @@
* matches.
*/
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { MarkdownManager, OK_DIR, sharedExtensions } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { withTempDir } from '../../temp-dir.test-helper.ts';
import { generateFixture } from './generate-view-count-fixtures.ts';
diff --git a/packages/app/tests/perf/lib/bootstrap.test.ts b/packages/app/tests/perf/lib/bootstrap.test.ts
index 05d8baa98..0d1f42b11 100644
--- a/packages/app/tests/perf/lib/bootstrap.test.ts
+++ b/packages/app/tests/perf/lib/bootstrap.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { bcaConfidenceInterval } from './bootstrap.ts';
/**
diff --git a/packages/app/tests/perf/lib/bundle-check.test.ts b/packages/app/tests/perf/lib/bundle-check.test.ts
index 90d7e35f3..75dae55e2 100644
--- a/packages/app/tests/perf/lib/bundle-check.test.ts
+++ b/packages/app/tests/perf/lib/bundle-check.test.ts
@@ -7,10 +7,11 @@
* a real `bun run build` happens at the perf-tier — local dev
* runs `bun run build` once and re-runs assertBundleHealth manually.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { assertBundleHealth, BASELINE_INDEX_GZIPPED_KB } from './bundle-check.ts';
let dir: string;
diff --git a/packages/app/tests/perf/lib/cdp-tracer.test.ts b/packages/app/tests/perf/lib/cdp-tracer.test.ts
index 7e9af356a..24de6fbed 100644
--- a/packages/app/tests/perf/lib/cdp-tracer.test.ts
+++ b/packages/app/tests/perf/lib/cdp-tracer.test.ts
@@ -7,7 +7,7 @@
* `profile.ts` require a real CDP session (exercised via scenario runs).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
aggregateTrace,
type CdpTraceEvent,
diff --git a/packages/app/tests/perf/lib/cell-measurement.test.ts b/packages/app/tests/perf/lib/cell-measurement.test.ts
index 62dde4c13..a44d79018 100644
--- a/packages/app/tests/perf/lib/cell-measurement.test.ts
+++ b/packages/app/tests/perf/lib/cell-measurement.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { CapRegime, WorkloadFixtureRef } from './cell-measurement.ts';
import {
bootstrapCi,
diff --git a/packages/app/tests/perf/lib/correlate-longtasks.test.ts b/packages/app/tests/perf/lib/correlate-longtasks.test.ts
index 7fb79b011..f2a9ad5ab 100644
--- a/packages/app/tests/perf/lib/correlate-longtasks.test.ts
+++ b/packages/app/tests/perf/lib/correlate-longtasks.test.ts
@@ -11,7 +11,7 @@
* tasks with marks distributed across them, half-open boundary discipline.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { correlateLongtasksWithMarks } from './correlate-longtasks.ts';
describe('correlateLongtasksWithMarks', () => {
diff --git a/packages/app/tests/perf/lib/define-sweep.test.ts b/packages/app/tests/perf/lib/define-sweep.test.ts
index 9f3101abb..e708eb9d4 100644
--- a/packages/app/tests/perf/lib/define-sweep.test.ts
+++ b/packages/app/tests/perf/lib/define-sweep.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { cartesian, defineSweep } from './define-sweep.ts';
import type { ScenarioCtx } from './scenario.ts';
diff --git a/packages/app/tests/perf/lib/kneedle.test.ts b/packages/app/tests/perf/lib/kneedle.test.ts
index 6ea572273..2654053ae 100644
--- a/packages/app/tests/perf/lib/kneedle.test.ts
+++ b/packages/app/tests/perf/lib/kneedle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { findKnee, isotonicSmooth } from './kneedle.ts';
describe('findKnee', () => {
diff --git a/packages/app/tests/perf/lib/longtask-observer.test.ts b/packages/app/tests/perf/lib/longtask-observer.test.ts
index a34ba81bb..c23b48f1f 100644
--- a/packages/app/tests/perf/lib/longtask-observer.test.ts
+++ b/packages/app/tests/perf/lib/longtask-observer.test.ts
@@ -16,8 +16,8 @@
* The fake-page mocks expose just the two methods the helper touches.
*/
-import { describe, expect, test } from 'bun:test';
import type { Page } from '@playwright/test';
+import { describe, expect, test } from 'vitest';
import {
installLongtaskObserver,
type LongTaskRecord,
diff --git a/packages/app/tests/perf/lib/macos-pressure.test.ts b/packages/app/tests/perf/lib/macos-pressure.test.ts
index d1688e35f..d20d5bbca 100644
--- a/packages/app/tests/perf/lib/macos-pressure.test.ts
+++ b/packages/app/tests/perf/lib/macos-pressure.test.ts
@@ -13,7 +13,7 @@
* the platform discriminator path runs without touching the binary.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
isPressureLevel,
type PressureLevel,
diff --git a/packages/app/tests/perf/lib/node-peer-simulator.test.ts b/packages/app/tests/perf/lib/node-peer-simulator.test.ts
index 95cd3ff9d..a3d61c1bb 100644
--- a/packages/app/tests/perf/lib/node-peer-simulator.test.ts
+++ b/packages/app/tests/perf/lib/node-peer-simulator.test.ts
@@ -16,7 +16,7 @@
* but we DO assert relative count ordering at a fixed window).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { createNodePeerSimulator, type NodePeerSimulatorHandle } from './node-peer-simulator.ts';
const DUMMY_PORT = 1;
diff --git a/packages/app/tests/perf/lib/perf-compare.test.ts b/packages/app/tests/perf/lib/perf-compare.test.ts
index fbcf130c0..833c0e372 100644
--- a/packages/app/tests/perf/lib/perf-compare.test.ts
+++ b/packages/app/tests/perf/lib/perf-compare.test.ts
@@ -15,10 +15,10 @@
* - Filters: --scenario / --doc narrow the table to matching rows.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
const SCRIPT = resolve(import.meta.dir, '..', '..', '..', 'scripts', 'perf-compare.sh');
diff --git a/packages/app/tests/perf/lib/sweep-runner.test.ts b/packages/app/tests/perf/lib/sweep-runner.test.ts
index c54937403..a84e9bc21 100644
--- a/packages/app/tests/perf/lib/sweep-runner.test.ts
+++ b/packages/app/tests/perf/lib/sweep-runner.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
aggregateCampaign,
BASELINE_CAP_REGIME,
diff --git a/packages/app/tests/perf/lib/tempo-client.test.ts b/packages/app/tests/perf/lib/tempo-client.test.ts
index a8966b907..a734f27ec 100644
--- a/packages/app/tests/perf/lib/tempo-client.test.ts
+++ b/packages/app/tests/perf/lib/tempo-client.test.ts
@@ -9,7 +9,7 @@
* with the live LGTM stack running — Docker is
* not running in this environment.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
parseTempoTimings,
queryTempoByMountId,
diff --git a/packages/app/tests/perf/lib/with-checkpoint.test.ts b/packages/app/tests/perf/lib/with-checkpoint.test.ts
index 605bfd030..3a89dd9a8 100644
--- a/packages/app/tests/perf/lib/with-checkpoint.test.ts
+++ b/packages/app/tests/perf/lib/with-checkpoint.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { type WithCheckpointConfig, withCheckpoint } from './with-checkpoint.ts';
interface SampleInput {
diff --git a/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts b/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts
index 0cd23daa9..4ddc1a637 100644
--- a/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts
+++ b/packages/app/tests/perf/probes/tiptap-destroy-leak.test.ts
@@ -38,10 +38,10 @@
* test just enforces what the engineer commits.
*/
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { withTempDir } from '../../temp-dir.test-helper.ts';
import { computeLeakRateMbPerCycle } from '../lib/cell-measurement.ts';
import {
diff --git a/packages/app/tests/perf/profile.test.ts b/packages/app/tests/perf/profile.test.ts
index d944989d5..9938323a2 100644
--- a/packages/app/tests/perf/profile.test.ts
+++ b/packages/app/tests/perf/profile.test.ts
@@ -11,7 +11,7 @@
* opts back in for paint/GPU diagnosis on a single-scenario run.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { parseArgs } from './profile.ts';
describe('parseArgs — launch-mode defaults', () => {
diff --git a/packages/app/tests/perf/scenarios/sweep-cache-regime.smoke.test.ts b/packages/app/tests/perf/scenarios/sweep-cache-regime.smoke.test.ts
index 395b5dd03..4359299cb 100644
--- a/packages/app/tests/perf/scenarios/sweep-cache-regime.smoke.test.ts
+++ b/packages/app/tests/perf/scenarios/sweep-cache-regime.smoke.test.ts
@@ -21,10 +21,10 @@
* aggregateCampaign cross-fixture winner selection.
*/
-import { describe, expect, it } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { describe, expect, it } from 'vitest';
import type { ScenarioCtx, ScenarioOptions } from '../lib/scenario.ts';
import type {
HostClassFingerprint,
diff --git a/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation-real-cycle.test.ts b/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation-real-cycle.test.ts
index 9e1ec7ff2..ed28455cb 100644
--- a/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation-real-cycle.test.ts
+++ b/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation-real-cycle.test.ts
@@ -19,8 +19,8 @@
* a verdict-update PR.
*/
-import { describe, expect, test } from 'bun:test';
import { chromium } from '@playwright/test';
+import { describe, expect, test } from 'vitest';
import {
buildProductionCycleDriver,
type CycleOutcome,
diff --git a/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation.smoke.test.ts b/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation.smoke.test.ts
index d382d01b0..daab48624 100644
--- a/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation.smoke.test.ts
+++ b/packages/app/tests/perf/scenarios/sweep-convention-cap-graduation.smoke.test.ts
@@ -11,7 +11,7 @@
* scaffolded JSON when calibration fails.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { TempoQueryResult } from '../lib/tempo-client.ts';
import {
analyzeCalibration,
diff --git a/packages/app/tests/stress/bridge-convergence.fuzz.test.ts b/packages/app/tests/stress/bridge-convergence.fuzz.test.ts
index 5642a54fe..e6707b0b2 100644
--- a/packages/app/tests/stress/bridge-convergence.fuzz.test.ts
+++ b/packages/app/tests/stress/bridge-convergence.fuzz.test.ts
@@ -39,13 +39,13 @@
* asserts a corresponding op kind exists in the generator.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { chunkedYTextInsert } from '@inkeep/open-knowledge-core';
import { applyExternalChange, isPairedWriteOrigin } from '@inkeep/open-knowledge-server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
diff --git a/packages/app/tests/stress/component-blocks.perf.test.ts b/packages/app/tests/stress/component-blocks.perf.test.ts
index d5b93d9a5..c1c90253d 100644
--- a/packages/app/tests/stress/component-blocks.perf.test.ts
+++ b/packages/app/tests/stress/component-blocks.perf.test.ts
@@ -15,7 +15,7 @@
* under a future policy flip it would produce PR-red on correct code.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { sharedExtensions } from '../../../../packages/core/src/extensions/shared.ts';
import { MarkdownManager } from '../../../../packages/core/src/markdown/index.ts';
diff --git a/packages/app/tests/stress/oracle-e-expectations.test.ts b/packages/app/tests/stress/oracle-e-expectations.test.ts
index 23e0f671a..d147bd3de 100644
--- a/packages/app/tests/stress/oracle-e-expectations.test.ts
+++ b/packages/app/tests/stress/oracle-e-expectations.test.ts
@@ -13,7 +13,7 @@
* (the markers are absent because the writes were refused, not because
* content was corrupted).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildOracleEExpectations,
markerPrefixOf,
diff --git a/packages/app/tests/stress/server-authoritative-stress.test.ts b/packages/app/tests/stress/server-authoritative-stress.test.ts
index 4d9814d04..03772aa52 100644
--- a/packages/app/tests/stress/server-authoritative-stress.test.ts
+++ b/packages/app/tests/stress/server-authoritative-stress.test.ts
@@ -28,8 +28,8 @@
* measurement that races with in-flight ops).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
assertBridgeInvariant,
diff --git a/packages/app/vitest.config.ts b/packages/app/vitest.config.ts
index 250868fef..7f3a4722a 100644
--- a/packages/app/vitest.config.ts
+++ b/packages/app/vitest.config.ts
@@ -1,7 +1,7 @@
import { fileURLToPath } from 'node:url';
import react from '@vitejs/plugin-react';
import { defineConfig, type ViteUserConfig } from 'vitest/config';
-import { bunGlobalShimPath, bunTestShimPath, okVitestBase } from '../../test-support/vitest.base';
+import { bunGlobalShimPath, okVitestBase } from '../../test-support/vitest.base';
import { RENDERER_DEDUPE } from './vite.dedupe';
// `@lingui/{react,core}/macro` only run under the build's Babel macro pass; a
@@ -29,7 +29,6 @@ export const appVitestConfig = {
resolve: {
...okVitestBase.resolve,
alias: [
- { find: 'bun:test', replacement: bunTestShimPath },
{ find: '@lingui/react/macro', replacement: linguiMacroShim },
{ find: '@lingui/core/macro', replacement: linguiMacroShim },
{ find: /^@\//, replacement: srcDir },
diff --git a/packages/app/vitest.dom.config.ts b/packages/app/vitest.dom.config.ts
index 3b231a1c0..df416f256 100644
--- a/packages/app/vitest.dom.config.ts
+++ b/packages/app/vitest.dom.config.ts
@@ -16,7 +16,7 @@ import { appVitestConfig } from './vitest.config';
// ResizeObserver, scrollIntoView, MessageChannel).
//
// `isolate: true` (the forks-pool default, pinned explicitly) gives each file a
-// fresh module registry so a `mock.module(...)` in one .dom.test.tsx cannot leak
+// fresh module registry so a `vi.doMock(...)` in one .dom.test.tsx cannot leak
// into the next — the parity-critical property the retired `--isolate` flag
// provided (oven-sh/bun#12823).
const jsdomSetupPath = fileURLToPath(new URL('./tests/dom/jsdom-preload.ts', import.meta.url));
diff --git a/packages/cli/src/auth/gh-detect.test.ts b/packages/cli/src/auth/gh-detect.test.ts
index 64b48ed27..5f398cb87 100644
--- a/packages/cli/src/auth/gh-detect.test.ts
+++ b/packages/cli/src/auth/gh-detect.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { ExecFileSyncFn } from './gh-detect.ts';
import { detectGh } from './gh-detect.ts';
diff --git a/packages/cli/src/auth/resolve-auth.test.ts b/packages/cli/src/auth/resolve-auth.test.ts
index 5eb890d68..aa3ba4530 100644
--- a/packages/cli/src/auth/resolve-auth.test.ts
+++ b/packages/cli/src/auth/resolve-auth.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { GhDetectResult } from './gh-detect.ts';
import { buildCliCredentialHelper, resolveAuth } from './resolve-auth.ts';
import { FileBackend } from './token-store.ts';
diff --git a/packages/cli/src/auth/token-store.test.ts b/packages/cli/src/auth/token-store.test.ts
index 8997efa37..cc1ca5c1f 100644
--- a/packages/cli/src/auth/token-store.test.ts
+++ b/packages/cli/src/auth/token-store.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
// Mutable mock state shared with the mocked `@napi-rs/keyring`. Each test
// resets this via `resetKeyringMockState()` in beforeEach. The mock's `Entry`
@@ -75,7 +75,7 @@ class MockKeyringEntry {
}
}
-mock.module('@napi-rs/keyring', () => ({ Entry: MockKeyringEntry }));
+vi.doMock('@napi-rs/keyring', () => ({ Entry: MockKeyringEntry }));
import { FileBackend } from './token-store.ts';
@@ -343,7 +343,7 @@ describe('createTokenStore diagnostics', () => {
// ---------------------------------------------------------------------------
// KeyringBackend upsert semantics
//
-// Reachability-tested via `createTokenStore` + mock.module rather than
+// Reachability-tested via `createTokenStore` + vi.doMock rather than
// importing KeyringBackend directly, to avoid widening token-store.ts's
// public surface.
//
diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.ts
index c7d28116d..8163f394a 100644
--- a/packages/cli/src/cli.test.ts
+++ b/packages/cli/src/cli.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
const CLI_PACKAGE_ROOT = import.meta.dir.replace(/\/src$/, '');
diff --git a/packages/cli/src/commands/auth/git-credential.test.ts b/packages/cli/src/commands/auth/git-credential.test.ts
index c150db620..99ce80ee7 100644
--- a/packages/cli/src/commands/auth/git-credential.test.ts
+++ b/packages/cli/src/commands/auth/git-credential.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable, Writable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { FileBackend } from '../../auth/token-store.ts';
import { type CredentialGetLogContext, handleCredentialGet } from './git-credential.ts';
diff --git a/packages/cli/src/commands/auth/repos.test.ts b/packages/cli/src/commands/auth/repos.test.ts
index 855602bca..d7bb55cdc 100644
--- a/packages/cli/src/commands/auth/repos.test.ts
+++ b/packages/cli/src/commands/auth/repos.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { GhDetectResult } from '../../auth/gh-detect.ts';
import { FileBackend } from '../../auth/token-store.ts';
import { resolveReposToken } from './repos.ts';
diff --git a/packages/cli/src/commands/auth/status.test.ts b/packages/cli/src/commands/auth/status.test.ts
index 6d1744456..e419be4fb 100644
--- a/packages/cli/src/commands/auth/status.test.ts
+++ b/packages/cli/src/commands/auth/status.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type { GhDetectResult } from '../../auth/gh-detect.ts';
import { FileBackend } from '../../auth/token-store.ts';
import { buildStatusPayload, resolveStatusSource } from './status.ts';
diff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.ts
index a2a74be3a..c6e126612 100644
--- a/packages/cli/src/commands/bug-report-bundle.test.ts
+++ b/packages/cli/src/commands/bug-report-bundle.test.ts
@@ -4,11 +4,11 @@
* directory is injected so tests never touch the real `~/.ok`.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
collectStandardBundle,
defaultBugReportZipPath,
diff --git a/packages/cli/src/commands/bug-report-redact.test.ts b/packages/cli/src/commands/bug-report-redact.test.ts
index e6f3c8922..a9032ce71 100644
--- a/packages/cli/src/commands/bug-report-redact.test.ts
+++ b/packages/cli/src/commands/bug-report-redact.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { redactContent } from './bug-report-redact.ts';
describe('redactContent', () => {
diff --git a/packages/cli/src/commands/clean.test.ts b/packages/cli/src/commands/clean.test.ts
index 245fa8c83..71eeb83f0 100644
--- a/packages/cli/src/commands/clean.test.ts
+++ b/packages/cli/src/commands/clean.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildCleanPlan, runClean } from './clean.ts';
import type { LockState } from './lock-state.ts';
diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.ts
index fccaaa008..e29f3a235 100644
--- a/packages/cli/src/commands/clone.test.ts
+++ b/packages/cli/src/commands/clone.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, it, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import type { Config } from '@inkeep/open-knowledge-server';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
+import { afterEach, beforeEach, describe, expect, it, test } from 'vitest';
import type { TokenStore } from '../auth/token-store.ts';
import { OK_DIR } from '../constants.ts';
import {
diff --git a/packages/cli/src/commands/config.test.ts b/packages/cli/src/commands/config.test.ts
index 27115eae8..029fdb500 100644
--- a/packages/cli/src/commands/config.test.ts
+++ b/packages/cli/src/commands/config.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { REMOVED_KEYS } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { CONFIG_FILENAME, OK_DIR } from '../constants.ts';
import { buildClearPatchForTest, DROPPED_FIELD_PATHS, runMigrate, runValidate } from './config.ts';
diff --git a/packages/cli/src/commands/cowork.test.ts b/packages/cli/src/commands/cowork.test.ts
index a39fb39b7..41d6e7155 100644
--- a/packages/cli/src/commands/cowork.test.ts
+++ b/packages/cli/src/commands/cowork.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import type { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync, statSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { runCoworkSkill } from './cowork.ts';
/**
diff --git a/packages/cli/src/commands/deinit.test.ts b/packages/cli/src/commands/deinit.test.ts
index 446508b2e..3815a6cad 100644
--- a/packages/cli/src/commands/deinit.test.ts
+++ b/packages/cli/src/commands/deinit.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { runDeinit } from './deinit.ts';
import { buildManagedServerEntry } from './editors.ts';
diff --git a/packages/cli/src/commands/diagnose-bundle.test.ts b/packages/cli/src/commands/diagnose-bundle.test.ts
index 8c211a09b..622e6c672 100644
--- a/packages/cli/src/commands/diagnose-bundle.test.ts
+++ b/packages/cli/src/commands/diagnose-bundle.test.ts
@@ -8,11 +8,11 @@
* deps are injected.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { type RunDiagnoseBundleDeps, runDiagnoseBundle } from './diagnose.ts';
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/commands/diagnose-health-checks/bun.test.ts b/packages/cli/src/commands/diagnose-health-checks/bun.test.ts
index 4aa109c72..176f52edb 100644
--- a/packages/cli/src/commands/diagnose-health-checks/bun.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/bun.test.ts
@@ -3,7 +3,7 @@
* the host PATH.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { makeBunCheck } from './bun.ts';
const ctx = { cwd: '/tmp/bun-check-test' };
diff --git a/packages/cli/src/commands/diagnose-health-checks/config-yaml.test.ts b/packages/cli/src/commands/diagnose-health-checks/config-yaml.test.ts
index bd9232973..50454c7df 100644
--- a/packages/cli/src/commands/diagnose-health-checks/config-yaml.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/config-yaml.test.ts
@@ -3,10 +3,10 @@
* paths via a fresh tmp project per case.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { makeConfigYamlCheck } from './config-yaml.ts';
let tmpDirs: string[] = [];
diff --git a/packages/cli/src/commands/diagnose-health-checks/content-dir.test.ts b/packages/cli/src/commands/diagnose-health-checks/content-dir.test.ts
index 778e44e79..94657e5c9 100644
--- a/packages/cli/src/commands/diagnose-health-checks/content-dir.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/content-dir.test.ts
@@ -3,10 +3,10 @@
* fail (missing dir), fail (not-a-directory), fail (not writable).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { makeContentDirCheck } from './content-dir.ts';
let tmpDirs: string[] = [];
diff --git a/packages/cli/src/commands/diagnose-health-checks/git.test.ts b/packages/cli/src/commands/diagnose-health-checks/git.test.ts
index 7e230421e..ff817dbf5 100644
--- a/packages/cli/src/commands/diagnose-health-checks/git.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/git.test.ts
@@ -3,13 +3,13 @@
* the runner-host's actual git binary.
*/
-import { describe, expect, test } from 'bun:test';
import {
type GitDetected,
GitNotAvailableError,
GitTooOldError,
type InstallGuidance,
} from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { makeGitCheck } from './git.ts';
const ctx = { cwd: '/tmp/git-check-test' };
diff --git a/packages/cli/src/commands/diagnose-health-checks/macos-codesig.test.ts b/packages/cli/src/commands/diagnose-health-checks/macos-codesig.test.ts
index f4a03ad73..d3d4d3da0 100644
--- a/packages/cli/src/commands/diagnose-health-checks/macos-codesig.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/macos-codesig.test.ts
@@ -4,7 +4,7 @@
* pass/fail branches.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { makeMacosCodesigCheck } from './macos-codesig.ts';
const ctx = { cwd: '/tmp/macos-codesig-test' };
diff --git a/packages/cli/src/commands/diagnose-health-checks/runner.test.ts b/packages/cli/src/commands/diagnose-health-checks/runner.test.ts
index 2ebb10bea..fc0571808 100644
--- a/packages/cli/src/commands/diagnose-health-checks/runner.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/runner.test.ts
@@ -3,7 +3,7 @@
* contracts in isolation from any check implementation.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type CheckDefinition, DEFAULT_CHECK_TIMEOUT_MS, runCheck } from './index.ts';
const fakeCtx = { cwd: '/tmp/runner-test' };
diff --git a/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts b/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts
index 9205e6094..39fb1c73a 100644
--- a/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts
@@ -3,11 +3,11 @@
* alive / foreign-host / dead-pid / corrupt) and the no-lockdir case.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { ProcessLockMetadata } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import type { LockState } from '../lock-state.ts';
import { makeServerLockCheck } from './server-lock.ts';
diff --git a/packages/cli/src/commands/diagnose-health-checks/shadow-health.test.ts b/packages/cli/src/commands/diagnose-health-checks/shadow-health.test.ts
index 9a234a24a..4089192f8 100644
--- a/packages/cli/src/commands/diagnose-health-checks/shadow-health.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/shadow-health.test.ts
@@ -4,10 +4,10 @@
* shadow repo; the no-init warn paths use real dirs.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { makeShadowHealthCheck, type ShadowHealthFacts } from './shadow-health.ts';
let tmpDirs: string[] = [];
diff --git a/packages/cli/src/commands/diagnose-health-checks/shadow-repo.test.ts b/packages/cli/src/commands/diagnose-health-checks/shadow-repo.test.ts
index dabf59808..62b731b1e 100644
--- a/packages/cli/src/commands/diagnose-health-checks/shadow-repo.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/shadow-repo.test.ts
@@ -4,11 +4,11 @@
* pass-with-HEAD branch.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { MalformedGitPointerError } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { makeShadowRepoCheck } from './shadow-repo.ts';
let tmpDirs: string[] = [];
diff --git a/packages/cli/src/commands/diagnose-health.test.ts b/packages/cli/src/commands/diagnose-health.test.ts
index 636629c4a..f9032457d 100644
--- a/packages/cli/src/commands/diagnose-health.test.ts
+++ b/packages/cli/src/commands/diagnose-health.test.ts
@@ -12,7 +12,7 @@
* filesystem state is required.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { runHealthChecks } from './diagnose-health.ts';
import type { CheckDefinition, CheckResult } from './diagnose-health-checks/index.ts';
diff --git a/packages/cli/src/commands/diagnose.test.ts b/packages/cli/src/commands/diagnose.test.ts
index ceb2bce4e..f6c3c3b36 100644
--- a/packages/cli/src/commands/diagnose.test.ts
+++ b/packages/cli/src/commands/diagnose.test.ts
@@ -4,10 +4,10 @@
* All subprocess calls and filesystem side effects are injected via deps.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { runDiagnose } from './diagnose.ts';
import type { LockState } from './lock-state.ts';
diff --git a/packages/cli/src/commands/editor-targets-lockstep.test.ts b/packages/cli/src/commands/editor-targets-lockstep.test.ts
index 4310eeca9..32c7d21b9 100644
--- a/packages/cli/src/commands/editor-targets-lockstep.test.ts
+++ b/packages/cli/src/commands/editor-targets-lockstep.test.ts
@@ -9,8 +9,8 @@
* `projectSkillPath`. If the CLI map drifts from the core root, this fails.
*/
-import { describe, expect, test } from 'bun:test';
import { ALL_EDITOR_IDS, EDITOR_PROJECT_SKILL_ROOT } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { EDITOR_TARGETS } from './editors.ts';
describe('EDITOR_TARGETS project-skill path lockstep with core root', () => {
diff --git a/packages/cli/src/commands/embeddings/index.test.ts b/packages/cli/src/commands/embeddings/index.test.ts
index d9d5d070a..74b76ae7f 100644
--- a/packages/cli/src/commands/embeddings/index.test.ts
+++ b/packages/cli/src/commands/embeddings/index.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DEFAULT_EMBEDDINGS_BASE_URL } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { embeddingsCommand } from './index.ts';
function readLocalConfig(dir: string): string {
diff --git a/packages/cli/src/commands/launch-json-removal.test.ts b/packages/cli/src/commands/launch-json-removal.test.ts
index 69a247662..002efc05b 100644
--- a/packages/cli/src/commands/launch-json-removal.test.ts
+++ b/packages/cli/src/commands/launch-json-removal.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { LAUNCH_CONFIG_NAME } from './init.ts';
import { removeOwnLaunchEntry } from './launch-json-removal.ts';
diff --git a/packages/cli/src/commands/lint.test.ts b/packages/cli/src/commands/lint.test.ts
index 0373e2df5..ee436466e 100644
--- a/packages/cli/src/commands/lint.test.ts
+++ b/packages/cli/src/commands/lint.test.ts
@@ -4,8 +4,8 @@
* shaping against a synthetic result (no fs).
*/
-import { describe, expect, test } from 'bun:test';
import { isAbsolute } from 'node:path';
+import { describe, expect, test } from 'vitest';
import type { LintRunResult } from '../content/lint-runner.ts';
import { formatLintReport, resolveTarget } from './lint.ts';
diff --git a/packages/cli/src/commands/lock-state.test.ts b/packages/cli/src/commands/lock-state.test.ts
index 9088bc35e..1aec06653 100644
--- a/packages/cli/src/commands/lock-state.test.ts
+++ b/packages/cli/src/commands/lock-state.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { inspectLock } from './lock-state.ts';
function freshLockDir(): string {
diff --git a/packages/cli/src/commands/mcp-config-removal.test.ts b/packages/cli/src/commands/mcp-config-removal.test.ts
index 90c537b7d..90fc1b855 100644
--- a/packages/cli/src/commands/mcp-config-removal.test.ts
+++ b/packages/cli/src/commands/mcp-config-removal.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { buildPiExtensionSource } from '../integrations/pi-extension.ts';
import {
createTomlConfigEngine,
diff --git a/packages/cli/src/commands/mcp-migrate-event.test.ts b/packages/cli/src/commands/mcp-migrate-event.test.ts
index d66947099..f8d51db51 100644
--- a/packages/cli/src/commands/mcp-migrate-event.test.ts
+++ b/packages/cli/src/commands/mcp-migrate-event.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'bun:test';
+import { describe, expect, it } from 'vitest';
import { buildMcpConfigMigrateEvent } from './mcp-migrate-event.ts';
describe('buildMcpConfigMigrateEvent', () => {
diff --git a/packages/cli/src/commands/mcp-symlink-write-through.test.ts b/packages/cli/src/commands/mcp-symlink-write-through.test.ts
index 38a8af699..04c3de692 100644
--- a/packages/cli/src/commands/mcp-symlink-write-through.test.ts
+++ b/packages/cli/src/commands/mcp-symlink-write-through.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, it } from 'bun:test';
import { lstatSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
import {
createTomlConfigEngine,
setTomlConfigEngineForTesting,
diff --git a/packages/cli/src/commands/migrate.test.ts b/packages/cli/src/commands/migrate.test.ts
index dfbfada04..5153555d5 100644
--- a/packages/cli/src/commands/migrate.test.ts
+++ b/packages/cli/src/commands/migrate.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { makeTree } from './migrate/notion/mktree.test-helper.ts';
import { migrateCommand } from './migrate.ts';
diff --git a/packages/cli/src/commands/migrate/notion/aside-callout.test.ts b/packages/cli/src/commands/migrate/notion/aside-callout.test.ts
index 43d4a26d4..c62667e3d 100644
--- a/packages/cli/src/commands/migrate/notion/aside-callout.test.ts
+++ b/packages/cli/src/commands/migrate/notion/aside-callout.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { asideToCallout } from './aside-callout.ts';
describe('asideToCallout', () => {
diff --git a/packages/cli/src/commands/migrate/notion/base64-images.test.ts b/packages/cli/src/commands/migrate/notion/base64-images.test.ts
index 30e081018..db02854bc 100644
--- a/packages/cli/src/commands/migrate/notion/base64-images.test.ts
+++ b/packages/cli/src/commands/migrate/notion/base64-images.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { extractBase64Images } from './base64-images.ts';
// 1x1 transparent PNG.
diff --git a/packages/cli/src/commands/migrate/notion/csv.test.ts b/packages/cli/src/commands/migrate/notion/csv.test.ts
index 2b91b4e5b..137d2f714 100644
--- a/packages/cli/src/commands/migrate/notion/csv.test.ts
+++ b/packages/cli/src/commands/migrate/notion/csv.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseCsv } from './csv.ts';
describe('parseCsv', () => {
diff --git a/packages/cli/src/commands/migrate/notion/decode-links.test.ts b/packages/cli/src/commands/migrate/notion/decode-links.test.ts
index 504e247eb..e07442021 100644
--- a/packages/cli/src/commands/migrate/notion/decode-links.test.ts
+++ b/packages/cli/src/commands/migrate/notion/decode-links.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { decodeLinks } from './decode-links.ts';
const ID = '30545f35b5ad80a38049d283dae66763';
diff --git a/packages/cli/src/commands/migrate/notion/detect.test.ts b/packages/cli/src/commands/migrate/notion/detect.test.ts
index 092071769..b6f18579e 100644
--- a/packages/cli/src/commands/migrate/notion/detect.test.ts
+++ b/packages/cli/src/commands/migrate/notion/detect.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isNotionExport } from './detect.ts';
import { makeTree } from './mktree.test-helper.ts';
diff --git a/packages/cli/src/commands/migrate/notion/fs-walk.test.ts b/packages/cli/src/commands/migrate/notion/fs-walk.test.ts
index 0a73a80ec..d53f52481 100644
--- a/packages/cli/src/commands/migrate/notion/fs-walk.test.ts
+++ b/packages/cli/src/commands/migrate/notion/fs-walk.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { symlinkSync } from 'node:fs';
import { basename, join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { walkFiles } from './fs-walk.ts';
import { makeTree } from './mktree.test-helper.ts';
diff --git a/packages/cli/src/commands/migrate/notion/normalized-index.test.ts b/packages/cli/src/commands/migrate/notion/normalized-index.test.ts
index 6f42bbda1..72f84a129 100644
--- a/packages/cli/src/commands/migrate/notion/normalized-index.test.ts
+++ b/packages/cli/src/commands/migrate/notion/normalized-index.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildIndex, normalizeKey, resolveKey } from './normalized-index.ts';
const ID = '30545f35b5ad80a38049d283dae66763';
diff --git a/packages/cli/src/commands/migrate/notion/plan.test.ts b/packages/cli/src/commands/migrate/notion/plan.test.ts
index 784b275d3..51a5fd478 100644
--- a/packages/cli/src/commands/migrate/notion/plan.test.ts
+++ b/packages/cli/src/commands/migrate/notion/plan.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
import { walkFiles } from './fs-walk.ts';
import { makeTree, read } from './mktree.test-helper.ts';
import { applyPlan, buildPlan } from './plan.ts';
diff --git a/packages/cli/src/commands/migrate/notion/properties-frontmatter.test.ts b/packages/cli/src/commands/migrate/notion/properties-frontmatter.test.ts
index d74d0d9e3..308640915 100644
--- a/packages/cli/src/commands/migrate/notion/properties-frontmatter.test.ts
+++ b/packages/cli/src/commands/migrate/notion/properties-frontmatter.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { propertiesToFrontmatter } from './properties-frontmatter.ts';
const KEYS = new Set(['Status', 'Owner', 'Priority', 'White-Paper / E-Book?', 'Target Metric']);
diff --git a/packages/cli/src/commands/migrate/notion/tables.test.ts b/packages/cli/src/commands/migrate/notion/tables.test.ts
index 2a9bdc7f6..e55264c0a 100644
--- a/packages/cli/src/commands/migrate/notion/tables.test.ts
+++ b/packages/cli/src/commands/migrate/notion/tables.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildStubPage, extractStubTitle, renderCsvTable } from './tables.ts';
describe('renderCsvTable', () => {
diff --git a/packages/cli/src/commands/open.test.ts b/packages/cli/src/commands/open.test.ts
index 0a6790449..fed2eddde 100644
--- a/packages/cli/src/commands/open.test.ts
+++ b/packages/cli/src/commands/open.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createRealOpenDeps, type OpenDeps, runOpen } from './open.ts';
function makeDeps(overrides: Partial<OpenDeps> = {}): {
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index 8db104aac..7621a74bf 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { type Config, ConfigSchema } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { OK_DIR } from '../constants.ts';
import { formatPreviewBlock, previewContent } from '../content/preview.ts';
diff --git a/packages/cli/src/commands/ps.test.ts b/packages/cli/src/commands/ps.test.ts
index 18b965dbb..596d5f42d 100644
--- a/packages/cli/src/commands/ps.test.ts
+++ b/packages/cli/src/commands/ps.test.ts
@@ -5,7 +5,7 @@
* argument — no actual processes or lock files needed.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { extractOkBinaryPath } from '../utils/process-scan.ts';
import type { LockState } from './lock-state.ts';
import { isDesktopCommand, renderTable, runPs, timeAgo } from './ps.ts';
diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.ts
index 909bbc55a..917754b69 100644
--- a/packages/cli/src/commands/removal-plan.test.ts
+++ b/packages/cli/src/commands/removal-plan.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import {
chmodSync,
existsSync,
@@ -13,6 +12,7 @@ import {
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { MCP_SERVER_NAME } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { readPathInstallMarker } from '../integrations/path-shim.ts';
import { buildManagedServerEntry } from './editors.ts';
import {
diff --git a/packages/cli/src/commands/repair-launch-json.test.ts b/packages/cli/src/commands/repair-launch-json.test.ts
index 384ae00f4..ecc060f84 100644
--- a/packages/cli/src/commands/repair-launch-json.test.ts
+++ b/packages/cli/src/commands/repair-launch-json.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { type LaunchJsonRepairLogEvent, repairLaunchJson } from './repair-launch-json.ts';
// OK no longer scaffolds `.claude/launch.json`; the `ok start` repair sweep now
diff --git a/packages/cli/src/commands/repair-mcp-configs.test.ts b/packages/cli/src/commands/repair-mcp-configs.test.ts
index 771408a01..16ecc5e72 100644
--- a/packages/cli/src/commands/repair-mcp-configs.test.ts
+++ b/packages/cli/src/commands/repair-mcp-configs.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { buildManagedServerEntry, resolveClaudeCodeConfigPath } from './editors.ts';
import { type RepairLogEvent, repairMcpConfigs } from './repair-mcp-configs.ts';
diff --git a/packages/cli/src/commands/repair-skills.test.ts b/packages/cli/src/commands/repair-skills.test.ts
index e04003845..bee029b1f 100644
--- a/packages/cli/src/commands/repair-skills.test.ts
+++ b/packages/cli/src/commands/repair-skills.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import type { SkillInstallEvent } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { EDITOR_TARGETS } from './editors.ts';
import {
__testing,
diff --git a/packages/cli/src/commands/seed.test.ts b/packages/cli/src/commands/seed.test.ts
index 511386cde..e28201e49 100644
--- a/packages/cli/src/commands/seed.test.ts
+++ b/packages/cli/src/commands/seed.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { STARTER_PACKS } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { CONFIG_FILENAME, OK_DIR } from '../constants.ts';
import { runSeed } from './seed.ts';
diff --git a/packages/cli/src/commands/self-spawn.test.ts b/packages/cli/src/commands/self-spawn.test.ts
index 5be94ad03..5774c2a55 100644
--- a/packages/cli/src/commands/self-spawn.test.ts
+++ b/packages/cli/src/commands/self-spawn.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, it, spyOn, test } from 'bun:test';
import {
HELPER_BUNDLE_NAME,
HELPER_EXECUTABLE_NAME,
resolveHelperBundleBinary,
} from '@inkeep/open-knowledge-core/helper-bundle';
+import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest';
import { maybeRedirectToHelperBundle, resolveSelfSpawn } from './self-spawn.ts';
const PACKAGED_APP = '/Applications/OpenKnowledge.app';
@@ -72,13 +72,13 @@ describe('maybeRedirectToHelperBundle', () => {
});
describe('resolveSelfSpawn', () => {
- let warnSpy: ReturnType<typeof spyOn>;
+ let warnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
// Squelch + capture the fallback's console.warn so the test output stays
// clean AND we can assert the warning fired (the warning is the only
// operator-visible signal that we hit the rare fallback path).
- warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
diff --git a/packages/cli/src/commands/share/name-check.test.ts b/packages/cli/src/commands/share/name-check.test.ts
index e4d6c7344..8aa747696 100644
--- a/packages/cli/src/commands/share/name-check.test.ts
+++ b/packages/cli/src/commands/share/name-check.test.ts
@@ -3,8 +3,8 @@
* decision tree without spawning Octokit or hitting GitHub.
*/
-import { describe, expect, test } from 'bun:test';
import type { Octokit } from '@octokit/rest';
+import { describe, expect, test } from 'vitest';
import { checkSharePublishName } from './name-check.ts';
function makeFakeOctokit(behavior: { status?: number; message?: string; ok?: boolean }): Octokit {
diff --git a/packages/cli/src/commands/share/owners.test.ts b/packages/cli/src/commands/share/owners.test.ts
index 4e2f9b807..693429cc1 100644
--- a/packages/cli/src/commands/share/owners.test.ts
+++ b/packages/cli/src/commands/share/owners.test.ts
@@ -4,8 +4,8 @@
* stubbed; no network or token-store work happens in this file.
*/
-import { describe, expect, test } from 'bun:test';
import type { Octokit } from '@octokit/rest';
+import { describe, expect, test } from 'vitest';
import { listShareOwners } from './owners.ts';
interface OrgMembershipFixture {
diff --git a/packages/cli/src/commands/sharing/sharing.test.ts b/packages/cli/src/commands/sharing/sharing.test.ts
index 0de3f2210..8b5f268b3 100644
--- a/packages/cli/src/commands/sharing/sharing.test.ts
+++ b/packages/cli/src/commands/sharing/sharing.test.ts
@@ -8,11 +8,11 @@
* mechanics are pinned in `../../sharing/git-exclude.test.ts`.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { sharingShareCommand } from './share.ts';
import { sharingStatusCommand } from './status.ts';
import { sharingUnshareCommand } from './unshare.ts';
diff --git a/packages/cli/src/commands/single-file-dispatch.test.ts b/packages/cli/src/commands/single-file-dispatch.test.ts
index 79ec782e3..4e5e68e6d 100644
--- a/packages/cli/src/commands/single-file-dispatch.test.ts
+++ b/packages/cli/src/commands/single-file-dispatch.test.ts
@@ -1,7 +1,7 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import {
decideSingleFileTarget,
hasMarkdownExtension,
diff --git a/packages/cli/src/commands/single-file-open.test.ts b/packages/cli/src/commands/single-file-open.test.ts
index a4b017d69..61c50a031 100644
--- a/packages/cli/src/commands/single-file-open.test.ts
+++ b/packages/cli/src/commands/single-file-open.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import {
SingleFileNotFoundError,
SingleFileNotMarkdownError,
type SingleFileOpenPlan,
} from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { runSingleFileOpen, type SingleFileOpenDeps } from './single-file-open.ts';
interface Recorder {
diff --git a/packages/cli/src/commands/status.test.ts b/packages/cli/src/commands/status.test.ts
index 19eccc8fc..c0ac288ad 100644
--- a/packages/cli/src/commands/status.test.ts
+++ b/packages/cli/src/commands/status.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { LockState } from './lock-state.ts';
import { buildStatusReport, renderStatusText, runStatus } from './status.ts';
diff --git a/packages/cli/src/commands/stop.test.ts b/packages/cli/src/commands/stop.test.ts
index d447edb9d..c14cd3769 100644
--- a/packages/cli/src/commands/stop.test.ts
+++ b/packages/cli/src/commands/stop.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { LockState } from './lock-state.ts';
import { buildStopPlan, runStop } from './stop.ts';
diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.ts
index d93feaa6b..34fed4c65 100644
--- a/packages/cli/src/commands/sync.test.ts
+++ b/packages/cli/src/commands/sync.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Config } from '@inkeep/open-knowledge-server';
import { RUNTIME_VERSION } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { runSync } from './sync.ts';
// runSync delegates to a running server via `POST /api/sync/trigger` when a live
diff --git a/packages/cli/src/commands/ui-proxy.test.ts b/packages/cli/src/commands/ui-proxy.test.ts
index 58424d9ac..eee153ddc 100644
--- a/packages/cli/src/commands/ui-proxy.test.ts
+++ b/packages/cli/src/commands/ui-proxy.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import {
createServer as createHttpServer,
type Server as HttpServer,
request as httpRequest,
type IncomingMessage,
} from 'node:http';
+import { afterEach, describe, expect, test } from 'vitest';
import { type ProxyServerHandle, startProxyServer } from './ui-proxy.ts';
/** Send a request with arbitrary Host / Origin headers. We can't use `fetch`
diff --git a/packages/cli/src/commands/ui.test.ts b/packages/cli/src/commands/ui.test.ts
index 8ce3ebcaf..35704570d 100644
--- a/packages/cli/src/commands/ui.test.ts
+++ b/packages/cli/src/commands/ui.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -24,6 +23,7 @@ import {
type UiLockMetadata,
updateServerLockPort,
} from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
closeHttpServers,
DEFAULT_UI_PORT,
diff --git a/packages/cli/src/commands/uninstall.test.ts b/packages/cli/src/commands/uninstall.test.ts
index 3733a6fbe..2254d6ae5 100644
--- a/packages/cli/src/commands/uninstall.test.ts
+++ b/packages/cli/src/commands/uninstall.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { detectInstallMethods, resolveRecentDeinitProjects, runUninstall } from './uninstall.ts';
function write(path: string, content: string): void {
diff --git a/packages/cli/src/config/loader.test.ts b/packages/cli/src/config/loader.test.ts
index 2c16e7fbd..cf66d0835 100644
--- a/packages/cli/src/config/loader.test.ts
+++ b/packages/cli/src/config/loader.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, mock, test, vi } from 'bun:test';
import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
let testDir: string;
// Seed a real default so the loader's transitive homedir() call at import time
@@ -14,7 +14,7 @@ let fakeHome: string = resolve(tmpdir(), '__ok_home_default__');
// config) doesn't read the real `~/.ok/global.yml` and pollute
// every test that asserts on `sources`. Bun caches the resolved homedir on
// first call, so mutating `process.env.HOME` in beforeEach is too late.
-await mock.module('node:os', async () => {
+await vi.doMock('node:os', async () => {
const actual = await vi.importActual<typeof import('node:os')>('node:os');
return {
...actual,
diff --git a/packages/cli/src/config/paths.test.ts b/packages/cli/src/config/paths.test.ts
index fc948f1cb..ca9c60ff2 100644
--- a/packages/cli/src/config/paths.test.ts
+++ b/packages/cli/src/config/paths.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { getLocalDir } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { resolveContentDir, resolveLockDir } from './paths.ts';
import type { Config } from './schema.ts';
diff --git a/packages/cli/src/config/schema.test.ts b/packages/cli/src/config/schema.test.ts
index a8125cd11..94b4ee3a4 100644
--- a/packages/cli/src/config/schema.test.ts
+++ b/packages/cli/src/config/schema.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { ConfigSchema } from './schema';
describe('ConfigSchema', () => {
diff --git a/packages/cli/src/content/lint-runner.test.ts b/packages/cli/src/content/lint-runner.test.ts
index 4c38b7ae7..4ab061263 100644
--- a/packages/cli/src/content/lint-runner.test.ts
+++ b/packages/cli/src/content/lint-runner.test.ts
@@ -6,11 +6,11 @@
* production.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DEFAULT_LINTER_CONFIG } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { runLint } from './lint-runner.ts';
let root: string;
diff --git a/packages/cli/src/content/preview.test.ts b/packages/cli/src/content/preview.test.ts
index 9f86906c5..0287bc9cd 100644
--- a/packages/cli/src/content/preview.test.ts
+++ b/packages/cli/src/content/preview.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { OK_DIR } from '../constants.ts';
import { previewContent } from './preview.ts';
diff --git a/packages/cli/src/content/published-schema.test.ts b/packages/cli/src/content/published-schema.test.ts
index 192ae4bc9..93e28c4f1 100644
--- a/packages/cli/src/content/published-schema.test.ts
+++ b/packages/cli/src/content/published-schema.test.ts
@@ -17,12 +17,13 @@
* the published artifact is current + ajv-compilable. If it goes stale,
* `bun run --filter=@inkeep/open-knowledge build:schema` regenerates it.
*/
-import { beforeEach, describe, expect, test, vi } from 'bun:test';
+
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
const here = dirname(fileURLToPath(import.meta.url));
const DIST = resolve(here, '..', '..', 'dist');
diff --git a/packages/cli/src/diagnose/path-parity.test.ts b/packages/cli/src/diagnose/path-parity.test.ts
index 91b6f4c9c..5bdd0e9d4 100644
--- a/packages/cli/src/diagnose/path-parity.test.ts
+++ b/packages/cli/src/diagnose/path-parity.test.ts
@@ -12,13 +12,13 @@
* asserting equivalence — when they drift, this test fails.
*/
-import { describe, expect, test } from 'bun:test';
import {
logsCurrentPath as serverLogsCurrentPath,
logsPreviousPath as serverLogsPreviousPath,
spansCurrentPath as serverSpansCurrentPath,
spansPreviousPath as serverSpansPreviousPath,
} from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { _pathHelpersForTests } from './bundle.ts';
describe('CLI bundle path helpers — parity with server telemetry-file-sink', () => {
diff --git a/packages/cli/src/github/visibility.test.ts b/packages/cli/src/github/visibility.test.ts
index 2682cd19a..7235f61f9 100644
--- a/packages/cli/src/github/visibility.test.ts
+++ b/packages/cli/src/github/visibility.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type FetchFn, isGitHubRepoPublic } from './visibility.ts';
function mockFetch(handler: (url: string, init?: RequestInit) => Response | Promise<Response>): {
diff --git a/packages/cli/src/integrations/desktop-state.test.ts b/packages/cli/src/integrations/desktop-state.test.ts
index 22d7be8fd..695b8a773 100644
--- a/packages/cli/src/integrations/desktop-state.test.ts
+++ b/packages/cli/src/integrations/desktop-state.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
DESKTOP_LEGACY_PRODUCT_NAME,
DESKTOP_PRODUCT_NAME,
diff --git a/packages/cli/src/integrations/path-shim.test.ts b/packages/cli/src/integrations/path-shim.test.ts
index 0d82663db..fc79263ad 100644
--- a/packages/cli/src/integrations/path-shim.test.ts
+++ b/packages/cli/src/integrations/path-shim.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
extraSymlinkStillOurs,
PATH_SHIM_BEGIN,
diff --git a/packages/cli/src/integrations/remove-project-skill.test.ts b/packages/cli/src/integrations/remove-project-skill.test.ts
index 83b38dd99..7320f5bb2 100644
--- a/packages/cli/src/integrations/remove-project-skill.test.ts
+++ b/packages/cli/src/integrations/remove-project-skill.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { EDITOR_TARGETS } from '../commands/editors.ts';
import { removeProjectSkill } from './write-project-skill.ts';
diff --git a/packages/cli/src/integrations/resolve-project-root.test.ts b/packages/cli/src/integrations/resolve-project-root.test.ts
index 0fcac8095..7038503b4 100644
--- a/packages/cli/src/integrations/resolve-project-root.test.ts
+++ b/packages/cli/src/integrations/resolve-project-root.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
type ResolveProjectRootOptions,
type ResolveProjectRootResult,
diff --git a/packages/cli/src/integrations/skill-teardown.test.ts b/packages/cli/src/integrations/skill-teardown.test.ts
index 5cd35a62c..1dedbdcbe 100644
--- a/packages/cli/src/integrations/skill-teardown.test.ts
+++ b/packages/cli/src/integrations/skill-teardown.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { join } from 'node:path';
import { BUNDLE_SKILL_NAME, USER_GLOBAL_BUNDLE_IDS } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { HOSTS_WITH_USER_SKILL_DIR } from '../commands/editors.ts';
import { userGlobalSkillBundleTargets } from './skill-teardown.ts';
diff --git a/packages/cli/src/integrations/write-project-ai-integrations.test.ts b/packages/cli/src/integrations/write-project-ai-integrations.test.ts
index 52f04babd..2417707ae 100644
--- a/packages/cli/src/integrations/write-project-ai-integrations.test.ts
+++ b/packages/cli/src/integrations/write-project-ai-integrations.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { ALL_EDITOR_IDS } from '../commands/editors.ts';
import { writeProjectAiIntegrations } from './write-project-ai-integrations.ts';
diff --git a/packages/cli/src/loopback-bind-discipline.test.ts b/packages/cli/src/loopback-bind-discipline.test.ts
index 0781979d0..fcf3c6258 100644
--- a/packages/cli/src/loopback-bind-discipline.test.ts
+++ b/packages/cli/src/loopback-bind-discipline.test.ts
@@ -33,10 +33,10 @@
* each package's test cache invalidates with its own sources.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { basename, dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PACKAGE_ROOT = join(__dirname, '..');
diff --git a/packages/cli/src/mcp/bridge-e2e.test.ts b/packages/cli/src/mcp/bridge-e2e.test.ts
index 710bf109b..1e45b0571 100644
--- a/packages/cli/src/mcp/bridge-e2e.test.ts
+++ b/packages/cli/src/mcp/bridge-e2e.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer as createHttpServer, type Server as HttpServer } from 'node:http';
import type { AddressInfo } from 'node:net';
@@ -14,6 +13,7 @@ import {
type McpHttpHandler,
RUNTIME_VERSION,
} from '@inkeep/open-knowledge-server';
+import { afterEach, expect, test } from 'vitest';
import { bridgeStdioToHttpMcp } from './shim.ts';
const MCP_PROTOCOL_VERSION = '2025-06-18';
diff --git a/packages/cli/src/mcp/bundle-identity.test.ts b/packages/cli/src/mcp/bundle-identity.test.ts
index 9191ea521..ea99b9d26 100644
--- a/packages/cli/src/mcp/bundle-identity.test.ts
+++ b/packages/cli/src/mcp/bundle-identity.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type BundleIdentityCheckInput,
type BundleIdentityState,
diff --git a/packages/cli/src/mcp/bundle-proxy.test.ts b/packages/cli/src/mcp/bundle-proxy.test.ts
index 0f678d4e3..c40354c96 100644
--- a/packages/cli/src/mcp/bundle-proxy.test.ts
+++ b/packages/cli/src/mcp/bundle-proxy.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { EventEmitter } from 'node:events';
+import { describe, expect, test } from 'vitest';
import {
emitBundleProxyEvent,
findBundledOkPath,
diff --git a/packages/cli/src/mcp/host-liveness.test.ts b/packages/cli/src/mcp/host-liveness.test.ts
index e5261b3c1..79fc4768b 100644
--- a/packages/cli/src/mcp/host-liveness.test.ts
+++ b/packages/cli/src/mcp/host-liveness.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type HostLivenessScheduler, startHostLivenessWatch } from './host-liveness.ts';
/**
diff --git a/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts b/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts
index 50e88d7af..c7b65870a 100644
--- a/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts
+++ b/packages/cli/src/mcp/keepalive-orphan-reaping.test.ts
@@ -40,13 +40,13 @@
* gate provides before tests run.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFileSync, spawn } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
+import { afterEach, describe, expect, test } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url));
// packages/cli/src/mcp -> packages/cli/dist/cli.mjs. The built entry (required
diff --git a/packages/cli/src/mcp/lifecycle-logging.test.ts b/packages/cli/src/mcp/lifecycle-logging.test.ts
index 8f80519c7..7c65e2b67 100644
--- a/packages/cli/src/mcp/lifecycle-logging.test.ts
+++ b/packages/cli/src/mcp/lifecycle-logging.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
attachLifecycleLogging,
type LifecycleLoggingProcess,
diff --git a/packages/cli/src/mcp/server.test.ts b/packages/cli/src/mcp/server.test.ts
index 8613108dc..1a669fc6c 100644
--- a/packages/cli/src/mcp/server.test.ts
+++ b/packages/cli/src/mcp/server.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { sanitizeClientName } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
countWorktrees,
findProjectDir,
diff --git a/packages/cli/src/mcp/shim.test.ts b/packages/cli/src/mcp/shim.test.ts
index feda70785..77d5c6828 100644
--- a/packages/cli/src/mcp/shim.test.ts
+++ b/packages/cli/src/mcp/shim.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
@@ -6,6 +5,7 @@ import { setTimeout as wait } from 'node:timers/promises';
import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';
import { AutoStartDisabledError, type ServerLockMetadata } from '@inkeep/open-knowledge-server';
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
bridgeStdioToHttpMcp,
parseSpawnTimeoutEnv,
diff --git a/packages/cli/src/mcp/stderr-mirror.test.ts b/packages/cli/src/mcp/stderr-mirror.test.ts
index e14d65602..79328bb23 100644
--- a/packages/cli/src/mcp/stderr-mirror.test.ts
+++ b/packages/cli/src/mcp/stderr-mirror.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
closeSync,
existsSync,
@@ -12,6 +11,7 @@ import {
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createMcpStderrMirror, pruneMirrorLogs } from './stderr-mirror.ts';
let dir: string;
diff --git a/packages/cli/src/native/load-native-config.test.ts b/packages/cli/src/native/load-native-config.test.ts
index bffd5dd1d..9ee2cff2c 100644
--- a/packages/cli/src/native/load-native-config.test.ts
+++ b/packages/cli/src/native/load-native-config.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { requireNativeConfigModule } from './load-native-config.ts';
/** Run `fn` with OK_DEBUG_NATIVE set and stderr captured; restore both after. */
diff --git a/packages/cli/src/native/toml-config-engine.test.ts b/packages/cli/src/native/toml-config-engine.test.ts
index 1ad0db49c..ea5400cf5 100644
--- a/packages/cli/src/native/toml-config-engine.test.ts
+++ b/packages/cli/src/native/toml-config-engine.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createTomlConfigEngine, type NativeTomlBinding } from './toml-config-engine.ts';
// A config value that exercises the whole point of the native engine: a 64-bit
diff --git a/packages/cli/src/project-anchor.test.ts b/packages/cli/src/project-anchor.test.ts
index f2e594632..f2800326a 100644
--- a/packages/cli/src/project-anchor.test.ts
+++ b/packages/cli/src/project-anchor.test.ts
@@ -1,8 +1,8 @@
-import { afterAll, afterEach, describe, expect, test } from 'bun:test';
import { spawn } from 'node:child_process';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, afterEach, describe, expect, test } from 'vitest';
import { getInvocationCwd, recordInvocationCwd, resolveProjectAnchor } from './project-anchor.ts';
const CLI_PACKAGE_ROOT = import.meta.dir.replace(/\/src$/, '');
diff --git a/packages/cli/src/report-bundle.test.ts b/packages/cli/src/report-bundle.test.ts
index f2ed52e12..7727295be 100644
--- a/packages/cli/src/report-bundle.test.ts
+++ b/packages/cli/src/report-bundle.test.ts
@@ -5,11 +5,11 @@
* `unzip` rather than adding a parser dep.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { collectReportBundle as collectReportBundleFromIndex } from './index.ts';
import { collectReportBundle } from './report-bundle.ts';
diff --git a/packages/cli/src/tsdown-bundle-coverage.test.ts b/packages/cli/src/tsdown-bundle-coverage.test.ts
index ae31c34e5..15f289ee8 100644
--- a/packages/cli/src/tsdown-bundle-coverage.test.ts
+++ b/packages/cli/src/tsdown-bundle-coverage.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
/**
* Regression guard: every runtime JS dep in packages/cli/package.json must
diff --git a/packages/cli/src/ui/banner.test.ts b/packages/cli/src/ui/banner.test.ts
index 42ccfbadb..e10c764b4 100644
--- a/packages/cli/src/ui/banner.test.ts
+++ b/packages/cli/src/ui/banner.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { renderBanner } from './banner.ts';
// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ANSI escape code detection
diff --git a/packages/cli/src/ui/colors.test.ts b/packages/cli/src/ui/colors.test.ts
index 8ea5b34e4..1c7b39d6a 100644
--- a/packages/cli/src/ui/colors.test.ts
+++ b/packages/cli/src/ui/colors.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ANSI escape code detection
const ANSI_RE = /\x1b\[[0-9;]*m/;
diff --git a/packages/cli/src/utils/detached-spawn.test.ts b/packages/cli/src/utils/detached-spawn.test.ts
index 84e8e862e..882d77bf0 100644
--- a/packages/cli/src/utils/detached-spawn.test.ts
+++ b/packages/cli/src/utils/detached-spawn.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { SpawnOptions } from 'node:child_process';
+import { describe, expect, test } from 'vitest';
import { spawnDetachedScrubbed } from './detached-spawn.ts';
describe('spawnDetachedScrubbed', () => {
diff --git a/packages/cli/src/utils/normalize-cwd.test.ts b/packages/cli/src/utils/normalize-cwd.test.ts
index b56939b49..fbb60ca56 100644
--- a/packages/cli/src/utils/normalize-cwd.test.ts
+++ b/packages/cli/src/utils/normalize-cwd.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { relative, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { normalizeCwd } from './normalize-cwd.ts';
describe('normalizeCwd', () => {
diff --git a/packages/cli/src/utils/open-browser.test.ts b/packages/cli/src/utils/open-browser.test.ts
index 456e730b0..85e68e979 100644
--- a/packages/cli/src/utils/open-browser.test.ts
+++ b/packages/cli/src/utils/open-browser.test.ts
@@ -1,14 +1,4 @@
-import {
- describe as _bunDescribe,
- afterEach,
- beforeAll,
- beforeEach,
- expect,
- it,
- mock,
- spyOn,
- vi,
-} from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): subprocess or git child spawns; Bun fails to reap children on ubuntu-latest GHA runners (oven-sh/bun#11892).
// Tests run normally locally; follow-up will narrow the leak surface.
@@ -21,7 +11,7 @@ const execFileMock = vi.fn();
let openBrowser: typeof import('./open-browser.ts')['openBrowser'];
beforeAll(async () => {
- await mock.module('node:child_process', async () => {
+ await vi.doMock('node:child_process', async () => {
const actual = await vi.importActual<typeof import('node:child_process')>('node:child_process');
return { ...actual, execFile: (...args: unknown[]) => execFileMock(...args) };
});
@@ -71,7 +61,7 @@ describe('openBrowser', () => {
it('prints fallback message when launcher fails', () => {
Object.defineProperty(process, 'platform', { value: 'linux' });
- const consoleSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
execFileMock.mockImplementation(((
_cmd: string,
@@ -131,7 +121,7 @@ _bunDescribe('openBrowser URL validation', () => {
for (const url of malicious) {
it(`rejects ${JSON.stringify(url)} without spawning a launcher`, () => {
Object.defineProperty(process, 'platform', { value: 'win32' });
- const consoleSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
openBrowser(url);
@@ -146,7 +136,7 @@ _bunDescribe('openBrowser URL validation', () => {
it('rejects non-http(s) schemes', () => {
Object.defineProperty(process, 'platform', { value: 'darwin' });
- const consoleSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
openBrowser('javascript:alert(1)');
openBrowser('file:///etc/passwd');
@@ -163,7 +153,7 @@ _bunDescribe('openBrowser URL validation', () => {
it('rejects malformed URLs', () => {
Object.defineProperty(process, 'platform', { value: 'darwin' });
- const consoleSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
openBrowser('not a url');
diff --git a/packages/cli/src/version-notice.test.ts b/packages/cli/src/version-notice.test.ts
index b42fce6c0..9d6cc7699 100644
--- a/packages/cli/src/version-notice.test.ts
+++ b/packages/cli/src/version-notice.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildVersionNotice } from './version-notice.ts';
describe('buildVersionNotice', () => {
diff --git a/packages/cli/tests/e2e/cli-linux-e2e.ts b/packages/cli/tests/e2e/cli-linux-e2e.ts
index 8265fe606..a954188ad 100644
--- a/packages/cli/tests/e2e/cli-linux-e2e.ts
+++ b/packages/cli/tests/e2e/cli-linux-e2e.ts
@@ -22,7 +22,6 @@
* native-loader failures.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { type ChildProcess, execFileSync, spawn, spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { connect } from 'node:net';
@@ -31,6 +30,7 @@ import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url));
const CLI_PKG_DIR = resolve(HERE, '..', '..'); // packages/cli
diff --git a/packages/cli/tests/integration/detached-spawn-lifetime.test.ts b/packages/cli/tests/integration/detached-spawn-lifetime.test.ts
index 38218a2ce..81ad29cd0 100644
--- a/packages/cli/tests/integration/detached-spawn-lifetime.test.ts
+++ b/packages/cli/tests/integration/detached-spawn-lifetime.test.ts
@@ -27,13 +27,14 @@
* structurally — but 5s keeps CI fast while still demonstrating the
* grandchild is genuinely independent of the parent's lifecycle.
*/
-import { describe as _describe, afterEach, beforeEach, expect, it } from 'bun:test';
+
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { request as httpRequest } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { describe as _describe, afterEach, beforeEach, expect, it } from 'vitest';
// Skip-on-CI gate: a detached grandchild plus SIGTERM cleanup can strand
// processes on Linux GHA runners. Tests run locally; a follow-up will narrow
diff --git a/packages/cli/tests/integration/mcp-host-config-race.test.ts b/packages/cli/tests/integration/mcp-host-config-race.test.ts
index e4a801a9c..5f7cda77c 100644
--- a/packages/cli/tests/integration/mcp-host-config-race.test.ts
+++ b/packages/cli/tests/integration/mcp-host-config-race.test.ts
@@ -30,11 +30,11 @@
* pre-existing entry plus every concurrent addition.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { spawn as nativeSpawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
const WORKER_PATH = resolve(__dirname, '_helpers', 'config-race-worker.ts');
const WORKER_TIMEOUT_MS = 30_000;
diff --git a/packages/cli/tests/integration/mcp-json-write-bundled.test.ts b/packages/cli/tests/integration/mcp-json-write-bundled.test.ts
index 37900fff7..8d4d83cad 100644
--- a/packages/cli/tests/integration/mcp-json-write-bundled.test.ts
+++ b/packages/cli/tests/integration/mcp-json-write-bundled.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, it } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
+import { describe, expect, it } from 'vitest';
/**
* Guards the jsonc-parser bundling fix at the boundary it actually matters:
diff --git a/packages/cli/tests/integration/multi-project-locks.test.ts b/packages/cli/tests/integration/multi-project-locks.test.ts
index 00e222c71..650b264ec 100644
--- a/packages/cli/tests/integration/multi-project-locks.test.ts
+++ b/packages/cli/tests/integration/multi-project-locks.test.ts
@@ -12,7 +12,7 @@
* configuration that exercises the live-foreign-pid collision path:
* 5 concurrent spawns across 5 content dirs.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+
import { type ChildProcess, spawn as nativeSpawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -24,6 +24,7 @@ import {
type ProcessLockHandle,
readProcessLock,
} from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
interface ProjectHandles {
lockDir: string;
diff --git a/packages/core/src/burst-grouping.test.ts b/packages/core/src/burst-grouping.test.ts
index df51216eb..86b3cef0e 100644
--- a/packages/core/src/burst-grouping.test.ts
+++ b/packages/core/src/burst-grouping.test.ts
@@ -1,7 +1,7 @@
/**
* Unit tests for bucketIntoBursts.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { bucketIntoBursts, type SessionTransaction } from './burst-grouping.ts';
function tx(session_id: string, timestamp: number, agent_type?: string): SessionTransaction {
diff --git a/packages/core/src/client-version.test.ts b/packages/core/src/client-version.test.ts
index 23e419f98..50c8a4bbb 100644
--- a/packages/core/src/client-version.test.ts
+++ b/packages/core/src/client-version.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
CLIENT_RUNTIME_VERSION_FALLBACK,
CLIENT_VERSION_HEADER,
diff --git a/packages/core/src/commands/command-identity.test.ts b/packages/core/src/commands/command-identity.test.ts
index 8e87da611..fc3f2f83e 100644
--- a/packages/core/src/commands/command-identity.test.ts
+++ b/packages/core/src/commands/command-identity.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { MENU_LABELS } from '../constants/menu-labels.ts';
import {
COMMAND_IDENTITIES,
diff --git a/packages/core/src/config/bind-config-doc.test.ts b/packages/core/src/config/bind-config-doc.test.ts
index 7627d1a2d..f1835dfc3 100644
--- a/packages/core/src/config/bind-config-doc.test.ts
+++ b/packages/core/src/config/bind-config-doc.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { bindConfigDoc, type ConfigDocProvider } from './bind-config-doc.ts';
import { isKnownConfigError } from './errors.ts';
diff --git a/packages/core/src/config/bind-okignore-doc.test.ts b/packages/core/src/config/bind-okignore-doc.test.ts
index 9968e5da0..22a680e49 100644
--- a/packages/core/src/config/bind-okignore-doc.test.ts
+++ b/packages/core/src/config/bind-okignore-doc.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { bindOkignoreDoc, type OkignoreDocProvider } from './bind-okignore-doc.ts';
import { isKnownConfigError } from './errors.ts';
diff --git a/packages/core/src/config/errors.test.ts b/packages/core/src/config/errors.test.ts
index e1326de65..ec226b90d 100644
--- a/packages/core/src/config/errors.test.ts
+++ b/packages/core/src/config/errors.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ConfigValidationErrorSchema,
FieldScopeSchema,
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index 2f2803887..2f30860be 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { z } from 'zod';
import { fieldRegistry, getFieldMeta } from './field-registry.ts';
import { ConfigSchema } from './schema.ts';
diff --git a/packages/core/src/config/inspect-config-paths.test.ts b/packages/core/src/config/inspect-config-paths.test.ts
index 22328fcea..ece61c56e 100644
--- a/packages/core/src/config/inspect-config-paths.test.ts
+++ b/packages/core/src/config/inspect-config-paths.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { inspectConfigPaths } from './inspect-config-paths.ts';
function makeTempProject(): { cwd: string; home: string } {
diff --git a/packages/core/src/config/linter-leaf-registry-consistency.test.ts b/packages/core/src/config/linter-leaf-registry-consistency.test.ts
index adc7846bc..fb242d701 100644
--- a/packages/core/src/config/linter-leaf-registry-consistency.test.ts
+++ b/packages/core/src/config/linter-leaf-registry-consistency.test.ts
@@ -10,7 +10,7 @@
* loud failure instead of a silent shape mismatch.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
LINT_PLUGINS,
LinterConfigSchema,
diff --git a/packages/core/src/config/merge-layered.test.ts b/packages/core/src/config/merge-layered.test.ts
index 3875f9ff0..798e1736e 100644
--- a/packages/core/src/config/merge-layered.test.ts
+++ b/packages/core/src/config/merge-layered.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { mergeLayered } from './merge-layered.ts';
import type { Config } from './schema.ts';
import { ConfigSchema } from './schema.ts';
diff --git a/packages/core/src/config/read-config-safely.test.ts b/packages/core/src/config/read-config-safely.test.ts
index 3e60805c6..a1bcfd2dc 100644
--- a/packages/core/src/config/read-config-safely.test.ts
+++ b/packages/core/src/config/read-config-safely.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { isKnownConfigError } from './errors.ts';
import { readConfigSafely } from './read-config-safely.ts';
diff --git a/packages/core/src/config/removed-keys.test.ts b/packages/core/src/config/removed-keys.test.ts
index afff29f36..e04654a72 100644
--- a/packages/core/src/config/removed-keys.test.ts
+++ b/packages/core/src/config/removed-keys.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseDocument } from 'yaml';
import { isKnownConfigError } from './errors.ts';
import { detectRemovedKeys, REMOVED_KEYS } from './removed-keys.ts';
diff --git a/packages/core/src/config/schema-jsonschema.test.ts b/packages/core/src/config/schema-jsonschema.test.ts
index 53c401fbe..d27ed9b8b 100644
--- a/packages/core/src/config/schema-jsonschema.test.ts
+++ b/packages/core/src/config/schema-jsonschema.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
+import { describe, expect, test } from 'vitest';
import { z } from 'zod';
import { fieldRegistry } from './field-registry.ts';
import { ConfigSchema } from './schema.ts';
diff --git a/packages/core/src/config/schema-leaf.test.ts b/packages/core/src/config/schema-leaf.test.ts
index fbc6359fe..436d0db25 100644
--- a/packages/core/src/config/schema-leaf.test.ts
+++ b/packages/core/src/config/schema-leaf.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { ConfigSchema } from './schema.ts';
import { getLeafFieldMeta, resolveLeafSchema } from './schema-leaf.ts';
diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.ts
index bcf51b338..2aa475a03 100644
--- a/packages/core/src/config/schema.test.ts
+++ b/packages/core/src/config/schema.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ConfigSchema,
checkEmbeddingsBaseUrl,
diff --git a/packages/core/src/config/source-locator.test.ts b/packages/core/src/config/source-locator.test.ts
index 555df05ec..02ffe239c 100644
--- a/packages/core/src/config/source-locator.test.ts
+++ b/packages/core/src/config/source-locator.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseDocument } from 'yaml';
import { locateIssue } from './source-locator.ts';
diff --git a/packages/core/src/config/validate-patch-scopes.test.ts b/packages/core/src/config/validate-patch-scopes.test.ts
index 47dd71fec..a87ad556e 100644
--- a/packages/core/src/config/validate-patch-scopes.test.ts
+++ b/packages/core/src/config/validate-patch-scopes.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { validatePatchScopes } from './validate-patch-scopes.ts';
describe('validatePatchScopes', () => {
diff --git a/packages/core/src/config/write-config-patch.test.ts b/packages/core/src/config/write-config-patch.test.ts
index cb7746f25..2e8cbbc77 100644
--- a/packages/core/src/config/write-config-patch.test.ts
+++ b/packages/core/src/config/write-config-patch.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -10,6 +9,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { isKnownConfigError } from './errors.ts';
import { resolveConfigPath, writeConfigPatch } from './write-config-patch.ts';
diff --git a/packages/core/src/config/yaml-patch.test.ts b/packages/core/src/config/yaml-patch.test.ts
index 4d080d9b6..5d2141374 100644
--- a/packages/core/src/config/yaml-patch.test.ts
+++ b/packages/core/src/config/yaml-patch.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseDocument } from 'yaml';
import { applyPatchToDocument } from './yaml-patch.ts';
diff --git a/packages/core/src/constants/cc1.test.ts b/packages/core/src/constants/cc1.test.ts
index eebd41421..b35725e2d 100644
--- a/packages/core/src/constants/cc1.test.ts
+++ b/packages/core/src/constants/cc1.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
managedArtifactDocNameFromContentTarget,
parseGlobalSkillBundleDoc,
diff --git a/packages/core/src/constants/chrome.test.ts b/packages/core/src/constants/chrome.test.ts
index b397792db..5a799d422 100644
--- a/packages/core/src/constants/chrome.test.ts
+++ b/packages/core/src/constants/chrome.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import {
renderChromeConstantsModule,
resolveChromeTokensFromCss,
diff --git a/packages/core/src/constants/code-languages.test.ts b/packages/core/src/constants/code-languages.test.ts
index b9b8aa27e..295f9dcdc 100644
--- a/packages/core/src/constants/code-languages.test.ts
+++ b/packages/core/src/constants/code-languages.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
CODE_FILE_BARE_NAMES_TO_LANGUAGE,
CODE_FILE_EXTENSIONS,
diff --git a/packages/core/src/constants/embedded-host.test.ts b/packages/core/src/constants/embedded-host.test.ts
index 26d0e1134..58edc67ef 100644
--- a/packages/core/src/constants/embedded-host.test.ts
+++ b/packages/core/src/constants/embedded-host.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { detectEmbeddedHostFromBrowser, type EmbeddedHost } from './embedded-host.ts';
function detectFromUA(ua: string): EmbeddedHost {
diff --git a/packages/core/src/constants/preview-embed-starters.test.ts b/packages/core/src/constants/preview-embed-starters.test.ts
index 90c4db85b..1a90dc8e3 100644
--- a/packages/core/src/constants/preview-embed-starters.test.ts
+++ b/packages/core/src/constants/preview-embed-starters.test.ts
@@ -17,7 +17,7 @@
* presentation attribute like `fill=` / `stroke=` / `color=`.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { PREVIEW_EMBED_STARTERS } from './preview-embed-starters';
/**
diff --git a/packages/core/src/constants/preview-theme-tokens.test.ts b/packages/core/src/constants/preview-theme-tokens.test.ts
index 2bac58f4f..05b65acd8 100644
--- a/packages/core/src/constants/preview-theme-tokens.test.ts
+++ b/packages/core/src/constants/preview-theme-tokens.test.ts
@@ -9,9 +9,10 @@
* categorical `--chart-*` palette against WCAG-AA non-text contrast in both
* themes.
*/
-import { describe, expect, test } from 'bun:test';
+
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import {
PREVIEW_TOKEN_NAMES,
renderPreviewThemeTokensModule,
diff --git a/packages/core/src/constants/upload.test.ts b/packages/core/src/constants/upload.test.ts
index 7ed1d5ff7..fba120312 100644
--- a/packages/core/src/constants/upload.test.ts
+++ b/packages/core/src/constants/upload.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ASSET_EXTENSIONS,
AUDIO_EXTENSIONS,
diff --git a/packages/core/src/extensions/emphasis-fidelity.test.ts b/packages/core/src/extensions/emphasis-fidelity.test.ts
index f749cf6d5..c5219347c 100644
--- a/packages/core/src/extensions/emphasis-fidelity.test.ts
+++ b/packages/core/src/extensions/emphasis-fidelity.test.ts
@@ -11,9 +11,9 @@
* the markInputRule contract.
*/
-import { describe, expect, test } from 'bun:test';
import { getSchema } from '@tiptap/core';
import { EditorState } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import {
EMPHASIS_STAR_INPUT_RE,
EMPHASIS_UNDERSCORE_INPUT_RE,
diff --git a/packages/core/src/extensions/footnote-reference.test.ts b/packages/core/src/extensions/footnote-reference.test.ts
index 3f7d963d0..9dca9539d 100644
--- a/packages/core/src/extensions/footnote-reference.test.ts
+++ b/packages/core/src/extensions/footnote-reference.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
collectFootnoteIdentifiers,
type FootnoteDescendableDoc,
diff --git a/packages/core/src/extensions/frontmatter.test.ts b/packages/core/src/extensions/frontmatter.test.ts
index 68f4b2b8d..d49cbe4e2 100644
--- a/packages/core/src/extensions/frontmatter.test.ts
+++ b/packages/core/src/extensions/frontmatter.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { prependFrontmatter, stripFrontmatter, unwrapFrontmatterFences } from './frontmatter';
describe('stripFrontmatter', () => {
diff --git a/packages/core/src/extensions/jsx-component.test.ts b/packages/core/src/extensions/jsx-component.test.ts
index 77402a0eb..059c34f66 100644
--- a/packages/core/src/extensions/jsx-component.test.ts
+++ b/packages/core/src/extensions/jsx-component.test.ts
@@ -4,8 +4,9 @@
* The old code-fence form (```jsx-component) is replaced by native MDX via remark-mdx.
* These tests verify the jsxComponent PM node works correctly with the new pipeline.
*/
-import { describe, expect, test } from 'bun:test';
+
import { type Extension, getSchema, type Mark, type Node } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { MarkdownManager } from '../markdown/index.ts';
import { sharedExtensions } from './shared';
diff --git a/packages/core/src/extensions/link-fidelity.test.ts b/packages/core/src/extensions/link-fidelity.test.ts
index 36607ed30..a3a45792e 100644
--- a/packages/core/src/extensions/link-fidelity.test.ts
+++ b/packages/core/src/extensions/link-fidelity.test.ts
@@ -13,7 +13,7 @@
* surface for `file:` / `blob:` / `intent:` / future schemes.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { LinkFidelity } from './link-fidelity.ts';
const opts = LinkFidelity.config.addOptions?.call({ parent: undefined } as never) as {
diff --git a/packages/core/src/extensions/list.test.ts b/packages/core/src/extensions/list.test.ts
index ecbd46356..e9ba45977 100644
--- a/packages/core/src/extensions/list.test.ts
+++ b/packages/core/src/extensions/list.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { getSchema } from '@tiptap/core';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
+import { describe, expect, test } from 'vitest';
import { MarkdownManager } from '../markdown/index.ts';
import { ListItemNode, ListNode } from './list.ts';
diff --git a/packages/core/src/extensions/shared.test.ts b/packages/core/src/extensions/shared.test.ts
index b83fb829c..09cdeefaf 100644
--- a/packages/core/src/extensions/shared.test.ts
+++ b/packages/core/src/extensions/shared.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { MarkdownManager } from '../markdown/index.ts';
import { sharedExtensions } from './shared';
diff --git a/packages/core/src/extensions/source-literal-mark.test.ts b/packages/core/src/extensions/source-literal-mark.test.ts
index 3463a80f2..9833a7ae5 100644
--- a/packages/core/src/extensions/source-literal-mark.test.ts
+++ b/packages/core/src/extensions/source-literal-mark.test.ts
@@ -12,7 +12,7 @@
* visible text.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isValidSourceLiteralRaw } from './source-literal-mark.ts';
describe('isValidSourceLiteralRaw — legitimate cases', () => {
diff --git a/packages/core/src/extensions/thematic-break-fidelity.test.ts b/packages/core/src/extensions/thematic-break-fidelity.test.ts
index ae7389297..29cf6c4af 100644
--- a/packages/core/src/extensions/thematic-break-fidelity.test.ts
+++ b/packages/core/src/extensions/thematic-break-fidelity.test.ts
@@ -10,9 +10,9 @@
* match.
*/
-import { describe, expect, test } from 'bun:test';
import { getSchema } from '@tiptap/core';
import { EditorState } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from './shared.ts';
import {
THEMATIC_BREAK_INPUT_RE,
diff --git a/packages/core/src/extensions/wiki-link-embed.test.ts b/packages/core/src/extensions/wiki-link-embed.test.ts
index b3c91d8fd..c6cd97672 100644
--- a/packages/core/src/extensions/wiki-link-embed.test.ts
+++ b/packages/core/src/extensions/wiki-link-embed.test.ts
@@ -21,9 +21,10 @@
* parseHTML (array of tag-matcher rules with getAttrs). Avoids
* requiring a DOM runtime (Bun's test env has no `window`).
*/
-import { describe, expect, test } from 'bun:test';
+
import { getSchema } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from './shared';
const schema = getSchema(sharedExtensions);
diff --git a/packages/core/src/extensions/wiki-link.test.ts b/packages/core/src/extensions/wiki-link.test.ts
index 20a752a0d..ea403b110 100644
--- a/packages/core/src/extensions/wiki-link.test.ts
+++ b/packages/core/src/extensions/wiki-link.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { getSchema } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { MarkdownManager } from '../markdown/index.ts';
import { sharedExtensions } from './shared';
import {
diff --git a/packages/core/src/frontmatter/schema.test.ts b/packages/core/src/frontmatter/schema.test.ts
index 6951179b2..f7eb824fb 100644
--- a/packages/core/src/frontmatter/schema.test.ts
+++ b/packages/core/src/frontmatter/schema.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
FRONTMATTER_TYPES,
FrontmatterMapSchema,
diff --git a/packages/core/src/frontmatter/tags.test.ts b/packages/core/src/frontmatter/tags.test.ts
index ab4f1146d..1429a40de 100644
--- a/packages/core/src/frontmatter/tags.test.ts
+++ b/packages/core/src/frontmatter/tags.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
extractFrontmatterTags,
FRONTMATTER_TAG_GRAMMAR_HINT,
diff --git a/packages/core/src/frontmatter/yaml-codec.test.ts b/packages/core/src/frontmatter/yaml-codec.test.ts
index 3d714fb61..de5d0d30b 100644
--- a/packages/core/src/frontmatter/yaml-codec.test.ts
+++ b/packages/core/src/frontmatter/yaml-codec.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import * as fc from 'fast-check';
+import { describe, expect, test } from 'vitest';
import {
applyPatchToDocument,
getDocumentKeys,
diff --git a/packages/core/src/git/branch-list-parser.test.ts b/packages/core/src/git/branch-list-parser.test.ts
index 6285c3478..8d697336f 100644
--- a/packages/core/src/git/branch-list-parser.test.ts
+++ b/packages/core/src/git/branch-list-parser.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseBranchList } from './branch-list-parser.ts';
describe('parseBranchList', () => {
diff --git a/packages/core/src/git/git-spawn-path.test.ts b/packages/core/src/git/git-spawn-path.test.ts
index eec87eca8..1dcbbeb36 100644
--- a/packages/core/src/git/git-spawn-path.test.ts
+++ b/packages/core/src/git/git-spawn-path.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { augmentGitSpawnPath, wellKnownToolDirs } from './git-spawn-path.ts';
const HOME = '/Users/tester';
diff --git a/packages/core/src/git/missing-git-helper.test.ts b/packages/core/src/git/missing-git-helper.test.ts
index 6cf83431c..e120f87d0 100644
--- a/packages/core/src/git/missing-git-helper.test.ts
+++ b/packages/core/src/git/missing-git-helper.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { detectMissingGitHelper } from './missing-git-helper.ts';
describe('detectMissingGitHelper', () => {
diff --git a/packages/core/src/git/worktree-list-parser.test.ts b/packages/core/src/git/worktree-list-parser.test.ts
index c86aa9132..c30999b13 100644
--- a/packages/core/src/git/worktree-list-parser.test.ts
+++ b/packages/core/src/git/worktree-list-parser.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type BridgeWorktreeEntry, parseWorktreeListPorcelain } from './worktree-list-parser.ts';
describe('parseWorktreeListPorcelain', () => {
diff --git a/packages/core/src/git/worktree-path.test.ts b/packages/core/src/git/worktree-path.test.ts
index b292490f7..59502681b 100644
--- a/packages/core/src/git/worktree-path.test.ts
+++ b/packages/core/src/git/worktree-path.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { WORKTREES_PARENT_DIR, worktreeRelativeDir } from './worktree-path.ts';
describe('worktreeRelativeDir', () => {
diff --git a/packages/core/src/git/worktree-selector-model.test.ts b/packages/core/src/git/worktree-selector-model.test.ts
index 10dd15c81..b96d4b834 100644
--- a/packages/core/src/git/worktree-selector-model.test.ts
+++ b/packages/core/src/git/worktree-selector-model.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { BridgeWorktreeEntry } from './worktree-list-parser.ts';
import { buildWorktreeSelectorModel } from './worktree-selector-model.ts';
diff --git a/packages/core/src/handoff/claude-url.test.ts b/packages/core/src/handoff/claude-url.test.ts
index 592dd47d1..149552b9d 100644
--- a/packages/core/src/handoff/claude-url.test.ts
+++ b/packages/core/src/handoff/claude-url.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test';
+import { expect, test } from 'vitest';
import { buildClaudeUrl } from './claude-url.ts';
import { composeEmptySpacePrompt } from './prompt-composer.ts';
import type { HandoffPayload } from './types.ts';
diff --git a/packages/core/src/handoff/codex-url.test.ts b/packages/core/src/handoff/codex-url.test.ts
index 4111b29ec..784f5d94f 100644
--- a/packages/core/src/handoff/codex-url.test.ts
+++ b/packages/core/src/handoff/codex-url.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test';
+import { expect, test } from 'vitest';
import { buildCodexUrl } from './codex-url.ts';
import { composeEmptySpacePrompt } from './prompt-composer.ts';
import type { HandoffPayload } from './types.ts';
diff --git a/packages/core/src/handoff/cursor-url.test.ts b/packages/core/src/handoff/cursor-url.test.ts
index eaae44776..b5a7e7f12 100644
--- a/packages/core/src/handoff/cursor-url.test.ts
+++ b/packages/core/src/handoff/cursor-url.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test';
+import { expect, test } from 'vitest';
import { buildCursorUrl } from './cursor-url.ts';
import { composeEmptySpacePrompt } from './prompt-composer.ts';
import type { HandoffPayload } from './types.ts';
diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.ts
index 59d3794a0..8c08b9d5f 100644
--- a/packages/core/src/handoff/prompt-composer.test.ts
+++ b/packages/core/src/handoff/prompt-composer.test.ts
@@ -1,4 +1,4 @@
-import { expect, test } from 'bun:test';
+import { expect, test } from 'vitest';
import { buildClaudeUrl } from './claude-url.ts';
import { buildCodexUrl } from './codex-url.ts';
import { buildCursorUrl } from './cursor-url.ts';
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index 0113c3ec7..1748777ff 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'bun:test';
+import { describe, expect, it } from 'vitest';
import { MCP_SERVER_NAME } from '../constants/mcp.ts';
import {
buildClaudeLaunchCommand,
diff --git a/packages/core/src/handoff/urn-ipc-registry.test.ts b/packages/core/src/handoff/urn-ipc-registry.test.ts
index d19c03685..0e8ce67c9 100644
--- a/packages/core/src/handoff/urn-ipc-registry.test.ts
+++ b/packages/core/src/handoff/urn-ipc-registry.test.ts
@@ -11,7 +11,7 @@
* wrong reason translations downstream.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { lookupUrnInRegistry } from './urn-ipc-registry.ts';
describe('lookupUrnInRegistry', () => {
diff --git a/packages/core/src/helper-bundle.test.ts b/packages/core/src/helper-bundle.test.ts
index 0a8111ce4..753019b09 100644
--- a/packages/core/src/helper-bundle.test.ts
+++ b/packages/core/src/helper-bundle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
HELPER_BUNDLE_NAME,
HELPER_EXECUTABLE_NAME,
diff --git a/packages/core/src/keepalive/keepalive.test.ts b/packages/core/src/keepalive/keepalive.test.ts
index 36c44e79b..44a3d2370 100644
--- a/packages/core/src/keepalive/keepalive.test.ts
+++ b/packages/core/src/keepalive/keepalive.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { setImmediate as runMicrotasks } from 'node:timers/promises';
+import { describe, expect, test } from 'vitest';
import type { KeepaliveScheduler, MinimalWebSocket } from './keepalive.ts';
import { startKeepalive } from './keepalive.ts';
diff --git a/packages/core/src/logging/renderer-log.test.ts b/packages/core/src/logging/renderer-log.test.ts
index 22ab95497..c3cc139af 100644
--- a/packages/core/src/logging/renderer-log.test.ts
+++ b/packages/core/src/logging/renderer-log.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
mapConsoleLevel,
parseStructuredConsoleMessage,
diff --git a/packages/core/src/markdown/round-trip-asserts.test-helper.ts b/packages/core/src/markdown/round-trip-asserts.test-helper.ts
index e9c80813d..55890de18 100644
--- a/packages/core/src/markdown/round-trip-asserts.test-helper.ts
+++ b/packages/core/src/markdown/round-trip-asserts.test-helper.ts
@@ -1,4 +1,4 @@
-import { expect } from 'bun:test';
+import { expect } from 'vitest';
export function assertByteStable(roundTrip: (s: string) => string, source: string): void {
const once = roundTrip(source);
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 8f9fdb08e..0dd54070e 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,6 +1,6 @@
-import { expect } from 'bun:test';
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
+import { expect } from 'vitest';
import { sharedExtensions } from '../extensions/shared.ts';
import { MarkdownManager } from './index.ts';
import { isInlineWhitespaceNumericCharRef } from './whitespace-char-ref.ts';
diff --git a/packages/core/src/metrics/parse-health.test.ts b/packages/core/src/metrics/parse-health.test.ts
index 77676378e..ee83036d8 100644
--- a/packages/core/src/metrics/parse-health.test.ts
+++ b/packages/core/src/metrics/parse-health.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
getParseHealth,
incrementBlockFallback,
diff --git a/packages/core/src/registry/canonical-compat.test.ts b/packages/core/src/registry/canonical-compat.test.ts
index 586e653e7..76585c872 100644
--- a/packages/core/src/registry/canonical-compat.test.ts
+++ b/packages/core/src/registry/canonical-compat.test.ts
@@ -12,7 +12,7 @@
* i19.test.ts` (HTML5 details ↔ Accordion structural equivalence).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { builtInComponents, createRegistry } from './index.ts';
import type { CompatMeta, JsxComponentMeta } from './types.ts';
diff --git a/packages/core/src/registry/projection.test.ts b/packages/core/src/registry/projection.test.ts
index 80478f37b..57946c910 100644
--- a/packages/core/src/registry/projection.test.ts
+++ b/packages/core/src/registry/projection.test.ts
@@ -8,10 +8,10 @@
* - per-entry / per-param projection shape
*/
-import { describe, expect, test } from 'bun:test';
import { fromMarkdown } from 'mdast-util-from-markdown';
import { mdxFromMarkdown } from 'mdast-util-mdx';
import { mdx } from 'micromark-extension-mdx';
+import { describe, expect, test } from 'vitest';
import {
getAgentCanonicalDescriptors,
getCanonicalDescriptors,
diff --git a/packages/core/src/registry/registry.test.ts b/packages/core/src/registry/registry.test.ts
index 55bf6734a..f763a72e0 100644
--- a/packages/core/src/registry/registry.test.ts
+++ b/packages/core/src/registry/registry.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { emitMdxJsx } from '../markdown/serialize-helpers.ts';
import { builtInComponents, createRegistry, wildcardMeta } from './index.ts';
import type { JsxComponentMeta } from './types.ts';
diff --git a/packages/core/src/registry/wiki-embed-compat.test.ts b/packages/core/src/registry/wiki-embed-compat.test.ts
index 824de06d3..4a00bdc61 100644
--- a/packages/core/src/registry/wiki-embed-compat.test.ts
+++ b/packages/core/src/registry/wiki-embed-compat.test.ts
@@ -15,8 +15,9 @@
* attachments. The pdfjs canvas viewer stays available via the explicit
* `<Pdf src="..." />` JSX form.
*/
-import { describe, expect, test } from 'bun:test';
+
import type { Node as PmNode } from '@tiptap/pm/model';
+import { describe, expect, test } from 'vitest';
import { builtInComponents } from './index.ts';
import type { CompatMeta } from './types.ts';
diff --git a/packages/core/src/schema-invariant.test.ts b/packages/core/src/schema-invariant.test.ts
index 55f13a7d4..de3227669 100644
--- a/packages/core/src/schema-invariant.test.ts
+++ b/packages/core/src/schema-invariant.test.ts
@@ -17,9 +17,10 @@
* schema.node() throws. The delete is multi-peer replicated and undo-resistant.
* Any schema narrowing = silent data loss.
*/
-import { describe, expect, test } from 'bun:test';
+
import { existsSync, readFileSync } from 'node:fs';
import { getSchema } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from './extensions/shared.ts';
// ── Schema shape capture ────────────────────────────────────────────
diff --git a/packages/core/src/schemas/api/_envelope.test.ts b/packages/core/src/schemas/api/_envelope.test.ts
index 93353d14a..5458f3d61 100644
--- a/packages/core/src/schemas/api/_envelope.test.ts
+++ b/packages/core/src/schemas/api/_envelope.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
LocalOpCloneRequestSchema,
PrincipalSuccessSchema,
diff --git a/packages/core/src/schemas/api/agent-write.test.ts b/packages/core/src/schemas/api/agent-write.test.ts
index 652bde179..96d8130b9 100644
--- a/packages/core/src/schemas/api/agent-write.test.ts
+++ b/packages/core/src/schemas/api/agent-write.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
AgentPatchRequestSchema,
AgentPatchSuccessSchema,
diff --git a/packages/core/src/schemas/api/client-logs.test.ts b/packages/core/src/schemas/api/client-logs.test.ts
index b4e9bf065..66663d750 100644
--- a/packages/core/src/schemas/api/client-logs.test.ts
+++ b/packages/core/src/schemas/api/client-logs.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
RENDERER_LOG_MAX_ENTRIES,
RENDERER_LOG_MAX_MESSAGE_BYTES,
diff --git a/packages/core/src/schemas/api/document-read.test.ts b/packages/core/src/schemas/api/document-read.test.ts
index 29211da13..7007319e7 100644
--- a/packages/core/src/schemas/api/document-read.test.ts
+++ b/packages/core/src/schemas/api/document-read.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
BacklinkCountsSuccessSchema,
BacklinkEntrySchema,
diff --git a/packages/core/src/schemas/api/history.test.ts b/packages/core/src/schemas/api/history.test.ts
index 841d4d8b0..6f9567361 100644
--- a/packages/core/src/schemas/api/history.test.ts
+++ b/packages/core/src/schemas/api/history.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { ServerInfoSuccessSchema, WorkspaceSuccessSchema } from './index.ts';
describe('ServerInfoSuccessSchema', () => {
diff --git a/packages/core/src/schemas/api/links-orphans.test.ts b/packages/core/src/schemas/api/links-orphans.test.ts
index 9c29f9346..c2b610280 100644
--- a/packages/core/src/schemas/api/links-orphans.test.ts
+++ b/packages/core/src/schemas/api/links-orphans.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
DeadLinkEntrySchema,
DeadLinkSourceSchema,
diff --git a/packages/core/src/schemas/api/local-op.test.ts b/packages/core/src/schemas/api/local-op.test.ts
index 027a6e861..9651c216e 100644
--- a/packages/core/src/schemas/api/local-op.test.ts
+++ b/packages/core/src/schemas/api/local-op.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
LocalOpAuthEmptySuccessSchema,
LocalOpAuthHostRequestSchema,
diff --git a/packages/core/src/schemas/api/metrics.test.ts b/packages/core/src/schemas/api/metrics.test.ts
index b0e7d067e..35d9b8768 100644
--- a/packages/core/src/schemas/api/metrics.test.ts
+++ b/packages/core/src/schemas/api/metrics.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ActivityAgentHeaderSchema,
ActivityBurstSchema,
diff --git a/packages/core/src/schemas/api/pages.test.ts b/packages/core/src/schemas/api/pages.test.ts
index f51541f59..4c3af78b0 100644
--- a/packages/core/src/schemas/api/pages.test.ts
+++ b/packages/core/src/schemas/api/pages.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
CreateFolderRequestSchema,
CreateFolderSuccessSchema,
diff --git a/packages/core/src/schemas/api/share.test.ts b/packages/core/src/schemas/api/share.test.ts
index cacab783b..198f0807c 100644
--- a/packages/core/src/schemas/api/share.test.ts
+++ b/packages/core/src/schemas/api/share.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
BranchInfoResponseSchema,
type ClassifiedGitAuthError,
diff --git a/packages/core/src/schemas/api/sync-seed.test.ts b/packages/core/src/schemas/api/sync-seed.test.ts
index bf1544f50..e9b446dcc 100644
--- a/packages/core/src/schemas/api/sync-seed.test.ts
+++ b/packages/core/src/schemas/api/sync-seed.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ConflictEntrySchema,
InstallSkillSuccessSchema,
diff --git a/packages/core/src/schemas/api/tags-search.test.ts b/packages/core/src/schemas/api/tags-search.test.ts
index 8335afcc6..90bbfc773 100644
--- a/packages/core/src/schemas/api/tags-search.test.ts
+++ b/packages/core/src/schemas/api/tags-search.test.ts
@@ -3,7 +3,7 @@
* `TemplateGetSuccessSchema` frontmatter shape.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { TemplateGetSuccessSchema, TemplatePayloadSchema } from './tags-search.ts';
const validPayload = (scope: 'local' | 'inherited') => ({
diff --git a/packages/core/src/schemas/cc1.test.ts b/packages/core/src/schemas/cc1.test.ts
index d5a39ebf1..66f7860c3 100644
--- a/packages/core/src/schemas/cc1.test.ts
+++ b/packages/core/src/schemas/cc1.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { CC1_CONTRACT_VERSION } from '../constants/cc1.ts';
import {
CC1_CHANNEL_CONFIG_IGNORE_NESTED_ERROR,
diff --git a/packages/core/src/search/workspace-search.category-caps.test.ts b/packages/core/src/search/workspace-search.category-caps.test.ts
index 17f9c0272..5565d678c 100644
--- a/packages/core/src/search/workspace-search.category-caps.test.ts
+++ b/packages/core/src/search/workspace-search.category-caps.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createWorkspaceSearchDocument,
DEFAULT_BODY_RESULT_CAP,
diff --git a/packages/core/src/search/workspace-search.filename-quota.test.ts b/packages/core/src/search/workspace-search.filename-quota.test.ts
index a5d3a995b..553502557 100644
--- a/packages/core/src/search/workspace-search.filename-quota.test.ts
+++ b/packages/core/src/search/workspace-search.filename-quota.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createWorkspaceSearchDocument,
DEFAULT_FILE_RESULT_CAP,
diff --git a/packages/core/src/search/workspace-search.parity.test.ts b/packages/core/src/search/workspace-search.parity.test.ts
index fe52603a3..36900a5df 100644
--- a/packages/core/src/search/workspace-search.parity.test.ts
+++ b/packages/core/src/search/workspace-search.parity.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
import {
createWorkspaceSearchCorpus,
searchWorkspaceCorpus,
diff --git a/packages/core/src/search/workspace-search.semantic.test.ts b/packages/core/src/search/workspace-search.semantic.test.ts
index 9a9a24c71..50642a5a9 100644
--- a/packages/core/src/search/workspace-search.semantic.test.ts
+++ b/packages/core/src/search/workspace-search.semantic.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createWorkspaceSearchCorpus,
createWorkspaceSearchDocument,
diff --git a/packages/core/src/search/workspace-search.test.ts b/packages/core/src/search/workspace-search.test.ts
index 4075b4d46..61a214d3d 100644
--- a/packages/core/src/search/workspace-search.test.ts
+++ b/packages/core/src/search/workspace-search.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createWorkspaceSearchDocument, searchWorkspaceDocuments } from './workspace-search.ts';
const documents = [
diff --git a/packages/core/src/search/workspace-search.tier-ranking.test.ts b/packages/core/src/search/workspace-search.tier-ranking.test.ts
index 7026de471..07b343105 100644
--- a/packages/core/src/search/workspace-search.tier-ranking.test.ts
+++ b/packages/core/src/search/workspace-search.tier-ranking.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createWorkspaceSearchDocument,
DEFAULT_FOLDER_RESULT_CAP,
diff --git a/packages/core/src/shadow-repo-layout.test.ts b/packages/core/src/shadow-repo-layout.test.ts
index 0d497c3e0..560e6793b 100644
--- a/packages/core/src/shadow-repo-layout.test.ts
+++ b/packages/core/src/shadow-repo-layout.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
COMMIT_SUBJECT_MAX_LEN,
composeCommitSubject,
diff --git a/packages/core/src/sharing/share-url.test.ts b/packages/core/src/sharing/share-url.test.ts
index 0ba257670..2d4a3e65d 100644
--- a/packages/core/src/sharing/share-url.test.ts
+++ b/packages/core/src/sharing/share-url.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
decodeShareUrl,
encodeShareUrl,
diff --git a/packages/core/src/skill-targets/editor-single-source.test.ts b/packages/core/src/skill-targets/editor-single-source.test.ts
index 32d60fe08..312cbd0c7 100644
--- a/packages/core/src/skill-targets/editor-single-source.test.ts
+++ b/packages/core/src/skill-targets/editor-single-source.test.ts
@@ -14,7 +14,7 @@
* prove the derivation rather than a duplicated literal.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ALL_EDITOR_IDS,
EDITOR_PROJECT_SKILL_ROOT,
diff --git a/packages/core/src/skill-targets/schema.test.ts b/packages/core/src/skill-targets/schema.test.ts
index ea5d8e998..eec933652 100644
--- a/packages/core/src/skill-targets/schema.test.ts
+++ b/packages/core/src/skill-targets/schema.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { PROJECT_SKILL_EDITOR_IDS } from '../constants/editors.ts';
import { parseSkillTargets, SkillTargetEditorSchema } from './schema.ts';
diff --git a/packages/core/src/templates/template-format.test.ts b/packages/core/src/templates/template-format.test.ts
index 285d40fc7..e421e7e7c 100644
--- a/packages/core/src/templates/template-format.test.ts
+++ b/packages/core/src/templates/template-format.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
composeTemplateFile,
instantiateDoc,
diff --git a/packages/core/src/theme/theme-plugins.test.ts b/packages/core/src/theme/theme-plugins.test.ts
index 9a8bb4532..292f3f6f4 100644
--- a/packages/core/src/theme/theme-plugins.test.ts
+++ b/packages/core/src/theme/theme-plugins.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type ColorThemeBase,
colorThemeMode,
diff --git a/packages/core/src/util/atomic-yaml-write.test.ts b/packages/core/src/util/atomic-yaml-write.test.ts
index b8b627ce6..2358759be 100644
--- a/packages/core/src/util/atomic-yaml-write.test.ts
+++ b/packages/core/src/util/atomic-yaml-write.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -11,6 +10,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { atomicWriteFile, atomicWriteFileSync } from './atomic-yaml-write.ts';
let testDir: string;
diff --git a/packages/core/src/util/doc-name.test.ts b/packages/core/src/util/doc-name.test.ts
index eecc2eb7e..6b707b73a 100644
--- a/packages/core/src/util/doc-name.test.ts
+++ b/packages/core/src/util/doc-name.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
HIDDEN_CONFIG_BASENAMES,
isHiddenDocName,
diff --git a/packages/core/src/util/file-lock.test.ts b/packages/core/src/util/file-lock.test.ts
index b6861cd1a..203694690 100644
--- a/packages/core/src/util/file-lock.test.ts
+++ b/packages/core/src/util/file-lock.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { FileLockTimeoutError, withFileLock, withFileLockSync } from './file-lock.ts';
let testDir: string;
diff --git a/packages/core/src/utils/apply-by-prefix-suffix.test.ts b/packages/core/src/utils/apply-by-prefix-suffix.test.ts
index b575d4992..6eb43a8f5 100644
--- a/packages/core/src/utils/apply-by-prefix-suffix.test.ts
+++ b/packages/core/src/utils/apply-by-prefix-suffix.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { applyByPrefixSuffix } from './apply-by-prefix-suffix.ts';
diff --git a/packages/core/src/utils/asset-href.test.ts b/packages/core/src/utils/asset-href.test.ts
index 09ad99c2b..7f56e1f02 100644
--- a/packages/core/src/utils/asset-href.test.ts
+++ b/packages/core/src/utils/asset-href.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { toDesktopAssetHref } from './asset-href.ts';
const g = globalThis as { window?: unknown };
diff --git a/packages/core/src/utils/chunked-insert.test.ts b/packages/core/src/utils/chunked-insert.test.ts
index 53b8bc41e..8d3625375 100644
--- a/packages/core/src/utils/chunked-insert.test.ts
+++ b/packages/core/src/utils/chunked-insert.test.ts
@@ -9,7 +9,7 @@
* Uses injectable yieldFn so tests don't depend on rAF/timers.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
ChunkedInsertError,
chunkedYTextInsert,
diff --git a/packages/core/src/utils/code-fence-tracker.test.ts b/packages/core/src/utils/code-fence-tracker.test.ts
index 53579ef4c..06c28abb9 100644
--- a/packages/core/src/utils/code-fence-tracker.test.ts
+++ b/packages/core/src/utils/code-fence-tracker.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createCodeFenceTracker } from './code-fence-tracker.ts';
function collectNonFence(lines: string[]): string[] {
diff --git a/packages/core/src/utils/embed-url-rewrite.test.ts b/packages/core/src/utils/embed-url-rewrite.test.ts
index f3d527374..4f473be83 100644
--- a/packages/core/src/utils/embed-url-rewrite.test.ts
+++ b/packages/core/src/utils/embed-url-rewrite.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isEmbedUrlRewritable, rewriteEmbedUrl } from './embed-url-rewrite.ts';
describe('rewriteEmbedUrl — YouTube', () => {
diff --git a/packages/core/src/utils/file-size.test.ts b/packages/core/src/utils/file-size.test.ts
index 428ab5708..29a337b0b 100644
--- a/packages/core/src/utils/file-size.test.ts
+++ b/packages/core/src/utils/file-size.test.ts
@@ -18,7 +18,7 @@
* (matches what the showcase doc displays for sample-local-pdf.pdf)
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { formatFileSize } from './file-size.ts';
describe('formatFileSize', () => {
diff --git a/packages/core/src/utils/identity.test.ts b/packages/core/src/utils/identity.test.ts
index 1cf7c05f5..e54714298 100644
--- a/packages/core/src/utils/identity.test.ts
+++ b/packages/core/src/utils/identity.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
AGENT_COLORS,
colorFromSeed,
diff --git a/packages/core/src/utils/link-targets.test.ts b/packages/core/src/utils/link-targets.test.ts
index 8d668b07f..1401c9b9c 100644
--- a/packages/core/src/utils/link-targets.test.ts
+++ b/packages/core/src/utils/link-targets.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildAbsoluteMarkdownHref,
buildRelativeMarkdownHref,
diff --git a/packages/core/src/utils/loom-embed.test.ts b/packages/core/src/utils/loom-embed.test.ts
index 622e9bfc0..98f33ed4a 100644
--- a/packages/core/src/utils/loom-embed.test.ts
+++ b/packages/core/src/utils/loom-embed.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isLoomUrl, parseLoomUrl } from './loom-embed.ts';
describe('parseLoomUrl', () => {
diff --git a/packages/core/src/utils/path-resolve.test.ts b/packages/core/src/utils/path-resolve.test.ts
index cd38ece49..5ea9519fa 100644
--- a/packages/core/src/utils/path-resolve.test.ts
+++ b/packages/core/src/utils/path-resolve.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import fc from 'fast-check';
+import { describe, expect, test } from 'vitest';
import { createBasenameIndex } from './path-resolve';
describe('createBasenameIndex — single-match lookup', () => {
diff --git a/packages/core/src/utils/resolve-internal-href.test.ts b/packages/core/src/utils/resolve-internal-href.test.ts
index 3e228198f..7c0a95f85 100644
--- a/packages/core/src/utils/resolve-internal-href.test.ts
+++ b/packages/core/src/utils/resolve-internal-href.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveInternalHref } from './resolve-internal-href.ts';
describe('resolveInternalHref', () => {
diff --git a/packages/core/src/utils/sanitize-folder-name.test.ts b/packages/core/src/utils/sanitize-folder-name.test.ts
index 347941bd1..3d0ccd280 100644
--- a/packages/core/src/utils/sanitize-folder-name.test.ts
+++ b/packages/core/src/utils/sanitize-folder-name.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { sanitizeFolderName } from './sanitize-folder-name.ts';
describe('sanitizeFolderName', () => {
diff --git a/packages/core/src/utils/slug.test.ts b/packages/core/src/utils/slug.test.ts
index a2d64ec16..9a746de60 100644
--- a/packages/core/src/utils/slug.test.ts
+++ b/packages/core/src/utils/slug.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { getHeadingSlug, toWikiLinkSlug, wikiLinkHref } from './slug.ts';
describe('toWikiLinkSlug', () => {
diff --git a/packages/core/src/utils/tag-rollup.test.ts b/packages/core/src/utils/tag-rollup.test.ts
index 40cbd5d01..0309b4964 100644
--- a/packages/core/src/utils/tag-rollup.test.ts
+++ b/packages/core/src/utils/tag-rollup.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { expandTagToHierarchy, tagsMatchingPrefix } from './tag-rollup.ts';
describe('expandTagToHierarchy', () => {
diff --git a/packages/core/src/utils/vimeo-embed.test.ts b/packages/core/src/utils/vimeo-embed.test.ts
index b5e873522..c03366fd0 100644
--- a/packages/core/src/utils/vimeo-embed.test.ts
+++ b/packages/core/src/utils/vimeo-embed.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isVimeoUrl } from './vimeo-embed.ts';
describe('isVimeoUrl', () => {
diff --git a/packages/core/src/utils/youtube-embed.test.ts b/packages/core/src/utils/youtube-embed.test.ts
index a8aafb40b..e0f8551a7 100644
--- a/packages/core/src/utils/youtube-embed.test.ts
+++ b/packages/core/src/utils/youtube-embed.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { parseYouTubeUrl, youtubeEmbedUrl } from './youtube-embed.ts';
describe('youtubeEmbedUrl', () => {
diff --git a/packages/core/src/y-prosemirror-patch.test.ts b/packages/core/src/y-prosemirror-patch.test.ts
index 1496e6544..da4e60b76 100644
--- a/packages/core/src/y-prosemirror-patch.test.ts
+++ b/packages/core/src/y-prosemirror-patch.test.ts
@@ -72,10 +72,10 @@
* at https://github.com/yjs/y-prosemirror and https://github.com/ueberdosis/y-tiptap.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
function findRepoRoot(): string {
// this file lives at packages/core/src/ — repo root is two dirs up from package.json
diff --git a/packages/core/tests/contract/render-html.test.ts b/packages/core/tests/contract/render-html.test.ts
index eb0c389b4..af8c24a61 100644
--- a/packages/core/tests/contract/render-html.test.ts
+++ b/packages/core/tests/contract/render-html.test.ts
@@ -22,7 +22,7 @@
* actual behavior, captured by exercising the public functions.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { markdownToHtml, mdastToHtml } from '../../src/index.ts';
describe('markdownToHtml — documented construct render contract', () => {
diff --git a/packages/core/tests/contract/resolved-path-conditions.test.ts b/packages/core/tests/contract/resolved-path-conditions.test.ts
index c6f920a76..cbcddfa77 100644
--- a/packages/core/tests/contract/resolved-path-conditions.test.ts
+++ b/packages/core/tests/contract/resolved-path-conditions.test.ts
@@ -13,8 +13,9 @@
* import and the direct source import share their bindings. A flip to `dist/`
* loads a second, distinct module and the identity breaks loud.
*/
-import { expect, test } from 'bun:test';
+
import * as viaPackageName from '@inkeep/open-knowledge-core';
+import { expect, test } from 'vitest';
import * as viaSource from '../../src/index.ts';
test('the package-name import resolves to src/ (development condition), not dist/', () => {
diff --git a/packages/core/tests/health/parse-health-gate.test.ts b/packages/core/tests/health/parse-health-gate.test.ts
index c6521bec2..53091380e 100644
--- a/packages/core/tests/health/parse-health-gate.test.ts
+++ b/packages/core/tests/health/parse-health-gate.test.ts
@@ -15,7 +15,7 @@
* this file's (it's minutes-long). These tests are sub-second.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from '../../src/extensions/shared.ts';
import { MarkdownManager } from '../../src/markdown/index.ts';
import {
diff --git a/packages/core/tests/perf/markdown-bench.test.ts b/packages/core/tests/perf/markdown-bench.test.ts
index 567aa720d..0a303bd48 100644
--- a/packages/core/tests/perf/markdown-bench.test.ts
+++ b/packages/core/tests/perf/markdown-bench.test.ts
@@ -24,11 +24,11 @@
* in the output so future runs are comparable even across machines.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync, writeFileSync } from 'node:fs';
import { cpus, hostname, totalmem } from 'node:os';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { sharedExtensions } from '../../src/extensions/shared.ts';
import {
loadPerfFixture,
diff --git a/packages/core/tests/perf/regression-gate.test.ts b/packages/core/tests/perf/regression-gate.test.ts
index 6979ddf8d..d5dc2bac8 100644
--- a/packages/core/tests/perf/regression-gate.test.ts
+++ b/packages/core/tests/perf/regression-gate.test.ts
@@ -18,10 +18,10 @@
* 6. variance-term dominance on noisy baselines
*/
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
type Baseline,
evaluateRegression,
diff --git a/packages/desktop/src/main/about-panel.test.ts b/packages/desktop/src/main/about-panel.test.ts
index 9b89df83a..dd684604b 100644
--- a/packages/desktop/src/main/about-panel.test.ts
+++ b/packages/desktop/src/main/about-panel.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildAboutPanelOptions } from './about-panel.ts';
describe('buildAboutPanelOptions', () => {
diff --git a/packages/desktop/src/main/append-okignore.test.ts b/packages/desktop/src/main/append-okignore.test.ts
index a1b11ea0a..7f550ee20 100644
--- a/packages/desktop/src/main/append-okignore.test.ts
+++ b/packages/desktop/src/main/append-okignore.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { appendOkIgnoreSync } from './append-okignore.ts';
describe('appendOkIgnoreSync', () => {
diff --git a/packages/desktop/src/main/auto-instance.test.ts b/packages/desktop/src/main/auto-instance.test.ts
index 2cafc609f..f5cb07920 100644
--- a/packages/desktop/src/main/auto-instance.test.ts
+++ b/packages/desktop/src/main/auto-instance.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
deriveAutoInstanceName,
type GitInstanceContext,
diff --git a/packages/desktop/src/main/boot-restore-decision.settle.test.ts b/packages/desktop/src/main/boot-restore-decision.settle.test.ts
index 495d64562..58678a847 100644
--- a/packages/desktop/src/main/boot-restore-decision.settle.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.settle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
// `resolveBootRestoreDecision` is the boot-orchestration seam: an async
// coordinator that withholds the boot-restore decision until cold-start URL
// delivery has SETTLED, then reads the launch flag, then delegates to the pure
diff --git a/packages/desktop/src/main/boot-restore-decision.test.ts b/packages/desktop/src/main/boot-restore-decision.test.ts
index 51bb7fccd..1d60c7bbd 100644
--- a/packages/desktop/src/main/boot-restore-decision.test.ts
+++ b/packages/desktop/src/main/boot-restore-decision.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { bootRestoreDecision } from './boot-restore-decision.ts';
function existsIn(paths: string[]): (p: string) => boolean {
diff --git a/packages/desktop/src/main/boot-session.test.ts b/packages/desktop/src/main/boot-session.test.ts
index 1f0e4147f..3f1aadbfb 100644
--- a/packages/desktop/src/main/boot-session.test.ts
+++ b/packages/desktop/src/main/boot-session.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { readBootSessionUuid } from './boot-session.ts';
const onDarwin = process.platform === 'darwin' ? test : test.skip;
diff --git a/packages/desktop/src/main/branch-info-proxy.test.ts b/packages/desktop/src/main/branch-info-proxy.test.ts
index ac0dc1a31..5da3b2d67 100644
--- a/packages/desktop/src/main/branch-info-proxy.test.ts
+++ b/packages/desktop/src/main/branch-info-proxy.test.ts
@@ -1,11 +1,10 @@
-import { describe, expect, test } from 'bun:test';
-
import type {
BranchInfoResponse,
CheckoutResponse,
ShareTargetStatusResponse,
} from '@inkeep/open-knowledge-core';
import { RUNTIME_VERSION } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import {
type BranchInfoProxyDeps,
diff --git a/packages/desktop/src/main/cascade-position.test.ts b/packages/desktop/src/main/cascade-position.test.ts
index f8331f2fe..1c553c574 100644
--- a/packages/desktop/src/main/cascade-position.test.ts
+++ b/packages/desktop/src/main/cascade-position.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { CASCADE_OFFSET_PX, cascadePosition } from './cascade-position.ts';
const WORK_AREA = { x: 0, y: 25, width: 1920, height: 1055 };
diff --git a/packages/desktop/src/main/check-target-exists.test.ts b/packages/desktop/src/main/check-target-exists.test.ts
index 5a01c9913..4d507aeeb 100644
--- a/packages/desktop/src/main/check-target-exists.test.ts
+++ b/packages/desktop/src/main/check-target-exists.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
checkProjectDirExists,
diff --git a/packages/desktop/src/main/consent-dialog.test.ts b/packages/desktop/src/main/consent-dialog.test.ts
index 26bf65993..853155722 100644
--- a/packages/desktop/src/main/consent-dialog.test.ts
+++ b/packages/desktop/src/main/consent-dialog.test.ts
@@ -5,11 +5,12 @@
* Electron runtime, no real fs writes (the probe walk uses real fs to enable
* an integration assertion against a tmp-dir fixture).
*/
-import { describe, expect, test } from 'bun:test';
+
import type { Dirent } from 'node:fs';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import type { OnboardingConfirmRequest, OnboardingShowPayload } from '../shared/ipc-channels.ts';
import {
type ConsentIpcMainLike,
diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.ts
index 0e78c0301..fb5af1c22 100644
--- a/packages/desktop/src/main/crash-detection.test.ts
+++ b/packages/desktop/src/main/crash-detection.test.ts
@@ -6,7 +6,6 @@
* seeded minidump mtimes are all comparable without wall-clock races.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -19,6 +18,7 @@ import {
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import {
type CrashDetectionDeps,
createCrashDetection,
diff --git a/packages/desktop/src/main/create-new-project.test.ts b/packages/desktop/src/main/create-new-project.test.ts
index 96b8f9bd5..f5a7b14a7 100644
--- a/packages/desktop/src/main/create-new-project.test.ts
+++ b/packages/desktop/src/main/create-new-project.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
chmodSync,
existsSync,
@@ -12,6 +11,7 @@ import {
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { ALL_EDITOR_IDS } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
CreateNewProjectError,
folderState,
diff --git a/packages/desktop/src/main/debug-ipc.test.ts b/packages/desktop/src/main/debug-ipc.test.ts
index 8966befed..b3980eeb4 100644
--- a/packages/desktop/src/main/debug-ipc.test.ts
+++ b/packages/desktop/src/main/debug-ipc.test.ts
@@ -1,11 +1,11 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import type { KeyringSmokeResult } from '../utility/keyring-smoke.ts';
import { createDebugIpc } from './debug-ipc.ts';
function fakeUtility() {
const posted: Array<{ type: string; correlationId?: string }> = [];
return {
- postMessage: mock((m: unknown) => {
+ postMessage: vi.fn((m: unknown) => {
posted.push(m as { type: string; correlationId?: string });
}),
get posted() {
@@ -142,7 +142,7 @@ describe('createDebugIpc', () => {
test('postMessage throw is caught and surfaced as rejection', async () => {
const utility = {
- postMessage: mock(() => {
+ postMessage: vi.fn(() => {
throw new Error('IPC port closed');
}),
};
diff --git a/packages/desktop/src/main/desktop-logger.test.ts b/packages/desktop/src/main/desktop-logger.test.ts
index eb71f66fb..6d3f03fd1 100644
--- a/packages/desktop/src/main/desktop-logger.test.ts
+++ b/packages/desktop/src/main/desktop-logger.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { flushDesktopLogger, getLogger } from './desktop-logger.ts';
// `flushDesktopLogger` runs on the shutdown path (`will-quit`, before
diff --git a/packages/desktop/src/main/dialog-helpers.test.ts b/packages/desktop/src/main/dialog-helpers.test.ts
index 4da512b5d..b46d7f480 100644
--- a/packages/desktop/src/main/dialog-helpers.test.ts
+++ b/packages/desktop/src/main/dialog-helpers.test.ts
@@ -4,7 +4,7 @@
* `OK_DESKTOP_E2E_SMOKE=1` so a stray env var on a developer's shell can't
* bypass the real picker.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
promptForExistingFolder,
promptForExistingMarkdownFile,
@@ -28,7 +28,7 @@ describe('promptForExistingFolder', () => {
});
test('OS picker uses openDirectory + createDirectory + showHiddenFiles (macOS: New Folder button + dot-dirs visible for `.claude/worktrees`)', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/picked'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/picked'] }));
const result = await promptForExistingFolder({ showOpenDialog });
expect(result).toBe('/picked');
expect(showOpenDialog).toHaveBeenCalledWith({
@@ -37,26 +37,26 @@ describe('promptForExistingFolder', () => {
});
test('OS picker returns null on cancel', async () => {
- const showOpenDialog = mock(async () => ({ canceled: true, filePaths: [] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: true, filePaths: [] }));
expect(await promptForExistingFolder({ showOpenDialog })).toBe(null);
});
test('OS picker returns null on empty filePaths', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: [] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: [] }));
expect(await promptForExistingFolder({ showOpenDialog })).toBe(null);
});
test('test seam returns env path when both gates set, never calls OS picker', async () => {
process.env.OK_DESKTOP_E2E_SMOKE = '1';
process.env.OK_DESKTOP_TEST_PICKED_PATH = '/tmp/seam';
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/never/used'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/never/used'] }));
expect(await promptForExistingFolder({ showOpenDialog })).toBe('/tmp/seam');
expect(showOpenDialog).not.toHaveBeenCalled();
});
test('test seam ignored when OK_DESKTOP_E2E_SMOKE missing — production safety', async () => {
process.env.OK_DESKTOP_TEST_PICKED_PATH = '/tmp/should-not-fire';
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/real/pick'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/real/pick'] }));
expect(await promptForExistingFolder({ showOpenDialog })).toBe('/real/pick');
expect(showOpenDialog).toHaveBeenCalled();
});
@@ -64,13 +64,13 @@ describe('promptForExistingFolder', () => {
test('test seam ignored when OK_DESKTOP_TEST_PICKED_PATH empty', async () => {
process.env.OK_DESKTOP_E2E_SMOKE = '1';
process.env.OK_DESKTOP_TEST_PICKED_PATH = '';
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/real/pick'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/real/pick'] }));
expect(await promptForExistingFolder({ showOpenDialog })).toBe('/real/pick');
expect(showOpenDialog).toHaveBeenCalled();
});
test('defaultPath threads through to showOpenDialog', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/picked'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/picked'] }));
await promptForExistingFolder({ showOpenDialog }, { defaultPath: '/project/root' });
expect(showOpenDialog).toHaveBeenCalledWith({
properties: ['openDirectory', 'createDirectory', 'showHiddenFiles'],
@@ -79,7 +79,7 @@ describe('promptForExistingFolder', () => {
});
test('omits defaultPath when not provided', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/picked'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/picked'] }));
await promptForExistingFolder({ showOpenDialog });
expect(showOpenDialog).toHaveBeenCalledWith({
properties: ['openDirectory', 'createDirectory', 'showHiddenFiles'],
@@ -133,7 +133,7 @@ describe('promptForExistingMarkdownFile', () => {
});
test('OS picker uses openFile + a md/mdx filter', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/notes/x.md'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/notes/x.md'] }));
const result = await promptForExistingMarkdownFile({ showOpenDialog });
expect(result).toBe('/notes/x.md');
expect(showOpenDialog).toHaveBeenCalledWith({
@@ -143,25 +143,25 @@ describe('promptForExistingMarkdownFile', () => {
});
test('OS picker returns null on cancel', async () => {
- const showOpenDialog = mock(async () => ({ canceled: true, filePaths: [] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: true, filePaths: [] }));
expect(await promptForExistingMarkdownFile({ showOpenDialog })).toBe(null);
});
test('OS picker returns null on empty filePaths', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: [] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: [] }));
expect(await promptForExistingMarkdownFile({ showOpenDialog })).toBe(null);
});
test('test seam returns env path when both gates set, never calls OS picker', async () => {
process.env.OK_DESKTOP_E2E_SMOKE = '1';
process.env.OK_DESKTOP_TEST_PICKED_PATH = '/tmp/seam.md';
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/never/used.md'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/never/used.md'] }));
expect(await promptForExistingMarkdownFile({ showOpenDialog })).toBe('/tmp/seam.md');
expect(showOpenDialog).not.toHaveBeenCalled();
});
test('defaultPath threads through to showOpenDialog', async () => {
- const showOpenDialog = mock(async () => ({ canceled: false, filePaths: ['/notes/x.md'] }));
+ const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/notes/x.md'] }));
await promptForExistingMarkdownFile({ showOpenDialog }, { defaultPath: '/notes' });
expect(showOpenDialog).toHaveBeenCalledWith({
properties: ['openFile'],
diff --git a/packages/desktop/src/main/driver-boot-smoke.test.ts b/packages/desktop/src/main/driver-boot-smoke.test.ts
index 5de859217..eabac7d92 100644
--- a/packages/desktop/src/main/driver-boot-smoke.test.ts
+++ b/packages/desktop/src/main/driver-boot-smoke.test.ts
@@ -14,7 +14,7 @@
* helper.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type DriverUtilityLike,
isDriverBootSmokeMode,
diff --git a/packages/desktop/src/main/git-preflight-handler-otel.test.ts b/packages/desktop/src/main/git-preflight-handler-otel.test.ts
index 14cfe0733..74c8f1069 100644
--- a/packages/desktop/src/main/git-preflight-handler-otel.test.ts
+++ b/packages/desktop/src/main/git-preflight-handler-otel.test.ts
@@ -2,7 +2,7 @@
* OTEL emission tests for the Electron preflight handler.
*
* The desktop package has no direct `@opentelemetry/*` deps and cannot
- * mount an `InMemorySpanExporter`. We use bun's `mock.module` to intercept
+ * mount an `InMemorySpanExporter`. We use bun's `vi.doMock` to intercept
* `emitPreflightFailureSpan` at the `@inkeep/open-knowledge-server`
* boundary — capturing every call without touching the real OTel SDK.
* Mirrors the precedent set by `onboarding-telemetry.test.ts`.
@@ -13,7 +13,7 @@
* two typed git-preflight error classes).
*/
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
// Pull the real server module first so we can re-export everything except
// `emitPreflightFailureSpan`. Top-level await is supported in bun ESM.
@@ -27,7 +27,7 @@ interface EmittedError {
const emissions: EmittedError[] = [];
-mock.module('@inkeep/open-knowledge-server', () => ({
+vi.doMock('@inkeep/open-knowledge-server', () => ({
...actual,
emitPreflightFailureSpan: (err: unknown) => {
const e = err as Error & { platform?: string; detected?: string };
@@ -57,7 +57,7 @@ interface MessageBoxOptionsLite {
function showMessageBoxSequence(responses: readonly number[]) {
const remaining = [...responses];
- return mock(async () => {
+ return vi.fn(async () => {
const next = remaining.shift();
if (next === undefined) {
throw new Error('showMessageBox called more times than queued');
@@ -79,11 +79,11 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
source: 'PATH' as const,
});
const showMessageBox = showMessageBoxSequence([]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
});
@@ -97,11 +97,11 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
};
const showMessageBox = showMessageBoxSequence([2]); // BUTTON_QUIT
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
});
@@ -121,11 +121,11 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
1, // BUTTON_RETRY
2, // BUTTON_QUIT
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
});
@@ -151,11 +151,11 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
};
};
const showMessageBox = showMessageBoxSequence([1]); // BUTTON_RETRY
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
});
@@ -169,11 +169,11 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
throw new GitTooOldError('darwin', '2.20.0', '2.31.0', '/usr/bin/git', LINUX_GUIDANCE);
};
const showMessageBox = showMessageBoxSequence([2]); // BUTTON_QUIT
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
});
@@ -190,12 +190,12 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
throw new Error('something completely different');
};
const showMessageBox = showMessageBoxSequence([]);
- const openExternal = mock(async () => {});
- const warn = mock(() => {});
+ const openExternal = vi.fn(async () => {});
+ const warn = vi.fn(() => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
log: { warn },
@@ -215,11 +215,11 @@ describe('ensureGitAvailable — FR8 emission per typed-error observation', () =
0, // BUTTON_OPEN_INSTALL_PAGE
2, // BUTTON_QUIT
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
- // biome-ignore lint/suspicious/noExplicitAny: mock.module returns the spy
+ // biome-ignore lint/suspicious/noExplicitAny: vi.doMock returns the spy
showMessageBox: showMessageBox as any,
openExternal,
});
diff --git a/packages/desktop/src/main/git-preflight-handler.test.ts b/packages/desktop/src/main/git-preflight-handler.test.ts
index 6a60b8448..fdfb07fd2 100644
--- a/packages/desktop/src/main/git-preflight-handler.test.ts
+++ b/packages/desktop/src/main/git-preflight-handler.test.ts
@@ -16,12 +16,12 @@
* mocks; the production wiring lives in `main/index.ts`.
*/
-import { describe, expect, mock, test } from 'bun:test';
import {
GitNotAvailableError,
GitTooOldError,
type InstallGuidance,
} from '@inkeep/open-knowledge-server';
+import { describe, expect, test, vi } from 'vitest';
import { ensureGitAvailable, type MessageBoxOptions } from './git-preflight-handler.ts';
const LINUX_GUIDANCE: InstallGuidance = {
@@ -59,7 +59,7 @@ const MAC_GUIDANCE: InstallGuidance = {
function showMessageBoxSequence(responses: readonly number[]) {
const remaining = [...responses];
const calls: MessageBoxOptions[] = [];
- const fn = mock(async (opts: MessageBoxOptions) => {
+ const fn = vi.fn(async (opts: MessageBoxOptions) => {
calls.push(opts);
const next = remaining.shift();
if (next === undefined) {
@@ -72,14 +72,14 @@ function showMessageBoxSequence(responses: readonly number[]) {
describe('ensureGitAvailable', () => {
test("returns 'ok' on first-try success without showing dialog", async () => {
- const assertGitAvailable = mock(() => ({
+ const assertGitAvailable = vi.fn(() => ({
ok: true as const,
version: '2.45.0',
resolvedPath: '/usr/bin/git',
source: 'PATH' as const,
}));
const { fn: showMessageBox, calls } = showMessageBoxSequence([]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -96,14 +96,14 @@ describe('ensureGitAvailable', () => {
test("Quit on first dialog returns 'aborted' without further preflight", async () => {
let calls = 0;
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
calls += 1;
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
2, // BUTTON_QUIT
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -130,14 +130,14 @@ describe('ensureGitAvailable', () => {
});
test('Open Install Page opens URL and re-shows dialog; Quit ends loop', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitNotAvailableError('darwin', MAC_GUIDANCE);
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
0, // BUTTON_OPEN_INSTALL_PAGE
2, // BUTTON_QUIT
]);
- const openExternal = mock(async (_url: string) => {});
+ const openExternal = vi.fn(async (_url: string) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -155,7 +155,7 @@ describe('ensureGitAvailable', () => {
test("Retry → success returns 'recovered'", async () => {
let attempts = 0;
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
attempts += 1;
if (attempts === 1) {
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
@@ -170,7 +170,7 @@ describe('ensureGitAvailable', () => {
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
1, // BUTTON_RETRY
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -185,7 +185,7 @@ describe('ensureGitAvailable', () => {
});
test('Retry → still-missing re-shows dialog; user can Quit to end', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
@@ -193,7 +193,7 @@ describe('ensureGitAvailable', () => {
1, // BUTTON_RETRY
2, // BUTTON_QUIT
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -208,13 +208,13 @@ describe('ensureGitAvailable', () => {
});
test('GitTooOldError variant: dialog title + message reflect the too-old shape', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitTooOldError('linux', '2.20.0', '2.31.0', '/usr/bin/git', LINUX_GUIDANCE);
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
2, // BUTTON_QUIT
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -231,14 +231,14 @@ describe('ensureGitAvailable', () => {
});
test("non-typed error from preflight shows error dialog before 'aborted'", async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new Error('something completely different');
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
0, // The unknown-error dialog has a single 'Quit' button at index 0.
]);
- const openExternal = mock(async () => {});
- const warn = mock((_msg: string, _obj?: unknown) => {});
+ const openExternal = vi.fn(async () => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -267,7 +267,7 @@ describe('ensureGitAvailable', () => {
test('retry that throws non-typed error shows error dialog before aborted', async () => {
let attempts = 0;
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
attempts += 1;
if (attempts === 1) {
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
@@ -278,8 +278,8 @@ describe('ensureGitAvailable', () => {
1, // BUTTON_RETRY on the typed-error dialog
0, // Quit on the unknown-error dialog that follows the failed retry
]);
- const openExternal = mock(async () => {});
- const warn = mock((_msg: string, _obj?: unknown) => {});
+ const openExternal = vi.fn(async () => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -303,17 +303,17 @@ describe('ensureGitAvailable', () => {
});
test('openExternal failure surfaces the URL in the next dialog detail', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitNotAvailableError('darwin', MAC_GUIDANCE);
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
0, // BUTTON_OPEN_INSTALL_PAGE (openExternal throws)
2, // BUTTON_QUIT
]);
- const openExternal = mock(async (_url: string) => {
+ const openExternal = vi.fn(async (_url: string) => {
throw new Error('no XDG default browser configured');
});
- const warn = mock((_msg: string, _obj?: unknown) => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -333,7 +333,7 @@ describe('ensureGitAvailable', () => {
});
test('openExternal success after prior failure clears the URL hint', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitNotAvailableError('darwin', MAC_GUIDANCE);
});
const { fn: showMessageBox, calls: boxCalls } = showMessageBoxSequence([
@@ -342,13 +342,13 @@ describe('ensureGitAvailable', () => {
2, // BUTTON_QUIT
]);
let attempts = 0;
- const openExternal = mock(async (_url: string) => {
+ const openExternal = vi.fn(async (_url: string) => {
attempts += 1;
if (attempts === 1) {
throw new Error('browser unavailable');
}
});
- const warn = mock((_msg: string, _obj?: unknown) => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -367,7 +367,7 @@ describe('ensureGitAvailable', () => {
test('openExternal failure does not abort the loop; user can still Retry', async () => {
let attempts = 0;
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
attempts += 1;
if (attempts === 1) {
throw new GitNotAvailableError('darwin', MAC_GUIDANCE);
@@ -383,10 +383,10 @@ describe('ensureGitAvailable', () => {
0, // BUTTON_OPEN_INSTALL_PAGE (openExternal throws)
1, // BUTTON_RETRY (preflight succeeds)
]);
- const openExternal = mock(async (_url: string) => {
+ const openExternal = vi.fn(async (_url: string) => {
throw new Error('browser unavailable');
});
- const warn = mock((_msg: string, _obj?: unknown) => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -404,7 +404,7 @@ describe('ensureGitAvailable', () => {
});
test('out-of-range dialog response is treated as Quit (defensive)', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
});
const { fn: showMessageBox } = showMessageBoxSequence([
@@ -414,8 +414,8 @@ describe('ensureGitAvailable', () => {
// default.
-1,
]);
- const openExternal = mock(async () => {});
- const warn = mock((_msg: string, _obj?: unknown) => {});
+ const openExternal = vi.fn(async () => {});
+ const warn = vi.fn((_msg: string, _obj?: unknown) => {});
const outcome = await ensureGitAvailable({
assertGitAvailable,
@@ -431,13 +431,13 @@ describe('ensureGitAvailable', () => {
});
test('handler does NOT require a log dep (no-op default)', async () => {
- const assertGitAvailable = mock(() => {
+ const assertGitAvailable = vi.fn(() => {
throw new GitNotAvailableError('linux', LINUX_GUIDANCE);
});
const { fn: showMessageBox } = showMessageBoxSequence([
2, // BUTTON_QUIT
]);
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
// No `log` passed — handler should not throw.
const outcome = await ensureGitAvailable({
diff --git a/packages/desktop/src/main/instance-identity.test.ts b/packages/desktop/src/main/instance-identity.test.ts
index 5496b44ef..b66368857 100644
--- a/packages/desktop/src/main/instance-identity.test.ts
+++ b/packages/desktop/src/main/instance-identity.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { formatInstanceAppName, resolveInstanceLabel } from './instance-identity.ts';
describe('resolveInstanceLabel', () => {
diff --git a/packages/desktop/src/main/instance-isolation.test.ts b/packages/desktop/src/main/instance-isolation.test.ts
index f6381b765..43edfb151 100644
--- a/packages/desktop/src/main/instance-isolation.test.ts
+++ b/packages/desktop/src/main/instance-isolation.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { deriveInstanceUserDataDir, sanitizeInstanceName } from './instance-isolation.ts';
describe('sanitizeInstanceName', () => {
diff --git a/packages/desktop/src/main/integrations-settings.test.ts b/packages/desktop/src/main/integrations-settings.test.ts
index f6369a4d4..d15be8141 100644
--- a/packages/desktop/src/main/integrations-settings.test.ts
+++ b/packages/desktop/src/main/integrations-settings.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { IpcMainInvokeEvent } from 'electron';
+import { describe, expect, test } from 'vitest';
import type {
IntegrationsSetRequest,
IntegrationsSetResult,
diff --git a/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts b/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts
index 85fb15b74..3b46868f5 100644
--- a/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts
+++ b/packages/desktop/src/main/ipc-handlers.showItemInFolder.test.ts
@@ -9,8 +9,9 @@
* outside every project, so an editor window hit `out-of-project` and a
* Navigator window hit `no-project-bound`.
*/
-import { describe, expect, test } from 'bun:test';
+
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { showItemInFolder } from './ipc-handlers.ts';
const BUG_REPORTS = '/Users/tester/.ok/bug-reports';
diff --git a/packages/desktop/src/main/ipc-log.test.ts b/packages/desktop/src/main/ipc-log.test.ts
index 73f1b30e0..7a407203b 100644
--- a/packages/desktop/src/main/ipc-log.test.ts
+++ b/packages/desktop/src/main/ipc-log.test.ts
@@ -19,7 +19,7 @@
* return shape that retriable-consent dialogs depend on.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { logIpcError } from './ipc-log.ts';
interface CapturedWarn {
diff --git a/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts b/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts
index da9406399..1e86b4a1e 100644
--- a/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts
+++ b/packages/desktop/src/main/ipc/local-op-auth-idempotent-start.test.ts
@@ -16,8 +16,9 @@
* happy path and the streamId-mismatch guard in handleAuthCancel /
* handleCloneCancel.
*/
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
+
import type { AuthEvent, CloneEvent } from '@inkeep/open-knowledge-server';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
interface DeviceFlowEntry {
resolve: () => void;
@@ -33,7 +34,7 @@ interface CloneEntry {
const deviceFlowControllers: DeviceFlowEntry[] = [];
const cloneControllers: CloneEntry[] = [];
-mock.module('@inkeep/open-knowledge-server', () => ({
+vi.doMock('@inkeep/open-knowledge-server', () => ({
runAuthStatusSubprocess: () => Promise.resolve({ authenticated: false, host: 'github.com' }),
runAuthReposSubprocess: () => Promise.resolve({ ok: false, error: 'unused' }),
runDeviceFlowSubprocess: ({ onEvent }: { onEvent: (event: AuthEvent) => void }) => {
diff --git a/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts b/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts
index 1d983ec20..deecf2353 100644
--- a/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts
+++ b/packages/desktop/src/main/ipc/local-op-clone-branch.test.ts
@@ -18,8 +18,9 @@
* subprocess. Each mock invocation captures `branch` + `onEvent` so we can
* assert both the spawn-time wire and the runtime event forwarding.
*/
-import { describe, expect, mock, test } from 'bun:test';
+
import type { CloneEvent } from '@inkeep/open-knowledge-server';
+import { describe, expect, test, vi } from 'vitest';
interface CloneSpawn {
url: string;
@@ -30,7 +31,7 @@ interface CloneSpawn {
const cloneSpawns: CloneSpawn[] = [];
-mock.module('@inkeep/open-knowledge-server', () => ({
+vi.doMock('@inkeep/open-knowledge-server', () => ({
runAuthStatusSubprocess: () => Promise.resolve({ authenticated: false, host: 'github.com' }),
runAuthReposSubprocess: () => Promise.resolve({ ok: false, error: 'unused' }),
runDeviceFlowSubprocess: () => ({ done: Promise.resolve(), cancel: () => {} }),
diff --git a/packages/desktop/src/main/ipc/local-op.test.ts b/packages/desktop/src/main/ipc/local-op.test.ts
index 293c95fce..4191cdc44 100644
--- a/packages/desktop/src/main/ipc/local-op.test.ts
+++ b/packages/desktop/src/main/ipc/local-op.test.ts
@@ -11,14 +11,15 @@
* factories surface a `resolve` hook so the test can hold each "subprocess"
* mid-flight while it asserts coalescing behavior.
*/
-import { describe, expect, mock, test } from 'bun:test';
+
import type { AuthReposResponse, AuthStatusResponse } from '@inkeep/open-knowledge-server';
+import { describe, expect, test, vi } from 'vitest';
const statusCalls: Array<{ host: string | undefined; resolve: (r: AuthStatusResponse) => void }> =
[];
const reposCalls: Array<{ host: string | undefined; resolve: (r: AuthReposResponse) => void }> = [];
-mock.module('@inkeep/open-knowledge-server', () => ({
+vi.doMock('@inkeep/open-knowledge-server', () => ({
runAuthStatusSubprocess: ({ host }: { host?: string }) =>
new Promise<AuthStatusResponse>((resolve) => {
statusCalls.push({ host, resolve });
diff --git a/packages/desktop/src/main/ipc/sharing.test.ts b/packages/desktop/src/main/ipc/sharing.test.ts
index a2d18b440..82bd3ec43 100644
--- a/packages/desktop/src/main/ipc/sharing.test.ts
+++ b/packages/desktop/src/main/ipc/sharing.test.ts
@@ -9,11 +9,11 @@
* tests for those siblings.
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
handleSharingSetMode,
handleSharingSetSkillsShared,
diff --git a/packages/desktop/src/main/keepalive.test.ts b/packages/desktop/src/main/keepalive.test.ts
index 9ee45dadf..c2b1ae128 100644
--- a/packages/desktop/src/main/keepalive.test.ts
+++ b/packages/desktop/src/main/keepalive.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { DesktopLogger } from './desktop-logger.ts';
import { createDesktopKeepaliveFactory, toKeepaliveLogger } from './keepalive.ts';
import type { ServerLockMetadataLike } from './window-manager.ts';
diff --git a/packages/desktop/src/main/list-git-worktrees.test.ts b/packages/desktop/src/main/list-git-worktrees.test.ts
index 282d1e0f4..b62e4b9d5 100644
--- a/packages/desktop/src/main/list-git-worktrees.test.ts
+++ b/packages/desktop/src/main/list-git-worktrees.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, describe, expect, test } from 'vitest';
import { listGitWorktrees } from './list-git-worktrees.ts';
const execFileAsync = promisify(execFile);
diff --git a/packages/desktop/src/main/mcp-wiring.test.ts b/packages/desktop/src/main/mcp-wiring.test.ts
index 791e91272..7bebdd275 100644
--- a/packages/desktop/src/main/mcp-wiring.test.ts
+++ b/packages/desktop/src/main/mcp-wiring.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import {
existsSync as fsExistsSync,
mkdirSync as fsMkdirSync,
@@ -18,6 +17,7 @@ import {
type EditorMcpTarget,
type McpEntryClassification,
} from '@inkeep/open-knowledge';
+import { afterEach, describe, expect, test } from 'vitest';
// Imported from cli source, not the @inkeep/open-knowledge build: the classify
// the fallback test drives must read the TOML engine it overrides, and only the
// in-repo source shares the engine singleton with setTomlConfigEngineForTesting.
diff --git a/packages/desktop/src/main/ok-init.test.ts b/packages/desktop/src/main/ok-init.test.ts
index f7e839980..573130714 100644
--- a/packages/desktop/src/main/ok-init.test.ts
+++ b/packages/desktop/src/main/ok-init.test.ts
@@ -4,12 +4,12 @@
* pure-fixture surface area is small enough that mocking adds no signal.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, describe, expect, test } from 'vitest';
import { runOkInit } from './ok-init.ts';
const execFileAsync = promisify(execFile);
diff --git a/packages/desktop/src/main/onboarding-telemetry.test.ts b/packages/desktop/src/main/onboarding-telemetry.test.ts
index 725253396..1948149a1 100644
--- a/packages/desktop/src/main/onboarding-telemetry.test.ts
+++ b/packages/desktop/src/main/onboarding-telemetry.test.ts
@@ -5,7 +5,7 @@
* module boundary so the assertions are independent of whether the OTel SDK
* is enabled.
*/
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { EntryPoint } from '../shared/entry-point.ts';
interface CapturedSpanCall {
@@ -15,7 +15,7 @@ interface CapturedSpanCall {
const capturedCalls: CapturedSpanCall[] = [];
-mock.module('@inkeep/open-knowledge-server', () => ({
+vi.doMock('@inkeep/open-knowledge-server', () => ({
withSpanSync: <T>(
name: string,
options: { attributes?: Record<string, unknown> } | undefined,
diff --git a/packages/desktop/src/main/path-containment.test.ts b/packages/desktop/src/main/path-containment.test.ts
index c9433d886..02eb75c2a 100644
--- a/packages/desktop/src/main/path-containment.test.ts
+++ b/packages/desktop/src/main/path-containment.test.ts
@@ -7,8 +7,8 @@
* suite is their only coverage.
*/
-import { describe, expect, test } from 'bun:test';
import { isPathWithinDir } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import { isPathWithinProject, validateSpawnPath } from './path-containment.ts';
describe('validateSpawnPath — posix', () => {
diff --git a/packages/desktop/src/main/path-containment.ts b/packages/desktop/src/main/path-containment.ts
index 7d28e3e18..129ec6fa3 100644
--- a/packages/desktop/src/main/path-containment.ts
+++ b/packages/desktop/src/main/path-containment.ts
@@ -4,7 +4,7 @@
* `trashItem`, asset opens, bug-report send). Lives in its own leaf module —
* importing only `node:path` — so validation-only consumers don't drag in the
* rest of the handler surface (and its `@inkeep/open-knowledge-server`
- * dependency, which several sibling test suites replace via `mock.module`).
+ * dependency, which several sibling test suites replace via `vi.doMock`).
*/
import { posix as pathPosix, win32 as pathWin32 } from 'node:path';
diff --git a/packages/desktop/src/main/process-safety-net.test.ts b/packages/desktop/src/main/process-safety-net.test.ts
index e29ef1127..95b4b1102 100644
--- a/packages/desktop/src/main/process-safety-net.test.ts
+++ b/packages/desktop/src/main/process-safety-net.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { EventEmitter } from 'node:events';
+import { describe, expect, test } from 'vitest';
import { installStdioBrokenPipeGuard, isBrokenPipeError } from './process-safety-net.ts';
/**
diff --git a/packages/desktop/src/main/project-integrations-settings.test.ts b/packages/desktop/src/main/project-integrations-settings.test.ts
index cb8e4a56f..55d7b87fe 100644
--- a/packages/desktop/src/main/project-integrations-settings.test.ts
+++ b/packages/desktop/src/main/project-integrations-settings.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import type { McpEntryClassification } from '@inkeep/open-knowledge';
import type { IpcMainInvokeEvent } from 'electron';
+import { describe, expect, test } from 'vitest';
import type {
McpWiringEditorId,
ProjectIntegrationsSetRequest,
diff --git a/packages/desktop/src/main/read-git-dir-kind.test.ts b/packages/desktop/src/main/read-git-dir-kind.test.ts
index eb898556a..29f1f171e 100644
--- a/packages/desktop/src/main/read-git-dir-kind.test.ts
+++ b/packages/desktop/src/main/read-git-dir-kind.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import {
chmodSync,
@@ -12,6 +11,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, describe, expect, test } from 'vitest';
import { readGitDirKind } from './read-git-dir-kind.ts';
const execFileAsync = promisify(execFile);
diff --git a/packages/desktop/src/main/remove-git-folder.test.ts b/packages/desktop/src/main/remove-git-folder.test.ts
index e30a351ad..9f86c54f5 100644
--- a/packages/desktop/src/main/remove-git-folder.test.ts
+++ b/packages/desktop/src/main/remove-git-folder.test.ts
@@ -25,7 +25,6 @@
* realpath dance is exercised against the real macOS/Linux semantics.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -37,6 +36,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { removeGitFolder } from './remove-git-folder.ts';
let tmpRoot: string;
diff --git a/packages/desktop/src/main/renderer-console-capture.test.ts b/packages/desktop/src/main/renderer-console-capture.test.ts
index 8e50c80b4..13d7e87b9 100644
--- a/packages/desktop/src/main/renderer-console-capture.test.ts
+++ b/packages/desktop/src/main/renderer-console-capture.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
attachRendererConsoleCapture,
type ConsoleCapturingWebContents,
diff --git a/packages/desktop/src/main/restore-focus.test.ts b/packages/desktop/src/main/restore-focus.test.ts
index ecc4bb281..0c7f0d9d2 100644
--- a/packages/desktop/src/main/restore-focus.test.ts
+++ b/packages/desktop/src/main/restore-focus.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type RestoreFocusDeps,
type RevealableWindow,
diff --git a/packages/desktop/src/main/reveal-external.test.ts b/packages/desktop/src/main/reveal-external.test.ts
index f9132b0db..623ade388 100644
--- a/packages/desktop/src/main/reveal-external.test.ts
+++ b/packages/desktop/src/main/reveal-external.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { handleRevealExternal, type RevealExternalDeps } from './reveal-external.ts';
function makeDeps(overrides: Partial<RevealExternalDeps> = {}) {
- const showItemInFolder = mock((_p: string) => {});
- const confirmReveal = mock(async (_p: string) => true);
+ const showItemInFolder = vi.fn((_p: string) => {});
+ const confirmReveal = vi.fn(async (_p: string) => true);
const deps: RevealExternalDeps = {
probe: () => 'exists',
confirmReveal,
diff --git a/packages/desktop/src/main/server-exit-record.test.ts b/packages/desktop/src/main/server-exit-record.test.ts
index be9c894e7..43f3d72ce 100644
--- a/packages/desktop/src/main/server-exit-record.test.ts
+++ b/packages/desktop/src/main/server-exit-record.test.ts
@@ -6,11 +6,11 @@
* them, and the fail-soft write path.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SERVER_EXIT_LOG } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import { createServerExitRecorder, type ServerExitRecord } from './server-exit-record.ts';
const tmpDirs: string[] = [];
diff --git a/packages/desktop/src/main/share-handoff.test.ts b/packages/desktop/src/main/share-handoff.test.ts
index ba19a6ebb..52e0722c9 100644
--- a/packages/desktop/src/main/share-handoff.test.ts
+++ b/packages/desktop/src/main/share-handoff.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildContinueUrl,
classifyRedeemRequest,
diff --git a/packages/desktop/src/main/signal-detached-server-stop.test.ts b/packages/desktop/src/main/signal-detached-server-stop.test.ts
index 71ab5aef9..cfbe055a1 100644
--- a/packages/desktop/src/main/signal-detached-server-stop.test.ts
+++ b/packages/desktop/src/main/signal-detached-server-stop.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
signalDetachedServerStop,
signalStopOwnedUtilityForks,
@@ -20,7 +20,7 @@ function ctx(
describe('signalDetachedServerStop (before-quit-for-update teardown)', () => {
test('sends SIGTERM to every detached server pid', () => {
- const killProbe = mock((_pid: number, _signal: number | NodeJS.Signals) => {});
+ const killProbe = vi.fn((_pid: number, _signal: number | NodeJS.Signals) => {});
const signalled = signalDetachedServerStop(
[
['/proj/a', 101],
@@ -35,26 +35,26 @@ describe('signalDetachedServerStop (before-quit-for-update teardown)', () => {
});
test('treats an already-exited server (ESRCH) as done without logging a failure', () => {
- const killProbe = mock((_pid: number, _signal: number | NodeJS.Signals) => {
+ const killProbe = vi.fn((_pid: number, _signal: number | NodeJS.Signals) => {
const err = new Error('no such process') as NodeJS.ErrnoException;
err.code = 'ESRCH';
throw err;
});
- const log = { warn: mock((_o: object, _m: string) => {}) };
+ const log = { warn: vi.fn((_o: object, _m: string) => {}) };
const signalled = signalDetachedServerStop([['/proj/gone', 303]], killProbe, log);
expect(signalled).toBe(0);
expect(log.warn).not.toHaveBeenCalled();
});
test('logs but never throws on a non-ESRCH signal failure, and continues to later pids', () => {
- const killProbe = mock((pid: number, _signal: number | NodeJS.Signals) => {
+ const killProbe = vi.fn((pid: number, _signal: number | NodeJS.Signals) => {
if (pid === 404) {
const err = new Error('operation not permitted') as NodeJS.ErrnoException;
err.code = 'EPERM';
throw err;
}
});
- const log = { warn: mock((_o: object, _m: string) => {}) };
+ const log = { warn: vi.fn((_o: object, _m: string) => {}) };
// The EPERM pid is first to prove iteration continues past a failure.
const signalled = signalDetachedServerStop(
[
@@ -76,7 +76,7 @@ describe('signalDetachedServerStop (before-quit-for-update teardown)', () => {
});
test('no entries (already drained — e.g. the Relaunch-now path) is a clean no-op', () => {
- const killProbe = mock((_pid: number, _signal: number | NodeJS.Signals) => {});
+ const killProbe = vi.fn((_pid: number, _signal: number | NodeJS.Signals) => {});
expect(signalDetachedServerStop([], killProbe)).toBe(0);
expect(killProbe).not.toHaveBeenCalled();
});
@@ -84,16 +84,16 @@ describe('signalDetachedServerStop (before-quit-for-update teardown)', () => {
describe('signalStopOwnedUtilityForks (shared utility-fork hard-kill)', () => {
test('SIGKILLs every owned utility fork', () => {
- const killA = mock((_s: NodeJS.Signals) => {});
- const killB = mock((_s: NodeJS.Signals) => {});
+ const killA = vi.fn((_s: NodeJS.Signals) => {});
+ const killB = vi.fn((_s: NodeJS.Signals) => {});
signalStopOwnedUtilityForks([ctx(true, killA, '/a'), ctx(true, killB, '/b')]);
expect(killA).toHaveBeenCalledWith('SIGKILL');
expect(killB).toHaveBeenCalledWith('SIGKILL');
});
test('skips contexts that do not own their server or have no utility', () => {
- const killOwned = mock((_s: NodeJS.Signals) => {});
- const killNotOwned = mock((_s: NodeJS.Signals) => {});
+ const killOwned = vi.fn((_s: NodeJS.Signals) => {});
+ const killNotOwned = vi.fn((_s: NodeJS.Signals) => {});
signalStopOwnedUtilityForks([
ctx(false, killNotOwned), // attached (sibling-owned) server — must not touch
ctx(true, null), // detached server, no in-process utility fork
@@ -104,11 +104,11 @@ describe('signalStopOwnedUtilityForks (shared utility-fork hard-kill)', () => {
});
test('logs but never throws on a kill failure, and continues to later forks', () => {
- const killLater = mock((_s: NodeJS.Signals) => {});
- const throwing = mock((_s: NodeJS.Signals) => {
+ const killLater = vi.fn((_s: NodeJS.Signals) => {});
+ const throwing = vi.fn((_s: NodeJS.Signals) => {
throw new Error('already dead');
});
- const log = { warn: mock((_o: object, _m: string) => {}) };
+ const log = { warn: vi.fn((_o: object, _m: string) => {}) };
signalStopOwnedUtilityForks([ctx(true, throwing, '/boom'), ctx(true, killLater, '/ok')], log);
expect(killLater).toHaveBeenCalledWith('SIGKILL');
expect(log.warn).toHaveBeenCalledTimes(1);
diff --git a/packages/desktop/src/main/startup-trace.test.ts b/packages/desktop/src/main/startup-trace.test.ts
index fba09c078..12dedf78a 100644
--- a/packages/desktop/src/main/startup-trace.test.ts
+++ b/packages/desktop/src/main/startup-trace.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetStartupTraceForTest,
beginRoot,
diff --git a/packages/desktop/src/main/startup-waterfall.test.ts b/packages/desktop/src/main/startup-waterfall.test.ts
index a6b65c0a1..96f0706e5 100644
--- a/packages/desktop/src/main/startup-waterfall.test.ts
+++ b/packages/desktop/src/main/startup-waterfall.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type RendererMarks,
type ServerBootTimings,
diff --git a/packages/desktop/src/main/terminal-consent.test.ts b/packages/desktop/src/main/terminal-consent.test.ts
index 9c532ee95..7adf98207 100644
--- a/packages/desktop/src/main/terminal-consent.test.ts
+++ b/packages/desktop/src/main/terminal-consent.test.ts
@@ -11,11 +11,11 @@
* (the symptom that shipped when the default was 750ms).
*/
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import { describe, expect, test } from 'vitest';
import {
isTerminalConsented,
isTerminalConsentedWithGrace,
diff --git a/packages/desktop/src/main/terminal-telemetry.test.ts b/packages/desktop/src/main/terminal-telemetry.test.ts
index 0c7b40ac7..870d70fd1 100644
--- a/packages/desktop/src/main/terminal-telemetry.test.ts
+++ b/packages/desktop/src/main/terminal-telemetry.test.ts
@@ -6,7 +6,7 @@
* the OTel SDK is enabled. The subject mirrors the `onboarding-telemetry.ts`
* emitter pattern (same `withSpanSync` + bounded-attribute discipline).
*/
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
interface CapturedSpanCall {
name: string;
@@ -15,7 +15,7 @@ interface CapturedSpanCall {
const capturedCalls: CapturedSpanCall[] = [];
-mock.module('@inkeep/open-knowledge-server', () => ({
+vi.doMock('@inkeep/open-knowledge-server', () => ({
withSpanSync: <T>(
name: string,
options: { attributes?: Record<string, unknown> } | undefined,
diff --git a/packages/desktop/src/main/terminal-window-registry.test.ts b/packages/desktop/src/main/terminal-window-registry.test.ts
index b38babe10..2d364d1be 100644
--- a/packages/desktop/src/main/terminal-window-registry.test.ts
+++ b/packages/desktop/src/main/terminal-window-registry.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
getTerminalWindowContext,
registerTerminalWindow,
diff --git a/packages/desktop/src/main/terminal-window.test.ts b/packages/desktop/src/main/terminal-window.test.ts
index 7d2919159..f5b2555de 100644
--- a/packages/desktop/src/main/terminal-window.test.ts
+++ b/packages/desktop/src/main/terminal-window.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { ShowGateRegistry } from './show-gate.ts';
import type { TerminalReaper } from './terminal-lifecycle.ts';
import {
@@ -26,8 +26,8 @@ function makeFakeWindow(id: number) {
if (event === 'closed') closedHandlers.push(cb);
},
once: () => {},
- loadFile: mock(async () => {}),
- loadURL: mock(async () => {}),
+ loadFile: vi.fn(async () => {}),
+ loadURL: vi.fn(async () => {}),
webContents: { send: () => {}, once: () => {} },
} as unknown as TerminalBrowserWindow;
return {
@@ -44,11 +44,11 @@ function makeDeps(opts: {
rendererDevUrl?: string | null;
}) {
const fake = makeFakeWindow(opts.id);
- const createWindow = mock((_o: { additionalArguments: string[]; title: string }) => fake.window);
- const disposeShowGate = mock(() => {});
- const register = mock((_window: unknown, _opts?: { kind?: string }) => disposeShowGate);
+ const createWindow = vi.fn((_o: { additionalArguments: string[]; title: string }) => fake.window);
+ const disposeShowGate = vi.fn(() => {});
+ const register = vi.fn((_window: unknown, _opts?: { kind?: string }) => disposeShowGate);
const showGate = { register, fireThemeApplied: () => {} } as unknown as ShowGateRegistry;
- const killForWindow = mock((_id: number) => {});
+ const killForWindow = vi.fn((_id: number) => {});
const terminalReaper = { killForWindow, killAll: () => {} } as unknown as TerminalReaper;
return {
fake,
@@ -170,13 +170,13 @@ describe('createTerminalWindow', () => {
test('a renderer load rejection surfaces a structured terminal-load-failed warn (not an unhandled rejection)', async () => {
const h = makeDeps({ id: 70_001, project: PROJECT, rendererDevUrl: 'http://localhost:5173' });
- const failing = mock(async () => {
+ const failing = vi.fn(async () => {
throw new Error('renderer boom');
});
// Override the happy-path loadURL with one that rejects, exercising the
// factory's `.catch` handler rather than the resolve path the tests above hit.
(h.fake.window as unknown as { loadURL: typeof failing }).loadURL = failing;
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
createTerminalWindow(h.deps);
// The factory attaches its `.catch` synchronously; the rejected promise queues
diff --git a/packages/desktop/src/main/url-scheme.settle.test.ts b/packages/desktop/src/main/url-scheme.settle.test.ts
index 0f5224b41..a7272f653 100644
--- a/packages/desktop/src/main/url-scheme.settle.test.ts
+++ b/packages/desktop/src/main/url-scheme.settle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
// `waitForUrlLaunchSettled` is the REAL settle SOURCE the boot coordinator
// (`resolveBootRestoreDecision`) awaits before reading the launch flag. It lives
// on the `ProtocolHandlerControl` returned by `registerProtocolHandler` — the
diff --git a/packages/desktop/src/main/userdata-migration.test.ts b/packages/desktop/src/main/userdata-migration.test.ts
index 3b285cdba..63eafd9fc 100644
--- a/packages/desktop/src/main/userdata-migration.test.ts
+++ b/packages/desktop/src/main/userdata-migration.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { migrateLegacyUserDataDir } from './userdata-migration.ts';
/**
diff --git a/packages/desktop/src/main/utility-fork-env.test.ts b/packages/desktop/src/main/utility-fork-env.test.ts
index c91a77d6f..f181e9b1a 100644
--- a/packages/desktop/src/main/utility-fork-env.test.ts
+++ b/packages/desktop/src/main/utility-fork-env.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { buildUtilityForkEnv } from './utility-fork-env.ts';
/**
diff --git a/packages/desktop/src/main/version-drift.test.ts b/packages/desktop/src/main/version-drift.test.ts
index 7aa3d6a1a..7c52dab9f 100644
--- a/packages/desktop/src/main/version-drift.test.ts
+++ b/packages/desktop/src/main/version-drift.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { CLIENT_RUNTIME_VERSION_FALLBACK } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
classifyServerVersion,
computeFirstLaunchAfterUpgrade,
diff --git a/packages/desktop/src/main/view-menu-state.test.ts b/packages/desktop/src/main/view-menu-state.test.ts
index a57da4a91..a69179188 100644
--- a/packages/desktop/src/main/view-menu-state.test.ts
+++ b/packages/desktop/src/main/view-menu-state.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildViewMenuStateDeps,
createDefaultEditorViewMenuState,
diff --git a/packages/desktop/src/main/window-min-size.test.ts b/packages/desktop/src/main/window-min-size.test.ts
index 07a3b4b6d..f193f8dd9 100644
--- a/packages/desktop/src/main/window-min-size.test.ts
+++ b/packages/desktop/src/main/window-min-size.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { WINDOW_MIN_SIZE } from './window-min-size.ts';
/**
diff --git a/packages/desktop/src/main/window-placement.test.ts b/packages/desktop/src/main/window-placement.test.ts
index 80d66150e..0b2e7bd18 100644
--- a/packages/desktop/src/main/window-placement.test.ts
+++ b/packages/desktop/src/main/window-placement.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { PersistedWindowBounds } from './state-store.ts';
import {
MIN_VISIBLE_WIDTH_PX,
diff --git a/packages/desktop/src/main/worktree-autosync-inherit.test.ts b/packages/desktop/src/main/worktree-autosync-inherit.test.ts
index 164e0408e..ef0d331c1 100644
--- a/packages/desktop/src/main/worktree-autosync-inherit.test.ts
+++ b/packages/desktop/src/main/worktree-autosync-inherit.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
import { resolveConfigPath, writeConfigPatch } from '@inkeep/open-knowledge-core/server';
+import { afterEach, describe, expect, test } from 'vitest';
import { parse as parseYaml } from 'yaml';
import { resolveRootAutoSync, seedWorktreeAutoSync } from './worktree-autosync-inherit.ts';
diff --git a/packages/desktop/src/main/worktree-recents.test.ts b/packages/desktop/src/main/worktree-recents.test.ts
index c2584b34c..d2e3c08f4 100644
--- a/packages/desktop/src/main/worktree-recents.test.ts
+++ b/packages/desktop/src/main/worktree-recents.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
classifyRecentGit,
classifyRecentGitAsync,
diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.ts
index 2375005b2..b41442788 100644
--- a/packages/desktop/src/main/worktree-service.test.ts
+++ b/packages/desktop/src/main/worktree-service.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFile, execFileSync } from 'node:child_process';
import {
existsSync,
@@ -14,6 +13,7 @@ import { join } from 'node:path';
import { promisify } from 'node:util';
import { addOkPathsToGitExclude, getOkArtifactPaths } from '@inkeep/open-knowledge';
import { initContent } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
import { discoverProject } from './folder-admission.ts';
import { clearRecentGitCache } from './worktree-recents.ts';
import {
diff --git a/packages/desktop/src/main/worktree-setup-inherit.test.ts b/packages/desktop/src/main/worktree-setup-inherit.test.ts
index ad0d7db26..b347d1774 100644
--- a/packages/desktop/src/main/worktree-setup-inherit.test.ts
+++ b/packages/desktop/src/main/worktree-setup-inherit.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -10,6 +9,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { parse as parseYaml } from 'yaml';
import {
detectRootWiredEditors,
diff --git a/packages/desktop/src/shared/entry-point.test.ts b/packages/desktop/src/shared/entry-point.test.ts
index 87e3f44dd..8f2008f2d 100644
--- a/packages/desktop/src/shared/entry-point.test.ts
+++ b/packages/desktop/src/shared/entry-point.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'bun:test';
+import { describe, expect, it } from 'vitest';
import { isEntryPoint } from './entry-point.ts';
describe('isEntryPoint', () => {
diff --git a/packages/desktop/src/shared/ipc-send.test.ts b/packages/desktop/src/shared/ipc-send.test.ts
index 4d35978ad..13177d4ce 100644
--- a/packages/desktop/src/shared/ipc-send.test.ts
+++ b/packages/desktop/src/shared/ipc-send.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type GateableWebContents, registerPendingDelivery } from './ipc-send.ts';
function makeFakeWebContents() {
diff --git a/packages/desktop/src/shared/ok-desktop-mode.test.ts b/packages/desktop/src/shared/ok-desktop-mode.test.ts
index 005d754fe..43e6c5207 100644
--- a/packages/desktop/src/shared/ok-desktop-mode.test.ts
+++ b/packages/desktop/src/shared/ok-desktop-mode.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveOkDesktopMode } from './ok-desktop-mode.ts';
describe('resolveOkDesktopMode', () => {
diff --git a/packages/desktop/src/utility/keyring-smoke.test.ts b/packages/desktop/src/utility/keyring-smoke.test.ts
index a87b6eca7..5a114896b 100644
--- a/packages/desktop/src/utility/keyring-smoke.test.ts
+++ b/packages/desktop/src/utility/keyring-smoke.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { runKeyringSmoke } from './keyring-smoke.ts';
interface FakeEntryCalls {
@@ -77,7 +77,7 @@ describe('runKeyringSmoke', () => {
});
test('load failure: loadKeyring throws, no Entry methods invoked', async () => {
- const loadKeyring = mock(() => Promise.reject(new Error('module not found')));
+ const loadKeyring = vi.fn(() => Promise.reject(new Error('module not found')));
const result = await runKeyringSmoke({ loadKeyring });
expect(result.ok).toBe(false);
expect(result.error).toBe('module not found');
diff --git a/packages/desktop/tests/integration/asset-open-ipc.test.ts b/packages/desktop/tests/integration/asset-open-ipc.test.ts
index 8ebfbe3c3..3b35d3840 100644
--- a/packages/desktop/tests/integration/asset-open-ipc.test.ts
+++ b/packages/desktop/tests/integration/asset-open-ipc.test.ts
@@ -25,8 +25,8 @@
* `handoff-ipc.test.ts`, extended with injected FS / shell-open deps.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { IpcMain, IpcMainInvokeEvent, IpcRenderer } from 'electron';
+import { describe, expect, test, vi } from 'vitest';
import { openAssetSafely, revealAssetSafely } from '../../src/main/asset-allowlist.ts';
import { createHandler } from '../../src/shared/ipc-handler.ts';
import { createInvoker } from '../../src/shared/ipc-invoke.ts';
@@ -78,7 +78,7 @@ function makeResolver(existingPaths: string[]): (path: string) => string {
describe("'ok:shell:open-asset' round-trip", () => {
test('happy path: renderer invoke → main handler → shell.openPath fires; result has ok:true', async () => {
const { handle, invoke } = setupRig();
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const canonical = `${PROJECT}/notes/meeting.pdf`;
handle('ok:shell:open-asset', async (_event, relPath) =>
@@ -101,7 +101,7 @@ describe("'ok:shell:open-asset' round-trip", () => {
test('path escape from renderer surfaces as result-object refusal (not Promise rejection)', async () => {
const { handle, invoke } = setupRig();
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
handle('ok:shell:open-asset', async (_event, relPath) =>
openAssetSafely(
@@ -125,7 +125,7 @@ describe("'ok:shell:open-asset' round-trip", () => {
test('executable extension rejected across the IPC boundary', async () => {
const { handle, invoke } = setupRig();
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const canonical = `${PROJECT}/notes/setup.sh`;
handle('ok:shell:open-asset', async (_event, relPath) =>
@@ -148,7 +148,7 @@ describe("'ok:shell:open-asset' round-trip", () => {
test('not-found refusal distinguished from resolve-error', async () => {
const { handle, invoke } = setupRig();
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
handle('ok:shell:open-asset', async (_event, relPath) =>
openAssetSafely(
@@ -171,7 +171,7 @@ describe("'ok:shell:open-asset' round-trip", () => {
describe("'ok:shell:reveal-asset' round-trip", () => {
test('happy path: shell.showItemInFolder fires on canonical path', async () => {
const { handle, invoke } = setupRig();
- const showItemInFolder = mock((_: string) => {});
+ const showItemInFolder = vi.fn((_: string) => {});
const canonical = `${PROJECT}/notes/meeting.pdf`;
handle('ok:shell:reveal-asset', async (_event, relPath) =>
@@ -194,7 +194,7 @@ describe("'ok:shell:reveal-asset' round-trip", () => {
test('reveal on an executable is allowed (content handler is not dispatched)', async () => {
const { handle, invoke } = setupRig();
- const showItemInFolder = mock((_: string) => {});
+ const showItemInFolder = vi.fn((_: string) => {});
const canonical = `${PROJECT}/notes/setup.sh`;
handle('ok:shell:reveal-asset', async (_event, relPath) =>
diff --git a/packages/desktop/tests/integration/detached-lifecycle.test.ts b/packages/desktop/tests/integration/detached-lifecycle.test.ts
index 5c1cac212..105fb466b 100644
--- a/packages/desktop/tests/integration/detached-lifecycle.test.ts
+++ b/packages/desktop/tests/integration/detached-lifecycle.test.ts
@@ -35,7 +35,6 @@
* signal worth surfacing.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
@@ -44,6 +43,7 @@ import { dirname, join, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
import { isProcessAlive } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
// Resolve the built CLI relative to this test file so the test runs from
// anywhere (root, packages/desktop, worktree).
diff --git a/packages/desktop/tests/integration/dock-visibility.test.ts b/packages/desktop/tests/integration/dock-visibility.test.ts
index 44359daec..0feefefc9 100644
--- a/packages/desktop/tests/integration/dock-visibility.test.ts
+++ b/packages/desktop/tests/integration/dock-visibility.test.ts
@@ -45,10 +45,10 @@
*
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { resolveDetachedSpawnArgs } from '../../src/main/resolve-detached-spawn-args.ts';
const HERE = dirname(fileURLToPath(import.meta.url));
diff --git a/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts b/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts
index febfef61a..a43ec00be 100644
--- a/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts
+++ b/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts
@@ -22,7 +22,6 @@
* teardown wiring is unit-tested; this pins the REAL server behavior it relies on.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
@@ -31,6 +30,7 @@ import { dirname, join, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
import { createEphemeralProjectDir, isProcessAlive } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url));
const CLI_MJS_PATH = resolve(HERE, '../../../cli/dist/cli.mjs');
diff --git a/packages/desktop/tests/integration/handoff-ipc.test.ts b/packages/desktop/tests/integration/handoff-ipc.test.ts
index e6ec3bbd2..b5de0bbbf 100644
--- a/packages/desktop/tests/integration/handoff-ipc.test.ts
+++ b/packages/desktop/tests/integration/handoff-ipc.test.ts
@@ -24,8 +24,8 @@
* unit tests, extended so both ends see the same in-memory surface.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { IpcMain, IpcMainInvokeEvent, IpcRenderer } from 'electron';
+import { describe, expect, test, vi } from 'vitest';
import {
detectProtocol as detectProtocolImpl,
recordHandoff as recordHandoffImpl,
@@ -109,7 +109,7 @@ describe("'ok:shell:open-external' routes v0 schemes through the allowlist", ()
for (const [label, url] of ALLOWED_PAYLOADS) {
test(`passes ${label} URL through to shell.openExternal`, async () => {
const { handle, invoke } = setupRig();
- const openExternal = mock((_url: string) => Promise.resolve());
+ const openExternal = vi.fn((_url: string) => Promise.resolve());
handle('ok:shell:open-external', async (_event, requested) => {
const check = checkOutboundUrl(requested);
if (!check.ok) {
@@ -135,7 +135,7 @@ describe("'ok:shell:open-external' routes v0 schemes through the allowlist", ()
for (const [label, url] of BLOCKED_PAYLOADS) {
test(`rejects ${label} — allowlist gate runs before shell.openExternal`, async () => {
const { handle, invoke } = setupRig();
- const openExternal = mock((_url: string) => Promise.resolve());
+ const openExternal = vi.fn((_url: string) => Promise.resolve());
handle('ok:shell:open-external', async (_event, requested) => {
const check = checkOutboundUrl(requested);
if (!check.ok) {
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index e8f3d0806..d0be2c159 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -29,9 +29,9 @@
* developer can find the existing tests via this index.
*/
-import { describe, expect, test } from 'bun:test';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
describe('M1 smoke', () => {
test('Test 1 — dev loop: Playwright _electron.launch (DEFERRED to M2)', () => {
diff --git a/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts b/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts
index 4e9714717..edbf9cbc6 100644
--- a/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts
+++ b/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts
@@ -18,9 +18,9 @@
* interface (`biome check`) → observable outcome (diagnostic count).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper.ts';
// __dirname → packages/desktop/tests/integration/. Repo root is 4 levels up.
diff --git a/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts b/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts
index 10c6061b2..3ea769718 100644
--- a/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts
+++ b/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts
@@ -22,9 +22,9 @@
* interface (`biome check`) → observable outcome (diagnostic count).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper.ts';
// __dirname → packages/desktop/tests/integration/. Repo root is 4 levels up.
diff --git a/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts b/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts
index ca629f161..16cb3a113 100644
--- a/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts
+++ b/packages/desktop/tests/integration/packaged-helper-runs-as-node.test.ts
@@ -49,7 +49,6 @@
* Or via the okdesk function (see ~/.zshrc).
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { existsSync, readdirSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
@@ -58,6 +57,7 @@ import {
HELPER_BUNDLE_NAME,
HELPER_EXECUTABLE_NAME,
} from '@inkeep/open-knowledge-core/helper-bundle';
+import { describe, expect, test } from 'vitest';
const HERE = dirname(fileURLToPath(import.meta.url));
const desktopRoot = resolve(HERE, '../..');
diff --git a/packages/desktop/tests/integration/smoke-mock-update.test.ts b/packages/desktop/tests/integration/smoke-mock-update.test.ts
index de4e955a7..f0bf972c8 100644
--- a/packages/desktop/tests/integration/smoke-mock-update.test.ts
+++ b/packages/desktop/tests/integration/smoke-mock-update.test.ts
@@ -14,10 +14,10 @@
* manual verification.
*/
-import { describe, expect, test } from 'bun:test';
import { spawn } from 'node:child_process';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
const __filename = fileURLToPath(import.meta.url);
const SCRIPT_PATH = join(dirname(__filename), '..', '..', 'scripts', 'smoke-mock-update.mjs');
diff --git a/packages/desktop/tests/main/asset-menu.test.ts b/packages/desktop/tests/main/asset-menu.test.ts
index d2c761ee2..47c217bad 100644
--- a/packages/desktop/tests/main/asset-menu.test.ts
+++ b/packages/desktop/tests/main/asset-menu.test.ts
@@ -4,8 +4,8 @@
* integration with an injected Menu ctor.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { BrowserWindow, Menu, MenuItemConstructorOptions } from 'electron';
+import { describe, expect, test, vi } from 'vitest';
import {
buildAssetMenuTemplate,
popAssetMenu,
@@ -27,9 +27,9 @@ describe('revealMenuLabel — platform-specific Reveal text', () => {
describe('buildAssetMenuTemplate', () => {
function makeActions() {
return {
- reveal: mock(() => {}),
- openInDefault: mock(() => {}),
- copyLink: mock(() => {}),
+ reveal: vi.fn(() => {}),
+ openInDefault: vi.fn(() => {}),
+ copyLink: vi.fn(() => {}),
};
}
@@ -104,9 +104,9 @@ describe('buildAssetMenuTemplate', () => {
describe('popAssetMenu', () => {
test('builds template + pops via injected Menu ctor', () => {
- const popup = mock((_: unknown) => {});
+ const popup = vi.fn((_: unknown) => {});
const menuInstance = { popup } as unknown as ReturnType<typeof Menu.buildFromTemplate>;
- const buildFromTemplate = mock((_: MenuItemConstructorOptions[]) => menuInstance);
+ const buildFromTemplate = vi.fn((_: MenuItemConstructorOptions[]) => menuInstance);
const fakeWindow = { id: 42, isDestroyed: () => false } as unknown as BrowserWindow;
popAssetMenu(
@@ -130,9 +130,9 @@ describe('popAssetMenu', () => {
});
test('destroyed window → no build, no popup (right-click racing window close)', () => {
- const popup = mock((_: unknown) => {});
+ const popup = vi.fn((_: unknown) => {});
const menuInstance = { popup } as unknown as ReturnType<typeof Menu.buildFromTemplate>;
- const buildFromTemplate = mock((_: MenuItemConstructorOptions[]) => menuInstance);
+ const buildFromTemplate = vi.fn((_: MenuItemConstructorOptions[]) => menuInstance);
const fakeWindow = { id: 42, isDestroyed: () => true } as unknown as BrowserWindow;
popAssetMenu(
diff --git a/packages/desktop/tests/main/asset-open-handlers.test.ts b/packages/desktop/tests/main/asset-open-handlers.test.ts
index d23611183..7cc177787 100644
--- a/packages/desktop/tests/main/asset-open-handlers.test.ts
+++ b/packages/desktop/tests/main/asset-open-handlers.test.ts
@@ -8,7 +8,7 @@
* the same handlers through the in-memory IPC bus.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
extractPathExtension,
openAssetSafely,
@@ -62,7 +62,7 @@ describe('extractPathExtension', () => {
describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
test('happy path: contained + exists + non-blocklist → openPath fires', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const canonical = `${PROJECT}/notes/meeting.pdf`;
const result = await openAssetSafely(
{
@@ -79,7 +79,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('path traversal (../../etc/passwd) → path-escape', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const result = await openAssetSafely(
{
projectPath: PROJECT,
@@ -95,7 +95,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('absolute path from renderer → path-escape', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const result = await openAssetSafely(
{
projectPath: PROJECT,
@@ -111,7 +111,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('symlink escape (realpath canonicalizes outside project) → path-escape', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
// Simulate: project has `notes/link.pdf` which is a symlink to /etc/passwd
const result = await openAssetSafely(
{
@@ -129,7 +129,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('missing file → not-found (ENOENT from realpath)', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const result = await openAssetSafely(
{
projectPath: PROJECT,
@@ -145,7 +145,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('non-ENOENT realpath failure → resolve-error', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const result = await openAssetSafely(
{
projectPath: PROJECT,
@@ -165,7 +165,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('executable extension (.sh) → extension-blocked even if path is contained + exists', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const canonical = `${PROJECT}/notes/setup.sh`;
const result = await openAssetSafely(
{
@@ -182,7 +182,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('uppercase executable extension (.EXE) is still blocked (case-insensitive)', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
const canonical = `${PROJECT}/notes/installer.EXE`;
const result = await openAssetSafely(
{
@@ -199,7 +199,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
});
test('scripted-doc extensions (.html, .svg, .xml) are blocked per stored-XSS defense', async () => {
- const openPath = mock(async (_: string) => '');
+ const openPath = vi.fn(async (_: string) => '');
for (const name of ['page.html', 'picture.svg', 'doc.xml', 'email.mhtml']) {
const canonical = `${PROJECT}/notes/${name}`;
const result = await openAssetSafely(
@@ -220,7 +220,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
test('openPath returning non-empty error string → resolve-error', async () => {
// shell.openPath returns a non-empty string when the OS handler refuses
// the dispatch — e.g. "No application is associated with .foo files"
- const openPath = mock(async (_: string) => 'No handler for .foo');
+ const openPath = vi.fn(async (_: string) => 'No handler for .foo');
const canonical = `${PROJECT}/notes/file.foo`;
const result = await openAssetSafely(
{
@@ -239,7 +239,7 @@ describe('openAssetSafely (FR-A6 + D-A5 + D-A9)', () => {
describe('revealAssetSafely (FR-A6; extension blocklist does NOT apply)', () => {
test('happy path: contained + exists → showItemInFolder fires on canonical', async () => {
- const showItemInFolder = mock((_: string) => {});
+ const showItemInFolder = vi.fn((_: string) => {});
const canonical = `${PROJECT}/notes/meeting.pdf`;
const result = await revealAssetSafely(
{
@@ -256,7 +256,7 @@ describe('revealAssetSafely (FR-A6; extension blocklist does NOT apply)', () =>
});
test('reveal on an executable is ALLOWED (shell.showItemInFolder opens parent only)', async () => {
- const showItemInFolder = mock((_: string) => {});
+ const showItemInFolder = vi.fn((_: string) => {});
const canonical = `${PROJECT}/notes/setup.sh`;
const result = await revealAssetSafely(
{
@@ -273,7 +273,7 @@ describe('revealAssetSafely (FR-A6; extension blocklist does NOT apply)', () =>
});
test('path escape still refused', async () => {
- const showItemInFolder = mock((_: string) => {});
+ const showItemInFolder = vi.fn((_: string) => {});
const result = await revealAssetSafely(
{
projectPath: PROJECT,
@@ -289,7 +289,7 @@ describe('revealAssetSafely (FR-A6; extension blocklist does NOT apply)', () =>
});
test('missing file → not-found', async () => {
- const showItemInFolder = mock((_: string) => {});
+ const showItemInFolder = vi.fn((_: string) => {});
const result = await revealAssetSafely(
{
projectPath: PROJECT,
diff --git a/packages/desktop/tests/main/asset-safety-net.test.ts b/packages/desktop/tests/main/asset-safety-net.test.ts
index f852887f9..8bd726e86 100644
--- a/packages/desktop/tests/main/asset-safety-net.test.ts
+++ b/packages/desktop/tests/main/asset-safety-net.test.ts
@@ -5,7 +5,7 @@
* external URLs.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
attachAssetSafetyNet,
matchAssetUrl,
@@ -136,9 +136,9 @@ function noopOpenExternal(_: string): Promise<void> {
describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
test('asset URL new-window request → denied + openAsset fires', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
- const log = mock((_: unknown) => {});
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+ const log = vi.fn((_: unknown) => {});
let installedHandler: ((details: { url: string }) => { action: 'allow' | 'deny' }) | null =
null;
@@ -165,8 +165,8 @@ describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
});
test('cross-origin https new-window → denied + openExternal fires', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
let installedHandler: ((details: { url: string }) => { action: 'allow' | 'deny' }) | null =
null;
@@ -188,8 +188,8 @@ describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
});
test('disallowed scheme new-window (javascript:) → denied + openExternal throw is logged', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(async (_: string) => {
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(async (_: string) => {
throw new Error('shell.openExternal blocked: scheme-not-allowed: javascript:');
});
const logEvents: unknown[] = [];
@@ -224,8 +224,8 @@ describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
});
test('openAsset refusal (path-escape on pdf) is logged', async () => {
- const openAsset = mock(async (_: string) => ({ ok: false, reason: 'path-escape' }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: false, reason: 'path-escape' }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
const logEvents: unknown[] = [];
const log = (evt: unknown) => {
logEvents.push(evt);
@@ -257,9 +257,9 @@ describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
// editorOrigin (apiOrigin) is a separate port. `window.open('#/doc')`
// resolves to a :5173 route — which must navigate the current window in-app,
// not leak to the OS browser.
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
- const executeJavaScript = mock(async (_: string) => undefined);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+ const executeJavaScript = vi.fn(async (_: string) => undefined);
let installedHandler: ((details: { url: string }) => { action: 'allow' | 'deny' }) | null =
null;
@@ -294,9 +294,9 @@ describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
});
test('cross-origin new-window with renderer URL present → still openExternal (not in-app)', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
- const executeJavaScript = mock(async (_: string) => undefined);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
+ const executeJavaScript = vi.fn(async (_: string) => undefined);
let installedHandler: ((details: { url: string }) => { action: 'allow' | 'deny' }) | null =
null;
@@ -324,8 +324,8 @@ describe('attachAssetSafetyNet — setWindowOpenHandler', () => {
describe('attachAssetSafetyNet — will-navigate', () => {
test('asset URL navigation → preventDefault + openAsset fires', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
@@ -341,7 +341,7 @@ describe('attachAssetSafetyNet — will-navigate', () => {
attachAssetSafetyNet(webContents, { openAsset, openExternal, editorOrigin: ORIGIN });
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
installedHandler?.({ preventDefault }, 'http://localhost:5173/notes/meeting.pdf');
expect(preventDefault).toHaveBeenCalledTimes(1);
await Promise.resolve();
@@ -351,8 +351,8 @@ describe('attachAssetSafetyNet — will-navigate', () => {
});
test('same-origin navigation (Vite reload, app bundle) → no preventDefault, no delegation', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
@@ -368,7 +368,7 @@ describe('attachAssetSafetyNet — will-navigate', () => {
attachAssetSafetyNet(webContents, { openAsset, openExternal, editorOrigin: ORIGIN });
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
installedHandler?.({ preventDefault }, 'http://localhost:5173/');
expect(preventDefault).not.toHaveBeenCalled();
await Promise.resolve();
@@ -379,8 +379,8 @@ describe('attachAssetSafetyNet — will-navigate', () => {
test('same-renderer-origin navigation (distinct from editorOrigin) → no preventDefault, no delegation', async () => {
// Renderer origin (:5173) differs from editorOrigin (api port) in dev; a
// top-level navigate to a :5173 route must stay in-app, not openExternal.
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
@@ -401,7 +401,7 @@ describe('attachAssetSafetyNet — will-navigate', () => {
editorOrigin: 'http://localhost:8765',
});
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
installedHandler?.({ preventDefault }, 'http://localhost:5173/#/people/ray-zaragoza');
expect(preventDefault).not.toHaveBeenCalled();
await Promise.resolve();
@@ -416,8 +416,8 @@ describe('attachAssetSafetyNet — will-navigate', () => {
// same-origin Electron behavior; deferring to Electron's own failure mode
// is the conservative choice. This test guards against a future refactor
// that removes the try/catch or flips the fallback.
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
@@ -433,7 +433,7 @@ describe('attachAssetSafetyNet — will-navigate', () => {
attachAssetSafetyNet(webContents, { openAsset, openExternal, editorOrigin: ORIGIN });
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
expect(() => installedHandler?.({ preventDefault }, 'not a valid url')).not.toThrow();
expect(preventDefault).not.toHaveBeenCalled();
await Promise.resolve();
@@ -442,8 +442,8 @@ describe('attachAssetSafetyNet — will-navigate', () => {
});
test('cross-origin navigation (pasted https link) → preventDefault + openExternal fires', async () => {
- const openAsset = mock(async (_: string) => ({ ok: true }) as const);
- const openExternal = mock(noopOpenExternal);
+ const openAsset = vi.fn(async (_: string) => ({ ok: true }) as const);
+ const openExternal = vi.fn(noopOpenExternal);
let installedHandler: ((event: { preventDefault: () => void }, url: string) => void) | null =
null;
@@ -459,7 +459,7 @@ describe('attachAssetSafetyNet — will-navigate', () => {
attachAssetSafetyNet(webContents, { openAsset, openExternal, editorOrigin: ORIGIN });
- const preventDefault = mock(() => {});
+ const preventDefault = vi.fn(() => {});
installedHandler?.({ preventDefault }, 'https://example.com/page');
expect(preventDefault).toHaveBeenCalledTimes(1);
await Promise.resolve();
diff --git a/packages/desktop/tests/main/bootstrap.test.ts b/packages/desktop/tests/main/bootstrap.test.ts
index 2185534b7..b67f637fa 100644
--- a/packages/desktop/tests/main/bootstrap.test.ts
+++ b/packages/desktop/tests/main/bootstrap.test.ts
@@ -12,7 +12,7 @@
* by call-order tracking against the injected deps.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { runBootstrap } from '../../src/main/bootstrap.ts';
import { emptyState } from '../../src/main/state-store.ts';
import type { OkThemeSource } from '../../src/shared/bridge-contract.ts';
diff --git a/packages/desktop/tests/main/bundle-replace-detector.test.ts b/packages/desktop/tests/main/bundle-replace-detector.test.ts
index 9a050d10f..a36ddb311 100644
--- a/packages/desktop/tests/main/bundle-replace-detector.test.ts
+++ b/packages/desktop/tests/main/bundle-replace-detector.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
type BundleReplaceDetectorInput,
detectBundleReplace,
@@ -16,7 +16,7 @@ import {
*/
afterEach(() => {
- mock.restore();
+ vi.restoreAllMocks();
});
function makeInput(
@@ -145,14 +145,14 @@ describe('extractShortVersionFromPlist', () => {
});
interface WatcherFixtures {
- showMessageBox: ReturnType<typeof mock>;
- relaunch: ReturnType<typeof mock>;
- quit: ReturnType<typeof mock>;
- setInterval: ReturnType<typeof mock>;
- clearInterval: ReturnType<typeof mock>;
+ showMessageBox: ReturnType<typeof vi.fn>;
+ relaunch: ReturnType<typeof vi.fn>;
+ quit: ReturnType<typeof vi.fn>;
+ setInterval: ReturnType<typeof vi.fn>;
+ clearInterval: ReturnType<typeof vi.fn>;
logger: {
- info: ReturnType<typeof mock>;
- warn: ReturnType<typeof mock>;
+ info: ReturnType<typeof vi.fn>;
+ warn: ReturnType<typeof vi.fn>;
};
/** The callback registered with setInterval — fire to simulate a tick. */
tickCallback: (() => void) | null;
@@ -162,19 +162,19 @@ interface WatcherFixtures {
function makeFixtures(): WatcherFixtures {
const fixtures: WatcherFixtures = {
- showMessageBox: mock(() => Promise.resolve({ response: 0, checkboxChecked: false })),
- relaunch: mock(() => {}),
- quit: mock(() => {}),
- setInterval: mock(() => Symbol('interval')),
- clearInterval: mock(() => {}),
+ showMessageBox: vi.fn(() => Promise.resolve({ response: 0, checkboxChecked: false })),
+ relaunch: vi.fn(() => {}),
+ quit: vi.fn(() => {}),
+ setInterval: vi.fn(() => Symbol('interval')),
+ clearInterval: vi.fn(() => {}),
logger: {
- info: mock(() => {}),
- warn: mock(() => {}),
+ info: vi.fn(() => {}),
+ warn: vi.fn(() => {}),
},
tickCallback: null,
intervalHandle: null,
};
- fixtures.setInterval = mock((cb: () => void, _ms: number) => {
+ fixtures.setInterval = vi.fn((cb: () => void, _ms: number) => {
fixtures.tickCallback = cb;
fixtures.intervalHandle = Symbol('interval');
return fixtures.intervalHandle as unknown as ReturnType<typeof setInterval>;
@@ -204,7 +204,7 @@ describe('startBundleReplaceWatcher', () => {
test('fires the prompt exactly once when an upgrade is detected', async () => {
const fx = makeFixtures();
- fx.showMessageBox = mock(() => Promise.resolve({ response: 1, checkboxChecked: false })); // user clicks "Later"
+ fx.showMessageBox = vi.fn(() => Promise.resolve({ response: 1, checkboxChecked: false })); // user clicks "Later"
startBundleReplaceWatcher({
infoPlistPath: '/x/Info.plist',
getCurrentVersion: () => '0.4.1',
@@ -236,7 +236,7 @@ describe('startBundleReplaceWatcher', () => {
// `.then` chain would silently break this test.
const fx = makeFixtures();
let resolveDialog: ((v: { response: number; checkboxChecked: boolean }) => void) | null = null;
- fx.showMessageBox = mock(
+ fx.showMessageBox = vi.fn(
() =>
new Promise<{ response: number; checkboxChecked: boolean }>((r) => {
resolveDialog = r;
@@ -273,7 +273,7 @@ describe('startBundleReplaceWatcher', () => {
// failures (window destroyed mid-show, framework error) must not
// permanently de-arm the session-level prompt.
const fx = makeFixtures();
- fx.showMessageBox = mock(() => Promise.reject(new Error('dialog destroyed')));
+ fx.showMessageBox = vi.fn(() => Promise.reject(new Error('dialog destroyed')));
startBundleReplaceWatcher({
infoPlistPath: '/x/Info.plist',
getCurrentVersion: () => '0.4.1',
@@ -308,7 +308,7 @@ describe('startBundleReplaceWatcher', () => {
// context.
const fx = makeFixtures();
let rejectDialog: ((err: Error) => void) | null = null;
- fx.showMessageBox = mock(
+ fx.showMessageBox = vi.fn(
() =>
new Promise<{ response: number; checkboxChecked: boolean }>((_, r) => {
rejectDialog = r;
@@ -350,7 +350,7 @@ describe('startBundleReplaceWatcher', () => {
// relaunch+quit on top of the already-in-flight shutdown.
const fx = makeFixtures();
let resolveDialog: ((v: { response: number; checkboxChecked: boolean }) => void) | null = null;
- fx.showMessageBox = mock(
+ fx.showMessageBox = vi.fn(
() =>
new Promise<{ response: number; checkboxChecked: boolean }>((r) => {
resolveDialog = r;
@@ -387,12 +387,12 @@ describe('startBundleReplaceWatcher', () => {
// the next quit. Reversing the two adjacent calls means the app quits
// without relaunching.
const fx = makeFixtures();
- fx.showMessageBox = mock(() => Promise.resolve({ response: 0, checkboxChecked: false }));
+ fx.showMessageBox = vi.fn(() => Promise.resolve({ response: 0, checkboxChecked: false }));
const callOrder: string[] = [];
- fx.relaunch = mock(() => {
+ fx.relaunch = vi.fn(() => {
callOrder.push('relaunch');
});
- fx.quit = mock(() => {
+ fx.quit = vi.fn(() => {
callOrder.push('quit');
});
startBundleReplaceWatcher({
@@ -417,7 +417,7 @@ describe('startBundleReplaceWatcher', () => {
test('"Later" (response 1) leaves the app running and stops the watcher', async () => {
const fx = makeFixtures();
- fx.showMessageBox = mock(() => Promise.resolve({ response: 1, checkboxChecked: false }));
+ fx.showMessageBox = vi.fn(() => Promise.resolve({ response: 1, checkboxChecked: false }));
const handle = startBundleReplaceWatcher({
infoPlistPath: '/x/Info.plist',
getCurrentVersion: () => '0.4.1',
@@ -442,7 +442,7 @@ describe('startBundleReplaceWatcher', () => {
test('errors in statSync are swallowed (logged at warn, no crash)', () => {
const fx = makeFixtures();
- const throwingStat = mock(() => {
+ const throwingStat = vi.fn(() => {
throw new Error('EACCES');
});
startBundleReplaceWatcher({
diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.ts
index 82b333f98..e409d4bb8 100644
--- a/packages/desktop/tests/main/claude-readiness.test.ts
+++ b/packages/desktop/tests/main/claude-readiness.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { TERMINAL_CLI_IDS, type TerminalCli } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
CLAUDE_PROBE_ARGS,
cliProbeArgs,
diff --git a/packages/desktop/tests/main/desktop-uninstall.test.ts b/packages/desktop/tests/main/desktop-uninstall.test.ts
index 56700e9e4..e3c8a83ac 100644
--- a/packages/desktop/tests/main/desktop-uninstall.test.ts
+++ b/packages/desktop/tests/main/desktop-uninstall.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, mock, test } from 'bun:test';
import { join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
import {
buildDesktopUninstallCleanupScript,
buildDesktopUninstallNoticeHtml,
@@ -298,11 +298,11 @@ describe('desktop self-uninstall helpers', () => {
test('runDesktopUninstallCleanup spawns an attached shell and resolves on close', async () => {
const listeners = new Map<string, (...args: unknown[]) => void>();
const child = {
- once: mock((event: string, listener: (...args: unknown[]) => void) => {
+ once: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
};
- const spawn = mock(() => child);
+ const spawn = vi.fn(() => child);
const resultPromise = runDesktopUninstallCleanup(
{
cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',
diff --git a/packages/desktop/tests/main/embed-referer.test.ts b/packages/desktop/tests/main/embed-referer.test.ts
index ea8138bc8..4d920c43f 100644
--- a/packages/desktop/tests/main/embed-referer.test.ts
+++ b/packages/desktop/tests/main/embed-referer.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
EMBED_HOST_PATTERNS,
EMBED_REFERER,
diff --git a/packages/desktop/tests/main/install-skill-ipc.test.ts b/packages/desktop/tests/main/install-skill-ipc.test.ts
index a5fef9bab..eeefa0d25 100644
--- a/packages/desktop/tests/main/install-skill-ipc.test.ts
+++ b/packages/desktop/tests/main/install-skill-ipc.test.ts
@@ -7,11 +7,11 @@
* Spec: (two write sites).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { readTargetVersion, writeTargetVersion } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { handleBuildAndOpen } from '../../src/main/ipc/install-skill.ts';
interface FakeApp {
@@ -19,7 +19,7 @@ interface FakeApp {
}
interface FakeShell {
- openPath: ReturnType<typeof mock>;
+ openPath: ReturnType<typeof vi.fn>;
}
function makeFakeApp(downloadsDir: string): FakeApp {
@@ -35,7 +35,7 @@ function makeFakeApp(downloadsDir: string): FakeApp {
function makeFakeShell(openResult: string | Error = ''): FakeShell {
return {
- openPath: mock(async () => {
+ openPath: vi.fn(async () => {
if (openResult instanceof Error) throw openResult;
return openResult;
}),
diff --git a/packages/desktop/tests/main/ipc-handlers.test.ts b/packages/desktop/tests/main/ipc-handlers.test.ts
index 98f15eb55..29cb7bac9 100644
--- a/packages/desktop/tests/main/ipc-handlers.test.ts
+++ b/packages/desktop/tests/main/ipc-handlers.test.ts
@@ -7,10 +7,10 @@
* smoke-tested by the integration surface (contract-equality scan).
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import {
detectProtocol,
extractTrashDetail,
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 102dc2c0a..1d6bf3fc3 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -12,8 +12,9 @@
* regression detection on the template shape: if a future edit breaks the
* top-10 clamp or the isMac branch, these tests fail with a precise diff.
*/
-import { describe, expect, mock, test } from 'bun:test';
+
import type { MenuItemConstructorOptions } from 'electron';
+import { describe, expect, test, vi } from 'vitest';
import { buildMenuTemplate, type MenuDeps } from '../../src/main/menu.ts';
type RecentRow = { path: string; name: string };
@@ -23,11 +24,11 @@ function makeDeps(overrides: Partial<MenuDeps> = {}): MenuDeps {
appName: 'OpenKnowledge',
showDevToolsMenu: true,
dialog: {} as MenuDeps['dialog'],
- openNavigator: mock(() => {}),
- openProject: mock(() => Promise.resolve()),
- getRecentProjects: mock(() => []),
- clearRecentProjects: mock(() => {}),
- openExternalUrl: mock(() => {}),
+ openNavigator: vi.fn(() => {}),
+ openProject: vi.fn(() => Promise.resolve()),
+ getRecentProjects: vi.fn(() => []),
+ clearRecentProjects: vi.fn(() => {}),
+ openExternalUrl: vi.fn(() => {}),
...overrides,
};
}
@@ -98,7 +99,7 @@ describe('buildMenuTemplate', () => {
});
test('recent-row click dispatches deps.openProject(path, "recents")', () => {
- const openProject = mock(() => Promise.resolve());
+ const openProject = vi.fn(() => Promise.resolve());
const deps = makeDeps({
getRecentProjects: () => [{ path: '/tmp/foo', name: 'foo' }],
openProject,
@@ -113,8 +114,8 @@ describe('buildMenuTemplate', () => {
});
test('File → Open folder click dispatches deps.openProject(path, "pick-existing")', async () => {
- const openProject = mock(() => Promise.resolve());
- const showOpenDialog = mock(() =>
+ const openProject = vi.fn(() => Promise.resolve());
+ const showOpenDialog = vi.fn(() =>
Promise.resolve({ canceled: false, filePaths: ['/tmp/picked'] }),
);
const deps = makeDeps({
@@ -129,7 +130,7 @@ describe('buildMenuTemplate', () => {
});
test('Clear menu click dispatches deps.clearRecentProjects()', () => {
- const clearRecentProjects = mock(() => {});
+ const clearRecentProjects = vi.fn(() => {});
const deps = makeDeps({
getRecentProjects: () => [{ path: '/tmp/foo', name: 'foo' }],
clearRecentProjects,
@@ -142,7 +143,7 @@ describe('buildMenuTemplate', () => {
});
test('Switch project click dispatches deps.openNavigator()', () => {
- const openNavigator = mock(() => {});
+ const openNavigator = vi.fn(() => {});
const deps = makeDeps({ openNavigator });
const template = buildMenuTemplate(deps);
const switchProject = findByLabel(template, 'Switch project…');
@@ -174,7 +175,7 @@ describe('buildMenuTemplate', () => {
});
test('New worktree… click dispatches deps.onNewWorktree()', () => {
- const onNewWorktree = mock(() => {});
+ const onNewWorktree = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onNewWorktree }));
const item = findByLabel(template, 'New worktree…');
expect(item?.enabled).toBe(true);
@@ -183,7 +184,7 @@ describe('buildMenuTemplate', () => {
});
test('Switch worktree… click dispatches deps.onSwitchWorktree()', () => {
- const onSwitchWorktree = mock(() => {});
+ const onSwitchWorktree = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onSwitchWorktree }));
const item = findByLabel(template, 'Switch worktree…');
expect(item?.enabled).toBe(true);
@@ -251,7 +252,7 @@ describe('buildMenuTemplate', () => {
const isMac = process.platform === 'darwin';
test('Settings… is rendered with the CmdOrCtrl+, accelerator', () => {
- const deps = makeDeps({ openSettings: mock(() => {}) });
+ const deps = makeDeps({ openSettings: vi.fn(() => {}) });
const template = buildMenuTemplate(deps);
const settings = findByLabel(template, 'Settings…');
expect(settings).toBeDefined();
@@ -259,7 +260,7 @@ describe('buildMenuTemplate', () => {
});
test('Settings… click dispatches deps.openSettings()', () => {
- const openSettings = mock(() => {});
+ const openSettings = vi.fn(() => {});
const deps = makeDeps({ openSettings });
const template = buildMenuTemplate(deps);
const settings = findByLabel(template, 'Settings…');
@@ -278,7 +279,7 @@ describe('buildMenuTemplate', () => {
if (isMac) {
test('macOS: Settings… lives in the App menu, between About and the services separator', () => {
- const deps = makeDeps({ openSettings: mock(() => {}) });
+ const deps = makeDeps({ openSettings: vi.fn(() => {}) });
const template = buildMenuTemplate(deps);
// The first top-level submenu on macOS is the App menu (label === appName).
const appMenu = template.find((t) => t.label === deps.appName);
@@ -296,7 +297,7 @@ describe('buildMenuTemplate', () => {
});
test('macOS: Settings… does NOT appear in the File submenu', () => {
- const deps = makeDeps({ openSettings: mock(() => {}) });
+ const deps = makeDeps({ openSettings: vi.fn(() => {}) });
const template = buildMenuTemplate(deps);
const fileMenu = template.find((t) => t.label === 'File');
const sub = fileMenu?.submenu as MenuItemConstructorOptions[] | undefined;
@@ -308,7 +309,7 @@ describe('buildMenuTemplate', () => {
});
} else {
test('Windows/Linux: Settings… lives in the File submenu, above the trailing close/quit row', () => {
- const deps = makeDeps({ openSettings: mock(() => {}) });
+ const deps = makeDeps({ openSettings: vi.fn(() => {}) });
const template = buildMenuTemplate(deps);
const fileMenu = template.find((t) => t.label === 'File');
const sub = fileMenu?.submenu as MenuItemConstructorOptions[] | undefined;
@@ -332,8 +333,8 @@ describe('buildMenuTemplate', () => {
if (isMac) {
test('macOS: appears in App menu between About and Settings…', () => {
- const onCheckForUpdates = mock(() => {});
- const deps = makeDeps({ onCheckForUpdates, openSettings: mock(() => {}) });
+ const onCheckForUpdates = vi.fn(() => {});
+ const deps = makeDeps({ onCheckForUpdates, openSettings: vi.fn(() => {}) });
const template = buildMenuTemplate(deps);
const appMenu = template.find((t) => t.label === deps.appName);
const sub = appMenu?.submenu as MenuItemConstructorOptions[] | undefined;
@@ -350,7 +351,7 @@ describe('buildMenuTemplate', () => {
// De-duplicated: the Apple-HIG App-menu placement is the single macOS
// entry (mirroring the Settings platform-XOR). The Help entry is
// non-macOS only, so macOS must not render it twice.
- const onCheckForUpdates = mock(() => {});
+ const onCheckForUpdates = vi.fn(() => {});
const deps = makeDeps({ onCheckForUpdates });
const template = buildMenuTemplate(deps);
const helpMenu = template.find((t) => t.label === 'Help');
@@ -360,7 +361,7 @@ describe('buildMenuTemplate', () => {
});
} else {
test('non-mac: appears in Help menu only (no App menu on these platforms)', () => {
- const onCheckForUpdates = mock(() => {});
+ const onCheckForUpdates = vi.fn(() => {});
const deps = makeDeps({ onCheckForUpdates });
const template = buildMenuTemplate(deps);
const helpMenu = template.find((t) => t.label === 'Help');
@@ -371,7 +372,7 @@ describe('buildMenuTemplate', () => {
}
test('click dispatches deps.onCheckForUpdates()', () => {
- const onCheckForUpdates = mock(() => {});
+ const onCheckForUpdates = vi.fn(() => {});
const deps = makeDeps({ onCheckForUpdates });
const template = buildMenuTemplate(deps);
const item = findByLabel(template, 'Check for updates…');
@@ -399,7 +400,7 @@ describe('buildMenuTemplate', () => {
});
test('click dispatches deps.onReportBug()', () => {
- const onReportBug = mock(() => {});
+ const onReportBug = vi.fn(() => {});
const deps = makeDeps({ onReportBug });
const template = buildMenuTemplate(deps);
const item = findByLabel(template, 'Report a bug…');
@@ -423,8 +424,8 @@ describe('buildMenuTemplate', () => {
test('click dispatches deps.onSendFeedback()', () => {
// The parity ratchet asserts the binding EXISTS; only this pins that it
// calls the right dep — a copy-paste to onReportBug would pass the ratchet.
- const onSendFeedback = mock(() => {});
- const onReportBug = mock(() => {});
+ const onSendFeedback = vi.fn(() => {});
+ const onReportBug = vi.fn(() => {});
const deps = makeDeps({ onSendFeedback, onReportBug });
const template = buildMenuTemplate(deps);
const item = findByLabel(template, 'Send feedback…');
@@ -445,7 +446,7 @@ describe('buildMenuTemplate', () => {
if (process.platform === 'darwin') {
test('macOS: appears in the App menu before Quit when wired', () => {
- const onUninstall = mock(() => {});
+ const onUninstall = vi.fn(() => {});
const deps = makeDeps({ onUninstall });
const template = buildMenuTemplate(deps);
const appMenu = template.find((t) => t.label === deps.appName);
@@ -459,7 +460,7 @@ describe('buildMenuTemplate', () => {
}
test('click dispatches deps.onUninstall()', () => {
- const onUninstall = mock(() => {});
+ const onUninstall = vi.fn(() => {});
const item = findByLabel(
buildMenuTemplate(makeDeps({ onUninstall })),
'Uninstall OpenKnowledge…',
@@ -510,7 +511,7 @@ describe('buildMenuTemplate', () => {
test('Close tab click dispatches deps.onCloseActiveTabOrWindow on macOS', () => {
if (process.platform !== 'darwin') return;
- const onCloseActiveTabOrWindow = mock(() => {});
+ const onCloseActiveTabOrWindow = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onCloseActiveTabOrWindow }));
const closeTab = findByLabel(template, 'Close tab');
expect(closeTab?.enabled).toBe(true);
@@ -521,28 +522,28 @@ describe('buildMenuTemplate', () => {
describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR19)', () => {
test('New file renders with Cmd+N accelerator (FR19 — was unbound today)', () => {
- const template = buildMenuTemplate(makeDeps({ onNewFile: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onNewFile: vi.fn(() => {}) }));
const newFile = findByLabel(template, 'New file');
expect(newFile).toBeDefined();
expect(newFile?.accelerator).toBe('CmdOrCtrl+N');
});
test('New folder renders with Cmd+Shift+N accelerator (FR19 — rebound from Switch project)', () => {
- const template = buildMenuTemplate(makeDeps({ onNewFolder: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onNewFolder: vi.fn(() => {}) }));
const newFolder = findByLabel(template, 'New folder');
expect(newFolder).toBeDefined();
expect(newFolder?.accelerator).toBe('CmdOrCtrl+Shift+N');
});
test('Move to Trash renders with Cmd+Delete accelerator (FR19 — matches Finder + VSCode)', () => {
- const template = buildMenuTemplate(makeDeps({ onMoveToTrash: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onMoveToTrash: vi.fn(() => {}) }));
const moveToTrash = findByLabel(template, 'Move to Trash');
expect(moveToTrash).toBeDefined();
expect(moveToTrash?.accelerator).toBe('CmdOrCtrl+Delete');
});
test('Duplicate renders with Cmd+D accelerator', () => {
- const template = buildMenuTemplate(makeDeps({ onDuplicate: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onDuplicate: vi.fn(() => {}) }));
const duplicate = findByLabel(template, 'Duplicate');
expect(duplicate).toBeDefined();
expect(duplicate?.accelerator).toBe('CmdOrCtrl+D');
@@ -552,9 +553,9 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: null },
- onRename: mock(() => {}),
- onDuplicate: mock(() => {}),
- onMoveToTrash: mock(() => {}),
+ onRename: vi.fn(() => {}),
+ onDuplicate: vi.fn(() => {}),
+ onMoveToTrash: vi.fn(() => {}),
}),
);
expect(findByLabel(template, 'Rename')?.enabled).toBe(false);
@@ -566,9 +567,9 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: 'doc', identifier: 'notes/today' },
- onRename: mock(() => {}),
- onDuplicate: mock(() => {}),
- onMoveToTrash: mock(() => {}),
+ onRename: vi.fn(() => {}),
+ onDuplicate: vi.fn(() => {}),
+ onMoveToTrash: vi.fn(() => {}),
}),
);
expect(findByLabel(template, 'Rename')?.enabled).toBe(true);
@@ -580,9 +581,9 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: 'folder', identifier: 'specs/2026' },
- onRename: mock(() => {}),
- onDuplicate: mock(() => {}),
- onMoveToTrash: mock(() => {}),
+ onRename: vi.fn(() => {}),
+ onDuplicate: vi.fn(() => {}),
+ onMoveToTrash: vi.fn(() => {}),
}),
);
expect(findByLabel(template, 'Rename')?.enabled).toBe(true);
@@ -594,10 +595,10 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: 'asset', identifier: 'media/diagram.png' },
- onRename: mock(() => {}),
- onDuplicate: mock(() => {}),
- onMoveToTrash: mock(() => {}),
- onSendToAi: mock(() => {}),
+ onRename: vi.fn(() => {}),
+ onDuplicate: vi.fn(() => {}),
+ onMoveToTrash: vi.fn(() => {}),
+ onSendToAi: vi.fn(() => {}),
}),
);
expect(findByLabel(template, 'Rename')?.enabled).toBe(true);
@@ -607,7 +608,7 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
});
test('Rename DISABLED when activeTarget is undefined (deps missing — unit-test default)', () => {
- const template = buildMenuTemplate(makeDeps({ onRename: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onRename: vi.fn(() => {}) }));
expect(findByLabel(template, 'Rename')?.enabled).toBe(false);
});
@@ -617,13 +618,13 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: null },
- onNewFile: mock(() => {}),
- onNewFolder: mock(() => {}),
- onNewFromTemplate: mock(() => {}),
- onRevealInFinder: mock(() => {}),
- onSendToAi: mock(() => {}),
- onCopyFullPath: mock(() => {}),
- onCopyRelativePath: mock(() => {}),
+ onNewFile: vi.fn(() => {}),
+ onNewFolder: vi.fn(() => {}),
+ onNewFromTemplate: vi.fn(() => {}),
+ onRevealInFinder: vi.fn(() => {}),
+ onSendToAi: vi.fn(() => {}),
+ onCopyFullPath: vi.fn(() => {}),
+ onCopyRelativePath: vi.fn(() => {}),
}),
);
expect(findByLabel(template, 'New file')?.enabled).toBe(true);
@@ -651,8 +652,8 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
test('Copy path submenu renders Full path + Relative path (FR9 parity with sidebar)', () => {
const template = buildMenuTemplate(
makeDeps({
- onCopyFullPath: mock(() => {}),
- onCopyRelativePath: mock(() => {}),
+ onCopyFullPath: vi.fn(() => {}),
+ onCopyRelativePath: vi.fn(() => {}),
}),
);
const copyPath = findByLabel(template, 'Copy path');
@@ -663,10 +664,10 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
});
test('click handlers dispatch to deps (e.g. New file → onNewFile)', () => {
- const onNewFile = mock(() => {});
- const onDuplicate = mock(() => {});
- const onMoveToTrash = mock(() => {});
- const onCopyFullPath = mock(() => {});
+ const onNewFile = vi.fn(() => {});
+ const onDuplicate = vi.fn(() => {});
+ const onMoveToTrash = vi.fn(() => {});
+ const onCopyFullPath = vi.fn(() => {});
const template = buildMenuTemplate(
makeDeps({
activeTarget: { kind: 'doc', identifier: 'a' },
@@ -699,7 +700,7 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
describe('buildMenuTemplate — New project… menu item', () => {
test('renders enabled when onNewProject dep is provided', () => {
- const template = buildMenuTemplate(makeDeps({ onNewProject: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onNewProject: vi.fn(() => {}) }));
const item = findByLabel(template, 'New project…');
expect(item).toBeDefined();
expect(item?.enabled).toBe(true);
@@ -714,13 +715,13 @@ describe('buildMenuTemplate — New project… menu item', () => {
// Unlike Rename / Duplicate / Move to Trash, creating a project does not
// depend on the current target — it must stay enabled in project scope.
const template = buildMenuTemplate(
- makeDeps({ activeTarget: { kind: null }, onNewProject: mock(() => {}) }),
+ makeDeps({ activeTarget: { kind: null }, onNewProject: vi.fn(() => {}) }),
);
expect(findByLabel(template, 'New project…')?.enabled).toBe(true);
});
test('click dispatches deps.onNewProject()', () => {
- const onNewProject = mock(() => {});
+ const onNewProject = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onNewProject }));
const item = findByLabel(template, 'New project…');
(item?.click as (() => void) | undefined)?.();
@@ -738,7 +739,7 @@ describe('buildMenuTemplate — New project… menu item', () => {
// actions in the same order: Recent project, New project, Switch project,
// Open folder — placed directly under the New… items, above the
// item-management actions (Duplicate / Rename / Move to Trash).
- const template = buildMenuTemplate(makeDeps({ onNewProject: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onNewProject: vi.fn(() => {}) }));
const fileMenu = template.find((t) => t.label === 'File');
const sub = fileMenu?.submenu as MenuItemConstructorOptions[] | undefined;
if (!sub) throw new Error('File submenu missing');
@@ -768,7 +769,7 @@ describe('buildMenuTemplate — New project… menu item', () => {
// The Navigator opener was once mislabeled "New Project…" (title case)
// before it became "Switch project…". The create action is now "New
// project…" (sentence case); this guards against the retired title-case label.
- const template = buildMenuTemplate(makeDeps({ onNewProject: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onNewProject: vi.fn(() => {}) }));
expect(findByLabel(template, 'New Project…')).toBeUndefined();
expect(findByLabel(template, 'New project…')).toBeDefined();
});
@@ -777,7 +778,7 @@ describe('buildMenuTemplate — New project… menu item', () => {
describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expand/collapse', () => {
test('Show hidden files renders as a checkbox-type item', () => {
const template = buildMenuTemplate(
- makeDeps({ onToggleShowHiddenFiles: mock(() => {}), showHiddenFilesChecked: false }),
+ makeDeps({ onToggleShowHiddenFiles: vi.fn(() => {}), showHiddenFilesChecked: false }),
);
const item = findByLabel(template, 'Show hidden files');
expect(item).toBeDefined();
@@ -792,7 +793,7 @@ describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expan
// toggle for hidden files. A future refactor that drops the accelerator
// would silently break that affordance — no other surface would catch it.
const template = buildMenuTemplate(
- makeDeps({ onToggleShowHiddenFiles: mock(() => {}), showHiddenFilesChecked: false }),
+ makeDeps({ onToggleShowHiddenFiles: vi.fn(() => {}), showHiddenFilesChecked: false }),
);
expect(findByLabel(template, 'Show hidden files')?.accelerator).toBe('CmdOrCtrl+Shift+.');
});
@@ -804,7 +805,7 @@ describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expan
test('Expand all / Collapse all render with visible=true by default', () => {
const template = buildMenuTemplate(
- makeDeps({ onExpandAll: mock(() => {}), onCollapseAll: mock(() => {}) }),
+ makeDeps({ onExpandAll: vi.fn(() => {}), onCollapseAll: vi.fn(() => {}) }),
);
expect(findByLabel(template, 'Expand all')?.visible).toBe(true);
expect(findByLabel(template, 'Collapse all')?.visible).toBe(true);
@@ -812,22 +813,22 @@ describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expan
test('Expand all HIDDEN when canExpandAll === false (smart-hide per D15)', () => {
const template = buildMenuTemplate(
- makeDeps({ onExpandAll: mock(() => {}), canExpandAll: false }),
+ makeDeps({ onExpandAll: vi.fn(() => {}), canExpandAll: false }),
);
expect(findByLabel(template, 'Expand all')?.visible).toBe(false);
});
test('Collapse all HIDDEN when canCollapseAll === false', () => {
const template = buildMenuTemplate(
- makeDeps({ onCollapseAll: mock(() => {}), canCollapseAll: false }),
+ makeDeps({ onCollapseAll: vi.fn(() => {}), canCollapseAll: false }),
);
expect(findByLabel(template, 'Collapse all')?.visible).toBe(false);
});
test('View menu click handlers dispatch to deps', () => {
- const onToggleShowHiddenFiles = mock(() => {});
- const onExpandAll = mock(() => {});
- const onCollapseAll = mock(() => {});
+ const onToggleShowHiddenFiles = vi.fn(() => {});
+ const onExpandAll = vi.fn(() => {});
+ const onCollapseAll = vi.fn(() => {});
const template = buildMenuTemplate(
makeDeps({
onToggleShowHiddenFiles,
@@ -858,8 +859,8 @@ describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expan
test('New View menu items appear BEFORE Zoom items (FR17 / D38 placement)', () => {
const template = buildMenuTemplate(
makeDeps({
- onToggleShowHiddenFiles: mock(() => {}),
- onExpandAll: mock(() => {}),
+ onToggleShowHiddenFiles: vi.fn(() => {}),
+ onExpandAll: vi.fn(() => {}),
}),
);
const view = findByLabel(template, 'View');
@@ -877,7 +878,7 @@ describe('buildMenuTemplate — View menu visibility toggles + tree-scoped expan
describe('buildMenuTemplate — View → Show .ok folders', () => {
test('renders as a checkbox, unchecked by default', () => {
- const template = buildMenuTemplate(makeDeps({ onToggleShowOkFolders: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onToggleShowOkFolders: vi.fn(() => {}) }));
const item = findByLabel(template, 'Show .ok folders');
expect(item).toBeDefined();
expect(item?.type).toBe('checkbox');
@@ -887,7 +888,7 @@ describe('buildMenuTemplate — View → Show .ok folders', () => {
test('reflects showOkFoldersChecked', () => {
const template = buildMenuTemplate(
- makeDeps({ onToggleShowOkFolders: mock(() => {}), showOkFoldersChecked: true }),
+ makeDeps({ onToggleShowOkFolders: vi.fn(() => {}), showOkFoldersChecked: true }),
);
expect(findByLabel(template, 'Show .ok folders')?.checked).toBe(true);
});
@@ -911,7 +912,7 @@ describe('buildMenuTemplate — View → Show .ok folders', () => {
});
test('binds no keyboard accelerator and click dispatches the toggle dep', () => {
- const onToggleShowOkFolders = mock(() => {});
+ const onToggleShowOkFolders = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onToggleShowOkFolders }));
const item = findByLabel(template, 'Show .ok folders');
expect(item?.accelerator).toBeUndefined();
@@ -929,7 +930,9 @@ describe('buildMenuTemplate — View → Show .ok folders', () => {
describe('buildMenuTemplate — View → Show only markdown files / Show skills section', () => {
test('Show only markdown files renders as a checkbox, unchecked by default', () => {
- const template = buildMenuTemplate(makeDeps({ onToggleShowOnlyMarkdownFiles: mock(() => {}) }));
+ const template = buildMenuTemplate(
+ makeDeps({ onToggleShowOnlyMarkdownFiles: vi.fn(() => {}) }),
+ );
const item = findByLabel(template, 'Show only markdown files');
expect(item).toBeDefined();
expect(item?.type).toBe('checkbox');
@@ -940,7 +943,7 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
test('Show only markdown files reflects showOnlyMarkdownFilesChecked', () => {
const template = buildMenuTemplate(
makeDeps({
- onToggleShowOnlyMarkdownFiles: mock(() => {}),
+ onToggleShowOnlyMarkdownFiles: vi.fn(() => {}),
showOnlyMarkdownFilesChecked: true,
}),
);
@@ -951,7 +954,7 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
// The unwired-checked default must match the renderer's resolved config
// default (showSkillsSection ?? true) so the menu reads correctly before
// the first renderer push lands — the inverse of Show hidden files.
- const template = buildMenuTemplate(makeDeps({ onToggleShowSkillsSection: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onToggleShowSkillsSection: vi.fn(() => {}) }));
const item = findByLabel(template, 'Show skills section');
expect(item).toBeDefined();
expect(item?.type).toBe('checkbox');
@@ -961,7 +964,7 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
test('Show skills section reflects showSkillsSectionChecked', () => {
const template = buildMenuTemplate(
- makeDeps({ onToggleShowSkillsSection: mock(() => {}), showSkillsSectionChecked: false }),
+ makeDeps({ onToggleShowSkillsSection: vi.fn(() => {}), showSkillsSectionChecked: false }),
);
expect(findByLabel(template, 'Show skills section')?.checked).toBe(false);
});
@@ -975,8 +978,8 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
test('neither binds a keyboard accelerator (only Show hidden files carries Cmd+Shift+.)', () => {
const template = buildMenuTemplate(
makeDeps({
- onToggleShowOnlyMarkdownFiles: mock(() => {}),
- onToggleShowSkillsSection: mock(() => {}),
+ onToggleShowOnlyMarkdownFiles: vi.fn(() => {}),
+ onToggleShowSkillsSection: vi.fn(() => {}),
}),
);
expect(findByLabel(template, 'Show only markdown files')?.accelerator).toBeUndefined();
@@ -984,8 +987,8 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
});
test('clicks dispatch their toggle deps', () => {
- const onToggleShowOnlyMarkdownFiles = mock(() => {});
- const onToggleShowSkillsSection = mock(() => {});
+ const onToggleShowOnlyMarkdownFiles = vi.fn(() => {});
+ const onToggleShowSkillsSection = vi.fn(() => {});
const template = buildMenuTemplate(
makeDeps({ onToggleShowOnlyMarkdownFiles, onToggleShowSkillsSection }),
);
@@ -1010,11 +1013,11 @@ describe('buildMenuTemplate — View → Show only markdown files / Show skills
// presents the visibility toggles identically.
const template = buildMenuTemplate(
makeDeps({
- onToggleShowHiddenFiles: mock(() => {}),
- onToggleShowOkFolders: mock(() => {}),
- onToggleShowOnlyMarkdownFiles: mock(() => {}),
- onToggleShowSkillsSection: mock(() => {}),
- onExpandAll: mock(() => {}),
+ onToggleShowHiddenFiles: vi.fn(() => {}),
+ onToggleShowOkFolders: vi.fn(() => {}),
+ onToggleShowOnlyMarkdownFiles: vi.fn(() => {}),
+ onToggleShowSkillsSection: vi.fn(() => {}),
+ onExpandAll: vi.fn(() => {}),
}),
);
const view = findByLabel(template, 'View');
@@ -1045,21 +1048,21 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
test('renders "Hide sidebar" when sidebarVisible is true (or undefined default)', () => {
const expanded = buildMenuTemplate(
- makeDeps({ onToggleSidebar: mock(() => {}), sidebarVisible: true }),
+ makeDeps({ onToggleSidebar: vi.fn(() => {}), sidebarVisible: true }),
);
expect(findByLabel(expanded, 'Hide sidebar')).toBeDefined();
expect(findByLabel(expanded, 'Show sidebar')).toBeUndefined();
// `undefined` defaults to "visible" so the menu reads correctly before
// the first renderer-pushed view-menu-state snapshot lands.
- const defaultDeps = buildMenuTemplate(makeDeps({ onToggleSidebar: mock(() => {}) }));
+ const defaultDeps = buildMenuTemplate(makeDeps({ onToggleSidebar: vi.fn(() => {}) }));
expect(findByLabel(defaultDeps, 'Hide sidebar')).toBeDefined();
expect(findByLabel(defaultDeps, 'Show sidebar')).toBeUndefined();
});
test('renders "Show sidebar" when sidebarVisible is false', () => {
const collapsed = buildMenuTemplate(
- makeDeps({ onToggleSidebar: mock(() => {}), sidebarVisible: false }),
+ makeDeps({ onToggleSidebar: vi.fn(() => {}), sidebarVisible: false }),
);
expect(findByLabel(collapsed, 'Show sidebar')).toBeDefined();
expect(findByLabel(collapsed, 'Hide sidebar')).toBeUndefined();
@@ -1074,11 +1077,11 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
// sibling accelerators use): Electron renders it as ⌥⌘S on macOS. A future
// refactor that drops or changes the accelerator would silently break that
// affordance.
- const template = buildMenuTemplate(makeDeps({ onToggleSidebar: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onToggleSidebar: vi.fn(() => {}) }));
expect(findByLabel(template, 'Hide sidebar')?.accelerator).toBe('CmdOrCtrl+Alt+S');
const collapsed = buildMenuTemplate(
- makeDeps({ onToggleSidebar: mock(() => {}), sidebarVisible: false }),
+ makeDeps({ onToggleSidebar: vi.fn(() => {}), sidebarVisible: false }),
);
expect(findByLabel(collapsed, 'Show sidebar')?.accelerator).toBe('CmdOrCtrl+Alt+S');
});
@@ -1089,12 +1092,12 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
});
test('click dispatches deps.onToggleSidebar', () => {
- const onToggleSidebar = mock(() => {});
+ const onToggleSidebar = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onToggleSidebar, sidebarVisible: true }));
(findByLabel(template, 'Hide sidebar')?.click as (() => void) | undefined)?.();
expect(onToggleSidebar).toHaveBeenCalledTimes(1);
- const onToggleSidebar2 = mock(() => {});
+ const onToggleSidebar2 = vi.fn(() => {});
const collapsed = buildMenuTemplate(
makeDeps({ onToggleSidebar: onToggleSidebar2, sidebarVisible: false }),
);
@@ -1105,8 +1108,8 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
test('Show/Hide sidebar precedes Show hidden files in the View submenu', () => {
const template = buildMenuTemplate(
makeDeps({
- onToggleSidebar: mock(() => {}),
- onToggleShowHiddenFiles: mock(() => {}),
+ onToggleSidebar: vi.fn(() => {}),
+ onToggleShowHiddenFiles: vi.fn(() => {}),
}),
);
const view = findByLabel(template, 'View');
@@ -1123,12 +1126,12 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
// Structural tests mirror the ⌥⌘S cluster above so accelerator drift, label
// drift on `docPanelVisible`, and unwired-deps disabling all fail loudly.
test('renders "Hide document panel" when docPanelVisible is unset or true', () => {
- const unsetDeps = buildMenuTemplate(makeDeps({ onToggleDocPanel: mock(() => {}) }));
+ const unsetDeps = buildMenuTemplate(makeDeps({ onToggleDocPanel: vi.fn(() => {}) }));
expect(findByLabel(unsetDeps, 'Hide document panel')).toBeDefined();
expect(findByLabel(unsetDeps, 'Show document panel')).toBeUndefined();
const visible = buildMenuTemplate(
- makeDeps({ onToggleDocPanel: mock(() => {}), docPanelVisible: true }),
+ makeDeps({ onToggleDocPanel: vi.fn(() => {}), docPanelVisible: true }),
);
expect(findByLabel(visible, 'Hide document panel')).toBeDefined();
expect(findByLabel(visible, 'Show document panel')).toBeUndefined();
@@ -1136,7 +1139,7 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
test('renders "Show document panel" when docPanelVisible is false', () => {
const collapsed = buildMenuTemplate(
- makeDeps({ onToggleDocPanel: mock(() => {}), docPanelVisible: false }),
+ makeDeps({ onToggleDocPanel: vi.fn(() => {}), docPanelVisible: false }),
);
expect(findByLabel(collapsed, 'Show document panel')).toBeDefined();
expect(findByLabel(collapsed, 'Hide document panel')).toBeUndefined();
@@ -1151,11 +1154,11 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
// clears all four collision surfaces (macOS / browser / Electron DevTools
// / TipTap-CodeMirror). Spelled `CmdOrCtrl+Alt+B` (cross-platform-safe;
// Electron renders as ⌥⌘B on macOS).
- const visible = buildMenuTemplate(makeDeps({ onToggleDocPanel: mock(() => {}) }));
+ const visible = buildMenuTemplate(makeDeps({ onToggleDocPanel: vi.fn(() => {}) }));
expect(findByLabel(visible, 'Hide document panel')?.accelerator).toBe('CmdOrCtrl+Alt+B');
const collapsed = buildMenuTemplate(
- makeDeps({ onToggleDocPanel: mock(() => {}), docPanelVisible: false }),
+ makeDeps({ onToggleDocPanel: vi.fn(() => {}), docPanelVisible: false }),
);
expect(findByLabel(collapsed, 'Show document panel')?.accelerator).toBe('CmdOrCtrl+Alt+B');
});
@@ -1166,12 +1169,12 @@ describe('buildMenuTemplate — View → Show/Hide sidebar', () => {
});
test('Document panel click dispatches deps.onToggleDocPanel', () => {
- const onToggleDocPanel = mock(() => {});
+ const onToggleDocPanel = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onToggleDocPanel, docPanelVisible: true }));
(findByLabel(template, 'Hide document panel')?.click as (() => void) | undefined)?.();
expect(onToggleDocPanel).toHaveBeenCalledTimes(1);
- const onToggleDocPanel2 = mock(() => {});
+ const onToggleDocPanel2 = vi.fn(() => {});
const collapsed = buildMenuTemplate(
makeDeps({ onToggleDocPanel: onToggleDocPanel2, docPanelVisible: false }),
);
@@ -1188,12 +1191,12 @@ describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
// sidebar item's accelerator model.
test('renders "Show Terminal" when terminalVisible is unset or false', () => {
- const unsetDeps = buildMenuTemplate(makeDeps({ onToggleTerminal: mock(() => {}) }));
+ const unsetDeps = buildMenuTemplate(makeDeps({ onToggleTerminal: vi.fn(() => {}) }));
expect(findByLabel(unsetDeps, 'Show Terminal')).toBeDefined();
expect(findByLabel(unsetDeps, 'Hide Terminal')).toBeUndefined();
const hidden = buildMenuTemplate(
- makeDeps({ onToggleTerminal: mock(() => {}), terminalVisible: false }),
+ makeDeps({ onToggleTerminal: vi.fn(() => {}), terminalVisible: false }),
);
expect(findByLabel(hidden, 'Show Terminal')).toBeDefined();
expect(findByLabel(hidden, 'Hide Terminal')).toBeUndefined();
@@ -1201,7 +1204,7 @@ describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
test('renders "Hide Terminal" when terminalVisible is true', () => {
const visible = buildMenuTemplate(
- makeDeps({ onToggleTerminal: mock(() => {}), terminalVisible: true }),
+ makeDeps({ onToggleTerminal: vi.fn(() => {}), terminalVisible: true }),
);
expect(findByLabel(visible, 'Hide Terminal')).toBeDefined();
expect(findByLabel(visible, 'Show Terminal')).toBeUndefined();
@@ -1211,11 +1214,11 @@ describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
// Pinned because ⌘J / Ctrl+J is the muscle-memory affordance for the bottom
// panel (VS Code parity); ⌘` is macOS window-cycling. A refactor that drops
// or rebinds the accelerator silently breaks that affordance.
- const hidden = buildMenuTemplate(makeDeps({ onToggleTerminal: mock(() => {}) }));
+ const hidden = buildMenuTemplate(makeDeps({ onToggleTerminal: vi.fn(() => {}) }));
expect(findByLabel(hidden, 'Show Terminal')?.accelerator).toBe('CmdOrCtrl+J');
const visible = buildMenuTemplate(
- makeDeps({ onToggleTerminal: mock(() => {}), terminalVisible: true }),
+ makeDeps({ onToggleTerminal: vi.fn(() => {}), terminalVisible: true }),
);
expect(findByLabel(visible, 'Hide Terminal')?.accelerator).toBe('CmdOrCtrl+J');
});
@@ -1226,12 +1229,12 @@ describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
});
test('Terminal click dispatches deps.onToggleTerminal', () => {
- const onToggleTerminal = mock(() => {});
+ const onToggleTerminal = vi.fn(() => {});
const template = buildMenuTemplate(makeDeps({ onToggleTerminal }));
(findByLabel(template, 'Show Terminal')?.click as (() => void) | undefined)?.();
expect(onToggleTerminal).toHaveBeenCalledTimes(1);
- const onToggleTerminal2 = mock(() => {});
+ const onToggleTerminal2 = vi.fn(() => {});
const visible = buildMenuTemplate(
makeDeps({ onToggleTerminal: onToggleTerminal2, terminalVisible: true }),
);
@@ -1241,7 +1244,7 @@ describe('buildMenuTemplate — View → Show/Hide Terminal', () => {
test('Terminal follows the Document Panel toggle and precedes the Zoom cluster', () => {
const template = buildMenuTemplate(
- makeDeps({ onToggleDocPanel: mock(() => {}), onToggleTerminal: mock(() => {}) }),
+ makeDeps({ onToggleDocPanel: vi.fn(() => {}), onToggleTerminal: vi.fn(() => {}) }),
);
const view = findByLabel(template, 'View');
const sub = view?.submenu as MenuItemConstructorOptions[] | undefined;
@@ -1272,9 +1275,9 @@ describe('buildMenuTemplate — top-level Terminal menu (New / Kill)', () => {
test('contains New Terminal, New Terminal Window, then Kill Terminal; New Terminal is click-only (no ⌘J)', () => {
const template = buildMenuTemplate(
makeDeps({
- onNewTerminal: mock(() => {}),
- onNewTerminalWindow: mock(() => {}),
- onKillTerminal: mock(() => {}),
+ onNewTerminal: vi.fn(() => {}),
+ onNewTerminalWindow: vi.fn(() => {}),
+ onKillTerminal: vi.fn(() => {}),
}),
);
const sub = findByLabel(template, 'Terminal')?.submenu as
@@ -1291,7 +1294,7 @@ describe('buildMenuTemplate — top-level Terminal menu (New / Kill)', () => {
});
test('New Terminal dispatches onNewTerminal; disabled when the handler is unwired', () => {
- const onNewTerminal = mock(() => {});
+ const onNewTerminal = vi.fn(() => {});
const item = findByLabel(buildMenuTemplate(makeDeps({ onNewTerminal })), 'New Terminal');
expect(item?.enabled).toBe(true);
(item?.click as (() => void) | undefined)?.();
@@ -1302,7 +1305,7 @@ describe('buildMenuTemplate — top-level Terminal menu (New / Kill)', () => {
test('Kill Terminal is disabled with no live session, enabled + kills when one is live', () => {
// Wired handler but no live session → disabled (spec: disable when no session).
- const offline = buildMenuTemplate(makeDeps({ onKillTerminal: mock(() => {}) }));
+ const offline = buildMenuTemplate(makeDeps({ onKillTerminal: vi.fn(() => {}) }));
expect(findByLabel(offline, 'Kill Terminal')?.enabled).toBe(false);
// A live session but no wired handler (unit-test default) → still disabled.
@@ -1310,7 +1313,7 @@ describe('buildMenuTemplate — top-level Terminal menu (New / Kill)', () => {
expect(findByLabel(unwired, 'Kill Terminal')?.enabled).toBe(false);
// Live + wired → enabled; clicking runs the kill path.
- const onKillTerminal = mock(() => {});
+ const onKillTerminal = vi.fn(() => {});
const live = buildMenuTemplate(makeDeps({ onKillTerminal, terminalLive: true }));
const killItem = findByLabel(live, 'Kill Terminal');
expect(killItem?.enabled).toBe(true);
@@ -1319,7 +1322,7 @@ describe('buildMenuTemplate — top-level Terminal menu (New / Kill)', () => {
});
test('the View → Show/Hide Terminal toggle is preserved alongside the Terminal menu', () => {
- const template = buildMenuTemplate(makeDeps({ onToggleTerminal: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onToggleTerminal: vi.fn(() => {}) }));
expect(findByLabel(template, 'Show Terminal')).toBeDefined();
expect(findByLabel(template, 'Terminal')).toBeDefined();
});
@@ -1335,7 +1338,7 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
test('renders as a checkbox-type item, checked when spellCheckEnabled is true', () => {
const item = findByLabel(
- buildMenuTemplate(makeDeps({ spellCheckEnabled: true, onToggleSpellCheck: mock(() => {}) })),
+ buildMenuTemplate(makeDeps({ spellCheckEnabled: true, onToggleSpellCheck: vi.fn(() => {}) })),
'Check spelling while typing',
);
expect(item).toBeDefined();
@@ -1345,7 +1348,9 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
test('renders unchecked when spellCheckEnabled is false', () => {
const item = findByLabel(
- buildMenuTemplate(makeDeps({ spellCheckEnabled: false, onToggleSpellCheck: mock(() => {}) })),
+ buildMenuTemplate(
+ makeDeps({ spellCheckEnabled: false, onToggleSpellCheck: vi.fn(() => {}) }),
+ ),
'Check spelling while typing',
);
expect(item?.checked).toBe(false);
@@ -1353,7 +1358,7 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
test('defaults to checked when spellCheckEnabled dep is omitted (matches the on-by-default persistence default)', () => {
const item = findByLabel(
- buildMenuTemplate(makeDeps({ onToggleSpellCheck: mock(() => {}) })),
+ buildMenuTemplate(makeDeps({ onToggleSpellCheck: vi.fn(() => {}) })),
'Check spelling while typing',
);
expect(item?.checked).toBe(true);
@@ -1361,7 +1366,7 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
test('ENABLED when onToggleSpellCheck handler is provided', () => {
const item = findByLabel(
- buildMenuTemplate(makeDeps({ onToggleSpellCheck: mock(() => {}) })),
+ buildMenuTemplate(makeDeps({ onToggleSpellCheck: vi.fn(() => {}) })),
'Check spelling while typing',
);
expect(item?.enabled).toBe(true);
@@ -1373,7 +1378,7 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
});
test('click dispatches deps.onToggleSpellCheck', () => {
- const onToggleSpellCheck = mock(() => {});
+ const onToggleSpellCheck = vi.fn(() => {});
const item = findByLabel(
buildMenuTemplate(makeDeps({ onToggleSpellCheck })),
'Check spelling while typing',
@@ -1388,7 +1393,7 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
});
test('lives in the Edit submenu after the Select All role', () => {
- const sub = editSubmenu(makeDeps({ onToggleSpellCheck: mock(() => {}) }));
+ const sub = editSubmenu(makeDeps({ onToggleSpellCheck: vi.fn(() => {}) }));
const selectAllIdx = sub.findIndex((i) => i.role === 'selectAll');
const spellIdx = sub.findIndex((i) => i.label === 'Check spelling while typing');
expect(selectAllIdx).toBeGreaterThanOrEqual(0);
@@ -1398,7 +1403,7 @@ describe('buildMenuTemplate — Edit → Check spelling while typing', () => {
describe('Terminal menu — New Terminal Window', () => {
test('appears in the Terminal submenu beside New Terminal', () => {
- const template = buildMenuTemplate(makeDeps({ onNewTerminalWindow: mock(() => {}) }));
+ const template = buildMenuTemplate(makeDeps({ onNewTerminalWindow: vi.fn(() => {}) }));
const terminalMenu = template.find((i) => i.label === 'Terminal');
const sub = terminalMenu?.submenu as MenuItemConstructorOptions[] | undefined;
if (!sub) throw new Error('Terminal submenu missing');
@@ -1409,7 +1414,7 @@ describe('Terminal menu — New Terminal Window', () => {
test('renders with no keyboard accelerator', () => {
const item = findByLabel(
- buildMenuTemplate(makeDeps({ onNewTerminalWindow: mock(() => {}) })),
+ buildMenuTemplate(makeDeps({ onNewTerminalWindow: vi.fn(() => {}) })),
'New Terminal Window',
);
expect(item).toBeDefined();
@@ -1417,7 +1422,7 @@ describe('Terminal menu — New Terminal Window', () => {
});
test('click invokes onNewTerminalWindow', () => {
- const onNewTerminalWindow = mock(() => {});
+ const onNewTerminalWindow = vi.fn(() => {});
const item = findByLabel(
buildMenuTemplate(makeDeps({ onNewTerminalWindow })),
'New Terminal Window',
@@ -1429,7 +1434,7 @@ describe('Terminal menu — New Terminal Window', () => {
test('disabled when the dep is omitted, enabled when wired', () => {
expect(findByLabel(buildMenuTemplate(makeDeps()), 'New Terminal Window')?.enabled).toBe(false);
const wired = findByLabel(
- buildMenuTemplate(makeDeps({ onNewTerminalWindow: mock(() => {}) })),
+ buildMenuTemplate(makeDeps({ onNewTerminalWindow: vi.fn(() => {}) })),
'New Terminal Window',
);
expect(wired?.enabled).toBe(true);
diff --git a/packages/desktop/tests/main/navigator-window.test.ts b/packages/desktop/tests/main/navigator-window.test.ts
index 7c74bc20d..51144ac10 100644
--- a/packages/desktop/tests/main/navigator-window.test.ts
+++ b/packages/desktop/tests/main/navigator-window.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import { createNavigatorWindow, tryCloseNavigator } from '../../src/main/navigator-window.ts';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import type { ShareNavigatorPayload } from '../../src/main/url-scheme.ts';
@@ -12,28 +12,28 @@ import type { BrowserWindowLike } from '../../src/main/window-manager.ts';
*/
interface MockNav extends BrowserWindowLike {
- closeMock: ReturnType<typeof mock>;
+ closeMock: ReturnType<typeof vi.fn>;
setDestroyed: (v: boolean) => void;
}
function makeNav(opts?: { destroyed?: boolean; closeImpl?: () => void }): MockNav {
let destroyed = opts?.destroyed ?? false;
- const closeMock = mock(() => {
+ const closeMock = vi.fn(() => {
if (opts?.closeImpl) opts.closeImpl();
});
return {
- focus: mock(() => {}),
- isDestroyed: mock(() => destroyed),
- on: mock(() => {}) as BrowserWindowLike['on'],
- once: mock(() => {}) as BrowserWindowLike['once'],
+ focus: vi.fn(() => {}),
+ isDestroyed: vi.fn(() => destroyed),
+ on: vi.fn(() => {}) as BrowserWindowLike['on'],
+ once: vi.fn(() => {}) as BrowserWindowLike['once'],
webContents: {
- send: mock(() => {}),
- once: mock(() => {}),
- setWindowOpenHandler: mock(() => {}),
- on: mock(() => {}),
+ send: vi.fn(() => {}),
+ once: vi.fn(() => {}),
+ setWindowOpenHandler: vi.fn(() => {}),
+ on: vi.fn(() => {}),
},
- loadFile: mock(() => Promise.resolve()),
- loadURL: mock(() => Promise.resolve()),
+ loadFile: vi.fn(() => Promise.resolve()),
+ loadURL: vi.fn(() => Promise.resolve()),
close: closeMock,
closeMock,
setDestroyed: (v) => {
@@ -44,7 +44,7 @@ function makeNav(opts?: { destroyed?: boolean; closeImpl?: () => void }): MockNa
describe('tryCloseNavigator', () => {
test('no-op when navigator is null', () => {
- const log = mock(() => {});
+ const log = vi.fn(() => {});
// null branch — caller never opened the Navigator (cold launch with
// lastOpenedProject set). Must not throw and must not log.
tryCloseNavigator(null, { projectPath: '/p' }, log);
@@ -53,7 +53,7 @@ describe('tryCloseNavigator', () => {
test('no-op when window is destroyed', () => {
const nav = makeNav({ destroyed: true });
- const log = mock(() => {});
+ const log = vi.fn(() => {});
// Race: the close listener nulls navigatorWindow on user-initiated
// close, but in a renderer-crash window between createProjectWindow
// resolving and reaching the close call the variable could still
@@ -66,7 +66,7 @@ describe('tryCloseNavigator', () => {
test('calls close() when window is alive', () => {
const nav = makeNav();
- const log = mock(() => {});
+ const log = vi.fn(() => {});
tryCloseNavigator(nav, { projectPath: '/p' }, log);
expect(nav.closeMock).toHaveBeenCalledTimes(1);
expect(log).not.toHaveBeenCalled();
@@ -78,7 +78,7 @@ describe('tryCloseNavigator', () => {
throw new Error('Object has been destroyed');
},
});
- const log = mock(() => {});
+ const log = vi.fn(() => {});
// The throw must NOT propagate — propagation would land in
// openProjectOrFallbackToNavigator's catch and surface "Unable to open
// project" to the user even though the project did open. The log
@@ -102,7 +102,7 @@ describe('tryCloseNavigator', () => {
throw 'native-string-throw';
},
});
- const log = mock(() => {});
+ const log = vi.fn(() => {});
tryCloseNavigator(nav, { projectPath: '/p' }, log);
expect(log).toHaveBeenCalledWith(
'failed to close Navigator after project open',
@@ -131,15 +131,15 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
const loadCallOrder: string[] = [];
let onceCalledBeforeLoad = false;
return {
- focus: mock(() => {}),
- isDestroyed: mock(() => false),
- on: mock((_event: 'closed', cb: () => void) => {
+ focus: vi.fn(() => {}),
+ isDestroyed: vi.fn(() => false),
+ on: vi.fn((_event: 'closed', cb: () => void) => {
closeHandlers.push(cb);
}) as BrowserWindowLike['on'],
- once: mock(() => {}) as BrowserWindowLike['once'],
+ once: vi.fn(() => {}) as BrowserWindowLike['once'],
webContents: {
- send: mock(() => {}),
- once: mock((event: 'dom-ready' | 'did-finish-load', cb: () => void) => {
+ send: vi.fn(() => {}),
+ once: vi.fn((event: 'dom-ready' | 'did-finish-load', cb: () => void) => {
if (event === 'dom-ready') {
domReadyHandler = cb;
loadCallOrder.push('once-dom-ready');
@@ -148,21 +148,21 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
loadCallOrder.push('once-did-finish-load');
}
}),
- executeJavaScript: mock(() => Promise.resolve()),
- setWindowOpenHandler: mock(() => {}),
- on: mock(() => {}),
+ executeJavaScript: vi.fn(() => Promise.resolve()),
+ setWindowOpenHandler: vi.fn(() => {}),
+ on: vi.fn(() => {}),
},
- loadFile: mock(() => {
+ loadFile: vi.fn(() => {
loadCallOrder.push('loadFile');
if (loadCallOrder.includes('once-dom-ready')) onceCalledBeforeLoad = true;
return Promise.resolve();
}),
- loadURL: mock(() => {
+ loadURL: vi.fn(() => {
loadCallOrder.push('loadURL');
if (loadCallOrder.includes('once-dom-ready')) onceCalledBeforeLoad = true;
return Promise.resolve();
}),
- close: mock(() => {
+ close: vi.fn(() => {
for (const h of closeHandlers) h();
}),
fireDomReady: () => domReadyHandler?.(),
@@ -211,14 +211,14 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
// Payload has NOT fired yet.
expect(
- (win.webContents.send as ReturnType<typeof mock>).mock.calls.find(
+ (win.webContents.send as ReturnType<typeof vi.fn>).mock.calls.find(
(c) => c[0] === 'ok:share:received',
),
).toBeUndefined();
// Firing dom-ready triggers the send.
win.fireDomReady();
- const shareCall = (win.webContents.send as ReturnType<typeof mock>).mock.calls.find(
+ const shareCall = (win.webContents.send as ReturnType<typeof vi.fn>).mock.calls.find(
(c) => c[0] === 'ok:share:received',
);
expect(shareCall).toBeDefined();
@@ -248,7 +248,7 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
});
win.fireDomReady();
- const sendCalls = (win.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (win.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
expect(sendCalls.find((c) => c[0] === 'ok:share:received')).toBeUndefined();
});
@@ -274,7 +274,7 @@ describe('createNavigatorWindow — pendingPayload dom-ready gate (US-004)', ()
});
win.fireDomReady();
- const shareCall = (win.webContents.send as ReturnType<typeof mock>).mock.calls.find(
+ const shareCall = (win.webContents.send as ReturnType<typeof vi.fn>).mock.calls.find(
(c) => c[0] === 'ok:share:received',
);
expect(shareCall?.[1]).toEqual(payload);
diff --git a/packages/desktop/tests/main/reduced-transparency-handler.test.ts b/packages/desktop/tests/main/reduced-transparency-handler.test.ts
index 766cbbb8e..4aa15d405 100644
--- a/packages/desktop/tests/main/reduced-transparency-handler.test.ts
+++ b/packages/desktop/tests/main/reduced-transparency-handler.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
applyReducedTransparency,
@@ -8,13 +8,13 @@ import {
interface WindowFixture {
win: BrowserWindowVibrancyTarget;
- setVibrancy: ReturnType<typeof mock>;
- isDestroyed: ReturnType<typeof mock>;
+ setVibrancy: ReturnType<typeof vi.fn>;
+ isDestroyed: ReturnType<typeof vi.fn>;
}
function makeWindow(opts?: { destroyed?: boolean }): WindowFixture {
- const setVibrancy = mock(() => {});
- const isDestroyed = mock(() => opts?.destroyed === true);
+ const setVibrancy = vi.fn(() => {});
+ const isDestroyed = vi.fn(() => opts?.destroyed === true);
return {
win: {
setVibrancy: setVibrancy as unknown as (mat: 'sidebar' | 'window' | null) => void,
@@ -62,7 +62,7 @@ describe('applyReducedTransparency — disable path (reduced=true)', () => {
// with `win.isDestroyed?.()`. Pin that the optional chain holds for a
// window that omits the method entirely — dropping the `?.` would throw
// TypeError mid-loop and abort vibrancy for every remaining window.
- const setVibrancy = mock(() => {});
+ const setVibrancy = vi.fn(() => {});
const win: BrowserWindowVibrancyTarget = {
setVibrancy: setVibrancy as unknown as (mat: 'sidebar' | 'window' | null) => void,
};
@@ -108,7 +108,7 @@ describe('applyReducedTransparency — diagnostic logging', () => {
test('emits structured warn with event/reducedTransparency/vibrancy/windowCount on disable', () => {
const a = makeWindow();
const b = makeWindow();
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win, b.win],
defaultVibrancy: 'sidebar',
@@ -129,7 +129,7 @@ describe('applyReducedTransparency — diagnostic logging', () => {
test('emits structured warn with vibrancy=defaultVibrancy on restore', () => {
const a = makeWindow();
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win],
defaultVibrancy: 'sidebar',
@@ -149,7 +149,7 @@ describe('applyReducedTransparency — diagnostic logging', () => {
test('windowCount counts only successfully-applied windows; destroyed windows go to destroyedCount', () => {
const live = makeWindow();
const dead = makeWindow({ destroyed: true });
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [live.win, dead.win],
defaultVibrancy: 'sidebar',
@@ -172,7 +172,7 @@ describe('applyReducedTransparency — diagnostic logging', () => {
// the completeness operators rely on to tell convergence from failure.
const a = makeWindow();
const b = makeWindow({ destroyed: true });
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win, b.win],
defaultVibrancy: 'sidebar',
@@ -198,7 +198,7 @@ describe('applyReducedTransparency — diagnostic logging', () => {
});
test('empty windows array still emits structured warn with windowCount=0', () => {
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [],
defaultVibrancy: 'sidebar',
@@ -238,10 +238,10 @@ describe('applyReducedTransparency — per-window throw isolation', () => {
// loop. The guard isolates each call.
function makeThrowingWindow(): WindowFixture {
const error = new Error('setVibrancy: window destroyed');
- const setVibrancy = mock(() => {
+ const setVibrancy = vi.fn(() => {
throw error;
});
- const isDestroyed = mock(() => false);
+ const isDestroyed = vi.fn(() => false);
return {
win: {
setVibrancy: setVibrancy as unknown as (mat: 'sidebar' | 'window' | null) => void,
@@ -273,7 +273,7 @@ describe('applyReducedTransparency — per-window throw isolation', () => {
test('throw on one window emits a structured per-window warn', () => {
const a = makeWindow();
const b = makeThrowingWindow();
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win, b.win],
defaultVibrancy: 'sidebar',
@@ -292,7 +292,7 @@ describe('applyReducedTransparency — per-window throw isolation', () => {
test('windowCount counts only successfully-toggled windows when one throws', () => {
const a = makeWindow();
const b = makeThrowingWindow();
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win, b.win],
defaultVibrancy: 'sidebar',
@@ -314,7 +314,7 @@ describe('applyReducedTransparency — per-window throw isolation', () => {
test('per-window failure warn carries the window id for attribution', () => {
const a = makeWindow();
// A throwing window that also exposes a stable id, as real BrowserWindows do.
- const setVibrancy = mock(() => {
+ const setVibrancy = vi.fn(() => {
throw new Error('setVibrancy: native failure');
});
const b: BrowserWindowVibrancyTarget = {
@@ -322,7 +322,7 @@ describe('applyReducedTransparency — per-window throw isolation', () => {
isDestroyed: () => false,
setVibrancy: setVibrancy as unknown as (mat: 'sidebar' | 'window' | null) => void,
};
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win, b],
defaultVibrancy: 'sidebar',
@@ -343,7 +343,7 @@ describe('applyReducedTransparency — per-window idempotence memo (flicker guar
// mints fresh window stubs, so memoized state never leaks across tests — but
// WITHIN a test, reusing the same stub across calls is what exercises the
// skip path that collapses the N² theme-change re-apply burst.
- function summaries(warn: ReturnType<typeof mock>) {
+ function summaries(warn: ReturnType<typeof vi.fn>) {
return warn.mock.calls
.map((call) => JSON.parse(call[0] as unknown as string))
.filter((l) => l.event === 'reduced-transparency-applied');
@@ -351,7 +351,7 @@ describe('applyReducedTransparency — per-window idempotence memo (flicker guar
test('skips a window already at the target material on a repeat call (no redundant setVibrancy)', () => {
const a = makeWindow();
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
const deps: ReducedTransparencyDeps = {
getAllWindows: () => [a.win],
defaultVibrancy: 'sidebar',
@@ -389,7 +389,7 @@ describe('applyReducedTransparency — per-window idempotence memo (flicker guar
test('applies once to a newly-opened window while skipping already-memoized windows', () => {
const a = makeWindow();
const b = makeWindow();
- const warn = mock(() => {});
+ const warn = vi.fn(() => {});
// a is present for the first toggle; b opens before the second.
applyReducedTransparency(
@@ -431,7 +431,7 @@ describe('applyReducedTransparency — per-window idempotence memo (flicker guar
// would permanently skip a window that hit one transient error — this test
// is the regression pin for that.
let calls = 0;
- const setVibrancy = mock(() => {
+ const setVibrancy = vi.fn(() => {
calls += 1;
if (calls === 1) throw new Error('setVibrancy: transient native failure');
});
diff --git a/packages/desktop/tests/main/seed-ipc.test.ts b/packages/desktop/tests/main/seed-ipc.test.ts
index 0b5868588..87f4d509e 100644
--- a/packages/desktop/tests/main/seed-ipc.test.ts
+++ b/packages/desktop/tests/main/seed-ipc.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { handleSeedApply, handleSeedPlan } from '../../src/main/ipc/seed.ts';
let testDir: string;
diff --git a/packages/desktop/tests/main/shell-allowlist.test.ts b/packages/desktop/tests/main/shell-allowlist.test.ts
index 05de62775..38525e6d9 100644
--- a/packages/desktop/tests/main/shell-allowlist.test.ts
+++ b/packages/desktop/tests/main/shell-allowlist.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
// Test-only cross-package import. Main-process runtime bundle does NOT include
// app-layer code (tree-shaken since no production handler imports from app).
// Relative path over workspace ref
@@ -81,42 +81,42 @@ describe('checkOutboundUrl (D47 outbound scheme allowlist)', () => {
describe('handleShellOpenExternal (preload → main bridge enforcement)', () => {
test('delegates to openExternal for allowed schemes', async () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
const handle = handleShellOpenExternal({ openExternal });
await handle('https://example.com');
expect(openExternal).toHaveBeenCalledWith('https://example.com');
});
test('delegates to openExternal for openknowledge:// (our own scheme)', async () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
const handle = handleShellOpenExternal({ openExternal });
await handle('openknowledge://open?project=/tmp&doc=x');
expect(openExternal).toHaveBeenCalledWith('openknowledge://open?project=/tmp&doc=x');
});
test('rejects file:// with a scheme-not-allowed error (no openExternal call)', async () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
const handle = handleShellOpenExternal({ openExternal });
await expect(handle('file:///etc/passwd')).rejects.toThrow(/scheme-not-allowed/);
expect(openExternal).not.toHaveBeenCalled();
});
test('rejects javascript: with a scheme-not-allowed error', async () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
const handle = handleShellOpenExternal({ openExternal });
await expect(handle('javascript:alert(1)')).rejects.toThrow(/scheme-not-allowed/);
expect(openExternal).not.toHaveBeenCalled();
});
test('rejects data: with a scheme-not-allowed error', async () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
const handle = handleShellOpenExternal({ openExternal });
await expect(handle('data:text/html,x')).rejects.toThrow(/scheme-not-allowed/);
expect(openExternal).not.toHaveBeenCalled();
});
test('rejects malformed URL with invalid-url reason', async () => {
- const openExternal = mock(() => Promise.resolve());
+ const openExternal = vi.fn(() => Promise.resolve());
const handle = handleShellOpenExternal({ openExternal });
await expect(handle('not a url')).rejects.toThrow(/invalid-url/);
expect(openExternal).not.toHaveBeenCalled();
diff --git a/packages/desktop/tests/main/spellcheck-context-menu.test.ts b/packages/desktop/tests/main/spellcheck-context-menu.test.ts
index 86ad8c938..fdd0ea2b4 100644
--- a/packages/desktop/tests/main/spellcheck-context-menu.test.ts
+++ b/packages/desktop/tests/main/spellcheck-context-menu.test.ts
@@ -5,7 +5,7 @@
* the right injected capability — all without mounting a BrowserWindow.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
attachSpellcheckContextMenu,
type ContextMenuHandlerParams,
@@ -33,7 +33,7 @@ function makeParams(overrides: Partial<ContextMenuHandlerParams> = {}): ContextM
function makeWebContents() {
let handler: ((event: unknown, params: ContextMenuHandlerParams) => void) | undefined;
return {
- on: mock(
+ on: vi.fn(
(
_event: 'context-menu',
listener: (event: unknown, params: ContextMenuHandlerParams) => void,
@@ -41,8 +41,8 @@ function makeWebContents() {
handler = listener;
},
),
- replaceMisspelling: mock((_: string) => {}),
- showDefinitionForSelection: mock(() => {}),
+ replaceMisspelling: vi.fn((_: string) => {}),
+ showDefinitionForSelection: vi.fn(() => {}),
/** Fire a context-menu event at the registered handler. */
fire(params: ContextMenuHandlerParams) {
if (!handler) throw new Error('no context-menu handler registered');
@@ -54,10 +54,10 @@ function makeWebContents() {
function makeDeps(isSpellCheckEnabled: () => boolean = () => true) {
return {
isSpellCheckEnabled,
- setSpellCheckEnabled: mock((_: boolean) => {}),
- addToDictionary: mock((_: string) => {}),
- openExternal: mock((_: string) => {}),
- popMenu: mock((_: BuildSpellcheckMenuTemplateParams) => {}),
+ setSpellCheckEnabled: vi.fn((_: boolean) => {}),
+ addToDictionary: vi.fn((_: string) => {}),
+ openExternal: vi.fn((_: string) => {}),
+ popMenu: vi.fn((_: BuildSpellcheckMenuTemplateParams) => {}),
};
}
diff --git a/packages/desktop/tests/main/spellcheck-menu.test.ts b/packages/desktop/tests/main/spellcheck-menu.test.ts
index a25795986..979c9e072 100644
--- a/packages/desktop/tests/main/spellcheck-menu.test.ts
+++ b/packages/desktop/tests/main/spellcheck-menu.test.ts
@@ -6,8 +6,8 @@
* without mounting Electron's Menu.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { BrowserWindow, Menu, MenuItemConstructorOptions } from 'electron';
+import { describe, expect, test, vi } from 'vitest';
import {
type BuildSpellcheckMenuTemplateParams,
buildSpellcheckMenuTemplate,
@@ -17,11 +17,11 @@ import {
function makeActions() {
return {
- replaceMisspelling: mock((_: string) => {}),
- addToDictionary: mock((_: string) => {}),
- setSpellCheckEnabled: mock((_: boolean) => {}),
- lookUp: mock(() => {}),
- search: mock((_: string) => {}),
+ replaceMisspelling: vi.fn((_: string) => {}),
+ addToDictionary: vi.fn((_: string) => {}),
+ setSpellCheckEnabled: vi.fn((_: boolean) => {}),
+ lookUp: vi.fn(() => {}),
+ search: vi.fn((_: string) => {}),
};
}
@@ -287,9 +287,9 @@ describe('buildSpellcheckMenuTemplate — callback dispatch', () => {
describe('popSpellcheckMenu', () => {
function makeMenuFakes() {
- const popup = mock((_: unknown) => {});
+ const popup = vi.fn((_: unknown) => {});
const menuInstance = { popup } as unknown as ReturnType<typeof Menu.buildFromTemplate>;
- const buildFromTemplate = mock((_: MenuItemConstructorOptions[]) => menuInstance);
+ const buildFromTemplate = vi.fn((_: MenuItemConstructorOptions[]) => menuInstance);
return { popup, buildFromTemplate };
}
diff --git a/packages/desktop/tests/main/state-store.test.ts b/packages/desktop/tests/main/state-store.test.ts
index 8b001c415..46df1fc13 100644
--- a/packages/desktop/tests/main/state-store.test.ts
+++ b/packages/desktop/tests/main/state-store.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, mock, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
import {
addRecentProject,
annotateMissing,
@@ -308,15 +308,15 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
// crash-safety property.
const calls: Array<{ op: string; path: string }> = [];
const fs: SaveAppStateFs = {
- existsSync: mock(() => true),
- mkdirSync: mock(() => undefined),
- writeFileSync: mock((p: string) => {
+ existsSync: vi.fn(() => true),
+ mkdirSync: vi.fn(() => undefined),
+ writeFileSync: vi.fn((p: string) => {
calls.push({ op: 'write', path: p });
}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock((from: string, to: string) => {
+ renameSync: vi.fn((from: string, to: string) => {
calls.push({ op: 'rename', path: `${from}->${to}` });
}) as unknown as SaveAppStateFs['renameSync'],
- unlinkSync: mock(() => undefined) as unknown as SaveAppStateFs['unlinkSync'],
+ unlinkSync: vi.fn(() => undefined) as unknown as SaveAppStateFs['unlinkSync'],
};
saveAppStateToDir('/fake/userdata', emptyState(), fs, {
error: () => {},
@@ -329,13 +329,13 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
});
test('renameSync failure → cleanup attempt + error log (does NOT throw)', () => {
- const errorLog = mock(() => {});
- const unlinkSpy = mock(() => {});
+ const errorLog = vi.fn(() => {});
+ const unlinkSpy = vi.fn(() => {});
const fs: SaveAppStateFs = {
- existsSync: mock(() => true),
- mkdirSync: mock(() => undefined),
- writeFileSync: mock(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock(() => {
+ existsSync: vi.fn(() => true),
+ mkdirSync: vi.fn(() => undefined),
+ writeFileSync: vi.fn(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
+ renameSync: vi.fn(() => {
throw new Error('EACCES: permission denied');
}) as unknown as SaveAppStateFs['renameSync'],
unlinkSync: unlinkSpy as unknown as SaveAppStateFs['unlinkSync'],
@@ -351,13 +351,13 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
test('mkdirSync failure → outer catch logs "userData setup failed"', () => {
const errorMessages: string[] = [];
const fs: SaveAppStateFs = {
- existsSync: mock(() => false),
- mkdirSync: mock(() => {
+ existsSync: vi.fn(() => false),
+ mkdirSync: vi.fn(() => {
throw new Error('EROFS: read-only fs');
}),
- writeFileSync: mock(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock(() => {}) as unknown as SaveAppStateFs['renameSync'],
- unlinkSync: mock(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
+ writeFileSync: vi.fn(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
+ renameSync: vi.fn(() => {}) as unknown as SaveAppStateFs['renameSync'],
+ unlinkSync: vi.fn(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
};
saveAppStateToDir('/fake/userdata', emptyState(), fs, {
error: (msg: string) => {
@@ -368,13 +368,13 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
});
test('creates userDataDir when absent', () => {
- const mkdirSpy = mock(() => undefined);
+ const mkdirSpy = vi.fn(() => undefined);
const fs: SaveAppStateFs = {
- existsSync: mock(() => false),
+ existsSync: vi.fn(() => false),
mkdirSync: mkdirSpy,
- writeFileSync: mock(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock(() => {}) as unknown as SaveAppStateFs['renameSync'],
- unlinkSync: mock(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
+ writeFileSync: vi.fn(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
+ renameSync: vi.fn(() => {}) as unknown as SaveAppStateFs['renameSync'],
+ unlinkSync: vi.fn(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
};
saveAppStateToDir('/fake/userdata', emptyState(), fs, { error: () => {} });
expect(mkdirSpy).toHaveBeenCalledWith('/fake/userdata', { recursive: true });
@@ -384,11 +384,11 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
// detect disk-failure and roll back in-memory state.
test('returns true on successful persist', () => {
const fs: SaveAppStateFs = {
- existsSync: mock(() => true),
- mkdirSync: mock(() => undefined),
- writeFileSync: mock(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock(() => {}) as unknown as SaveAppStateFs['renameSync'],
- unlinkSync: mock(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
+ existsSync: vi.fn(() => true),
+ mkdirSync: vi.fn(() => undefined),
+ writeFileSync: vi.fn(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
+ renameSync: vi.fn(() => {}) as unknown as SaveAppStateFs['renameSync'],
+ unlinkSync: vi.fn(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
};
const result = saveAppStateToDir('/fake/userdata', emptyState(), fs, { error: () => {} });
expect(result).toBe(true);
@@ -396,13 +396,13 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
test('returns false when renameSync throws', () => {
const fs: SaveAppStateFs = {
- existsSync: mock(() => true),
- mkdirSync: mock(() => undefined),
- writeFileSync: mock(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock(() => {
+ existsSync: vi.fn(() => true),
+ mkdirSync: vi.fn(() => undefined),
+ writeFileSync: vi.fn(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
+ renameSync: vi.fn(() => {
throw new Error('EACCES');
}) as unknown as SaveAppStateFs['renameSync'],
- unlinkSync: mock(() => undefined) as unknown as SaveAppStateFs['unlinkSync'],
+ unlinkSync: vi.fn(() => undefined) as unknown as SaveAppStateFs['unlinkSync'],
};
const result = saveAppStateToDir('/fake/userdata', emptyState(), fs, { error: () => {} });
expect(result).toBe(false);
@@ -440,13 +440,13 @@ describe('saveAppStateToDir (atomic write via tmp + rename)', () => {
test('returns false when userData mkdir throws', () => {
const fs: SaveAppStateFs = {
- existsSync: mock(() => false),
- mkdirSync: mock(() => {
+ existsSync: vi.fn(() => false),
+ mkdirSync: vi.fn(() => {
throw new Error('EROFS');
}),
- writeFileSync: mock(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
- renameSync: mock(() => {}) as unknown as SaveAppStateFs['renameSync'],
- unlinkSync: mock(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
+ writeFileSync: vi.fn(() => {}) as unknown as SaveAppStateFs['writeFileSync'],
+ renameSync: vi.fn(() => {}) as unknown as SaveAppStateFs['renameSync'],
+ unlinkSync: vi.fn(() => {}) as unknown as SaveAppStateFs['unlinkSync'],
};
const result = saveAppStateToDir('/fake/userdata', emptyState(), fs, { error: () => {} });
expect(result).toBe(false);
diff --git a/packages/desktop/tests/main/terminal-consent.test.ts b/packages/desktop/tests/main/terminal-consent.test.ts
index 84240aa54..09aefeb89 100644
--- a/packages/desktop/tests/main/terminal-consent.test.ts
+++ b/packages/desktop/tests/main/terminal-consent.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
isTerminalConsented,
isTerminalConsentedWithGrace,
diff --git a/packages/desktop/tests/main/terminal-lifecycle.test.ts b/packages/desktop/tests/main/terminal-lifecycle.test.ts
index 43c86efb1..2aaefa1e1 100644
--- a/packages/desktop/tests/main/terminal-lifecycle.test.ts
+++ b/packages/desktop/tests/main/terminal-lifecycle.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type ClosableWindow,
type TerminalReaper,
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
index 600e0f37d..d4c5b8820 100644
--- a/packages/desktop/tests/main/terminal-manager.test.ts
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
clampPtyDimension,
createTerminalManager,
diff --git a/packages/desktop/tests/main/terminal-reload-survival.test.ts b/packages/desktop/tests/main/terminal-reload-survival.test.ts
index e00e1e775..b05d049f9 100644
--- a/packages/desktop/tests/main/terminal-reload-survival.test.ts
+++ b/packages/desktop/tests/main/terminal-reload-survival.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
createTerminalManager,
type PtyUtilityLike,
diff --git a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts b/packages/desktop/tests/main/terminal-window-attach-survival.test.ts
index 033da9f05..f409f1e4e 100644
--- a/packages/desktop/tests/main/terminal-window-attach-survival.test.ts
+++ b/packages/desktop/tests/main/terminal-window-attach-survival.test.ts
@@ -20,7 +20,7 @@
* terminal-window-pty.test.ts.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTerminalManager, type PtyUtilityLike } from '../../src/main/terminal-manager.ts';
import {
getTerminalWindowContext,
diff --git a/packages/desktop/tests/main/terminal-window-pty.test.ts b/packages/desktop/tests/main/terminal-window-pty.test.ts
index dd36fa584..402084a9f 100644
--- a/packages/desktop/tests/main/terminal-window-pty.test.ts
+++ b/packages/desktop/tests/main/terminal-window-pty.test.ts
@@ -8,7 +8,7 @@
* `_electron` smoke (terminal-window.e2e.ts); this is the gate-run rung.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { createTerminalManager, type PtyUtilityLike } from '../../src/main/terminal-manager.ts';
import {
getTerminalWindowContext,
diff --git a/packages/desktop/tests/main/theme-applied-handler.test.ts b/packages/desktop/tests/main/theme-applied-handler.test.ts
index 6836c198a..729689105 100644
--- a/packages/desktop/tests/main/theme-applied-handler.test.ts
+++ b/packages/desktop/tests/main/theme-applied-handler.test.ts
@@ -27,7 +27,7 @@
* public interface.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { applyThemeApplied } from '../../src/main/theme-applied-handler.ts';
interface TraceEvent {
diff --git a/packages/desktop/tests/main/theme-handler.test.ts b/packages/desktop/tests/main/theme-handler.test.ts
index 556062df8..1e1711085 100644
--- a/packages/desktop/tests/main/theme-handler.test.ts
+++ b/packages/desktop/tests/main/theme-handler.test.ts
@@ -13,7 +13,7 @@
* (or a non-typed IPC fallback) would land here.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { applyThemeSource, isOkThemeSource } from '../../src/main/theme-handler.ts';
import type { OkThemeSource } from '../../src/shared/bridge-contract.ts';
diff --git a/packages/desktop/tests/main/update-state-handlers.test.ts b/packages/desktop/tests/main/update-state-handlers.test.ts
index 15e7ba66f..f75f2464e 100644
--- a/packages/desktop/tests/main/update-state-handlers.test.ts
+++ b/packages/desktop/tests/main/update-state-handlers.test.ts
@@ -8,7 +8,7 @@
* dep on `ok:state:query`.
*/
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
import {
type AppState,
emptyState,
@@ -51,7 +51,7 @@ function makeRig(overrides?: {
setAppState: (s) => {
rig.state = s;
},
- saveAppState: mock((next: AppState) => {
+ saveAppState: vi.fn((next: AppState) => {
rig.saveCalls.push(next);
return rig.saveResult;
}),
diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
index aba1923c9..1837feb31 100644
--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts
+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts
@@ -1,6 +1,6 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { getLocalDir } from '@inkeep/open-knowledge-server';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import {
type BrowserWindowLike,
@@ -38,35 +38,35 @@ function makeWindow(): FakeWindow {
for (const h of closeHandlers) h();
};
return {
- focus: mock(() => {}),
- show: mock(() => {}),
- restore: mock(() => {}),
- isMinimized: mock(() => false),
- isDestroyed: mock(() => destroyed),
- isVisible: mock(() => true),
- on: mock((_event: 'closed', cb: () => void) => {
+ focus: vi.fn(() => {}),
+ show: vi.fn(() => {}),
+ restore: vi.fn(() => {}),
+ isMinimized: vi.fn(() => false),
+ isDestroyed: vi.fn(() => destroyed),
+ isVisible: vi.fn(() => true),
+ on: vi.fn((_event: 'closed', cb: () => void) => {
closeHandlers.push(cb);
}) as BrowserWindowLike['on'],
- once: mock(() => {}) as BrowserWindowLike['once'],
- close: mock(() => {
+ once: vi.fn(() => {}) as BrowserWindowLike['once'],
+ close: vi.fn(() => {
destroyed = true;
fireClose();
}),
- destroy: mock(() => {
+ destroy: vi.fn(() => {
destroyed = true;
fireClose();
}),
webContents: {
- send: mock((channel: string, payload: unknown) => {
+ send: vi.fn((channel: string, payload: unknown) => {
sent.push({ channel, payload });
}),
- once: mock((event: 'dom-ready' | 'did-finish-load', cb: () => void) => {
+ once: vi.fn((event: 'dom-ready' | 'did-finish-load', cb: () => void) => {
if (event === 'dom-ready') domReadyHandler = cb;
}),
isDestroyed: () => destroyed,
},
- loadFile: mock(() => Promise.resolve()),
- loadURL: mock(() => Promise.resolve()),
+ loadFile: vi.fn(() => Promise.resolve()),
+ loadURL: vi.fn(() => Promise.resolve()),
fireClose,
fireDomReady: () => domReadyHandler?.(),
sent,
@@ -350,7 +350,7 @@ describe('createEphemeralWindow', () => {
env.deps.createWindow = (opts) => {
env.createWindowOpts.push(opts);
const w = makeWindow();
- w.loadFile = mock(() => Promise.reject(new Error('renderer load boom')));
+ w.loadFile = vi.fn(() => Promise.reject(new Error('renderer load boom')));
env.windows.push(w);
return w;
};
diff --git a/packages/desktop/tests/main/window-manager-safety-net.test.ts b/packages/desktop/tests/main/window-manager-safety-net.test.ts
index c3820bc25..83e3ac94f 100644
--- a/packages/desktop/tests/main/window-manager-safety-net.test.ts
+++ b/packages/desktop/tests/main/window-manager-safety-net.test.ts
@@ -25,8 +25,8 @@
* of the factory's own logic.
*/
-import { describe, expect, mock, test } from 'bun:test';
import { getLocalDir } from '@inkeep/open-knowledge-server';
+import { describe, expect, test, vi } from 'vitest';
import type { AssetOpenResult } from '../../src/main/asset-allowlist.ts';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import {
@@ -52,14 +52,14 @@ function makeUtility(pid: number): MockUtility {
let exitHandler: ((c: number | null) => void) | null = null;
return {
pid,
- postMessage: mock(() => {}),
- on: mock((event: 'message' | 'exit', cb: (msg: unknown) => void) => {
+ postMessage: vi.fn(() => {}),
+ on: vi.fn((event: 'message' | 'exit', cb: (msg: unknown) => void) => {
if (event === 'message') messageHandler = cb;
else if (event === 'exit') exitHandler = cb as (c: number | null) => void;
}) as UtilityProcessLike['on'],
- once: mock(() => {}),
- removeListener: mock(() => {}),
- kill: mock(() => true),
+ once: vi.fn(() => {}),
+ removeListener: vi.fn(() => {}),
+ kill: vi.fn(() => true),
fire: (msg) => messageHandler?.(msg),
fireExit: (code) => exitHandler?.(code),
};
@@ -81,41 +81,41 @@ function makeWindow(): SafetyNetWindow {
let destroyed = false;
let visible = false;
const win: SafetyNetWindow = {
- focus: mock(() => {}),
- show: mock(() => {
+ focus: vi.fn(() => {}),
+ show: vi.fn(() => {
visible = true;
}),
- restore: mock(() => {}),
- isMinimized: mock(() => false),
- moveTop: mock(() => {}),
- isFocused: mock(() => false),
- isDestroyed: mock(() => destroyed),
- isVisible: mock(() => visible),
- on: mock((_event: 'closed', cb: () => void) => {
+ restore: vi.fn(() => {}),
+ isMinimized: vi.fn(() => false),
+ moveTop: vi.fn(() => {}),
+ isFocused: vi.fn(() => false),
+ isDestroyed: vi.fn(() => destroyed),
+ isVisible: vi.fn(() => visible),
+ on: vi.fn((_event: 'closed', cb: () => void) => {
closeHandlers.push(cb);
}) as BrowserWindowLike['on'],
- once: mock((_event: 'ready-to-show', _cb: () => void) => {}) as BrowserWindowLike['once'],
- close: mock(() => {
+ once: vi.fn((_event: 'ready-to-show', _cb: () => void) => {}) as BrowserWindowLike['once'],
+ close: vi.fn(() => {
destroyed = true;
for (const h of closeHandlers) h();
}),
- destroy: mock(() => {
+ destroy: vi.fn(() => {
destroyed = true;
for (const h of closeHandlers) h();
}),
webContents: {
- send: mock(() => {}),
- once: mock(() => {}),
- executeJavaScript: mock(() => Promise.resolve(undefined)),
- setWindowOpenHandler: mock((handler: WindowOpenHandler) => {
+ send: vi.fn(() => {}),
+ once: vi.fn(() => {}),
+ executeJavaScript: vi.fn(() => Promise.resolve(undefined)),
+ setWindowOpenHandler: vi.fn((handler: WindowOpenHandler) => {
win.windowOpenHandler = handler;
}),
- on: mock((event: 'will-navigate', handler: WillNavigateHandler) => {
+ on: vi.fn((event: 'will-navigate', handler: WillNavigateHandler) => {
if (event === 'will-navigate') win.willNavigateHandler = handler;
}),
} as unknown as BrowserWindowLike['webContents'],
- loadFile: mock(() => Promise.resolve()),
- loadURL: mock(() => Promise.resolve()),
+ loadFile: vi.fn(() => Promise.resolve()),
+ loadURL: vi.fn(() => Promise.resolve()),
fireClose: () => {
for (const h of closeHandlers) h();
},
@@ -128,8 +128,8 @@ function makeWindow(): SafetyNetWindow {
interface TestEnv {
utilities: MockUtility[];
windows: SafetyNetWindow[];
- openExternal: ReturnType<typeof mock>;
- openAsset: ReturnType<typeof mock>;
+ openExternal: ReturnType<typeof vi.fn>;
+ openAsset: ReturnType<typeof vi.fn>;
deps: WindowManagerDeps;
}
@@ -144,8 +144,8 @@ function buildEnv(): TestEnv {
// The two boundary delegates the safety net needs. `openAsset` is 2-arg
// (`projectPath`, `relPath`) — matching `WindowManagerDeps.safetyNet.openAsset`
// and the `attachSafetyNet` call `net.openAsset(assetRoot, relPath)`.
- const openExternal = mock(async (_url: string): Promise<void> => {});
- const openAsset = mock(
+ const openExternal = vi.fn(async (_url: string): Promise<void> => {});
+ const openAsset = vi.fn(
async (_projectPath: string, _relPath: string): Promise<AssetOpenResult> => ({ ok: true }),
);
const deps: WindowManagerDeps = {
@@ -163,7 +163,7 @@ function buildEnv(): TestEnv {
rendererEntryPath: '/fake/renderer/index.html',
appVersion: '9.9.9-test',
setTimeout: () => null,
- killProbe: mock(() => {}),
+ killProbe: vi.fn(() => {}),
showGate,
// The ephemeral / detached-spawn deps are wired PER-TEST (createEphemeral
// and restart only). Leaving them off the base keeps the spawn test on the
@@ -215,7 +215,7 @@ const EXTERNAL_URL = 'https://example.com/watch';
*/
async function expectExternalSafetyNet(
window: SafetyNetWindow,
- openExternal: ReturnType<typeof mock>,
+ openExternal: ReturnType<typeof vi.fn>,
): Promise<void> {
// The factory installed a window-open handler on the created window.
expect(window.windowOpenHandler).not.toBeNull();
@@ -292,7 +292,7 @@ describe('WindowManager factory attaches the external-link safety net', () => {
env.deps.isProcessAlive = (pid) => (pid === 5555 ? !killed : true);
env.deps.hostname = () => 'my-host';
env.deps.probeWsUpgrade = () => Promise.resolve(true);
- env.deps.killProbe = mock((_pid: number, signal: number | NodeJS.Signals) => {
+ env.deps.killProbe = vi.fn((_pid: number, signal: number | NodeJS.Signals) => {
if (signal === 'SIGTERM') killed = true;
});
env.deps.spawnDetachedServer = async () => {
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index 5be7575e6..18ea54960 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -1,8 +1,8 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import {
type BrowserWindowLike,
@@ -33,14 +33,14 @@ function makeUtility(pid: number): MockUtility {
let exitHandler: ((c: number | null) => void) | null = null;
return {
pid,
- postMessage: mock(() => {}),
- on: mock((event: 'message' | 'exit', cb: (msg: unknown) => void) => {
+ postMessage: vi.fn(() => {}),
+ on: vi.fn((event: 'message' | 'exit', cb: (msg: unknown) => void) => {
if (event === 'message') messageHandler = cb;
else if (event === 'exit') exitHandler = cb as (c: number | null) => void;
}) as UtilityProcessLike['on'],
- once: mock(() => {}),
- removeListener: mock(() => {}),
- kill: mock(() => true),
+ once: vi.fn(() => {}),
+ removeListener: vi.fn(() => {}),
+ kill: vi.fn(() => true),
fire: (msg) => messageHandler?.(msg),
fireExit: (code) => exitHandler?.(code),
};
@@ -65,39 +65,39 @@ function makeWindow(opts?: { minimized?: boolean; focused?: boolean }): BrowserW
for (const h of closeHandlers) h();
};
return {
- focus: mock(() => {}),
- show: mock(() => {
+ focus: vi.fn(() => {}),
+ show: vi.fn(() => {
visible = true;
}),
- restore: mock(() => {
+ restore: vi.fn(() => {
minimized = false;
}),
- isMinimized: mock(() => minimized),
- moveTop: mock(() => {}),
- isFocused: mock(() => opts?.focused ?? false),
- isDestroyed: mock(() => destroyed),
- isVisible: mock(() => visible),
- on: mock((_event: 'closed', cb: () => void) => {
+ isMinimized: vi.fn(() => minimized),
+ moveTop: vi.fn(() => {}),
+ isFocused: vi.fn(() => opts?.focused ?? false),
+ isDestroyed: vi.fn(() => destroyed),
+ isVisible: vi.fn(() => visible),
+ on: vi.fn((_event: 'closed', cb: () => void) => {
closeHandlers.push(cb);
}) as BrowserWindowLike['on'],
- once: mock((_event: 'ready-to-show', _cb: () => void) => {}) as BrowserWindowLike['once'],
- close: mock(() => {
+ once: vi.fn((_event: 'ready-to-show', _cb: () => void) => {}) as BrowserWindowLike['once'],
+ close: vi.fn(() => {
destroyed = true;
fireClose();
}),
- destroy: mock(() => {
+ destroy: vi.fn(() => {
destroyed = true;
fireClose();
}),
webContents: {
- send: mock(() => {}),
- once: mock((event: 'dom-ready' | 'did-finish-load', cb: () => void) => {
+ send: vi.fn(() => {}),
+ once: vi.fn((event: 'dom-ready' | 'did-finish-load', cb: () => void) => {
if (event === 'dom-ready') domReadyHandler = cb;
else if (event === 'did-finish-load') didFinishLoadHandler = cb;
}),
},
- loadFile: mock(() => Promise.resolve()),
- loadURL: mock(() => Promise.resolve()),
+ loadFile: vi.fn(() => Promise.resolve()),
+ loadURL: vi.fn(() => Promise.resolve()),
fireClose,
markDestroyed: () => {
destroyed = true;
@@ -124,8 +124,8 @@ interface TestEnv {
}>;
forkUtilityArgs: string[][];
timers: Array<{ cb: () => void; ms: number }>;
- killProbe: ReturnType<typeof mock>;
- activateApp: ReturnType<typeof mock>;
+ killProbe: ReturnType<typeof vi.fn>;
+ activateApp: ReturnType<typeof vi.fn>;
showGateRegistrations: ShowGateRegistration[];
deps: WindowManagerDeps;
}
@@ -140,8 +140,8 @@ function buildEnv(): TestEnv {
}> = [];
const forkUtilityArgs: string[][] = [];
const timers: Array<{ cb: () => void; ms: number }> = [];
- const killProbe = mock(() => {});
- const activateApp = mock(() => {});
+ const killProbe = vi.fn(() => {});
+ const activateApp = vi.fn(() => {});
const showGateRegistrations: ShowGateRegistration[] = [];
// Test stub for the show-gate — captures register() calls and immediately
// signals the dual-signal contract so existing tests that rely on `show()`
@@ -534,7 +534,7 @@ describe('WindowManager', () => {
});
test('liveness probe is silent if pid is truly gone (probe throws)', async () => {
- env.killProbe = mock(() => {
+ env.killProbe = vi.fn(() => {
throw new Error('No such process');
});
env.deps.killProbe = env.killProbe;
@@ -553,7 +553,7 @@ describe('WindowManager', () => {
});
test('runClean (when provided) is called before forking utility', async () => {
- const runClean = mock(() => Promise.resolve());
+ const runClean = vi.fn(() => Promise.resolve());
env.deps.runClean = runClean;
const wm = new WindowManager(env.deps);
const promise = wm.createProjectWindow({ projectPath: '/tmp/clean-run' });
@@ -589,7 +589,7 @@ describe('WindowManager', () => {
// (ERR_IPC_CHANNEL_CLOSED in production).
const utility = env.utilities[0];
if (!utility) throw new Error('utility missing');
- utility.postMessage = mock(() => {
+ utility.postMessage = vi.fn(() => {
throw new Error('ERR_IPC_CHANNEL_CLOSED');
});
@@ -717,7 +717,7 @@ describe('WindowManager', () => {
test('attaches to live same-host lock — no utility forked', async () => {
enableAttachProbe();
- const runClean = mock(() => Promise.resolve());
+ const runClean = vi.fn(() => Promise.resolve());
env.deps.runClean = runClean;
const wm = new WindowManager(env.deps);
@@ -764,7 +764,7 @@ describe('WindowManager', () => {
});
function driftSends(w: ReturnType<typeof makeWindow>): unknown[] {
- return (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ return (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-version-drift',
);
}
@@ -849,7 +849,7 @@ describe('WindowManager', () => {
protocolVersion: 1,
runtimeVersion: '0.8.2',
};
- const killProbe = mock((_pid: number, signal: string) => {
+ const killProbe = vi.fn((_pid: number, signal: string) => {
if (signal === 'SIGTERM') killed = true;
});
enableAttachProbe({
@@ -886,7 +886,7 @@ describe('WindowManager', () => {
// The recreated window confirms the restart on did-finish-load.
newWindow.fireDidFinishLoad();
const restartedSends = (
- newWindow.webContents.send as ReturnType<typeof mock>
+ newWindow.webContents.send as ReturnType<typeof vi.fn>
).mock.calls.filter((c: unknown[]) => c[0] === 'ok:server-restarted');
expect(restartedSends.length).toBe(1);
expect((restartedSends[0] as unknown[])[1]).toEqual({ appRuntime: '0.8.2' });
@@ -895,7 +895,7 @@ describe('WindowManager', () => {
test('restartAttachedServer returns eperm without recreating when the kill is blocked', async () => {
const lockWithPid = { ...liveLock, pid: 7777, protocolVersion: 1, runtimeVersion: '0.8.0' };
env.deps.readServerLock = () => lockWithPid;
- env.deps.killProbe = mock(() => {
+ env.deps.killProbe = vi.fn(() => {
const err = new Error('operation not permitted') as NodeJS.ErrnoException;
err.code = 'EPERM';
throw err;
@@ -920,7 +920,7 @@ describe('WindowManager', () => {
readServerLock: () => (killed ? null : oldLock),
isProcessAlive: (pid) => (pid === 5555 ? !killed : true),
});
- env.deps.killProbe = mock((_pid: number, signal: string) => {
+ env.deps.killProbe = vi.fn((_pid: number, signal: string) => {
if (signal === 'SIGTERM') killed = true;
});
env.deps.spawnDetachedServer = async () => {
@@ -936,7 +936,7 @@ describe('WindowManager', () => {
const outcome = await wm.restartAttachedServer('/tmp/dragon');
expect(outcome).toEqual({ ok: false, reason: 'other' });
// The originating window was not closed and remains the project's window.
- expect((originating.close as ReturnType<typeof mock>).mock.calls.length).toBe(0);
+ expect((originating.close as ReturnType<typeof vi.fn>).mock.calls.length).toBe(0);
expect(originating.isDestroyed?.()).toBe(false);
expect(wm.getContextForBrowserWindow(originating as BrowserWindowLike)?.projectPath).toBe(
'/tmp/dragon',
@@ -948,7 +948,7 @@ describe('WindowManager', () => {
test('reclaimForeignServerInDev terminates a foreign server and spawns fresh via utility-fork, SILENTLY (no notice)', async () => {
env.deps.reclaimForeignServerInDev = true;
let killed = false;
- const killProbe = mock((_pid: number, signal: string) => {
+ const killProbe = vi.fn((_pid: number, signal: string) => {
if (signal === 'SIGTERM') killed = true;
});
env.deps.killProbe = killProbe;
@@ -982,14 +982,14 @@ describe('WindowManager', () => {
// reaches the renderer (the "started a fresh server" notice is gone).
w.fireDomReady();
w.fireDidFinishLoad();
- const lifecycleSends = (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ const lifecycleSends = (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-restarted',
);
expect(lifecycleSends.length).toBe(0);
});
test('without reclaimForeignServerInDev (production default), a foreign server is attached — no termination, no notice', async () => {
- const killProbe = mock(() => {});
+ const killProbe = vi.fn(() => {});
env.deps.killProbe = killProbe;
enableAttachProbe();
const wm = new WindowManager(env.deps);
@@ -1001,7 +1001,7 @@ describe('WindowManager', () => {
const w = env.windows[0];
if (!w) throw new Error('no window created');
w.fireDidFinishLoad();
- const lifecycleSends = (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ const lifecycleSends = (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-restarted',
);
expect(lifecycleSends.length).toBe(0);
@@ -1026,7 +1026,7 @@ describe('WindowManager', () => {
protocolVersion: 1,
runtimeVersion: '0.8.2',
};
- const killProbe = mock((_pid: number, signal: string) => {
+ const killProbe = vi.fn((_pid: number, signal: string) => {
if (signal === 'SIGTERM') killed = true;
});
enableAttachProbe({
@@ -1054,7 +1054,7 @@ describe('WindowManager', () => {
w.fireDomReady();
expect(driftSends(w).length).toBe(0);
w.fireDidFinishLoad();
- const restartedSends = (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ const restartedSends = (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-restarted',
);
expect(restartedSends.length).toBe(0);
@@ -1076,7 +1076,7 @@ describe('WindowManager', () => {
protocolVersion: 1,
runtimeVersion: '0.8.2',
};
- const killProbe = mock((_pid: number, signal: string) => {
+ const killProbe = vi.fn((_pid: number, signal: string) => {
if (signal === 'SIGTERM') killed = true;
});
enableAttachProbe({
@@ -1100,7 +1100,7 @@ describe('WindowManager', () => {
env.deps.selfProtocolVersion = 1;
env.deps.selfRuntimeVersion = '0.8.2';
env.deps.isFirstLaunchAfterUpgrade = () => true;
- const killProbe = mock(() => {});
+ const killProbe = vi.fn(() => {});
env.deps.killProbe = killProbe;
enableAttachProbe({
readServerLock: () => ({ ...liveLock, protocolVersion: 1, runtimeVersion: '0.8.2' }),
@@ -1124,7 +1124,7 @@ describe('WindowManager', () => {
env.deps.selfProtocolVersion = 1;
env.deps.selfRuntimeVersion = '0.8.2';
// isFirstLaunchAfterUpgrade left unset (undefined).
- const killProbe = mock(() => {});
+ const killProbe = vi.fn(() => {});
env.deps.killProbe = killProbe;
enableAttachProbe({
readServerLock: () => ({ ...liveLock, protocolVersion: 1, runtimeVersion: '0.8.0' }),
@@ -1140,7 +1140,7 @@ describe('WindowManager', () => {
// The manual version-drift prompt fires; no auto-restart confirmation.
expect(driftSends(w).length).toBe(1);
w.fireDidFinishLoad();
- const restartedSends = (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ const restartedSends = (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-restarted',
);
expect(restartedSends.length).toBe(0);
@@ -1154,7 +1154,7 @@ describe('WindowManager', () => {
env.deps.selfProtocolVersion = 1;
env.deps.selfRuntimeVersion = '0.8.2';
env.deps.isFirstLaunchAfterUpgrade = () => true;
- env.deps.killProbe = mock(() => {
+ env.deps.killProbe = vi.fn(() => {
const err = new Error('operation not permitted') as NodeJS.ErrnoException;
err.code = 'EPERM';
throw err;
@@ -1174,7 +1174,7 @@ describe('WindowManager', () => {
// The manual version-drift prompt is the fallback remedy.
expect(driftSends(w).length).toBe(1);
w.fireDidFinishLoad();
- const restartedSends = (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ const restartedSends = (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-restarted',
);
expect(restartedSends.length).toBe(0);
@@ -1185,7 +1185,7 @@ describe('WindowManager', () => {
// but the pid guard must hold if a future build does: a same-session
// reopen that attaches to OUR OWN detached server must not be reclaimed.
env.deps.reclaimForeignServerInDev = true;
- const killProbe = mock(() => {});
+ const killProbe = vi.fn(() => {});
env.deps.killProbe = killProbe;
const ownLock = { ...liveLock, pid: 6666, port: 60000 };
let spawned = false;
@@ -1214,7 +1214,7 @@ describe('WindowManager', () => {
test('reclaim falls back to attaching when terminating the foreign server fails (eperm)', async () => {
env.deps.reclaimForeignServerInDev = true;
- env.deps.killProbe = mock(() => {
+ env.deps.killProbe = vi.fn(() => {
const err = new Error('operation not permitted') as NodeJS.ErrnoException;
err.code = 'EPERM';
throw err;
@@ -1229,7 +1229,7 @@ describe('WindowManager', () => {
const w = env.windows[0];
if (!w) throw new Error('no window created');
w.fireDidFinishLoad();
- const restartedSends = (w.webContents.send as ReturnType<typeof mock>).mock.calls.filter(
+ const restartedSends = (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-restarted',
);
expect(restartedSends.length).toBe(0);
@@ -1237,7 +1237,7 @@ describe('WindowManager', () => {
test('stale lock (pid dead) falls through to spawn mode', async () => {
enableAttachProbe({ isProcessAlive: () => false });
- const runClean = mock(() => Promise.resolve());
+ const runClean = vi.fn(() => Promise.resolve());
env.deps.runClean = runClean;
const wm = new WindowManager(env.deps);
@@ -1421,7 +1421,7 @@ describe('WindowManager', () => {
env.deps.hostname = () => 'my-host';
env.deps.probeWsUpgrade = () => Promise.resolve(true);
- const spawn = mock(() => Promise.resolve({ pid: 88001 }));
+ const spawn = vi.fn(() => Promise.resolve({ pid: 88001 }));
env.deps.spawnDetachedServer = spawn;
const wm = new WindowManager(env.deps);
@@ -1561,7 +1561,7 @@ describe('WindowManager', () => {
env.deps.isProcessAlive = () => true;
env.deps.hostname = () => 'my-host';
env.deps.probeWsUpgrade = () => Promise.resolve(true);
- const spawn = mock(() => Promise.resolve({ pid: 91001 }));
+ const spawn = vi.fn(() => Promise.resolve({ pid: 91001 }));
env.deps.spawnDetachedServer = spawn;
const wm = new WindowManager(env.deps);
@@ -1582,7 +1582,7 @@ describe('WindowManager', () => {
env.deps.isProcessAlive = () => true;
env.deps.hostname = () => 'my-host';
env.deps.probeWsUpgrade = () => Promise.resolve(true);
- const spawn = mock(() => Promise.resolve({ pid: 99 }));
+ const spawn = vi.fn(() => Promise.resolve({ pid: 99 }));
env.deps.spawnDetachedServer = spawn;
const wm = new WindowManager(env.deps);
@@ -1680,7 +1680,7 @@ describe('WindowManager', () => {
function makeKeepaliveMock() {
const calls: Array<{ lockDir: string }> = [];
const handles: Array<{ closed: boolean }> = [];
- const create = mock((opts: { lockDir: string }) => {
+ const create = vi.fn((opts: { lockDir: string }) => {
calls.push(opts);
const handle = { closed: false };
handles.push(handle);
@@ -1964,7 +1964,7 @@ describe('WindowManager', () => {
});
test('WS-upgrade probe failure falls through to spawn mode', async () => {
- const probe = mock(() => Promise.resolve(false));
+ const probe = vi.fn(() => Promise.resolve(false));
enableAttachProbe({ probeWsUpgrade: probe });
const wm = new WindowManager(env.deps);
const p = wm.createProjectWindow({ projectPath: '/tmp/dragon' });
@@ -1977,7 +1977,7 @@ describe('WindowManager', () => {
});
test('WS-upgrade probe rejection (thrown error) falls through to spawn mode', async () => {
- const probe = mock(() => Promise.reject(new Error('socket refused')));
+ const probe = vi.fn(() => Promise.reject(new Error('socket refused')));
enableAttachProbe({ probeWsUpgrade: probe });
const wm = new WindowManager(env.deps);
const p = wm.createProjectWindow({ projectPath: '/tmp/dragon' });
@@ -2162,7 +2162,7 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
baseOnce(event, cb);
}) as typeof w.webContents.once;
const baseLoadFile = w.loadFile as () => Promise<void>;
- w.loadFile = mock(async () => {
+ w.loadFile = vi.fn(async () => {
onceCalledBeforeLoadResolved = domReadyRegistrations > 0;
return baseLoadFile();
}) as typeof w.loadFile;
@@ -2184,9 +2184,9 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
if (!window) throw new Error('expected window to be created');
// dom-ready callback sends the deep-link event.
- expect((window.webContents.send as ReturnType<typeof mock>).mock.calls.length).toBe(0);
+ expect((window.webContents.send as ReturnType<typeof vi.fn>).mock.calls.length).toBe(0);
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
const deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');
expect(deepLinkCall).toBeDefined();
expect(deepLinkCall?.[1]).toEqual({
@@ -2206,7 +2206,7 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
expect(sendCalls.find((c) => c[0] === 'ok:deep-link')).toBeUndefined();
});
@@ -2237,7 +2237,7 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
const deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');
expect(deepLinkCall).toBeDefined();
expect(deepLinkCall?.[1]).toEqual({
@@ -2264,7 +2264,7 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
const deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');
expect(deepLinkCall?.[1]).toEqual({
doc: 'docs/page.md',
@@ -2299,7 +2299,7 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
const deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');
expect(deepLinkCall?.[1]).toEqual({
doc: 'attached/note',
@@ -2324,7 +2324,7 @@ describe('WindowManager — pendingDeepLinkTarget dom-ready gate (M4 US-007 / Fi
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
const deepLinkCall = sendCalls.find((c) => c[0] === 'ok:deep-link');
expect(deepLinkCall?.[1]).toEqual({
doc: 'docs',
@@ -2360,7 +2360,7 @@ describe('WindowManager — pendingShareBranchSwitch dom-ready gate (US-004)', (
baseOnce(event, cb);
}) as typeof w.webContents.once;
const baseLoadFile = w.loadFile as () => Promise<void>;
- w.loadFile = mock(async () => {
+ w.loadFile = vi.fn(async () => {
onceCalledBeforeLoadResolved = domReadyRegistrations > 0;
return baseLoadFile();
}) as typeof w.loadFile;
@@ -2393,13 +2393,13 @@ describe('WindowManager — pendingShareBranchSwitch dom-ready gate (US-004)', (
// No send fires until dom-ready signal arrives.
expect(
- (window.webContents.send as ReturnType<typeof mock>).mock.calls.find(
+ (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls.find(
(c) => c[0] === 'ok:share:received',
),
).toBeUndefined();
window.fireDomReady();
- const shareCall = (window.webContents.send as ReturnType<typeof mock>).mock.calls.find(
+ const shareCall = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls.find(
(c) => c[0] === 'ok:share:received',
);
expect(shareCall).toBeDefined();
@@ -2426,7 +2426,7 @@ describe('WindowManager — pendingShareBranchSwitch dom-ready gate (US-004)', (
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const sendCalls = (window.webContents.send as ReturnType<typeof mock>).mock.calls;
+ const sendCalls = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls;
expect(sendCalls.find((c) => c[0] === 'ok:share:received')).toBeUndefined();
});
@@ -2452,7 +2452,7 @@ describe('WindowManager — pendingShareBranchSwitch dom-ready gate (US-004)', (
baseOnce(event, cb);
}) as typeof w.webContents.once;
const baseLoadFile = w.loadFile as () => Promise<void>;
- w.loadFile = mock(async () => {
+ w.loadFile = vi.fn(async () => {
onceCalledBeforeLoadResolved = domReadyRegistrations > 0;
return baseLoadFile();
}) as typeof w.loadFile;
@@ -2495,7 +2495,7 @@ describe('WindowManager — pendingShareBranchSwitch dom-ready gate (US-004)', (
const window = env.windows[0];
if (!window) throw new Error('expected window to be created');
window.fireDomReady();
- const shareCall = (window.webContents.send as ReturnType<typeof mock>).mock.calls.find(
+ const shareCall = (window.webContents.send as ReturnType<typeof vi.fn>).mock.calls.find(
(c) => c[0] === 'ok:share:received',
);
expect(shareCall).toBeDefined();
diff --git a/packages/desktop/tests/preload/bridge.test.ts b/packages/desktop/tests/preload/bridge.test.ts
index 0dedfffc2..1da38b9c3 100644
--- a/packages/desktop/tests/preload/bridge.test.ts
+++ b/packages/desktop/tests/preload/bridge.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, mock, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
import { createInvoker } from '../../src/shared/ipc-invoke.ts';
/**
@@ -18,7 +18,7 @@ import { createInvoker } from '../../src/shared/ipc-invoke.ts';
describe('createInvoker (typed IPC factory)', () => {
test('forwards channel + args to ipcRenderer.invoke verbatim', async () => {
- const invoke = mock((channel: string, ...args: unknown[]) =>
+ const invoke = vi.fn((channel: string, ...args: unknown[]) =>
Promise.resolve({ channel, args }),
);
// biome-ignore lint/suspicious/noExplicitAny: minimal IpcRenderer-compatible mock
@@ -30,7 +30,7 @@ describe('createInvoker (typed IPC factory)', () => {
});
test('passes positional args through (e.g., shell.openExternal URL)', async () => {
- const invoke = mock((channel: string, ...args: unknown[]) =>
+ const invoke = vi.fn((channel: string, ...args: unknown[]) =>
Promise.resolve({ channel, args }),
);
// biome-ignore lint/suspicious/noExplicitAny: minimal IpcRenderer-compatible mock
@@ -41,7 +41,7 @@ describe('createInvoker (typed IPC factory)', () => {
});
test('return type is awaited from invoke', async () => {
- const invoke = mock(() => Promise.resolve('/Users/test/picked-folder'));
+ const invoke = vi.fn(() => Promise.resolve('/Users/test/picked-folder'));
// biome-ignore lint/suspicious/noExplicitAny: minimal IpcRenderer-compatible mock
const fakeIpc = { invoke } as any;
const typedInvoker = createInvoker(fakeIpc);
diff --git a/packages/desktop/tests/preload/update-listeners.test.ts b/packages/desktop/tests/preload/update-listeners.test.ts
index ecfc596cd..35e223122 100644
--- a/packages/desktop/tests/preload/update-listeners.test.ts
+++ b/packages/desktop/tests/preload/update-listeners.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from 'bun:test';
+import { describe, expect, test, vi } from 'vitest';
/**
* update-listener preload-pattern test.
@@ -24,18 +24,18 @@ import { describe, expect, mock, test } from 'bun:test';
type FakeListener = (_event: unknown, payload: unknown) => void;
interface FakeIpcRenderer {
- on: ReturnType<typeof mock>;
- removeListener: ReturnType<typeof mock>;
+ on: ReturnType<typeof vi.fn>;
+ removeListener: ReturnType<typeof vi.fn>;
}
function makeFakeIpc(): FakeIpcRenderer {
const listeners = new Map<string, Set<FakeListener>>();
return {
- on: mock((channel: string, listener: FakeListener) => {
+ on: vi.fn((channel: string, listener: FakeListener) => {
if (!listeners.has(channel)) listeners.set(channel, new Set());
listeners.get(channel)?.add(listener);
}),
- removeListener: mock((channel: string, listener: FakeListener) => {
+ removeListener: vi.fn((channel: string, listener: FakeListener) => {
listeners.get(channel)?.delete(listener);
}),
};
@@ -61,7 +61,7 @@ function createUpdateSubscription<T>(
describe('M3 update-listener subscribe/unsubscribe pattern', () => {
test('onUpdateDownloaded subscription registers on correct channel', () => {
const ipc = makeFakeIpc();
- const cb = mock(() => {});
+ const cb = vi.fn(() => {});
createUpdateSubscription(ipc, 'ok:update:downloaded', cb);
expect(ipc.on).toHaveBeenCalledTimes(1);
expect(ipc.on.mock.calls[0]?.[0]).toBe('ok:update:downloaded');
@@ -69,7 +69,7 @@ describe('M3 update-listener subscribe/unsubscribe pattern', () => {
test('unsubscribe closure detaches the listener by reference identity', () => {
const ipc = makeFakeIpc();
- const cb = mock(() => {});
+ const cb = vi.fn(() => {});
const unsubscribe = createUpdateSubscription(ipc, 'ok:update:downloaded', cb);
// Capture the wrapper that was registered.
@@ -86,7 +86,7 @@ describe('M3 update-listener subscribe/unsubscribe pattern', () => {
test('unsubscribe prevents callback from firing on subsequent events', () => {
const ipc = makeFakeIpc();
- const cb = mock(() => {});
+ const cb = vi.fn(() => {});
const unsubscribe = createUpdateSubscription<{ version: string }>(
ipc,
'ok:update:downloaded',
@@ -120,7 +120,7 @@ describe('M3 update-listener subscribe/unsubscribe pattern', () => {
] as const;
for (const channel of channels) {
const ipc = makeFakeIpc();
- const cb = mock(() => {});
+ const cb = vi.fn(() => {});
const unsubscribe = createUpdateSubscription(ipc, channel, cb);
expect(ipc.on.mock.calls[0]?.[0]).toBe(channel);
unsubscribe();
diff --git a/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts b/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts
index 1d19ba4e6..d97903ec1 100644
--- a/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/electron-cleanup.test.ts
@@ -34,8 +34,8 @@
* reaper without adding signal beyond the existing assertions.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { type ChildProcess, spawn } from 'node:child_process';
+import { afterEach, describe, expect, test } from 'vitest';
import { closeAppBounded } from './electron-cleanup';
/**
diff --git a/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts b/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts
index 35c8a3f6d..3c6629e09 100644
--- a/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/no-unbounded-app-close.test.ts
@@ -39,9 +39,9 @@
* so any future re-introduction has a complete inventory to walk.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { stripCommentsAndStrings } from './parse-timeouts';
const SMOKE_DIR = join(__dirname, '..');
diff --git a/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts b/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts
index 0c4d6c33a..4c234a214 100644
--- a/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/parse-timeouts.test.ts
@@ -10,10 +10,10 @@
* current state.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import {
extractHelperBudgets,
extractTestEntries,
diff --git a/packages/desktop/tests/unit/auto-updater-apply-channel.test.ts b/packages/desktop/tests/unit/auto-updater-apply-channel.test.ts
index 3a2bb1713..e7113b27e 100644
--- a/packages/desktop/tests/unit/auto-updater-apply-channel.test.ts
+++ b/packages/desktop/tests/unit/auto-updater-apply-channel.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { applyChannelSettings, channelFromVersion } from '../../src/main/auto-updater.ts';
/**
diff --git a/packages/desktop/tests/unit/electron-builder-cli-pkgjson.test.ts b/packages/desktop/tests/unit/electron-builder-cli-pkgjson.test.ts
index fd31a2981..510cacc15 100644
--- a/packages/desktop/tests/unit/electron-builder-cli-pkgjson.test.ts
+++ b/packages/desktop/tests/unit/electron-builder-cli-pkgjson.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { parse } from 'yaml';
/**
diff --git a/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts b/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts
index a8af770ea..036e22901 100644
--- a/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts
+++ b/packages/desktop/tests/unit/electron-builder-node-pty-deps.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { parse } from 'yaml';
/**
diff --git a/packages/desktop/tests/unit/electron-builder-parcel-watcher-deps.test.ts b/packages/desktop/tests/unit/electron-builder-parcel-watcher-deps.test.ts
index 688863add..6eba53128 100644
--- a/packages/desktop/tests/unit/electron-builder-parcel-watcher-deps.test.ts
+++ b/packages/desktop/tests/unit/electron-builder-parcel-watcher-deps.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { parse } from 'yaml';
/**
diff --git a/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts b/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts
index 17f5c3f79..94ed2346d 100644
--- a/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts
+++ b/packages/desktop/tests/unit/electron-cleanup-bounded.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import type { ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
import type { ElectronApplication } from '@playwright/test';
+import { describe, expect, test } from 'vitest';
import { captureAppProcess, closeAppBounded } from '../smoke/_helpers/electron-cleanup';
/**
diff --git a/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts b/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts
index c25e8bcf4..3dbfd509f 100644
--- a/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts
+++ b/packages/desktop/tests/unit/ensure-node-pty-exec.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
ensureNodePtySpawnHelperExecutable,
ensureNodePtySpawnHelperExecutableInNodeModules,
diff --git a/packages/desktop/tests/unit/entitlements-helper-split.test.ts b/packages/desktop/tests/unit/entitlements-helper-split.test.ts
index 683079aff..158b89884 100644
--- a/packages/desktop/tests/unit/entitlements-helper-split.test.ts
+++ b/packages/desktop/tests/unit/entitlements-helper-split.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
/**
* Helper-process entitlements MUST NOT include restricted entitlements (those
diff --git a/packages/desktop/tests/unit/helper-bundle-info-plist.test.ts b/packages/desktop/tests/unit/helper-bundle-info-plist.test.ts
index dfa77717b..69d9cab5a 100644
--- a/packages/desktop/tests/unit/helper-bundle-info-plist.test.ts
+++ b/packages/desktop/tests/unit/helper-bundle-info-plist.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
/**
* Regression guard for the helper-bundle Info.plist shipped alongside the
diff --git a/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts b/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts
index 5e9ee3c7f..158627b9f 100644
--- a/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts
+++ b/packages/desktop/tests/unit/helper-bundle-name-agreement.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -6,6 +5,7 @@ import {
HELPER_BUNDLE_NAME,
HELPER_EXECUTABLE_NAME,
} from '@inkeep/open-knowledge-core/helper-bundle';
+import { describe, expect, test } from 'vitest';
/**
* Cross-reference regression guard: the FIVE independent sites that all
diff --git a/packages/desktop/tests/unit/local-op-types-drift.test.ts b/packages/desktop/tests/unit/local-op-types-drift.test.ts
index 33fac8a29..b3fc97720 100644
--- a/packages/desktop/tests/unit/local-op-types-drift.test.ts
+++ b/packages/desktop/tests/unit/local-op-types-drift.test.ts
@@ -21,13 +21,14 @@
* Failures surface during `turbo run typecheck` at the literal `true`
* assignment, not just at `bun test` execution time.
*/
-import { describe, expect, test } from 'bun:test';
+
import type {
AuthEvent,
AuthReposResponse,
AuthStatusResponse,
RawCloneEvent,
} from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
import type {
OkLocalOpAuthEvent,
OkLocalOpAuthReposResponse,
diff --git a/packages/desktop/tests/unit/scaffold.test.ts b/packages/desktop/tests/unit/scaffold.test.ts
index 292a665f7..93f10097b 100644
--- a/packages/desktop/tests/unit/scaffold.test.ts
+++ b/packages/desktop/tests/unit/scaffold.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
/**
* Scaffold placeholder test. Validates that the desktop package can
diff --git a/packages/desktop/tests/unit/smoke-test-fixture-attach-conditional.test.ts b/packages/desktop/tests/unit/smoke-test-fixture-attach-conditional.test.ts
index b85a65a13..d0bdb3faf 100644
--- a/packages/desktop/tests/unit/smoke-test-fixture-attach-conditional.test.ts
+++ b/packages/desktop/tests/unit/smoke-test-fixture-attach-conditional.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { TestInfo } from '@playwright/test';
+import { describe, expect, test } from 'vitest';
import { shouldAttachStderr } from '../smoke/_helpers/electron-stderr';
/**
diff --git a/packages/desktop/tests/unit/state-store-channel-fields.test.ts b/packages/desktop/tests/unit/state-store-channel-fields.test.ts
index 9ca7c48c9..dc16731cb 100644
--- a/packages/desktop/tests/unit/state-store-channel-fields.test.ts
+++ b/packages/desktop/tests/unit/state-store-channel-fields.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
CURRENT_SCHEMA_VERSION,
emptyState,
diff --git a/packages/desktop/tests/unit/state-store-m3-fields.test.ts b/packages/desktop/tests/unit/state-store-m3-fields.test.ts
index b19a4dfaf..8bc769b35 100644
--- a/packages/desktop/tests/unit/state-store-m3-fields.test.ts
+++ b/packages/desktop/tests/unit/state-store-m3-fields.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { emptyState, parseAppState } from '../../src/main/state-store.ts';
/**
diff --git a/packages/desktop/tests/unit/verify-keyring-driver.test.mjs b/packages/desktop/tests/unit/verify-keyring-driver.test.mjs
index 6bc9ed673..c5d05623d 100644
--- a/packages/desktop/tests/unit/verify-keyring-driver.test.mjs
+++ b/packages/desktop/tests/unit/verify-keyring-driver.test.mjs
@@ -1,6 +1,6 @@
-import { describe, expect, mock, test } from 'bun:test';
import { EventEmitter } from 'node:events';
import { setImmediate } from 'node:timers/promises';
+import { describe, expect, test, vi } from 'vitest';
import {
classifyInputPath,
parseArgs,
@@ -41,7 +41,7 @@ describe('classifyInputPath', () => {
describe('readSmokeResult', () => {
test('returns parsed JSON on success', async () => {
- const readFile = mock(() =>
+ const readFile = vi.fn(() =>
Promise.resolve('{"ok":true,"backend":"keyring","timestamp":"2026-04-21T00:00:00Z"}'),
);
const result = await readSmokeResult('/tmp/smoke.json', { readFile });
@@ -54,13 +54,13 @@ describe('readSmokeResult', () => {
test('returns null on ENOENT', async () => {
const err = Object.assign(new Error('file missing'), { code: 'ENOENT' });
- const readFile = mock(() => Promise.reject(err));
+ const readFile = vi.fn(() => Promise.reject(err));
const result = await readSmokeResult('/tmp/never-written.json', { readFile });
expect(result).toBeNull();
});
test('propagates non-ENOENT errors', async () => {
- const readFile = mock(() => Promise.reject(new Error('EACCES')));
+ const readFile = vi.fn(() => Promise.reject(new Error('EACCES')));
await expect(readSmokeResult('/tmp/x.json', { readFile })).rejects.toThrow('EACCES');
});
});
@@ -75,7 +75,7 @@ function fakeSpawn({ exitCode = 0, stderr = '', delayMs = 0 } = {}) {
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
- child.kill = mock(() => {});
+ child.kill = vi.fn(() => {});
setTimeout(() => {
if (stderr) child.stderr.emit('data', Buffer.from(stderr, 'utf-8'));
if (exitCode !== null) child.emit('exit', exitCode);
@@ -90,13 +90,13 @@ describe('runDriver (full orchestration)', () => {
return {
writeStream: (s) => messages.stdout.push(s),
errStream: (s) => messages.stderr.push(s),
- mkdtemp: mock(async () => '/tmp/ok-fake'),
- rm: mock(async () => {}),
- runCommand: mock(async () => {}),
- cp: mock(async () => {}),
- stat: mock(async () => ({})),
- listAppsInMount: mock(async () => ['OpenKnowledge.app']),
- readFile: mock(() =>
+ mkdtemp: vi.fn(async () => '/tmp/ok-fake'),
+ rm: vi.fn(async () => {}),
+ runCommand: vi.fn(async () => {}),
+ cp: vi.fn(async () => {}),
+ stat: vi.fn(async () => ({})),
+ listAppsInMount: vi.fn(async () => ['OpenKnowledge.app']),
+ readFile: vi.fn(() =>
Promise.resolve('{"ok":true,"backend":"keyring","durationMs":5,"timestamp":"t"}'),
),
spawn: fakeSpawn({ exitCode: 0 }),
@@ -117,7 +117,7 @@ describe('runDriver (full orchestration)', () => {
test('exit 1: ok:false result prints error + stderr tail', async () => {
const deps = fakeDeps({
- readFile: mock(() =>
+ readFile: vi.fn(() =>
Promise.resolve('{"ok":false,"error":"module not found","timestamp":"t"}'),
),
spawn: fakeSpawn({ exitCode: 1, stderr: 'fatal: dlopen failed\n' }),
@@ -143,7 +143,7 @@ describe('runDriver (full orchestration)', () => {
test('exit 3: app exits without writing OUT file', async () => {
const err = Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
const deps = fakeDeps({
- readFile: mock(() => Promise.reject(err)),
+ readFile: vi.fn(() => Promise.reject(err)),
spawn: fakeSpawn({ exitCode: 0, stderr: 'dying early\n' }),
});
const code = await runDriver(['node', 'script', '/tmp/app.app'], deps);
@@ -172,12 +172,12 @@ describe('runDriver (full orchestration)', () => {
});
test('.dmg input: runs hdiutil attach/detach + copies .app to tmp', async () => {
- const runCommand = mock(async () => {});
- const cp = mock(async () => {});
+ const runCommand = vi.fn(async () => {});
+ const cp = vi.fn(async () => {});
const deps = fakeDeps({
runCommand,
cp,
- listAppsInMount: mock(async () => ['OpenKnowledge.app']),
+ listAppsInMount: vi.fn(async () => ['OpenKnowledge.app']),
});
const code = await runDriver(['node', 'script', '/tmp/foo.dmg'], deps);
expect(code).toBe(0);
@@ -188,7 +188,7 @@ describe('runDriver (full orchestration)', () => {
test('.dmg input with empty mount rejects with driver error', async () => {
const deps = fakeDeps({
- listAppsInMount: mock(async () => []),
+ listAppsInMount: vi.fn(async () => []),
});
const code = await runDriver(['node', 'script', '/tmp/empty.dmg'], deps);
expect(code).toBe(1);
@@ -229,13 +229,13 @@ describe('runDriver (full orchestration)', () => {
exit: (code) => exits.push(code),
};
let runCommandCalls = 0;
- const runCommand = mock(async (cmd) => {
+ const runCommand = vi.fn(async (cmd) => {
runCommandCalls += 1;
// Simulate .dmg path so resolvedApp.cleanup has work to do (detach)
if (cmd === 'hdiutil' && runCommandCalls === 1) return; // attach
if (cmd === 'hdiutil' && runCommandCalls === 2) return; // detach (normal finally)
});
- const rm = mock(async () => {});
+ const rm = vi.fn(async () => {});
const deps = fakeDeps({
process: proc,
runCommand,
diff --git a/packages/desktop/tests/unit/verify-native-config-driver.test.mjs b/packages/desktop/tests/unit/verify-native-config-driver.test.mjs
index 6119585cd..930ec3923 100644
--- a/packages/desktop/tests/unit/verify-native-config-driver.test.mjs
+++ b/packages/desktop/tests/unit/verify-native-config-driver.test.mjs
@@ -1,7 +1,7 @@
-import { describe, expect, mock, test } from 'bun:test';
import { existsSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test, vi } from 'vitest';
import {
classifyInputPath,
loadAndRoundTrip,
@@ -44,14 +44,14 @@ describe('classifyInputPath', () => {
describe('resolveBundledNativeDirInDir', () => {
test('finds the loader at <dir>/dist/native', () => {
- const existsSyncMock = mock((p) => p === '/proj/dist/native/index.js');
+ const existsSyncMock = vi.fn((p) => p === '/proj/dist/native/index.js');
expect(resolveBundledNativeDirInDir('/proj', { existsSync: existsSyncMock })).toBe(
'/proj/dist/native',
);
});
test('finds the loader when <dir> is itself the native dir', () => {
- const existsSyncMock = mock((p) => p === '/proj/native/index.js');
+ const existsSyncMock = vi.fn((p) => p === '/proj/native/index.js');
// The first candidate '.' checks /proj/index.js (absent), then 'native'.
expect(resolveBundledNativeDirInDir('/proj', { existsSync: existsSyncMock })).toBe(
'/proj/native',
@@ -157,14 +157,14 @@ describe('runDriver (full orchestration)', () => {
});
test('.dmg input mounts, copies the .app, and detaches', async () => {
- const runCommand = mock(async () => {});
- const cpMock = mock(async () => {});
+ const runCommand = vi.fn(async () => {});
+ const cpMock = vi.fn(async () => {});
const deps = fakeDeps({
runCommand,
cp: cpMock,
- mkdtemp: mock(async () => '/tmp/ok-nc-fake'),
- rm: mock(async () => {}),
- listAppsInMount: mock(async () => ['OpenKnowledge.app']),
+ mkdtemp: vi.fn(async () => '/tmp/ok-nc-fake'),
+ rm: vi.fn(async () => {}),
+ listAppsInMount: vi.fn(async () => ['OpenKnowledge.app']),
existsSync: () => true,
});
expect(await runDriver(['node', 'script', '/tmp/build.dmg'], deps)).toBe(0);
diff --git a/packages/desktop/tests/utility/pty-flood.test.ts b/packages/desktop/tests/utility/pty-flood.test.ts
index a16574633..2150147fb 100644
--- a/packages/desktop/tests/utility/pty-flood.test.ts
+++ b/packages/desktop/tests/utility/pty-flood.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
/**
* Ship gate for the terminal's real-PTY output path: the no-precedent
diff --git a/packages/desktop/tests/utility/pty-host-real-io.test.ts b/packages/desktop/tests/utility/pty-host-real-io.test.ts
index 3365863e6..bf96bbcd5 100644
--- a/packages/desktop/tests/utility/pty-host-real-io.test.ts
+++ b/packages/desktop/tests/utility/pty-host-real-io.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
/**
* Gate wrapper for the real-shell-I/O seam. node-pty does not pump under Bun,
diff --git a/packages/desktop/tests/utility/pty-host-reap.test.ts b/packages/desktop/tests/utility/pty-host-reap.test.ts
index c9077c4fe..e047014fc 100644
--- a/packages/desktop/tests/utility/pty-host-reap.test.ts
+++ b/packages/desktop/tests/utility/pty-host-reap.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { spawn as nodeSpawn } from 'node:child_process';
import { once } from 'node:events';
import { Readable } from 'node:stream';
import { isProcessAlive } from '@inkeep/open-knowledge-server';
+import { describe, expect, test } from 'vitest';
/**
* No-orphan OUTCOME seam. Verifies the system property the feature requires:
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index d9498093b..44ddb346c 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildShellArgs,
buildShellEnv,
diff --git a/packages/desktop/tests/utility/server-entry.test.ts b/packages/desktop/tests/utility/server-entry.test.ts
index 67e86f8a9..c102270c8 100644
--- a/packages/desktop/tests/utility/server-entry.test.ts
+++ b/packages/desktop/tests/utility/server-entry.test.ts
@@ -1,10 +1,10 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { ConfigSchema } from '@inkeep/open-knowledge-server';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { KeyringSmokeResult } from '../../src/utility/keyring-smoke.ts';
import {
type PreparedBootEnvironment,
@@ -25,41 +25,41 @@ import {
*/
interface MockParentPort {
- on: ReturnType<typeof mock>;
- postMessage: ReturnType<typeof mock>;
+ on: ReturnType<typeof vi.fn>;
+ postMessage: ReturnType<typeof vi.fn>;
/** Helper — fire a message into the registered handler. */
fire: (msg: unknown) => void;
}
function mockParentPort(): MockParentPort {
let handler: ((event: { data: unknown }) => void) | null = null;
- const on = mock((_event: 'message', h: (event: { data: unknown }) => void) => {
+ const on = vi.fn((_event: 'message', h: (event: { data: unknown }) => void) => {
handler = h;
});
return {
on,
- postMessage: mock(() => {}),
+ postMessage: vi.fn(() => {}),
fire: (msg: unknown) => handler?.({ data: msg }),
};
}
interface MockEnv {
parentPort: MockParentPort;
- exit: ReturnType<typeof mock>;
- killProbe: ReturnType<typeof mock>;
+ exit: ReturnType<typeof vi.fn>;
+ killProbe: ReturnType<typeof vi.fn>;
signalHandlers: Map<string, () => void>;
intervals: Array<{ cb: () => void; ms: number }>;
- intervalCancel: ReturnType<typeof mock>;
+ intervalCancel: ReturnType<typeof vi.fn>;
}
function buildEnv(): MockEnv {
const env: MockEnv = {
parentPort: mockParentPort(),
- exit: mock(() => {}),
- killProbe: mock(() => {}),
+ exit: vi.fn(() => {}),
+ killProbe: vi.fn(() => {}),
signalHandlers: new Map(),
intervals: [],
- intervalCancel: mock(() => {}),
+ intervalCancel: vi.fn(() => {}),
};
return env;
}
@@ -81,7 +81,7 @@ function makeFakePrepared(overrides?: Partial<PreparedBootEnvironment>): Prepare
}
function fakePrepare(returnValue?: PreparedBootEnvironment) {
- return mock(() => Promise.resolve(returnValue ?? makeFakePrepared()));
+ return vi.fn(() => Promise.resolve(returnValue ?? makeFakePrepared()));
}
describe('setupUtility (IPC handshake + lifecycle)', () => {
@@ -94,11 +94,11 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
test('on init message: imports server, calls bootServer with M1 opt-outs, posts ready', async () => {
const fakeBooted = {
port: 51234,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
- const importServer = mock(() =>
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
+ const importServer = vi.fn(() =>
Promise.resolve({ bootServer } as unknown as typeof import('@inkeep/open-knowledge-server')),
);
const prepared = makeFakePrepared({ contentDir: '/fake/test-project', contentRoot: undefined });
@@ -112,7 +112,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(prepared),
});
@@ -150,7 +150,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
});
test('on init failure: posts error and exits non-zero', async () => {
- const importServer = mock(() => Promise.reject(new Error('boot failed')));
+ const importServer = vi.fn(() => Promise.reject(new Error('boot failed')));
const handle = setupUtility({
parentPort: env.parentPort,
importServer,
@@ -160,7 +160,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
});
@@ -176,10 +176,10 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
test('parent-death poll: triggers shutdown on EPERM/ESRCH', async () => {
const fakeBooted = {
port: 51234,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -197,7 +197,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
parentPollMs: 100,
prepareBootEnvironment: fakePrepare(),
@@ -216,9 +216,9 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
});
test('shutdown IPC: drains booted server then exits 0', async () => {
- const destroy = mock(() => Promise.resolve());
+ const destroy = vi.fn(() => Promise.resolve());
const fakeBooted = { port: 51234, destroy, degraded: [] as readonly string[] };
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -232,7 +232,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(),
});
@@ -255,9 +255,9 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
});
test('SIGTERM handler triggers same shutdown path as IPC', async () => {
- const destroy = mock(() => Promise.resolve());
+ const destroy = vi.fn(() => Promise.resolve());
const fakeBooted = { port: 51234, destroy, degraded: [] as readonly string[] };
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -271,7 +271,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(),
});
@@ -292,9 +292,9 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
});
test('shutdown is idempotent — multiple calls drain once', async () => {
- const destroy = mock(() => Promise.resolve());
+ const destroy = vi.fn(() => Promise.resolve());
const fakeBooted = { port: 51234, destroy, degraded: [] as readonly string[] };
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -308,7 +308,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(),
});
@@ -331,8 +331,8 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
durationMs: 12,
timestamp: '2026-04-21T00:00:00.000Z',
};
- const runSmoke = mock(() => Promise.resolve(smokeResult));
- const writeSmokeResult = mock(() => Promise.resolve());
+ const runSmoke = vi.fn(() => Promise.resolve(smokeResult));
+ const writeSmokeResult = vi.fn(() => Promise.resolve());
setupUtility({
parentPort: env.parentPort,
@@ -344,7 +344,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
runSmoke,
env: {
@@ -375,8 +375,8 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
durationMs: 5,
timestamp: '2026-04-21T00:00:00.000Z',
};
- const runSmoke = mock(() => Promise.resolve(smokeResult));
- const writeSmokeResult = mock(() => Promise.resolve());
+ const runSmoke = vi.fn(() => Promise.resolve(smokeResult));
+ const writeSmokeResult = vi.fn(() => Promise.resolve());
setupUtility({
parentPort: env.parentPort,
@@ -388,7 +388,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
runSmoke,
env: {
@@ -416,8 +416,8 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
durationMs: 8,
timestamp: '2026-04-21T00:00:00.000Z',
};
- const runSmoke = mock(() => Promise.resolve(smokeResult));
- const writeSmokeResult = mock(() => Promise.resolve());
+ const runSmoke = vi.fn(() => Promise.resolve(smokeResult));
+ const writeSmokeResult = vi.fn(() => Promise.resolve());
setupUtility({
parentPort: env.parentPort,
@@ -429,7 +429,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
runSmoke,
env: { OK_DEBUG_KEYRING_SMOKE: '1' },
@@ -452,7 +452,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
});
test('boot auto-smoke: env unset → no smoke runs, listener registered immediately', async () => {
- const runSmoke = mock(() =>
+ const runSmoke = vi.fn(() =>
Promise.resolve({ ok: true, timestamp: 'x' } as KeyringSmokeResult),
);
@@ -466,7 +466,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
runSmoke,
env: {},
@@ -485,8 +485,8 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
durationMs: 3,
timestamp: '2026-04-21T00:00:00.000Z',
};
- const runSmoke = mock(() => Promise.resolve(smokeResult));
- const writeSmokeResult = mock(() => Promise.reject(new Error('EACCES')));
+ const runSmoke = vi.fn(() => Promise.resolve(smokeResult));
+ const writeSmokeResult = vi.fn(() => Promise.reject(new Error('EACCES')));
setupUtility({
parentPort: env.parentPort,
@@ -498,7 +498,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
runSmoke,
env: {
@@ -526,13 +526,13 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
durationMs: 7,
timestamp: '2026-04-21T00:00:00.000Z',
};
- const runSmoke = mock(() => Promise.resolve(smokeResult));
+ const runSmoke = vi.fn(() => Promise.resolve(smokeResult));
setupUtility({
parentPort: env.parentPort,
importServer: () =>
Promise.resolve({
- bootServer: mock(() => Promise.resolve({})),
+ bootServer: vi.fn(() => Promise.resolve({})),
} as unknown as typeof import('@inkeep/open-knowledge-server')),
exit: env.exit,
parentPid: 99999,
@@ -540,7 +540,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
runSmoke,
});
@@ -559,10 +559,10 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
test('degraded subsystems are reported via separate IPC after ready', async () => {
const fakeBooted = {
port: 51234,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: ['shadow-repo'] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -576,7 +576,7 @@ describe('setupUtility (IPC handshake + lifecycle)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(),
});
@@ -610,10 +610,10 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
});
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -627,7 +627,7 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(prepared),
});
@@ -653,10 +653,10 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
const prepare = fakePrepare();
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -670,7 +670,7 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: prepare,
});
@@ -697,11 +697,11 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
test('OK_DEBUG_DESKTOP_BOOT_TRACE=1 logs the resolved config trace', async () => {
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
- const warnSpy = mock(() => {});
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
+ const warnSpy = vi.fn(() => {});
const originalWarn = console.warn;
console.warn = warnSpy;
try {
@@ -717,7 +717,7 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(
makeFakePrepared({
@@ -759,10 +759,10 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
const prepared = makeFakePrepared({ config, configValid: false });
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -776,7 +776,7 @@ describe('handleInit boot prelude (FR-16/17/18/19/22/24)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
prepareBootEnvironment: fakePrepare(prepared),
});
@@ -827,7 +827,7 @@ describe('resolveContentDir (FR-17 unit)', () => {
});
test('".." escape falls back to ipcFallback (defense-in-depth)', () => {
- const warnSpy = mock(() => {});
+ const warnSpy = vi.fn(() => {});
const originalWarn = console.warn;
console.warn = warnSpy;
try {
@@ -844,7 +844,7 @@ describe('resolveContentDir (FR-17 unit)', () => {
});
test('absolute content.dir outside projectDir falls back to ipcFallback', () => {
- const warnSpy = mock(() => {});
+ const warnSpy = vi.fn(() => {});
const originalWarn = console.warn;
console.warn = warnSpy;
try {
@@ -890,10 +890,10 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -907,7 +907,7 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
});
@@ -936,10 +936,10 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
// Pre-state: no .git/, no .ok/. The prelude must materialize both.
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -953,7 +953,7 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
});
@@ -991,12 +991,12 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
- const warnSpy = mock(() => {});
+ const warnSpy = vi.fn(() => {});
const originalWarn = console.warn;
console.warn = warnSpy;
try {
@@ -1012,7 +1012,7 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
});
@@ -1056,10 +1056,10 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
const fakeBooted = {
port: 4242,
- destroy: mock(() => Promise.resolve()),
+ destroy: vi.fn(() => Promise.resolve()),
degraded: [] as readonly string[],
};
- const bootServer = mock(() => Promise.resolve(fakeBooted));
+ const bootServer = vi.fn(() => Promise.resolve(fakeBooted));
const handle = setupUtility({
parentPort: env.parentPort,
@@ -1073,7 +1073,7 @@ describe('handleInit defaultPrepareBootEnvironment (integration)', () => {
onSignal: (sig, h) => env.signalHandlers.set(sig, h),
setInterval: (cb, ms) => {
env.intervals.push({ cb, ms });
- return { unref: mock(() => {}), clear: env.intervalCancel };
+ return { unref: vi.fn(() => {}), clear: env.intervalCancel };
},
});
diff --git a/packages/server/scripts/build-skill-bundles.test.ts b/packages/server/scripts/build-skill-bundles.test.ts
index 171242938..8647f1a89 100644
--- a/packages/server/scripts/build-skill-bundles.test.ts
+++ b/packages/server/scripts/build-skill-bundles.test.ts
@@ -6,7 +6,7 @@
* tmpdir fixtures, then the guard is run once against the REAL repo assets so
* `bun run check` fails on any production drift.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import {
existsSync,
mkdirSync,
@@ -18,6 +18,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
BUNDLE_IDS,
buildPackSkills,
diff --git a/packages/server/src/activity-log.test.ts b/packages/server/src/activity-log.test.ts
index 0fec55a37..fb77345fa 100644
--- a/packages/server/src/activity-log.test.ts
+++ b/packages/server/src/activity-log.test.ts
@@ -1,7 +1,7 @@
/**
* Unit tests for activity-log ring-buffer.
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+import { beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { captureEffect, type EffectValue } from './activity-log.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
diff --git a/packages/server/src/agent-activity.test.ts b/packages/server/src/agent-activity.test.ts
index 5f51b8e06..62f61988d 100644
--- a/packages/server/src/agent-activity.test.ts
+++ b/packages/server/src/agent-activity.test.ts
@@ -4,7 +4,7 @@
* Tests the pure diff-synthesis functions and listAgentActivity using
* real Y.Doc / Y.UndoManager instances (no mocks of internal CRDT state).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
listAgentActivity,
diff --git a/packages/server/src/agent-focus.test.ts b/packages/server/src/agent-focus.test.ts
index e9a115dc2..b2bd8dcda 100644
--- a/packages/server/src/agent-focus.test.ts
+++ b/packages/server/src/agent-focus.test.ts
@@ -1,6 +1,6 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
import type { Hocuspocus } from '@hocuspocus/server';
import { SYSTEM_DOC_NAME } from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test } from 'vitest';
import { AgentFocusBroadcaster } from './agent-focus.ts';
function makeMockAwareness() {
diff --git a/packages/server/src/agent-id.test.ts b/packages/server/src/agent-id.test.ts
index 157a05e50..dcc03aa0d 100644
--- a/packages/server/src/agent-id.test.ts
+++ b/packages/server/src/agent-id.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
AGENT_ID_MAX_LEN,
AGENT_ID_RE,
diff --git a/packages/server/src/agent-patch-crdt-convergence.test.ts b/packages/server/src/agent-patch-crdt-convergence.test.ts
index 8752f11e8..6de6e6a18 100644
--- a/packages/server/src/agent-patch-crdt-convergence.test.ts
+++ b/packages/server/src/agent-patch-crdt-convergence.test.ts
@@ -18,8 +18,9 @@
* cannot satisfy both — which is exactly why `position: 'replace'` was
* de-overloaded into `replace` (atomic) and `patch` (incremental).
*/
-import { describe, expect, test } from 'bun:test';
+
import type { Document } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN, applyAgentMarkdownWrite } from './agent-sessions.ts';
diff --git a/packages/server/src/agent-presence.test.ts b/packages/server/src/agent-presence.test.ts
index 4dd7ce768..66e2724c3 100644
--- a/packages/server/src/agent-presence.test.ts
+++ b/packages/server/src/agent-presence.test.ts
@@ -1,8 +1,8 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { Hocuspocus } from '@hocuspocus/server';
import { type AgentPresenceEntry, SYSTEM_DOC_NAME } from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test } from 'vitest';
import { AgentPresenceBroadcaster } from './agent-presence.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
@@ -303,7 +303,7 @@ describe('AgentPresenceBroadcaster', () => {
// moves setPresence back out of the try (which would re-open the stuck-
// writing race).
//
- // Why at the broadcaster level: `mock.module` leaks across test files in
+ // Why at the broadcaster level: `vi.doMock` leaks across test files in
// the same `bun test` process, so a
// direct handler-unit test that forces `applyAgentMarkdownWrite` to throw
// is impractical without process isolation. Instead, these tests encode
@@ -406,7 +406,7 @@ describe('AgentPresenceBroadcaster', () => {
test('structural: every agent write handler pairs setPresence("writing") + touchMode("idle")', () => {
// Source-level regression guard. Runtime equivalence is infeasible
- // because `mock.module` leaks across test files
+ // because `vi.doMock` leaks across test files
// ; this test reads the handler source and
// asserts the try/finally shape. The runtime broadcaster-level tests
// prove the pattern IS race-safe.
diff --git a/packages/server/src/agent-sessions.test.ts b/packages/server/src/agent-sessions.test.ts
index 711bc185b..3179380f5 100644
--- a/packages/server/src/agent-sessions.test.ts
+++ b/packages/server/src/agent-sessions.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import type { Document } from '@hocuspocus/server';
import { sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
type AgentDirectConnection,
diff --git a/packages/server/src/agent-write-replace-crdt-convergence.test.ts b/packages/server/src/agent-write-replace-crdt-convergence.test.ts
index 78c6f2453..10c78b409 100644
--- a/packages/server/src/agent-write-replace-crdt-convergence.test.ts
+++ b/packages/server/src/agent-write-replace-crdt-convergence.test.ts
@@ -38,8 +38,9 @@
* pinning the byte shape is Yjs-version-fragile. A separate product
* decision will choose Layer 2 recovery policy.
*/
-import { describe, expect, test } from 'bun:test';
+
import type { Document } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN, applyAgentMarkdownWrite } from './agent-sessions.ts';
diff --git a/packages/server/src/agent-write-summary.test.ts b/packages/server/src/agent-write-summary.test.ts
index f3629860c..34f048d36 100644
--- a/packages/server/src/agent-write-summary.test.ts
+++ b/packages/server/src/agent-write-summary.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { MAX_SUMMARY_LENGTH, normalizeSummary } from './agent-write-summary.ts';
describe('normalizeSummary — classification', () => {
diff --git a/packages/server/src/api-agent-frontmatter.test.ts b/packages/server/src/api-agent-frontmatter.test.ts
index 86b5401f4..9cb70a677 100644
--- a/packages/server/src/api-agent-frontmatter.test.ts
+++ b/packages/server/src/api-agent-frontmatter.test.ts
@@ -11,7 +11,7 @@
* 5. body-only agent-patch continues to work.
* 6. agent-undo reverts the FM region in lock-step with body changes.
*/
-import { describe, expect, spyOn, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
@@ -19,6 +19,7 @@ import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
import { readFmMap, stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import {
AGENT_WRITE_ORIGIN,
AgentSessionManager,
@@ -1136,7 +1137,7 @@ describe('POST /api/agent-write-md — telemetry refusal-class split (PRD-6947,
// change to either the event shape or the classifier surfaces a regression.
function collectRefusalEvents(
- spy: ReturnType<typeof spyOn<typeof console, 'warn'>>,
+ spy: ReturnType<typeof vi.spyOn<typeof console, 'warn'>>,
): Array<Record<string, unknown>> {
return spy.mock.calls
.map((call) => call[0])
@@ -1155,7 +1156,7 @@ describe('POST /api/agent-write-md — telemetry refusal-class split (PRD-6947,
}
test('yaml@2 parse error (PRD-6781 unquoted-colon) classifies as `yaml-parse-error`', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
try {
await sessionManager.getSession('test-doc');
@@ -1184,7 +1185,7 @@ describe('POST /api/agent-write-md — telemetry refusal-class split (PRD-6947,
});
test('top-level array FM classifies as `non-mapping-top-level`', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
try {
await sessionManager.getSession('test-doc');
@@ -1212,7 +1213,7 @@ describe('POST /api/agent-write-md — telemetry refusal-class split (PRD-6947,
});
test('nested-but-valid frontmatter does NOT fire the refusal event (retired bucket)', async () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { contentDir, hocuspocus, sessionManager, cleanup } = setup();
try {
await sessionManager.getSession('test-doc');
diff --git a/packages/server/src/api-agent-patch-ytext-truth.test.ts b/packages/server/src/api-agent-patch-ytext-truth.test.ts
index cb5a7344b..7775f559e 100644
--- a/packages/server/src/api-agent-patch-ytext-truth.test.ts
+++ b/packages/server/src/api-agent-patch-ytext-truth.test.ts
@@ -15,13 +15,14 @@
* 409 (stale offset). Bounded cardinality (event name + numeric lengths +
* doc.name + hadOffset boolean).
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import {
AGENT_WRITE_ORIGIN,
AgentSessionManager,
diff --git a/packages/server/src/api-agent-patch.test.ts b/packages/server/src/api-agent-patch.test.ts
index 4db821900..dd66f50df 100644
--- a/packages/server/src/api-agent-patch.test.ts
+++ b/packages/server/src/api-agent-patch.test.ts
@@ -1,10 +1,10 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
import {
AGENT_WRITE_ORIGIN,
diff --git a/packages/server/src/api-agent-write-extension.test.ts b/packages/server/src/api-agent-write-extension.test.ts
index f51b76b4a..be66fc43c 100644
--- a/packages/server/src/api-agent-write-extension.test.ts
+++ b/packages/server/src/api-agent-write-extension.test.ts
@@ -11,13 +11,14 @@
* `createApiExtension` harness other agent-write tests use has no persistence
* extension and never lands a file).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { _resetDocExtensionsForTests, getDocExtension } from './doc-extensions.ts';
import { createServer } from './server-factory.ts';
diff --git a/packages/server/src/api-agent-write-file-index.test.ts b/packages/server/src/api-agent-write-file-index.test.ts
index 55354a2a1..a6afd338d 100644
--- a/packages/server/src/api-agent-write-file-index.test.ts
+++ b/packages/server/src/api-agent-write-file-index.test.ts
@@ -8,13 +8,14 @@
* (no persistence extension, no watcher) and spy on `mutateFileIndex`, so what
* they observe is the handler's own registration, not the watcher's.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import {
AGENT_WRITE_ORIGIN,
AgentSessionManager,
diff --git a/packages/server/src/api-agent-write-summary.test.ts b/packages/server/src/api-agent-write-summary.test.ts
index 9951d2101..3e6e40bac 100644
--- a/packages/server/src/api-agent-write-summary.test.ts
+++ b/packages/server/src/api-agent-write-summary.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { AgentSessionManager, applyAgentMarkdownWrite } from './agent-sessions.ts';
import { createApiExtension } from './api-extension.ts';
import {
diff --git a/packages/server/src/api-asset.test.ts b/packages/server/src/api-asset.test.ts
index 0a3632728..e8989312e 100644
--- a/packages/server/src/api-asset.test.ts
+++ b/packages/server/src/api-asset.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { createServer, type Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import type { ContentFilter } from './content-filter.ts';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
diff --git a/packages/server/src/api-backlinks.test.ts b/packages/server/src/api-backlinks.test.ts
index 20067d639..3ecd1af4c 100644
--- a/packages/server/src/api-backlinks.test.ts
+++ b/packages/server/src/api-backlinks.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { type ContentFilter, createContentFilter } from './content-filter.ts';
diff --git a/packages/server/src/api-config.test.ts b/packages/server/src/api-config.test.ts
index add55ac8c..a07b52ae6 100644
--- a/packages/server/src/api-config.test.ts
+++ b/packages/server/src/api-config.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { getLocalDir } from './config/paths.ts';
import { acquireServerLock } from './server-lock.ts';
diff --git a/packages/server/src/api-create-page.test.ts b/packages/server/src/api-create-page.test.ts
index 2d220bb77..88ab25674 100644
--- a/packages/server/src/api-create-page.test.ts
+++ b/packages/server/src/api-create-page.test.ts
@@ -6,13 +6,13 @@
* the actual file creation can be verified without mocking node:fs.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import type { Principal } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { contributorCount, hasContributor, swapContributors } from './contributor-tracker.ts';
diff --git a/packages/server/src/api-docname-validation.test.ts b/packages/server/src/api-docname-validation.test.ts
index 76763b20b..0afdac31b 100644
--- a/packages/server/src/api-docname-validation.test.ts
+++ b/packages/server/src/api-docname-validation.test.ts
@@ -6,13 +6,14 @@
* hidden, or unaddressable files on disk. The shared docName contract now
* rejects them at the request-schema boundary.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import { AgentSessionManager } from './agent-sessions.ts';
import { createApiExtension } from './api-extension.ts';
diff --git a/packages/server/src/api-document-list-ready-gate.test.ts b/packages/server/src/api-document-list-ready-gate.test.ts
index 7b5bdbc05..301c5fb64 100644
--- a/packages/server/src/api-document-list-ready-gate.test.ts
+++ b/packages/server/src/api-document-list-ready-gate.test.ts
@@ -16,13 +16,13 @@
* file index that becomes visible at the moment `ready` settles.
*/
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import type { FileIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/api-empty-docname.test.ts b/packages/server/src/api-empty-docname.test.ts
index 948c61f47..7c89c3eb5 100644
--- a/packages/server/src/api-empty-docname.test.ts
+++ b/packages/server/src/api-empty-docname.test.ts
@@ -8,13 +8,14 @@
* mutating handler that read the `test-doc` fallback now answers 400 and
* creates no `test-doc` session.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import { AgentSessionManager } from './agent-sessions.ts';
import { createApiExtension } from './api-extension.ts';
diff --git a/packages/server/src/api-extension.branch-info.test.ts b/packages/server/src/api-extension.branch-info.test.ts
index f32406534..4ae7506c7 100644
--- a/packages/server/src/api-extension.branch-info.test.ts
+++ b/packages/server/src/api-extension.branch-info.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
interface TestRig {
diff --git a/packages/server/src/api-extension.checkout.test.ts b/packages/server/src/api-extension.checkout.test.ts
index 175ba3e06..723d95559 100644
--- a/packages/server/src/api-extension.checkout.test.ts
+++ b/packages/server/src/api-extension.checkout.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import type { Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
interface TestRig {
diff --git a/packages/server/src/api-extension.ok-init.test.ts b/packages/server/src/api-extension.ok-init.test.ts
index 36a44bc1e..ae3daf276 100644
--- a/packages/server/src/api-extension.ok-init.test.ts
+++ b/packages/server/src/api-extension.ok-init.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import {
existsSync,
@@ -12,6 +11,7 @@ import {
import type { Server } from 'node:http';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
/**
diff --git a/packages/server/src/api-file-ops.test.ts b/packages/server/src/api-file-ops.test.ts
index 96c4c4f8c..17e8d8e31 100644
--- a/packages/server/src/api-file-ops.test.ts
+++ b/packages/server/src/api-file-ops.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -16,6 +15,7 @@ import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
import simpleGit from 'simple-git';
+import { afterEach, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
diff --git a/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts b/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts
index 80b8c307f..763193994 100644
--- a/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts
+++ b/packages/server/src/api-folder-delete-duplicate-disk-enum.test.ts
@@ -18,12 +18,13 @@
* docs. Asserting enumeration alone would pass even if the cleanup / gate were
* skipped; the bug is precisely those skipped side effects.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { _resetDocExtensionsForTests } from './doc-extensions.ts';
import { RecentlyRemovedDocs } from './recently-removed-docs.ts';
diff --git a/packages/server/src/api-folder-rename-disk-enum.test.ts b/packages/server/src/api-folder-rename-disk-enum.test.ts
index 73f13f3f0..f5d6679d0 100644
--- a/packages/server/src/api-folder-rename-disk-enum.test.ts
+++ b/packages/server/src/api-folder-rename-disk-enum.test.ts
@@ -12,12 +12,13 @@
* the `.mdx` snapshot read resolves to a non-existent `.md` path and the spine
* throws `ManagedRenameMissingDocumentError`).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { _resetDocExtensionsForTests } from './doc-extensions.ts';
diff --git a/packages/server/src/api-link-preview.test.ts b/packages/server/src/api-link-preview.test.ts
index 285cc3254..ed64a54f6 100644
--- a/packages/server/src/api-link-preview.test.ts
+++ b/packages/server/src/api-link-preview.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, type Mock, spyOn, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { createServer, type Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, type Mock, test, vi } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import type { GuardRejectReason } from './link-preview/guarded-fetch.ts';
import type { GuardedFetch } from './link-preview/metadata.ts';
@@ -405,7 +405,7 @@ describe('POST /api/link-preview outcome instrumentation', () => {
let debugSpy: Mock<PinoLogger['debug']>;
beforeEach(() => {
- debugSpy = spyOn(PinoLogger.prototype, 'debug');
+ debugSpy = vi.spyOn(PinoLogger.prototype, 'debug');
});
afterEach(() => {
diff --git a/packages/server/src/api-ok-reserved-guard.test.ts b/packages/server/src/api-ok-reserved-guard.test.ts
index 60562b338..91c75cda0 100644
--- a/packages/server/src/api-ok-reserved-guard.test.ts
+++ b/packages/server/src/api-ok-reserved-guard.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { afterEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { _resetDocExtensionsForTests } from './doc-extensions.ts';
diff --git a/packages/server/src/api-pages.test.ts b/packages/server/src/api-pages.test.ts
index 9226ae766..81b517753 100644
--- a/packages/server/src/api-pages.test.ts
+++ b/packages/server/src/api-pages.test.ts
@@ -3,12 +3,13 @@
*
* Priority: frontmatter `title:` field → first `# heading` line → filename without extension.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { createApiExtension, extractHeadings, extractPageTitle } from './api-extension.ts';
import type { FileIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/api-patch.test.ts b/packages/server/src/api-patch.test.ts
index 5d1f90ed3..122c652ca 100644
--- a/packages/server/src/api-patch.test.ts
+++ b/packages/server/src/api-patch.test.ts
@@ -8,8 +8,9 @@
* Core invariant: a patch only mutates the matched character span — everything
* else in Y.Text survives untouched, regardless of what other writes have landed.
*/
-import { describe, expect, test } from 'bun:test';
+
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
diff --git a/packages/server/src/api-rename-race-conditions.test.ts b/packages/server/src/api-rename-race-conditions.test.ts
index fc0a2e852..b9873f812 100644
--- a/packages/server/src/api-rename-race-conditions.test.ts
+++ b/packages/server/src/api-rename-race-conditions.test.ts
@@ -14,12 +14,13 @@
* defeats `.mdx`-specific exclusion patterns when both extensions are
* present on disk.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { swapContributors } from './contributor-tracker.ts';
diff --git a/packages/server/src/api-rename-rollback-summary.test.ts b/packages/server/src/api-rename-rollback-summary.test.ts
index 973e1453d..95d59bc0e 100644
--- a/packages/server/src/api-rename-rollback-summary.test.ts
+++ b/packages/server/src/api-rename-rollback-summary.test.ts
@@ -6,7 +6,7 @@
* these tests pin that invariant alongside the behavior
* where an absent `agentId` falls back to the server-loaded principal.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import {
existsSync,
mkdirSync,
@@ -23,6 +23,7 @@ import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
import { setImmediate } from 'node:timers/promises';
import type { Principal } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import {
diff --git a/packages/server/src/api-rename-telemetry.test.ts b/packages/server/src/api-rename-telemetry.test.ts
index f7c12f301..149c2483b 100644
--- a/packages/server/src/api-rename-telemetry.test.ts
+++ b/packages/server/src/api-rename-telemetry.test.ts
@@ -6,7 +6,7 @@
* call, mistypes the attribute keys, or fires on a 400-validation path
* would silently degrade observability without these assertions.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
@@ -21,6 +21,7 @@ import {
MeterProvider,
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import { __resetRenameTelemetryForTesting, createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { swapContributors } from './contributor-tracker.ts';
diff --git a/packages/server/src/api-rollback-actor-identity.test.ts b/packages/server/src/api-rollback-actor-identity.test.ts
index 69c0aba38..f81f040e8 100644
--- a/packages/server/src/api-rollback-actor-identity.test.ts
+++ b/packages/server/src/api-rollback-actor-identity.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
@@ -6,6 +5,7 @@ import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
import type { Principal } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
diff --git a/packages/server/src/api-rollback-rename-history.test.ts b/packages/server/src/api-rollback-rename-history.test.ts
index 649c7cf9b..7f1ce72ec 100644
--- a/packages/server/src/api-rollback-rename-history.test.ts
+++ b/packages/server/src/api-rollback-rename-history.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
diff --git a/packages/server/src/api-search-semantic-factory.test.ts b/packages/server/src/api-search-semantic-factory.test.ts
index 72aea034f..442e2d0bd 100644
--- a/packages/server/src/api-search-semantic-factory.test.ts
+++ b/packages/server/src/api-search-semantic-factory.test.ts
@@ -1,10 +1,10 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import type { Extension } from '@hocuspocus/server';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { createConceptEmbedder } from './embeddings/index.ts';
import { createServer, type ServerInstance } from './server-factory.ts';
import { initShadowRepo } from './shadow-repo.ts';
diff --git a/packages/server/src/api-search-semantic.test.ts b/packages/server/src/api-search-semantic.test.ts
index 31cccff6b..294f7f2b6 100644
--- a/packages/server/src/api-search-semantic.test.ts
+++ b/packages/server/src/api-search-semantic.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import {
mkdirSync,
mkdtempSync,
@@ -13,6 +12,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { createWorkspaceSearchDocument } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { createConceptEmbedder, type Embedder, SemanticSearchService } from './embeddings/index.ts';
import type { FileIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/api-search.test.ts b/packages/server/src/api-search.test.ts
index 6a6fbf1d8..677477ab7 100644
--- a/packages/server/src/api-search.test.ts
+++ b/packages/server/src/api-search.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import {
createApiExtension,
DEFAULT_SEARCH_MAX_ENTRIES,
diff --git a/packages/server/src/api-suggest-links.test.ts b/packages/server/src/api-suggest-links.test.ts
index dc4b1a1bd..bf5c32a22 100644
--- a/packages/server/src/api-suggest-links.test.ts
+++ b/packages/server/src/api-suggest-links.test.ts
@@ -1,10 +1,10 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import type { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import type { FileIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/api-tags.test.ts b/packages/server/src/api-tags.test.ts
index a7da165d8..fa178c2cf 100644
--- a/packages/server/src/api-tags.test.ts
+++ b/packages/server/src/api-tags.test.ts
@@ -1,9 +1,9 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import type { FileIndexEntry } from './file-watcher.ts';
import { TagIndex } from './tag-index.ts';
diff --git a/packages/server/src/api-template-get.test.ts b/packages/server/src/api-template-get.test.ts
index 344432ee8..bc469243c 100644
--- a/packages/server/src/api-template-get.test.ts
+++ b/packages/server/src/api-template-get.test.ts
@@ -8,12 +8,13 @@
* Harness mirrors `api-pages.test.ts`: createApiExtension with stub
* hocuspocus/sessionManager, dispatch through `onRequest`.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
function makeReq(url: string): IncomingMessage {
diff --git a/packages/server/src/api-test-rescan-files.test.ts b/packages/server/src/api-test-rescan-files.test.ts
index fad1bd9f4..f24861e56 100644
--- a/packages/server/src/api-test-rescan-files.test.ts
+++ b/packages/server/src/api-test-rescan-files.test.ts
@@ -15,12 +15,13 @@
* handler).
* 3. Method gate — non-POST methods return 405.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import type { FileIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/api-trash-cleanup.test.ts b/packages/server/src/api-trash-cleanup.test.ts
index 7d8c8eda3..cf12eea14 100644
--- a/packages/server/src/api-trash-cleanup.test.ts
+++ b/packages/server/src/api-trash-cleanup.test.ts
@@ -15,7 +15,7 @@
* - Idempotent: 200 + empty array when fileIndex no longer has the entries
* - Validation: reserved docName, invalid path, malformed body all 400
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import {
existsSync,
mkdirSync,
@@ -30,6 +30,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
import type { Principal } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import { createApiExtension } from './api-extension.ts';
import { BacklinkIndex } from './backlink-index.ts';
import type { FileIndexEntry, FolderIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/apply-managed-rename.test.ts b/packages/server/src/apply-managed-rename.test.ts
index 1f51a9580..2d4b1b87c 100644
--- a/packages/server/src/apply-managed-rename.test.ts
+++ b/packages/server/src/apply-managed-rename.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
applyRenameMap,
buildRenameMap,
diff --git a/packages/server/src/asset-serve-middleware.integration.test.ts b/packages/server/src/asset-serve-middleware.integration.test.ts
index b1b4a6cc0..0038e3448 100644
--- a/packages/server/src/asset-serve-middleware.integration.test.ts
+++ b/packages/server/src/asset-serve-middleware.integration.test.ts
@@ -23,7 +23,6 @@
* (real HTTP + listen-on-0 + fetch).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { tmpdir } from 'node:os';
@@ -34,6 +33,7 @@ import {
INLINE_RENDERABLE_EXTENSIONS,
} from '@inkeep/open-knowledge-core';
import sirv from 'sirv';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createAssetServeMiddleware } from './asset-serve-middleware.ts';
import { createContentFilter } from './content-filter.ts';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
diff --git a/packages/server/src/asset-serve-middleware.test.ts b/packages/server/src/asset-serve-middleware.test.ts
index e11b344a2..a685cb0d6 100644
--- a/packages/server/src/asset-serve-middleware.test.ts
+++ b/packages/server/src/asset-serve-middleware.test.ts
@@ -10,9 +10,9 @@
* `asset-serve-middleware.integration.test.ts`.
*/
-import { describe, expect, test } from 'bun:test';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
+import { describe, expect, test } from 'vitest';
import {
type AssetServeFilter,
createAssetServeMiddleware,
diff --git a/packages/server/src/asset-walk.test.ts b/packages/server/src/asset-walk.test.ts
index 0287b46ef..85dab21d7 100644
--- a/packages/server/src/asset-walk.test.ts
+++ b/packages/server/src/asset-walk.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createBasenameIndex } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { seedBasenameIndex } from './asset-walk.ts';
import { createContentFilter } from './content-filter.ts';
diff --git a/packages/server/src/auth-token-schema.test.ts b/packages/server/src/auth-token-schema.test.ts
index 591bb585c..7490fe85b 100644
--- a/packages/server/src/auth-token-schema.test.ts
+++ b/packages/server/src/auth-token-schema.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'bun:test';
+import { describe, expect, it } from 'vitest';
import {
formatAuthRejectionWire,
HOCUSPOCUS_AUTH_REJECTION_REASONS,
diff --git a/packages/server/src/backlink-index.test.ts b/packages/server/src/backlink-index.test.ts
index 7fb5dc2b0..224f7cd90 100644
--- a/packages/server/src/backlink-index.test.ts
+++ b/packages/server/src/backlink-index.test.ts
@@ -1,4 +1,3 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
import {
mkdirSync,
mkdtempSync,
@@ -11,6 +10,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test } from 'vitest';
import {
BacklinkIndex,
type BrokenOutboundLink,
diff --git a/packages/server/src/bash/extract-paths.test.ts b/packages/server/src/bash/extract-paths.test.ts
index 504bed9fd..494ce0e92 100644
--- a/packages/server/src/bash/extract-paths.test.ts
+++ b/packages/server/src/bash/extract-paths.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { extractReferencedPaths } from './extract-paths.ts';
import type { Stage } from './parse-command.ts';
diff --git a/packages/server/src/bash/index.test.ts b/packages/server/src/bash/index.test.ts
index 18c63497c..20229c687 100644
--- a/packages/server/src/bash/index.test.ts
+++ b/packages/server/src/bash/index.test.ts
@@ -1,7 +1,7 @@
-import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { createBashInstance, execBash, StdoutOverflowError, shellEscape } from './index.ts';
describe('shellEscape', () => {
diff --git a/packages/server/src/bash/mtime-scan.test.ts b/packages/server/src/bash/mtime-scan.test.ts
index c89b9e4aa..7baa6bb8e 100644
--- a/packages/server/src/bash/mtime-scan.test.ts
+++ b/packages/server/src/bash/mtime-scan.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
deriveScanRoots,
diffMtimes,
diff --git a/packages/server/src/bash/parse-command.test.ts b/packages/server/src/bash/parse-command.test.ts
index 554d6d2d2..df6274e2a 100644
--- a/packages/server/src/bash/parse-command.test.ts
+++ b/packages/server/src/bash/parse-command.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { augmentStagesWithExcludes, parseCommand, serializeStages } from './parse-command.ts';
function expectOk(
diff --git a/packages/server/src/boot-conflict-restore.test.ts b/packages/server/src/boot-conflict-restore.test.ts
index 15583be6e..878cd41ea 100644
--- a/packages/server/src/boot-conflict-restore.test.ts
+++ b/packages/server/src/boot-conflict-restore.test.ts
@@ -12,7 +12,7 @@
* the existing boot.test.ts skip gate.
*/
-import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'vitest';
const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
diff --git a/packages/server/src/boot-legacy-detection.test.ts b/packages/server/src/boot-legacy-detection.test.ts
index b5bf19881..2b06a0e83 100644
--- a/packages/server/src/boot-legacy-detection.test.ts
+++ b/packages/server/src/boot-legacy-detection.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { findLegacyRuntimeFiles } from './boot.ts';
describe('findLegacyRuntimeFiles', () => {
diff --git a/packages/server/src/boot-timings.test.ts b/packages/server/src/boot-timings.test.ts
index 0c19b86eb..75328a6d4 100644
--- a/packages/server/src/boot-timings.test.ts
+++ b/packages/server/src/boot-timings.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
bootElapsedMs,
getBootTimings,
diff --git a/packages/server/src/boot-walk-responsiveness.test.ts b/packages/server/src/boot-walk-responsiveness.test.ts
index 5a63887e0..bae88c0e5 100644
--- a/packages/server/src/boot-walk-responsiveness.test.ts
+++ b/packages/server/src/boot-walk-responsiveness.test.ts
@@ -19,11 +19,11 @@
* pinning that the async conversion didn't change discovery semantics.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createBasenameIndex } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { seedBasenameIndex } from './asset-walk.ts';
import { BacklinkIndex } from './backlink-index.ts';
import { startWatcher } from './file-watcher.ts';
diff --git a/packages/server/src/bridge-intake.test.ts b/packages/server/src/bridge-intake.test.ts
index ece6d239e..9b63cfdba 100644
--- a/packages/server/src/bridge-intake.test.ts
+++ b/packages/server/src/bridge-intake.test.ts
@@ -28,9 +28,10 @@
* (replaceRawBody = full overwrite; deriveFragmentFromYtext = zero
* ytext writes)
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+
import { normalizeBridge, stripFrontmatter } from '@inkeep/open-knowledge-core';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { ROLLBACK_ORIGIN } from './api-extension.ts';
import {
diff --git a/packages/server/src/bridge-no-wallclock.test.ts b/packages/server/src/bridge-no-wallclock.test.ts
index fa76e2a47..7efd3f0c9 100644
--- a/packages/server/src/bridge-no-wallclock.test.ts
+++ b/packages/server/src/bridge-no-wallclock.test.ts
@@ -26,10 +26,10 @@
* allow-list individual lines. Greenfield posture.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
// Resolve repo root deterministically from this file's own path.
// packages/server/src/<this>.test.ts → ../../.. = repo root.
diff --git a/packages/server/src/bridge-quiescence.test.ts b/packages/server/src/bridge-quiescence.test.ts
index ea897ea41..81c50ff6a 100644
--- a/packages/server/src/bridge-quiescence.test.ts
+++ b/packages/server/src/bridge-quiescence.test.ts
@@ -9,7 +9,7 @@
* MUST NOT bump userTx — counting them would re-flip the gate every drain.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
__resetQuiescenceForTests,
diff --git a/packages/server/src/bridge-watchdog.test.ts b/packages/server/src/bridge-watchdog.test.ts
index 2be88f3f1..6aeb93f30 100644
--- a/packages/server/src/bridge-watchdog.test.ts
+++ b/packages/server/src/bridge-watchdog.test.ts
@@ -16,7 +16,6 @@
* core mechanics without a Y.Doc.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
BridgeInvariantViolationError,
MarkdownManager,
@@ -25,6 +24,7 @@ import {
sharedExtensions,
type ToleranceFireRecord,
} from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__getSplitBrainRateTupleCountForTests,
__getViolationRateTupleCountForTests,
diff --git a/packages/server/src/build-skill-zip.test.ts b/packages/server/src/build-skill-zip.test.ts
index b30679671..5a751f760 100644
--- a/packages/server/src/build-skill-zip.test.ts
+++ b/packages/server/src/build-skill-zip.test.ts
@@ -5,10 +5,10 @@
* use `\` separators.
*/
-import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, posix, win32 } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { __testing, resolveBundledSkillDir } from './build-skill-zip.ts';
const { computeWrapperFolderName, extractMetadataVersion, toPosixZipPath } = __testing;
diff --git a/packages/server/src/cc1-broadcast.test.ts b/packages/server/src/cc1-broadcast.test.ts
index 966c5b8ad..7d1e08596 100644
--- a/packages/server/src/cc1-broadcast.test.ts
+++ b/packages/server/src/cc1-broadcast.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import type { Hocuspocus } from '@hocuspocus/server';
import {
@@ -19,6 +18,7 @@ import {
CONFIG_DOC_NAMES,
SYSTEM_DOC_NAME,
} from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
CC1Broadcaster,
isConfigDoc,
diff --git a/packages/server/src/child-process-windows-hide.test.ts b/packages/server/src/child-process-windows-hide.test.ts
index a944bd84d..18219bd8a 100644
--- a/packages/server/src/child-process-windows-hide.test.ts
+++ b/packages/server/src/child-process-windows-hide.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import { readdirSync } from 'node:fs';
import { resolve } from 'node:path';
import {
@@ -9,6 +8,7 @@ import {
Project,
type SourceFile,
} from 'ts-morph';
+import { describe, expect, test } from 'vitest';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
const SERVER_SRC_DIR = import.meta.dir;
diff --git a/packages/server/src/collab-message-limit.test.ts b/packages/server/src/collab-message-limit.test.ts
index acca67820..c4a0f5ba5 100644
--- a/packages/server/src/collab-message-limit.test.ts
+++ b/packages/server/src/collab-message-limit.test.ts
@@ -1,4 +1,3 @@
-import { afterAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -6,6 +5,7 @@ import { setTimeout as wait } from 'node:timers/promises';
import { MessageType } from '@hocuspocus/server';
import { OK_DIR } from '@inkeep/open-knowledge-core';
import * as encoding from 'lib0/encoding';
+import { afterAll, describe, expect, test } from 'vitest';
import { WebSocket as WsClient } from 'ws';
import { messageYjsUpdate } from 'y-protocols/sync';
import { type BootedServer, bootServer } from './boot.ts';
diff --git a/packages/server/src/config-file-watcher.test.ts b/packages/server/src/config-file-watcher.test.ts
index edc961571..811cc4a9a 100644
--- a/packages/server/src/config-file-watcher.test.ts
+++ b/packages/server/src/config-file-watcher.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
import { rename } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
type ConfigFileWatcherUnsubscribe,
startConfigFileWatcher,
diff --git a/packages/server/src/config-persistence.test.ts b/packages/server/src/config-persistence.test.ts
index 78054975d..770f83c71 100644
--- a/packages/server/src/config-persistence.test.ts
+++ b/packages/server/src/config-persistence.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -18,6 +17,7 @@ import {
type ConfigValidationError,
isKnownConfigError,
} from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
CONFIG_FILE_WATCHER_ORIGIN,
diff --git a/packages/server/src/config-telemetry.test.ts b/packages/server/src/config-telemetry.test.ts
index 24a9b1c59..5fd51cecb 100644
--- a/packages/server/src/config-telemetry.test.ts
+++ b/packages/server/src/config-telemetry.test.ts
@@ -9,7 +9,7 @@
* Bounded enum attributes only — Zod issue paths land in span events, not
* attributes (cardinality discipline).
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -28,6 +28,7 @@ import {
type ReadableSpan,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import * as Y from 'yjs';
import { applyExternalConfigChange, storeConfigDoc } from './config-persistence.ts';
diff --git a/packages/server/src/config/paths.test.ts b/packages/server/src/config/paths.test.ts
index 544ac842e..333ee7a6f 100644
--- a/packages/server/src/config/paths.test.ts
+++ b/packages/server/src/config/paths.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { getLocalDir, resolveContentDir, resolveLockDir } from './paths.ts';
import type { Config } from './schema.ts';
diff --git a/packages/server/src/config/schema.test.ts b/packages/server/src/config/schema.test.ts
index 0bdf2e5d0..fd030b80b 100644
--- a/packages/server/src/config/schema.test.ts
+++ b/packages/server/src/config/schema.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { ConfigSchema } from './schema';
describe('ConfigSchema', () => {
diff --git a/packages/server/src/conflict-errors.test.ts b/packages/server/src/conflict-errors.test.ts
index 7576dd8b1..d02e48af8 100644
--- a/packages/server/src/conflict-errors.test.ts
+++ b/packages/server/src/conflict-errors.test.ts
@@ -9,8 +9,8 @@
* the title, change the URN) and break every agent's 409-class branching.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import type { ServerResponse } from 'node:http';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { DocInConflictError, respondDocInConflict } from './conflict-errors.ts';
const originalWarn = console.warn;
diff --git a/packages/server/src/conflict-lifecycle-seed.test.ts b/packages/server/src/conflict-lifecycle-seed.test.ts
index a6c3eab87..0b724e1b5 100644
--- a/packages/server/src/conflict-lifecycle-seed.test.ts
+++ b/packages/server/src/conflict-lifecycle-seed.test.ts
@@ -7,8 +7,9 @@
* the previously-uncovered race: conflict landed on disk while the doc was
* NOT loaded, and the client now connects to it for the first time.
*/
-import { describe, expect, test } from 'bun:test';
+
import type { Document, Extension } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { createConflictLifecycleSeedExtension } from './conflict-lifecycle-seed.ts';
import type { ConflictEntry } from './conflict-storage.ts';
diff --git a/packages/server/src/content-divergence-gate.test.ts b/packages/server/src/content-divergence-gate.test.ts
index 517d8206e..c224be68c 100644
--- a/packages/server/src/content-divergence-gate.test.ts
+++ b/packages/server/src/content-divergence-gate.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { ContentDivergenceWarningSchema } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
CONTENT_DIVERGENCE_CAP_BYTES,
capContent,
diff --git a/packages/server/src/content-filter.test.ts b/packages/server/src/content-filter.test.ts
index f56198ac1..c7e7916a8 100644
--- a/packages/server/src/content-filter.test.ts
+++ b/packages/server/src/content-filter.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
@@ -13,6 +12,7 @@ import {
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import ignore from 'ignore';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import {
type ContentFilter,
createContentFilter,
@@ -1406,7 +1406,7 @@ describe('ContentFilter', () => {
// process — but mockImplementationOnce ensures only the next call
// throws. We trigger that call by entering rebuildIgnorePatterns.
const sampleProto = Object.getPrototypeOf(ignore());
- const addSpy = spyOn(sampleProto, 'add').mockImplementationOnce(() => {
+ const addSpy = vi.spyOn(sampleProto, 'add').mockImplementationOnce(() => {
throw new Error('forced ignore.add failure');
});
@@ -1438,7 +1438,7 @@ describe('ContentFilter', () => {
// Force the rebuild to fail.
const sampleProto = Object.getPrototypeOf(ignore());
- const addSpy = spyOn(sampleProto, 'add').mockImplementationOnce(() => {
+ const addSpy = vi.spyOn(sampleProto, 'add').mockImplementationOnce(() => {
throw new Error('boom');
});
@@ -1539,7 +1539,7 @@ describe('ContentFilter', () => {
const filter = createContentFilter({ projectDir, contentDir: projectDir });
const sampleProto = Object.getPrototypeOf(ignore());
- const addSpy = spyOn(sampleProto, 'add').mockImplementationOnce(() => {
+ const addSpy = vi.spyOn(sampleProto, 'add').mockImplementationOnce(() => {
throw new Error('boom');
});
diff --git a/packages/server/src/content/enrichment.test.ts b/packages/server/src/content/enrichment.test.ts
index e93def6f9..01b962345 100644
--- a/packages/server/src/content/enrichment.test.ts
+++ b/packages/server/src/content/enrichment.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { commitWip, initShadowRepo, type WriterIdentity } from '@inkeep/open-knowledge-server';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { computeGraphRole, enrichDirectory, enrichPath } from './enrichment.ts';
let tmpDir: string;
diff --git a/packages/server/src/content/frontmatter-merge.test.ts b/packages/server/src/content/frontmatter-merge.test.ts
index d2636bbdd..ce2075e72 100644
--- a/packages/server/src/content/frontmatter-merge.test.ts
+++ b/packages/server/src/content/frontmatter-merge.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { mergePatch } from './frontmatter-merge.ts';
describe('mergePatch — write path (scalars + arrays REPLACE; empties drop)', () => {
diff --git a/packages/server/src/content/nested-folder-rules.test.ts b/packages/server/src/content/nested-folder-rules.test.ts
index 6f278daf1..e6b80b609 100644
--- a/packages/server/src/content/nested-folder-rules.test.ts
+++ b/packages/server/src/content/nested-folder-rules.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { nestedOkPath, parentFolderOf, readFolderFrontmatter } from './nested-folder-rules.ts';
describe('readFolderFrontmatter — self-only (no cascade)', () => {
diff --git a/packages/server/src/content/shadow-log.test.ts b/packages/server/src/content/shadow-log.test.ts
index 8debd4a14..f21149556 100644
--- a/packages/server/src/content/shadow-log.test.ts
+++ b/packages/server/src/content/shadow-log.test.ts
@@ -1,4 +1,4 @@
-import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in this
// test setup spawns git children that Bun fails to reap on ubuntu-latest
diff --git a/packages/server/src/content/skills-write.test.ts b/packages/server/src/content/skills-write.test.ts
index d3def5a3f..20e88d3f6 100644
--- a/packages/server/src/content/skills-write.test.ts
+++ b/packages/server/src/content/skills-write.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
applySkillBundleFileDelete,
applySkillBundleFileWrite,
diff --git a/packages/server/src/content/substitution.test.ts b/packages/server/src/content/substitution.test.ts
index 124e2a488..1fd986907 100644
--- a/packages/server/src/content/substitution.test.ts
+++ b/packages/server/src/content/substitution.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'bun:test';
+import { describe, expect, it } from 'vitest';
import {
applySubstitution,
SUBSTITUTION_ALLOWLIST,
diff --git a/packages/server/src/content/templates-resolver.test.ts b/packages/server/src/content/templates-resolver.test.ts
index df9a82bed..d4b88a485 100644
--- a/packages/server/src/content/templates-resolver.test.ts
+++ b/packages/server/src/content/templates-resolver.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { resolveProjectTemplates, resolveTemplatesAvailable } from './templates-resolver.ts';
describe('resolveTemplatesAvailable', () => {
diff --git a/packages/server/src/content/templates-write.test.ts b/packages/server/src/content/templates-write.test.ts
index c305db1af..48aab34d7 100644
--- a/packages/server/src/content/templates-write.test.ts
+++ b/packages/server/src/content/templates-write.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { applyTemplateDelete, applyTemplateMove, applyTemplateWrite } from './templates-write.ts';
describe('applyTemplateWrite', () => {
diff --git a/packages/server/src/contributor-tracker.test.ts b/packages/server/src/contributor-tracker.test.ts
index ed21c236e..9177fd44b 100644
--- a/packages/server/src/contributor-tracker.test.ts
+++ b/packages/server/src/contributor-tracker.test.ts
@@ -1,5 +1,5 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
import { parseContributors } from '@inkeep/open-knowledge-core/shadow-repo-layout';
+import { beforeEach, describe, expect, test } from 'vitest';
import {
contributorCount,
__formatContributorsForTests as formatContributorsForTest,
diff --git a/packages/server/src/crash-capture.test.ts b/packages/server/src/crash-capture.test.ts
index b2baa9560..cf4ead0ce 100644
--- a/packages/server/src/crash-capture.test.ts
+++ b/packages/server/src/crash-capture.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SERVER_CRASH_LOG } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
buildCrashRecord,
type CrashCaptureHandle,
diff --git a/packages/server/src/doc-extensions.test.ts b/packages/server/src/doc-extensions.test.ts
index 0f23b93f2..4f6658573 100644
--- a/packages/server/src/doc-extensions.test.ts
+++ b/packages/server/src/doc-extensions.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
+import { beforeEach, describe, expect, test } from 'vitest';
import {
_resetDocExtensionsForTests,
docNameToRelativePath,
diff --git a/packages/server/src/doc-lineage-guard.test.ts b/packages/server/src/doc-lineage-guard.test.ts
index 4642706c9..b297c1c7e 100644
--- a/packages/server/src/doc-lineage-guard.test.ts
+++ b/packages/server/src/doc-lineage-guard.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { HocuspocusAuthRejection, LINEAGE_EPOCH_KEY } from './auth-token-schema.ts';
import { type DocLineageGuardDeps, runDocLineageGuard } from './doc-lineage-guard.ts';
diff --git a/packages/server/src/document-list.test.ts b/packages/server/src/document-list.test.ts
index f3d1e7e26..71b276a4c 100644
--- a/packages/server/src/document-list.test.ts
+++ b/packages/server/src/document-list.test.ts
@@ -5,7 +5,7 @@
* The document list API now reads from the watcher's in-memory file index
* (populated and filtered by ContentFilter) instead of doing its own readdirSync.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { safeSubdir } from './api-extension.ts';
import type { FileIndexEntry } from './file-watcher.ts';
diff --git a/packages/server/src/embed-probe.test.ts b/packages/server/src/embed-probe.test.ts
index 6975b8c54..4d88a9cbb 100644
--- a/packages/server/src/embed-probe.test.ts
+++ b/packages/server/src/embed-probe.test.ts
@@ -2,7 +2,7 @@
* Tests for the in-process embed-detection ring buffer + diagnostic
* endpoint wiring.
*/
-import { describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
@@ -10,6 +10,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import { AgentSessionManager } from './agent-sessions.ts';
import { createApiExtension } from './api-extension.ts';
import {
diff --git a/packages/server/src/embeddings/chunking.test.ts b/packages/server/src/embeddings/chunking.test.ts
index 8b3de3958..1d8c89c48 100644
--- a/packages/server/src/embeddings/chunking.test.ts
+++ b/packages/server/src/embeddings/chunking.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
CHUNK_OVERLAP_CHARS,
CHUNK_TARGET_CHARS,
diff --git a/packages/server/src/embeddings/concept-embedder.test.ts b/packages/server/src/embeddings/concept-embedder.test.ts
index 1d2f33b79..48a19fc8c 100644
--- a/packages/server/src/embeddings/concept-embedder.test.ts
+++ b/packages/server/src/embeddings/concept-embedder.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createConceptEmbedder } from './concept-embedder.ts';
import { cosineSimilarity, DEFAULT_EMBEDDINGS_DIMENSIONS } from './embedder.ts';
diff --git a/packages/server/src/embeddings/embedder.test.ts b/packages/server/src/embeddings/embedder.test.ts
index ae1b2528f..614adcae0 100644
--- a/packages/server/src/embeddings/embedder.test.ts
+++ b/packages/server/src/embeddings/embedder.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
cosineSimilarity,
createOpenAiEmbedder,
diff --git a/packages/server/src/embeddings/embeddings-telemetry.test.ts b/packages/server/src/embeddings/embeddings-telemetry.test.ts
index 5e4b60473..bea3f433f 100644
--- a/packages/server/src/embeddings/embeddings-telemetry.test.ts
+++ b/packages/server/src/embeddings/embeddings-telemetry.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
__resetEmbeddingsTelemetryForTesting,
recordEmbeddingProviderError,
diff --git a/packages/server/src/embeddings/eval/eval-set.test.ts b/packages/server/src/embeddings/eval/eval-set.test.ts
index 882960257..9ea38e9cb 100644
--- a/packages/server/src/embeddings/eval/eval-set.test.ts
+++ b/packages/server/src/embeddings/eval/eval-set.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type EvalSet, loadEvalSet } from './semantic-eval.ts';
/**
diff --git a/packages/server/src/embeddings/eval/semantic-eval.smoke.test.ts b/packages/server/src/embeddings/eval/semantic-eval.smoke.test.ts
index d99a07fd1..765c3f369 100644
--- a/packages/server/src/embeddings/eval/semantic-eval.smoke.test.ts
+++ b/packages/server/src/embeddings/eval/semantic-eval.smoke.test.ts
@@ -16,8 +16,8 @@
* dark). The flag-flip decision reads this number from the run output.
*/
-import { describe, expect, test } from 'bun:test';
import { searchWorkspaceCorpus } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { loadEvalEmbedder, loadEvalSet, prepareEval, runHeldOutEval } from './semantic-eval.ts';
const ENABLED = process.env.OK_EMBED_SMOKE === '1';
diff --git a/packages/server/src/embeddings/secrets-store.test.ts b/packages/server/src/embeddings/secrets-store.test.ts
index 2086d3f3a..f3668b2ee 100644
--- a/packages/server/src/embeddings/secrets-store.test.ts
+++ b/packages/server/src/embeddings/secrets-store.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
chmodSync,
existsSync,
@@ -11,6 +10,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { parse } from 'yaml';
import {
clearEmbeddingsKeyFromAllBackends,
diff --git a/packages/server/src/embeddings/semantic-config.test.ts b/packages/server/src/embeddings/semantic-config.test.ts
index 1e2f35508..48ec30fba 100644
--- a/packages/server/src/embeddings/semantic-config.test.ts
+++ b/packages/server/src/embeddings/semantic-config.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readProjectLocalSemanticConfig } from './semantic-config.ts';
function makeProject(): string {
diff --git a/packages/server/src/embeddings/semantic-search-service.test.ts b/packages/server/src/embeddings/semantic-search-service.test.ts
index 7560ea8b2..c04bb028c 100644
--- a/packages/server/src/embeddings/semantic-search-service.test.ts
+++ b/packages/server/src/embeddings/semantic-search-service.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -6,6 +5,7 @@ import {
createWorkspaceSearchDocument,
type WorkspaceSearchDocument,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { CHUNK_CONFIG_ID } from './chunking.ts';
import { createConceptEmbedder } from './concept-embedder.ts';
import type { Embedder } from './embedder.ts';
diff --git a/packages/server/src/embeddings/vector-cache.test.ts b/packages/server/src/embeddings/vector-cache.test.ts
index ba3510a2f..2da362c5d 100644
--- a/packages/server/src/embeddings/vector-cache.test.ts
+++ b/packages/server/src/embeddings/vector-cache.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { hashContent, VectorCache } from './vector-cache.ts';
const DIMS = 4;
diff --git a/packages/server/src/ensure-single-file-session.test.ts b/packages/server/src/ensure-single-file-session.test.ts
index 878b91c00..c54462f9a 100644
--- a/packages/server/src/ensure-single-file-session.test.ts
+++ b/packages/server/src/ensure-single-file-session.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__resetEnsureSingleFileInflightForTests,
type EnsureSingleFileDeps,
diff --git a/packages/server/src/error-classification.test.ts b/packages/server/src/error-classification.test.ts
index dd0b9987f..719d2e2f3 100644
--- a/packages/server/src/error-classification.test.ts
+++ b/packages/server/src/error-classification.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyGitError, deriveUserFacingCode } from './error-classification.ts';
function mkErr(message: string, stderr?: string): Error {
diff --git a/packages/server/src/extract-actor-identity.test.ts b/packages/server/src/extract-actor-identity.test.ts
index 5b52111c3..44abda008 100644
--- a/packages/server/src/extract-actor-identity.test.ts
+++ b/packages/server/src/extract-actor-identity.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import type { Principal } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { extractActorIdentity } from './extract-actor-identity.ts';
const fixturePrincipal: Principal = {
diff --git a/packages/server/src/file-watcher-allfiles.test.ts b/packages/server/src/file-watcher-allfiles.test.ts
index 856d06dcb..7e3294a80 100644
--- a/packages/server/src/file-watcher-allfiles.test.ts
+++ b/packages/server/src/file-watcher-allfiles.test.ts
@@ -5,11 +5,12 @@
* ContentFilter-passing extension) and (the seed walk performs no
* content read for `kind:'file'` entries).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createContentFilter } from './content-filter.ts';
import { handleRawEvents, lastKnownHash, startWatcher } from './file-watcher.ts';
diff --git a/packages/server/src/frontmatter-malformed-error.test.ts b/packages/server/src/frontmatter-malformed-error.test.ts
index d9eac38c3..1ebddf150 100644
--- a/packages/server/src/frontmatter-malformed-error.test.ts
+++ b/packages/server/src/frontmatter-malformed-error.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyParseError } from './frontmatter-malformed-error.ts';
describe('classifyParseError — bounded-cardinality refusal class', () => {
diff --git a/packages/server/src/frontmatter-telemetry.test.ts b/packages/server/src/frontmatter-telemetry.test.ts
index b98376830..d8e14564a 100644
--- a/packages/server/src/frontmatter-telemetry.test.ts
+++ b/packages/server/src/frontmatter-telemetry.test.ts
@@ -9,7 +9,7 @@
* caches so the helpers rebind, runs the operation, asserts the recorded
* data.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { metrics, trace } from '@opentelemetry/api';
import {
AggregationTemporality,
@@ -22,6 +22,7 @@ import {
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetFrontmatterTelemetryForTests,
recordFrontmatterEditSurface,
diff --git a/packages/server/src/fs-traced.test.ts b/packages/server/src/fs-traced.test.ts
index 5aa0682d3..abd283cee 100644
--- a/packages/server/src/fs-traced.test.ts
+++ b/packages/server/src/fs-traced.test.ts
@@ -1,5 +1,5 @@
-import { describe, expect, test } from 'bun:test';
import { sep } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { classifyFsPath } from './fs-traced.ts';
/**
diff --git a/packages/server/src/fs/find-git-root.test.ts b/packages/server/src/fs/find-git-root.test.ts
index fa54cbd0a..4288d6cb1 100644
--- a/packages/server/src/fs/find-git-root.test.ts
+++ b/packages/server/src/fs/find-git-root.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { findEnclosingGitRoot } from './find-git-root.ts';
describe('findEnclosingGitRoot', () => {
diff --git a/packages/server/src/fs/find-project-root.test.ts b/packages/server/src/fs/find-project-root.test.ts
index f1312c601..51356a66a 100644
--- a/packages/server/src/fs/find-project-root.test.ts
+++ b/packages/server/src/fs/find-project-root.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { findEnclosingProjectRoot } from './find-project-root.ts';
describe('findEnclosingProjectRoot', () => {
diff --git a/packages/server/src/gh-token-source.test.ts b/packages/server/src/gh-token-source.test.ts
index df360e553..2ac81aee0 100644
--- a/packages/server/src/gh-token-source.test.ts
+++ b/packages/server/src/gh-token-source.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createGhTokenSource } from './gh-token-source.ts';
import type { DetectGhFn } from './github-permissions.ts';
diff --git a/packages/server/src/git-branch-info.test.ts b/packages/server/src/git-branch-info.test.ts
index 92bfffa60..4d6c5c245 100644
--- a/packages/server/src/git-branch-info.test.ts
+++ b/packages/server/src/git-branch-info.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
computeBranchInfo,
diff --git a/packages/server/src/git-checkout.test.ts b/packages/server/src/git-checkout.test.ts
index d5bf356b3..b0474433a 100644
--- a/packages/server/src/git-checkout.test.ts
+++ b/packages/server/src/git-checkout.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, describe, expect, test } from 'vitest';
import {
fastForwardBranchToOrigin,
diff --git a/packages/server/src/git-dirty.test.ts b/packages/server/src/git-dirty.test.ts
index 177c4e21b..d67722fc8 100644
--- a/packages/server/src/git-dirty.test.ts
+++ b/packages/server/src/git-dirty.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { dirtyFilesOverlapWith } from './git-dirty.ts';
let projectDir: string;
diff --git a/packages/server/src/git-handle.test.ts b/packages/server/src/git-handle.test.ts
index bc5e77721..aa8385683 100644
--- a/packages/server/src/git-handle.test.ts
+++ b/packages/server/src/git-handle.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { applyGitEnv, buildGitEnv, createGitInstance, type GitHandle } from './git-handle.ts';
import { withParentLock } from './git-mutex.ts';
diff --git a/packages/server/src/git-identity-sanitize.test.ts b/packages/server/src/git-identity-sanitize.test.ts
index 3865efb97..1b1ae3b4c 100644
--- a/packages/server/src/git-identity-sanitize.test.ts
+++ b/packages/server/src/git-identity-sanitize.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { sanitizeGitIdentity } from './git-identity-sanitize.ts';
describe('sanitizeGitIdentity', () => {
diff --git a/packages/server/src/git-identity.test.ts b/packages/server/src/git-identity.test.ts
index 517d37330..616dab248 100644
--- a/packages/server/src/git-identity.test.ts
+++ b/packages/server/src/git-identity.test.ts
@@ -5,7 +5,7 @@
* Chain: per-worktree → repo-local → global → tokenStore → null
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type GitConfigReader,
type GitIdentityTokenStore,
diff --git a/packages/server/src/git-identity.worktree.test.ts b/packages/server/src/git-identity.worktree.test.ts
index 1cdb3b7ee..c23225bf9 100644
--- a/packages/server/src/git-identity.worktree.test.ts
+++ b/packages/server/src/git-identity.worktree.test.ts
@@ -10,11 +10,11 @@
* the existing `--local` behavior.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { resolveGitIdentity, writeGitIdentity } from './git-identity.ts';
diff --git a/packages/server/src/git-paths.test.ts b/packages/server/src/git-paths.test.ts
index 0de7fe17a..96d61e332 100644
--- a/packages/server/src/git-paths.test.ts
+++ b/packages/server/src/git-paths.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { execSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
listNameStatus,
listNames,
diff --git a/packages/server/src/git-preflight-spawn.test.ts b/packages/server/src/git-preflight-spawn.test.ts
index 8c7791dbe..0ae3196d4 100644
--- a/packages/server/src/git-preflight-spawn.test.ts
+++ b/packages/server/src/git-preflight-spawn.test.ts
@@ -34,12 +34,12 @@
* invoked from a fresh subprocess.
*/
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
/**
* Path of the server-package root (where `package.json` lives). The
diff --git a/packages/server/src/git-preflight-telemetry.test.ts b/packages/server/src/git-preflight-telemetry.test.ts
index a5a5f3826..983cd1bbe 100644
--- a/packages/server/src/git-preflight-telemetry.test.ts
+++ b/packages/server/src/git-preflight-telemetry.test.ts
@@ -9,13 +9,13 @@
* covered separately in `git-preflight-boot.test.ts`.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { context, metrics, trace } from '@opentelemetry/api';
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { GitNotAvailableError, GitTooOldError, type InstallGuidance } from './git-preflight.ts';
import {
emitPreflightFailureSpan,
diff --git a/packages/server/src/handoff-api.test.ts b/packages/server/src/handoff-api.test.ts
index 1aa464916..4c20af880 100644
--- a/packages/server/src/handoff-api.test.ts
+++ b/packages/server/src/handoff-api.test.ts
@@ -1,5 +1,5 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
createInstalledAgentsProbe,
createOsProbe,
diff --git a/packages/server/src/handoff-dispatch-api.test.ts b/packages/server/src/handoff-dispatch-api.test.ts
index 77286c104..e0176cee4 100644
--- a/packages/server/src/handoff-dispatch-api.test.ts
+++ b/packages/server/src/handoff-dispatch-api.test.ts
@@ -14,9 +14,9 @@
* URN body) back to the in-process `HandoffOutcome` discriminated union.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
+import { describe, expect, test, vi } from 'vitest';
import {
type HandleHandoffDispatchDeps,
handleHandoffDispatch,
@@ -137,12 +137,12 @@ describe('resolveUrlOpenInvocation — per-platform protocol-URL opener', () =>
describe('handleHandoffDispatch — app-bundle cross-platform (Windows / Linux)', () => {
test('Windows claude-cowork, scheme registered → single rundll32 URL fire; no osascript/open -a', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
- const isSchemeRegistered = mock(async () => true);
- const sleep = mock(async (_ms: number) => undefined);
+ const isSchemeRegistered = vi.fn(async () => true);
+ const sleep = vi.fn(async (_ms: number) => undefined);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'claude-cowork', url: CLAUDE_URL }),
@@ -163,11 +163,11 @@ describe('handleHandoffDispatch — app-bundle cross-platform (Windows / Linux)'
test('Windows codex, scheme registered → rundll32 URL fire; quitFirst does NOT spawn osascript off-darwin', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
- const isSchemeRegistered = mock(async () => true);
+ const isSchemeRegistered = vi.fn(async () => true);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'codex', url: CODEX_URL }),
@@ -183,7 +183,7 @@ describe('handleHandoffDispatch — app-bundle cross-platform (Windows / Linux)'
test('Linux claude-code, scheme registered → single xdg-open URL fire', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
@@ -198,7 +198,7 @@ describe('handleHandoffDispatch — app-bundle cross-platform (Windows / Linux)'
});
test('Windows claude-cowork, scheme NOT registered → 422 handoff-target-not-installed; no spawn', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'claude-cowork', url: CLAUDE_URL }),
@@ -211,7 +211,7 @@ describe('handleHandoffDispatch — app-bundle cross-platform (Windows / Linux)'
});
test('Linux codex, scheme NOT registered → 422 handoff-target-not-installed; no spawn', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'codex', url: CODEX_URL }),
@@ -224,7 +224,7 @@ describe('handleHandoffDispatch — app-bundle cross-platform (Windows / Linux)'
});
test('Windows app-bundle URL-spawn failure (spawn-error) → 502 handoff-spawn-failed', async () => {
- const spawnDetached = mock(async () => ({ ok: false, reason: 'spawn-error' }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: false, reason: 'spawn-error' }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'claude-cowork', url: CLAUDE_URL }),
@@ -243,11 +243,11 @@ describe('handleHandoffDispatch — cursor cross-platform (cli-binary)', () => {
const cmdPath =
'C:\\Users\\who\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd';
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
- const sleep = mock(async (_ms: number) => undefined);
+ const sleep = vi.fn(async (_ms: number) => undefined);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'cursor', url: CURSOR_URL, workspacePath: winWorkspace }),
@@ -277,7 +277,7 @@ describe('handleHandoffDispatch — cursor cross-platform (cli-binary)', () => {
const linuxContentDir = '/home/who/dragons';
const linuxWorkspace = '/home/who/dragons/specs';
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
@@ -363,11 +363,11 @@ describe('handleHandoffDispatch — body validation', () => {
describe('handleHandoffDispatch — claude-cowork recipe (app-bundle, quitFirst=false)', () => {
test('happy path: open -a Claude → sleep → open URL; no osascript quit', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
- const sleep = mock(async (_ms: number) => undefined);
+ const sleep = vi.fn(async (_ms: number) => undefined);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'claude-cowork', url: CLAUDE_URL }),
@@ -388,7 +388,7 @@ describe('handleHandoffDispatch — claude-cowork recipe (app-bundle, quitFirst=
test('claude-code uses the same recipe as claude-cowork', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
@@ -407,7 +407,7 @@ describe('handleHandoffDispatch — claude-cowork recipe (app-bundle, quitFirst=
test('activate failure (not-installed) → 422 handoff-target-not-installed; URL spawn skipped', async () => {
let firstCall = true;
- const spawnDetached = mock(async () => {
+ const spawnDetached = vi.fn(async () => {
if (firstCall) {
firstCall = false;
return { ok: false, reason: 'not-installed' } as SpawnOutcome;
@@ -427,7 +427,7 @@ describe('handleHandoffDispatch — claude-cowork recipe (app-bundle, quitFirst=
test('URL spawn failure (timeout) → 504 handoff-spawn-timeout', async () => {
let callCount = 0;
- const spawnDetached = mock(async () => {
+ const spawnDetached = vi.fn(async () => {
callCount += 1;
if (callCount === 1) return { ok: true } as SpawnOutcome;
return { ok: false, reason: 'timeout' } as SpawnOutcome;
@@ -445,7 +445,7 @@ describe('handleHandoffDispatch — claude-cowork recipe (app-bundle, quitFirst=
test('URL spawn failure (spawn-error) → 502 handoff-spawn-failed', async () => {
let callCount = 0;
- const spawnDetached = mock(async () => {
+ const spawnDetached = vi.fn(async () => {
callCount += 1;
if (callCount === 1) return { ok: true } as SpawnOutcome;
return { ok: false, reason: 'spawn-error' } as SpawnOutcome;
@@ -464,11 +464,11 @@ describe('handleHandoffDispatch — claude-cowork recipe (app-bundle, quitFirst=
describe('handleHandoffDispatch — codex recipe (app-bundle, quitFirst=true)', () => {
test('happy path: osascript quit → sleep → open -a Codex → sleep → open URL', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
- const sleep = mock(async (_ms: number) => undefined);
+ const sleep = vi.fn(async (_ms: number) => undefined);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'codex', url: CODEX_URL }),
@@ -493,7 +493,7 @@ describe('handleHandoffDispatch — codex recipe (app-bundle, quitFirst=true)',
test('quit-step failure is swallowed; recipe still proceeds with activate + URL', async () => {
let callCount = 0;
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
callCount += 1;
calls.push({ exec, args: [...args] });
// First call is the quit step — return spawn-error to verify it's not a recipe-killer.
@@ -516,7 +516,7 @@ describe('handleHandoffDispatch — codex recipe (app-bundle, quitFirst=true)',
test('activate failure on codex → 422 handoff-target-not-installed with target=codex', async () => {
let callCount = 0;
- const spawnDetached = mock(async () => {
+ const spawnDetached = vi.fn(async () => {
callCount += 1;
// quit passes, activate fails.
if (callCount === 1) return { ok: true } as SpawnOutcome;
@@ -536,11 +536,11 @@ describe('handleHandoffDispatch — codex recipe (app-bundle, quitFirst=true)',
describe('handleHandoffDispatch — cursor recipe (cli-binary)', () => {
test('happy path: cursor <path> → sleep → open URL', async () => {
const calls: Array<{ exec: string; args: ReadonlyArray<string> }> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
calls.push({ exec, args: [...args] });
return { ok: true } as SpawnOutcome;
});
- const sleep = mock(async (_ms: number) => undefined);
+ const sleep = vi.fn(async (_ms: number) => undefined);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', {
@@ -565,7 +565,7 @@ describe('handleHandoffDispatch — cursor recipe (cli-binary)', () => {
});
test('missing workspacePath → 400 invalid-request; no spawn', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'cursor', url: CURSOR_URL }),
@@ -577,7 +577,7 @@ describe('handleHandoffDispatch — cursor recipe (cli-binary)', () => {
});
test('workspacePath outside contentDir → 403 path-escape; no spawn', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', { target: 'cursor', url: CURSOR_URL, workspacePath: '/etc/passwd' }),
@@ -589,7 +589,7 @@ describe('handleHandoffDispatch — cursor recipe (cli-binary)', () => {
});
test('cursor binary not found → 422 handoff-target-not-installed; no spawn', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', {
@@ -606,7 +606,7 @@ describe('handleHandoffDispatch — cursor recipe (cli-binary)', () => {
});
test('cursor spawn failure (timeout) → 504 handoff-spawn-timeout; URL spawn skipped', async () => {
- const spawnDetached = mock(async () => ({ ok: false, reason: 'timeout' }) as SpawnOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: false, reason: 'timeout' }) as SpawnOutcome);
const { res, captured } = makeRes();
await handleHandoffDispatch(
makeReq('POST', {
@@ -624,7 +624,7 @@ describe('handleHandoffDispatch — cursor recipe (cli-binary)', () => {
test('URL spawn failure after cursor → 502 handoff-spawn-failed', async () => {
let callCount = 0;
- const spawnDetached = mock(async () => {
+ const spawnDetached = vi.fn(async () => {
callCount += 1;
if (callCount === 1) return { ok: true } as SpawnOutcome;
return { ok: false, reason: 'spawn-error' } as SpawnOutcome;
diff --git a/packages/server/src/http/error-response.test.ts b/packages/server/src/http/error-response.test.ts
index 3b6f91978..19ad9ceb3 100644
--- a/packages/server/src/http/error-response.test.ts
+++ b/packages/server/src/http/error-response.test.ts
@@ -5,8 +5,8 @@
* re-expose the original crash risk that motivated the fix.
*/
-import { describe, expect, spyOn, test } from 'bun:test';
import type { ServerResponse } from 'node:http';
+import { describe, expect, test, vi } from 'vitest';
import { loggerFactory } from '../logger.ts';
import {
createStreamingErrorWriter,
@@ -57,7 +57,7 @@ describe('errorResponse — defense-in-depth branches', () => {
// but silently drop the diagnostic event — operators relying on
// `api.error.double-write` for alerting would never see the bug.
const log = loggerFactory.getLogger('http');
- const errorSpy = spyOn(log, 'error');
+ const errorSpy = vi.spyOn(log, 'error');
errorSpy.mockClear();
const { res, writeHeadCalls, endCalls } = makeMockRes({ headersSent: true });
@@ -100,8 +100,8 @@ describe('errorResponse — defense-in-depth branches', () => {
// Both regressions break monitoring contracts that the structured
// `api.error` event powers downstream.
const log = loggerFactory.getLogger('http');
- const warnSpy = spyOn(log, 'warn');
- const errorSpy = spyOn(log, 'error');
+ const warnSpy = vi.spyOn(log, 'warn');
+ const errorSpy = vi.spyOn(log, 'error');
warnSpy.mockClear();
errorSpy.mockClear();
@@ -288,7 +288,7 @@ describe('errorResponse — defense-in-depth branches', () => {
// Caller-supplied instance UUID is preserved across the fallback for
// grep correlation between the structured log and the wire envelope.
const log = loggerFactory.getLogger('http');
- const errorSpy = spyOn(log, 'error');
+ const errorSpy = vi.spyOn(log, 'error');
errorSpy.mockClear();
const { res, writeHeadCalls, endCalls } = makeMockRes();
diff --git a/packages/server/src/http/request-validation.test.ts b/packages/server/src/http/request-validation.test.ts
index c97f84a0f..de794291b 100644
--- a/packages/server/src/http/request-validation.test.ts
+++ b/packages/server/src/http/request-validation.test.ts
@@ -19,8 +19,8 @@
* regression in production.
*/
-import { describe, expect, test } from 'bun:test';
import type { IncomingMessage, ServerResponse } from 'node:http';
+import { describe, expect, test } from 'vitest';
import { z } from 'zod';
import {
PayloadTooLargeError,
diff --git a/packages/server/src/http/success-response.test.ts b/packages/server/src/http/success-response.test.ts
index a068a6751..114bacd42 100644
--- a/packages/server/src/http/success-response.test.ts
+++ b/packages/server/src/http/success-response.test.ts
@@ -7,8 +7,8 @@
* sites.
*/
-import { describe, expect, spyOn, test } from 'bun:test';
import type { ServerResponse } from 'node:http';
+import { describe, expect, test, vi } from 'vitest';
import { z } from 'zod';
import { loggerFactory } from '../logger.ts';
import { successResponse } from './success-response.ts';
@@ -116,7 +116,7 @@ describe('successResponse — defense-in-depth branches', () => {
// `api.success.double-write` observability event so a refactor that
// drops the `log.error()` call would fail this test.
const log = loggerFactory.getLogger('http');
- const errorSpy = spyOn(log, 'error');
+ const errorSpy = vi.spyOn(log, 'error');
errorSpy.mockClear();
const Schema = z.object({ x: z.number() });
@@ -234,7 +234,7 @@ describe('successResponse — defense-in-depth branches', () => {
// Asymmetric with errorResponse's malformed-envelope log: that body is
// the small fixed-shape ProblemDetails envelope, not unbounded user data.
const log = loggerFactory.getLogger('http');
- const errorSpy = spyOn(log, 'error');
+ const errorSpy = vi.spyOn(log, 'error');
errorSpy.mockClear();
const Schema = z.object({ x: z.number() });
@@ -280,7 +280,7 @@ describe('successResponse — defense-in-depth branches', () => {
// guard in `errorResponse` for symmetric defense across both wire-emit
// helpers.
const log = loggerFactory.getLogger('http');
- const errorSpy = spyOn(log, 'error');
+ const errorSpy = vi.spyOn(log, 'error');
errorSpy.mockClear();
const Schema = z.object({ checkpoint: z.unknown().nullable() });
@@ -321,7 +321,7 @@ describe('successResponse — defense-in-depth branches', () => {
// for any input — no crash on `Object.keys(null)`, no leak through
// stringification of the primitive.
const log = loggerFactory.getLogger('http');
- const errorSpy = spyOn(log, 'error');
+ const errorSpy = vi.spyOn(log, 'error');
errorSpy.mockClear();
const Schema = z.object({ x: z.number() });
diff --git a/packages/server/src/hub-candidates.test.ts b/packages/server/src/hub-candidates.test.ts
index b12062a89..a1d54f97c 100644
--- a/packages/server/src/hub-candidates.test.ts
+++ b/packages/server/src/hub-candidates.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { findHubCandidates } from './hub-candidates.ts';
function makeIndex(docNames: string[]): ReadonlyMap<string, unknown> {
diff --git a/packages/server/src/idle-shutdown.test.ts b/packages/server/src/idle-shutdown.test.ts
index 60003e10d..293f992c4 100644
--- a/packages/server/src/idle-shutdown.test.ts
+++ b/packages/server/src/idle-shutdown.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, mock, test } from 'bun:test';
import { EventEmitter } from 'node:events';
import type { Server as HttpServer, IncomingMessage } from 'node:http';
import type { Duplex } from 'node:stream';
import type { Scheduler } from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import { attachIdleShutdown } from './idle-shutdown';
// ─────────────────────────────────────────────────────────────
@@ -69,7 +69,7 @@ function emitUpgrade(server: HttpServer, url: string, socket: Duplex): void {
describe('attachIdleShutdown', () => {
test('fires onShutdown after thresholdMs when zero WebSocket clients', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -88,7 +88,7 @@ describe('attachIdleShutdown', () => {
test('incrementing WebSocket client count clears the shutdown timer', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -109,7 +109,7 @@ describe('attachIdleShutdown', () => {
test('decrementing WebSocket client count to zero restarts the timer', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -134,7 +134,7 @@ describe('attachIdleShutdown', () => {
test('reconnecting within the threshold resets the timer', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -153,7 +153,7 @@ describe('attachIdleShutdown', () => {
test('upgrades on non-/collab paths do NOT count', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -174,7 +174,7 @@ describe('attachIdleShutdown', () => {
// Simulates CC1 broadcaster + AgentSessionManager DirectConnections:
// they never transit an HTTP upgrade event. The timer must still fire.
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -192,13 +192,13 @@ describe('attachIdleShutdown', () => {
test('emits WARN at thresholdMs - warnBeforeMs (default 5 min before)', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
- const warnSpy = mock((_data: unknown, _message: string) => {});
+ const onShutdown = vi.fn(() => Promise.resolve());
+ const warnSpy = vi.fn((_data: unknown, _message: string) => {});
const log = {
warn: warnSpy,
- info: mock(() => {}),
- error: mock(() => {}),
- debug: mock(() => {}),
+ info: vi.fn(() => {}),
+ error: vi.fn(() => {}),
+ debug: vi.fn(() => {}),
} as unknown as Parameters<typeof attachIdleShutdown>[0]['log'];
const server = createFakeHttpServer();
@@ -225,12 +225,12 @@ describe('attachIdleShutdown', () => {
test('WARN is suppressed if warnBeforeMs >= thresholdMs', () => {
const scheduler = createManualScheduler();
- const warnSpy = mock((_data: unknown, _message: string) => {});
+ const warnSpy = vi.fn((_data: unknown, _message: string) => {});
const log = {
warn: warnSpy,
- info: mock(() => {}),
- error: mock(() => {}),
- debug: mock(() => {}),
+ info: vi.fn(() => {}),
+ error: vi.fn(() => {}),
+ debug: vi.fn(() => {}),
} as unknown as Parameters<typeof attachIdleShutdown>[0]['log'];
const server = createFakeHttpServer();
@@ -249,7 +249,7 @@ describe('attachIdleShutdown', () => {
test('detach() removes listener and cancels pending timers', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
const handle = attachIdleShutdown({
@@ -271,7 +271,7 @@ describe('attachIdleShutdown', () => {
test('detach() is idempotent and safe to call after onShutdown fires', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
const handle = attachIdleShutdown({
@@ -291,7 +291,7 @@ describe('attachIdleShutdown', () => {
test('onShutdown fires exactly once even if timer would re-trigger', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -315,7 +315,7 @@ describe('attachIdleShutdown', () => {
test('multiple concurrent WebSocket clients decrement independently', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => Promise.resolve());
+ const onShutdown = vi.fn(() => Promise.resolve());
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -344,7 +344,7 @@ describe('attachIdleShutdown', () => {
test('synchronous onShutdown is supported', () => {
const scheduler = createManualScheduler();
- const onShutdown = mock(() => {}); // void return, not a Promise
+ const onShutdown = vi.fn(() => {}); // void return, not a Promise
const server = createFakeHttpServer();
attachIdleShutdown({
@@ -361,12 +361,12 @@ describe('attachIdleShutdown', () => {
test('async onShutdown rejection is caught (logged, not thrown)', () => {
const scheduler = createManualScheduler();
- const errorSpy = mock((_data: unknown, _message: string) => {});
+ const errorSpy = vi.fn((_data: unknown, _message: string) => {});
const log = {
- warn: mock(() => {}),
- info: mock(() => {}),
+ warn: vi.fn(() => {}),
+ info: vi.fn(() => {}),
error: errorSpy,
- debug: mock(() => {}),
+ debug: vi.fn(() => {}),
} as unknown as Parameters<typeof attachIdleShutdown>[0]['log'];
const server = createFakeHttpServer();
diff --git a/packages/server/src/incident-replay.test.ts b/packages/server/src/incident-replay.test.ts
index 5c08b4427..4983b4fb5 100644
--- a/packages/server/src/incident-replay.test.ts
+++ b/packages/server/src/incident-replay.test.ts
@@ -9,7 +9,7 @@
* reconstructable from emitted telemetry + the diagnose repo-fact readers
* ALONE — no forensic bundle.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { randomUUID } from 'node:crypto';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
@@ -23,6 +23,7 @@ import {
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { createMaintenanceCoordinator } from './maintenance-coordinator.ts';
import {
__resetMaintenanceTelemetryForTesting,
diff --git a/packages/server/src/installed-skills-marker.test.ts b/packages/server/src/installed-skills-marker.test.ts
index beb750cbe..f26e0b6b1 100644
--- a/packages/server/src/installed-skills-marker.test.ts
+++ b/packages/server/src/installed-skills-marker.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
installedSkillsPath,
readInstalledSkills,
diff --git a/packages/server/src/keepalive-presence-bootstrap.test.ts b/packages/server/src/keepalive-presence-bootstrap.test.ts
index af5a7fdc0..4e20437e8 100644
--- a/packages/server/src/keepalive-presence-bootstrap.test.ts
+++ b/packages/server/src/keepalive-presence-bootstrap.test.ts
@@ -22,12 +22,13 @@
* bootstrap + lifecycle cleanup, with the existing `bumpPresenceTs`
* heartbeat keeping the entry fresh during the open WS.
*/
-import { afterAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { afterAll, describe, expect, test } from 'vitest';
import { WebSocket as WsClient } from 'ws';
import { toBroadcasterKey } from './agent-id.ts';
import { type BootedServer, bootServer } from './boot.ts';
diff --git a/packages/server/src/keepalive-presence-cleanup.test.ts b/packages/server/src/keepalive-presence-cleanup.test.ts
index e404717b6..bf70c6b08 100644
--- a/packages/server/src/keepalive-presence-cleanup.test.ts
+++ b/packages/server/src/keepalive-presence-cleanup.test.ts
@@ -15,12 +15,13 @@
* `bootServer` wires the keepalive-close → grace-timer → cleanup handler
* (that's the exact wiring under test).
*/
-import { afterAll, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { afterAll, describe, expect, test } from 'vitest';
import { WebSocket as WsClient } from 'ws';
import { toBroadcasterKey } from './agent-id.ts';
import { type BootedServer, bootServer } from './boot.ts';
diff --git a/packages/server/src/link-preview/ip-classifier.test.ts b/packages/server/src/link-preview/ip-classifier.test.ts
index b83a6b7bd..77d5b887f 100644
--- a/packages/server/src/link-preview/ip-classifier.test.ts
+++ b/packages/server/src/link-preview/ip-classifier.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyHost, isPublicUnicastIp } from './ip-classifier.ts';
describe('isPublicUnicastIp', () => {
diff --git a/packages/server/src/link-preview/metadata.test.ts b/packages/server/src/link-preview/metadata.test.ts
index 6539d46c4..34dea1ae1 100644
--- a/packages/server/src/link-preview/metadata.test.ts
+++ b/packages/server/src/link-preview/metadata.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import type { GuardedFetchOptions, GuardedFetchResult } from './guarded-fetch.ts';
import { buildLinkPreviewMetadata, type GuardedFetch } from './metadata.ts';
diff --git a/packages/server/src/link-preview/preview-cache.test.ts b/packages/server/src/link-preview/preview-cache.test.ts
index f8a467d8c..00717b7f3 100644
--- a/packages/server/src/link-preview/preview-cache.test.ts
+++ b/packages/server/src/link-preview/preview-cache.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { LinkPreviewMetadata } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
LinkPreviewCache,
type LinkPreviewCacheOptions,
diff --git a/packages/server/src/link-preview/request-gate.test.ts b/packages/server/src/link-preview/request-gate.test.ts
index 998f161d8..f122546bf 100644
--- a/packages/server/src/link-preview/request-gate.test.ts
+++ b/packages/server/src/link-preview/request-gate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
classifyLinkPreviewRequest,
isJsonContentType,
diff --git a/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts b/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts
index 0a09cfce4..107073cbc 100644
--- a/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts
+++ b/packages/server/src/lint-plugins/require-windowshide-on-spawn.test.ts
@@ -20,9 +20,9 @@
* excluded.
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper.ts';
const REPO_ROOT = join(__dirname, '..', '..', '..', '..');
diff --git a/packages/server/src/lint/audit-symlink.test.ts b/packages/server/src/lint/audit-symlink.test.ts
index 820eca219..0648a3f64 100644
--- a/packages/server/src/lint/audit-symlink.test.ts
+++ b/packages/server/src/lint/audit-symlink.test.ts
@@ -4,11 +4,11 @@
* lint diagnostics echo source text, so an escaped read is exfiltration.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { auditProject, lintDoc } from './audit.ts';
let root: string;
diff --git a/packages/server/src/lint/audit.test.ts b/packages/server/src/lint/audit.test.ts
index 7b35eb5e2..d8493b06a 100644
--- a/packages/server/src/lint/audit.test.ts
+++ b/packages/server/src/lint/audit.test.ts
@@ -4,11 +4,11 @@
* diagnostics-only audit payload.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { auditProject, lintDoc } from './audit.ts';
let root: string;
diff --git a/packages/server/src/lint/markdownlint-discovery.test.ts b/packages/server/src/lint/markdownlint-discovery.test.ts
index 7bd484939..f0042e627 100644
--- a/packages/server/src/lint/markdownlint-discovery.test.ts
+++ b/packages/server/src/lint/markdownlint-discovery.test.ts
@@ -6,7 +6,6 @@
* (markdownlint-cli2 semantics: nearest file governs wholesale).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
chmodSync,
mkdirSync,
@@ -18,6 +17,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
discoverMarkdownlintConfig,
readOwnNativeRules,
@@ -275,7 +275,7 @@ describe('readOwnNativeRules', () => {
// Root reads any file regardless of mode, so the permission probe only
// proves the rethrow when the process isn't privileged.
- test.if(process.getuid?.() !== 0)(
+ test.runIf(process.getuid?.() !== 0)(
'THROWS on a filesystem read failure — an unreadable file is not "no rules"',
() => {
write('.markdownlint.json', JSON.stringify({ MD013: false }));
diff --git a/packages/server/src/local-op-security.test.ts b/packages/server/src/local-op-security.test.ts
index 43c30f1b8..22777fb77 100644
--- a/packages/server/src/local-op-security.test.ts
+++ b/packages/server/src/local-op-security.test.ts
@@ -1,10 +1,10 @@
-import { afterAll, beforeAll, describe, expect, mock, test, vi } from 'bun:test';
import { EventEmitter } from 'node:events';
import type * as fs from 'node:fs';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
// node:fs is mocked so realpathSync/lstatSync can be redirected per test: vitest
// cannot redefine a live ESM namespace binding the way bun's spyOn did. The SUT
@@ -26,7 +26,7 @@ beforeAll(async () => {
realFs = await vi.importActual<typeof import('node:fs')>('node:fs');
realpathSyncMock.mockImplementation(realFs.realpathSync as (...args: never[]) => unknown);
lstatSyncMock.mockImplementation(realFs.lstatSync as (...args: never[]) => unknown);
- mock.module('node:fs', () => ({
+ vi.doMock('node:fs', () => ({
...realFs,
realpathSync: realpathSyncMock,
lstatSync: lstatSyncMock,
@@ -221,9 +221,8 @@ describe('isSafeLocalPath', () => {
//
// Tests inject a tmp dir as `home` so symlink scenarios can be exercised
// without touching the developer's actual home. The public `isSafeLocalPath`
-// is a thin wrapper over `isPathWithinHome(_, homedir())`; mocking `homedir()`
-// is unreliable in Bun (no `$HOME` honoring after first call; `mock.module`
-// leaks across files per server-factory.test.ts).
+// is a thin wrapper over `isPathWithinHome(_, homedir())`; exercising the
+// parameterized function keeps these cases independent of the real home path.
describe('isPathWithinHome — symlink containment', () => {
let fakeHome: string;
diff --git a/packages/server/src/local-ops/auth-flow.test.ts b/packages/server/src/local-ops/auth-flow.test.ts
index 6f64efc1b..cc3b5f099 100644
--- a/packages/server/src/local-ops/auth-flow.test.ts
+++ b/packages/server/src/local-ops/auth-flow.test.ts
@@ -5,7 +5,7 @@
* Fixture subprocesses spawned via `process.execPath -e <script>` so the tests
* don't require the project CLI on PATH.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { runDeviceFlowSubprocess } from './auth-flow.ts';
import type { AuthEvent } from './types.ts';
diff --git a/packages/server/src/local-ops/auth-query.test.ts b/packages/server/src/local-ops/auth-query.test.ts
index d34e10a6d..e35506db1 100644
--- a/packages/server/src/local-ops/auth-query.test.ts
+++ b/packages/server/src/local-ops/auth-query.test.ts
@@ -4,7 +4,7 @@
* Both spawn the CLI via `process.execPath -e <script>` for deterministic
* testing without depending on the project CLI being installed.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { runAuthReposSubprocess, runAuthStatusSubprocess } from './auth-query.ts';
const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];
diff --git a/packages/server/src/local-ops/clone-error-classify.test.ts b/packages/server/src/local-ops/clone-error-classify.test.ts
index a6628ac62..b47eb3296 100644
--- a/packages/server/src/local-ops/clone-error-classify.test.ts
+++ b/packages/server/src/local-ops/clone-error-classify.test.ts
@@ -14,7 +14,7 @@
* visible fix, so test assertions use `toBe` not `toMatch`.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyCloneError } from './clone-error-classify.ts';
// Pin copy at the test level — if these change, the title-mapping
diff --git a/packages/server/src/local-ops/clone-flow.preflight.test.ts b/packages/server/src/local-ops/clone-flow.preflight.test.ts
index c93992dea..885b33346 100644
--- a/packages/server/src/local-ops/clone-flow.preflight.test.ts
+++ b/packages/server/src/local-ops/clone-flow.preflight.test.ts
@@ -15,10 +15,11 @@
* surfaces it (sync throw, rejected `done`, or an error event) — see
* git-unusable-setup.test-helper.ts.
*/
-import { describe, expect, test } from 'bun:test';
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { delimiter, isAbsolute, join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
__resetResolveOnPathCacheForTests,
__seedResolveOnPathCacheForTests,
diff --git a/packages/server/src/local-ops/clone-flow.test.ts b/packages/server/src/local-ops/clone-flow.test.ts
index b863c0a40..9ab88b5ce 100644
--- a/packages/server/src/local-ops/clone-flow.test.ts
+++ b/packages/server/src/local-ops/clone-flow.test.ts
@@ -4,9 +4,9 @@
* `validateCloneInputs` URL/path allowlists.
*/
-import { describe, expect, test } from 'bun:test';
import { homedir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { type RawCloneEvent, runCloneSubprocess, validateCloneInputs } from './clone-flow.ts';
// `validateCloneInputs` confines the target to the user's home directory.
diff --git a/packages/server/src/local-ops/subprocess.test.ts b/packages/server/src/local-ops/subprocess.test.ts
index 948725bf2..5b5d9457a 100644
--- a/packages/server/src/local-ops/subprocess.test.ts
+++ b/packages/server/src/local-ops/subprocess.test.ts
@@ -5,8 +5,8 @@
* tests stay self-contained (no dependence on the project CLI being on PATH).
*/
-import { describe, expect, test } from 'bun:test';
import { delimiter as PATH_DELIMITER } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { runSubprocess } from './subprocess.ts';
const fixtureCli = (script: string): readonly string[] => [process.execPath, '-e', script];
diff --git a/packages/server/src/local-sink-resolver.test.ts b/packages/server/src/local-sink-resolver.test.ts
index 5668dff55..3934f62c7 100644
--- a/packages/server/src/local-sink-resolver.test.ts
+++ b/packages/server/src/local-sink-resolver.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { stringify as stringifyYaml } from 'yaml';
import { resolveLocalSinkConfig } from './local-sink-resolver';
diff --git a/packages/server/src/loopback-bind-discipline.test.ts b/packages/server/src/loopback-bind-discipline.test.ts
index 9539713f4..09b1bb790 100644
--- a/packages/server/src/loopback-bind-discipline.test.ts
+++ b/packages/server/src/loopback-bind-discipline.test.ts
@@ -28,10 +28,10 @@
* test cache invalidates with its own sources.
*/
-import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync } from 'node:fs';
import { basename, dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PACKAGE_ROOT = join(__dirname, '..');
diff --git a/packages/server/src/loopback.test.ts b/packages/server/src/loopback.test.ts
index d550fbc15..ecd8fb4bf 100644
--- a/packages/server/src/loopback.test.ts
+++ b/packages/server/src/loopback.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback';
describe('isLoopbackAddress', () => {
diff --git a/packages/server/src/machine-id.test.ts b/packages/server/src/machine-id.test.ts
index 4014a64be..5fe9d0739 100644
Binary files a/packages/server/src/machine-id.test.ts and b/packages/server/src/machine-id.test.ts differ
diff --git a/packages/server/src/maintenance-consolidation.test.ts b/packages/server/src/maintenance-consolidation.test.ts
index dc8babb8a..0b2a6a6e6 100644
--- a/packages/server/src/maintenance-consolidation.test.ts
+++ b/packages/server/src/maintenance-consolidation.test.ts
@@ -1,10 +1,10 @@
-import { beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { parseCheckpoint } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import simpleGit from 'simple-git';
+import { beforeEach, describe, expect, test } from 'vitest';
import { createMaintenanceCoordinator } from './maintenance-coordinator.ts';
import { commitWip, initShadowRepo, type ShadowHandle, shadowGit } from './shadow-repo.ts';
import { getDocumentHistory } from './timeline-query.ts';
diff --git a/packages/server/src/managed-artifact-persistence.test.ts b/packages/server/src/managed-artifact-persistence.test.ts
index 367487abc..b1f879624 100644
--- a/packages/server/src/managed-artifact-persistence.test.ts
+++ b/packages/server/src/managed-artifact-persistence.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { LINEAGE_EPOCH_KEY } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { FILE_WATCHER_ORIGIN } from './external-change.ts';
import {
diff --git a/packages/server/src/managed-artifact-watcher.test.ts b/packages/server/src/managed-artifact-watcher.test.ts
index 61d2436a0..88f3252f0 100644
--- a/packages/server/src/managed-artifact-watcher.test.ts
+++ b/packages/server/src/managed-artifact-watcher.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
type ManagedArtifactWatcherUnsubscribe,
startManagedArtifactWatcher,
diff --git a/packages/server/src/managed-rename-journal.test.ts b/packages/server/src/managed-rename-journal.test.ts
index 28d5fd605..c873c9c9c 100644
--- a/packages/server/src/managed-rename-journal.test.ts
+++ b/packages/server/src/managed-rename-journal.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -10,6 +9,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
createManagedRenameRecoveryJournal,
managedRenameJournalPath,
diff --git a/packages/server/src/managed-rename-rewrite.test.ts b/packages/server/src/managed-rename-rewrite.test.ts
index bcd8b1f58..bbaf89bef 100644
--- a/packages/server/src/managed-rename-rewrite.test.ts
+++ b/packages/server/src/managed-rename-rewrite.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
rewriteAssetReferencesForRename,
rewriteMarkdownLinksForDocumentRename,
diff --git a/packages/server/src/managed-rename.test.ts b/packages/server/src/managed-rename.test.ts
index e85b1d986..82d0184d9 100644
--- a/packages/server/src/managed-rename.test.ts
+++ b/packages/server/src/managed-rename.test.ts
@@ -19,10 +19,11 @@
* partial-failure recovery), specialized to the rename call site whose write
* sequence is open-coded inside the api-extension closure.
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+
import { applyFastDiff, sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { MANAGED_RENAME_ORIGIN } from './api-extension.ts';
import { mdManager } from './md-manager.ts';
diff --git a/packages/server/src/map-driven-splice.test.ts b/packages/server/src/map-driven-splice.test.ts
index d674c46df..b6b9ac03e 100644
--- a/packages/server/src/map-driven-splice.test.ts
+++ b/packages/server/src/map-driven-splice.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { computeMapDrivenBodySplice } from './map-driven-splice.ts';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
diff --git a/packages/server/src/map-driven-splice.unchanged-detector.test.ts b/packages/server/src/map-driven-splice.unchanged-detector.test.ts
index c359ea153..94382980b 100644
--- a/packages/server/src/map-driven-splice.unchanged-detector.test.ts
+++ b/packages/server/src/map-driven-splice.unchanged-detector.test.ts
@@ -6,9 +6,9 @@
* children whose bytes the editor never touched.
*/
-import { describe, expect, test } from 'bun:test';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import type { JSONContent } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import { computeMapDrivenBodySplice } from './map-driven-splice.ts';
const mdManager = new MarkdownManager({ extensions: sharedExtensions });
diff --git a/packages/server/src/mcp-http.test.ts b/packages/server/src/mcp-http.test.ts
index c6e25b12a..6e4512c62 100644
--- a/packages/server/src/mcp-http.test.ts
+++ b/packages/server/src/mcp-http.test.ts
@@ -12,12 +12,13 @@
* Co-located with `mcp-http.ts`; the `packages/app/tests/integration/mcp-http.test.ts`
* sibling covers the basic init+tools/list flow.
*/
-import { afterEach, beforeEach, expect, test } from 'bun:test';
+
import { mkdtempSync, rmSync } from 'node:fs';
import { createServer as createHttpServer, type Server as HttpServer } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
+import { afterEach, beforeEach, expect, test } from 'vitest';
import { type Config, ConfigSchema } from './config/schema.ts';
import { getFreeLoopbackPort } from './loopback-rig-test-helpers.ts';
import { MCP_CONNECTION_ID_HEADER } from './mcp/agent-identity.ts';
diff --git a/packages/server/src/mcp-mount.test.ts b/packages/server/src/mcp-mount.test.ts
index 3c00b88a5..a14f0a24f 100644
--- a/packages/server/src/mcp-mount.test.ts
+++ b/packages/server/src/mcp-mount.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer, type Server as HttpServer, request as httpRequest } from 'node:http';
import { connect as createNetConnection } from 'node:net';
@@ -11,6 +10,7 @@ import {
INLINE_RENDERABLE_EXTENSIONS,
} from '@inkeep/open-knowledge-core';
import sirv from 'sirv';
+import { afterEach, describe, expect, test } from 'vitest';
import { WebSocket } from 'ws';
import { createAssetServeMiddleware } from './asset-serve-middleware.ts';
import { getFreeLoopbackPort } from './loopback-rig-test-helpers.ts';
diff --git a/packages/server/src/mcp/logger.test.ts b/packages/server/src/mcp/logger.test.ts
index 2c280a952..6495e1d8c 100644
--- a/packages/server/src/mcp/logger.test.ts
+++ b/packages/server/src/mcp/logger.test.ts
@@ -1,4 +1,4 @@
-import { describe as _bunDescribe, afterEach, beforeEach, expect, spyOn, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test, vi } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
// test setup spawns git children that Bun fails to reap on ubuntu-latest
@@ -14,8 +14,8 @@ import { getCurrentMcpLogger, McpLogger, runWithMcpLogger } from './logger.ts';
describe('McpLogger', () => {
let stderrLines: string[];
- let stderrSpy: ReturnType<typeof spyOn>;
- let warnSpy: ReturnType<typeof spyOn> | undefined;
+ let stderrSpy: ReturnType<typeof vi.spyOn>;
+ let warnSpy: ReturnType<typeof vi.spyOn> | undefined;
let tmpLogDir: string | undefined;
let originalMcpDebug: string | undefined;
let originalDebug: string | undefined;
@@ -23,7 +23,9 @@ describe('McpLogger', () => {
beforeEach(() => {
stderrLines = [];
- stderrSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => {
+ stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(((
+ chunk: string | Uint8Array,
+ ) => {
stderrLines.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8'));
return true;
}) as never);
@@ -89,7 +91,7 @@ describe('McpLogger', () => {
test('warns when OK_LOG_FILE cannot be written', () => {
tmpLogDir = mkdtempSync(resolve(tmpdir(), 'ok-mcp-logger-'));
process.env.OK_LOG_FILE = tmpLogDir;
- warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const logger = new McpLogger();
logger.info('persist this');
diff --git a/packages/server/src/mcp/pretty-zod-errors.test.ts b/packages/server/src/mcp/pretty-zod-errors.test.ts
index 421499d02..12eee18d9 100644
--- a/packages/server/src/mcp/pretty-zod-errors.test.ts
+++ b/packages/server/src/mcp/pretty-zod-errors.test.ts
@@ -14,9 +14,10 @@
* see in the chat surface (`McpError.message`), not how the formatter is
* structured internally. Keeps the test resilient to formatter changes.
*/
-import { describe, expect, test } from 'bun:test';
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
+import { describe, expect, test } from 'vitest';
import { z } from 'zod';
import { installPrettyZodErrors } from './pretty-zod-errors.ts';
diff --git a/packages/server/src/mcp/tool-logging.test.ts b/packages/server/src/mcp/tool-logging.test.ts
index 99965b7be..f36826538 100644
--- a/packages/server/src/mcp/tool-logging.test.ts
+++ b/packages/server/src/mcp/tool-logging.test.ts
@@ -1,4 +1,4 @@
-import { describe as _bunDescribe, afterEach, beforeEach, expect, spyOn, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test, vi } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
// test setup spawns git children that Bun fails to reap on ubuntu-latest
@@ -13,11 +13,13 @@ import { textPlusStructured } from './tools/shared.ts';
describe('tool logging wrapper', () => {
let stderrLines: string[];
- let stderrSpy: ReturnType<typeof spyOn>;
+ let stderrSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
stderrLines = [];
- stderrSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string | Uint8Array) => {
+ stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(((
+ chunk: string | Uint8Array,
+ ) => {
stderrLines.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8'));
return true;
}) as never);
diff --git a/packages/server/src/mcp/tools/advisory-warnings.test.ts b/packages/server/src/mcp/tools/advisory-warnings.test.ts
index 98892f3ca..a6017935e 100644
--- a/packages/server/src/mcp/tools/advisory-warnings.test.ts
+++ b/packages/server/src/mcp/tools/advisory-warnings.test.ts
@@ -4,7 +4,6 @@
* make every advisory family visible to text-only MCP consumers.
*/
-import { describe, expect, test } from 'bun:test';
import type {
AdvisoryWarning,
BrokenLink,
@@ -12,6 +11,7 @@ import type {
RenderWarning,
WriteWarning,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
formatAdvisoryBriefs,
formatAdvisoryLines,
diff --git a/packages/server/src/mcp/tools/checkpoint.test.ts b/packages/server/src/mcp/tools/checkpoint.test.ts
index eda541c12..e6faa560f 100644
--- a/packages/server/src/mcp/tools/checkpoint.test.ts
+++ b/packages/server/src/mcp/tools/checkpoint.test.ts
@@ -1,3 +1,6 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
import {
describe as _bunDescribe,
afterAll,
@@ -6,10 +9,7 @@ import {
beforeEach,
expect,
test,
-} from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
+} from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type CheckpointDeps, DESCRIPTION, register } from './checkpoint.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
diff --git a/packages/server/src/mcp/tools/config.test.ts b/packages/server/src/mcp/tools/config.test.ts
index 63211f026..b5f56664d 100644
--- a/packages/server/src/mcp/tools/config.test.ts
+++ b/packages/server/src/mcp/tools/config.test.ts
@@ -1,4 +1,4 @@
-import { describe as _bunDescribe, expect, test } from 'bun:test';
+import { describe as _bunDescribe, expect, test } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
// test setup spawns git children that Bun fails to reap on ubuntu-latest
diff --git a/packages/server/src/mcp/tools/conflicts.test.ts b/packages/server/src/mcp/tools/conflicts.test.ts
index 93a0b0027..4c28646e9 100644
--- a/packages/server/src/mcp/tools/conflicts.test.ts
+++ b/packages/server/src/mcp/tools/conflicts.test.ts
@@ -1,7 +1,7 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register } from './conflicts.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
diff --git a/packages/server/src/mcp/tools/exec.test.ts b/packages/server/src/mcp/tools/exec.test.ts
index 90e5d932d..f380c8edd 100644
--- a/packages/server/src/mcp/tools/exec.test.ts
+++ b/packages/server/src/mcp/tools/exec.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { commitWip, initShadowRepo, type WriterIdentity } from '@inkeep/open-knowledge-server';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { EnrichedMeta } from '../../content/enrichment.ts';
import {
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index 35799fef6..13dcdefb6 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -10,10 +10,10 @@
* recovery hint (`ok start` vs `ok ui` by `server.lock` liveness).
*/
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { AutoStartDisabledError } from '../../autostart.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { OffCwdResolverDeps } from '../../off-cwd-resolver.ts';
diff --git a/packages/server/src/mcp/tools/history.test.ts b/packages/server/src/mcp/tools/history.test.ts
index 5e9d7ec05..b74ea9c0c 100644
--- a/packages/server/src/mcp/tools/history.test.ts
+++ b/packages/server/src/mcp/tools/history.test.ts
@@ -6,7 +6,7 @@ import {
beforeEach,
expect,
test,
-} from 'bun:test';
+} from 'vitest';
import { bindTestUiLock } from './preview-url-test-helpers.ts';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
diff --git a/packages/server/src/mcp/tools/links.test.ts b/packages/server/src/mcp/tools/links.test.ts
index 06bb4d53f..9c94fe04e 100644
--- a/packages/server/src/mcp/tools/links.test.ts
+++ b/packages/server/src/mcp/tools/links.test.ts
@@ -1,3 +1,6 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
import {
describe as _bunDescribe,
afterAll,
@@ -6,10 +9,7 @@ import {
beforeEach,
expect,
test,
-} from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
+} from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import { DESCRIPTION, type LinksDeps, register } from './links.ts';
diff --git a/packages/server/src/mcp/tools/lint.test.ts b/packages/server/src/mcp/tools/lint.test.ts
index e569818b6..6b0c61fd9 100644
--- a/packages/server/src/mcp/tools/lint.test.ts
+++ b/packages/server/src/mcp/tools/lint.test.ts
@@ -1,3 +1,6 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
import {
describe as _bunDescribe,
afterAll,
@@ -6,10 +9,7 @@ import {
beforeEach,
expect,
test,
-} from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
+} from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import {
diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
index 6b73eb49c..3672506c4 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -20,7 +20,6 @@
* goes through `textPlusStructured`).
*/
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -36,6 +35,7 @@ import { join } from 'node:path';
import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register as registerConfig } from './config.ts';
import { registerAllTools } from './index.ts';
diff --git a/packages/server/src/mcp/tools/palette.test.ts b/packages/server/src/mcp/tools/palette.test.ts
index 8c7414960..3587c4441 100644
--- a/packages/server/src/mcp/tools/palette.test.ts
+++ b/packages/server/src/mcp/tools/palette.test.ts
@@ -5,12 +5,12 @@
* every registry-backed authoring form must name a live canonical descriptor.
*/
-import { describe, expect, test } from 'bun:test';
import {
getAgentCanonicalDescriptors,
PREVIEW_EMBED_STARTERS,
PREVIEW_THEME_TOKENS,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register } from './palette.ts';
import type { ServerInstance } from './shared.ts';
diff --git a/packages/server/src/mcp/tools/path-safety.test.ts b/packages/server/src/mcp/tools/path-safety.test.ts
index cd8ec020e..7e349566a 100644
--- a/packages/server/src/mcp/tools/path-safety.test.ts
+++ b/packages/server/src/mcp/tools/path-safety.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveWithinRoot } from './path-safety.ts';
describe('resolveWithinRoot — accepts inputs contained in root', () => {
diff --git a/packages/server/src/mcp/tools/preview-url.test.ts b/packages/server/src/mcp/tools/preview-url.test.ts
index 55dd35a91..463e53c50 100644
--- a/packages/server/src/mcp/tools/preview-url.test.ts
+++ b/packages/server/src/mcp/tools/preview-url.test.ts
@@ -1,4 +1,4 @@
-import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
// test setup spawns git children that Bun fails to reap on ubuntu-latest
diff --git a/packages/server/src/mcp/tools/resolve-conflict.test.ts b/packages/server/src/mcp/tools/resolve-conflict.test.ts
index e6df0c544..59ffe100d 100644
--- a/packages/server/src/mcp/tools/resolve-conflict.test.ts
+++ b/packages/server/src/mcp/tools/resolve-conflict.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register } from './resolve-conflict.ts';
import { HOCUSPOCUS_NOT_RUNNING_ERROR, type ServerInstance } from './shared.ts';
diff --git a/packages/server/src/mcp/tools/restore-version.test.ts b/packages/server/src/mcp/tools/restore-version.test.ts
index 63f96d7bd..6f616d671 100644
--- a/packages/server/src/mcp/tools/restore-version.test.ts
+++ b/packages/server/src/mcp/tools/restore-version.test.ts
@@ -1,3 +1,6 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
import {
describe as _bunDescribe,
afterAll,
@@ -6,10 +9,7 @@ import {
beforeEach,
expect,
test,
-} from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
+} from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import { DESCRIPTION, type RestoreVersionDeps, register } from './restore-version.ts';
diff --git a/packages/server/src/mcp/tools/search.test.ts b/packages/server/src/mcp/tools/search.test.ts
index e426ffb94..f05421be8 100644
--- a/packages/server/src/mcp/tools/search.test.ts
+++ b/packages/server/src/mcp/tools/search.test.ts
@@ -6,10 +6,10 @@
* isolation.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { bindTestUiLock } from './preview-url-test-helpers.ts';
import { DESCRIPTION, register } from './search.ts';
@@ -66,7 +66,7 @@ afterEach(() => {
});
function mockFetchOk(payload: Record<string, unknown>): void {
- globalThis.fetch = mock(async (_url: string, _init?: RequestInit) => {
+ globalThis.fetch = vi.fn(async (_url: string, _init?: RequestInit) => {
return new Response(JSON.stringify(payload), {
status: 200,
headers: { 'content-type': 'application/json' },
@@ -83,7 +83,7 @@ function mockFetchProblem(
status: number,
payload: { type: string; title: string; detail?: string; instance?: string },
): void {
- globalThis.fetch = mock(async (_url: string, _init?: RequestInit) => {
+ globalThis.fetch = vi.fn(async (_url: string, _init?: RequestInit) => {
return new Response(JSON.stringify({ ...payload, status }), {
status,
headers: { 'content-type': 'application/problem+json' },
@@ -142,7 +142,7 @@ describe('search MCP tool — registration', () => {
describe('search MCP tool — happy path', () => {
test('forwards query / intent / scopes / limit to POST /api/search and normalizes the response', async () => {
const captured: { url?: string; init?: RequestInit } = {};
- globalThis.fetch = mock(async (url: string, init?: RequestInit) => {
+ globalThis.fetch = vi.fn(async (url: string, init?: RequestInit) => {
captured.url = String(url);
captured.init = init;
return new Response(
@@ -239,7 +239,7 @@ describe('search MCP tool — happy path', () => {
test("default intent is 'full_text' when caller omits it (D4)", async () => {
const captured: { body?: string } = {};
- globalThis.fetch = mock(async (_url: string, init?: RequestInit) => {
+ globalThis.fetch = vi.fn(async (_url: string, init?: RequestInit) => {
captured.body = String(init?.body);
return new Response(JSON.stringify({ ok: true, results: [] }), {
status: 200,
@@ -262,7 +262,7 @@ describe('search MCP tool — happy path', () => {
test('semantic:false is forwarded as the per-call lexical override', async () => {
const captured: { body?: string } = {};
- globalThis.fetch = mock(async (_url: string, init?: RequestInit) => {
+ globalThis.fetch = vi.fn(async (_url: string, init?: RequestInit) => {
captured.body = String(init?.body);
return new Response(JSON.stringify({ ok: true, results: [] }), {
status: 200,
@@ -364,7 +364,7 @@ describe('search MCP tool — happy path', () => {
test("scopes:['file'] is forwarded to /api/search (Zod accepts 'file')", async () => {
const captured: { body?: string } = {};
- globalThis.fetch = mock(async (_url: string, init?: RequestInit) => {
+ globalThis.fetch = vi.fn(async (_url: string, init?: RequestInit) => {
captured.body = String(init?.body);
return new Response(JSON.stringify({ ok: true, results: [] }), {
status: 200,
diff --git a/packages/server/src/mcp/tools/share-link.test.ts b/packages/server/src/mcp/tools/share-link.test.ts
index a835918f2..534ecd55f 100644
--- a/packages/server/src/mcp/tools/share-link.test.ts
+++ b/packages/server/src/mcp/tools/share-link.test.ts
@@ -14,10 +14,11 @@
* `urn:ok:error:doc-not-found` envelope.
* - Happy path returns the marketing share URL + branch + resolvedKind.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { hostname, tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import { register, type ShareLinkDeps } from './share-link.ts';
diff --git a/packages/server/src/mcp/tools/shared.test.ts b/packages/server/src/mcp/tools/shared.test.ts
index dc7807248..9e948e081 100644
--- a/packages/server/src/mcp/tools/shared.test.ts
+++ b/packages/server/src/mcp/tools/shared.test.ts
@@ -12,7 +12,7 @@
* tests in CI would let regressions like the 2xx-with-`type`+`title`
* misclassification slip through.
*/
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { z } from 'zod';
import { type Config, ConfigSchema } from '../../config/schema.ts';
diff --git a/packages/server/src/mcp/tools/skill-target.test.ts b/packages/server/src/mcp/tools/skill-target.test.ts
index a5c1e26f0..932e1cd49 100644
--- a/packages/server/src/mcp/tools/skill-target.test.ts
+++ b/packages/server/src/mcp/tools/skill-target.test.ts
@@ -13,7 +13,7 @@
* runs in CI too.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
import { deleteSkill, moveSkill, moveSkillCrossScope, writeSkill } from './skill-target.ts';
diff --git a/packages/server/src/mcp/tools/skills.test.ts b/packages/server/src/mcp/tools/skills.test.ts
index 0ca7edc72..8f6a94ab9 100644
--- a/packages/server/src/mcp/tools/skills.test.ts
+++ b/packages/server/src/mcp/tools/skills.test.ts
@@ -7,7 +7,7 @@
* round-trip (a project `.md` ref joining the link graph, a script round-trip
* read) lives in the integration suite.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { BUNDLE_SKILL_NAME } from '../../skill-bundles.ts';
import { HOCUSPOCUS_NOT_RUNNING_ERROR, type ServerInstance } from './shared.ts';
diff --git a/packages/server/src/mcp/tools/summary-passthrough.test.ts b/packages/server/src/mcp/tools/summary-passthrough.test.ts
index 24e3d9127..afde31dde 100644
--- a/packages/server/src/mcp/tools/summary-passthrough.test.ts
+++ b/packages/server/src/mcp/tools/summary-passthrough.test.ts
@@ -15,7 +15,7 @@ import {
beforeEach,
expect,
test,
-} from 'bun:test';
+} from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
// test setup spawns git children that Bun fails to reap on ubuntu-latest
diff --git a/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts b/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
index 0f937d2ad..4d45d1bc1 100644
--- a/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
+++ b/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
@@ -15,7 +15,6 @@
* silently re-break local-inference and function-calling clients.
*/
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -24,6 +23,7 @@ import { join } from 'node:path';
// pinned to an exact version so a minor bump can't silently rename them.
import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { registerAllTools } from './index.ts';
import type { ServerInstance } from './shared.ts';
diff --git a/packages/server/src/mcp/tools/verb-schemas.test.ts b/packages/server/src/mcp/tools/verb-schemas.test.ts
index e77b10983..cefab4593 100644
--- a/packages/server/src/mcp/tools/verb-schemas.test.ts
+++ b/packages/server/src/mcp/tools/verb-schemas.test.ts
@@ -5,7 +5,7 @@
* accept. These tests pin the wire-level acceptance so a future schema
* rewrite can't silently re-introduce the "flat-only" contract.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { SUPPORTED_DOC_EXTENSIONS } from '../../doc-extensions.ts';
import { DocExtensionArg, FrontmatterArg, resolveSkillFilePath } from './verb-schemas.ts';
diff --git a/packages/server/src/mcp/tools/verb-tools.test.ts b/packages/server/src/mcp/tools/verb-tools.test.ts
index aff5839ac..761a97625 100644
--- a/packages/server/src/mcp/tools/verb-tools.test.ts
+++ b/packages/server/src/mcp/tools/verb-tools.test.ts
@@ -6,7 +6,7 @@
* suite), and the migration meta-test that fails if the shipped skill
* surface still teaches a retired tool name.
*/
-import { describe, expect, test } from 'bun:test';
+
import {
existsSync,
mkdirSync,
@@ -19,6 +19,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register as registerDelete } from './delete.ts';
import { register as registerEdit } from './edit.ts';
diff --git a/packages/server/src/mcp/tools/workflow.test.ts b/packages/server/src/mcp/tools/workflow.test.ts
index daad897c8..e6b5ceb25 100644
--- a/packages/server/src/mcp/tools/workflow.test.ts
+++ b/packages/server/src/mcp/tools/workflow.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { ServerInstance } from './shared.ts';
import { DESCRIPTION, register } from './workflow.ts';
diff --git a/packages/server/src/mcp/tools/write.test.ts b/packages/server/src/mcp/tools/write.test.ts
index db292d91e..68af74757 100644
--- a/packages/server/src/mcp/tools/write.test.ts
+++ b/packages/server/src/mcp/tools/write.test.ts
@@ -8,8 +8,9 @@
* prepended a SECOND block, stacking two frontmatter blocks on disk. The fix
* merges the embedded block with the param (param wins) into a single block.
*/
-import { describe, expect, it } from 'bun:test';
+
import { stripFrontmatter } from '@inkeep/open-knowledge-core';
+import { describe, expect, it } from 'vitest';
import { composeWithFrontmatter } from './write.ts';
/** Count leading-or-anywhere `---` fence lines that open a frontmatter block. */
diff --git a/packages/server/src/mermaid-persistence.test.ts b/packages/server/src/mermaid-persistence.test.ts
index 2bbcf0c25..007e423e5 100644
--- a/packages/server/src/mermaid-persistence.test.ts
+++ b/packages/server/src/mermaid-persistence.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { LINEAGE_EPOCH_KEY } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import {
loadMermaidDoc,
diff --git a/packages/server/src/mermaid-validator.test.ts b/packages/server/src/mermaid-validator.test.ts
index dde01d6be..a663b14ab 100644
--- a/packages/server/src/mermaid-validator.test.ts
+++ b/packages/server/src/mermaid-validator.test.ts
@@ -5,7 +5,7 @@
* hygiene, input caps, error classification, and failure containment.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import {
extractMermaidFences,
setMermaidImporterForTests,
diff --git a/packages/server/src/mermaid-version-alignment.test.ts b/packages/server/src/mermaid-version-alignment.test.ts
index 21c729056..30ebe8f46 100644
--- a/packages/server/src/mermaid-version-alignment.test.ts
+++ b/packages/server/src/mermaid-version-alignment.test.ts
@@ -6,9 +6,9 @@
* together.
*/
-import { expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { expect, test } from 'vitest';
test('server and app declare the identical mermaid range', () => {
const serverPkg = JSON.parse(readFileSync(join(import.meta.dir, '../package.json'), 'utf8')) as {
diff --git a/packages/server/src/metrics.test.ts b/packages/server/src/metrics.test.ts
index 02e888883..1aac747a3 100644
--- a/packages/server/src/metrics.test.ts
+++ b/packages/server/src/metrics.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
getMetrics,
handleCollabSocketError,
diff --git a/packages/server/src/missing-ok-config-error.test.ts b/packages/server/src/missing-ok-config-error.test.ts
index f96f4a981..f0434f887 100644
--- a/packages/server/src/missing-ok-config-error.test.ts
+++ b/packages/server/src/missing-ok-config-error.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { MISSING_OK_CONFIG_MESSAGE, MissingOkConfigError } from './missing-ok-config-error.ts';
describe('MissingOkConfigError', () => {
diff --git a/packages/server/src/observer-bridge-spans.test.ts b/packages/server/src/observer-bridge-spans.test.ts
index 123479c84..a163fac98 100644
--- a/packages/server/src/observer-bridge-spans.test.ts
+++ b/packages/server/src/observer-bridge-spans.test.ts
@@ -13,7 +13,7 @@
* Bounded-enum + pre-validated string attributes only (STOP
* rule: no raw paths, no doc content, no free-form user strings).
*/
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
+
import { context, metrics, trace } from '@opentelemetry/api';
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
import {
@@ -22,6 +22,7 @@ import {
type ReadableSpan,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import * as Y from 'yjs';
import { composeAndWriteRawBody } from './bridge-intake';
import { mdManager, schema } from './md-manager';
diff --git a/packages/server/src/off-cwd-resolver.test.ts b/packages/server/src/off-cwd-resolver.test.ts
index a009bbd53..d414f62c6 100644
--- a/packages/server/src/off-cwd-resolver.test.ts
+++ b/packages/server/src/off-cwd-resolver.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
type OffCwdCandidate,
type OffCwdResolverDeps,
diff --git a/packages/server/src/on-agent-write.test.ts b/packages/server/src/on-agent-write.test.ts
index 6f562e3da..dc6b38804 100644
--- a/packages/server/src/on-agent-write.test.ts
+++ b/packages/server/src/on-agent-write.test.ts
@@ -5,13 +5,14 @@
* /api/agent-write-md, edit_document → /api/agent-patch). The CLI layer uses
* this signal to auto-open the browser on the first agent edit per session.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
+import { describe, expect, test } from 'vitest';
import {
AGENT_WRITE_ORIGIN,
AgentSessionManager,
diff --git a/packages/server/src/package-exports.test.ts b/packages/server/src/package-exports.test.ts
index 0b8b461d1..920e0bbe1 100644
--- a/packages/server/src/package-exports.test.ts
+++ b/packages/server/src/package-exports.test.ts
@@ -36,9 +36,9 @@
* packaged Electron main).
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
interface ExportEntry {
development?: string;
diff --git a/packages/server/src/page-identity.test.ts b/packages/server/src/page-identity.test.ts
index d83000667..e37adaf16 100644
--- a/packages/server/src/page-identity.test.ts
+++ b/packages/server/src/page-identity.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
extractPageAliases,
extractPageIcon,
diff --git a/packages/server/src/paired-write-enforcement.test.ts b/packages/server/src/paired-write-enforcement.test.ts
index 411096036..ca683fec5 100644
--- a/packages/server/src/paired-write-enforcement.test.ts
+++ b/packages/server/src/paired-write-enforcement.test.ts
@@ -17,7 +17,7 @@
* origin name that doesn't match one of the three buckets fails loudly with
* a message naming the file:line and the unrecognized origin.
*/
-import { beforeAll, describe, expect, test } from 'bun:test';
+
import { join, relative } from 'node:path';
import {
type CallExpression,
@@ -27,6 +27,7 @@ import {
type SourceFile,
SyntaxKind,
} from 'ts-morph';
+import { beforeAll, describe, expect, test } from 'vitest';
// ─── Allowlists ──────────────────────────────────────────────
diff --git a/packages/server/src/paired-write-origin.test.ts b/packages/server/src/paired-write-origin.test.ts
index 117e4025d..e6e42f6b3 100644
--- a/packages/server/src/paired-write-origin.test.ts
+++ b/packages/server/src/paired-write-origin.test.ts
@@ -15,7 +15,7 @@
* the negative `@ts-expect-error` cases.
*/
-import { describe, test } from 'bun:test';
+import { describe, test } from 'vitest';
import type { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
import type { MANAGED_RENAME_ORIGIN, ROLLBACK_ORIGIN } from './api-extension.ts';
import type { FILE_WATCHER_ORIGIN } from './external-change.ts';
diff --git a/packages/server/src/path-conditional-map-driven-origin.test.ts b/packages/server/src/path-conditional-map-driven-origin.test.ts
index 09b15ca72..483e2ecb7 100644
--- a/packages/server/src/path-conditional-map-driven-origin.test.ts
+++ b/packages/server/src/path-conditional-map-driven-origin.test.ts
@@ -23,9 +23,9 @@
* (the file missing from the override) fails CI.
*/
-import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readBiomeConfig } from '../../../test-support/read-biome-config.test-helper';
const REPO_ROOT = join(__dirname, '..', '..', '..');
diff --git a/packages/server/src/path-utils.test.ts b/packages/server/src/path-utils.test.ts
index feb6fcaa6..51c69ee8f 100644
--- a/packages/server/src/path-utils.test.ts
+++ b/packages/server/src/path-utils.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isWithinDir, toPosix } from './path-utils.ts';
// These exercise the Windows (`\`-separated) branch on a POSIX CI runner — the
diff --git a/packages/server/src/perf-measurement.test.ts b/packages/server/src/perf-measurement.test.ts
index f80c7402b..446565c92 100644
--- a/packages/server/src/perf-measurement.test.ts
+++ b/packages/server/src/perf-measurement.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
import type { Extension, Hocuspocus } from '@hocuspocus/server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
captureServerMemorySnapshot,
installPerfMeasurementHttpRoute,
diff --git a/packages/server/src/persistence-fan-out.test.ts b/packages/server/src/persistence-fan-out.test.ts
index 62da912c9..f260aba4a 100644
--- a/packages/server/src/persistence-fan-out.test.ts
+++ b/packages/server/src/persistence-fan-out.test.ts
@@ -7,10 +7,10 @@
* commits correctly.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { recordContributor, swapContributors } from './contributor-tracker.ts';
import { applyExternalChange } from './external-change.ts';
diff --git a/packages/server/src/persistence-large-file-cap.test.ts b/packages/server/src/persistence-large-file-cap.test.ts
index a9c3510d3..b9d94d292 100644
--- a/packages/server/src/persistence-large-file-cap.test.ts
+++ b/packages/server/src/persistence-large-file-cap.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DOCUMENT_OPEN_BYTE_LIMIT } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { createPersistenceExtension, DocumentOpenSizeLimitError } from './persistence.ts';
diff --git a/packages/server/src/persistence-phantom-commit.test.ts b/packages/server/src/persistence-phantom-commit.test.ts
index e2b96f60a..e539c4c92 100644
--- a/packages/server/src/persistence-phantom-commit.test.ts
+++ b/packages/server/src/persistence-phantom-commit.test.ts
@@ -21,11 +21,11 @@
* the safety-net back above the gate silently fails.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { contributorCount, swapContributors } from './contributor-tracker.ts';
import { createServer } from './server-factory.ts';
diff --git a/packages/server/src/persistence-phantom-doc-guard.test.ts b/packages/server/src/persistence-phantom-doc-guard.test.ts
index 23859c807..39775db8f 100644
--- a/packages/server/src/persistence-phantom-doc-guard.test.ts
+++ b/packages/server/src/persistence-phantom-doc-guard.test.ts
@@ -17,11 +17,11 @@
* positive test.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { createServer } from './server-factory.ts';
diff --git a/packages/server/src/persistence-tripwire-block.test.ts b/packages/server/src/persistence-tripwire-block.test.ts
index d472515b6..0b2f74f7e 100644
--- a/packages/server/src/persistence-tripwire-block.test.ts
+++ b/packages/server/src/persistence-tripwire-block.test.ts
@@ -8,12 +8,13 @@
* (`intentional-faq-repeated-section`) does NOT trigger the tripwire and
* the corresponding disk write proceeds.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { updateYFragment } from '@tiptap/y-tiptap';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type * as Y from 'yjs';
import { mdManager, schema } from './md-manager.ts';
import { createServer } from './server-factory.ts';
@@ -109,7 +110,7 @@ describe('persistence onStoreDocument tripwire', () => {
writeFileSync(docPath, baseMarkdown, 'utf-8');
const baselineBytes = readFileSync(docPath, 'utf-8');
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const server = createServer({
contentDir: fixture.contentDir,
projectDir: fixture.tmpDir,
@@ -198,7 +199,7 @@ describe('persistence onStoreDocument tripwire', () => {
const candidateMarkdown = loadFixture('intentional-faq-repeated-section.candidate.md');
writeFileSync(docPath, baseMarkdown, 'utf-8');
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const server = createServer({
contentDir: fixture.contentDir,
projectDir: fixture.tmpDir,
diff --git a/packages/server/src/persistence-tripwire.test.ts b/packages/server/src/persistence-tripwire.test.ts
index d97d0e290..5877409bc 100644
--- a/packages/server/src/persistence-tripwire.test.ts
+++ b/packages/server/src/persistence-tripwire.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { classifyDuplication } from './persistence-tripwire.ts';
const FIXTURE_DIR = resolve(
diff --git a/packages/server/src/persistence-ytext-truth.test.ts b/packages/server/src/persistence-ytext-truth.test.ts
index 9e598d331..89b5d53c9 100644
--- a/packages/server/src/persistence-ytext-truth.test.ts
+++ b/packages/server/src/persistence-ytext-truth.test.ts
@@ -23,7 +23,7 @@
* structurally avoided).
*/
-import { describe as _bunDescribe, afterEach, beforeEach, expect, spyOn, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test, vi } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892 — child-process reaping bug). The full
// contract surface lives in this file: every test boots a real
@@ -409,7 +409,7 @@ describe('Quiescence gate via direct counter manipulation', () => {
writeFileSync(docPath, 'initial\n', 'utf-8');
const initialMtime = (await Bun.file(docPath).stat()).mtimeMs;
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const server = createServer({
contentDir: fixture.contentDir,
projectDir: fixture.tmpDir,
@@ -484,7 +484,7 @@ describe('Quiescence gate via direct counter manipulation', () => {
const docPath = join(fixture.contentDir, `${docName}.md`);
writeFileSync(docPath, 'initial\n', 'utf-8');
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const server = createServer({
contentDir: fixture.contentDir,
projectDir: fixture.tmpDir,
@@ -655,7 +655,7 @@ describe('Pre-write sanity check: divergence at persistence-fire time', () => {
// persistence reaches via `options.mdManager`. Other call sites keep
// using the production `mdManager` singleton.
const testMdManager = new MarkdownManager({ extensions: sharedExtensions });
- spyOn(testMdManager, 'serialize').mockImplementation(() => 'INJECTED-DIVERGENT-CANONICAL\n');
+ vi.spyOn(testMdManager, 'serialize').mockImplementation(() => 'INJECTED-DIVERGENT-CANONICAL\n');
const server = createServer({
contentDir: fixture.contentDir,
@@ -753,7 +753,7 @@ describe('Pre-write sanity check: divergence at persistence-fire time', () => {
// hits this. Observer A baseline init, Observer B watchdog, and
// reconcile use the real production singleton.
const testMdManager = new MarkdownManager({ extensions: sharedExtensions });
- spyOn(testMdManager, 'serialize').mockImplementation(() => {
+ vi.spyOn(testMdManager, 'serialize').mockImplementation(() => {
throw new Error('synthetic schema-rejection: invalid Y.XmlElement type');
});
diff --git a/packages/server/src/persistence.test.ts b/packages/server/src/persistence.test.ts
index 0abbcf5c5..e38a5fe2f 100644
--- a/packages/server/src/persistence.test.ts
+++ b/packages/server/src/persistence.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
lstatSync,
@@ -13,6 +12,7 @@ import {
import { mkdir, realpath, rename, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, resolve, sep } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { contentHash, isSelfWrite, registerWrite } from './file-watcher';
import {
diff --git a/packages/server/src/prd-6654-e2e-repro.test.ts b/packages/server/src/prd-6654-e2e-repro.test.ts
index 133a9becd..54f895a22 100644
--- a/packages/server/src/prd-6654-e2e-repro.test.ts
+++ b/packages/server/src/prd-6654-e2e-repro.test.ts
@@ -11,7 +11,7 @@
* handler) and asserts the second find SUCCEEDS (200) — a byte round-trip
* for the byte-requiring consumer, not tolerance-equivalence.
*/
-import { describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
@@ -20,6 +20,7 @@ import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN, AgentSessionManager } from './agent-sessions.ts';
import { createApiExtension } from './api-extension.ts';
diff --git a/packages/server/src/principal.test.ts b/packages/server/src/principal.test.ts
index 87bcb6a33..95a41479b 100644
--- a/packages/server/src/principal.test.ts
+++ b/packages/server/src/principal.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { loadPrincipal } from './principal.ts';
let tmpDir: string;
diff --git a/packages/server/src/process-scan.test.ts b/packages/server/src/process-scan.test.ts
index 4b63c3b4f..ce3ca3764 100644
--- a/packages/server/src/process-scan.test.ts
+++ b/packages/server/src/process-scan.test.ts
@@ -1,6 +1,5 @@
-import { afterEach, beforeAll, beforeEach, describe, expect, it, mock, spyOn, vi } from 'bun:test';
-
import type { SpawnSyncReturns } from 'node:child_process';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
// The SUT imports spawnSync/existsSync/readdirSync/lstatSync as named bindings
// and calls them directly. Vitest cannot redefine a live ESM namespace binding
@@ -21,8 +20,8 @@ let realFs: typeof import('node:fs');
beforeAll(async () => {
realCp = await vi.importActual<typeof import('node:child_process')>('node:child_process');
realFs = await vi.importActual<typeof import('node:fs')>('node:fs');
- mock.module('node:child_process', () => ({ ...realCp, spawnSync: spawnSyncMock }));
- mock.module('node:fs', () => ({
+ vi.doMock('node:child_process', () => ({ ...realCp, spawnSync: spawnSyncMock }));
+ vi.doMock('node:fs', () => ({
...realFs,
existsSync: existsSyncMock,
readdirSync: readdirSyncMock,
@@ -469,7 +468,7 @@ describe('discoverLockDirs', () => {
});
it('discovers child project locks from the current-directory subtree fallback', async () => {
- const cwdSpy = spyOn(process, 'cwd');
+ const cwdSpy = vi.spyOn(process, 'cwd');
const parent = '/Users/mike/Documents/OpenKnowledge';
const child = `${parent}/garth_nix`;
const lockDir = `${child}/.ok/local`;
@@ -505,7 +504,7 @@ describe('discoverLockDirs', () => {
});
it('runs subtree fallback for slash-cwd helpers even when another candidate was found', async () => {
- const cwdSpy = spyOn(process, 'cwd');
+ const cwdSpy = vi.spyOn(process, 'cwd');
const parent = '/Users/mike/Documents/OpenKnowledge';
const directProject = '/Users/mike/direct-notes';
const directLockDir = `${directProject}/.ok/local`;
diff --git a/packages/server/src/project-git.preflight.test.ts b/packages/server/src/project-git.preflight.test.ts
index c7cb91ac1..b8e375535 100644
--- a/packages/server/src/project-git.preflight.test.ts
+++ b/packages/server/src/project-git.preflight.test.ts
@@ -20,10 +20,11 @@
* a nonexistent dir → ENOENT): this exercises present-but-broken git (nonzero
* exit), the failure mode the report and the fix turn on.
*/
-import { describe, expect, test } from 'bun:test';
+
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import {
__resetResolveOnPathCacheForTests,
__seedResolveOnPathCacheForTests,
diff --git a/packages/server/src/project-git.test.ts b/packages/server/src/project-git.test.ts
index ad9b52e53..56cbbc018 100644
--- a/packages/server/src/project-git.test.ts
+++ b/packages/server/src/project-git.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { execFile } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
__resetResolveOnPathCacheForTests,
__seedResolveOnPathCacheForTests,
diff --git a/packages/server/src/project-skill-git.test.ts b/packages/server/src/project-skill-git.test.ts
index 5c5f5b08b..aa809a1cf 100644
--- a/packages/server/src/project-skill-git.test.ts
+++ b/packages/server/src/project-skill-git.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ensureProjectSkillGitignore } from './init-project.ts';
import { untrackTrackedProjectSkillProjection } from './project-skill-git.ts';
diff --git a/packages/server/src/recently-removed-docs.test.ts b/packages/server/src/recently-removed-docs.test.ts
index 7fa6db35e..fe9a491d9 100644
--- a/packages/server/src/recently-removed-docs.test.ts
+++ b/packages/server/src/recently-removed-docs.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { RecentlyRemovedDocs, type RemovalEntry } from './recently-removed-docs.ts';
describe('RecentlyRemovedDocs — basic shape', () => {
diff --git a/packages/server/src/reconcile-own-flush-window.test.ts b/packages/server/src/reconcile-own-flush-window.test.ts
index 9e8f13e3d..4f705f7a2 100644
--- a/packages/server/src/reconcile-own-flush-window.test.ts
+++ b/packages/server/src/reconcile-own-flush-window.test.ts
@@ -29,12 +29,13 @@
* every run. `isDocInConflict` is asserted because it is the exact predicate
* every mutating write surface uses to throw `DocInConflictError` (HTTP 409).
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Hocuspocus } from '@hocuspocus/server';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { isDocInConflict } from './conflict-errors.ts';
import {
diff --git a/packages/server/src/reconciliation.test.ts b/packages/server/src/reconciliation.test.ts
index 5c1bead40..b67a92d22 100644
--- a/packages/server/src/reconciliation.test.ts
+++ b/packages/server/src/reconciliation.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
containsConflictMarkers,
MAX_LCS_CELLS,
diff --git a/packages/server/src/removal-redirect-guard.test.ts b/packages/server/src/removal-redirect-guard.test.ts
index 3e4ef8fe3..07a76167f 100644
--- a/packages/server/src/removal-redirect-guard.test.ts
+++ b/packages/server/src/removal-redirect-guard.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { HocuspocusAuthRejection } from './auth-token-schema.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
import { RecentlyRemovedDocs } from './recently-removed-docs.ts';
diff --git a/packages/server/src/removed-docs-journal.test.ts b/packages/server/src/removed-docs-journal.test.ts
index 0226263c7..610a381d3 100644
--- a/packages/server/src/removed-docs-journal.test.ts
+++ b/packages/server/src/removed-docs-journal.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { RecentlyRemovedDocs } from './recently-removed-docs.ts';
import {
loadRemovedDocsJournal,
diff --git a/packages/server/src/resolve-package-version.test.ts b/packages/server/src/resolve-package-version.test.ts
index 63e78a1ed..78e1ab506 100644
--- a/packages/server/src/resolve-package-version.test.ts
+++ b/packages/server/src/resolve-package-version.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { resolvePackageVersion } from './resolve-package-version.ts';
describe('resolvePackageVersion', () => {
diff --git a/packages/server/src/resolve-upload-dest-dir.test.ts b/packages/server/src/resolve-upload-dest-dir.test.ts
index 715e0730c..ce08782db 100644
--- a/packages/server/src/resolve-upload-dest-dir.test.ts
+++ b/packages/server/src/resolve-upload-dest-dir.test.ts
@@ -10,7 +10,7 @@
* vault open (the acceptance scenario that depends on the
* bare-name branch specifically).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { resolveUploadDestDir } from './api-extension.ts';
describe('resolveUploadDestDir (SPEC §6 FR-5 + docs matrix)', () => {
diff --git a/packages/server/src/resolve-upstream-author.test.ts b/packages/server/src/resolve-upstream-author.test.ts
index 692a089a8..9047b1a89 100644
--- a/packages/server/src/resolve-upstream-author.test.ts
+++ b/packages/server/src/resolve-upstream-author.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import simpleGit, { type SimpleGit } from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { resolveUpstreamChanges } from './server-factory.ts';
/**
diff --git a/packages/server/src/rig-loopback-exclusivity.test.ts b/packages/server/src/rig-loopback-exclusivity.test.ts
index f88bb3ece..9ad9f62e0 100644
--- a/packages/server/src/rig-loopback-exclusivity.test.ts
+++ b/packages/server/src/rig-loopback-exclusivity.test.ts
@@ -31,9 +31,9 @@
* migrate.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { createServer, type RequestListener, type Server } from 'node:http';
+import { afterEach, describe, expect, test } from 'vitest';
import { listenOnLoopback } from './loopback-rig-test-helpers.ts';
interface RigSeam {
diff --git a/packages/server/src/rollback-write-order.test.ts b/packages/server/src/rollback-write-order.test.ts
index 888cd6854..272ebb148 100644
--- a/packages/server/src/rollback-write-order.test.ts
+++ b/packages/server/src/rollback-write-order.test.ts
@@ -21,10 +21,11 @@
* to the rollback call site whose write sequence is open-coded inside the
* api-extension closure.
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+
import { sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { ROLLBACK_ORIGIN } from './api-extension.ts';
import { replaceRawBody } from './bridge-intake.ts';
diff --git a/packages/server/src/save-version.test.ts b/packages/server/src/save-version.test.ts
index 021525b7b..b07989e80 100644
--- a/packages/server/src/save-version.test.ts
+++ b/packages/server/src/save-version.test.ts
@@ -6,7 +6,6 @@
* - The user's parent git repo is never mutated.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
@@ -14,6 +13,7 @@ import { join, resolve } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { AgentSessionManager } from './agent-sessions.ts';
import { createApiExtension } from './api-extension.ts';
diff --git a/packages/server/src/seed/apply.test.ts b/packages/server/src/seed/apply.test.ts
index 1545bac72..5457a809c 100644
--- a/packages/server/src/seed/apply.test.ts
+++ b/packages/server/src/seed/apply.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { applySeed } from './apply.ts';
import { planSeed } from './plan.ts';
import { STARTER_PACKS } from './starter.ts';
diff --git a/packages/server/src/seed/install-pack-skill.test.ts b/packages/server/src/seed/install-pack-skill.test.ts
index b20d70936..38e8888d4 100644
--- a/packages/server/src/seed/install-pack-skill.test.ts
+++ b/packages/server/src/seed/install-pack-skill.test.ts
@@ -1,4 +1,3 @@
-import { describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -9,6 +8,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { readInstalledSkills } from '../installed-skills-marker.ts';
import { installPackSkill } from './install-pack-skill.ts';
diff --git a/packages/server/src/seed/okf-conformance.test.ts b/packages/server/src/seed/okf-conformance.test.ts
index 983cdda46..c5dd3f8a0 100644
--- a/packages/server/src/seed/okf-conformance.test.ts
+++ b/packages/server/src/seed/okf-conformance.test.ts
@@ -23,7 +23,6 @@
* conformance is asserted on the instantiated doc-frontmatter.
*/
-import { describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
@@ -34,6 +33,7 @@ import {
stripFrontmatter,
unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { parse as parseYaml } from 'yaml';
import { applySubstitution } from '../content/substitution.ts';
import { applySeed } from './apply.ts';
diff --git a/packages/server/src/seed/packs-no-jargon.test.ts b/packages/server/src/seed/packs-no-jargon.test.ts
index f975c2956..022611b4c 100644
--- a/packages/server/src/seed/packs-no-jargon.test.ts
+++ b/packages/server/src/seed/packs-no-jargon.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { STARTER_PACK_IDS, STARTER_PACKS } from './starter.ts';
/**
diff --git a/packages/server/src/seed/path-safety.test.ts b/packages/server/src/seed/path-safety.test.ts
index 43c456340..506f0520e 100644
--- a/packages/server/src/seed/path-safety.test.ts
+++ b/packages/server/src/seed/path-safety.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { applySeed } from './apply.ts';
import { planSeed } from './plan.ts';
import { SeedRootDirError } from './types.ts';
diff --git a/packages/server/src/seed/plan.test.ts b/packages/server/src/seed/plan.test.ts
index f0d4971eb..98feef242 100644
--- a/packages/server/src/seed/plan.test.ts
+++ b/packages/server/src/seed/plan.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { planSeed } from './plan.ts';
import { STARTER_PACKS } from './starter.ts';
import { SeedPrerequisiteError, SeedRootDirError } from './types.ts';
diff --git a/packages/server/src/seed/rationale.test.ts b/packages/server/src/seed/rationale.test.ts
index d840f2a19..139b97468 100644
--- a/packages/server/src/seed/rationale.test.ts
+++ b/packages/server/src/seed/rationale.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { formatPackRationale, PACK_INSPIRATION_NOTE } from './rationale.ts';
import { STARTER_PACK_IDS, STARTER_PACKS } from './starter.ts';
diff --git a/packages/server/src/seed/seed-frontmatter-guard.test.ts b/packages/server/src/seed/seed-frontmatter-guard.test.ts
index 7df7e9293..5768d9fa6 100644
--- a/packages/server/src/seed/seed-frontmatter-guard.test.ts
+++ b/packages/server/src/seed/seed-frontmatter-guard.test.ts
@@ -10,12 +10,12 @@
* loud in CI rather than relying on review to catch the next one.
*/
-import { describe, expect, test } from 'bun:test';
import {
parseTemplateFile,
stripFrontmatter,
unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { parse as parseYaml } from 'yaml';
import { STARTER_PACKS } from './starter.ts';
diff --git a/packages/server/src/seed/skill-pack-list-drift.test.ts b/packages/server/src/seed/skill-pack-list-drift.test.ts
index be2b87099..2353f3168 100644
--- a/packages/server/src/seed/skill-pack-list-drift.test.ts
+++ b/packages/server/src/seed/skill-pack-list-drift.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { STARTER_PACK_IDS } from './starter.ts';
// The project skill carries a hand-written starter-pack awareness list (names +
diff --git a/packages/server/src/seed/starter.test.ts b/packages/server/src/seed/starter.test.ts
index 06cecf596..227dc0c1f 100644
--- a/packages/server/src/seed/starter.test.ts
+++ b/packages/server/src/seed/starter.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parseTemplateFile } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
extractMarkdownLinksFromMarkdown,
extractWikiLinksFromMarkdown,
diff --git a/packages/server/src/serialize-doc-vs-git-show-byte-equality.test.ts b/packages/server/src/serialize-doc-vs-git-show-byte-equality.test.ts
index 1aaa850f1..5bc4aa673 100644
--- a/packages/server/src/serialize-doc-vs-git-show-byte-equality.test.ts
+++ b/packages/server/src/serialize-doc-vs-git-show-byte-equality.test.ts
@@ -19,19 +19,13 @@
* stages-of-merge `ours` is consumed by line-diff UIs that already
* tolerate one-newline drift).
*/
-import {
- describe as _bunDescribe,
- afterEach,
- beforeEach,
- expect,
- setDefaultTimeout,
- test,
-} from 'bun:test';
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { prependFrontmatter, stripFrontmatter } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test, vi } from 'vitest';
import { __resetQuiescenceForTests } from './bridge-quiescence.ts';
import { resetMetrics } from './metrics.ts';
import { createServer } from './server-factory.ts';
@@ -61,7 +55,7 @@ function reconstructSerializeDoc(
// process reaping bug surfaces here under Ubuntu Bun).
const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
-setDefaultTimeout(20_000);
+vi.setConfig({ testTimeout: 20_000, hookTimeout: 20_000 });
interface Fixture {
tmpDir: string;
diff --git a/packages/server/src/serialize-doc-ytext.test.ts b/packages/server/src/serialize-doc-ytext.test.ts
index e2494196e..ebd4fe984 100644
--- a/packages/server/src/serialize-doc-ytext.test.ts
+++ b/packages/server/src/serialize-doc-ytext.test.ts
@@ -29,18 +29,11 @@
* after each path fires.
*/
-import {
- describe as _bunDescribe,
- afterEach,
- beforeEach,
- expect,
- setDefaultTimeout,
- test,
-} from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import simpleGit from 'simple-git';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test, vi } from 'vitest';
import { __resetQuiescenceForTests } from './bridge-quiescence.ts';
import { resetMetrics } from './metrics.ts';
import { getReconciledBase } from './persistence.ts';
@@ -68,7 +61,7 @@ const describe = process.env.CI ? _bunDescribe.skip : _bunDescribe;
// File-watcher startup + reconcile fire is parcel-watcher latency-bound;
// 5s Bun default isn't enough headroom under suite contention. Tests
// inside still bound their own waits via `waitForCondition`.
-setDefaultTimeout(20_000);
+vi.setConfig({ testTimeout: 20_000, hookTimeout: 20_000 });
interface Fixture {
tmpDir: string;
diff --git a/packages/server/src/serialize-error.test.ts b/packages/server/src/serialize-error.test.ts
index 4dfc9be41..69f470c83 100644
--- a/packages/server/src/serialize-error.test.ts
+++ b/packages/server/src/serialize-error.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { serializeError } from './serialize-error.ts';
describe('serializeError', () => {
diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.ts
index 36ba245b9..34e0b06c0 100644
--- a/packages/server/src/server-factory.test.ts
+++ b/packages/server/src/server-factory.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
@@ -6,6 +5,7 @@ import { join, resolve } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
import shellQuote from 'shell-quote';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import type {
CheckPushPermissionOptions,
@@ -521,7 +521,7 @@ describe('createServer().destroy() — graceful shutdown flush', () => {
* invalid paths) and startHeadWatcher returns a no-op handle on missing
* .git. The degraded.push wiring for these subsystems is verified by
* the shadow-repo test (same push pattern) + code-level assertions.
- * mock.module was attempted but leaks across all test files in the same
+ * vi.doMock was attempted but leaks across all test files in the same
* `bun test` process, breaking file-watcher.test.ts.
*/
@@ -580,7 +580,7 @@ describe('createServer() degraded signal', () => {
test('degraded push wiring exists for all three subsystems', () => {
// Verify at the source level that the degraded.push calls exist in
// initAsync for file-watcher and head-watcher. This is a code-level
- // assertion — not as strong as a runtime test, but mock.module leaks
+ // assertion — not as strong as a runtime test, but vi.doMock leaks
// make runtime testing impractical without process isolation.
const dir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;
const src = readFileSync(resolve(dir, 'server-factory.ts'), 'utf-8');
diff --git a/packages/server/src/server-lock.test.ts b/packages/server/src/server-lock.test.ts
index 19825bbe2..41ca28f0e 100644
--- a/packages/server/src/server-lock.test.ts
+++ b/packages/server/src/server-lock.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { hostname, tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
acquireServerLock,
readServerLock,
diff --git a/packages/server/src/server-memory-telemetry.test.ts b/packages/server/src/server-memory-telemetry.test.ts
index a5c83826e..03ace256d 100644
--- a/packages/server/src/server-memory-telemetry.test.ts
+++ b/packages/server/src/server-memory-telemetry.test.ts
@@ -1,4 +1,3 @@
-import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { metrics } from '@opentelemetry/api';
import {
AggregationTemporality,
@@ -7,6 +6,7 @@ import {
MeterProvider,
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import {
__resetServerRuntimeTelemetryForTests,
installServerMemoryGauge,
diff --git a/packages/server/src/server-observers-divergent-fallback.test.ts b/packages/server/src/server-observers-divergent-fallback.test.ts
index 4af511d4b..49a19d636 100644
--- a/packages/server/src/server-observers-divergent-fallback.test.ts
+++ b/packages/server/src/server-observers-divergent-fallback.test.ts
@@ -40,10 +40,11 @@
* NODE_ENV=test watchdog gates throw at doc load on the injected divergence,
* which would mask the silent-destruction behavior these tests pin.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { __resetBridgeWatchdogForTests } from './bridge-watchdog.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
diff --git a/packages/server/src/server-observers-duplication-gate.test.ts b/packages/server/src/server-observers-duplication-gate.test.ts
index b5b36bf7b..e011f237a 100644
--- a/packages/server/src/server-observers-duplication-gate.test.ts
+++ b/packages/server/src/server-observers-duplication-gate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { findRaceDuplicatedSpans } from './server-observers.ts';
diff --git a/packages/server/src/server-observers-paired-write-baseline.test.ts b/packages/server/src/server-observers-paired-write-baseline.test.ts
index cd756a12b..aff7aa8f9 100644
--- a/packages/server/src/server-observers-paired-write-baseline.test.ts
+++ b/packages/server/src/server-observers-paired-write-baseline.test.ts
@@ -16,10 +16,11 @@
* under a non-paired origin; in production TipTap fires the same
* XmlFragment YEvent through its prosemirror-binding).
*/
-import { describe, expect, test } from 'bun:test';
+
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
import { composeAndWriteRawBody } from './bridge-intake.ts';
diff --git a/packages/server/src/server-observers.fm-fence-hazard.test.ts b/packages/server/src/server-observers.fm-fence-hazard.test.ts
index c464938b4..ec3a8b2b7 100644
--- a/packages/server/src/server-observers.fm-fence-hazard.test.ts
+++ b/packages/server/src/server-observers.fm-fence-hazard.test.ts
@@ -17,7 +17,7 @@
* (c) the WYSIWYG edit is applied, and
* (d) the FM region is not re-derived into the WYSIWYG body.
*/
-import { describe, expect, test } from 'bun:test';
+
import {
MarkdownManager,
prependFrontmatter,
@@ -26,6 +26,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { composeAndWriteRawBody } from './bridge-intake.ts';
import { __resetBridgeWatchdogForTests } from './bridge-watchdog.ts';
diff --git a/packages/server/src/server-observers.lazy-continuation.test.ts b/packages/server/src/server-observers.lazy-continuation.test.ts
index 09f6b2b4e..7a9af2a0b 100644
--- a/packages/server/src/server-observers.lazy-continuation.test.ts
+++ b/packages/server/src/server-observers.lazy-continuation.test.ts
@@ -21,7 +21,7 @@
* (paired-write intake first, observer attach second) — the same rig as
* `server-observers.test.ts`.
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+
import {
MarkdownManager,
normalizeBridge,
@@ -31,6 +31,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { composeAndWriteRawBody } from './bridge-intake.ts';
import { __resetBridgeWatchdogForTests } from './bridge-watchdog.ts';
diff --git a/packages/server/src/server-observers.path-b-doc-boundary.test.ts b/packages/server/src/server-observers.path-b-doc-boundary.test.ts
index 8bf82f9e9..bdcccf097 100644
--- a/packages/server/src/server-observers.path-b-doc-boundary.test.ts
+++ b/packages/server/src/server-observers.path-b-doc-boundary.test.ts
@@ -30,7 +30,7 @@
* mergeThreeWay the same edits with all three inputs in one boundary
* byte-space merges cleanly with both edits landing verbatim.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import {
BridgeMergeContentLossError,
MarkdownManager,
@@ -41,6 +41,7 @@ import {
stripFrontmatter,
} from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
import { composeAndWriteRawBody } from './bridge-intake.ts';
import { __resetBridgeWatchdogForTests } from './bridge-watchdog.ts';
diff --git a/packages/server/src/server-observers.path-b-respell.test.ts b/packages/server/src/server-observers.path-b-respell.test.ts
index ef06e8f58..ddaf4f082 100644
--- a/packages/server/src/server-observers.path-b-respell.test.ts
+++ b/packages/server/src/server-observers.path-b-respell.test.ts
@@ -31,7 +31,7 @@
* rung); these tests pin the suppression WIRING and the drain's clean
* convergence.
*/
-import { describe, expect, spyOn, test } from 'bun:test';
+
import {
type JSONContent,
MarkdownManager,
@@ -40,6 +40,7 @@ import {
} from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment } from '@tiptap/y-tiptap';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { type SetupServerObserversOpts, setupServerObservers } from './server-observers.ts';
@@ -162,7 +163,7 @@ describe('Observer A — freshness suppression on diverged-baseline drains', ()
// Y.Text write inside the quiescence window defers freshness; a drain
// after the window re-arms it.
let clock = 1_000_000;
- const nowSpy = spyOn(Date, 'now').mockImplementation(() => clock);
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);
const { manager, serializeOpts } = makeRecordingManager();
const doc = new Y.Doc();
const xmlFragment = doc.getXmlFragment('default');
diff --git a/packages/server/src/shadow-branch-gc.test.ts b/packages/server/src/shadow-branch-gc.test.ts
index fae874a7e..13025a0ff 100644
--- a/packages/server/src/shadow-branch-gc.test.ts
+++ b/packages/server/src/shadow-branch-gc.test.ts
@@ -1,10 +1,10 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { parseCheckpoint } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { gcShadowBranches } from './shadow-branch-gc';
import { commitWip, initShadowRepo, shadowGit, type WriterIdentity } from './shadow-repo';
diff --git a/packages/server/src/shadow-lock.test.ts b/packages/server/src/shadow-lock.test.ts
index ec2458f3b..78b42dc55 100644
--- a/packages/server/src/shadow-lock.test.ts
+++ b/packages/server/src/shadow-lock.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { hostname, tmpdir } from 'node:os';
import { resolve } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { acquireLock, type LockMetadata, releaseLock } from './shadow-lock';
let tmpDir: string;
diff --git a/packages/server/src/shadow-op-gate.test.ts b/packages/server/src/shadow-op-gate.test.ts
index 92a19ddd5..1701d5852 100644
--- a/packages/server/src/shadow-op-gate.test.ts
+++ b/packages/server/src/shadow-op-gate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { releaseShadowOpGate, ShadowOpGate, shadowOpGateFor } from './shadow-op-gate.ts';
/** A promise whose settle order we can observe alongside manual triggers. */
diff --git a/packages/server/src/shadow-repo-stats.test.ts b/packages/server/src/shadow-repo-stats.test.ts
index 9cb6cb721..9efa994e1 100644
--- a/packages/server/src/shadow-repo-stats.test.ts
+++ b/packages/server/src/shadow-repo-stats.test.ts
@@ -4,12 +4,13 @@
* (folded by the 30-day TTL, not the fast auto path), excludes park/non-session
* refs, and honors the staleness cutoff — all without the live keepalive map.
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import simpleGit from 'simple-git';
+import { beforeEach, describe, expect, test } from 'vitest';
import { initShadowRepo, type ShadowHandle, shadowGit } from './shadow-repo.ts';
import { countStaleAgentWipRefs } from './shadow-repo-stats.ts';
diff --git a/packages/server/src/share/endpoint-real-git.test.ts b/packages/server/src/share/endpoint-real-git.test.ts
index ddc8fadaf..1b41ab017 100644
--- a/packages/server/src/share/endpoint-real-git.test.ts
+++ b/packages/server/src/share/endpoint-real-git.test.ts
@@ -9,9 +9,9 @@
* they run unskipped in the default test tier.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { createServer as createHttpServer } from 'node:http';
import type { AddressInfo, Socket } from 'node:net';
+import { afterEach, describe, expect, test } from 'vitest';
import { bootEndpointServer, type EndpointRig } from './endpoint-http.test-helper.ts';
import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';
import { computeShareTargetStatus } from './target-status.ts';
diff --git a/packages/server/src/share/freshness.test.ts b/packages/server/src/share/freshness.test.ts
index f88f6b161..fd1fb76a7 100644
--- a/packages/server/src/share/freshness.test.ts
+++ b/packages/server/src/share/freshness.test.ts
@@ -4,10 +4,11 @@
* that can't run returns `undefined` (the share still ships) rather than a
* wrong verdict or a throw.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { computeShareFreshness } from './freshness.ts';
import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';
diff --git a/packages/server/src/share/git-fixture.test.ts b/packages/server/src/share/git-fixture.test.ts
index 4e171a9ac..a838d30d5 100644
--- a/packages/server/src/share/git-fixture.test.ts
+++ b/packages/server/src/share/git-fixture.test.ts
@@ -5,9 +5,10 @@
* faithful before the handler tests depend on it. Synchronous `execFileSync`
* git keeps this unskipped on CI (oven-sh/bun#11892 only bites async children).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
+import { afterEach, describe, expect, test } from 'vitest';
import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';
const triangles: GitTriangle[] = [];
diff --git a/packages/server/src/share/publish.integration.test.ts b/packages/server/src/share/publish.integration.test.ts
index 426542f07..3d3386adf 100644
--- a/packages/server/src/share/publish.integration.test.ts
+++ b/packages/server/src/share/publish.integration.test.ts
@@ -10,12 +10,12 @@
* so tests don't depend on a built CLI on PATH.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
import { mkdirSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import type { Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import { listenOnLoopback } from '../loopback-rig-test-helpers.ts';
import type { SyncEngine } from '../sync-engine.ts';
diff --git a/packages/server/src/share/publish.test.ts b/packages/server/src/share/publish.test.ts
index b742f80eb..dbc59ca51 100644
--- a/packages/server/src/share/publish.test.ts
+++ b/packages/server/src/share/publish.test.ts
@@ -5,7 +5,7 @@
* are exercised by the integration test at `./publish.integration.test.ts`.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
isValidShareOwnerName,
isValidShareRepoName,
diff --git a/packages/server/src/share/target-status.test.ts b/packages/server/src/share/target-status.test.ts
index a9eedda55..624b74cf7 100644
--- a/packages/server/src/share/target-status.test.ts
+++ b/packages/server/src/share/target-status.test.ts
@@ -4,7 +4,7 @@
* in the move/delete cases, so the fetch inside `computeShareTargetStatus` is
* what reveals the change (a stale local ref would otherwise misclassify it).
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, test } from 'vitest';
import { createGitTriangle, type GitTriangle } from './git-fixture.test-helper.ts';
import { computeShareTargetStatus } from './target-status.ts';
diff --git a/packages/server/src/showall-cap.test.ts b/packages/server/src/showall-cap.test.ts
index 2c1a48595..99bebd093 100644
--- a/packages/server/src/showall-cap.test.ts
+++ b/packages/server/src/showall-cap.test.ts
@@ -7,11 +7,12 @@
* over the edge), leaving the off-by-one (exactly-cap vs cap+1) unverified.
* Also pins the env-parser fallback for hostile `OK_SHOWALL_MAX_ENTRIES` input.
*/
-import { afterEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { DocumentListEntry } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test } from 'vitest';
import {
__getShowAllWalkStatsForTesting,
__resetShowAllWalkStatsForTesting,
diff --git a/packages/server/src/single-file-open.test.ts b/packages/server/src/single-file-open.test.ts
index a5c81a1af..f310b4e54 100644
--- a/packages/server/src/single-file-open.test.ts
+++ b/packages/server/src/single-file-open.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, describe, expect, test } from 'bun:test';
import {
existsSync,
mkdirSync,
@@ -11,6 +10,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
import {
createEphemeralProjectDir,
prepareSingleFileOpen,
diff --git a/packages/server/src/single-flight.test.ts b/packages/server/src/single-flight.test.ts
index fb7710294..0343d387f 100644
--- a/packages/server/src/single-flight.test.ts
+++ b/packages/server/src/single-flight.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { createSingleFlight } from './single-flight.ts';
describe('createSingleFlight (PRD-6972 FR2)', () => {
diff --git a/packages/server/src/skill-bundles.test.ts b/packages/server/src/skill-bundles.test.ts
index 639a6aebe..54f5edc98 100644
--- a/packages/server/src/skill-bundles.test.ts
+++ b/packages/server/src/skill-bundles.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { RESERVED_PROJECT_SKILL_NAME } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { BUNDLE_IDS, BUNDLE_SKILL_NAME, bundleSkillMdPath } from './skill-bundles.ts';
// Repo root = three levels up from this file (packages/server/src → root).
diff --git a/packages/server/src/skill-install-events.test.ts b/packages/server/src/skill-install-events.test.ts
index 780529225..cf44cfb71 100644
--- a/packages/server/src/skill-install-events.test.ts
+++ b/packages/server/src/skill-install-events.test.ts
@@ -4,11 +4,11 @@
* collapses to a logged warning + resolved void.
*/
-import { describe, expect, mock, test } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
import {
recordSkillInstallEvent,
SKILL_INSTALL_EVENTS_FILE_REL,
@@ -83,7 +83,7 @@ describe('recordSkillInstallEvent — fail-soft contract', () => {
test('no HOME → warns + resolves; never throws', async () => {
const warnRecorder: ((data: unknown, message: string) => void) & {
mock: { calls: ReadonlyArray<readonly [unknown, string]> };
- } = mock((_data: unknown, _message: string) => {}) as unknown as typeof warnRecorder;
+ } = vi.fn((_data: unknown, _message: string) => {}) as unknown as typeof warnRecorder;
await expect(
recordSkillInstallEvent(makeEvent(), {
homedir: () => '',
@@ -106,7 +106,7 @@ describe('recordSkillInstallEvent — fail-soft contract', () => {
const warnRecorder: ((data: unknown, message: string) => void) & {
mock: { calls: ReadonlyArray<readonly [unknown, string]> };
- } = mock((_data: unknown, _message: string) => {}) as unknown as typeof warnRecorder;
+ } = vi.fn((_data: unknown, _message: string) => {}) as unknown as typeof warnRecorder;
await expect(
recordSkillInstallEvent(makeEvent(), {
homedir: () => blocker,
@@ -130,7 +130,7 @@ describe('recordSkillInstallEvent — fail-soft contract', () => {
const warnRecorder: ((data: unknown, message: string) => void) & {
mock: { calls: ReadonlyArray<readonly [unknown, string]> };
- } = mock((_data: unknown, _message: string) => {}) as unknown as typeof warnRecorder;
+ } = vi.fn((_data: unknown, _message: string) => {}) as unknown as typeof warnRecorder;
await expect(
recordSkillInstallEvent(makeEvent(), {
homedir: () => home,
diff --git a/packages/server/src/skill-install.test.ts b/packages/server/src/skill-install.test.ts
index 020d9e228..f6f7c9254 100644
--- a/packages/server/src/skill-install.test.ts
+++ b/packages/server/src/skill-install.test.ts
@@ -5,7 +5,7 @@
* Each test uses a fresh `mkdtempSync`-backed HOME so the sidecar write path
* touches only the tmpdir — never the real `~/`.
*/
-import { beforeEach, describe, expect, test } from 'bun:test';
+
import type { SpawnOptions } from 'node:child_process';
import { EventEmitter } from 'node:events';
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
@@ -13,6 +13,7 @@ import { readFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PassThrough } from 'node:stream';
+import { beforeEach, describe, expect, test } from 'vitest';
import {
buildAndOpenSkill,
diff --git a/packages/server/src/skill-linking-contract.test.ts b/packages/server/src/skill-linking-contract.test.ts
index ff27a5175..ae6faaf66 100644
--- a/packages/server/src/skill-linking-contract.test.ts
+++ b/packages/server/src/skill-linking-contract.test.ts
@@ -1,6 +1,6 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
/**
* Guards the link-authoring contract in the bundled project skill so a later
diff --git a/packages/server/src/skill-management.test.ts b/packages/server/src/skill-management.test.ts
index 287c3f960..b9fd58133 100644
--- a/packages/server/src/skill-management.test.ts
+++ b/packages/server/src/skill-management.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
isProjectSkillManaged,
readSkillManagement,
diff --git a/packages/server/src/skill-pack-version.test.ts b/packages/server/src/skill-pack-version.test.ts
index 2cf443254..2c346c29c 100644
--- a/packages/server/src/skill-pack-version.test.ts
+++ b/packages/server/src/skill-pack-version.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import {
bundledPackVersion,
computePackUpdateStatus,
diff --git a/packages/server/src/skill-projection.test.ts b/packages/server/src/skill-projection.test.ts
index 16b18fa07..2e0bc26da 100644
--- a/packages/server/src/skill-projection.test.ts
+++ b/packages/server/src/skill-projection.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
chmodSync,
existsSync,
@@ -12,6 +11,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
hostSkillsRootEscapes,
projectSkill,
diff --git a/packages/server/src/skill-reconcile.test.ts b/packages/server/src/skill-reconcile.test.ts
index d811d8e4a..add4d9e27 100644
--- a/packages/server/src/skill-reconcile.test.ts
+++ b/packages/server/src/skill-reconcile.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
existsSync,
lstatSync,
@@ -11,6 +10,7 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join, relative } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { readInstalledSkills } from './installed-skills-marker.ts';
import { countImportableEditorSkills, reconcileSkillInstalls } from './skill-reconcile.ts';
diff --git a/packages/server/src/skill-reproject.test.ts b/packages/server/src/skill-reproject.test.ts
index d3807575e..22d77b01a 100644
--- a/packages/server/src/skill-reproject.test.ts
+++ b/packages/server/src/skill-reproject.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { readInstalledSkills, recordSkillInstall } from './installed-skills-marker.ts';
import { projectSkill } from './skill-projection.ts';
import { reprojectAllManagedSkills } from './skill-reproject.ts';
diff --git a/packages/server/src/skill-restore.test.ts b/packages/server/src/skill-restore.test.ts
index 8dd10654c..fe696f3fc 100644
--- a/packages/server/src/skill-restore.test.ts
+++ b/packages/server/src/skill-restore.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isGitObjectNotFound } from './skill-restore.ts';
/**
diff --git a/packages/server/src/skill-state.test.ts b/packages/server/src/skill-state.test.ts
index 95f6e8e16..714a78082 100644
--- a/packages/server/src/skill-state.test.ts
+++ b/packages/server/src/skill-state.test.ts
@@ -8,12 +8,12 @@
* encounter).
*/
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync } from 'node:fs';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import {
readAllTargets,
readBundleDecision,
diff --git a/packages/server/src/skill-targets-store.test.ts b/packages/server/src/skill-targets-store.test.ts
index c0fedd4e2..adc42d537 100644
--- a/packages/server/src/skill-targets-store.test.ts
+++ b/packages/server/src/skill-targets-store.test.ts
@@ -1,7 +1,7 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { readSkillTargets, skillTargetsPath, writeSkillTargets } from './skill-targets-store.ts';
let projectDir: string;
diff --git a/packages/server/src/spawn-cursor-api.test.ts b/packages/server/src/spawn-cursor-api.test.ts
index 35d5d5f38..63d00f7af 100644
--- a/packages/server/src/spawn-cursor-api.test.ts
+++ b/packages/server/src/spawn-cursor-api.test.ts
@@ -12,9 +12,9 @@
* shape back to the in-process `SpawnCursorOutcome` discriminated union.
*/
-import { describe, expect, mock, test } from 'bun:test';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
+import { describe, expect, test, vi } from 'vitest';
import {
type HandleSpawnCursorDeps,
handleSpawnCursor,
@@ -128,7 +128,7 @@ describe('handleSpawnCursor — body validation', () => {
describe('handleSpawnCursor — path containment', () => {
test('rejects paths outside contentDir → 403 path-escape', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnCursorOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnCursorOutcome);
const { res, captured } = makeRes();
await handleSpawnCursor(
makeReq('POST', { path: '/etc/passwd' }),
@@ -140,7 +140,7 @@ describe('handleSpawnCursor — path containment', () => {
});
test('rejects parent traversal → 403 path-escape', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnCursorOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnCursorOutcome);
const { res, captured } = makeRes();
await handleSpawnCursor(
makeReq('POST', { path: '/Users/who/dragons/../../etc' }),
@@ -180,7 +180,7 @@ describe('handleSpawnCursor — path containment', () => {
describe('handleSpawnCursor — binary resolution', () => {
test('resolveCursorBinary returns null → 422 cursor-not-installed', async () => {
- const spawnDetached = mock(async () => ({ ok: true }) as SpawnCursorOutcome);
+ const spawnDetached = vi.fn(async () => ({ ok: true }) as SpawnCursorOutcome);
const { res, captured } = makeRes();
await handleSpawnCursor(
makeReq('POST', { path: VALID_PATH }),
@@ -194,7 +194,7 @@ describe('handleSpawnCursor — binary resolution', () => {
describe('handleSpawnCursor — spawn dispatch', () => {
test('macOS .app bundle path routes through /usr/bin/open -a', async () => {
- const spawnDetached = mock(
+ const spawnDetached = vi.fn(
async (_exec: string, _args: ReadonlyArray<string>) => ({ ok: true }) as SpawnCursorOutcome,
);
const { res, captured } = makeRes();
@@ -218,7 +218,7 @@ describe('handleSpawnCursor — spawn dispatch', () => {
});
test('non-bundle exec path is invoked directly with [path] argv', async () => {
- const spawnDetached = mock(
+ const spawnDetached = vi.fn(
async (_exec: string, _args: ReadonlyArray<string>) => ({ ok: true }) as SpawnCursorOutcome,
);
const { res, captured } = makeRes();
@@ -296,7 +296,7 @@ describe('handleSpawnCursor — spawn dispatch', () => {
describe('handleSpawnCursor — Cursor binary discovery (per-platform)', () => {
test('macOS: bundle-path probe finds the shim without `which`', async () => {
let whichCalled = false;
- const spawnDetached = mock(async (exec: string, _args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, _args: ReadonlyArray<string>) => {
// /Applications/Cursor.app exists in production tests on developer
// Macs; we mock the resolver to return its bundle path explicitly so
// the test is hermetic regardless of the host machine's installs.
@@ -329,7 +329,7 @@ describe('handleSpawnCursor — Cursor binary discovery (per-platform)', () => {
'C:\\Users\\who\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin\\cursor.cmd';
let capturedExec = '';
let capturedArgs: ReadonlyArray<string> = [];
- const spawnDetached = mock(async (exec: string, args: ReadonlyArray<string>) => {
+ const spawnDetached = vi.fn(async (exec: string, args: ReadonlyArray<string>) => {
// A bare `spawn('cursor.cmd', …, {shell:false})` throws EINVAL on Windows;
// the invocation must wrap the shim in `cmd.exe /d /c`.
capturedExec = exec;
@@ -358,7 +358,7 @@ describe('handleSpawnCursor — Cursor binary discovery (per-platform)', () => {
// canonical bundle path — the production resolver skips bundle probing
// entirely on linux and goes straight to `which`. Tests stub
// `resolveCursorBinary` directly to mirror that contract.
- const spawnDetached = mock(
+ const spawnDetached = vi.fn(
async (_exec: string, _args: ReadonlyArray<string>) => ({ ok: true }) as SpawnCursorOutcome,
);
const { res, captured } = makeRes();
diff --git a/packages/server/src/spawn-detached.test.ts b/packages/server/src/spawn-detached.test.ts
index 3fe12ac05..23fbe9f73 100644
--- a/packages/server/src/spawn-detached.test.ts
+++ b/packages/server/src/spawn-detached.test.ts
@@ -25,10 +25,10 @@
* complaining.
*/
-import { describe, expect, test } from 'bun:test';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { spawnDetached } from './spawn-detached.ts';
const NEVER_HIT = 5_000;
diff --git a/packages/server/src/state-manifest.test.ts b/packages/server/src/state-manifest.test.ts
index 5aa4785a7..7ef8b1191 100644
--- a/packages/server/src/state-manifest.test.ts
+++ b/packages/server/src/state-manifest.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
assertCompatibleStateManifest,
detectProjectShape,
diff --git a/packages/server/src/suggest-links.test.ts b/packages/server/src/suggest-links.test.ts
index f3da83fa9..8e4df12e9 100644
--- a/packages/server/src/suggest-links.test.ts
+++ b/packages/server/src/suggest-links.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Hocuspocus } from '@hocuspocus/server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN, applyAgentMarkdownWrite } from './agent-sessions.ts';
import { applyExternalChange } from './external-change.ts';
diff --git a/packages/server/src/summary-e2e.test.ts b/packages/server/src/summary-e2e.test.ts
index 6057fd9f0..92a593862 100644
--- a/packages/server/src/summary-e2e.test.ts
+++ b/packages/server/src/summary-e2e.test.ts
@@ -10,11 +10,12 @@
* storage contract has been broken somewhere between the accumulator and the
* read path.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
formatContributorsFrom,
recordContributor,
diff --git a/packages/server/src/sync-engine.test.ts b/packages/server/src/sync-engine.test.ts
index 722a268c4..73824beea 100644
--- a/packages/server/src/sync-engine.test.ts
+++ b/packages/server/src/sync-engine.test.ts
@@ -9,7 +9,7 @@
* detection) belong in a future integration test that spins up a bare git repo.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
// This suite runs in CI despite oven-sh/bun#11892 (Bun fails to kill/reap
// spawned child processes on GitHub Actions runners; still open upstream).
diff --git a/packages/server/src/sync-timing.test.ts b/packages/server/src/sync-timing.test.ts
index b461a06ad..8fb151b6a 100644
--- a/packages/server/src/sync-timing.test.ts
+++ b/packages/server/src/sync-timing.test.ts
@@ -2,7 +2,7 @@
* Unit tests for sync-timing helpers (restart recovery).
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeRemainingMs } from './sync-timing.ts';
const SECOND = 1000;
diff --git a/packages/server/src/tag-index.test.ts b/packages/server/src/tag-index.test.ts
index dda9bb8b9..168babbed 100644
--- a/packages/server/src/tag-index.test.ts
+++ b/packages/server/src/tag-index.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
import { TagIndex } from './tag-index.ts';
function tempContentDir(): { contentDir: string; cleanup: () => void } {
diff --git a/packages/server/src/telemetry-file-sink.test.ts b/packages/server/src/telemetry-file-sink.test.ts
index 132b4160e..d148983e2 100644
--- a/packages/server/src/telemetry-file-sink.test.ts
+++ b/packages/server/src/telemetry-file-sink.test.ts
@@ -1,9 +1,9 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { context, trace } from '@opentelemetry/api';
import { BasicTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
DEFAULT_MAX_VALUE_BYTES,
FileSpanExporter,
diff --git a/packages/server/src/telemetry.test.ts b/packages/server/src/telemetry.test.ts
index 46f4b9dc2..6af4aa47a 100644
--- a/packages/server/src/telemetry.test.ts
+++ b/packages/server/src/telemetry.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -8,6 +7,7 @@ import {
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
getMeter,
getTracer,
diff --git a/packages/server/src/tsdown-bundle-coverage.test.ts b/packages/server/src/tsdown-bundle-coverage.test.ts
index 432c59648..0461fbcc9 100644
--- a/packages/server/src/tsdown-bundle-coverage.test.ts
+++ b/packages/server/src/tsdown-bundle-coverage.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
/**
* Regression guard: logger deps stay inlined in the server bundle.
diff --git a/packages/server/src/upload-errors.test.ts b/packages/server/src/upload-errors.test.ts
index 168f09ffa..31c9491b2 100644
--- a/packages/server/src/upload-errors.test.ts
+++ b/packages/server/src/upload-errors.test.ts
@@ -10,7 +10,7 @@
* SDK consumers branching on the URN to display wrong retry guidance.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { classifyUploadErrno, uploadStatusFor, uploadTitleFor } from './upload-errors.ts';
function withCode(code: string): NodeJS.ErrnoException {
diff --git a/packages/server/src/upload-streaming.test.ts b/packages/server/src/upload-streaming.test.ts
index 0b7526763..4f2f015e8 100644
--- a/packages/server/src/upload-streaming.test.ts
+++ b/packages/server/src/upload-streaming.test.ts
@@ -10,7 +10,6 @@
* missing-dir no-op, per-entry error containment
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { createHash, randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { mkdtemp } from 'node:fs/promises';
@@ -18,8 +17,8 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { Readable, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
-
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { UploadWriteError } from './upload-errors.ts';
import {
cleanupOrphanUploadTempfiles,
diff --git a/packages/server/src/upstream-attribution.integration.test.ts b/packages/server/src/upstream-attribution.integration.test.ts
index 2328b1b95..708f70fe2 100644
--- a/packages/server/src/upstream-attribution.integration.test.ts
+++ b/packages/server/src/upstream-attribution.integration.test.ts
@@ -1,8 +1,8 @@
-import { afterEach, beforeEach, expect, test } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import simpleGit, { type SimpleGit } from 'simple-git';
+import { afterEach, beforeEach, expect, test } from 'vitest';
import { __resetContributorsForTests as resetContributorsForTest } from './contributor-tracker.ts';
import { createServer, type ServerInstance } from './server-factory.ts';
import { initShadowRepo, type ShadowHandle, shadowGit } from './shadow-repo.ts';
diff --git a/packages/server/src/version-constants.test.ts b/packages/server/src/version-constants.test.ts
index dbb32ceaf..87d4e42fc 100644
--- a/packages/server/src/version-constants.test.ts
+++ b/packages/server/src/version-constants.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { PROTOCOL_VERSION, RUNTIME_VERSION, STATE_SCHEMA_VERSION } from './version-constants.ts';
describe('version-constants', () => {
diff --git a/scripts/aggregate-stable-changelog.test.mjs b/scripts/aggregate-stable-changelog.test.mjs
index 0b90da533..2e865ebe7 100644
--- a/scripts/aggregate-stable-changelog.test.mjs
+++ b/scripts/aggregate-stable-changelog.test.mjs
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { aggregateStableChangelog } from './aggregate-stable-changelog.mjs';
// A raw beta body as produced by the beta cadence: a lead line, one bump-level
diff --git a/scripts/compute-next-beta.test.mjs b/scripts/compute-next-beta.test.mjs
index dee451e34..ec8e9ab3f 100644
--- a/scripts/compute-next-beta.test.mjs
+++ b/scripts/compute-next-beta.test.mjs
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
bumpSemver,
computeBaseVersion,
diff --git a/scripts/compute-stable-version.test.mjs b/scripts/compute-stable-version.test.mjs
index ab89afada..3194de19b 100644
--- a/scripts/compute-stable-version.test.mjs
+++ b/scripts/compute-stable-version.test.mjs
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { computeStablePromotion } from './compute-stable-version.mjs';
// Injected git boundary so tests need no repo. Defaults: unknown changeset bump
diff --git a/test-support/bun-global-shim.test.ts b/test-support/bun-global-shim.test.ts
index 970defa58..c256a02eb 100644
--- a/test-support/bun-global-shim.test.ts
+++ b/test-support/bun-global-shim.test.ts
@@ -1,8 +1,8 @@
-import { describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
import { bunFacade, installBunGlobal } from './bun-global-shim';
const selfPath = fileURLToPath(import.meta.url);
@@ -47,7 +47,7 @@ describe('Bun global facade', () => {
const scanned = [...new bunFacade.Glob('*.test.ts').scanSync({ cwd: selfDir })];
expect(scanned).toContain('bun-global-shim.test.ts');
- expect(scanned).not.toContain('fixtures/mockable.ts');
+ expect(scanned).not.toContain('bun-global-shim.ts');
});
test('Bun.Glob skips dotfiles and dot-directories (default dot:false parity)', () => {
diff --git a/test-support/bun-global-shim.ts b/test-support/bun-global-shim.ts
index 516418aae..b8aa9d8c9 100644
--- a/test-support/bun-global-shim.ts
+++ b/test-support/bun-global-shim.ts
@@ -404,7 +404,6 @@ class BunCryptoHasherFacade {
* is provided.
*/
class BunTranspilerFacade {
- constructor(_options?: { loader?: string }) {}
transformSync(code: string): string {
return stripTypeScriptTypes(code, { mode: 'transform' });
}
diff --git a/test-support/bun-test-shim.test.ts b/test-support/bun-test-shim.test.ts
deleted file mode 100644
index 2bdf4f239..000000000
--- a/test-support/bun-test-shim.test.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { afterEach, describe, expect, mock, setSystemTime, test, vi } from 'bun:test';
-import type { Mock } from './bun-test-shim';
-import * as shim from './bun-test-shim';
-import { installCrossDirTargetMock } from './fixtures/cross-dir/mock-installer';
-
-// If the alias or the shim regressed, this file would not even import: the
-// `from 'bun:test'` specifiers above resolve only through the configured alias.
-
-describe('bun:test shim', () => {
- test('re-exports the full runtime surface the suite imports from bun:test', () => {
- const surface: Record<string, unknown> = {
- describe: shim.describe,
- test: shim.test,
- it: shim.it,
- expect: shim.expect,
- beforeEach: shim.beforeEach,
- afterEach: shim.afterEach,
- beforeAll: shim.beforeAll,
- afterAll: shim.afterAll,
- spyOn: shim.spyOn,
- mock: shim.mock,
- jest: shim.jest,
- vi: shim.vi,
- setDefaultTimeout: shim.setDefaultTimeout,
- };
- for (const [name, value] of Object.entries(surface)) {
- expect(value, `missing shim export: ${name}`).toBeDefined();
- }
- expect(typeof shim.mock.module).toBe('function');
- // `Mock` is a type-only export; annotating with it proves it resolves.
- const typed: Mock | undefined = undefined;
- expect(typed).toBeUndefined();
- });
-
- test('setDefaultTimeout is callable and re-configures the runtime', () => {
- expect(() => {
- shim.setDefaultTimeout(20_000);
- }).not.toThrow();
- });
-
- test('mock.module facade mocks a subsequently dynamic-imported module', async () => {
- mock.module('./fixtures/mockable', () => ({ greet: () => 'mocked' }));
- const mocked = await import('./fixtures/mockable');
- expect(mocked.greet()).toBe('mocked');
- mock.restore();
- });
-
- test('mock.module facade mocks a subsequently dynamic-imported BARE package', async () => {
- // A bare package specifier resolves relative to the test module, not this
- // shim. Under pnpm's isolated node_modules the two can be different physical
- // copies, so keying the mock against the shim (plain `vi.doMock`) would miss
- // the dynamic import below. `smol-toml` is a real dependency: a passing
- // assertion proves the mock overrides the genuine export.
- const SENTINEL = { __bare_specifier_mock__: true };
- mock.module('smol-toml', () => ({ parse: () => SENTINEL }));
- const mocked = (await import('smol-toml')) as unknown as { parse: (s: string) => unknown };
- expect(mocked.parse('a = 1')).toBe(SENTINEL);
- mock.restore();
- });
-
- test('mock.module registers a bare-package mock against the test module, not the shim', () => {
- // Regression guard for the pnpm resolution fix: the mock must be keyed
- // against the calling test module so the specifier resolves through the same
- // Vite base the SUT imports through. A revert to plain `vi.doMock` would key
- // it against this shim file instead. Because the self-test shares a directory
- // with the shim, a behavioral assertion cannot distinguish the two — so pin
- // the importer directly.
- const mocker = (globalThis as { __vitest_mocker__?: { queueMock: unknown } }).__vitest_mocker__;
- expect(mocker, 'vitest mocker global must be present').toBeDefined();
- const queueMock = vi.spyOn(mocker as { queueMock: (...args: unknown[]) => void }, 'queueMock');
- try {
- mock.module('smol-toml', () => ({ parse: () => null }));
- const call = queueMock.mock.calls.find(([rawId]) => rawId === 'smol-toml');
- expect(call, 'queueMock must be invoked for the bare specifier').toBeDefined();
- const importer = call?.[1] as string;
- expect(importer.endsWith('bun-test-shim.test.ts')).toBe(true);
- expect(importer.endsWith('bun-test-shim.ts')).toBe(false);
- } finally {
- queueMock.mockRestore();
- mock.restore();
- }
- });
-
- test('mock.module resolves a relative specifier against the CALLER, cross-directory', async () => {
- // The installer lives in fixtures/cross-dir/ and mocks './target' relative
- // to ITS OWN directory. This test lives in test-support/, a different dir.
- // If callerFile()/absolutize() work, the mock keys against
- // fixtures/cross-dir/target.ts (which the import below resolves to). If they
- // instead resolved against this test's directory (or left the specifier
- // relative), the key would miss and the dynamic import would get the real
- // module, so the 'mocked-cross-dir' assertion genuinely discriminates.
- installCrossDirTargetMock();
- const mocked = await import('./fixtures/cross-dir/target');
- expect(mocked.greet()).toBe('mocked-cross-dir');
- mock.restore();
- });
-});
-
-describe('test.if / it.if conditional registration', () => {
- // These cases register at collection time; the bodies below run in source
- // order before the final assertion test, which reads the flags they set.
- let ranWhenTrue = false;
- let ranWhenFalse = false;
- let ranWhenTruthyValue = false;
- let ranWhenZero = false;
- let ranWhenEmptyString = false;
-
- test.if(true)('runs the body when the condition is true', () => {
- ranWhenTrue = true;
- });
- test.if(false)('is skipped when the condition is false', () => {
- ranWhenFalse = true;
- });
- test.if('nonempty')('runs when the condition is a truthy non-boolean', () => {
- ranWhenTruthyValue = true;
- });
- test.if(0)('is skipped when the condition is a falsy number (0)', () => {
- ranWhenZero = true;
- });
- test.if('')('is skipped when the condition is a falsy empty string', () => {
- ranWhenEmptyString = true;
- });
-
- test('.if is installed as a function on the shared test/it callables', () => {
- expect(typeof (test as unknown as { if?: unknown }).if).toBe('function');
- expect(typeof (shim.it as unknown as { if?: unknown }).if).toBe('function');
- });
-
- test('ran exactly the truthy-condition bodies and skipped the falsy ones', () => {
- expect(ranWhenTrue).toBe(true);
- expect(ranWhenTruthyValue).toBe(true);
- expect(ranWhenFalse).toBe(false);
- expect(ranWhenZero).toBe(false);
- expect(ranWhenEmptyString).toBe(false);
- });
-});
-
-describe('setSystemTime', () => {
- afterEach(() => {
- // Guarantee the faked Date never leaks into a later test even if an
- // assertion above throws before the no-arg restore runs.
- vi.useRealTimers();
- });
-
- test('freezes Date to the set instant', () => {
- setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
- expect(new Date().toISOString()).toBe('2020-01-01T00:00:00.000Z');
- expect(Date.now()).toBe(Date.parse('2020-01-01T00:00:00.000Z'));
- });
-
- test('leaves real timers running while Date stays frozen', async () => {
- setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
- const frozenBefore = Date.now();
- // Only Date is faked (toFake: ['Date']); a real setTimeout must still fire.
- // If timers were faked too this promise would never resolve and the test
- // would time out — so its resolution proves timers stayed real.
- const fired = await new Promise<boolean>((resolve) => {
- setTimeout(() => resolve(true), 5);
- });
- expect(fired).toBe(true);
- // Real wall time advanced during the await, but the faked Date did not.
- expect(Date.now()).toBe(frozenBefore);
- });
-
- test('a no-arg call restores the real wall clock', () => {
- setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
- expect(new Date().getUTCFullYear()).toBe(2020);
- setSystemTime();
- // Back on the real clock, which is well past 2020.
- expect(new Date().getUTCFullYear()).toBeGreaterThanOrEqual(2026);
- });
-});
-
-describe('vitest-internal mocker canary', () => {
- // Version-pinned tripwire: the bare-specifier path of mock.module keys mocks
- // through the private `globalThis.__vitest_mocker__.queueMock(rawId, importer,
- // factory)`. If a Vitest bump renames/removes/reshapes that internal, mocking
- // would silently break across the whole flipped suite — so fail LOUDLY here
- // instead. Verified against vitest 4.1.10; re-confirm the shape on a bump.
- test('__vitest_mocker__.queueMock has the (rawId, importer, factory) shape the shim depends on', () => {
- const mocker = (globalThis as { __vitest_mocker__?: { queueMock?: unknown } })
- .__vitest_mocker__;
- expect(mocker, 'globalThis.__vitest_mocker__ must be installed by Vitest').toBeDefined();
- const queueMock = mocker?.queueMock;
- expect(typeof queueMock, 'mocker.queueMock must be a function').toBe('function');
- expect(
- (queueMock as (...a: unknown[]) => unknown).length,
- 'queueMock must take (rawId, importer, factory) — an arity change means the importer contract moved',
- ).toBe(3);
- });
-});
diff --git a/test-support/bun-test-shim.ts b/test-support/bun-test-shim.ts
deleted file mode 100644
index 29f506e63..000000000
--- a/test-support/bun-test-shim.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-/**
- * `bun:test` compatibility shim for Vitest 4.
- *
- * Aliased in the shared vitest base config (`resolve.alias['bun:test']` -> this
- * file), so every `import { ... } from 'bun:test'` resolves here unchanged while
- * packages are migrated. Re-exports the exact surface Open Knowledge's suites
- * import from `bun:test` (the 14 symbols across all packages: the hooks +
- * `expect`/`describe`/`test`/`it`, plus `spyOn`, `mock`, `jest`, `vi`, the
- * `Mock` type, and `setDefaultTimeout`), mapping each to its Vitest equivalent.
- *
- * Known behavioral divergences the mapping cannot hide:
- * - `mock.module(path, factory)`: bun patches the module registry AND retro-
- * patches live bindings of already-imported modules. The `vi.doMock` facade
- * below only affects modules imported AFTER the call via dynamic `import()`;
- * static imports already evaluated keep their real bindings. Files relying on
- * retro-patching are rewritten to the mock-then-dynamic-import pattern during
- * their package's flip.
- * - `vi.doMock` resolves the mocked specifier against the CALLING module, which
- * through this shim is the shim file rather than the test. For relative
- * specifiers the facade absolutizes the path against the real caller (derived
- * from the stack) before delegating. For BARE package specifiers it registers
- * the mock against the calling test module directly (see `mockBareSpecifier`)
- * so the specifier resolves through the same Vite base the system-under-test
- * uses — under pnpm's isolated node_modules a package can otherwise resolve to
- * a different physical copy from the shim's location (a root hard-copy) than
- * from the test's package (the `.pnpm` store copy), and the two keys never
- * match.
- *
- * Future work (tracked, not optional): codemod the suite off this shim — rewrite
- * `from 'bun:test'` imports to `from 'vitest'` and `Bun.*` calls to their Node
- * equivalents — then delete both shims. This shim leans on a Vitest-internal
- * mocker (`globalThis.__vitest_mocker__`), so run the codemod BEFORE the next
- * Vitest major bump; each major is a chance for that internal to move, and the
- * canary in the self-test is the trip-wire that forces the decision.
- */
-import fs from 'node:fs';
-import { vi, it as viIt, test as viTest } from 'vitest';
-
-export type { Mock } from 'vitest';
-export {
- afterAll,
- afterEach,
- beforeAll,
- beforeEach,
- describe,
- expect,
- vi,
-} from 'vitest';
-
-/**
- * bun:test exposes `test.if(cond)` / `it.if(cond)` — register the case only when
- * `cond` is truthy. Vitest spells the same conditional `runIf`, so add an `.if`
- * alias to the re-exported callables. Suites typecheck against bun-types (which
- * declares `.if`), so only the runtime value is missing. Additive and idempotent
- * on Vitest's shared test/it singleton.
- */
-for (const target of [viTest, viIt]) {
- const t = target as unknown as {
- if?: (c: unknown) => unknown;
- runIf: (c: unknown) => unknown;
- };
- if (typeof t.if !== 'function') t.if = (c: unknown) => t.runIf(Boolean(c));
-}
-
-export { viIt as it, viTest as test };
-
-export const spyOn: typeof vi.spyOn = vi.spyOn.bind(vi);
-
-/**
- * bun:test's `setSystemTime(date?)` mocks only the wall clock (Date.now / new
- * Date), leaving timers real. Map it to Vitest fake timers scoped to `Date` so
- * the suites' time-travel assertions (e.g. pending-intent expiry) behave the
- * same; a no-arg call restores the real clock, matching bun's reset semantics.
- */
-export function setSystemTime(now?: Date | number): void {
- if (now === undefined) {
- vi.useRealTimers();
- return;
- }
- vi.useFakeTimers({ toFake: ['Date'] });
- vi.setSystemTime(now);
-}
-
-type AnyFn = (...args: unknown[]) => unknown;
-
-/** The first stack frame outside this shim = the test module that called us. */
-function callerFile(): string | undefined {
- const stack = new Error().stack ?? '';
- for (const line of stack.split('\n').slice(1)) {
- const match = line.match(/(?:file:\/\/)?(\/[^\s()]+?):\d+:\d+/);
- // Skip frames inside the shim module itself (but NOT the shim's own
- // self-test, whose path ends `bun-test-shim.test.ts`).
- if (match?.[1] && !match[1].endsWith('bun-test-shim.ts')) return match[1];
- }
- return undefined;
-}
-
-function absolutize(specifier: string): string {
- if (!specifier.startsWith('./') && !specifier.startsWith('../')) return specifier;
- const caller = callerFile();
- if (!caller) {
- // Without the caller we cannot absolutize; the unresolved relative
- // specifier gets keyed against this shim, so the mock silently misses the
- // test's dynamic import. Surface it rather than fail a downstream assertion
- // with no trace back to the resolution gap.
- console.warn(
- `[bun-test-shim] mock.module('${specifier}'): caller file unresolved; mock may not apply`,
- );
- return specifier;
- }
- const base = new URL(specifier, `file://${caller}`).pathname;
- // vitest keys the module registry by the fully-resolved path (with
- // extension); a bare `./foo` would not match the `./foo.ts` the subsequent
- // dynamic import resolves to, so probe the real on-disk file.
- const candidates = [
- base,
- `${base}.ts`,
- `${base}.tsx`,
- `${base}.mts`,
- `${base}.js`,
- `${base}.mjs`,
- `${base}.cjs`,
- `${base}.jsx`,
- `${base}/index.ts`,
- `${base}/index.tsx`,
- `${base}/index.js`,
- ];
- for (const candidate of candidates) {
- try {
- if (fs.statSync(candidate).isFile()) return candidate;
- } catch {
- /* candidate does not exist — try the next extension */
- }
- }
- return base;
-}
-
-/**
- * Vitest's mocker instance for this environment (the same object the injected
- * `vi.mock`/`vi.doMock` compiler hints talk to). `queueMock(rawId, importer,
- * factory)` registers a mock resolving `rawId` against `importer`; going through
- * it lets us set the importer to the test module rather than this shim.
- */
-interface VitestMocker {
- queueMock: (rawId: string, importer: string, factory: () => unknown) => void;
-}
-function getMocker(): VitestMocker | undefined {
- return (globalThis as { __vitest_mocker__?: VitestMocker }).__vitest_mocker__;
-}
-
-/** A relative specifier is resolved on-disk against the caller (see absolutize). */
-function isRelative(specifier: string): boolean {
- return specifier.startsWith('./') || specifier.startsWith('../');
-}
-
-/**
- * Register a bare-package mock against the calling test module. `vi.doMock` keys
- * the mock relative to whoever calls it — here always this shim — so under
- * pnpm's isolated node_modules the shim can resolve a package to a different
- * physical copy than the test's own package does, and the mock silently misses
- * the SUT's dynamic `import('<pkg>')`. Resolving against the test module (the
- * importer Vitest would use had the test called `vi.doMock` directly) keys the
- * mock through the exact Vite resolver base the SUT imports through, so aliases
- * and export conditions stay identical on both sides. Falls back to `vi.doMock`
- * if the internal mocker is unavailable, preserving prior behavior.
- */
-function mockBareSpecifier(path: string, factory: () => unknown): void {
- const mocker = getMocker();
- const importer = callerFile();
- if (mocker && importer) {
- mocker.queueMock(path, importer, () => factory());
- return;
- }
- // Degraded path: the internal mocker or the caller frame is unavailable, so
- // the mock keys against this shim instead of the test module — under pnpm's
- // isolated node_modules that can resolve to a different physical copy and
- // silently miss the SUT's import. Observable so the gap is diagnosable.
- console.warn(
- `[bun-test-shim] mock.module('${path}'): ${mocker ? 'caller file' : 'vitest mocker'} unavailable; falling back to vi.doMock (mock may miss under pnpm)`,
- );
- vi.doMock(path, factory as () => Promise<unknown>);
-}
-
-const mockFn = ((fn?: AnyFn) => vi.fn(fn)) as ((fn?: AnyFn) => ReturnType<typeof vi.fn>) & {
- module: (path: string, factory: () => unknown) => void;
- restore: () => void;
- clearAllMocks: () => void;
-};
-
-mockFn.module = (path: string, factory: () => unknown) => {
- if (isRelative(path)) {
- vi.doMock(absolutize(path), factory as () => Promise<unknown>);
- return;
- }
- mockBareSpecifier(path, factory);
-};
-mockFn.restore = () => {
- vi.restoreAllMocks();
-};
-mockFn.clearAllMocks = () => {
- vi.clearAllMocks();
-};
-
-export const mock = mockFn;
-
-/**
- * bun's `setDefaultTimeout` raises the default budget for both tests and hooks;
- * `vi.setConfig` is the Vitest equivalent that governs the rest of the file.
- */
-export function setDefaultTimeout(ms: number): void {
- vi.setConfig({ testTimeout: ms, hookTimeout: ms });
-}
-
-export const jest = {
- fn: vi.fn.bind(vi),
- spyOn: vi.spyOn.bind(vi),
- restoreAllMocks: () => vi.restoreAllMocks(),
- clearAllMocks: () => vi.clearAllMocks(),
- useFakeTimers: () => vi.useFakeTimers(),
- useRealTimers: () => vi.useRealTimers(),
- advanceTimersByTime: (ms: number) => vi.advanceTimersByTime(ms),
- advanceTimersByTimeAsync: (ms: number) => vi.advanceTimersByTimeAsync(ms),
- runAllTimers: () => vi.runAllTimers(),
- runAllTimersAsync: () => vi.runAllTimersAsync(),
- runOnlyPendingTimers: () => vi.runOnlyPendingTimers(),
- runOnlyPendingTimersAsync: () => vi.runOnlyPendingTimersAsync(),
- advanceTimersToNextTimer: () => vi.advanceTimersToNextTimer(),
- clearAllTimers: () => vi.clearAllTimers(),
- getTimerCount: () => vi.getTimerCount(),
- setSystemTime: (time?: number | Date) => vi.setSystemTime(time),
- getRealSystemTime: () => vi.getRealSystemTime(),
-};
diff --git a/test-support/fixtures/cross-dir/mock-installer.ts b/test-support/fixtures/cross-dir/mock-installer.ts
deleted file mode 100644
index ff25ada16..000000000
--- a/test-support/fixtures/cross-dir/mock-installer.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { mock } from 'bun:test';
-
-/**
- * Calls `mock.module` with a specifier relative to THIS file's directory, not
- * the test's. The mock resolves correctly only if the shim's `callerFile()`
- * walks the stack to this module and `absolutize()` resolves `./target` against
- * this directory — so a test that mocks from here and imports the target from
- * its own (different) directory proves the relative-path resolution.
- */
-export function installCrossDirTargetMock(): void {
- mock.module('./target', () => ({ greet: () => 'mocked-cross-dir' }));
-}
diff --git a/test-support/fixtures/cross-dir/target.ts b/test-support/fixtures/cross-dir/target.ts
deleted file mode 100644
index f612fc669..000000000
--- a/test-support/fixtures/cross-dir/target.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-/** Fixture module for the shim's CROSS-DIRECTORY mock.module self-test. Its
- * real export is replaced when a helper in this same directory (not the test's
- * directory) mocks it via a relative specifier, exercising callerFile/absolutize. */
-export function greet(): string {
- return 'real';
-}
diff --git a/test-support/fixtures/mockable.ts b/test-support/fixtures/mockable.ts
deleted file mode 100644
index 8f0294f7c..000000000
--- a/test-support/fixtures/mockable.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-/** Fixture module for the shim's mock.module self-test. Its real export is
- * replaced by the mock-then-dynamic-import path exercised in the test. */
-export function greet(): string {
- return 'real';
-}
diff --git a/test-support/vitest.base.test.ts b/test-support/vitest.base.test.ts
index 37ad611ae..a5a797ef0 100644
--- a/test-support/vitest.base.test.ts
+++ b/test-support/vitest.base.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { importMetaDirPlugin } from './vitest.base';
type TransformFn = (code: string) => { code: string } | null;
diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.ts
index fa830959a..db6cf6c89 100644
--- a/test-support/vitest.base.ts
+++ b/test-support/vitest.base.ts
@@ -11,7 +11,6 @@
* instead of `src/` — tests would then run against stale build output. The
* SSR resolver is the operative one for inlined workspace symlinks; the
* client-side `resolve.conditions` is set too for safety.
- * - `resolve.alias['bun:test']` routes every `bun:test` import to the shim.
* - `test.setupFiles` installs the `Bun` global facade before any test runs.
*
* `import.meta.dir` (bun-only, no trailing slash) is rewritten at transform time
@@ -48,18 +47,19 @@ export const importMetaDirPlugin: Plugin = {
// transform), and a `.dir`-literal guard would rewrite itself.
if (!code.includes('import.meta')) return null;
IMPORT_META_DIR.lastIndex = 0;
- const out = code.replace(IMPORT_META_DIR, '(new URL(".", import.meta.url).pathname.slice(0, -1))');
+ const out = code.replace(
+ IMPORT_META_DIR,
+ '(new URL(".", import.meta.url).pathname.slice(0, -1))',
+ );
return out === code ? null : { code: out, map: null };
},
};
-export const bunTestShimPath = fileURLToPath(new URL('./bun-test-shim.ts', import.meta.url));
export const bunGlobalShimPath = fileURLToPath(new URL('./bun-global-shim.ts', import.meta.url));
export const okVitestBase = {
plugins: [importMetaDirPlugin],
resolve: {
- alias: { 'bun:test': bunTestShimPath },
conditions: ['development'],
},
ssr: {