Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6977: test: remove implementation-only coverage (#7932)

Multica Eve603519d15836
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4c13848e6f..5114811b65 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -95,10 +95,9 @@ jobs:
# mode for everyone with no error anywhere, so a change to the
# frontend half must run the backend suite.
- 'packages/core/runtimes/cli-version.ts'
- # internal/daemon/agent_command_names_test.go reads both of
- # these as test inputs; the guard script is additionally the
- # entry point scripts/test-go.sh runs, and the names file is
- # the data that guard consumes.
+ # internal/daemon/agent_command_names_test.go exercises the
+ # guard script; scripts/test-go.sh also uses it as the backend
+ # test entry point, and the script reads the command names file.
- 'scripts/agent-cli-command-names.txt'
- 'scripts/go-test-with-agent-cli-guard.sh'
- 'scripts/helm-config.test.sh'
diff --git a/apps/desktop/scripts/package.test.mjs b/apps/desktop/scripts/package.test.mjs
index 5105c2895c..50e2dee949 100644
--- a/apps/desktop/scripts/package.test.mjs
+++ b/apps/desktop/scripts/package.test.mjs
@@ -86,12 +86,9 @@ describe("normalizeGitVersion", () => {
describe("DESCRIBE_ARGS", () => {
it("passes the match pattern as one bare argv token, never a shell-quoted string", () => {
- // The Windows regression this locks down: the pattern used to be embedded
- // in a shell command string as `--match 'v[0-9]*'`. cmd.exe does not strip
- // POSIX single quotes, so git received them literally and matched no tag,
- // collapsing the Desktop version to the 0.0.0-g<hash> fallback. As a
- // standalone argv element with no surrounding quotes the pattern is
- // shell-independent.
+ // Windows cmd.exe does not strip POSIX single quotes. Keeping the pattern
+ // as a bare argv element prevents tagged builds from falling back to a
+ // synthetic 0.0.0-g<hash> version.
expect(DESCRIBE_ARGS).toContain("v[0-9]*");
for (const arg of DESCRIBE_ARGS) {
expect(arg).not.toContain("'");
@@ -470,7 +467,7 @@ describe("electron-builder.yml packaging config", () => {
return entries;
}
- it("excludes the dist output directory from the packaged files", () => {
+ it("excludes prior architecture output from packaged files", () => {
expect(configPath, "electron-builder.yml not found").toBeTruthy();
const entries = readFilesBlock(readFileSync(configPath, "utf-8"));
expect(entries.length).toBeGreaterThan(0);
diff --git a/apps/desktop/src/main/renderer-web-preferences.test.ts b/apps/desktop/src/main/renderer-web-preferences.test.ts
index 008f87349e..2745c891bf 100644
--- a/apps/desktop/src/main/renderer-web-preferences.test.ts
+++ b/apps/desktop/src/main/renderer-web-preferences.test.ts
@@ -31,10 +31,6 @@ describe("createRendererWebPreferences", () => {
expect(createRendererWebPreferences(PRELOAD, "en").plugins).toBe(true);
});
- it("loads the given preload script", () => {
- expect(createRendererWebPreferences(PRELOAD, "en").preload).toBe(PRELOAD);
- });
-
it("passes the system locale and extra arguments to the renderer", () => {
const prefs = createRendererWebPreferences(PRELOAD, "de", [
"--issue-window=<ctx>",
diff --git a/apps/desktop/src/renderer/src/components/desktop-runtimes-page.test.tsx b/apps/desktop/src/renderer/src/components/desktop-runtimes-page.test.tsx
deleted file mode 100644
index c4ce3a437e..0000000000
--- a/apps/desktop/src/renderer/src/components/desktop-runtimes-page.test.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { render } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const runtimesPage = vi.fn<(props: Record<string, unknown>) => null>(() => null);
-const useDesktopRuntimeContext = vi.fn();
-
-vi.mock("@multica/views/runtimes", () => ({
- RuntimesPage: (props: Record<string, unknown>) => runtimesPage(props),
-}));
-
-vi.mock("./use-desktop-runtime-context", () => ({
- useDesktopRuntimeContext: () => useDesktopRuntimeContext(),
-}));
-
-import { DesktopRuntimesPage } from "./desktop-runtimes-page";
-
-describe("DesktopRuntimesPage", () => {
- beforeEach(() => {
- runtimesPage.mockClear();
- useDesktopRuntimeContext.mockReturnValue({
- localDaemonId: "daemon-local",
- localMachineName: "Jiayuan's MacBook",
- bootstrapping: false,
- });
- });
-
- it("keeps daemon controls out of the machine collection", () => {
- render(<DesktopRuntimesPage />);
-
- expect(runtimesPage).toHaveBeenCalledWith({
- localDaemonId: "daemon-local",
- localMachineName: "Jiayuan's MacBook",
- hasLocalMachine: true,
- bootstrapping: false,
- });
- });
-});
diff --git a/apps/desktop/src/renderer/src/font-fallback-order.test.ts b/apps/desktop/src/renderer/src/font-fallback-order.test.ts
deleted file mode 100644
index 96188792d2..0000000000
--- a/apps/desktop/src/renderer/src/font-fallback-order.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-// @vitest-environment node
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { describe, expect, it } from "vitest";
-
-const chineseFonts = ["PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC"];
-const koreanFonts = ["Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans CJK KR"];
-const japaneseFonts = ["Hiragino Sans", "Yu Gothic", "Noto Sans CJK JP"];
-
-function expectChineseFontsBeforeKoreanFonts(source: string) {
- const chineseIndexes = chineseFonts.map((font) => source.indexOf(font));
- const koreanIndexes = koreanFonts.map((font) => source.indexOf(font));
-
- expect(chineseIndexes).not.toContain(-1);
- expect(koreanIndexes).not.toContain(-1);
-
- for (const chineseIndex of chineseIndexes) {
- for (const koreanIndex of koreanIndexes) {
- expect(chineseIndex).toBeLessThan(koreanIndex);
- }
- }
-}
-
-// Japanese Kanji share the Han Unicode block with Chinese, so the global
-// Chinese-first stack must stay Chinese-first (no zh regression) while a
-// Japanese-first CJK stack is scoped to html[lang|="ja"]. App.tsx syncs
-// document.documentElement.lang so the selector matches at runtime.
-function expectJapaneseScopedOverride(source: string) {
- expect(source).toContain('html[lang|="ja"]');
-
- const japaneseIndexes = japaneseFonts.map((font) => source.indexOf(font));
- expect(japaneseIndexes).not.toContain(-1);
-
- const firstJapanese = Math.min(...japaneseIndexes);
- const lastChinese = Math.max(
- ...chineseFonts.map((font) => source.lastIndexOf(font)),
- );
- expect(firstJapanese).toBeLessThan(lastChinese);
-}
-
-describe("CJK font fallback order", () => {
- it("keeps desktop Chinese font fallbacks before Korean font fallbacks", () => {
- const desktopCss = readFileSync(
- resolve(process.cwd(), "src/renderer/src/globals.css"),
- "utf8",
- );
-
- expectChineseFontsBeforeKoreanFonts(desktopCss);
- });
-
- it("scopes the Japanese-first CJK stack to html[lang|='ja']", () => {
- const desktopCss = readFileSync(
- resolve(process.cwd(), "src/renderer/src/globals.css"),
- "utf8",
- );
-
- expectJapaneseScopedOverride(desktopCss);
- });
-});
diff --git a/apps/desktop/src/shared/runtime-config.test.ts b/apps/desktop/src/shared/runtime-config.test.ts
index 08d5b72a3a..d59311139e 100644
--- a/apps/desktop/src/shared/runtime-config.test.ts
+++ b/apps/desktop/src/shared/runtime-config.test.ts
@@ -1,22 +1,12 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import {
- DEFAULT_RUNTIME_CONFIG,
deriveWsUrl,
parseRuntimeConfig,
runtimeConfigFromDevEnv,
} from "./runtime-config";
describe("runtime config", () => {
- it("uses cloud defaults without a desktop.json file", () => {
- expect(DEFAULT_RUNTIME_CONFIG).toEqual({
- schemaVersion: 1,
- apiUrl: "https://api.multica.ai",
- wsUrl: "wss://api.multica.ai/ws",
- appUrl: "https://multica.ai",
- });
- });
-
it("derives https/wss compatible URLs from apiUrl", () => {
expect(
parseRuntimeConfig(
diff --git a/apps/docs/app/font-fallback-order.test.ts b/apps/docs/app/font-fallback-order.test.ts
deleted file mode 100644
index edc7f446b5..0000000000
--- a/apps/docs/app/font-fallback-order.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { describe, expect, it } from "vitest";
-
-const chineseFonts = ["PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC"];
-const koreanFonts = ["Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans CJK KR"];
-const japaneseFonts = ["Hiragino Sans", "Yu Gothic", "Noto Sans CJK JP"];
-
-function expectChineseFontsBeforeKoreanFonts(source: string) {
- const chineseIndexes = chineseFonts.map((font) => source.indexOf(font));
- const koreanIndexes = koreanFonts.map((font) => source.indexOf(font));
-
- expect(chineseIndexes).not.toContain(-1);
- expect(koreanIndexes).not.toContain(-1);
-
- for (const chineseIndex of chineseIndexes) {
- for (const koreanIndex of koreanIndexes) {
- expect(chineseIndex).toBeLessThan(koreanIndex);
- }
- }
-}
-
-// Japanese Kanji share the Han Unicode block with Chinese, so the docs
-// Japanese-first CJK stack must be scoped to html[lang|="ja"] (zh/en keep
-// Chinese-first) and order Japanese fonts before the Chinese families.
-function expectJapaneseScopedOverride(source: string) {
- expect(source).toContain('html[lang|="ja"]');
-
- const japaneseIndexes = japaneseFonts.map((font) => source.indexOf(font));
- expect(japaneseIndexes).not.toContain(-1);
-
- const firstJapanese = Math.min(...japaneseIndexes);
- const lastChinese = Math.max(
- ...chineseFonts.map((font) => source.lastIndexOf(font)),
- );
- expect(firstJapanese).toBeLessThan(lastChinese);
-}
-
-describe("CJK font fallback order", () => {
- it("keeps docs Chinese font fallbacks before Korean font fallbacks", () => {
- const cssSource = readFileSync(
- resolve(process.cwd(), "app/global.css"),
- "utf8",
- );
-
- expectChineseFontsBeforeKoreanFonts(cssSource);
- });
-
- it("scopes the Japanese-first CJK stack to html[lang|='ja']", () => {
- const cssSource = readFileSync(
- resolve(process.cwd(), "app/global.css"),
- "utf8",
- );
-
- expectJapaneseScopedOverride(cssSource);
- });
-});
diff --git a/apps/web/app/favicon.ico/route.test.ts b/apps/web/app/favicon.ico/route.test.ts
index 1655ad809a..17091e9549 100644
--- a/apps/web/app/favicon.ico/route.test.ts
+++ b/apps/web/app/favicon.ico/route.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import { dynamic, GET } from "./route";
+import { GET } from "./route";
describe("GET /favicon.ico", () => {
it("redirects to the SVG favicon", () => {
@@ -21,18 +21,4 @@ describe("GET /favicon.ico", () => {
expect(location.startsWith("/")).toBe(true);
expect(location).not.toMatch(/^https?:\/\//);
});
-
- it("stays off the prerender cache path", () => {
- // Regression: `GET()` takes no arguments, so nothing marks the route
- // dynamic the way the old `request.url` read did. Next then tried to cache
- // a zero-byte body, which the prerender LRU rejects — one
- // "calculateSize returned 0" error per request, and every browser asks for
- // /favicon.ico unprompted.
- //
- // This asserts the export, not the framework behaviour it buys: a unit test
- // cannot observe Next's caching lifecycle. The behaviour itself is checked
- // against a production build (`pnpm build && pnpm start`), where the fix
- // removes both `cache-control: s-maxage=31536000` and the error.
- expect(dynamic).toBe("force-dynamic");
- });
});
diff --git a/apps/web/app/font-fallback-order.test.ts b/apps/web/app/font-fallback-order.test.ts
deleted file mode 100644
index c8f961fb0d..0000000000
--- a/apps/web/app/font-fallback-order.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-// @vitest-environment node
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { describe, expect, it } from "vitest";
-
-const repoRoot = resolve(process.cwd(), "../..");
-const chineseFonts = ["PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC"];
-const koreanFonts = ["Apple SD Gothic Neo", "Malgun Gothic", "Noto Sans CJK KR"];
-const japaneseFonts = ["Hiragino Sans", "Yu Gothic", "Noto Sans CJK JP"];
-
-function expectChineseFontsBeforeKoreanFonts(source: string) {
- const chineseIndexes = chineseFonts.map((font) => source.indexOf(font));
- const koreanIndexes = koreanFonts.map((font) => source.indexOf(font));
-
- expect(chineseIndexes).not.toContain(-1);
- expect(koreanIndexes).not.toContain(-1);
-
- for (const chineseIndex of chineseIndexes) {
- for (const koreanIndex of koreanIndexes) {
- expect(chineseIndex).toBeLessThan(koreanIndex);
- }
- }
-}
-
-// Japanese Kanji share the Han Unicode block with Chinese, so the Korean
-// "append after Chinese" tactic would render Japanese with Chinese glyph
-// shapes. The Japanese CJK chain must therefore be (a) gated behind a lang
-// selector so zh/en keep Chinese-first ordering, and (b) ordered Japanese
-// fonts BEFORE the Chinese families inside that scoped stack.
-function expectJapaneseScopedOverride(source: string) {
- expect(source).toContain('html[lang|="ja"]');
-
- const japaneseIndexes = japaneseFonts.map((font) => source.indexOf(font));
- expect(japaneseIndexes).not.toContain(-1);
-
- const firstJapanese = Math.min(...japaneseIndexes);
- const lastChinese = Math.max(
- ...chineseFonts.map((font) => source.lastIndexOf(font)),
- );
- expect(firstJapanese).toBeLessThan(lastChinese);
-}
-
-describe("CJK font fallback order", () => {
- it("keeps web Chinese font fallbacks before Korean font fallbacks", () => {
- const cssSource = readFileSync(
- resolve(repoRoot, "apps/web/app/globals.css"),
- "utf8",
- );
-
- expectChineseFontsBeforeKoreanFonts(cssSource);
- });
-
- it("scopes the Japanese-first CJK stack to html[lang|='ja'] (web)", () => {
- const cssSource = readFileSync(
- resolve(repoRoot, "apps/web/app/globals.css"),
- "utf8",
- );
-
- expectJapaneseScopedOverride(cssSource);
- });
-
- it("keeps desktop Chinese font fallbacks before Korean font fallbacks", () => {
- const desktopCss = readFileSync(
- resolve(repoRoot, "apps/desktop/src/renderer/src/globals.css"),
- "utf8",
- );
-
- expectChineseFontsBeforeKoreanFonts(desktopCss);
- });
-
- it("scopes the Japanese-first CJK stack to html[lang|='ja'] (desktop)", () => {
- const desktopCss = readFileSync(
- resolve(repoRoot, "apps/desktop/src/renderer/src/globals.css"),
- "utf8",
- );
-
- expectJapaneseScopedOverride(desktopCss);
- });
-});
diff --git a/apps/web/app/manifest.test.ts b/apps/web/app/manifest.test.ts
index 910bc88330..492e41b984 100644
--- a/apps/web/app/manifest.test.ts
+++ b/apps/web/app/manifest.test.ts
@@ -16,28 +16,6 @@ function launch(cookies: Record<string, string>, host = "www.multica.ai") {
}
describe("web app manifest", () => {
- it("declares the fields a browser needs to offer installation", () => {
- const m = manifest();
-
- expect(m.display).toBe("standalone");
- expect(m.scope).toBe("/");
- expect(m.name).toBeTruthy();
- expect(m.short_name).toBeTruthy();
- });
-
- it("ships both icon sizes Chrome requires, plus a maskable one", () => {
- const icons = manifest().icons ?? [];
- const sizesFor = (purpose: string) =>
- icons.filter((icon) => icon.purpose === purpose).map((icon) => icon.sizes);
-
- expect(sizesFor("any")).toEqual(
- expect.arrayContaining(["192x192", "512x512"]),
- );
- // Without a maskable icon Android pads the `any` icon into a white blob
- // instead of cropping it to the launcher shape.
- expect(sizesFor("maskable")).toContain("512x512");
- for (const icon of icons) expect(icon.src.startsWith("/icons/")).toBe(true);
- });
it("does not launch at the root path", () => {
// The official marketing hosts keep "/" on the public site even for a
diff --git a/apps/web/app/type-scale.test.ts b/apps/web/app/type-scale.test.ts
deleted file mode 100644
index 47817d0a4a..0000000000
--- a/apps/web/app/type-scale.test.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-// @vitest-environment node
-import { readFileSync, readdirSync, statSync } from "node:fs";
-import { resolve, join, relative } from "node:path";
-import { describe, expect, it } from "vitest";
-
-/**
- * Does the product still have exactly one type scale?
- *
- * Before `--text-*` existed in tokens.css there was no baseline to align to, so
- * font sizes grew wherever they were needed: 51 distinct sizes across web and
- * desktop, 370 written as arbitrary pixel values, six of those at half a pixel
- * (10.5 / 11.5 / 12.5 / 13.5 / 14.5 / 15.5px). A scale only holds if going off
- * it is harder than staying on it, and nothing in a Tailwind build makes an
- * off-scale arbitrary size look wrong — it compiles exactly like a token does.
- *
- * So the guard lives here. This asserts on source text rather than on rendered
- * components because the failure mode is authorial, not behavioural: a
- * component test would prove a class name renders, never that the class was one
- * of the ten the design system actually defines.
- *
- * Any unit counts, not just px. The first sweep of this migration only looked
- * for `px` and so walked straight past four `0.8rem` call sites in
- * packages/ui — an off-scale size is off-scale however it is spelled.
- *
- * Scope is product UI. `apps/mobile` builds through its own NativeWind config
- * and `apps/docs` rides fumadocs' type system; both keep Tailwind's default
- * scale on purpose and are not scanned.
- */
-
-const repoRoot = resolve(process.cwd(), "../..");
-
-/** The scale, as tokens.css defines it. Sizes in px. */
-const SCALE = [
- ["micro", 11, 15],
- ["caption", 12, 16],
- ["label", 13, 18],
- ["body", 14, 20],
- ["body-lg", 15, 22],
- ["title-sm", 16, 24],
- ["title", 18, 28],
- ["title-lg", 20, 28],
- ["display-sm", 24, 32],
- ["display", 36, 40],
-] as const;
-
-const scanRoots = ["packages/ui", "packages/views", "apps/web", "apps/desktop/src"];
-const skipDirs = new Set(["node_modules", ".next", "dist", "out", "build", ".turbo"]);
-const sourceExtensions = [".ts", ".tsx", ".css"];
-
-/**
- * Landing pages run a marketing display ramp (rem/clamp, 2.2-6.4rem) that is
- * deliberately not this scale — a hero headline does not belong on the same
- * steps as a table cell. They still may not use pixel sizes, so only the
- * relative-unit rule is lifted for them.
- */
-const marketingPaths = ["apps/web/app/(landing)", "apps/web/features/landing"];
-const isMarketing = (rel: string) => marketingPaths.some((p) => rel.startsWith(p));
-
-/**
- * Tailwind's default steps that the role scale replaces one-for-one. `text-4xl`
- * and larger are not listed: their only call sites are decorative emoji and the
- * serif onboarding hero, which are not UI text and do not sit on this ramp.
- */
-const replacedDefaults = ["xs", "sm", "base", "lg", "xl", "2xl", "3xl"];
-
-const bannedPatterns = [
- {
- label: "arbitrary pixel size",
- regex: /\btext-\[\d+(?:\.\d+)?px\]/g,
- hint: "use a scale step (text-micro … text-display)",
- appliesTo: () => true,
- },
- {
- label: "arbitrary relative size",
- regex: /\btext-\[\d*\.?\d+(?:rem|em)\]/g,
- hint: "use a scale step (text-micro … text-display)",
- appliesTo: (rel: string) => !isMarketing(rel),
- },
- {
- label: "Tailwind default size",
- regex: new RegExp(String.raw`\btext-(?:${replacedDefaults.join("|")})\b`, "g"),
- hint: "use the role-named equivalent: sm -> body, base -> title-sm, 2xl -> display-sm",
- appliesTo: () => true,
- },
- /**
- * Hand-written CSS is the blind spot a class-only guard leaves open, and it
- * is where the worst of the old drift survived longest: the transcript kept
- * a 12.5px body long after every Tailwind call site was on the scale, so the
- * "no half-pixel sizes" claim was true of the classes and false of the
- * product. A literal length here is off-scale by definition — the steps are
- * reachable as `var(--text-*)`.
- */
- {
- // The lookahead sits directly after the colon and swallows the whitespace
- // itself. Written as `\s*(?!var\()` the engine simply backtracks `\s*` to
- // zero width, the lookahead then sees a space rather than `var(`, and every
- // tokenised declaration matches as a violation.
- label: "raw CSS font-size",
- regex: /font-size:(?!\s*var\()\s*[^;}]+/g,
- hint: "use var(--text-micro) … var(--text-display)",
- appliesTo: (rel: string) => rel.endsWith(".css") && !isMarketing(rel),
- },
-];
-
-/**
- * `base.css` pins editable text to 16px on coarse pointers because iOS Safari
- * zooms the page when a focused input is below 16px. That is a platform
- * workaround, not typography, and no scale step can express it.
- */
-const rawCssExemptions = [/font-size:\s*16px\s*!important/];
-
-/**
- * Tailwind scans this file like any other source, so a banned class written out
- * in full here would compile into the bundle as dead CSS — the exact thing the
- * test exists to prevent. Hints and prose above therefore name the steps
- * without the `text-` prefix, and the patterns build it at runtime.
- */
-
-/**
- * Comments legitimately name the old classes when explaining what a step
- * replaced, so they are stripped before scanning. Over-stripping would only
- * ever hide a violation, never invent one, and a class name never follows a
- * comment marker on the same line in practice.
- */
-function stripComments(source: string): string {
- return source
- // Block comments are replaced with their own newlines rather than removed,
- // so a violation's reported line still matches the real file. Collapsing
- // them shifts every line below a file header comment.
- .replace(/\/\*[\s\S]*?\*\//g, (block) => "\n".repeat((block.match(/\n/g) ?? []).length))
- .replace(/(^|[^:])\/\/[^\n]*/g, "$1");
-}
-
-function collectSourceFiles(dir: string, found: string[] = []): string[] {
- for (const entry of readdirSync(dir)) {
- if (skipDirs.has(entry)) continue;
- const path = join(dir, entry);
- if (statSync(path).isDirectory()) {
- collectSourceFiles(path, found);
- continue;
- }
- if (!sourceExtensions.some((ext) => entry.endsWith(ext))) continue;
- if (/\.test\.tsx?$/.test(entry)) continue;
- found.push(path);
- }
- return found;
-}
-
-describe("type scale", () => {
- const tokens = readFileSync(resolve(repoRoot, "packages/ui/styles/tokens.css"), "utf8");
-
- it.each(SCALE)("defines --text-%s with a paired line-height", (name, size, lineHeight) => {
- expect(tokens).toContain(`--text-${name}: ${size}px;`);
- expect(tokens).toContain(`--text-${name}--line-height: ${lineHeight}px;`);
- });
-
- it("steps ascend in size and never tighten line-height going up", () => {
- for (let i = 1; i < SCALE.length; i += 1) {
- const [name, size, lineHeight] = SCALE[i]!;
- const [, previousSize, previousLineHeight] = SCALE[i - 1]!;
- expect(size, `${name} must be larger than the step below it`).toBeGreaterThan(previousSize);
- expect(lineHeight, `${name} line-height must not drop below the step below it`)
- .toBeGreaterThanOrEqual(previousLineHeight);
- }
- });
-
- /**
- * The steps are role-named, so tailwind-merge cannot infer that they are font
- * sizes and needs them registered explicitly in `packages/ui/lib/utils.ts`.
- * A step missing from that list is dropped whenever it meets a colour class,
- * silently, so the two lists have to agree.
- */
- it("registers every step with tailwind-merge so cn() cannot drop it", () => {
- const utils = readFileSync(resolve(repoRoot, "packages/ui/lib/utils.ts"), "utf8");
- for (const [name] of SCALE) {
- expect(utils, `${name} missing from the tailwind-merge font-size group`)
- .toContain(`"${name}"`);
- }
- });
-
- it("product UI writes no font size outside the scale", () => {
- const violations: string[] = [];
-
- for (const root of scanRoots) {
- for (const path of collectSourceFiles(resolve(repoRoot, root))) {
- const rel = relative(repoRoot, path);
- const lines = stripComments(readFileSync(path, "utf8")).split("\n");
- lines.forEach((line, index) => {
- for (const { label, regex, hint, appliesTo } of bannedPatterns) {
- if (!appliesTo(rel)) continue;
- regex.lastIndex = 0;
- for (const match of line.matchAll(regex)) {
- if (rawCssExemptions.some((exempt) => exempt.test(match[0]))) continue;
- violations.push(
- `${rel}:${index + 1} ${match[0].trim()} (${label} — ${hint})`,
- );
- }
- }
- });
- }
- }
-
- expect(violations, `Font sizes off the scale:\n${violations.join("\n")}`).toEqual([]);
- });
-});
diff --git a/packages/core/agents/effective-access.test.ts b/packages/core/agents/effective-access.test.ts
index 728815af6f..0ea1ca32b9 100644
--- a/packages/core/agents/effective-access.test.ts
+++ b/packages/core/agents/effective-access.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import type { AgentInvocationTarget } from "../types";
import {
- ALL_ACCESS_SCOPES,
effectiveAccessScope,
isAccessChangeReady,
} from "./effective-access";
@@ -52,16 +51,6 @@ describe("effectiveAccessScope", () => {
});
});
-describe("ALL_ACCESS_SCOPES", () => {
- it("lists the three scopes in display order", () => {
- expect(ALL_ACCESS_SCOPES).toEqual([
- "workspace",
- "specific-people",
- "owner-only",
- ]);
- });
-});
-
describe("isAccessChangeReady", () => {
it("null is not ready (no scope picked yet)", () => {
expect(isAccessChangeReady(null)).toBe(false);
diff --git a/packages/core/agents/mcp-support.test.ts b/packages/core/agents/mcp-support.test.ts
index 36ae3d985a..674876b02c 100644
--- a/packages/core/agents/mcp-support.test.ts
+++ b/packages/core/agents/mcp-support.test.ts
@@ -3,30 +3,9 @@ import { describe, expect, it } from "vitest";
import { providerSupportsMcpConfig } from "./mcp-support";
describe("providerSupportsMcpConfig", () => {
- it("matches providers whose runtime consumes mcp_config", () => {
+ it("accepts a provider whose runtime consumes mcp_config", () => {
expect(providerSupportsMcpConfig("claude")).toBe(true);
- expect(providerSupportsMcpConfig("codebuddy")).toBe(true);
- expect(providerSupportsMcpConfig("codearts")).toBe(true);
- expect(providerSupportsMcpConfig("codex")).toBe(true);
- expect(providerSupportsMcpConfig("cursor")).toBe(true);
- expect(providerSupportsMcpConfig("hermes")).toBe(true);
- expect(providerSupportsMcpConfig("kimi")).toBe(true);
- expect(providerSupportsMcpConfig("reasonix")).toBe(true);
- expect(providerSupportsMcpConfig("dsh")).toBe(true);
- expect(providerSupportsMcpConfig("kiro")).toBe(true);
- expect(providerSupportsMcpConfig("opencode")).toBe(true);
- expect(providerSupportsMcpConfig("openclaw")).toBe(true);
- expect(providerSupportsMcpConfig("qoder")).toBe(true);
- expect(providerSupportsMcpConfig("qoderclicn")).toBe(true);
- expect(providerSupportsMcpConfig("qwen")).toBe(true);
- expect(providerSupportsMcpConfig("qwenpaw")).toBe(true);
- expect(providerSupportsMcpConfig("traecli")).toBe(true);
- expect(providerSupportsMcpConfig("grok")).toBe(true);
- expect(providerSupportsMcpConfig("dim")).toBe(true);
- expect(providerSupportsMcpConfig("mcode")).toBe(true);
- expect(providerSupportsMcpConfig("omp")).toBe(true);
});
-
it("rejects providers whose runtime ignores mcp_config", () => {
expect(providerSupportsMcpConfig("antigravity")).toBe(false);
expect(providerSupportsMcpConfig("copilot")).toBe(false);
diff --git a/packages/core/agents/stores/transcript-view-store.test.ts b/packages/core/agents/stores/transcript-view-store.test.ts
index c1ea081d74..8391f27c38 100644
--- a/packages/core/agents/stores/transcript-view-store.test.ts
+++ b/packages/core/agents/stores/transcript-view-store.test.ts
@@ -9,20 +9,6 @@ beforeEach(() => {
});
describe("useTranscriptViewStore", () => {
- it("defaults to chronological and unfiltered", () => {
- expect(useTranscriptViewStore.getState().sortDirection).toBe("chronological");
- expect(useTranscriptViewStore.getState().selectedFilterKeys).toEqual([]);
- });
-
- it("setSortDirection switches between the two known directions", () => {
- const { setSortDirection } = useTranscriptViewStore.getState();
-
- setSortDirection("newest_first");
- expect(useTranscriptViewStore.getState().sortDirection).toBe("newest_first");
-
- setSortDirection("chronological");
- expect(useTranscriptViewStore.getState().sortDirection).toBe("chronological");
- });
it("stores filter preferences as unique serializable keys", () => {
const { setSelectedFilterKeys, toggleFilterKey, clearFilterKeys } =
diff --git a/packages/core/agents/stores/view-store.test.ts b/packages/core/agents/stores/view-store.test.ts
index 5cb95b700f..d48a7be756 100644
--- a/packages/core/agents/stores/view-store.test.ts
+++ b/packages/core/agents/stores/view-store.test.ts
@@ -35,14 +35,6 @@ afterEach(() => {
});
describe("useAgentsViewStore", () => {
- it("defaults to 'mine'", () => {
- expect(useAgentsViewStore.getState().scope).toBe("mine");
- });
-
- it("setScope mutates the store", () => {
- useAgentsViewStore.getState().setScope("all");
- expect(useAgentsViewStore.getState().scope).toBe("all");
- });
it("partialize persists only view prefs (no actions) under the workspace-namespaced key", async () => {
setCurrentWorkspace("acme", "ws_a");
@@ -123,11 +115,6 @@ describe("useAgentsViewStore", () => {
});
describe("access filter dimension", () => {
- it("EMPTY_AGENT_FILTERS initializes access to []", async () => {
- const { EMPTY_AGENT_FILTERS } = await import("./view-store");
- expect(EMPTY_AGENT_FILTERS.access).toEqual([]);
- });
-
it("toggleFilter('access', value) adds and removes the value", () => {
const { toggleFilter } = useAgentsViewStore.getState();
toggleFilter("access", "owner-only");
diff --git a/packages/core/issues/stores/comment-composer-store.test.ts b/packages/core/issues/stores/comment-composer-store.test.ts
index 26e3e41fe2..7e727f0523 100644
--- a/packages/core/issues/stores/comment-composer-store.test.ts
+++ b/packages/core/issues/stores/comment-composer-store.test.ts
@@ -26,10 +26,6 @@ describe("comment composer store", () => {
useCommentComposerStore.setState({ sticky: true });
});
- it("defaults to sticky", () => {
- expect(useCommentComposerStore.getState().sticky).toBe(true);
- });
-
it("toggleSticky flips the preference", () => {
useCommentComposerStore.getState().toggleSticky();
expect(useCommentComposerStore.getState().sticky).toBe(false);
diff --git a/packages/core/issues/stores/issue-create-settings-store.test.ts b/packages/core/issues/stores/issue-create-settings-store.test.ts
index dc0f984f0c..2c2b1d8e4b 100644
--- a/packages/core/issues/stores/issue-create-settings-store.test.ts
+++ b/packages/core/issues/stores/issue-create-settings-store.test.ts
@@ -13,17 +13,6 @@ describe("issue create settings store", () => {
});
});
- it("defaults to project-only quick create and the classic manual toolbar", () => {
- expect(useIssueCreateSettingsStore.getState().quickCreateFields).toEqual(["project"]);
- expect(useIssueCreateSettingsStore.getState().manualCreateFields).toEqual([
- "status",
- "priority",
- "assignee",
- "labels",
- "project",
- ]);
- });
-
it("keeps quick create fields in canonical order regardless of toggle sequence", () => {
const { setQuickCreateFieldVisible } = useIssueCreateSettingsStore.getState();
diff --git a/packages/core/issues/stores/issues-scope-store.test.ts b/packages/core/issues/stores/issues-scope-store.test.ts
index 22e152b9a4..154d9899c4 100644
--- a/packages/core/issues/stores/issues-scope-store.test.ts
+++ b/packages/core/issues/stores/issues-scope-store.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it } from "vitest";
-import { useIssuesScope, useIssuesScopeStore } from "./issues-scope-store";
+import { useIssuesScopeStore } from "./issues-scope-store";
describe("issues scope store", () => {
beforeEach(() => {
@@ -18,13 +18,6 @@ describe("issues scope store", () => {
expect(scopes["project:p2"]).toBeUndefined();
});
- it("defaults an untouched page to the unrestricted tab", () => {
- // Same fallback the useIssuesScope hook applies.
- const { scopes } = useIssuesScopeStore.getState();
- expect(scopes["project:p9"] ?? "all").toBe("all");
- expect(useIssuesScope).toBeTypeOf("function");
- });
-
it("migrates the v0 global tab onto the Issues page only", () => {
const migrate = useIssuesScopeStore.persist.getOptions().migrate!;
expect(migrate({ scope: "agents" }, 0)).toEqual({
diff --git a/packages/core/issues/stores/sub-issue-display-store.test.ts b/packages/core/issues/stores/sub-issue-display-store.test.ts
index 521f3f8fd3..3a001528c3 100644
--- a/packages/core/issues/stores/sub-issue-display-store.test.ts
+++ b/packages/core/issues/stores/sub-issue-display-store.test.ts
@@ -32,18 +32,6 @@ describe("sub-issue display store", () => {
});
});
- it("defaults to showing every built-in field and no custom properties", () => {
- const s = useSubIssueDisplayStore.getState();
- expect(s.rowProperties).toEqual({
- priority: true,
- labels: true,
- childProgress: true,
- dueDate: true,
- assignee: true,
- });
- expect(s.rowPropertyIds).toEqual([]);
- });
-
it("toggleRowProperty flips a single field without touching the rest", () => {
useSubIssueDisplayStore.getState().toggleRowProperty("dueDate");
expect(useSubIssueDisplayStore.getState().rowProperties).toEqual({
diff --git a/packages/core/onboarding/welcome-store.test.ts b/packages/core/onboarding/welcome-store.test.ts
index b977c30fa2..f0650e5bb4 100644
--- a/packages/core/onboarding/welcome-store.test.ts
+++ b/packages/core/onboarding/welcome-store.test.ts
@@ -11,11 +11,6 @@ describe("welcome-store", () => {
useWelcomeStore.getState().reset();
});
- it("starts empty and not dismissed", () => {
- expect(useWelcomeStore.getState().signal).toBeNull();
- expect(useWelcomeStore.getState().dismissed).toBe(false);
- });
-
it("set() stores the signal and clears any prior dismissed flag", () => {
useWelcomeStore.getState().dismiss();
expect(useWelcomeStore.getState().dismissed).toBe(true);
diff --git a/packages/core/paths/consistency.test.ts b/packages/core/paths/consistency.test.ts
index 6723b2e726..fc804adc69 100644
--- a/packages/core/paths/consistency.test.ts
+++ b/packages/core/paths/consistency.test.ts
@@ -8,34 +8,6 @@ import { RESERVED_SLUGS } from "./reserved-slugs";
// we hardcode the expected list and assert paths.workspace produces the same
// keys. If you change either, BOTH need to be updated — the test catches drift.
describe("paths.workspace() shape", () => {
- it("exposes the expected parameterless workspace route methods", () => {
- const ws = paths.workspace("__probe__");
- const parameterlessRoutes = Object.entries(ws)
- .filter(([, fn]) => typeof fn === "function" && fn.length === 0)
- .map(([key]) => key);
-
- expect(new Set(parameterlessRoutes)).toEqual(
- new Set([
- "root",
- "usage",
- "issues",
- "projects",
- "autopilots",
- "agents",
- "newAgent",
- "newAgentManual",
- "newAgentAi",
- "chat",
- "squads",
- "inbox",
- "myIssues",
- "runtimes",
- "skills",
- "squads",
- "settings",
- ]),
- );
- });
it("each parameterless route emits /{slug}/{segment}", () => {
const ws = paths.workspace("acme");
diff --git a/packages/core/paths/reserved-slugs.test.ts b/packages/core/paths/reserved-slugs.test.ts
index bac2518d0a..8f042d0b8f 100644
--- a/packages/core/paths/reserved-slugs.test.ts
+++ b/packages/core/paths/reserved-slugs.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { RESERVED_SLUGS, isReservedSlug } from "./reserved-slugs";
+import { isReservedSlug } from "./reserved-slugs";
describe("reserved slugs", () => {
it("returns true for a known reserved slug", () => {
@@ -14,16 +14,6 @@ describe("reserved slugs", () => {
expect(isReservedSlug("")).toBe(false);
});
- it("exposes a non-empty reserved slug set", () => {
- expect(RESERVED_SLUGS.size).toBeGreaterThan(0);
- });
-
- it("keeps the set and predicate consistent", () => {
- for (const slug of RESERVED_SLUGS) {
- expect(isReservedSlug(slug)).toBe(true);
- }
- });
-
it("matches slugs case-sensitively", () => {
expect(isReservedSlug("Login")).toBe(false);
});
diff --git a/packages/core/projects/stores/view-store.test.ts b/packages/core/projects/stores/view-store.test.ts
index 7d35c93f7e..9c742ee069 100644
--- a/packages/core/projects/stores/view-store.test.ts
+++ b/packages/core/projects/stores/view-store.test.ts
@@ -35,14 +35,6 @@ afterEach(() => {
});
describe("useProjectViewStore", () => {
- it("defaults to 'compact'", () => {
- expect(useProjectViewStore.getState().viewMode).toBe("compact");
- });
-
- it("setViewMode mutates the store", () => {
- useProjectViewStore.getState().setViewMode("comfortable");
- expect(useProjectViewStore.getState().viewMode).toBe("comfortable");
- });
it("partialize persists view prefs (no actions) under the workspace-namespaced key", async () => {
setCurrentWorkspace("acme", "ws_a");
diff --git a/packages/core/shortcuts/definitions.test.ts b/packages/core/shortcuts/definitions.test.ts
index 04a4830160..360152a0a5 100644
--- a/packages/core/shortcuts/definitions.test.ts
+++ b/packages/core/shortcuts/definitions.test.ts
@@ -93,20 +93,8 @@ describe("keyboard shortcut definitions", () => {
expect(action.allowInEditable).toBe(true);
});
- it("assigns distinct defaults to the left and right sidebar toggles", () => {
- expect(SHORTCUT_ACTION_BY_ID.toggleSidebar.defaultShortcut).toEqual(
- createShortcutChord("B", { primary: true }),
- );
- expect(SHORTCUT_ACTION_BY_ID.toggleRightSidebar.defaultShortcut).toEqual(
- createShortcutChord("/", { primary: true }),
- );
- expect(SHORTCUT_ACTION_BY_ID.toggleRightSidebar.allowInEditable).toBe(false);
- });
-
- it("keeps the inbox archive key out of editable controls", () => {
- const action = SHORTCUT_ACTION_BY_ID.archiveInboxItem;
- expect(action.defaultShortcut).toEqual(createShortcutChord("E"));
- expect(action.allowInEditable).toBe(false);
+ it("keeps the plain inbox archive key out of editable controls", () => {
+ expect(SHORTCUT_ACTION_BY_ID.archiveInboxItem.allowInEditable).toBe(false);
});
it("strictly distinguishes Command and Control on macOS", () => {
diff --git a/packages/core/squads/stores/view-store.test.ts b/packages/core/squads/stores/view-store.test.ts
index af22d66ccd..960eb9afa9 100644
--- a/packages/core/squads/stores/view-store.test.ts
+++ b/packages/core/squads/stores/view-store.test.ts
@@ -35,14 +35,6 @@ afterEach(() => {
});
describe("useSquadsViewStore", () => {
- it("defaults to 'mine'", () => {
- expect(useSquadsViewStore.getState().scope).toBe("mine");
- });
-
- it("setScope mutates the store", () => {
- useSquadsViewStore.getState().setScope("all");
- expect(useSquadsViewStore.getState().scope).toBe("all");
- });
it("partialize persists view prefs (no actions) under the workspace-namespaced key", async () => {
setCurrentWorkspace("acme", "ws_a");
diff --git a/packages/views/agents/components/agent-batch-toolbar.test.tsx b/packages/views/agents/components/agent-batch-toolbar.test.tsx
index 505c7cb5dc..5282961b70 100644
--- a/packages/views/agents/components/agent-batch-toolbar.test.tsx
+++ b/packages/views/agents/components/agent-batch-toolbar.test.tsx
@@ -151,12 +151,6 @@ describe("AgentBatchToolbar — presence", () => {
});
describe("AgentBatchToolbar — bulk Set access scope", () => {
- it("shows the Set access scope button for active owned agents", () => {
- renderToolbar([makeRow("a", "user-1")]);
- expect(
- screen.getByRole("button", { name: "Set access scope" }),
- ).toBeInTheDocument();
- });
it("renders Applies to N with skip count in the dialog", async () => {
renderToolbar([
diff --git a/packages/views/agents/components/agent-overview-pane.test.tsx b/packages/views/agents/components/agent-overview-pane.test.tsx
index 30ba45691d..e8d09b1abf 100644
--- a/packages/views/agents/components/agent-overview-pane.test.tsx
+++ b/packages/views/agents/components/agent-overview-pane.test.tsx
@@ -258,14 +258,6 @@ describe("AgentOverviewPane Integrations tab visibility", () => {
});
});
-describe("AgentOverviewPane Settings navigation", () => {
- it("gives Access its own settings tab", () => {
- renderPane([makeRuntime("claude")]);
- openSettings();
- expect(screen.getByRole("tab", { name: /^Access$/i })).toBeInTheDocument();
- });
-});
-
describe("AgentOverviewPane Environment tab visibility", () => {
it("shows the Environment tab to someone who can manage the agent", () => {
renderPane([makeRuntime("claude")]);
diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsx
index 59d2329bab..df99c2faa4 100644
--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.test.tsx
@@ -283,13 +283,6 @@ describe("IntegrationsTab", () => {
);
});
- it("renders the DingTalk brand mark in the DingTalk integration card", () => {
- renderTab(<IntegrationsTab agent={agent} />);
- const section = screen.getByText("DingTalk").closest("section");
- expect(section?.querySelector('[data-testid="dingtalk-mark"].h-5.w-5')).toBeTruthy();
- expect(screen.getByText(enSettings.dingtalk.agent_page_description)).toBeTruthy();
- });
-
it("shows only this Agent's 1:1 bot and its groups", () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-08-19T10:00:00Z"));
diff --git a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
index 067b7ad27d..ca3a22d3e7 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
@@ -404,28 +404,6 @@ describe("McpConfigTab workspace servers", () => {
await waitFor(() => expect(mockAddServer).toHaveBeenCalledWith("srv-9"));
});
- // A workspace can accumulate a lot of shared servers, and the picker is a
- // menu anchored to a small button: it has to stay inside a bounded, scrolling
- // box and keep the trigger's width instead of growing down the page.
- it("keeps the picker bounded, scrollable, and anchored when the library is long", async () => {
- const user = userEvent.setup();
- workspaceMcp.library = Array.from({ length: 40 }, (_, i) =>
- wsServer({ id: `srv-${i}`, name: `shared-server-${i}` }),
- );
- renderTab({ mcp_config: null });
-
- await user.click(
- await screen.findByRole("button", { name: /Add from workspace/ }),
- );
-
- const items = await screen.findAllByRole("menuitem");
- expect(items).toHaveLength(40);
- const menu = items[0]!.closest("[data-slot='dropdown-menu-content']");
- expect(menu?.className).toMatch(/\bmax-h-72\b/);
- expect(menu?.className).toMatch(/\boverflow-y-auto\b/);
- expect(menu?.className).toMatch(/min-w-\(--anchor-width\)/);
- });
-
it("toggles an assignment off without dropping it", async () => {
const user = userEvent.setup();
workspaceMcp.assigned = [wsServer({ enabled: true })];
diff --git a/packages/views/agents/create/create-agent-ui.test.ts b/packages/views/agents/create/create-agent-ui.test.ts
index e493b7aac0..9f6ddc992c 100644
--- a/packages/views/agents/create/create-agent-ui.test.ts
+++ b/packages/views/agents/create/create-agent-ui.test.ts
@@ -9,21 +9,9 @@ import {
workspaceKeys,
} from "@multica/core/workspace/queries";
import { AgentNameField } from "./agent-configuration-panel";
-import { CreateMethodChooser } from "./choose-create-method-page";
import { CreateAgentFooter } from "./create-agent-footer";
import { draftPreview } from "./unfinished-drafts";
import { classifyAgentCreateError } from "./use-create-agent-submit";
-import { NavigationProvider, type NavigationAdapter } from "../../navigation";
-
-const TEST_NAVIGATION: NavigationAdapter = {
- push: vi.fn(),
- replace: vi.fn(),
- back: vi.fn(),
- pathname: "/acme/agents/new",
- searchParams: new URLSearchParams(),
- hash: "",
- getShareableUrl: (path: string) => path,
-};
vi.mock("../../i18n", () => ({
useT: () => ({
@@ -277,27 +265,3 @@ describe("Unfinished draft preview", () => {
).toBe("");
});
});
-
-describe("Agent creation method chooser", () => {
- it("always offers AI-assisted creation", () => {
- render(
- createElement(NavigationProvider, {
- value: TEST_NAVIGATION,
- children: createElement(CreateMethodChooser, {
- blankHref: "/acme/agents/new/manual",
- aiHref: "/acme/agents/new/ai",
- }),
- }),
- );
-
- expect(screen.getByText("Start blank")).toBeInTheDocument();
- expect(screen.getByText("Build with AI")).toBeInTheDocument();
- expect(
- screen.getByText("Start blank").closest("a"),
- ).toHaveAttribute("href", "/acme/agents/new/manual");
- expect(screen.getByText("Build with AI").closest("a")).toHaveAttribute(
- "href",
- "/acme/agents/new/ai",
- );
- });
-});
diff --git a/packages/views/auth/login-page.test.tsx b/packages/views/auth/login-page.test.tsx
index b351c09315..19c43ff08b 100644
--- a/packages/views/auth/login-page.test.tsx
+++ b/packages/views/auth/login-page.test.tsx
@@ -333,22 +333,6 @@ describe("LoginPage", () => {
expect(resendBtn).toBeDisabled();
});
- it("shows resend button with cooldown text after sending code", async () => {
- mockSendCode.mockResolvedValue(undefined);
- const user = userEvent.setup();
- renderWithI18n(<LoginPage onSuccess={onSuccess} />);
-
- await user.type(screen.getByLabelText(/email/i), "[email protected]");
- await user.click(screen.getByRole("button", { name: /continue/i }));
-
- await waitFor(() => {
- expect(screen.getByText(/check your email/i)).toBeInTheDocument();
- });
-
- // After transition, resend shows cooldown text and is disabled
- expect(screen.getByText(/resend in/i)).toBeInTheDocument();
- });
-
it("calls sendCode again when resend is clicked after cooldown", async () => {
mockSendCode.mockResolvedValue(undefined);
renderWithI18n(<LoginPage onSuccess={onSuccess} />);
@@ -631,11 +615,6 @@ describe("LoginPage", () => {
expect(screen.getByTestId("custom-logo")).toBeInTheDocument();
});
- it("does not render logo placeholder when omitted", () => {
- renderWithI18n(<LoginPage onSuccess={onSuccess} />);
- expect(screen.queryByTestId("custom-logo")).not.toBeInTheDocument();
- });
-
// -------------------------------------------------------------------------
// onTokenObtained callback
// -------------------------------------------------------------------------
diff --git a/packages/views/autopilots/components/autopilots-page.test.ts b/packages/views/autopilots/components/autopilots-page.test.ts
deleted file mode 100644
index 8126804015..0000000000
--- a/packages/views/autopilots/components/autopilots-page.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-// @vitest-environment node
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-
-const pageSource = readFileSync(
- "autopilots/components/autopilots-page.tsx",
- "utf8",
-);
-
-describe("built-in Autopilot templates", () => {
- it("queries only backlog issues in the bug triage template", () => {
- const prompt = pageSource.match(/id: "bug_triage",\s*prompt: `([^`]*)`/s)?.[1];
-
- expect(prompt).toBeDefined();
- expect(prompt?.split("\n", 1)[0]?.trimEnd()).toBe(
- "1. List all backlog issues that have not been prioritized",
- );
- expect(prompt).not.toContain('status "triage"');
- });
-});
diff --git a/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsx b/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsx
index a87961296c..f0f6d302fc 100644
--- a/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsx
+++ b/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsx
@@ -190,18 +190,6 @@ async function editCronText(expr: string) {
}
describe("ScheduleEditor", () => {
- // Parsing/serialization, descriptions, state transitions, and rejection
- // classification are canonical in the sibling .test.ts suites. This file
- // only keeps DOM wiring, accessibility, and integration-specific behavior.
- it("renders the three form blocks and the cron readback", () => {
- renderEditor(cron("0 9-21 * * *"));
- expect(screen.getByText("Time")).toBeInTheDocument();
- expect(screen.getByText("Days")).toBeInTheDocument();
- expect(screen.getByText("Timezone")).toBeInTheDocument();
- // The cron expression lives in the result panel below the form, shown as a
- // click-to-edit readback rather than a labelled field.
- expect(screen.getByRole("button", { name: /click to edit/ })).toBeInTheDocument();
- });
it("never fires onChange on mount (untouched save sends no update)", async () => {
const onChange = vi.fn();
@@ -522,35 +510,6 @@ describe("ScheduleEditor", () => {
expect(cronOut()).toBe("0 9-9 * * *");
});
- it("draws the interval and its unit in one box, lit by whichever holds focus", async () => {
- renderEditor(cron("0 */3 * * *"));
- const step = screen.getByLabelText("Interval");
- const unit = screen.getByLabelText("Interval unit");
- // "Every 3 hours" is one setting: the step and the unit share a box, rather
- // than sitting in two that happen to be next to each other.
- const box = step.closest("[data-slot=input-group]");
- expect(box).not.toBeNull();
- expect(box).toContainElement(unit);
- // The box lights its border from the control inside it that has focus, and it
- // knows them by this slot. A trigger that kept its own would leave the box
- // dark while the select it holds is the very thing focused.
- expect(step).toHaveAttribute("data-slot", "input-group-control");
- expect(unit).toHaveAttribute("data-slot", "input-group-control");
- });
-
- it("draws the window's two ends in one box", async () => {
- renderEditor(cron("0 9-21/3 * * *"));
- const start = screen.getByLabelText("Window start hour");
- // A window is one value with two ends, so it reads as one control rather than
- // two fields that happen to sit next to each other.
- const box = start.closest("[data-slot=input-group]");
- expect(box).not.toBeNull();
- expect(box).toContainElement(screen.getByLabelText("Window end hour"));
- // The segments, not their wrapper, are what the box lights its border from:
- // they are what gets focused.
- expect(start).toHaveAttribute("data-slot", "input-group-control");
- });
-
// The window is a dimension of the schedule, not a mode of the editor: it is on
// screen for every interval, and narrowing it is one edit — not a mode switch
// followed by one.
diff --git a/packages/views/autopilots/components/webhook-url-field.test.tsx b/packages/views/autopilots/components/webhook-url-field.test.tsx
index 43d757934c..ecdd64b5e7 100644
--- a/packages/views/autopilots/components/webhook-url-field.test.tsx
+++ b/packages/views/autopilots/components/webhook-url-field.test.tsx
@@ -64,11 +64,4 @@ describe("WebhookUrlField", () => {
fireEvent.click(screen.getByRole("button", { name: "Webhook URL hidden — click to show" }));
expect(container.textContent).toContain(rotated);
});
-
- it("renders trailing actions alongside the field", () => {
- renderWithI18n(
- <WebhookUrlField url={URL} actions={<button type="button">Rotate</button>} />,
- );
- expect(screen.getByRole("button", { name: "Rotate" })).toBeInTheDocument();
- });
});
diff --git a/packages/views/chat/components/chat-column.test.tsx b/packages/views/chat/components/chat-column.test.tsx
index 1766c7a9f9..e21c02adf5 100644
--- a/packages/views/chat/components/chat-column.test.tsx
+++ b/packages/views/chat/components/chat-column.test.tsx
@@ -37,30 +37,6 @@ function root(container: HTMLElement): HTMLElement {
}
describe("chat column geometry", () => {
- it("keeps the gutter a container query, not a viewport one", () => {
- // The chat body renders in a resizable split pane, a 360px floating window,
- // and the agent builder — all independent widths inside one browser window,
- // so a `sm:`/`lg:` variant would widen the floating window's gutter just
- // because the page behind it is wide.
- for (const cls of GUTTER_CLASSES) {
- if (cls.includes(":")) expect(cls).toMatch(/^@/);
- }
- // Base gutter with no variant, so a host that forgets `@container` degrades
- // to the old flat spacing instead of losing its padding entirely.
- expect(GUTTER_CLASSES).toContain("px-5");
- });
-
- it("puts the gutter OUTSIDE the width cap, never on one element", () => {
- // This is the invariant that broke: a single element carrying both means
- // the padding eats into the cap, and that layer ends up narrower than its
- // siblings once the surface is wider than the cap.
- for (const cls of GUTTER_CLASSES) {
- expect(COLUMN_CLASSES).not.toContain(cls);
- }
- expect(COLUMN_CLASSES).toContain("max-w-4xl");
- expect(GUTTER_CLASSES.some((c) => c.includes("max-w"))).toBe(false);
- });
-
it.each([
["no-agent banner", <NoAgentBanner key="n" />],
["archived-agent banner", <ArchivedAgentBanner key="a" agentName="Lambda" />],
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 1250c24294..2f0b1e0b45 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -709,21 +709,6 @@ describe("ChatInput project context", () => {
expect(screen.queryByRole("button", { name: "Queue message" })).not.toBeInTheDocument();
});
- it("keeps the composer chrome independent of the queue", () => {
- // The follow-up queue tucks its bottom edge under the composer, which
- // therefore ALWAYS paints on top (static z-10) — but the queue's presence
- // must never restyle the input surface itself.
- const { container } = renderInput();
- const surface = container.querySelector('[data-slot="chat-input-surface"]');
-
- expect(container.firstElementChild).toHaveClass("relative", "z-10");
- expect(surface).toHaveClass("rounded-lg");
- expect(surface).not.toHaveClass(
- "rounded-4xl",
- "shadow-[var(--menu-shadow)]",
- );
- });
-
it("locks the project control while a send is in flight so a mid-send switch cannot retarget the session", async () => {
// A brand-new chat creates its session row lazily during send, bound to
// the project selected at click time. If the user could switch project
diff --git a/packages/views/chat/components/use-chat-controller.test.ts b/packages/views/chat/components/use-chat-controller.test.ts
index 7ec97bafd9..d2534e7f17 100644
--- a/packages/views/chat/components/use-chat-controller.test.ts
+++ b/packages/views/chat/components/use-chat-controller.test.ts
@@ -143,11 +143,8 @@ describe("isStillOnComposeTarget", () => {
});
it("is true for a new chat the user is still sitting in", () => {
- // Both null: ensureSession creates the row but does not publish it as
- // active, so a user who stayed put is still looking at the new-chat box.
expect(isStillOnComposeTarget(null, null)).toBe(true);
});
-
it("is false once the user opens a different session mid-send", () => {
expect(isStillOnComposeTarget("session-2", sid)).toBe(false);
});
diff --git a/packages/views/common/expandable-description.test.tsx b/packages/views/common/expandable-description.test.tsx
index 171a2c1c7a..56ae51ac7f 100644
--- a/packages/views/common/expandable-description.test.tsx
+++ b/packages/views/common/expandable-description.test.tsx
@@ -54,17 +54,4 @@ describe("ExpandableDescription", () => {
await userEvent.click(screen.getByRole("button"));
expect(text).toHaveClass("line-clamp-2");
});
-
- it("keeps the toggle quiet rather than styling it as a primary action", async () => {
- stageOverflow(120, 48);
- await renderWithI18n(
- <ExpandableDescription>A description that runs on</ExpandableDescription>,
- );
-
- // Brand is for primary actions and live state. On a detail page that is
- // Save and Add-to-agent, not a text expander.
- const toggle = screen.getByRole("button");
- expect(toggle.className).toContain("text-muted-foreground");
- expect(toggle.className).not.toContain("brand");
- });
});
diff --git a/packages/views/common/row-actions-menu.test.tsx b/packages/views/common/row-actions-menu.test.tsx
index 1ec59c5884..bac9bfe423 100644
--- a/packages/views/common/row-actions-menu.test.tsx
+++ b/packages/views/common/row-actions-menu.test.tsx
@@ -47,23 +47,6 @@ describe("RowActionsMenu", () => {
expect(onRowClick).not.toHaveBeenCalled();
});
- it("hides only where the pointer can hover, never by viewport width", () => {
- // A width breakpoint would strand every wide touch surface — a phone in
- // landscape clears `md` while still having no hover, so it would lose this
- // menu and get hover controls it cannot trigger.
- render(
- <RowActionsMenu
- label="Chat actions"
- groups={[[{ key: "archive", icon: null, label: "Archive", onSelect: vi.fn() }]]}
- />,
- );
-
- const trigger = screen.getByRole("button", { name: "Chat actions" });
-
- expect(trigger.className).toContain("[@media(hover:hover)]:hidden");
- expect(trigger.className).not.toMatch(/(^|\s)(sm|md|lg|xl|2xl):hidden/);
- });
-
it("renders nothing when every group is empty", () => {
// A running chat with no pending task has no action to offer; an empty
// trigger would be a dead control.
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index 1763c0688a..149512b4a3 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -1,6 +1,5 @@
// @vitest-environment jsdom
-import { readFileSync } from "node:fs";
import { act, cleanup, fireEvent, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -581,25 +580,6 @@ describe("AgentTranscriptDialog", () => {
expect(container.querySelector(".hljs-keyword")?.textContent).toBe("let");
});
- it("carries the scope class the hljs palette is defined under", () => {
- // The palette lives in editor/styles/code.css, scoped to the editor surface
- // and this class. Without it the spans render but stay uncoloured.
- const { container } = renderDialog([
- {
- seq: 1,
- type: "tool_use",
- tool: "Edit",
- input: { file_path: "/repo/src/lib.rs", old_string: "let a = 1;", new_string: "let b = 2;" },
- },
- ]);
-
- fireEvent.click(screen.getByRole("button", { name: /Edit/ }));
-
- expect(container.querySelector("pre")?.className).toContain("transcript-code");
- const css = readFileSync("editor/styles/code.css", "utf8");
- expect(css).toContain(".transcript-code");
- });
-
it("leaves an unknown extension unhighlighted rather than guessing", () => {
const { container } = renderDialog([
{
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index 99099d9d1d..51b5a8851d 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -939,42 +939,6 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
- it("gives the canvas a flex-column parent so it can claim the modal body height", () => {
- // jsdom has no layout, so this is asserted structurally: `.zoom-canvas`
- // sizes itself with `flex: 1 1 auto` and positions its content
- // absolutely. In a plain block parent it collapses to zero height and the
- // image disappears entirely.
- stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
-
- const body = zoomCanvas().parentElement!;
- expect(body.className).toContain("flex-col");
- expect(body.className).toContain("flex-1");
- expect(body.className).toContain("overflow-hidden");
- });
-
- it("keeps the scrolling block body for non-image kinds", () => {
- render(
- <AttachmentPreviewModal
- source={{
- kind: "full",
- attachment: makeAttachment({
- filename: "notes.md",
- content_type: "text/markdown",
- }),
- }}
- open
- onClose={() => {}}
- />,
- );
-
- // A flex column here would let a tall markdown preview shrink to fit
- // instead of scrolling.
- const body = document.querySelector(".min-h-0.flex-1")!;
- expect(body.className).toContain("overflow-auto");
- expect(body.className).not.toContain("flex-col");
- });
-
it("shows no zoom controls for non-image kinds", () => {
render(
<AttachmentPreviewModal
diff --git a/packages/views/editor/code-block-static.test.tsx b/packages/views/editor/code-block-static.test.tsx
index 9f5caf16ed..8335f79f03 100644
--- a/packages/views/editor/code-block-static.test.tsx
+++ b/packages/views/editor/code-block-static.test.tsx
@@ -1,5 +1,4 @@
import { render } from "@testing-library/react";
-import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CodeBlockStatic } from "./code-block-static";
@@ -25,11 +24,4 @@ describe("CodeBlockStatic", () => {
expect(code?.textContent).toBe("const answer = 42;");
expect(code?.querySelector("span")).toBeNull();
});
-
- it("keeps standalone static code blocks under the block-code CSS selectors", () => {
- const codeCss = readFileSync("editor/styles/code.css", "utf8");
-
- expect(codeCss).toContain("pre.rich-text-editor");
- expect(codeCss).toContain("pre.rich-text-editor code");
- });
});
diff --git a/packages/views/editor/mermaid-diagram.test.tsx b/packages/views/editor/mermaid-diagram.test.tsx
index 21342123d0..ea3c4db632 100644
--- a/packages/views/editor/mermaid-diagram.test.tsx
+++ b/packages/views/editor/mermaid-diagram.test.tsx
@@ -1,6 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { readFileSync } from "node:fs";
vi.mock("../i18n", async () => {
const editor = (await import("../locales/en/editor.json")).default;
@@ -198,36 +197,6 @@ describe("MermaidDiagram theme changes", () => {
});
});
-// Verified in Chromium: dragging a diagram starts a native text selection that
-// paints the whole iframe box with the selection highlight (it is a replaced
-// element) and runs on into the surrounding comment text. Asserted against the
-// stylesheet because jsdom has no layout and cannot reproduce a real selection.
-// Deliberately NOT solved by preventDefault-ing pointerdown: that also drops
-// the default focus, which silently kills the viewer's keyboard controls.
-describe("Mermaid selection suppression", () => {
- function blockFor(css: string, selector: string): string {
- const start = css.indexOf(selector);
- expect(start, `${selector} missing from stylesheet`).toBeGreaterThan(-1);
- return css.slice(start, css.indexOf("}", start));
- }
-
- it("stops a drag on the inline diagram from selecting text", () => {
- const mermaidCss = readFileSync("editor/styles/mermaid.css", "utf8");
-
- expect(blockFor(mermaidCss, ".mermaid-diagram-scroll {")).toContain(
- "user-select: none",
- );
- });
-
- it("stops a pan that leaves the viewer canvas from selecting text", () => {
- // The canvas moved to the shared stylesheet when the image preview started
- // using it; the rule still has to be there.
- const zoomCss = readFileSync("editor/styles/zoom-canvas.css", "utf8");
-
- expect(blockFor(zoomCss, ".zoom-canvas {")).toContain("user-select: none");
- });
-});
-
describe("MermaidDiagram rendering config", () => {
it("renders labels as SVG text, without which PNG export silently produces nothing", async () => {
render(<MermaidDiagram chart={CHART} />);
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 43a4ca68c2..ca749fc75d 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, waitFor } from "@testing-library/react";
import type { ReactElement } from "react";
-import { readFileSync } from "node:fs";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const { getAttachmentTextContentMock, resolveIssueIdentifierMock } = vi.hoisted(
@@ -98,20 +97,6 @@ afterEach(() => {
vi.restoreAllMocks();
});
-describe("ReadonlyContent memoization", () => {
- // Long-timeline issues (Inbox + IssueDetail with thousands of comments)
- // freeze the tab when each comment re-runs the full react-markdown pipeline
- // on every parent re-render. Wrapping the component in React.memo is the
- // mitigation; this test guards against a future revert that would silently
- // reintroduce the perf regression.
- it("is wrapped in React.memo", () => {
- const memoTypeSymbol = Symbol.for("react.memo");
- expect((ReadonlyContent as unknown as { $$typeof: symbol }).$$typeof).toBe(
- memoTypeSymbol,
- );
- });
-});
-
describe("ReadonlyContent math rendering", () => {
it("renders inline and block LaTeX with KaTeX markup", () => {
const { container } = render(
@@ -403,16 +388,6 @@ describe("ReadonlyContent code styling", () => {
expect(writeText).toHaveBeenCalledWith(source);
});
});
-
- it("keeps editor code literal by disabling font ligatures", () => {
- const codeCss = readFileSync("editor/styles/code.css", "utf8");
-
- expect(codeCss).toContain(".rich-text-editor code");
- expect(codeCss).toContain(".rich-text-editor pre");
- expect(codeCss).toContain(".rich-text-editor pre code");
- expect(codeCss).toContain("font-variant-ligatures: none;");
- expect(codeCss).toContain('font-feature-settings: "liga" 0;');
- });
});
describe("ReadonlyContent Mermaid rendering", () => {
diff --git a/packages/views/editor/utils/hash-string.test.ts b/packages/views/editor/utils/hash-string.test.ts
index 704f35ad8d..4d13952a57 100644
--- a/packages/views/editor/utils/hash-string.test.ts
+++ b/packages/views/editor/utils/hash-string.test.ts
@@ -3,10 +3,6 @@ import { describe, expect, it } from "vitest";
import { hashString } from "./hash-string";
describe("hashString", () => {
- it("returns a stable base36 digest for identical input", () => {
- expect(hashString("hello world")).toBe(hashString("hello world"));
- });
-
it("differs for different inputs (collision-resistant enough for contentKey)", () => {
expect(hashString("<p>a</p>")).not.toBe(hashString("<p>b</p>"));
});
diff --git a/packages/views/editor/utils/iframe-fragment-nav.test.ts b/packages/views/editor/utils/iframe-fragment-nav.test.ts
index 2fc25dfbc3..43e6dbd440 100644
--- a/packages/views/editor/utils/iframe-fragment-nav.test.ts
+++ b/packages/views/editor/utils/iframe-fragment-nav.test.ts
@@ -1,28 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- __FRAGMENT_NAV_SHIM__,
- withFragmentNavShim,
-} from "./iframe-fragment-nav";
-
-describe("withFragmentNavShim", () => {
- it("appends the shim verbatim at the end of the original HTML", () => {
- const html = "<h1 id='a'>A</h1><a href='#a'>jump</a>";
- const out = withFragmentNavShim(html);
- expect(out.startsWith(html)).toBe(true);
- expect(out.endsWith(__FRAGMENT_NAV_SHIM__)).toBe(true);
- expect(out).toBe(html + __FRAGMENT_NAV_SHIM__);
- });
-
- it("does not mutate the input string", () => {
- const html = "<p>hi</p>";
- withFragmentNavShim(html);
- expect(html).toBe("<p>hi</p>");
- });
-
- it("handles empty input", () => {
- expect(withFragmentNavShim("")).toBe(__FRAGMENT_NAV_SHIM__);
- });
-});
+import { __FRAGMENT_NAV_SHIM__ } from "./iframe-fragment-nav";
// The shim itself ships as a <script> string injected into a srcdoc iframe.
// To exercise its runtime behavior in unit tests, evaluate the inner script
diff --git a/packages/views/editor/utils/parse-markdown-chunked.test.ts b/packages/views/editor/utils/parse-markdown-chunked.test.ts
index ff8f51af61..bc56aa41fa 100644
--- a/packages/views/editor/utils/parse-markdown-chunked.test.ts
+++ b/packages/views/editor/utils/parse-markdown-chunked.test.ts
@@ -1,15 +1,8 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
-import {
- MARKDOWN_CHUNK_THRESHOLD,
- parseMarkdownChunked,
-} from "./parse-markdown-chunked";
+import { parseMarkdownChunked } from "./parse-markdown-chunked";
describe("parseMarkdownChunked", () => {
- it("routes a typical 22k issue through the chunked parse path", () => {
- expect(MARKDOWN_CHUNK_THRESHOLD).toBeLessThan(22_000);
- });
-
it("keeps ordinary paragraph chunks small enough to avoid quadratic scans", () => {
const markdown = Array.from(
{ length: 240 },
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 5f835b5cc9..bd9f6054a3 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -389,17 +389,6 @@ describe("comment composers", () => {
expect(shell.className).not.toContain("h-[60vh]");
});
- it("lets default-size replies grow without a height cap", () => {
- const { container } = renderReplyInput({ size: "default" });
-
- activateComposer("reply-composer-shell");
- expect(screen.getByPlaceholderText("Leave a reply...")).toBeInTheDocument();
- expect(container.querySelectorAll("button")).toHaveLength(2);
-
- const shell = screen.getByTestId("drop-zone");
- expect(shell.className).not.toMatch(/max-h-/);
- });
-
it("keeps main comment submission wired after removing expand", async () => {
const { container, onSubmit } = renderCommentInput();
diff --git a/packages/views/issues/components/data-table-sticky.test.tsx b/packages/views/issues/components/data-table-sticky.test.tsx
index 1a5a56a18a..8dd5a613bd 100644
--- a/packages/views/issues/components/data-table-sticky.test.tsx
+++ b/packages/views/issues/components/data-table-sticky.test.tsx
@@ -93,20 +93,6 @@ describe("DataTable pinned columns", () => {
expect(measured.filter(Boolean).length).toBe(2);
});
- it("keeps the header strip off the compositor's blur path", () => {
- render(<PinnedTable />);
-
- const strip = document.querySelector("thead")!;
- // A backdrop-filter on a sticky element with content scrolling beneath it
- // recomputes its backdrop every frame while virtualisation churns the rows
- // under it, and the strip flickers black (electron#12906). The mix resolves
- // to the same colour bg-muted/30 composited to.
- expect(strip).toHaveClass(
- "bg-[color-mix(in_oklab,var(--muted)_30%,var(--background))]",
- );
- expect(strip).not.toHaveClass("backdrop-blur");
- });
-
it("uses opaque backgrounds so scrolled columns cannot show through", () => {
render(<PinnedTable />);
diff --git a/packages/views/issues/components/execution-log-section.test.tsx b/packages/views/issues/components/execution-log-section.test.tsx
index 7d6132a9a1..539f2c6e40 100644
--- a/packages/views/issues/components/execution-log-section.test.tsx
+++ b/packages/views/issues/components/execution-log-section.test.tsx
@@ -88,23 +88,6 @@ describe("ActiveTaskRow", () => {
expect(screen.getByText("View transcript")).toBeInTheDocument();
expect(mockState.taskMessagesOptions).not.toHaveBeenCalled();
});
-
- it("does not make transcript actions depend on hover-only rendering", () => {
- renderWithI18n(<ActiveTaskRow task={makeTask()} issueId="issue-1" />);
-
- const transcriptButton = screen.getByRole("button", { name: "View transcript" });
- const status = screen.getByText("5m 04s");
-
- expect(status.parentElement?.className).toContain("flex h-7");
- expect(status.parentElement?.className).toContain(
- "[@media(hover:hover)]:group-hover/execution-log-row:hidden",
- );
- expect(transcriptButton.parentElement?.className).toContain("flex h-7");
- expect(transcriptButton.parentElement?.className).toContain("[@media(hover:hover)]:hidden");
- expect(transcriptButton.parentElement?.className).toContain(
- "[@media(hover:hover)]:group-hover/execution-log-row:flex",
- );
- });
});
describe("TaskCommentCoverage", () => {
@@ -348,17 +331,6 @@ describe("execution log header geometry", () => {
usage: [usageSlice()],
});
- it("keeps the section label on one line", () => {
- renderSection([completed]);
-
- const label = screen.getByText("Execution log");
- // The label is the only header item allowed to shrink, so it is the one
- // that must carry nowrap + ellipsis. A heading that reflows mid-phrase
- // reads as broken; an ellipsis reads as a narrow column.
- expect(label.className).toContain("truncate");
- expect(label.closest("button")?.className).toContain("whitespace-nowrap");
- });
-
it("tiers on the sidebar's width, not the viewport's", () => {
const { container } = renderSection([completed]);
diff --git a/packages/views/issues/components/issue-chip.test.tsx b/packages/views/issues/components/issue-chip.test.tsx
index 635840e0f9..797d816a9f 100644
--- a/packages/views/issues/components/issue-chip.test.tsx
+++ b/packages/views/issues/components/issue-chip.test.tsx
@@ -75,19 +75,6 @@ describe("IssueChip", () => {
});
});
- it("caps the chip against both its content and its container, and truncates the title", () => {
- render(<IssueChip issueId="issue-1" />);
-
- const chip = screen.getByText("MUL-3405").closest(".issue-mention");
- // 18rem bounds the chip against a long title so it cannot dominate a line
- // of prose (#6732); 100% keeps it inside a narrow parent such as a chat
- // bubble. ProjectChip carries the identical cap — see its own test.
- expect(chip).toHaveClass("min-w-0");
- expect(chip).toHaveClass("max-w-[min(18rem,100%)]");
- expect(screen.getByText("A very long issue title that should stay inside a narrow chat bubble"))
- .toHaveClass("min-w-0", "truncate");
- });
-
it("truncates unresolved fallback labels inside the chip width", () => {
render(
<IssueChip
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 294e31c4f1..1e4e4b24e8 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -806,16 +806,6 @@ describe("IssueDetail (shared)", () => {
);
});
- it("renders comment bodies without Base UI collapsible panels", async () => {
- const { container } = renderIssueDetail();
-
- await screen.findByText("Started working on this");
-
- expect(
- container.querySelector('[data-slot="collapsible-content"]'),
- ).toBeNull();
- });
-
it("renders issue title and description after loading", async () => {
renderIssueDetail();
@@ -1146,20 +1136,6 @@ describe("IssueDetail (shared)", () => {
expect(scrollIntoViewSpy).not.toHaveBeenCalled();
});
- it("reserves the chat launcher's corner at the end of the mobile scroll", async () => {
- mockViewport.isMobile = true;
-
- const { container } = renderIssueDetail();
-
- await waitFor(() => {
- expect(screen.getByText("Implement authentication")).toBeInTheDocument();
- });
-
- // Unpinned, the composer lands in that corner once the reader reaches the
- // bottom, so the column has to end above the launcher rather than under it.
- expect(container.querySelector(".max-md\\:pb-chat-launcher")).not.toBeNull();
- });
-
it("hides metadata content from the sidebar and shows a button when the bag has keys", async () => {
// Metadata is agent-facing; the sidebar only exposes a button that opens
// the raw JSON on demand. Keys are NOT rendered inline anywhere.
@@ -1223,18 +1199,6 @@ describe("IssueDetail (shared)", () => {
expect(screen.queryByRole("button", { name: /^Metadata\b/ })).not.toBeInTheDocument();
});
- it("renders Details section with Created by and dates", async () => {
- renderIssueDetail();
-
- await waitFor(() => {
- expect(screen.getByText("Details")).toBeInTheDocument();
- });
-
- expect(screen.getByText("Created by")).toBeInTheDocument();
- expect(screen.getByText("Created")).toBeInTheDocument();
- expect(screen.getByText("Updated")).toBeInTheDocument();
- });
-
// Details is creator + immutable timestamps, so it ranks below the
// execution log, which is what people actually open the sidebar for.
it("orders the Details section after the execution log", async () => {
@@ -1289,14 +1253,6 @@ describe("IssueDetail (shared)", () => {
});
});
- it("renders Activity section header", async () => {
- renderIssueDetail();
-
- await waitFor(() => {
- expect(screen.getAllByText("Activity").length).toBeGreaterThanOrEqual(1);
- });
- });
-
it("renders comments from timeline", async () => {
renderIssueDetail();
diff --git a/packages/views/issues/components/issue-hover-card.test.tsx b/packages/views/issues/components/issue-hover-card.test.tsx
index b9ba975576..001868ea31 100644
--- a/packages/views/issues/components/issue-hover-card.test.tsx
+++ b/packages/views/issues/components/issue-hover-card.test.tsx
@@ -364,17 +364,6 @@ describe("IssueHoverCard", () => {
expect(paragraphCount()).toBe(1);
});
- it("breaks a long unbroken title instead of overflowing the card", async () => {
- const title = "https://example.com/a/very/long/path/that/never/offers/a/break/opportunity";
- mockIssue({ ...BASE_ISSUE, title });
-
- await openCard();
-
- const titleEl = screen.getByText(title);
- expect(titleEl).toHaveClass("break-words");
- expect(titleEl).not.toHaveClass("truncate");
- });
-
it("keeps the skeleton while the detail query is pending", async () => {
mockQueries({ phase: "pending" });
const user = userEvent.setup();
diff --git a/packages/views/issues/components/issue-usage-dialog.test.tsx b/packages/views/issues/components/issue-usage-dialog.test.tsx
index 8976a89c3a..337b6bb1f1 100644
--- a/packages/views/issues/components/issue-usage-dialog.test.tsx
+++ b/packages/views/issues/components/issue-usage-dialog.test.tsx
@@ -105,18 +105,4 @@ describe("IssueUsageDialog", () => {
expect(screen.getByText("Completed")).toBeInTheDocument();
expect(screen.getByText("Failed")).toBeInTheDocument();
});
-
- it("lets the run table scroll rather than widening the dialog", () => {
- // jsdom has no layout engine, so the overflow itself is verified in a
- // browser. What is pinned here is the contract that produced the bug: the
- // scroll container must be able to shrink below its content. Drop
- // `min-w-0` and the box grows to the table's min-content width instead of
- // clipping, which is what pushed the table outside the dialog.
- open([makeTask({ usage: [usage()] })]);
-
- const table = screen.getByRole("table");
- const scroller = table.parentElement;
- expect(scroller?.className).toContain("overflow-auto");
- expect(scroller?.className).toContain("min-w-0");
- });
});
diff --git a/packages/views/issues/components/pull-request-list.test.tsx b/packages/views/issues/components/pull-request-list.test.tsx
index 1cc3853cfc..d432e5ca77 100644
--- a/packages/views/issues/components/pull-request-list.test.tsx
+++ b/packages/views/issues/components/pull-request-list.test.tsx
@@ -78,14 +78,6 @@ async function waitForRender() {
}
describe("PullRequestList sidebar rows", () => {
- it("uses the sidebar list-row surface instead of a card surface", async () => {
- mockPRs = [makePR({ title: "Visual row" })];
- renderList();
- await waitForRender();
- const row = screen.getByTestId("pull-request-row");
- expect(row).toHaveClass("rounded-md", "-mx-2", "hover:bg-accent/50");
- expect(row).not.toHaveClass("rounded-lg", "border", "bg-card");
- });
// --- CI status element ---------------------------------------------------
diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsx
index b794efc3e7..d0ad51f4b3 100644
--- a/packages/views/issues/components/swimlane-view.test.tsx
+++ b/packages/views/issues/components/swimlane-view.test.tsx
@@ -572,26 +572,6 @@ describe("SwimLaneView", () => {
expect(mockOpenModal).not.toHaveBeenCalled();
});
- it("routes add button through the surface create callback when provided", () => {
- const onCreateIssue = vi.fn();
- renderWithI18n(
- <SwimLaneView
- issues={mockIssues}
- onMoveIssue={vi.fn()}
- projectId="proj-42"
- onCreateIssue={onCreateIssue}
- />,
- );
-
- const addButtons = screen.getAllByRole("button", { name: /add issue/i });
- fireEvent.click(addButtons[0]!);
-
- expect(onCreateIssue).toHaveBeenCalledWith(
- expect.objectContaining({ project_id: "proj-42" }),
- );
- expect(mockOpenModal).not.toHaveBeenCalled();
- });
-
// A child whose parent isn't in the loaded set — lands in "Other parents".
const orphanChild: Issue = {
id: "lonely-child",
@@ -896,29 +876,6 @@ describe("SwimLaneView", () => {
);
});
- it("passes a settle callback that releases the lock without error", () => {
- const mockOnMoveIssue = vi.fn();
- renderWithI18n(
- <SwimLaneView issues={mockIssues} onMoveIssue={mockOnMoveIssue} />,
- );
-
- const targetCellId = "swim:parent:none:in_progress";
- act(() => {
- lastOnDragOver({ active: { id: "orphan-1" }, over: { id: targetCellId } });
- });
- act(() => {
- lastOnDragEnd({ active: { id: "orphan-1" }, over: { id: targetCellId } });
- });
-
- // The move carries a settle callback (held from drop until the mutation
- // settles); invoking it releases the lock and re-syncs from the cache.
- const onSettled = mockOnMoveIssue.mock.calls[0]?.[2] as
- | (() => void)
- | undefined;
- expect(typeof onSettled).toBe("function");
- expect(() => act(() => onSettled?.())).not.toThrow();
- });
-
it("does not call onMoveIssue when drop target equals source cell (no-op)", () => {
const mockOnMoveIssue = vi.fn();
renderWithI18n(
diff --git a/packages/views/issues/components/thread-nav-panel.test.tsx b/packages/views/issues/components/thread-nav-panel.test.tsx
index b2e97ecb34..0d08148e5d 100644
--- a/packages/views/issues/components/thread-nav-panel.test.tsx
+++ b/packages/views/issues/components/thread-nav-panel.test.tsx
@@ -580,19 +580,6 @@ describe("ThreadNavPanel", () => {
expect(container.querySelector(".bg-brand")).toBeNull();
});
- it("renders the keyboard hints as real keycaps, not glyphs in a string", () => {
- renderWithI18n(<Harness />);
- fireEvent.click(screen.getByRole("button", { name: /Comment threads/ }));
- // Scoped to the footer: the trigger's tooltip renders keycaps too.
- const footer = screen.getByText("select").closest("div")!.parentElement!;
- const keycaps = footer.querySelectorAll('[data-slot="shortcut-keycaps"]');
- // Up, Down, Enter, Escape.
- expect(keycaps).toHaveLength(4);
- expect(screen.getByText("select")).toBeTruthy();
- expect(screen.getByText("jump")).toBeTruthy();
- expect(screen.getByText("close")).toBeTruthy();
- });
-
// Enter used to be handled for every keydown bubbling up to the popup, and
// preventDefault on a button's keydown cancels the click the browser is about
// to synthesize — so Enter on a filter pill jumped away instead of filtering.
diff --git a/packages/views/issues/components/use-board-drag-pan.test.tsx b/packages/views/issues/components/use-board-drag-pan.test.tsx
index 938ba8d3be..9d1db48936 100644
--- a/packages/views/issues/components/use-board-drag-pan.test.tsx
+++ b/packages/views/issues/components/use-board-drag-pan.test.tsx
@@ -249,11 +249,6 @@ describe("useBoardDragPan", () => {
expect(fireSelectStart()).toBe(true); // released after gesture end
});
- it("does not set touch-action because touch/pen stay browser-owned", () => {
- const { getByTestId } = render(<Harness />);
- expect(getByTestId("scroller").style.touchAction).toBe("");
- });
-
it("ignores touch and pen pointerdown entirely (mouse-only scope)", () => {
const { getByTestId } = render(<Harness />);
const el = getByTestId("scroller");
diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsx
index 46966c362b..73be2991e3 100644
--- a/packages/views/issues/hooks/use-issue-timeline.test.tsx
+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx
@@ -151,16 +151,6 @@ describe("useIssueTimeline", () => {
expect(result.current.submitComment).toBe(first.submitComment);
});
- it("returns the timeline as a flat array directly from the query cache", () => {
- queryState.data = [
- { type: "comment", id: "c1", actor_type: "member", actor_id: "u", created_at: "2026-05-06T01:00:00Z" },
- { type: "comment", id: "c2", actor_type: "member", actor_id: "u", created_at: "2026-05-06T02:00:00Z" },
- { type: "comment", id: "c3", actor_type: "member", actor_id: "u", created_at: "2026-05-06T03:00:00Z" },
- ];
- const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));
- expect(result.current.timeline.map((e) => e.id)).toEqual(["c1", "c2", "c3"]);
- });
-
it("passes suppressed agent ids through editComment", async () => {
const { result } = renderHook(() => useIssueTimeline("issue-1", "user-1"));
diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
index 070b9e4ea3..b5ef1d98b7 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -536,33 +536,6 @@ describe("useIssueSurfaceController", () => {
expect(onSettled).toHaveBeenCalled();
});
- it("exposes surface actions and surface-local selection", async () => {
- const { result } = renderHook(
- () =>
- useIssueSurfaceController({
- scope: { type: "project", projectId: "p1" },
- modes: ["board", "list", "swimlane", "gantt"],
- }),
- { wrapper: makeWrapper(qc, "project:p1") },
- );
-
- act(() => {
- result.current.selection.select(["issue-1"]);
- });
- expect(result.current.selection.selectedIds).toEqual(new Set(["issue-1"]));
-
- await act(async () => {
- await result.current.actions.batchUpdate(["issue-1"], { status: "done" });
- await result.current.actions.batchDelete(["issue-2"]);
- });
-
- expect(batchUpdateMutateAsync).toHaveBeenCalledWith({
- ids: ["issue-1"],
- updates: { status: "done" },
- });
- expect(batchDeleteMutateAsync).toHaveBeenCalledWith(["issue-2"]);
- });
-
it("never reports isEmpty in gantt mode — an empty scheduled subset cannot prove the window is empty", async () => {
// The gantt query returns only issues with a start/due date. A project
// full of unscheduled issues comes back [] here, and the surface used to
diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.ts
index a6383d82ad..eea36d226e 100644
--- a/packages/views/issues/utils/filter.test.ts
+++ b/packages/views/issues/utils/filter.test.ts
@@ -104,11 +104,6 @@ describe("filterIssues", () => {
expect(result).toEqual([]);
});
- it("hides assigned issues when only 'No assignee' is selected", () => {
- const result = filterIssues(issues, { ...NO_FILTER, includeNoAssignee: true });
- expect(result.every((i) => !i.assignee_id)).toBe(true);
- });
-
// --- Creator ---
it("filters by creator", () => {
const result = filterIssues(issues, {
@@ -169,11 +164,6 @@ describe("filterIssues", () => {
expect(result.map((i) => i.id)).toEqual(["2", "3"]);
});
- it("hides project issues when only 'No project' is selected", () => {
- const result = filterIssues(issues, { ...NO_FILTER, includeNoProject: true });
- expect(result.every((i) => !i.project_id)).toBe(true);
- });
-
it("applies status + project filters together", () => {
const result = filterIssues(issues, {
...NO_FILTER,
diff --git a/packages/views/layout/help-launcher.test.tsx b/packages/views/layout/help-launcher.test.tsx
index b312576d03..966f33489b 100644
--- a/packages/views/layout/help-launcher.test.tsx
+++ b/packages/views/layout/help-launcher.test.tsx
@@ -93,16 +93,6 @@ describe("HelpLauncher", () => {
expect(screen.getByText("Server version 1.2.3")).toBeInTheDocument();
});
- // MUL-4819: the version row's DropdownMenuLabel must sit inside a
- // DropdownMenuGroup. Rendering it bare made Base UI's Menu.GroupLabel throw
- // on open, unmounting the whole app (black screen, no error) because no error
- // boundary sits above the sidebar. Rendering here must not throw.
- it("renders the version row without a missing-group crash", () => {
- configStore.getState().setServerVersion("9.9.9");
- expect(() => render(<HelpLauncher />)).not.toThrow();
- expect(screen.getByText("Server version 9.9.9")).toBeInTheDocument();
- });
-
// MUL-6462: after web onboarding the desktop download CTA was unreachable —
// no entry anywhere in the app, so users had to remember the URL or detour
// through the marketing site. The Help menu is the persistent home for it.
diff --git a/packages/views/layout/page-header.test.tsx b/packages/views/layout/page-header.test.tsx
index 9ee696a287..023d4a6cdd 100644
--- a/packages/views/layout/page-header.test.tsx
+++ b/packages/views/layout/page-header.test.tsx
@@ -67,18 +67,6 @@ describe("PageHeader title alignment", () => {
});
describe("PageHeader base chrome", () => {
- it("supplies the trigger, gap and gutter without per-page classes", () => {
- const header = renderHeader(
- <PageHeader>
- <h1>Inbox</h1>
- </PageHeader>,
- );
-
- const trigger = header.querySelector("[data-slot='sidebar-trigger']")!;
- expect(trigger).toHaveClass("xl:hidden");
- expect(trigger.className).not.toMatch(/(^|\s)-?m[rsxe]?-/);
- expect(header).toHaveClass("gap-2", PAGE_GUTTER);
- });
it("does not let a call site override the shared gutter", () => {
const header = renderHeader(
@@ -124,22 +112,4 @@ describe("PageHeader base chrome", () => {
expect(container.querySelector("[data-slot='sidebar-trigger']")).toBeNull();
});
-
- // Collection and issues headers drifted apart when each declared its own
- // spacing; both must resolve to the base gap and gutter.
- it("resolves the same gutter and gap for collection and issues headers", () => {
- const collection = renderHeader(
- <CollectionPageHeader icon={Zap} title="Autopilot" count={2} />,
- );
- const issues = renderHeader(
- <PageHeader>
- <ListTodo className="h-4 w-4" />
- <h1>Issues</h1>
- </PageHeader>,
- );
-
- for (const header of [collection, issues]) {
- expect(header).toHaveClass("gap-2", PAGE_GUTTER);
- }
- });
});
diff --git a/packages/views/layout/route-icon-components.test.tsx b/packages/views/layout/route-icon-components.test.tsx
index 82323b08c4..cb306dd387 100644
--- a/packages/views/layout/route-icon-components.test.tsx
+++ b/packages/views/layout/route-icon-components.test.tsx
@@ -1,16 +1,7 @@
import { describe, it, expect } from "vitest";
-import { paths, WORKSPACE_PAGES, DEFAULT_ROUTE_ICON_NAME } from "@multica/core/paths";
+import { paths, DEFAULT_ROUTE_ICON_NAME } from "@multica/core/paths";
import { ROUTE_ICON_COMPONENTS, routeIconForPath } from "./route-icon-components";
-describe("ROUTE_ICON_COMPONENTS", () => {
- it("has a component for every page icon", () => {
- const missing = Object.values(WORKSPACE_PAGES)
- .map((page) => page.icon)
- .filter((name) => !ROUTE_ICON_COMPONENTS[name]);
- expect(missing).toEqual([]);
- });
-});
-
describe("routeIconForPath", () => {
// The invariant this whole contract exists for (MUL-4370): the sidebar and
// the desktop tab bar both resolve from a path, so the same route can never
diff --git a/packages/views/layout/sidebar-auto-collapse.test.tsx b/packages/views/layout/sidebar-auto-collapse.test.tsx
index d64b73d294..ee9fa73257 100644
--- a/packages/views/layout/sidebar-auto-collapse.test.tsx
+++ b/packages/views/layout/sidebar-auto-collapse.test.tsx
@@ -1,11 +1,7 @@
import { act, fireEvent, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import {
- Sidebar,
- SidebarProvider,
- useSidebar,
-} from "@multica/ui/components/ui/sidebar";
+import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
import { renderWithI18n } from "../test/i18n";
// A width-driven `matchMedia`: the provider watches the `lg`–`xl` band and
@@ -134,29 +130,6 @@ describe("sidebar auto-collapse between lg and xl", () => {
expect(state()).toBe("expanded");
});
- it("gates the in-flow sidebar on the same breakpoint the hook uses", () => {
- // `useIsCompact()` resolves after the first paint, so between the two
- // breakpoints the CSS gate alone decides that frame. While it said `md`
- // and the hook said `lg`, every load in 768–1023 painted a 256px sidebar
- // before collapsing it into a sheet. jsdom applies no stylesheet, so the
- // agreement is asserted on the class itself.
- const { container } = renderWithI18n(
- <SidebarProvider>
- <Sidebar />
- </SidebarProvider>,
- );
-
- const root = container.querySelector<HTMLElement>("[data-slot='sidebar']")!;
- const inner = container.querySelector<HTMLElement>(
- "[data-slot='sidebar-container']",
- )!;
-
- expect(root.className).toContain("lg:block");
- expect(root.className).not.toContain("md:block");
- expect(inner.className).toContain("lg:flex");
- expect(inner.className).not.toContain("md:flex");
- });
-
it("does not touch the collapsed state below the band", () => {
// Under 1024 the nav is a sheet, which has its own open state — the
// in-flow state must be left where the user last put it.
diff --git a/packages/views/layout/sidebar-wrapper-fill.test.tsx b/packages/views/layout/sidebar-wrapper-fill.test.tsx
deleted file mode 100644
index e670b18498..0000000000
--- a/packages/views/layout/sidebar-wrapper-fill.test.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- SIDEBAR_WRAPPER_FILL_CLASS,
- SidebarProvider,
-} from "@multica/ui/components/ui/sidebar";
-import { renderWithI18n } from "../test/i18n";
-
-// The wrapper's fill is conditional, and descendants that paint an opaque layer
-// over it have to match it exactly (the desktop tab flares do — #6874 shipped a
-// dark square under the active tab when they didn't). SIDEBAR_WRAPPER_FILL_CLASS
-// is the contract that keeps them in step. None of it is observable in jsdom, so
-// these assertions cover what a rename or a class-merge conflict would silently
-// break; the compiled selectors themselves are Tailwind's business.
-describe("sidebar wrapper fill contract", () => {
- const variable = /^bg-\((--[a-z-]+)\)$/.exec(SIDEBAR_WRAPPER_FILL_CLASS)?.[1];
-
- function wrapperOf(className?: string) {
- const { container } = renderWithI18n(<SidebarProvider className={className} />);
- return container.querySelector<HTMLElement>("[data-slot='sidebar-wrapper']")!;
- }
-
- it("publishes the variable that SIDEBAR_WRAPPER_FILL_CLASS reads", () => {
- expect(variable).toBeDefined();
- expect(wrapperOf().className).toContain(`${variable}:var(--sidebar)`);
- });
-
- // Paint and variable must carry the identical condition. If one branch grows a
- // condition the other lacks, the variable starts naming a color the wrapper is
- // not painted with, which is the original bug in a new place.
- it("gates the inset fill and the inset variable on the same condition", () => {
- const classes = wrapperOf().className.split(/\s+/);
- const insetBranch = classes.filter((c) => c.startsWith("has-data-[variant=inset]:"));
-
- expect(insetBranch).toContain("has-data-[variant=inset]:bg-sidebar");
- expect(insetBranch).toContain(`has-data-[variant=inset]:[${variable}:var(--sidebar)]`);
- });
-
- // tailwind-merge drops same-group utilities, and the consumer's non-inset pair
- // arrives through the same cn() call as the inset pair above. All four have to
- // survive: lose the variable and the flares fall back to transparent, lose the
- // background and the wrapper does.
- it("keeps a consumer's non-inset fill alongside the inset branch", () => {
- const classes = wrapperOf(
- `flex-1 bg-app-shell [${variable}:var(--app-shell)]`,
- ).className.split(/\s+/);
-
- expect(classes).toEqual(
- expect.arrayContaining([
- "bg-app-shell",
- `[${variable}:var(--app-shell)]`,
- "has-data-[variant=inset]:bg-sidebar",
- `has-data-[variant=inset]:[${variable}:var(--sidebar)]`,
- ]),
- );
- });
-});
diff --git a/packages/views/modals/create-issue-dialog.test.tsx b/packages/views/modals/create-issue-dialog.test.tsx
index 535d22e12d..ce43ae9e13 100644
--- a/packages/views/modals/create-issue-dialog.test.tsx
+++ b/packages/views/modals/create-issue-dialog.test.tsx
@@ -125,29 +125,6 @@ describe("CreateIssueDialog sizing", () => {
beforeEach(() => {
vi.clearAllMocks();
});
- // MUL-6236: every width the shell sets is `!important` so it can beat
- // DialogContent's own sizing — which also beat DialogContent's
- // `max-w-[calc(100%-2rem)]` gutter, so the card ran the full width of a
- // phone screen with no margin on either side.
- it("caps the agent dialog inside the viewport on phones", () => {
- render(<CreateIssueDialog onClose={vi.fn()} initialMode="agent" />);
-
- expect(contentClass()).toContain("!max-w-[calc(100vw-1.5rem)]");
- expect(contentClass()).toContain("sm:!max-w-xl");
- });
-
- it("keeps the ordinary agent dialog content-driven", () => {
- render(<CreateIssueDialog onClose={vi.fn()} initialMode="agent" />);
-
- expect(contentClass()).toContain("!max-h-[80dvh]");
- expect(contentClass()).not.toContain("!h-96");
- });
-
- it("hands manual mode its own sizing", () => {
- render(<CreateIssueDialog onClose={vi.fn()} initialMode="manual" />);
-
- expect(contentClass()).toBe("manual-dialog-class");
- });
it("leaves ordinary create outside the isolated source-context path", () => {
render(
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 55a5171e91..0bd886c2f7 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -610,7 +610,6 @@ vi.mock("sonner", () => ({
import {
CreateIssueModal,
ManualCreatePanel,
- manualDialogContentClass,
} from "./create-issue";
function renderModal(element: React.ReactElement) {
@@ -1830,35 +1829,11 @@ describe("CreateIssueModal", () => {
createButton.focus();
expect(createButton).toHaveFocus();
});
-
- it("carries its own disabled visuals, since the Button base only styles native disabled", () => {
- renderManual();
- const createButton = screen.getByRole("button", { name: "Create Issue" });
-
- // Without these the control reads as a live primary button while
- // aria-disabled. `pointer-events-none` is deliberately absent: it would
- // kill the tooltip hover and the click that focuses the title.
- expect(createButton.className).toContain("aria-disabled:opacity-50");
- expect(createButton.className).toContain("aria-disabled:cursor-not-allowed");
- expect(createButton.className).toContain("aria-disabled:active:translate-y-0");
- expect(createButton.className).not.toContain("aria-disabled:pointer-events-none");
- });
});
// MUL-6236 — the manual panel shares the agent panel's phone treatment; it
// is one tap away behind "Switch to Manual", so it hit the same bugs.
describe("phone layout", () => {
- it("caps the dialog inside the viewport on phones", () => {
- for (const isExpanded of [false, true]) {
- const className = manualDialogContentClass(isExpanded);
-
- // Without this the `!important` widths below also override
- // DialogContent's own `max-w-[calc(100%-2rem)]` and the card runs
- // edge to edge on a phone.
- expect(className).toContain("!max-w-[calc(100vw-1.5rem)]");
- expect(className).toContain(isExpanded ? "sm:!max-w-4xl" : "sm:!max-w-2xl");
- }
- });
it("keeps every footer control a direct child of the grid container", () => {
renderModal(<CreateIssueModal onClose={vi.fn()} />);
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index 0d4dd3f1d8..4cd4dc7d05 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -1205,14 +1205,5 @@ describe("AgentCreatePanel", () => {
expect(attach.parentElement?.parentElement).toBe(footer);
expect(attach).toHaveAttribute("data-size", "sm");
});
-
- it("hides the send keycaps below the sm breakpoint", () => {
- const keycaps = document.querySelector('[data-slot="shortcut-keycaps"]');
-
- // Present for pointer devices, display:none on a touch phone that has
- // no ⌘ key and the least room in the footer row.
- expect(keycaps).not.toBeNull();
- expect(keycaps?.className).toContain("max-sm:hidden");
- });
});
});
diff --git a/packages/views/modals/source-context-preview.test.tsx b/packages/views/modals/source-context-preview.test.tsx
index 9a191ff2af..7553fed924 100644
--- a/packages/views/modals/source-context-preview.test.tsx
+++ b/packages/views/modals/source-context-preview.test.tsx
@@ -6,52 +6,6 @@ import enIssues from "../locales/en/issues.json";
import { SourceContextPreviewCard } from "./source-context-preview";
describe("SourceContextPreviewCard", () => {
- it("emphasizes a comment's left quote border on hover", () => {
- render(
- <I18nProvider locale="en" resources={{ en: { issues: enIssues } }}>
- <SourceContextPreviewCard preview={{
- source_issue: {
- id: "issue-1", identifier: "MUL-1", number: 1, title: "Source",
- description: null, created_at: "now", updated_at: "now", revision: 1,
- attachments: [],
- },
- comment_thread: [{
- id: "comment-1", parent_id: null, type: "comment", content: "Quoted context",
- author: { type: "member", id: "user-1", name: "Alice" },
- created_at: "now", updated_at: "now", revision: 1, attachments: [],
- }],
- anchor_comment_id: "comment-1",
- capture_token: "sha256:token",
- limits: { comment_count: 1, text_bytes: 14, attachment_count: 0, attachment_bytes: 0 },
- }} />
- </I18nProvider>,
- );
-
- expect(screen.getByText(
- "Context from MUL-1 · issue description + 1 comment",
- )).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: /Context from MUL-1/ }));
- expect(screen.getByText("Alice").closest("li")).toHaveClass(
- "transition-colors",
- "duration-150",
- "hover:border-l-foreground/50",
- );
- expect(screen.getByText("Alice").parentElement).toHaveClass(
- "flex",
- "gap-2",
- "text-muted-foreground",
- );
- expect(screen.getByText("Quoted context").closest("div.mt-1\\.5")).toBeInTheDocument();
- expect(screen.getByText("Alice").closest("ol")?.parentElement).toHaveClass("space-y-8");
- expect(screen.getByText("Alice").closest('[data-slot="source-context-content"]')).toBeInTheDocument();
- expect(screen.getByText("Source comment")).toHaveClass(
- "rounded",
- "bg-info/10",
- "px-1.5",
- "py-0.5",
- "text-info",
- );
- });
it("pluralizes the preview comment count", () => {
render(
@@ -117,43 +71,6 @@ describe("SourceContextPreviewCard", () => {
expect(screen.queryByText("comment-attachment.txt")).not.toBeInTheDocument();
});
- it("stays visible when collapsed and scrolls internally when parent-constrained", () => {
- render(
- <I18nProvider locale="en" resources={{ en: { issues: enIssues } }}>
- <SourceContextPreviewCard
- constrainToParent
- preview={{
- source_issue: {
- id: "issue-1", identifier: "MUL-1", number: 1, title: "Source",
- description: null, created_at: "now", updated_at: "now", revision: 1,
- attachments: [],
- },
- comment_thread: [{
- id: "comment-1", parent_id: null, type: "comment", content: "Quoted context",
- author: { type: "member", id: "user-1", name: "Alice" },
- created_at: "now", updated_at: "now", revision: 1, attachments: [],
- }],
- anchor_comment_id: "comment-1",
- capture_token: "sha256:token",
- limits: { comment_count: 1, text_bytes: 14, attachment_count: 0, attachment_bytes: 0 },
- }}
- />
- </I18nProvider>,
- );
-
- const header = screen.getByRole("button", { name: /Context from MUL-1/ });
- const card = document.querySelector('[data-slot="source-context-preview"]');
- expect(card).toHaveClass("shrink-0");
-
- fireEvent.click(header);
- expect(card).toHaveClass("flex", "h-[53%]", "min-h-0", "shrink-0", "flex-col");
- expect(card).not.toHaveClass("max-h-[65%]", "shrink");
- expect(header).toHaveClass("shrink-0");
- const body = document.querySelector('[data-slot="source-context-preview-body"]');
- expect(body).toHaveClass("min-h-0", "flex-1", "overflow-y-auto", "overscroll-contain");
- expect(body).not.toHaveClass("max-h-72");
- });
-
it("explains every exceeded source-context limit from the structured response", () => {
const error = new ApiError("too large", 422, "Unprocessable Entity", {
code: "source_context_too_large",
diff --git a/packages/views/onboarding/components/step-shell.test.tsx b/packages/views/onboarding/components/step-shell.test.tsx
index 4fafffc4bc..3dec5b8125 100644
--- a/packages/views/onboarding/components/step-shell.test.tsx
+++ b/packages/views/onboarding/components/step-shell.test.tsx
@@ -5,9 +5,6 @@ import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enOnboarding from "../../locales/en/onboarding.json";
import {
- STEP_COLUMN,
- STEP_GUTTER,
- StepFooter,
StepHeading,
StepShell,
} from "./step-shell";
@@ -25,38 +22,6 @@ function renderShell(props: Partial<Parameters<typeof StepShell>[0]> = {}) {
}
describe("onboarding step shell", () => {
- // The regression this guards: the horizontal padding used to live on the
- // element that also carried the measure. Inside a max-w box the two fight —
- // `md` and `lg` resolved to different content widths for the same box, and
- // the reading column jumped from 508px to 620px at a breakpoint.
- it("puts the gutter on the scrolling pane and the measure on the content", () => {
- const { container } = renderShell();
-
- const main = container.querySelector("main")!;
- for (const cls of STEP_GUTTER.split(" ")) {
- expect(main.className).toContain(cls);
- }
- expect(main.className).not.toMatch(/\bmax-w-/);
- });
-
- // One measure, not three. Two centred measures of different widths do not
- // share a left edge, which is how the platform fork ended up ~150px right
- // of every other step.
- it("centres a single content measure", () => {
- expect(STEP_COLUMN).toContain("mx-auto");
- expect(STEP_COLUMN).toMatch(/max-w-\[[\d.]+rem\]/);
- expect(STEP_COLUMN).not.toMatch(/\bp[xlr]?-/);
- });
-
- // The column fills the pane so StepFooter's `mt-auto` has something to push
- // against; without it the actions ride up under short content.
- it("makes the column fill the pane so the footer can pin to the bottom", () => {
- const { container } = renderShell();
-
- const column = container.querySelector("main > div")!;
- expect(column.className).toContain("min-h-full");
- expect(column.className).toContain("flex-col");
- });
// The panes persist across steps, so a screen reader user gets no
// navigation event when the step changes — the heading has to announce.
@@ -73,19 +38,6 @@ describe("onboarding step shell", () => {
expect(screen.getByText("Pick a URL.")).toBeInTheDocument();
});
- it("pins the step actions to the bottom of the column", () => {
- const { container } = render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <StepFooter hint="Name it to continue.">
- <button type="button">Continue</button>
- </StepFooter>
- </I18nProvider>,
- );
-
- expect(container.firstElementChild!.className).toContain("mt-auto");
- expect(screen.getByText("Name it to continue.")).toBeInTheDocument();
- });
-
// Two Back buttons is the intended shape, not a duplicate: the rail is
// hidden below `md` and the compact bar above the content is hidden at and
// above it. jsdom applies no media queries, so both are in the tree here.
@@ -143,19 +95,6 @@ describe("onboarding step shell", () => {
});
describe("onboarding progress rail", () => {
- // The rail replaced a row of dots plus a "Step 2 of 3" counter, which said
- // how much was left but never what was coming — so the runtime step always
- // arrived unannounced. Naming every step is the whole point of the change.
- it("names all three steps up front", () => {
- const { container } = renderShell({ currentStep: "about_you" });
-
- // Scoped to the rail: the compact bar also prints the current step's name,
- // so an unscoped query matches it twice.
- const rail = within(container.querySelector("aside")!);
- expect(rail.getByText("About you")).toBeInTheDocument();
- expect(rail.getByText("Workspace")).toBeInTheDocument();
- expect(rail.getByText("Meet Mika")).toBeInTheDocument();
- });
it("marks the current step for assistive tech", () => {
const { container } = renderShell({ currentStep: "workspace" });
diff --git a/packages/views/onboarding/steps/cli-install-instructions.test.tsx b/packages/views/onboarding/steps/cli-install-instructions.test.tsx
deleted file mode 100644
index 93064a2c2a..0000000000
--- a/packages/views/onboarding/steps/cli-install-instructions.test.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-import { I18nProvider } from "@multica/core/i18n/react";
-import enCommon from "../../locales/en/common.json";
-import enOnboarding from "../../locales/en/onboarding.json";
-import { CliInstallInstructions } from "./cli-install-instructions";
-
-const TEST_RESOURCES = { en: { common: enCommon, onboarding: enOnboarding } };
-
-const ligatureClasses = [
- "[font-variant-ligatures:none]",
- "[font-feature-settings:'liga'_0]",
-];
-
-describe("CliInstallInstructions", () => {
- it("disables font ligatures in CLI command code", () => {
- render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <CliInstallInstructions />
- </I18nProvider>,
- );
-
- expect(screen.getByText("multica setup")).toHaveClass(...ligatureClasses);
- });
-});
diff --git a/packages/views/onboarding/steps/step-about-you.test.tsx b/packages/views/onboarding/steps/step-about-you.test.tsx
index 53f7257edc..8f96bcc3af 100644
--- a/packages/views/onboarding/steps/step-about-you.test.tsx
+++ b/packages/views/onboarding/steps/step-about-you.test.tsx
@@ -42,16 +42,6 @@ function renderStep(answers: QuestionnaireAnswers = EMPTY) {
describe("StepAboutYou", () => {
beforeEach(() => vi.restoreAllMocks());
- it("renders both question groups on one screen", () => {
- renderStep();
- expect(
- screen.getByText("Which best describes you?"),
- ).toBeInTheDocument();
- expect(
- screen.getByText("What do you want to use Multica for?"),
- ).toBeInTheDocument();
- });
-
it("selecting a role patches the slug and clears Other/skip", async () => {
const user = userEvent.setup();
const { onChange, onAdvance } = renderStep();
diff --git a/packages/views/onboarding/steps/step-runtime-connect.test.tsx b/packages/views/onboarding/steps/step-runtime-connect.test.tsx
index f56db26aba..58e8a90a6f 100644
--- a/packages/views/onboarding/steps/step-runtime-connect.test.tsx
+++ b/packages/views/onboarding/steps/step-runtime-connect.test.tsx
@@ -69,13 +69,6 @@ describe("StepRuntimeConnect", () => {
vi.useRealTimers();
});
- it("mounts and shows the scanning UI without touching framework-level globals", () => {
- renderStep();
- expect(
- screen.getByText(/connecting this computer/i),
- ).toBeInTheDocument();
- });
-
it("does not render a permanently-disabled Mika action while scanning", () => {
renderStep();
expect(
diff --git a/packages/views/platform/scroll-restoration.test.tsx b/packages/views/platform/scroll-restoration.test.tsx
index 524bb689d7..1605897a04 100644
--- a/packages/views/platform/scroll-restoration.test.tsx
+++ b/packages/views/platform/scroll-restoration.test.tsx
@@ -18,34 +18,6 @@ describe("scroll-restoration public surface", () => {
expect(result.current).toBeNull();
});
- it("useScrollRestorationAdapter returns the adapter when provided", () => {
- const adapter = makeAdapter(() => undefined);
- const { result } = renderHook(() => useScrollRestorationAdapter(), {
- wrapper: ({ children }) => (
- <ScrollRestorationProvider adapter={adapter}>
- {children}
- </ScrollRestorationProvider>
- ),
- });
- expect(result.current).toBe(adapter);
- });
-
- it("useRestoredScrollEntry returns the full entry including contentKey", () => {
- const adapter = makeAdapter(() => ({
- top: 321,
- height: 900,
- contentKey: "ck",
- }));
- const { result } = renderHook(() => useRestoredScrollEntry("html-iframe"), {
- wrapper: ({ children }) => (
- <ScrollRestorationProvider adapter={adapter}>
- {children}
- </ScrollRestorationProvider>
- ),
- });
- expect(result.current).toEqual({ top: 321, height: 900, contentKey: "ck" });
- });
-
it("useRestoredScrollOffset remains a thin wrapper returning only top (back-compat)", () => {
const adapter = makeAdapter(() => ({
top: 123,
diff --git a/packages/views/projects/components/local-directory-mode-dialog.test.tsx b/packages/views/projects/components/local-directory-mode-dialog.test.tsx
index f9773b3fab..39cb5c41da 100644
--- a/packages/views/projects/components/local-directory-mode-dialog.test.tsx
+++ b/packages/views/projects/components/local-directory-mode-dialog.test.tsx
@@ -42,16 +42,6 @@ function worktreeOption(): HTMLElement {
}
describe("LocalDirectoryModeDialog", () => {
- it("leads with what the user gets back, not the mode identifiers", () => {
- renderDialog();
- // The identifiers stay visible as a secondary hint for anyone cross-
- // referencing the CLI or docs, but the decision is framed by outcome.
- expect(screen.getByText("Edit this folder directly")).toBeTruthy();
- expect(screen.getByText("Run in parallel, isolated")).toBeTruthy();
- expect(screen.getByText("in_place")).toBeTruthy();
- expect(screen.getByText("worktree")).toBeTruthy();
- expect(screen.getByText("/Users/dev/work/game-client")).toBeTruthy();
- });
it("marks the current mode as selected", () => {
renderDialog({ value: "worktree" });
diff --git a/packages/views/projects/components/project-chip.test.tsx b/packages/views/projects/components/project-chip.test.tsx
deleted file mode 100644
index 5a3091512b..0000000000
--- a/packages/views/projects/components/project-chip.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { useQuery } from "@tanstack/react-query";
-import { ProjectChip } from "./project-chip";
-
-vi.mock("@tanstack/react-query", () => ({
- useQuery: vi.fn(),
-}));
-
-vi.mock("@multica/core/hooks", () => ({
- useWorkspaceId: () => "workspace-1",
-}));
-
-vi.mock("@multica/core/projects/queries", () => ({
- projectListOptions: () => ({ queryKey: ["projects"] }),
- projectDetailOptions: (_workspaceId: string, projectId: string) => ({
- queryKey: ["project", projectId],
- }),
-}));
-
-vi.mock("./project-icon", () => ({
- ProjectIcon: ({ className }: { className?: string }) => (
- <span data-testid="project-icon" className={className} />
- ),
-}));
-
-vi.mock("../../i18n", () => ({
- useT: () => ({ t: () => "Unknown project" }),
-}));
-
-const mockUseQuery = vi.mocked(useQuery);
-
-const LONG_TITLE =
- "A very long project title that should stay inside a narrow chat bubble";
-
-describe("ProjectChip", () => {
- beforeEach(() => {
- mockUseQuery.mockImplementation((options: { queryKey?: readonly unknown[] }) => {
- if (options.queryKey?.[0] === "projects") {
- return {
- data: [{ id: "project-1", title: LONG_TITLE, emoji: "🚀" }],
- } as ReturnType<typeof useQuery>;
- }
- return { data: undefined } as ReturnType<typeof useQuery>;
- });
- });
-
- // ProjectChip and IssueChip render the same inline-chip shape in the same
- // prose. If only one of them bounds its width, reference-dense content breaks
- // for that one — which is how #6732 happened. Locking the cap in both tests
- // is what keeps them from drifting apart again.
- it("carries the same width cap as IssueChip and truncates the title", () => {
- render(<ProjectChip projectId="project-1" />);
-
- const chip = screen.getByText(LONG_TITLE).closest(".project-chip");
- expect(chip).toHaveClass("min-w-0");
- expect(chip).toHaveClass("max-w-[min(18rem,100%)]");
- expect(screen.getByText(LONG_TITLE)).toHaveClass("min-w-0", "truncate");
- });
-
- it("truncates the fallback label inside the chip width", () => {
- render(<ProjectChip projectId="missing-project" fallbackLabel={LONG_TITLE} />);
-
- expect(screen.getByText(LONG_TITLE)).toHaveClass("min-w-0", "truncate");
- });
-});
diff --git a/packages/views/projects/components/project-issue-metrics.test.ts b/packages/views/projects/components/project-issue-metrics.test.ts
deleted file mode 100644
index 9ae9fe7682..0000000000
--- a/packages/views/projects/components/project-issue-metrics.test.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-// @vitest-environment node
-import { describe, expect, it } from "vitest";
-import { getProjectIssueMetrics } from "./project-issue-metrics";
-
-describe("getProjectIssueMetrics", () => {
- it("surfaces project-level totals from the project record", () => {
- const metrics = getProjectIssueMetrics({ issue_count: 9, done_count: 5 });
-
- expect(metrics).toEqual({
- totalCount: 9,
- completedCount: 5,
- });
- });
-});
diff --git a/packages/views/rich-content/package-exports.test.ts b/packages/views/rich-content/package-exports.test.ts
index 394202fc57..3a3fd42a37 100644
--- a/packages/views/rich-content/package-exports.test.ts
+++ b/packages/views/rich-content/package-exports.test.ts
@@ -2,17 +2,10 @@
/**
* Package export-target guard.
*
- * Every path in a workspace's `exports` map must point at a file that actually
- * exists. Deleting or moving a module without updating `exports` leaves a
- * dangling subpath that still *resolves* for TypeScript (which reads the source
- * tree) but throws at bundle time in whichever app imports it — so it survives
- * typecheck and unit tests and only shows up in a consuming app's build.
- *
- * This regressed once already in MUL-4922: `./common/markdown` was deleted when
- * Chat moved onto RichContent, but its export entry stayed behind.
- *
- * Scoped to the whole monorepo rather than just `views`: the failure mode is a
- * property of package.json, not of this package.
+ * A dangling export can still resolve from the source tree during typecheck,
+ * then fail only when a consuming application is bundled. This regressed in
+ * MUL-4922, so validate the filesystem boundary rather than mirroring an
+ * individual package.json entry.
*/
import { describe, expect, it } from "vitest";
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
@@ -33,7 +26,6 @@ function workspacePackageJsons(): string[] {
return out;
}
-/** Every string target in an exports value (string, or a conditions object). */
function exportTargets(value: unknown): string[] {
if (typeof value === "string") return [value];
if (value && typeof value === "object") {
@@ -42,6 +34,11 @@ function exportTargets(value: unknown): string[] {
return [];
}
+function exportTargetExists(pkgDir: string, target: string): boolean {
+ const path = target.includes("*") ? target.slice(0, target.indexOf("*")) : target;
+ return existsSync(join(pkgDir, path));
+}
+
interface Dangling {
pkg: string;
subpath: string;
@@ -59,22 +56,18 @@ function findDanglingExports(): Dangling[] {
} catch {
continue;
}
- const exports = parsed.exports;
- if (!exports || typeof exports !== "object") continue;
+ if (!parsed.exports || typeof parsed.exports !== "object") continue;
- for (const [subpath, value] of Object.entries(exports as Record<string, unknown>)) {
+ for (const [subpath, value] of Object.entries(
+ parsed.exports as Record<string, unknown>,
+ )) {
for (const target of exportTargets(value)) {
- if (target.includes("*")) {
- // Wildcard subpath (e.g. "./locales/*"): the concrete file depends on
- // the importer, so assert the directory prefix exists instead.
- const prefix = target.slice(0, target.indexOf("*"));
- if (!existsSync(join(pkgDir, prefix))) {
- dangling.push({ pkg: relative(REPO_ROOT, pkgPath), subpath, target });
- }
- continue;
- }
- if (!existsSync(join(pkgDir, target))) {
- dangling.push({ pkg: relative(REPO_ROOT, pkgPath), subpath, target });
+ if (!exportTargetExists(pkgDir, target)) {
+ dangling.push({
+ pkg: relative(REPO_ROOT, pkgPath),
+ subpath,
+ target,
+ });
}
}
}
@@ -86,25 +79,13 @@ function findDanglingExports(): Dangling[] {
describe("workspace package exports", () => {
it("every export target points at a file that exists", () => {
const dangling = findDanglingExports();
- // Surfaced as readable strings so a failure names the offending subpath
- // instead of printing an object diff.
expect(dangling.map((d) => `${d.pkg} :: "${d.subpath}" -> ${d.target}`)).toEqual([]);
});
- it("the deleted chat markdown bridge is not exported", () => {
- const views = JSON.parse(
- readFileSync(join(REPO_ROOT, "packages/views/package.json"), "utf8"),
- ) as { exports?: Record<string, unknown> };
-
- expect(Object.keys(views.exports ?? {})).not.toContain("./common/markdown");
- });
-
- it("detects a dangling target when one is introduced", () => {
- // Guards the guard: if the traversal silently stopped finding anything
- // (wrong root, changed layout), the first test would pass vacuously.
- const pkgDir = join(REPO_ROOT, "packages/views");
- expect(existsSync(join(pkgDir, "./editor/index.ts"))).toBe(true);
- expect(existsSync(join(pkgDir, "./common/markdown.tsx"))).toBe(false);
+ it("does not pass vacuously when traversal or existence checks break", () => {
+ const viewsDir = join(REPO_ROOT, "packages/views");
expect(workspacePackageJsons().length).toBeGreaterThan(3);
+ expect(exportTargetExists(viewsDir, "./editor/index.ts")).toBe(true);
+ expect(exportTargetExists(viewsDir, "./definitely-missing.ts")).toBe(false);
});
});
diff --git a/packages/views/rich-content/rich-content-boundary.test.ts b/packages/views/rich-content/rich-content-boundary.test.ts
deleted file mode 100644
index 0d7f9d301e..0000000000
--- a/packages/views/rich-content/rich-content-boundary.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-// @vitest-environment node
-/**
- * Import boundary guard (MUL-4922, Howard's contract #3).
- *
- * The point of this sweep is that there is exactly ONE product-level readonly
- * renderer. That property is not self-enforcing: the cheapest way to add a
- * feature to Chat will always look like "render this bit with the generic
- * Markdown component" or "pass a custom code renderer here", and each of those
- * quietly recreates the second chain we just deleted.
- *
- * These tests read the actual source tree, so they fail on the commit that
- * introduces the fork rather than months later when the surfaces have visibly
- * diverged again.
- */
-import { describe, expect, it } from "vitest";
-import { readFileSync, readdirSync, statSync } from "node:fs";
-import { join, relative } from "node:path";
-
-const VIEWS_ROOT = join(__dirname, "..");
-
-// Product surfaces that render user/agent-authored content. Any of these
-// reaching for a generic Markdown renderer is the regression.
-const PRODUCT_SURFACES = ["chat", "issues", "skills", "autopilots", "inbox"];
-
-function walk(dir: string, out: string[] = []): string[] {
- let entries: string[];
- try {
- entries = readdirSync(dir);
- } catch {
- return out;
- }
- for (const entry of entries) {
- if (entry === "node_modules" || entry.startsWith(".")) continue;
- const full = join(dir, entry);
- if (statSync(full).isDirectory()) walk(full, out);
- else if (/\.tsx?$/.test(full) && !/\.test\.tsx?$/.test(full)) out.push(full);
- }
- return out;
-}
-
-/**
- * Drop comments before matching. These guards look for real imports and real
- * language branches; prose that merely *mentions* one (a doc comment
- * explaining which renderer mounts a leaf) is not a violation, and treating it
- * as one would train the next person to delete the guard.
- */
-function stripComments(text: string): string {
- return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
-}
-
-function sourceFiles(subdirs: string[]): { path: string; text: string }[] {
- return subdirs
- .flatMap((d) => walk(join(VIEWS_ROOT, d)))
- .map((path) => ({
- path: relative(VIEWS_ROOT, path),
- text: stripComments(readFileSync(path, "utf8")),
- }));
-}
-
-describe("RichContent import boundary", () => {
- it("no product surface imports the generic ui Markdown renderer", () => {
- const offenders = sourceFiles(PRODUCT_SURFACES)
- .filter(({ text }) =>
- /from\s+["']@multica\/ui\/markdown["']/.test(text) &&
- /\bMarkdown\b|\bMemoizedMarkdown\b|\bStreamingMarkdown\b/.test(text),
- )
- .map(({ path }) => path);
-
- expect(offenders).toEqual([]);
- });
-
- it("the deleted chat markdown bridge has not come back", () => {
- const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
- .filter(({ text }) => /common\/markdown/.test(text))
- .map(({ path }) => path);
-
- expect(offenders).toEqual([]);
- });
-
- it("no product surface builds its own react-markdown pipeline", () => {
- // react-markdown may be imported only by the canonical renderer. A second
- // import means a second pipeline with its own sanitize + components map.
- const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
- .filter(({ text }) => /from\s+["']react-markdown["']/.test(text))
- .map(({ path }) => path);
-
- expect(offenders).toEqual([]);
- });
-
- it("only the canonical renderer configures the sanitize schema", () => {
- const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
- .filter(({ text }) => /rehype-sanitize|markdownSanitizeSchema/.test(text))
- .map(({ path }) => path);
-
- expect(offenders).toEqual([]);
- });
-
- it("only rich-code-block dispatches on a fence language", () => {
- // A `lang === "mermaid"` / `"html"` comparison outside the dispatcher is a
- // per-surface language branch — architecture constraint 2.
- //
- // The Tiptap NodeView is the one sanctioned exception (constraint 6): the
- // EDITABLE code block owns its own preview-toggle lifecycle while the user
- // types, and reuses the same leaf components rather than the readonly
- // renderer. Rewriting the editor is explicitly out of scope for MUL-4922.
- // Narrow, named, and justified — not a general loophole.
- const TIPTAP_NODEVIEW = "editor/extensions/code-block-view.tsx";
-
- const offenders = sourceFiles([...PRODUCT_SURFACES, "common", "editor"])
- .filter(({ path }) => path !== TIPTAP_NODEVIEW)
- .filter(({ text }) =>
- /(?:lang|language)\w*\s*===\s*["'](?:mermaid|html)["']/.test(text),
- )
- .map(({ path }) => path);
-
- expect(offenders).toEqual([]);
- });
-
- it("Tiptap reuses the leaf components but never imports RichContent", () => {
- // Constraint 6: the editor keeps its own parser/lifecycle. Pulling the
- // readonly renderer into the editor is the classic way this collapses.
- const offenders = walk(join(VIEWS_ROOT, "editor"))
- .filter((p) => !/readonly-content\.tsx$/.test(p))
- .map((path) => ({
- path: relative(VIEWS_ROOT, path),
- // stripComments, consistently with the other checks: an editor file may
- // *mention* RichContent in a doc comment (explaining why a helper is
- // shaped the way it is). Only real code references are violations.
- text: stripComments(readFileSync(path, "utf8")),
- }))
- .filter(({ text }) => /\bRichContent\b/.test(text))
- .map(({ path }) => path);
-
- expect(offenders).toEqual([]);
- });
-
- it("the canonical renderer stays in views, not ui", () => {
- // Mention/Attachment/navigation are product concerns; moving this into
- // packages/ui would break the ui -> no-core/views boundary.
- const uiRoot = join(VIEWS_ROOT, "..", "ui");
- const offenders = walk(uiRoot)
- .map((path) => ({ path, text: stripComments(readFileSync(path, "utf8")) }))
- .filter(({ text }) => /\bRichContent\b|from\s+["']@multica\/views/.test(text))
- .map(({ path }) => relative(uiRoot, path));
-
- expect(offenders).toEqual([]);
- });
-});
-
-describe("chat renders every text entry through RichContent", () => {
- const chatList = readFileSync(
- join(VIEWS_ROOT, "chat/components/chat-message-list.tsx"),
- "utf8",
- );
-
- it("uses RichContent and no other markdown renderer", () => {
- expect(chatList).toMatch(/\bRichContent\b/);
- expect(chatList).not.toMatch(/MemoizedMarkdown|<Markdown\b/);
- });
-
- it("keys the live row and the persisted assistant row on the task", () => {
- // The identity contract in source form: if someone reverts to `msg.id`,
- // the parity test's remount assertion and this both fail.
- expect(chatList).toMatch(/task:\$\{/);
- expect(chatList).not.toMatch(/computeItemKey=\{\(_, msg\) => msg\.id\}/);
- });
-});
diff --git a/packages/views/runtimes/components/connect-remote-dialog.test.tsx b/packages/views/runtimes/components/connect-remote-dialog.test.tsx
index 01131fbfda..4f1933474a 100644
--- a/packages/views/runtimes/components/connect-remote-dialog.test.tsx
+++ b/packages/views/runtimes/components/connect-remote-dialog.test.tsx
@@ -66,11 +66,6 @@ function renderDialog(config?: {
);
}
-const ligatureClasses = [
- "[font-variant-ligatures:none]",
- "[font-feature-settings:'liga'_0]",
-];
-
describe("ConnectRemoteDialog", () => {
beforeEach(() => {
wsEventState.handler = null;
@@ -106,26 +101,6 @@ describe("ConnectRemoteDialog", () => {
);
});
- it("disables font ligatures in setup command code", () => {
- const { baseElement } = renderDialog();
-
- const setupCode = Array.from(baseElement.querySelectorAll("code")).find((node) =>
- node.textContent?.includes("multica setup"),
- );
-
- expect(setupCode).toHaveClass(...ligatureClasses);
- });
-
- it("disables font ligatures in fallback token command code", () => {
- const { baseElement } = renderDialog();
-
- const tokenCode = Array.from(baseElement.querySelectorAll("code")).find((node) =>
- node.textContent?.includes("multica login --token <YOUR_TOKEN>"),
- );
-
- expect(tokenCode).toHaveClass(...ligatureClasses);
- });
-
it("transitions from setup instructions to the connected state", async () => {
const { baseElement } = renderDialog();
diff --git a/packages/views/runtimes/components/provider-logo.test.tsx b/packages/views/runtimes/components/provider-logo.test.tsx
deleted file mode 100644
index 1253e8820d..0000000000
--- a/packages/views/runtimes/components/provider-logo.test.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { readFileSync } from "node:fs";
-import { render } from "@testing-library/react";
-import { describe, expect, it } from "vitest";
-import { ProviderLogo } from "./provider-logo";
-
-describe("ProviderLogo", () => {
- it("renders the dedicated CodeArts icon", () => {
- const { container } = render(
- <ProviderLogo provider="codearts" className="runtime-logo" />,
- );
-
- const logo = container.querySelector('img[alt="CodeArts"]');
-
- expect(logo?.getAttribute("src")).toBeTruthy();
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("keeps the official Reasonix artwork", () => {
- const logoSvg = readFileSync("runtimes/components/reasonix-logo.svg", "utf8");
-
- expect(logoSvg).toContain('viewBox="0 0 64 64"');
- expect(logoSvg).toContain('stop-color="#4f9dff"');
- expect(logoSvg).toContain('stop-color="#c46bff"');
- });
-
- it("renders the official Reasonix logo", () => {
- const { container } = render(
- <ProviderLogo provider="reasonix" className="runtime-logo" />,
- );
-
- const logo = container.querySelector('img[alt="Reasonix"]');
-
- expect(logo?.getAttribute("src")).toBeTruthy();
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("renders the dedicated Dim mark", () => {
- const { container } = render(<ProviderLogo provider="dim" className="runtime-logo" />);
-
- const logo = container.querySelector("img");
- const logoSrc = decodeURIComponent(logo?.getAttribute("src") ?? "");
-
- expect(logo?.getAttribute("alt")).toBe("");
- expect(logoSrc).toContain("dim-logo.png");
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("renders the dedicated Qwen Code mark", () => {
- const { container } = render(<ProviderLogo provider="qwen" className="runtime-logo" />);
-
- const logo = container.querySelector('img[aria-hidden="true"]');
- const logoSrc = decodeURIComponent(logo?.getAttribute("src") ?? "");
-
- expect(logo?.getAttribute("alt")).toBe("");
- expect(logoSrc).toContain("viewBox='0 0 141.38 140'");
- expect(logoSrc).toContain("fill='#6D44E8'");
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("renders the official DeepSeek Harness mark instead of the generic fallback", () => {
- const { container } = render(
- <ProviderLogo provider="dsh" className="runtime-logo" />,
- );
-
- const logo = container.querySelector("svg");
-
- // Inlined rather than loaded through <img>: currentColor only resolves
- // against the host document, so an <img> would pin the mark to black and
- // lose it against the dark theme.
- expect(logo?.getAttribute("viewBox")).toBe("0 0 50 50");
- expect(logo?.getAttribute("fill")).toBe("currentColor");
- expect(logo?.querySelector("path")).not.toBeNull();
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("renders the QwenPaw mark instead of the generic fallback", () => {
- const { container } = render(
- <ProviderLogo provider="qwenpaw" className="runtime-logo" />,
- );
-
- const logo = container.querySelector("svg");
-
- // currentColor keeps the single path legible in both themes, matching the
- // separate light/dark marks upstream ships.
- expect(logo?.getAttribute("fill")).toBe("currentColor");
- expect(logo?.querySelector("path")).not.toBeNull();
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("renders the MiniMax Code mark instead of the generic fallback", () => {
- const { container } = render(
- <ProviderLogo provider="mcode" className="runtime-logo" />,
- );
-
- const logo = container.querySelector("svg");
- const path = logo?.querySelector("path");
-
- // Official MiniMax Code compound path: clipped-corner card + inner "m".
- // currentColor follows the theme instead of pinning the mark to black.
- expect(logo?.getAttribute("viewBox")).toBe("2.1 2 27.9 28");
- expect(logo?.getAttribute("fill")).toBe("currentColor");
- expect(path?.getAttribute("d")).toContain("M27.0157 5.80436");
- expect(path?.getAttribute("d")).toContain("ZM11.0587 8.88053");
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-
- it("renders the ZeroClaw placeholder mark instead of the generic fallback", () => {
- const { container } = render(
- <ProviderLogo provider="zeroclaw" className="runtime-logo" />,
- );
-
- const logo = container.querySelector("svg");
-
- // No official ZeroClaw asset has been sourced yet, so this pins the
- // deliberate placeholder mark (three strokes) rather than the generic
- // <Monitor /> fallback that unknown providers get.
- expect(logo?.getAttribute("viewBox")).toBe("0 0 24 24");
- expect(logo?.getAttribute("stroke")).toBe("currentColor");
- expect(logo?.querySelectorAll("path").length).toBe(3);
- expect(logo?.classList.contains("runtime-logo")).toBe(true);
- });
-});
diff --git a/packages/views/runtimes/components/runtime-profile-catalog.test.ts b/packages/views/runtimes/components/runtime-profile-catalog.test.ts
index e1ff16a517..cab94f34ee 100644
--- a/packages/views/runtimes/components/runtime-profile-catalog.test.ts
+++ b/packages/views/runtimes/components/runtime-profile-catalog.test.ts
@@ -31,10 +31,6 @@ function profile(
}
describe("buildRuntimeCatalog", () => {
- it("offers CodeArts as an independent protocol family", () => {
- expect(PROTOCOL_FAMILIES).toContain("codearts");
- });
-
it("keeps custom profiles separate from built-in protocol families", () => {
const catalog = buildRuntimeCatalog([
profile("prof-1", "Team Codex", "2026-01-02T00:00:00Z"),
diff --git a/packages/views/settings/components/dingtalk-tab.test.tsx b/packages/views/settings/components/dingtalk-tab.test.tsx
index 5518fa98d8..4a0b3006a7 100644
--- a/packages/views/settings/components/dingtalk-tab.test.tsx
+++ b/packages/views/settings/components/dingtalk-tab.test.tsx
@@ -190,12 +190,6 @@ function resetFixtures() {
describe("DingTalkAgentBindButton", () => {
beforeEach(resetFixtures);
- it("renders the DingTalk brand mark in the connect button", () => {
- renderUI(<DingTalkAgentBindButton agentId="agent-1" agentName="Bot" />);
- const button = screen.getByTestId("dingtalk-agent-connect");
- expect(button.querySelector('[data-testid="dingtalk-mark"].h-4.w-4')).toBeTruthy();
- });
-
it("opens the BYO dialog and submits the pasted AppKey + AppSecret", async () => {
mockRegisterBYO.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
renderUI(<DingTalkAgentBindButton agentId="agent-1" agentName="Bot" />);
diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsx
index 76d08daf80..782769ed5f 100644
--- a/packages/views/settings/components/integrations-tab.test.tsx
+++ b/packages/views/settings/components/integrations-tab.test.tsx
@@ -100,21 +100,6 @@ describe("Settings IntegrationsTab", () => {
expect(queryCallsRef.current[0]?.enabled).toBe(true);
});
- it("shows each channel description below its icon and title", () => {
- renderTab();
-
- for (const channel of ["lark", "slack", "dingtalk", "wecom", "telegram"]) {
- const icon = screen.getByTestId(`integration-channel-icon-${channel}`);
- const title = icon.closest("h3");
- const description = title?.nextElementSibling;
- expect(title).not.toBeNull();
- expect(description?.tagName).toBe("P");
- expect(description).toHaveClass("text-caption", "text-muted-foreground");
- expect(icon).not.toHaveClass("border");
- expect(icon).not.toHaveClass("bg-muted/40");
- }
- });
-
// Reaching for a generic lucide glyph is how Slack and WeCom ended up sharing
// one speech bubble, with nothing on the row saying which platform it was
// (#6585). Requiring five distinct shapes is the cheap guard against a
diff --git a/packages/views/settings/components/labels-tab.test.tsx b/packages/views/settings/components/labels-tab.test.tsx
index 2ab255d04a..1ac2c873fd 100644
--- a/packages/views/settings/components/labels-tab.test.tsx
+++ b/packages/views/settings/components/labels-tab.test.tsx
@@ -33,10 +33,4 @@ describe("LabelsTab scopes", () => {
expect(screen.getByRole("button", { name: /Skills/ })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /Agents/ })).toBeNull();
});
-
- it("describes the tab without promising an agent catalog", () => {
- renderWithI18n(<LabelsTab />);
-
- expect(screen.getByText(/organize issues and skills/i)).toBeInTheDocument();
- });
});
diff --git a/packages/views/settings/components/mcp-tab.test.tsx b/packages/views/settings/components/mcp-tab.test.tsx
index 669bc11320..c89f139488 100644
--- a/packages/views/settings/components/mcp-tab.test.tsx
+++ b/packages/views/settings/components/mcp-tab.test.tsx
@@ -210,14 +210,6 @@ describe("McpTab", () => {
expect(screen.getByText("No shared MCP servers")).toBeInTheDocument();
});
- // The document is write-only, so the screen must never imply it is showing
- // a saved configuration: it says an edit replaces the entry.
- it("states that saved configurations are write-only", () => {
- render(<McpTab />, { wrapper: Wrapper });
-
- expect(screen.getByText(/write-only/)).toBeInTheDocument();
- });
-
it("survives a payload that is not an array", () => {
// Backend drift: the schema defaults the list to [], but the component
// must not crash if it ever arrives undefined.
diff --git a/packages/views/skills/components/create-skill-dialog.test.tsx b/packages/views/skills/components/create-skill-dialog.test.tsx
index d7b36415ae..acf4f7fc89 100644
--- a/packages/views/skills/components/create-skill-dialog.test.tsx
+++ b/packages/views/skills/components/create-skill-dialog.test.tsx
@@ -126,22 +126,6 @@ describe("CreateSkillDialog local import", () => {
});
});
- it("lists Import from local as the second method", () => {
- renderDialog();
- const cards = screen.getAllByRole("button");
- const titles = cards
- .map((el) => el.textContent ?? "")
- .filter((text) =>
- /Create manually|Import from local|Import from URL|Copy from runtime/.test(
- text,
- ),
- );
- expect(titles[0]).toContain("Create manually");
- expect(titles[1]).toContain("Import from local");
- expect(titles[2]).toContain("Import from URL");
- expect(titles[3]).toContain("Copy from runtime");
- });
-
it("opens the folder picker when Import from local is clicked", () => {
renderDialog();
const click = vi.fn();
diff --git a/packages/views/skills/components/file-tree.test.tsx b/packages/views/skills/components/file-tree.test.tsx
index 3ff6a6dc61..377cf17158 100644
--- a/packages/views/skills/components/file-tree.test.tsx
+++ b/packages/views/skills/components/file-tree.test.tsx
@@ -72,28 +72,6 @@ describe("FileTree row actions", () => {
expect(onEdit).toHaveBeenCalledWith("notes.txt");
});
- it("keeps the menu trigger's widened hit area inside the trigger", async () => {
- await renderWithI18n(
- <FileTree
- filePaths={PATHS}
- selectedPath="SKILL.md"
- onSelect={vi.fn()}
- actions={makeActions()}
- />,
- );
-
- // MUL-5654: the trigger widens its hit area with an absolutely positioned
- // `after:-inset-1`. Drop `relative` and that pseudo-element resolves
- // against the row instead, covering it end to end and swallowing every
- // click on the file name — the row stops selecting and opens this menu.
- // jsdom has no layout or hit testing, so the class pairing is the part a
- // unit test can hold; the behaviour itself needs a real browser.
- // The name button carries role="tab", so a "button" match is the trigger.
- const trigger = screen.getByRole("button", { name: /notes\.txt/ });
- expect(trigger.className).toContain("after:absolute");
- expect(trigger.className).toContain("relative");
- });
-
it("deletes the row acted on, not whichever file happens to be open", async () => {
const onDelete = vi.fn();
await renderWithI18n(
diff --git a/packages/views/skills/components/skill-detail-page.test.tsx b/packages/views/skills/components/skill-detail-page.test.tsx
index af4e31f9a1..43699a8e7b 100644
--- a/packages/views/skills/components/skill-detail-page.test.tsx
+++ b/packages/views/skills/components/skill-detail-page.test.tsx
@@ -170,11 +170,6 @@ describe("SkillDetailPage tabs", () => {
).toBe("true");
});
- it("shows resource labels in Overview without a release flag", async () => {
- renderPage();
- expect(await screen.findByTestId("labels")).toBeTruthy();
- });
-
it("mirrors the active tab into ?view= so the pane survives a reload", async () => {
const { replace } = renderPage();
fireEvent.click(await screen.findByRole("tab", { name: "Files 2" }));
diff --git a/packages/views/skills/lib/skill-icon.test.ts b/packages/views/skills/lib/skill-icon.test.ts
deleted file mode 100644
index 0bec0d057e..0000000000
--- a/packages/views/skills/lib/skill-icon.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { routeIconForPath } from "../../layout/route-icon-components";
-import { SkillIcon } from "./skill-icon";
-
-describe("SkillIcon", () => {
- // The sidebar and desktop tab bar both render the route icon, while every
- // in-page surface renders SkillIcon. Before they were derived from one
- // declaration the product showed four icons for the same entity
- // (BookOpenText, BookOpen, FileText, Sparkles).
- it("is the same component the sidebar and tab bar resolve for /skills", () => {
- expect(SkillIcon).toBe(routeIconForPath("/acme/skills"));
- });
-
- it("keeps matching for a nested skill detail path", () => {
- expect(SkillIcon).toBe(routeIconForPath("/acme/skills/skill-1"));
- });
-});
diff --git a/packages/views/workspace/paths-hooks.test.tsx b/packages/views/workspace/paths-hooks.test.tsx
index 7a0961a517..e9aa2ae546 100644
--- a/packages/views/workspace/paths-hooks.test.tsx
+++ b/packages/views/workspace/paths-hooks.test.tsx
@@ -44,13 +44,6 @@ function setup(slug: string | null, wsList: Workspace[] = []) {
}
describe("useWorkspaceSlug", () => {
- it("returns the provided slug", () => {
- function Probe() {
- return <div data-testid="slug">{useWorkspaceSlug() ?? "null"}</div>;
- }
- render(<Probe />, { wrapper: setup("acme") });
- expect(screen.getByTestId("slug").textContent).toBe("acme");
- });
it("returns null when no slug is provided", () => {
function Probe() {
diff --git a/server/cmd/migrate/migrate_source_context_test.go b/server/cmd/migrate/migrate_source_context_test.go
index 1fcd25662d..e6a5d1b64a 100644
--- a/server/cmd/migrate/migrate_source_context_test.go
+++ b/server/cmd/migrate/migrate_source_context_test.go
@@ -171,14 +171,6 @@ func TestSourceContextMigrationsRollbackFailsClosedWithCapturedData(t *testing.T
}
}
-func TestSourceContextRollbackGuardRegisteredForEveryMigrationStep(t *testing.T) {
- for _, version := range sourceContextMigrationVersions {
- if preRollbackHooks[version] == nil {
- t.Errorf("source-context rollback guard is not registered for %s", version)
- }
- }
-}
-
func assertSourceContextSchema(t *testing.T, pool interface {
QueryRow(context.Context, string, ...any) pgx.Row
}, schema string, want bool) {
diff --git a/server/cmd/multica/cmd_agent_copy_test.go b/server/cmd/multica/cmd_agent_copy_test.go
index 209981b300..bd888bf6d4 100644
--- a/server/cmd/multica/cmd_agent_copy_test.go
+++ b/server/cmd/multica/cmd_agent_copy_test.go
@@ -355,16 +355,3 @@ func TestAgentCopyAcceptsExplicitCustomEnv(t *testing.T) {
t.Errorf("custom_env[API_KEY] = %v, want fresh", ce["API_KEY"])
}
}
-
-// The copy command must expose the same secret-safe input channels as create so
-// scripts can keep secrets off the command line.
-func TestAgentCopyExposesSecretSafeFlags(t *testing.T) {
- for _, name := range []string{
- "custom-env-stdin", "custom-env-file",
- "mcp-config-stdin", "mcp-config-file",
- } {
- if agentCopyCmd.Flag(name) == nil {
- t.Errorf("agent copy is missing the %q flag", name)
- }
- }
-}
diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.go
index 46cd6e12b5..46ef1a7282 100644
--- a/server/cmd/multica/cmd_agent_test.go
+++ b/server/cmd/multica/cmd_agent_test.go
@@ -703,18 +703,6 @@ func TestAgentUpdateNoFieldsErrorPointsAtEnvCommand(t *testing.T) {
}
}
-// TestAgentUpdateDoesNotExposeCustomEnvFlags is the inverse guarantee
-// for the above test: if someone re-adds the --custom-env* flags to
-// `agent update`, this fails loudly. The /env path is the only
-// audited surface and we don't want a silent regression.
-func TestAgentUpdateDoesNotExposeCustomEnvFlags(t *testing.T) {
- for _, flag := range []string{"custom-env", "custom-env-stdin", "custom-env-file"} {
- if agentUpdateCmd.Flag(flag) != nil {
- t.Errorf("agent update must NOT expose --%s after MUL-2600; use `multica agent env set` instead", flag)
- }
- }
-}
-
func TestAgentMaxConcurrentTasksFlagValidation(t *testing.T) {
previousDir, err := os.Getwd()
if err != nil {
@@ -885,37 +873,6 @@ func TestParseCustomArgsErrorSanitization(t *testing.T) {
}
}
-// TestAgentCreateAndEnvSetExposeSecretSafeFlags guarantees the
-// --custom-env-stdin and --custom-env-file alternatives stay wired
-// up on both commands that accept env input (`agent create` and the
-// new `agent env set`). They exist specifically so callers can keep
-// secret material out of shell history / 'ps'; regressing either
-// surface reopens the foot-gun.
-func TestAgentCreateAndEnvSetExposeSecretSafeFlags(t *testing.T) {
- for _, flag := range []string{"custom-env-stdin", "custom-env-file"} {
- if agentCreateCmd.Flag(flag) == nil {
- t.Fatalf("agent create must expose --%s", flag)
- }
- if agentEnvSetCmd.Flag(flag) == nil {
- t.Fatalf("agent env set must expose --%s", flag)
- }
- }
- // The --custom-env help text must warn users that argv is visible
- // to shell history / 'ps' — "never logged" alone is misleading.
- for _, c := range []struct {
- name string
- usage string
- }{
- {"agent create", agentCreateCmd.Flag("custom-env").Usage},
- {"agent env set", agentEnvSetCmd.Flag("custom-env").Usage},
- } {
- low := strings.ToLower(c.usage)
- if !strings.Contains(low, "shell history") || !strings.Contains(low, "'ps'") {
- t.Fatalf("%s --custom-env usage must warn about shell history and 'ps' exposure; got: %q", c.name, c.usage)
- }
- }
-}
-
// TestResolveCustomEnv exercises the input-channel resolver: inline
// flag, stdin, file, mutual exclusion, and the "not supplied" path.
func TestResolveCustomEnv(t *testing.T) {
@@ -1276,36 +1233,6 @@ func TestResolveMcpConfig(t *testing.T) {
})
}
-// TestAgentCreateAndUpdateExposeMcpConfigFlags guarantees the secret-safe
-// --mcp-config-stdin / --mcp-config-file alternatives stay wired up on both
-// commands that accept MCP input. Unlike custom_env, mcp_config IS updatable
-// via `agent update` (it has no dedicated audited endpoint), so both surfaces
-// must expose all three channels.
-func TestAgentCreateAndUpdateExposeMcpConfigFlags(t *testing.T) {
- for _, flag := range []string{"mcp-config", "mcp-config-stdin", "mcp-config-file"} {
- if agentCreateCmd.Flag(flag) == nil {
- t.Fatalf("agent create must expose --%s", flag)
- }
- if agentUpdateCmd.Flag(flag) == nil {
- t.Fatalf("agent update must expose --%s", flag)
- }
- }
- // The --mcp-config help text must warn that argv is visible to shell
- // history / 'ps' — the same foot-gun the custom-env flags warn about.
- for _, c := range []struct {
- name string
- usage string
- }{
- {"agent create", agentCreateCmd.Flag("mcp-config").Usage},
- {"agent update", agentUpdateCmd.Flag("mcp-config").Usage},
- } {
- low := strings.ToLower(c.usage)
- if !strings.Contains(low, "shell history") || !strings.Contains(low, "'ps'") {
- t.Fatalf("%s --mcp-config usage must warn about shell history and 'ps' exposure; got: %q", c.name, c.usage)
- }
- }
-}
-
func TestAgentSkillsAddCallsAdditiveEndpoint(t *testing.T) {
var gotMethod string
var gotPath string
@@ -1947,18 +1874,6 @@ func TestAgentUpdateSendsThinkingLevel(t *testing.T) {
}
}
-// TestAgentCreateAndUpdateExposeThinkingLevelFlag guarantees the flag stays
-// wired on both write surfaces. The read side (`agent get`) already exposes
-// thinking_level; this is the matching write surface (#4170).
-func TestAgentCreateAndUpdateExposeThinkingLevelFlag(t *testing.T) {
- if agentCreateCmd.Flag("thinking-level") == nil {
- t.Error("agent create must expose --thinking-level")
- }
- if agentUpdateCmd.Flag("thinking-level") == nil {
- t.Error("agent update must expose --thinking-level")
- }
-}
-
func TestAgentServiceTierFlagsAndBodies(t *testing.T) {
if agentCreateCmd.Flag("service-tier") == nil {
t.Error("agent create must expose --service-tier")
diff --git a/server/cmd/multica/cmd_compat_test.go b/server/cmd/multica/cmd_compat_test.go
index 3b4a9961af..3a9634ed7b 100644
--- a/server/cmd/multica/cmd_compat_test.go
+++ b/server/cmd/multica/cmd_compat_test.go
@@ -6,29 +6,6 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
)
-func TestLegacyCompatibilityCommandsRemainAvailable(t *testing.T) {
- t.Run("workspace get remains available", func(t *testing.T) {
- if _, _, err := workspaceCmd.Find([]string{"get"}); err != nil {
- t.Fatalf("expected workspace get command to exist: %v", err)
- }
- })
-
- t.Run("workspace member list remains available", func(t *testing.T) {
- if _, _, err := workspaceCmd.Find([]string{"member", "list"}); err != nil {
- t.Fatalf("expected workspace member list command to exist: %v", err)
- }
- })
-
- t.Run("config show and set remain available", func(t *testing.T) {
- if _, _, err := configCmd.Find([]string{"show"}); err != nil {
- t.Fatalf("expected config show command to exist: %v", err)
- }
- if _, _, err := configCmd.Find([]string{"set"}); err != nil {
- t.Fatalf("expected config set command to exist: %v", err)
- }
- })
-}
-
func TestRunConfigSetPersistsValues(t *testing.T) {
t.Setenv("HOME", t.TempDir())
cmd := testCmd()
diff --git a/server/cmd/multica/cmd_daemon_log_test.go b/server/cmd/multica/cmd_daemon_log_test.go
index 846f6e6396..a544bfe5bf 100644
--- a/server/cmd/multica/cmd_daemon_log_test.go
+++ b/server/cmd/multica/cmd_daemon_log_test.go
@@ -96,33 +96,6 @@ func TestOpenBoundedErrLogKeepsSmall(t *testing.T) {
}
}
-// TestNewDaemonLogRotatorDefaults asserts the rotator is wired to the intended
-// policy when no env overrides are set: the configured path, the default
-// size/backups/age, and gzip compression so rotated files stay small.
-func TestNewDaemonLogRotatorDefaults(t *testing.T) {
- os.Unsetenv("MULTICA_DAEMON_LOG_MAX_SIZE_MB")
- os.Unsetenv("MULTICA_DAEMON_LOG_MAX_BACKUPS")
- os.Unsetenv("MULTICA_DAEMON_LOG_MAX_AGE_DAYS")
-
- path := filepath.Join(t.TempDir(), "daemon.log")
- r := newDaemonLogRotator(path)
- if r.Filename != path {
- t.Errorf("Filename = %q, want %q", r.Filename, path)
- }
- if r.MaxSize != defaultDaemonLogMaxSizeMB {
- t.Errorf("MaxSize = %d, want %d", r.MaxSize, defaultDaemonLogMaxSizeMB)
- }
- if r.MaxBackups != defaultDaemonLogMaxBackups {
- t.Errorf("MaxBackups = %d, want %d", r.MaxBackups, defaultDaemonLogMaxBackups)
- }
- if r.MaxAge != defaultDaemonLogMaxAgeDays {
- t.Errorf("MaxAge = %d, want %d", r.MaxAge, defaultDaemonLogMaxAgeDays)
- }
- if !r.Compress {
- t.Error("Compress = false, want true")
- }
-}
-
// TestNewDaemonLogRotatorEnvOverride confirms operators can tune retention via
// env without a rebuild.
func TestNewDaemonLogRotatorEnvOverride(t *testing.T) {
diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.go
index b63546a74f..48ae8f9850 100644
--- a/server/cmd/multica/cmd_daemon_test.go
+++ b/server/cmd/multica/cmd_daemon_test.go
@@ -136,29 +136,6 @@ func TestBuildDaemonStartArgsForwardsNoAutoReload(t *testing.T) {
}
}
-// TestNoAutoReloadFlagRegisteredOnBothDaemonCommands: `daemon restart` mirrors
-// every `daemon start` flag, and a knob registered on only one of them fails at
-// parse time for users who restart rather than start.
-func TestNoAutoReloadFlagRegisteredOnBothDaemonCommands(t *testing.T) {
- t.Parallel()
-
- for _, cmd := range []*cobra.Command{daemonStartCmd, daemonRestartCmd} {
- if cmd.Flags().Lookup("no-auto-reload") == nil {
- t.Errorf("daemon %s is missing --no-auto-reload", cmd.Name())
- }
- }
-}
-
-func TestWorkspacesRootFlagRegisteredOnBothDaemonCommands(t *testing.T) {
- t.Parallel()
-
- for _, cmd := range []*cobra.Command{daemonStartCmd, daemonRestartCmd} {
- if cmd.Flags().Lookup("workspaces-root") == nil {
- t.Errorf("daemon %s is missing --workspaces-root", cmd.Name())
- }
- }
-}
-
// TestPrintDaemonStatusExplainsDeferredRestart: when the daemon has confirmed a
// version change but is still busy, `daemon status` is where a user finds out.
// The row is absent otherwise so it reads as an explanation, not a status line.
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 944c5bbd8e..aecfe82197 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -3768,47 +3768,6 @@ func TestRunIssueUpdateOmitsPositionWhenUnset(t *testing.T) {
}
}
-// TestIssueCommentListHelpCarriesReadContract pins the read-surface contract
-// that MUL-5442 moved out of the runtime brief into this command's --help: the
-// --recent saturation semantics (MUL-5372), the bounded two-step alternative,
-// and the pagination cursor labels. The brief now only points here — if these
-// leave the help, the pointer dangles and the over-read trap returns
-// undocumented.
-//
-// The assertions run against the RENDERED FlagUsages output, not raw
-// Flag.Usage: pflag's UnquoteUsage hijacks the first backtick pair in a usage
-// string as the flag's value placeholder (see
-// TestLoginTokenHelpOutputRendersCleanly for the original regression), so only
-// the rendered output proves what an agent actually reads.
-func TestIssueCommentListHelpCarriesReadContract(t *testing.T) {
- help := issueCommentListCmd.Flags().FlagUsages()
-
- for _, want := range []string{
- // --before must keep its string placeholder — a backticked phrase in
- // the usage text would replace it (the UnquoteUsage hijack).
- "--before string",
- // The saturation contract relocated from the brief (MUL-5372).
- "caps THREADS, not comments",
- "no per-thread cap",
- "fewer than N root threads",
- // The bounded alternative, as two sequential reads — the flags are
- // mutually exclusive, so the help must never suggest composing them.
- "scan with --roots-only --summary",
- "then open selected threads with --thread <id> --tail N",
- // Pagination cursor labels, exactly as the CLI prints them on stderr.
- "Next thread cursor",
- "Next reply cursor",
- // The --compact contract (#5999 follow-up): what goes and what is
- // untouchable.
- "drop response fields that carry no information",
- "Content and identity fields pass through untouched",
- } {
- if !strings.Contains(help, want) {
- t.Errorf("comment list rendered help missing %q, got:\n%s", want, help)
- }
- }
-}
-
// TestCompactCommentsDropsReaderNoise pins the --compact contract (#5999
// follow-up, MUL-5442): reader-noise fields go — the echoed issue_id,
// source_task_id, updated_at when identical to created_at, null values,
diff --git a/server/cmd/multica/cmd_issue_timeline_test.go b/server/cmd/multica/cmd_issue_timeline_test.go
index 106279e2bd..96ca15984d 100644
--- a/server/cmd/multica/cmd_issue_timeline_test.go
+++ b/server/cmd/multica/cmd_issue_timeline_test.go
@@ -365,40 +365,6 @@ func TestRunIssueTimelineSilentWhenNotTruncated(t *testing.T) {
}
}
-// The help text is the discovery surface: this command is deliberately absent
-// from the runtime brief, so an agent only finds it by scanning `issue --help`
-// for the question it is trying to answer. These anchors are the contract.
-func TestIssueTimelineHelpCarriesDiscoveryContract(t *testing.T) {
- if want := "how long it has been stuck"; !strings.Contains(issueTimelineCmd.Short, want) {
- t.Errorf("timeline Short missing %q, got: %s", want, issueTimelineCmd.Short)
- }
-
- for _, want := range []string{
- // Points back at the authoritative current state, so nobody
- // reconstructs "now" from history.
- "issue get",
- "authoritative",
- // Why comments alone cannot answer this.
- "never a comment",
- // The truncation caveat must be discoverable, not just printed.
- "truncated",
- } {
- if !strings.Contains(issueTimelineCmd.Long, want) {
- t.Errorf("timeline Long missing %q, got:\n%s", want, issueTimelineCmd.Long)
- }
- }
-
- // The action list must stay honest about what the server actually writes;
- // omitting the task events is what made the first cut of this command
- // misdescribe --activity-only.
- help := issueTimelineCmd.Flags().FlagUsages()
- for _, want := range []string{"task_completed", "task_failed", "status_changed", "Implies --activity-only"} {
- if !strings.Contains(help, want) {
- t.Errorf("timeline rendered flag help missing %q, got:\n%s", want, help)
- }
- }
-}
-
func TestClipTimelineText(t *testing.T) {
if got := clipTimelineText("短", 10); got != "短" {
t.Fatalf("clip short = %q", got)
diff --git a/server/cmd/multica/cmd_runtime_profile_test.go b/server/cmd/multica/cmd_runtime_profile_test.go
index c4cdac8243..9c1569ff6e 100644
--- a/server/cmd/multica/cmd_runtime_profile_test.go
+++ b/server/cmd/multica/cmd_runtime_profile_test.go
@@ -72,25 +72,6 @@ func newProfileUnsetPathTestCmd() *cobra.Command {
return cmd
}
-// TestRuntimeProfileCommandsRegistered verifies the subcommands are wired
-// under `runtime profile`.
-func TestRuntimeProfileCommandsRegistered(t *testing.T) {
- for _, name := range []string{"list", "create", "update", "delete", "set-path", "unset-path"} {
- cmd, _, err := runtimeProfileCmd.Find([]string{name})
- if err != nil {
- t.Fatalf("find %q: %v", name, err)
- }
- if cmd == nil || cmd.Name() != name {
- t.Fatalf("%q not registered under `runtime profile`; got %#v", name, cmd)
- }
- }
- // And `profile` itself must hang off `runtime`.
- cmd, _, err := runtimeCmd.Find([]string{"profile", "list"})
- if err != nil || cmd == nil || cmd.Name() != "list" {
- t.Fatalf("`runtime profile list` not reachable from runtime command: %v / %#v", err, cmd)
- }
-}
-
func TestRunRuntimeProfileList(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
diff --git a/server/cmd/multica/cmd_setup_test.go b/server/cmd/multica/cmd_setup_test.go
index a82c29d63f..2d0062274a 100644
--- a/server/cmd/multica/cmd_setup_test.go
+++ b/server/cmd/multica/cmd_setup_test.go
@@ -1,7 +1,6 @@
package main
import (
- "bytes"
"os"
"path/filepath"
"strings"
@@ -355,40 +354,6 @@ func TestResolveSelfHostAppURL(t *testing.T) {
})
}
-func TestSetupCallbackHostFlagWiring(t *testing.T) {
- cases := []struct {
- name string
- cmd *cobra.Command
- }{
- {name: "setup", cmd: setupCmd},
- {name: "setup cloud", cmd: setupCloudCmd},
- {name: "setup self-host", cmd: setupSelfHostCmd},
- }
-
- for _, tc := range cases {
- tc := tc
- t.Run(tc.name, func(t *testing.T) {
- if tc.cmd.Flag(callbackHostFlag) == nil {
- t.Fatalf("%s is missing --%s", tc.name, callbackHostFlag)
- }
- })
- }
-}
-
-func TestSetupHelpShowsCallbackHostFlag(t *testing.T) {
- var out bytes.Buffer
- setupCmd.SetOut(&out)
- setupCmd.SetErr(&out)
- defer setupCmd.SetOut(nil)
- defer setupCmd.SetErr(nil)
- if err := setupCmd.Help(); err != nil {
- t.Fatalf("setup help: %v", err)
- }
- if !strings.Contains(out.String(), "--callback-host") {
- t.Fatalf("setup help should show --%s, got:\n%s", callbackHostFlag, out.String())
- }
-}
-
// TestFormatURLChange covers the setup overwrite prompt: a changed value is
// shown as "old -> new" so the passed --server-url/--app-url is visibly
// received, while an unchanged value renders plain.
diff --git a/server/cmd/multica/cmd_squad_test.go b/server/cmd/multica/cmd_squad_test.go
index 49d82324a9..31ef9c98d0 100644
--- a/server/cmd/multica/cmd_squad_test.go
+++ b/server/cmd/multica/cmd_squad_test.go
@@ -21,21 +21,6 @@ func newSquadMemberSetRoleTestCmd() *cobra.Command {
return cmd
}
-func TestSquadMemberSetRoleCommandIsRegistered(t *testing.T) {
- cmd, _, err := squadMemberCmd.Find([]string{"set-role", "squad-123"})
- if err != nil {
- t.Fatalf("find set-role command: %v", err)
- }
- if cmd == nil || cmd.Name() != "set-role" {
- t.Fatalf("set-role command not registered; got %#v", cmd)
- }
- for _, flag := range []string{"member-id", "member-type", "role", "output"} {
- if cmd.Flags().Lookup(flag) == nil {
- t.Fatalf("set-role command missing --%s flag", flag)
- }
- }
-}
-
func TestRunSquadMemberSetRolePatchesRole(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
diff --git a/server/cmd/multica/cmd_update_test.go b/server/cmd/multica/cmd_update_test.go
index 89d15e32d1..f968796eb1 100644
--- a/server/cmd/multica/cmd_update_test.go
+++ b/server/cmd/multica/cmd_update_test.go
@@ -3,7 +3,6 @@ package main
import (
"strings"
"testing"
- "time"
)
func TestRunUpdateRejectsNonPositiveDownloadTimeout(t *testing.T) {
@@ -16,13 +15,3 @@ func TestRunUpdateRejectsNonPositiveDownloadTimeout(t *testing.T) {
t.Fatalf("runUpdate error = %v, want download timeout validation", err)
}
}
-
-func TestUpdateCommandRegistersDownloadTimeoutFlag(t *testing.T) {
- flag := updateCmd.Flags().Lookup("download-timeout")
- if flag == nil {
- t.Fatal("updateCmd is missing --download-timeout")
- }
- if got := flag.DefValue; got != (120 * time.Second).String() {
- t.Fatalf("--download-timeout default = %q, want %q", got, (120 * time.Second).String())
- }
-}
diff --git a/server/cmd/multica/cmd_workspace_test.go b/server/cmd/multica/cmd_workspace_test.go
index 7c37453267..824ed3ef5e 100644
--- a/server/cmd/multica/cmd_workspace_test.go
+++ b/server/cmd/multica/cmd_workspace_test.go
@@ -688,21 +688,6 @@ func newWorkspaceMemberInviteTestCmd() *cobra.Command {
return cmd
}
-func TestWorkspaceMemberInviteCommandIsRegistered(t *testing.T) {
- cmd, _, err := workspaceMemberCmd.Find([]string{"invite", "[email protected]"})
- if err != nil {
- t.Fatalf("find invite command: %v", err)
- }
- if cmd == nil || cmd.Name() != "invite" {
- t.Fatalf("invite command not registered; got %#v", cmd)
- }
- for _, flag := range []string{"role", "output"} {
- if cmd.Flags().Lookup(flag) == nil {
- t.Fatalf("invite command missing --%s flag", flag)
- }
- }
-}
-
func TestRunWorkspaceMemberInvitePostsInvitation(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("MULTICA_TOKEN", "test-token")
diff --git a/server/cmd/server/channel_media_invariant_test.go b/server/cmd/server/channel_media_invariant_test.go
deleted file mode 100644
index 3e2046fc96..0000000000
--- a/server/cmd/server/channel_media_invariant_test.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package main
-
-import (
- "testing"
-
- "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
- "github.com/multica-ai/multica/server/internal/integrations/lark"
- "github.com/multica-ai/multica/server/internal/service"
-)
-
-// The reconciler's settle delay carries NO correctness weight (the ledger
-// state machine does), but it must dwarf every media/HTTP budget in the
-// pipeline so the reconciler never races a healthy in-flight operation's
-// normal completion. This is the cross-package assertion of that invariant:
-// if any budget grows past a tenth of the settle delay, this test forces the
-// author to re-derive the margin instead of silently eroding it.
-func TestChannelMediaSettleDwarfsEveryPipelineBudget(t *testing.T) {
- budgets := map[string]int64{
- "engine media timeout (download+upload+bind budget)": int64(engine.DefaultMediaTimeout),
- "lark resource download cap": int64(lark.DefaultResourceDownloadTimeout),
- }
- settle := int64(service.ChannelMediaReconcileSettleDelay)
- for name, budget := range budgets {
- if settle < 10*budget {
- t.Fatalf("settle delay %d must be >= 10x %s (%d)", settle, name, budget)
- }
- }
-}
diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.go
index 414bd3d6e2..bfb75b3123 100644
--- a/server/cmd/server/cors_headers_test.go
+++ b/server/cmd/server/cors_headers_test.go
@@ -1,51 +1,65 @@
package main
import (
- "slices"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
- "github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/multica-ai/multica/server/internal/realtime"
)
-// The app advertises its capabilities on the cancel request (#5219). Browsers
-// preflight a custom request header, so an entry missing from AllowedHeaders is
-// not a degraded feature — it is a failed request: the cancel never reaches the
-// server, and the user's prompt is lost in a way no server-side test can see.
-func TestCORSAllowedHeaders_IncludeClientCapabilities(t *testing.T) {
- if !slices.Contains(corsAllowedHeaders, "X-Client-Capabilities") {
- t.Fatalf("X-Client-Capabilities missing from CORS allowed headers: %v", corsAllowedHeaders)
- }
- // Named so the constant and the header travel together: the capability is
- // useless if the header carrying it cannot cross the preflight.
- if protocol.AppCapabilityChatDraftRestoreV1 == "" {
- t.Fatal("AppCapabilityChatDraftRestoreV1 must be a non-empty capability token")
- }
-}
+func TestRouterCORSContract(t *testing.T) {
+ const origin = "https://cors-client.example"
+ t.Setenv("CORS_ALLOWED_ORIGINS", origin)
+ router := NewRouter(nil, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil)
-// Workspace subscription checkout and portal requests use Idempotency-Key to
-// make retries safe. Browsers preflight that custom request header, so omitting
-// it from AllowedHeaders prevents the billing request from reaching the server.
-func TestCORSAllowedHeaders_IncludeIdempotencyKey(t *testing.T) {
- if !slices.Contains(corsAllowedHeaders, "Idempotency-Key") {
- t.Fatalf("Idempotency-Key missing from CORS allowed headers: %v", corsAllowedHeaders)
- }
+ t.Run("preflight accepts browser request headers", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodOptions, "/api/config", nil)
+ req.Header.Set("Origin", origin)
+ req.Header.Set("Access-Control-Request-Method", http.MethodPost)
+ req.Header.Set("Access-Control-Request-Headers", "X-Client-Capabilities, Idempotency-Key")
+ rec := httptest.NewRecorder()
+
+ router.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("preflight status = %d, want %d", rec.Code, http.StatusOK)
+ }
+ for _, want := range []string{"X-Client-Capabilities", "Idempotency-Key"} {
+ if !headerListContains(rec.Header().Get("Access-Control-Allow-Headers"), want) {
+ t.Errorf("Access-Control-Allow-Headers = %q, missing %q", rec.Header().Get("Access-Control-Allow-Headers"), want)
+ }
+ }
+ })
+
+ t.Run("browser can read truncation signals", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health", nil)
+ req.Header.Set("Origin", origin)
+ rec := httptest.NewRecorder()
+
+ router.ServeHTTP(rec, req)
+
+ for _, want := range []string{
+ handler.HeaderCommentsTruncated,
+ handler.HeaderTimelineTruncated,
+ handler.HeaderActiveRunsTruncated,
+ } {
+ if !headerListContains(rec.Header().Get("Access-Control-Expose-Headers"), want) {
+ t.Errorf("Access-Control-Expose-Headers = %q, missing %q", rec.Header().Get("Access-Control-Expose-Headers"), want)
+ }
+ }
+ })
}
-// Timeline, comment-list and active-run reads report defensive hard-cap clamps
-// with custom response headers.
-// Custom response headers are not readable from browser JS unless the server
-// exposes them, and only the CORS-safelisted headers are exposed by default — so
-// an entry missing here is not a degraded signal, it is no signal at all: the
-// header arrives on the wire and the client cannot see it (MUL-5492).
-func TestCORSExposedHeaders_IncludeTruncationSignals(t *testing.T) {
- for _, want := range []string{
- handler.HeaderCommentsTruncated,
- handler.HeaderTimelineTruncated,
- handler.HeaderActiveRunsTruncated,
- } {
- if !slices.Contains(corsExposedHeaders, want) {
- t.Errorf("%s missing from CORS exposed headers: %v", want, corsExposedHeaders)
+func headerListContains(header, want string) bool {
+ for _, value := range strings.Split(header, ",") {
+ if strings.EqualFold(strings.TrimSpace(value), want) {
+ return true
}
}
+ return false
}
diff --git a/server/cmd/server/dbstats_test.go b/server/cmd/server/dbstats_test.go
index 41120100b6..30608180fb 100644
--- a/server/cmd/server/dbstats_test.go
+++ b/server/cmd/server/dbstats_test.go
@@ -41,13 +41,6 @@ func applyPoolSizing(t *testing.T, dbURL string, envMax, envMin string) (max, mi
return cfg.MaxConns, cfg.MinConns
}
-func TestPoolSizing_DefaultsWhenNothingSet(t *testing.T) {
- max, min := applyPoolSizing(t, "postgres://u:p@h/db?sslmode=disable", "", "")
- if max != defaultMaxConns || min != defaultMinConns {
- t.Fatalf("got max=%d min=%d, want %d/%d", max, min, defaultMaxConns, defaultMinConns)
- }
-}
-
func TestPoolSizing_URLParamsHonoredWhenEnvUnset(t *testing.T) {
url := "postgres://u:p@h/db?sslmode=disable&pool_max_conns=40&pool_min_conns=8"
max, min := applyPoolSizing(t, url, "", "")
@@ -100,10 +93,3 @@ func TestPoolSizing_InvalidEnvFallsBackToURLParam(t *testing.T) {
t.Fatalf("invalid env should fall back to URL param; got max=%d, want 40", max)
}
}
-
-func TestPoolSizing_MinClampedToMax(t *testing.T) {
- max, min := applyPoolSizing(t, "postgres://u:p@h/db?sslmode=disable", "10", "50")
- if min > max {
- t.Fatalf("min should be clamped to max; got max=%d min=%d", max, min)
- }
-}
diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.go
index 26c5c3de20..1b120dc765 100644
--- a/server/cmd/server/main_test.go
+++ b/server/cmd/server/main_test.go
@@ -1,15 +1,8 @@
package main
import (
- "bytes"
- "fmt"
- "go/ast"
- "go/parser"
- "go/printer"
- "go/token"
"os"
"strconv"
- "strings"
"syscall"
"testing"
"time"
@@ -175,162 +168,6 @@ func TestNewNamedRedisClient_DisableClientName_InvalidValue(t *testing.T) {
}
}
-// mainSourceFile is parsed by TestMainUsesRouterOwnedBackgroundServices. The
-// test asserts the markers below are actually present so a future move of the
-// background-worker wiring fails loudly instead of vacuously passing on a walk
-// that matched nothing.
-const mainSourceFile = "main.go"
-
-// backgroundServiceConstructors must never be called from main(): they build a
-// TaskService / AutopilotService that the router has not finished wiring.
-var backgroundServiceConstructors = []string{
- "service.NewTaskService",
- "service.NewAutopilotService",
-}
-
-// TestMainUsesRouterOwnedBackgroundServices guards the process wiring behind
-// scheduled Autopilot dispatch and the runtime sweeper: both must take the
-// router's fully wired services off *handler.Handler instead of constructing
-// their own.
-//
-// The router — not NewTaskService — assigns h.TaskService.EmptyClaim. A second
-// TaskService built inside main() therefore has EmptyClaim == nil, and because
-// EmptyClaimCache is deliberately nil-safe the missed invalidation is silent:
-// a scheduled dispatch still delivers the daemon wakeup while the claim path's
-// cached "no queued task" verdict survives, so an idle runtime keeps returning
-// empty claims until EmptyClaimCacheTTL expires.
-//
-// This parses main.go instead of asserting on backgroundServices' return
-// values. A value-level assertion only proves the helper hands back h's fields,
-// which stays true even when main() stops calling it and constructs its own
-// services again — i.e. it cannot fail on the exact regression it names.
-func TestMainUsesRouterOwnedBackgroundServices(t *testing.T) {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, mainSourceFile, nil, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", mainSourceFile, err)
- }
-
- var mainFunc *ast.FuncDecl
- for _, decl := range file.Decls {
- fn, ok := decl.(*ast.FuncDecl)
- if ok && fn.Recv == nil && fn.Name.Name == "main" {
- mainFunc = fn
- break
- }
- }
- if mainFunc == nil || mainFunc.Body == nil {
- t.Fatalf("no func main() with a body found in %s — this guard must be pointed at the real wiring", mainSourceFile)
- }
-
- // Resolve the variable holding the router's *handler.Handler rather than
- // hardcoding "h": the argument identity is the whole point of the guard,
- // and reading it off the NewRouterWithOptions assignment keeps a rename of
- // that variable from silently weakening the check below.
- routerHandlerVar := routerHandlerIdent(mainFunc.Body)
- if routerHandlerVar == "" {
- t.Fatalf("could not find the *handler.Handler result of NewRouterWithOptions in main() — re-point this guard at the current router wiring")
- }
-
- forbidden := make(map[string]bool, len(backgroundServiceConstructors))
- for _, name := range backgroundServiceConstructors {
- forbidden[name] = true
- }
-
- var (
- offenders []string
- badReuse []string
- reusesRouter bool
- registersScheduler bool
- )
- ast.Inspect(mainFunc.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- switch callee := calleeName(call); {
- case forbidden[callee]:
- offenders = append(offenders, fmt.Sprintf("%s at %s", callee, fset.Position(call.Pos())))
- case callee == "backgroundServices":
- // Matching the callee name alone would accept
- // backgroundServices(nil) — which compiles, reuses nothing, and
- // panics at startup. The argument must be the router's handler.
- if len(call.Args) == 1 {
- if arg, ok := call.Args[0].(*ast.Ident); ok && arg.Name == routerHandlerVar {
- reusesRouter = true
- return true
- }
- }
- badReuse = append(badReuse, fmt.Sprintf("%s at %s", exprText(fset, call), fset.Position(call.Pos())))
- case callee == "scheduler.AutopilotScheduleDispatchJob":
- registersScheduler = true
- }
- return true
- })
-
- // Anti-vacuity: the scheduled-dispatch registration is what makes the
- // unwired-service hazard reachable. If it moves out of main(), this test
- // no longer covers the path it claims to and must fail rather than pass.
- if !registersScheduler {
- t.Fatalf("scheduler.AutopilotScheduleDispatchJob is no longer registered in main() — re-point this guard at wherever the schedule job is now wired")
- }
- if len(offenders) > 0 {
- t.Errorf("main() constructs its own background services (%s); take them from the router via backgroundServices(%s) so EmptyClaim and the rest of the router wiring come along", strings.Join(offenders, ", "), routerHandlerVar)
- }
- if len(badReuse) > 0 {
- t.Errorf("main() calls backgroundServices with something other than the router handler %q (%s); background workers must reuse the services the router finished wiring", routerHandlerVar, strings.Join(badReuse, ", "))
- }
- if !reusesRouter {
- t.Errorf("main() no longer calls backgroundServices(%s); background workers must reuse the router-owned TaskService/AutopilotService", routerHandlerVar)
- }
-}
-
-// routerHandlerIdent returns the name of the variable that receives the
-// *handler.Handler from NewRouterWithOptions (the `h` in `r, h := ...`), or ""
-// when that assignment is no longer recognizable.
-func routerHandlerIdent(body *ast.BlockStmt) string {
- var name string
- ast.Inspect(body, func(n ast.Node) bool {
- assign, ok := n.(*ast.AssignStmt)
- if !ok || len(assign.Rhs) != 1 || len(assign.Lhs) != 2 {
- return true
- }
- call, ok := assign.Rhs[0].(*ast.CallExpr)
- if !ok || calleeName(call) != "NewRouterWithOptions" {
- return true
- }
- if ident, ok := assign.Lhs[1].(*ast.Ident); ok {
- name = ident.Name
- return false
- }
- return true
- })
- return name
-}
-
-// exprText renders an expression back to source for error messages.
-func exprText(fset *token.FileSet, expr ast.Expr) string {
- var buf bytes.Buffer
- if err := printer.Fprint(&buf, fset, expr); err != nil {
- return "<unprintable expression>"
- }
- return buf.String()
-}
-
-// calleeName renders a call's target as "pkg.Func" or "Func" for matching.
-func calleeName(call *ast.CallExpr) string {
- switch fn := call.Fun.(type) {
- case *ast.Ident:
- return fn.Name
- case *ast.SelectorExpr:
- if pkg, ok := fn.X.(*ast.Ident); ok {
- return pkg.Name + "." + fn.Sel.Name
- }
- return fn.Sel.Name
- }
- return ""
-}
-
// TestNormalizeServerVersion covers the router-config wiring path (not just
// a hand-set handler.Config field): an unstamped "dev" build must not leak
// into /api/config's server_version, or the Help popover would render
diff --git a/server/cmd/server/notification_mute_group_test.go b/server/cmd/server/notification_mute_group_test.go
index e77192e7d4..d50a6673fb 100644
--- a/server/cmd/server/notification_mute_group_test.go
+++ b/server/cmd/server/notification_mute_group_test.go
@@ -45,15 +45,3 @@ func TestIsNotifMutedGroupSplit(t *testing.T) {
})
}
}
-
-// TestNotifTypeToGroupMentionsIsOwnGroup guards the mapping itself: a future
-// edit that folds `mentioned` back under `comments` should fail here rather
-// than silently reintroduce the coupling.
-func TestNotifTypeToGroupMentionsIsOwnGroup(t *testing.T) {
- if got := notifTypeToGroup["mentioned"]; got != "mentions" {
- t.Fatalf("notifTypeToGroup[mentioned] = %q, want %q", got, "mentions")
- }
- if got := notifTypeToGroup["new_comment"]; got != "comments" {
- t.Fatalf("notifTypeToGroup[new_comment] = %q, want %q", got, "comments")
- }
-}
diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.go
index f512bfd421..97597ba425 100644
--- a/server/cmd/server/runtime_sweeper_test.go
+++ b/server/cmd/server/runtime_sweeper_test.go
@@ -2,7 +2,6 @@ package main
import (
"context"
- "os"
"strings"
"sync"
"testing"
@@ -13,38 +12,6 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// TestRuntimeGCRunsOutsideTheLivenessLoop pins PR1's deployment boundary: GC
-// keeps its existing predicates and budgets, but its seven-day retention scan
-// no longer occupies the 30-second runtime/task loop.
-func TestRuntimeGCRunsOutsideTheLivenessLoop(t *testing.T) {
- if runtimeGCSweepInterval != time.Hour {
- t.Fatalf("runtime GC interval = %s, want 1h", runtimeGCSweepInterval)
- }
-
- source, err := os.ReadFile("runtime_sweeper.go")
- if err != nil {
- t.Fatalf("read runtime_sweeper.go: %v", err)
- }
- start := strings.Index(string(source), "func runRuntimeSweeper(")
- end := strings.Index(string(source), "func runRuntimeGCSweeper(")
- if start < 0 || end <= start {
- t.Fatal("could not isolate runtime sweeper loops")
- }
- if strings.Contains(string(source[start:end]), "gcRuntimes(") {
- t.Fatal("runtime GC is still invoked from the 30-second liveness loop")
- }
-}
-
-// TestRuntimeGCDailyCandidateCapacity prevents an interval or batch-size change
-// from silently reducing the hourly GC worker below its agreed daily capacity.
-func TestRuntimeGCDailyCandidateCapacity(t *testing.T) {
- const wantCandidatesPerDay = 12_000
- got := int(24*time.Hour/runtimeGCSweepInterval) * runtimeGCBatchSize
- if got != wantCandidatesPerDay {
- t.Fatalf("runtime GC candidate capacity = %d/day, want %d/day", got, wantCandidatesPerDay)
- }
-}
-
func TestPeriodicSweepStopsWithItsContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
called := make(chan struct{}, 1)
diff --git a/server/cmd/server/source_context_sweeper_test.go b/server/cmd/server/source_context_sweeper_test.go
index 01be715bf2..e7d83c2eb2 100644
--- a/server/cmd/server/source_context_sweeper_test.go
+++ b/server/cmd/server/source_context_sweeper_test.go
@@ -2,8 +2,6 @@ package main
import (
"context"
- "os"
- "strings"
"sync/atomic"
"testing"
"time"
@@ -92,20 +90,3 @@ func TestSourceContextSweeperStopsWithItsContext(t *testing.T) {
t.Fatal("source context sweeper did not stop with its context")
}
}
-
-// TestRuntimeSweepTickHasNoObjectStoreStage is a regression guard for the
-// reason this sweeper exists (MUL-6555 / MUL-6670): source-context cleanup used
-// to run at the top of the 30s runtime tick, so a slow object store delayed
-// marking runtimes offline and reclaiming their orphaned tasks. Object-store
-// work must stay out of that tick; put it in runSourceContextSweeper instead.
-func TestRuntimeSweepTickHasNoObjectStoreStage(t *testing.T) {
- source, err := os.ReadFile("runtime_sweeper.go")
- if err != nil {
- t.Fatalf("read runtime_sweeper.go: %v", err)
- }
- for _, stage := range []string{"CleanupSourceContextObjectIntents", "CleanupAbandonedSourceContexts"} {
- if strings.Contains(string(source), stage) {
- t.Fatalf("runtime_sweeper.go calls %s; object-store cleanup belongs on runSourceContextSweeper", stage)
- }
- }
-}
diff --git a/server/cmd/server/subscriber_listeners_test.go b/server/cmd/server/subscriber_listeners_test.go
index 5d0e27a348..ebb956d0f1 100644
--- a/server/cmd/server/subscriber_listeners_test.go
+++ b/server/cmd/server/subscriber_listeners_test.go
@@ -391,26 +391,3 @@ func TestSubscriberIssueCreated_AutopilotMapPayload(t *testing.T) {
t.Fatal("expected creator to be subscribed when autopilot publishes map payload")
}
}
-
-// Verify parseUUID is consistent — the local helper should agree with util.MustParseUUID
-// for valid input, and panic on invalid input (the silent-zero behavior was removed
-// after #1661 to prevent silent SQL writes against a zero UUID).
-func TestParseUUIDConsistency(t *testing.T) {
- uuid := "550e8400-e29b-41d4-a716-446655440000"
- local := parseUUID(uuid)
- utilResult := util.MustParseUUID(uuid)
- if local != utilResult {
- t.Fatalf("parseUUID inconsistency: local=%v, util=%v", local, utilResult)
- }
- if !local.Valid {
- t.Fatal("expected valid UUID")
- }
-
- // Invalid input (empty string) must panic now — never silently return a zero UUID.
- defer func() {
- if r := recover(); r == nil {
- t.Fatal("expected parseUUID(\"\") to panic, but it returned normally")
- }
- }()
- _ = parseUUID("")
-}
diff --git a/server/cmd/server/wecom_media_allow_wiring_test.go b/server/cmd/server/wecom_media_allow_wiring_test.go
deleted file mode 100644
index 2e9f9b3605..0000000000
--- a/server/cmd/server/wecom_media_allow_wiring_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package main
-
-import (
- "go/ast"
- "go/parser"
- "go/token"
- "testing"
-)
-
-// routerSourceFile is parsed by TestWecomMediaAllowListIsWiredAtBoot. Kept as
-// a constant so a rename shows up as one failing test rather than a silently
-// skipped guard.
-const routerSourceFile = "router.go"
-
-const wecomMediaAllowEnv = "MULTICA_WECOM_MEDIA_ALLOW_CIDRS"
-
-// TestWecomMediaAllowListIsWiredAtBoot guards the operator switch behind the
-// media guard's allow-list.
-//
-// wecom.SetMediaAllowedPrefixes widens the SSRF guard that stands between a
-// WeCom-supplied URL and the deployment's own network. It shipped once with no
-// production caller at all: the exemption existed, its own doc comment claimed
-// it was "called at boot from MULTICA_WECOM_MEDIA_ALLOW_CIDRS", and nothing
-// read that variable. An operator behind a fake-IP proxy — where every
-// hostname resolves into 198.18.0.0/15 and the guard therefore refuses every
-// download — had the exemption and no way to turn it on.
-//
-// This parses router.go rather than asserting on behaviour, for the same
-// reason TestMainUsesRouterOwnedBackgroundServices does: the regression being
-// guarded is the absence of a call, and no value-level assertion can observe a
-// call that was never made. The allow-list itself lives in unexported package
-// state, so the only thing reachable from here is the wiring.
-func TestWecomMediaAllowListIsWiredAtBoot(t *testing.T) {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, routerSourceFile, nil, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", routerSourceFile, err)
- }
-
- var (
- readsEnv string // position of os.Getenv(wecomMediaAllowEnv)
- appliesIt string // position of wecom.SetMediaAllowedPrefixes(...)
- )
- for _, decl := range file.Decls {
- fn, ok := decl.(*ast.FuncDecl)
- if !ok || fn.Body == nil {
- continue
- }
- // Both must sit in the SAME function. Reading the variable in one
- // place and calling the setter in another is how the two halves drift
- // apart again — e.g. a caller that only ever passes a constant.
- var envHere, applyHere string
- ast.Inspect(fn.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- switch calleeName(call) {
- case "os.Getenv":
- if len(call.Args) == 1 && stringLit(call.Args[0]) == wecomMediaAllowEnv {
- envHere = fset.Position(call.Pos()).String()
- }
- case "wecom.SetMediaAllowedPrefixes":
- applyHere = fset.Position(call.Pos()).String()
- }
- return true
- })
- if envHere != "" && applyHere != "" {
- readsEnv, appliesIt = envHere, applyHere
- break
- }
- if envHere != "" {
- readsEnv = envHere
- }
- if applyHere != "" {
- appliesIt = applyHere
- }
- }
-
- if readsEnv == "" {
- t.Errorf("no os.Getenv(%q) in %s — the media guard's allow-list has no operator switch again",
- wecomMediaAllowEnv, routerSourceFile)
- }
- if appliesIt == "" {
- t.Errorf("no call to wecom.SetMediaAllowedPrefixes in %s — %s is read but never reaches the guard",
- routerSourceFile, wecomMediaAllowEnv)
- }
- if t.Failed() {
- t.FailNow()
- }
-
- // The errors SetMediaAllowedPrefixes returns are the only report an
- // operator gets for a typo'd CIDR. Dropping them on the floor turns a
- // malformed entry into a guard that is silently narrower than the .env
- // says it is.
- if !reportsMalformedCIDRs(fset, file) {
- t.Errorf("the []error from wecom.SetMediaAllowedPrefixes at %s is discarded — a malformed %s entry would be dropped silently",
- appliesIt, wecomMediaAllowEnv)
- }
-}
-
-// reportsMalformedCIDRs reports whether the SetMediaAllowedPrefixes call site
-// consumes the returned errors — ranged over, assigned, or passed on — rather
-// than being used as a bare statement.
-func reportsMalformedCIDRs(fset *token.FileSet, file *ast.File) bool {
- var consumed bool
- ast.Inspect(file, func(n ast.Node) bool {
- if consumed {
- return false
- }
- switch stmt := n.(type) {
- case *ast.ExprStmt:
- // A bare `wecom.SetMediaAllowedPrefixes(...)` throws the errors away.
- if call, ok := stmt.X.(*ast.CallExpr); ok && calleeName(call) == "wecom.SetMediaAllowedPrefixes" {
- return false
- }
- case *ast.RangeStmt:
- if call, ok := stmt.X.(*ast.CallExpr); ok && calleeName(call) == "wecom.SetMediaAllowedPrefixes" {
- consumed = true
- return false
- }
- case *ast.AssignStmt:
- for _, rhs := range stmt.Rhs {
- if call, ok := rhs.(*ast.CallExpr); ok && calleeName(call) == "wecom.SetMediaAllowedPrefixes" {
- consumed = true
- return false
- }
- }
- }
- return true
- })
- return consumed
-}
-
-// stringLit returns the value of a plain string literal, or "".
-func stringLit(e ast.Expr) string {
- lit, ok := e.(*ast.BasicLit)
- if !ok || lit.Kind != token.STRING || len(lit.Value) < 2 {
- return ""
- }
- return lit.Value[1 : len(lit.Value)-1]
-}
diff --git a/server/internal/analytics/client_test.go b/server/internal/analytics/client_test.go
index ef6732ebcd..1bef297f69 100644
--- a/server/internal/analytics/client_test.go
+++ b/server/internal/analytics/client_test.go
@@ -10,12 +10,6 @@ import (
"time"
)
-func TestNoopClient(t *testing.T) {
- c := NoopClient{}
- c.Capture(Event{Name: "foo"})
- c.Close()
-}
-
func TestPostHogClient_Batching(t *testing.T) {
var (
mu sync.Mutex
diff --git a/server/internal/analytics/events_test.go b/server/internal/analytics/events_test.go
index 085ddc64e0..73af9f8608 100644
--- a/server/internal/analytics/events_test.go
+++ b/server/internal/analytics/events_test.go
@@ -24,31 +24,6 @@ func TestFailedEventsUseWillRetry(t *testing.T) {
}
}
-func TestIsMetricsOnly(t *testing.T) {
- // As of MUL-4127, PostHog is retired for server-side product analytics:
- // every server-side event is Prometheus-only and must not ship to PostHog.
- for _, name := range []string{
- // runtime / autopilot execution-lifecycle telemetry
- EventRuntimeRegistered, EventRuntimeReady, EventRuntimeFailed, EventRuntimeOffline,
- EventAutopilotRunStarted, EventAutopilotRunCompleted, EventAutopilotRunFailed,
- // product-behaviour events (now DB + Grafana only)
- EventSignup, EventWorkspaceCreated, EventIssueCreated, EventIssueExecuted,
- EventChatMessageSent, EventTeamInviteSent, EventTeamInviteAccepted,
- EventOnboardingStarted, EventOnboardingQuestionnaireSubmit, EventOnboardingSourceSubmit,
- EventAgentCreated,
- EventOnboardingCompleted, EventCloudWaitlistJoined, EventFeedbackSubmitted,
- EventContactSalesSubmitted, EventSquadCreated, EventAutopilotCreated,
- } {
- if !IsMetricsOnly(name) {
- t.Errorf("IsMetricsOnly(%q) = false, want true (server events stay out of PostHog since MUL-4127)", name)
- }
- }
- // A name that isn't a declared server event is not metrics-only.
- if IsMetricsOnly("$exception") {
- t.Errorf("IsMetricsOnly(%q) = true, want false (frontend-only event)", "$exception")
- }
-}
-
func TestOnboardingSourceSubmittedSetOnlyWhenAnswered(t *testing.T) {
answered := OnboardingSourceSubmitted("u1", []string{"search"}, false, false)
if answered.Properties["source_skipped"] != false {
diff --git a/server/internal/daemon/agent_command_names_test.go b/server/internal/daemon/agent_command_names_test.go
index b326a399b3..8bfeb122c3 100644
--- a/server/internal/daemon/agent_command_names_test.go
+++ b/server/internal/daemon/agent_command_names_test.go
@@ -1,143 +1,14 @@
package daemon
import (
- "go/ast"
- "go/parser"
- "go/token"
"os"
"os/exec"
"path/filepath"
"runtime"
- "sort"
"strings"
"testing"
-
- "github.com/multica-ai/multica/server/pkg/agent"
)
-// TestDefaultAgentCommandNamesCoversAllProbes guards the invariant documented
-// on defaultAgentCommandNames: the shell-fallback resolver only pre-fetches
-// canonical paths for the bare command names in that list, so every agent the
-// probe loop tries must appear there. A GUI/Launchpad-started daemon does not
-// inherit the interactive shell PATH, so an agent missing from this list is
-// undetectable when its binary lives only on the login-shell PATH (e.g. an
-// `npm install -g` global). This test parses the probe(...) calls so a new
-// probe can't silently diverge from the fallback list.
-//
-// It parses agents_probe.go, which is where probeAgentCLIs now lives. It used
-// to parse config.go and silently degraded into a no-op when the probe loop
-// moved out of that file — which is how the missing "qodercli" entry survived
-// (MUL-5524). probeSourceFile is asserted to actually contain probe() calls so
-// a future move fails loudly instead of vacuously passing.
-const probeSourceFile = "agents_probe.go"
-
-func TestDefaultAgentCommandNamesCoversAllProbes(t *testing.T) {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, probeSourceFile, nil, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", probeSourceFile, err)
- }
-
- known := make(map[string]bool, len(defaultAgentCommandNames))
- for _, name := range defaultAgentCommandNames {
- known[name] = true
- }
-
- var missing []string
- var probeCalls int
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- ident, ok := call.Fun.(*ast.Ident)
- if !ok || ident.Name != "probe" {
- return true
- }
- // probe(envPathVar, commandName, envModelVar): the command name is the
- // second argument and is the value pre-fetched by the shell fallback.
- if len(call.Args) < 2 {
- return true
- }
- lit, ok := call.Args[1].(*ast.BasicLit)
- if !ok || lit.Kind != token.STRING {
- return true
- }
- probeCalls++
- name := lit.Value
- if len(name) >= 2 {
- name = name[1 : len(name)-1] // strip surrounding quotes
- }
- if !known[name] {
- missing = append(missing, name)
- }
- return true
- })
-
- // Without this the whole test passes vacuously the moment probeAgentCLIs
- // moves to another file, which is exactly how this guard failed before.
- // Built-in runtime identities (from agent.BuiltinRuntimes) are probed in
- // a loop, not with literal probe() calls, so their command names are
- // counted from the descriptor, not the AST.
- descriptorProbes := len(agent.BuiltinRuntimes)
- if probeCalls+descriptorProbes < len(defaultAgentCommandNames) {
- t.Fatalf("found only %d probe() call(s) (%d literal + %d from descriptor) in %s, "+
- "expected at least %d (one per default agent command); "+
- "did the probe loop move, or is a provider probed without probe()?",
- probeCalls+descriptorProbes, probeCalls, descriptorProbes, probeSourceFile, len(defaultAgentCommandNames))
- }
-
- // Also verify that built-in runtime descriptor commands are covered.
- for _, desc := range agent.BuiltinRuntimes {
- if !known[desc.DefaultCommand] {
- missing = append(missing, desc.DefaultCommand)
- }
- }
-
- if len(missing) > 0 {
- sort.Strings(missing)
- t.Fatalf("probe() command names missing from defaultAgentCommandNames: %v; "+
- "add them so GUI-launched daemons can resolve these agents via the login shell", missing)
- }
-}
-
-func TestAgentCLIGuardCoversDefaultCommands(t *testing.T) {
- data, err := os.ReadFile(filepath.Join("..", "..", "..", "scripts", "agent-cli-command-names.txt"))
- if err != nil {
- t.Fatalf("read agent CLI guard names: %v", err)
- }
- guarded := map[string]bool{}
- for lineNumber, line := range strings.Split(string(data), "\n") {
- if line != strings.TrimSpace(line) {
- t.Fatalf("agent CLI guard name on line %d has surrounding whitespace", lineNumber+1)
- }
- if line != "" && !strings.HasPrefix(line, "#") {
- if !isSafeAgentCLICommandName(line) {
- t.Fatalf("agent CLI guard name on line %d contains unsafe characters: %q", lineNumber+1, line)
- }
- guarded[line] = true
- }
- }
- for _, name := range defaultAgentCommandNames {
- if !guarded[name] {
- t.Errorf("default agent command %q is not covered by the test guard", name)
- }
- }
-}
-
-func isSafeAgentCLICommandName(name string) bool {
- for _, char := range name {
- if (char >= 'a' && char <= 'z') ||
- (char >= 'A' && char <= 'Z') ||
- (char >= '0' && char <= '9') ||
- char == '.' || char == '_' || char == '-' {
- continue
- }
- return false
- }
- return name != ""
-}
-
func TestAgentCLIGuardDetectsSwallowedFailure(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("the full guarded backend suite runs on Linux/macOS")
diff --git a/server/internal/daemon/agents_probe_qoder_test.go b/server/internal/daemon/agents_probe_qoder_test.go
index 55d318da3b..07da4fcbf6 100644
--- a/server/internal/daemon/agents_probe_qoder_test.go
+++ b/server/internal/daemon/agents_probe_qoder_test.go
@@ -87,20 +87,3 @@ func TestProbeAgentCLIs_QoderPinnedPathStaysHardMiss(t *testing.T) {
t.Errorf("pinned-but-missing MULTICA_QODER_PATH resolved to %q, want a hard miss", entry.Path)
}
}
-
-// TestDefaultAgentCommandNamesIncludesQoder guards the other half of the same
-// bug: cachedShellResolvedAgents only asks the login shell about the names in
-// defaultAgentCommandNames, so omitting "qodercli" would leave the fallback
-// permanently blind to Qoder even once the probe consults it.
-func TestDefaultAgentCommandNamesIncludesQoder(t *testing.T) {
- found := map[string]bool{}
- for _, name := range defaultAgentCommandNames {
- found[name] = true
- }
- for _, name := range []string{"qodercli", "qoderclicn"} {
- if !found[name] {
- t.Fatalf("defaultAgentCommandNames is missing %q; the login-shell resolver "+
- "only pre-fetches names in that list, so Qoder stays undetectable on a GUI-launched daemon", name)
- }
- }
-}
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index b20846f227..a94fca52c3 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -441,21 +441,6 @@ func TestPostJSONWithRetry_CtxCancelStopsRetries(t *testing.T) {
}
}
-func TestDefaultTerminalRetrySchedule_MatchesAgreedPlan(t *testing.T) {
- // MUL-2780 settled on a 5-step exponential backoff (4s, 8s, 16s, 32s, 64s).
- // Pin it so a future "tidy this up" refactor can't silently flatten or
- // shorten the recovery window without explicit discussion.
- want := []time.Duration{4 * time.Second, 8 * time.Second, 16 * time.Second, 32 * time.Second, 64 * time.Second}
- if len(defaultTerminalRetrySchedule) != len(want) {
- t.Fatalf("schedule length: got %d, want %d", len(defaultTerminalRetrySchedule), len(want))
- }
- for i, d := range want {
- if defaultTerminalRetrySchedule[i] != d {
- t.Errorf("schedule[%d]: got %s, want %s", i, defaultTerminalRetrySchedule[i], d)
- }
- }
-}
-
func TestNormalizeGOOS(t *testing.T) {
cases := map[string]string{
"darwin": "macos",
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 52bf0e0c63..c6bde47f27 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -106,12 +106,6 @@ func TestPatternsFromEnv_DefaultsWhenUnset(t *testing.T) {
}
}
-func TestDefaultGCIntervalIsTwoHours(t *testing.T) {
- if DefaultGCInterval != 2*time.Hour {
- t.Fatalf("DefaultGCInterval = %s, want 2h", DefaultGCInterval)
- }
-}
-
// A localhost server URL is not the official cloud host, so this exercises the
// self-host branch of defaultGCCompletedTaskTTL: retention stays unbounded until
// an operator opts in, and a daemon upgrade never starts deleting on its own.
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 2ffb727c80..fb2b3b72cc 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2162,20 +2162,6 @@ func TestGatePiResumeDropsUnusableSessionFile(t *testing.T) {
}
}
-func TestProviderUsesPiSessionFileFollowsBuiltinRuntimeDescriptors(t *testing.T) {
- t.Parallel()
-
- if !providerUsesPiSessionFile("pi") {
- t.Fatal("pi protocol family did not use Pi session-file reachability")
- }
- for _, desc := range agent.BuiltinRuntimes {
- want := desc.ProtocolFamily == "pi"
- if got := providerUsesPiSessionFile(desc.ID); got != want {
- t.Errorf("providerUsesPiSessionFile(%q) = %v, want %v for protocol family %q", desc.ID, got, want, desc.ProtocolFamily)
- }
- }
-}
-
func TestSessionHomeReachable(t *testing.T) {
t.Parallel()
@@ -4177,17 +4163,6 @@ type reportTaskResultRecorder struct {
payload map[string]any
}
-func TestTerminalTaskReportTimeoutCoversRetrySchedule(t *testing.T) {
- client := NewClient("http://example.invalid")
- worstCase := time.Duration(len(defaultTerminalRetrySchedule)+1) * client.client.Timeout
- for _, delay := range defaultTerminalRetrySchedule {
- worstCase += delay
- }
- if terminalTaskReportTimeout < worstCase {
- t.Fatalf("terminal report timeout = %s, want at least retry worst case %s", terminalTaskReportTimeout, worstCase)
- }
-}
-
func (r *reportTaskResultRecorder) handler(t *testing.T) http.HandlerFunc {
t.Helper()
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
diff --git a/server/internal/daemon/execenv/openclaw_config_timeout_test.go b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
index 0f0fa3f33b..a2b830a2ea 100644
--- a/server/internal/daemon/execenv/openclaw_config_timeout_test.go
+++ b/server/internal/daemon/execenv/openclaw_config_timeout_test.go
@@ -18,25 +18,6 @@ import (
// deadline must tolerate, not a target.
const slowestMeasuredOpenclawCall = 10860 * time.Millisecond
-// TestOpenclawCLIDefaultTimeoutCoversMeasuredSlowHosts is the regression for
-// the reported bug. The old 5s default was written against an assumed <200ms
-// CLI; the reporter's host needs twice that budget for a single call, every
-// time, and had no way to raise it — so the OpenClaw runtime was unusable
-// there. Anything that lowers this default back under the measured range
-// re-breaks that host.
-func TestOpenclawCLIDefaultTimeoutCoversMeasuredSlowHosts(t *testing.T) {
- if openclawCLITimeout <= slowestMeasuredOpenclawCall {
- t.Errorf("default openclaw CLI timeout %v must exceed the slowest measured call %v (#7112)",
- openclawCLITimeout, slowestMeasuredOpenclawCall)
- }
- // Headroom, not a bare pass: a host at the measured worst case should not
- // sit one scheduling hiccup away from failing again.
- if openclawCLITimeout < 2*slowestMeasuredOpenclawCall {
- t.Errorf("default openclaw CLI timeout %v leaves less than 2x headroom over %v",
- openclawCLITimeout, slowestMeasuredOpenclawCall)
- }
-}
-
func TestResolveOpenclawCLITimeout(t *testing.T) {
cases := []struct {
name string
@@ -163,31 +144,6 @@ func TestExecOpenclawCLICancellationIsNotATimeout(t *testing.T) {
}
}
-// TestOpenclawCLIMaxTimeoutFitsPreparationBudget is the arithmetic the
-// override ceiling rests on. Each preparation *step* gets its own deadline, so
-// the budget that matters is worst-case-deadlines x ceiling, and it has to stay
-// under the daemon's 5-minute task preparation deadline with room for the rest
-// of Prepare (repo checkout, skills, context files). Otherwise a user who raises
-// the timeout turns a specific, non-retryable CLI timeout back into the
-// generic — and retryable — prepare timeout, which is the failure mode this
-// change set out to remove.
-func TestOpenclawCLIMaxTimeoutFitsPreparationBudget(t *testing.T) {
- // Mirrors daemon.defaultTaskPrepareTimeout, which execenv cannot import
- // (the daemon imports this package, not the other way round).
- const taskPrepareBudget = 5 * time.Minute
- // Everything Prepare does besides openclaw config discovery.
- const nonOpenclawPrepareSlack = time.Minute
-
- worst := openclawMaxCLIDeadlinesPerPreparation * openclawCLIMaxTimeout
- if worst+nonOpenclawPrepareSlack > taskPrepareBudget {
- t.Errorf("worst-case openclaw discovery %v (%d deadlines x %v) leaves less than %v under the %v preparation budget",
- worst, openclawMaxCLIDeadlinesPerPreparation, openclawCLIMaxTimeout, nonOpenclawPrepareSlack, taskPrepareBudget)
- }
- if openclawCLITimeout > openclawCLIMaxTimeout {
- t.Errorf("default %v exceeds the override ceiling %v", openclawCLITimeout, openclawCLIMaxTimeout)
- }
-}
-
// TestOpenclawActiveConfigPathSpendsOneBudgetAcrossBothAttempts is the
// consequence of sharing that deadline, asserted rather than left implicit.
//
diff --git a/server/internal/daemon/execenv/runtime_config_channel_context_test.go b/server/internal/daemon/execenv/runtime_config_channel_context_test.go
index 24028f16b4..cbfd124871 100644
--- a/server/internal/daemon/execenv/runtime_config_channel_context_test.go
+++ b/server/internal/daemon/execenv/runtime_config_channel_context_test.go
@@ -1,7 +1,6 @@
package execenv
import (
- "reflect"
"strings"
"testing"
)
@@ -37,17 +36,6 @@ func TestBriefChatWorkflowDoesNotAssertAudience(t *testing.T) {
}
}
-// This structural guard prevents a future caller from quietly threading the
-// room discriminator back into the cached brief. ChatType remains on daemon.Task
-// for BuildPrompt, but the execenv context cannot consume it.
-func TestBriefContextExcludesChatType(t *testing.T) {
- t.Parallel()
-
- if _, ok := reflect.TypeOf(TaskContextForEnv{}).FieldByName("ChatType"); ok {
- t.Fatal("TaskContextForEnv must not carry ChatType; audience is per-turn context")
- }
-}
-
func TestAudienceOf(t *testing.T) {
t.Parallel()
diff --git a/server/internal/daemon/task_log_correlation_test.go b/server/internal/daemon/task_log_correlation_test.go
index 063626699c..03234c5ec8 100644
--- a/server/internal/daemon/task_log_correlation_test.go
+++ b/server/internal/daemon/task_log_correlation_test.go
@@ -3,13 +3,9 @@ package daemon
import (
"bytes"
"context"
- "go/ast"
- "go/parser"
- "go/token"
"log/slog"
"net/http"
"net/http/httptest"
- "os"
"regexp"
"strings"
"sync"
@@ -184,72 +180,3 @@ func TestHandleTask_UntrackedRuntimeLogsFullTaskID(t *testing.T) {
t.Errorf("runtime-offline warning did not carry the full task id; logs:\n%s", out)
}
}
-
-// taskLogSourceFiles are the package sources the structural guard below reads.
-// Asserting a call count against them keeps a rename or a file move from
-// turning the guard into a vacuous pass (the failure mode MUL-5524 hit).
-const minTaskLogCalls = 20
-
-// TestTaskLogCallsDoNotRepeatTheBoundTaskField is the structural half of the
-// one-line-one-`task=` rule above. The behavioural test can only see the lines
-// its own code path emits; most `taskLog` calls live deep inside runTask,
-// behind a real agent process. This reads the package source instead and fails
-// on any `taskLog.<Level>(...)` that passes a literal "task" key — by
-// convention in this package `taskLog` is always the logger handleTask bound
-// the full task id to, so such an argument can only be a duplicate.
-//
-// A string literal "task" can never be a *value* in these calls, so matching
-// the literal anywhere in the argument list needs no position arithmetic.
-func TestTaskLogCallsDoNotRepeatTheBoundTaskField(t *testing.T) {
- t.Parallel()
-
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatalf("read package dir: %v", err)
- }
-
- fset := token.NewFileSet()
- var calls int
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
- continue
- }
- file, err := parser.ParseFile(fset, name, nil, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", name, err)
- }
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return true
- }
- recv, ok := sel.X.(*ast.Ident)
- if !ok || recv.Name != "taskLog" {
- return true
- }
- switch sel.Sel.Name {
- case "Debug", "Info", "Warn", "Error":
- default:
- return true
- }
- calls++
- for _, arg := range call.Args {
- lit, ok := arg.(*ast.BasicLit)
- if !ok || lit.Kind != token.STRING || lit.Value != `"task"` {
- continue
- }
- t.Errorf("%s: taskLog call passes a \"task\" field it is already bound to — the id would print twice on that line", fset.Position(call.Pos()))
- }
- return true
- })
- }
-
- if calls < minTaskLogCalls {
- t.Fatalf("found only %d taskLog logging calls, want >= %d — the scan stopped matching (renamed logger? moved file?) and would pass vacuously", calls, minTaskLogCalls)
- }
-}
diff --git a/server/internal/events/bus_test.go b/server/internal/events/bus_test.go
index 5ccb3f1aaa..1cb84524fc 100644
--- a/server/internal/events/bus_test.go
+++ b/server/internal/events/bus_test.go
@@ -117,30 +117,3 @@ func TestSubscribeAllPanicRecovery(t *testing.T) {
t.Fatal("second global handler was not called after first panicked")
}
}
-
-func TestEventFieldsPassedThrough(t *testing.T) {
- bus := New()
- var received Event
-
- bus.Subscribe("test:fields", func(e Event) {
- received = e
- })
-
- bus.Publish(Event{
- Type: "test:fields",
- WorkspaceID: "ws-123",
- ActorType: "member",
- ActorID: "user-456",
- Payload: map[string]string{"key": "value"},
- })
-
- if received.WorkspaceID != "ws-123" {
- t.Errorf("expected WorkspaceID ws-123, got %s", received.WorkspaceID)
- }
- if received.ActorType != "member" {
- t.Errorf("expected ActorType member, got %s", received.ActorType)
- }
- if received.ActorID != "user-456" {
- t.Errorf("expected ActorID user-456, got %s", received.ActorID)
- }
-}
diff --git a/server/internal/featureflags/keys_test.go b/server/internal/featureflags/keys_test.go
deleted file mode 100644
index eead10ff59..0000000000
--- a/server/internal/featureflags/keys_test.go
+++ /dev/null
@@ -1,73 +0,0 @@
-package featureflags
-
-import (
- "context"
- "testing"
-)
-
-func TestResourceLabelsCompatDecisionStaysEnabled(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if !flags[resourceLabelsCompat] {
- t.Fatal("resource labels must stay enabled for installed clients")
- }
-}
-
-// MUL-5345: hang stack capture is gone from this build, but v0.4.13–v0.4.18 are
-// installed and still hold a debugger channel open on every renderer whenever
-// this key arrives as `true`. Those clients are fail-closed on absence, so NOT
-// publishing the key is what disarms them — re-adding it would put a flag flip
-// back within reach of a fleet that can no longer produce a usable stack.
-func TestDesktopHangStackCaptureIsNotPublished(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if _, published := flags["desktop_hang_stack_capture"]; published {
- t.Fatal("hang stack capture must stay unpublished so installed clients keep their debugger channels closed")
- }
-}
-
-func TestAgentBuilderCompatDecisionStaysEnabled(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if !flags[agentBuilderCompat] {
- t.Fatal("agent builder must stay enabled for installed clients")
- }
-}
-
-func TestAgentSkillTogglesCompatDecisionStaysEnabled(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if !flags[agentSkillTogglesCompat] {
- t.Fatal("agent skill toggles must stay enabled for installed v0.4.0 clients")
- }
-}
-
-// MUL-6643: the server-side rollout gate on creating a custom status is gone,
-// but the key stays unpublished on purpose. v0.4.30 shipped the feature without
-// the four fixes that landed in v0.4.31 — custom-status cards render in the
-// wrong board column (MUL-6409), the timeline glyph loses the status identity
-// (MUL-6413), built-in colors are wrong (MUL-6440), and the catalog does not
-// sync over the realtime channel (MUL-6458). Those clients gate their "New
-// status" button on this key and fail closed on absence, so NOT publishing it
-// is what keeps a client that cannot render the result from producing one.
-//
-// Clients from v0.4.33 read no flag at all, so they get the button the moment
-// they update — the key never has to be published again.
-func TestCustomIssueStatusesIsNotPublished(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if _, published := flags["custom_issue_statuses"]; published {
- t.Fatal("custom_issue_statuses must stay unpublished so pre-v0.4.33 clients keep creation hidden")
- }
-}
-
-func TestPluginsV1DefaultsOff(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- if flags[PluginsV1] {
- t.Fatal("plugins_v1 must stay disabled unless explicitly enabled")
- }
-}
-
-func TestPluginSubFlagsAreNotPublished(t *testing.T) {
- flags := EvaluateFrontendPublicFlags(context.Background(), nil)
- for _, retired := range []string{"private_plugins_v1", "remote_mcp_plugins_v1"} {
- if _, published := flags[retired]; published {
- t.Fatalf("retired Plugin sub-flag %q must not be published", retired)
- }
- }
-}
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index c499078849..5f37a4dbd4 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -17,18 +17,6 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-func TestAgentBuilderInstructionsConstrainModelsToRuntimeCatalog(t *testing.T) {
- for _, requirement := range []string{
- "AVAILABLE RUNTIME MODELS",
- "Never use a model label as the id",
- "never invent a model id",
- } {
- if !strings.Contains(agentBuilderInstructions, requirement) {
- t.Fatalf("agent builder instructions missing model constraint %q", requirement)
- }
- }
-}
-
func TestCreateAgentBuilderSessionCreatesIsolatedHiddenBuilder(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.go
index 2c6a2c9869..89432f81bf 100644
--- a/server/internal/handler/agent_test.go
+++ b/server/internal/handler/agent_test.go
@@ -1347,23 +1347,6 @@ func TestMergeAgentEnv_PureFunction(t *testing.T) {
}
}
-// Compile-time guard: AgentResponse must NOT carry the legacy env
-// fields. Reintroducing them is a security regression — this test
-// fails to compile rather than fails at runtime so reviewers see the
-// breakage in the diff. Kept as a runtime test because the package
-// boundary makes a struct-tag introspection cheap and obvious.
-func TestAgentResponseShape_HasNoLegacyEnvFields(t *testing.T) {
- typ := reflect.TypeOf(AgentResponse{})
- for i := 0; i < typ.NumField(); i++ {
- f := typ.Field(i)
- tag := strings.Split(f.Tag.Get("json"), ",")[0]
- switch tag {
- case "custom_env", "custom_env_redacted", "custom_env_redacted_reason":
- t.Errorf("AgentResponse must not carry %q field (MUL-2600)", tag)
- }
- }
-}
-
// TestUpdateAgent_RedactsMcpConfigForAgentActor closes the second leg
// of MUL-2600 review #2: an agent process with a task token (or with
// the X-Actor-Source server marker) must not be able to scrape another
diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.go
index bc01edd751..ce6c3ee3a4 100644
--- a/server/internal/handler/autopilot_webhook_handler_test.go
+++ b/server/internal/handler/autopilot_webhook_handler_test.go
@@ -951,26 +951,6 @@ func TestWebhookHandler_AbsoluteIPRateLimitRetainsEmergencyCeiling(t *testing.T)
}
}
-func TestWebhookHandler_DBErrorOnTokenLookupReturns500(t *testing.T) {
- // Inject a fake Queries-like wrapper via a shadow type isn't simple
- // here because Handler.Queries is a *db.Queries struct, not an
- // interface. Instead, simulate the path by deleting the trigger row
- // out from under a known-valid token AND swapping in a stub limiter
- // that always allows. The handler will then call
- // GetWebhookTriggerByToken with a non-existent value → pgx.ErrNoRows
- // → 404. So this test alone can't drive the 500 branch without
- // breaking the DB connection. The 500 branch is exercised via the
- // unit tests in this package's TestRedactWebhookPath /
- // TestRequestLogger_*; we leave a regression marker here so a future
- // refactor that collapses ErrNoRows into 500 (or vice versa) is
- // caught by a code review rather than a missing test.
- //
- // The real verification for this branch is: the file diff for
- // autopilot_webhook.go must show `errors.Is(err, pgx.ErrNoRows)` —
- // see PR #2348 review item Blocking #2.
- t.Skip("500-branch requires injecting a stub Queries; left as a code-review-protected invariant")
-}
-
func TestCreateAutopilotTrigger_RejectsAPIKind(t *testing.T) {
agentID := createWebhookTestAgent(t, "WebhookAPIKind Agent")
apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
diff --git a/server/internal/handler/autopilot_webhook_test.go b/server/internal/handler/autopilot_webhook_test.go
index 9c2c94e2f0..d79f48097f 100644
--- a/server/internal/handler/autopilot_webhook_test.go
+++ b/server/internal/handler/autopilot_webhook_test.go
@@ -23,20 +23,6 @@ func TestGenerateWebhookToken_PrefixAndLength(t *testing.T) {
}
}
-func TestGenerateWebhookToken_Uniqueness(t *testing.T) {
- seen := make(map[string]struct{}, 128)
- for i := 0; i < 128; i++ {
- token, err := generateWebhookToken()
- if err != nil {
- t.Fatalf("generateWebhookToken: %v", err)
- }
- if _, dup := seen[token]; dup {
- t.Fatalf("duplicate token after %d generations: %q", i, token)
- }
- seen[token] = struct{}{}
- }
-}
-
func TestGenerateWebhookToken_NoUnsafeURLChars(t *testing.T) {
token, err := generateWebhookToken()
if err != nil {
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index 85c7c57cfb..7748cc1fe1 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -449,10 +449,20 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {
if !cfg.FeatureFlags["settings_resource_labels"] {
t.Fatalf("settings_resource_labels: want true for installed clients, got false")
}
+ if !cfg.FeatureFlags["agents_agent_builder"] {
+ t.Fatalf("agents_agent_builder: want true for installed clients, got false")
+ }
+ // MUL-5345: hang stack capture is gone from this build, but v0.4.13–v0.4.18 are
+ // installed and still hold a debugger channel open on every renderer whenever
+ // this key arrives as `true`. Those clients are fail-closed on absence, so NOT
+ // publishing the key is what disarms them — re-adding it would put a flag flip
+ // back within reach of a fleet that can no longer produce a usable stack.
+ if _, published := cfg.FeatureFlags["desktop_hang_stack_capture"]; published {
+ t.Fatalf("desktop_hang_stack_capture: must stay unpublished so installed clients keep their debugger channels closed")
+ }
// Deliberately unpublished: pre-v0.4.33 clients gate their "New status"
// button on this key and fail closed, which is how a client that predates
- // the v0.4.31 rendering fixes is kept from creating one. See
- // featureflags.TestCustomIssueStatusesIsNotPublished.
+ // the v0.4.31 rendering fixes is kept from creating one.
if _, published := cfg.FeatureFlags["custom_issue_statuses"]; published {
t.Fatalf("custom_issue_statuses: want unpublished, got %v", cfg.FeatureFlags["custom_issue_statuses"])
}
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index 0bf8559a75..a3d67743b2 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
- "log/slog"
"net/http"
"net/http/httptest"
"strings"
@@ -27,29 +26,6 @@ import (
"github.com/multica-ai/multica/server/pkg/remotemcp"
)
-func TestLogClaimEndpointSlowIncludesPayloadFields(t *testing.T) {
- var logs bytes.Buffer
- prev := slog.Default()
- slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))
- t.Cleanup(func() { slog.SetDefault(prev) })
-
- logClaimEndpointSlow("runtime-1", "claimed", time.Now().Add(-600*time.Millisecond), 10, 20, 30, 4096, 2, 8, 3072)
-
- got := logs.String()
- for _, want := range []string{
- "msg=\"claim_endpoint slow\"",
- "runtime_id=runtime-1",
- "payload_bytes=4096",
- "agent_skill_count=2",
- "builtin_skill_count=8",
- "skill_payload_bytes=3072",
- } {
- if !strings.Contains(got, want) {
- t.Fatalf("slow claim log missing %q in %s", want, got)
- }
- }
-}
-
// slowProbeLocalSkillListStore wraps a LocalSkillListStore but blocks inside
// HasPending until the provided context is cancelled. PopPending delegates
// to the underlying store. Used to verify that a stalled probe cannot wedge
diff --git a/server/internal/handler/invitation_test.go b/server/internal/handler/invitation_test.go
index 0643c87467..c8221dee83 100644
--- a/server/internal/handler/invitation_test.go
+++ b/server/internal/handler/invitation_test.go
@@ -73,14 +73,6 @@ func useSeatCapacity(t *testing.T, executor seatcapacity.Executor) {
})
}
-func TestDefaultInvitationRateLimits(t *testing.T) {
- limits := DefaultInvitationRateLimits()
- want := SlidingWindowRateLimit{Limit: 6, Window: 24 * time.Hour}
- if limits.Recipient != want {
- t.Fatalf("recipient limit = %+v, want %+v", limits.Recipient, want)
- }
-}
-
type stubInvitationRateLimiter struct {
allowed bool
allowResult *bool
diff --git a/server/internal/handler/mika_onboarding_opening_test.go b/server/internal/handler/mika_onboarding_opening_test.go
index 11a3de8530..0627367a03 100644
--- a/server/internal/handler/mika_onboarding_opening_test.go
+++ b/server/internal/handler/mika_onboarding_opening_test.go
@@ -76,27 +76,3 @@ func TestEscapeMarkdownInlineHandlesBackslashesFirst(t *testing.T) {
t.Fatalf("escapeMarkdownInline(`a\\*b`) = %q, want %q", got, `a\\\*b`)
}
}
-
-// The opening is the member's introduction to the working model, so all four
-// beats have to survive a copy edit: what Multica is, who Mika is, what happens
-// next, and the handoff to the starter cards below.
-func TestMikaOnboardingOpeningKeepsItsFourBeats(t *testing.T) {
- opening := buildMikaOnboardingOpening("en", "Mika", "Venus")
-
- for _, beat := range []string{
- "Multica is a workspace", // what the product is
- "Chief of Staff", // who is speaking
- "turn it into an issue", // what happens next
- "Pick one below", // the bridge to the cards
- } {
- if !strings.Contains(opening, beat) {
- t.Errorf("opening lost a required beat (%q):\n%s", beat, opening)
- }
- }
-
- // The cards below name the options; a written menu duplicates them and
- // costs the member a retype where a click would do.
- if strings.Count(opening, "\n-") > 0 {
- t.Errorf("the opening must not list options — that is the cards' job:\n%s", opening)
- }
-}
diff --git a/server/internal/handler/runtime_liveness_store_test.go b/server/internal/handler/runtime_liveness_store_test.go
index d36fd27329..49b24310af 100644
--- a/server/internal/handler/runtime_liveness_store_test.go
+++ b/server/internal/handler/runtime_liveness_store_test.go
@@ -6,22 +6,6 @@ import (
"time"
)
-func TestNoopLivenessStore_AlwaysUnavailable(t *testing.T) {
- s := NewNoopLivenessStore()
- if s.Available() {
- t.Fatal("noop store reported Available()=true")
- }
- if err := s.Touch(context.Background(), "rt-1", time.Second); err != nil {
- t.Fatalf("noop Touch returned error: %v", err)
- }
- alive, ok := s.IsAliveBatch(context.Background(), []string{"rt-1"})
- if ok {
- t.Fatalf("noop IsAliveBatch returned ok=true with alive=%v", alive)
- }
- // Forget on the noop must not panic.
- s.Forget(context.Background(), "rt-1")
-}
-
func TestRedisLivenessStore_TouchAndIsAlive(t *testing.T) {
rdb := newRedisTestClient(t)
ctx := context.Background()
diff --git a/server/internal/handler/runtime_model_catalog_test.go b/server/internal/handler/runtime_model_catalog_test.go
index 01df6ec08e..0e5655615c 100644
--- a/server/internal/handler/runtime_model_catalog_test.go
+++ b/server/internal/handler/runtime_model_catalog_test.go
@@ -2,7 +2,6 @@ package handler
import (
"context"
- "encoding/json"
"errors"
"sync"
"testing"
@@ -403,70 +402,6 @@ func TestCacheableModelCatalog(t *testing.T) {
}
}
-// TestCachedModelListResponse_WireShape pins what a cache hit looks like on the
-// wire. Existing clients only branch on status/models, so the response must be
-// indistinguishable from a completed live discovery apart from the additive
-// `cached` marker.
-func TestCachedModelListResponse_WireShape(t *testing.T) {
- storedAt := time.Now().Add(-2 * time.Minute)
- resp := &ModelListRequest{
- ID: randomID(),
- RuntimeID: "rt-1",
- Status: ModelListCompleted,
- Models: sampleCatalog(),
- Supported: true,
- CreatedAt: storedAt,
- UpdatedAt: storedAt,
- Cached: true,
- CachedAt: &storedAt,
- }
- raw, err := json.Marshal(resp)
- if err != nil {
- t.Fatalf("marshal: %v", err)
- }
-
- var decoded struct {
- ID string `json:"id"`
- Status ModelListStatus `json:"status"`
- Models []ModelEntry `json:"models"`
- Supported bool `json:"supported"`
- Cached bool `json:"cached"`
- CachedAt *time.Time `json:"cached_at"`
- }
- if err := json.Unmarshal(raw, &decoded); err != nil {
- t.Fatalf("unmarshal: %v", err)
- }
- if decoded.Status != ModelListCompleted {
- t.Fatalf("status = %q, want completed so clients stop polling", decoded.Status)
- }
- if decoded.ID == "" {
- t.Error("a cache hit still needs a request id for client-side bookkeeping")
- }
- if len(decoded.Models) != 2 || !decoded.Supported {
- t.Fatalf("cache hit must carry the catalog: %+v supported=%v", decoded.Models, decoded.Supported)
- }
- if !decoded.Cached || decoded.CachedAt == nil {
- t.Fatalf("cache hit must be marked: cached=%v cached_at=%v", decoded.Cached, decoded.CachedAt)
- }
-
- // A live (non-cached) response must not carry the markers at all, so older
- // clients see exactly the previous payload.
- live, err := json.Marshal(&ModelListRequest{ID: "x", RuntimeID: "rt-1", Status: ModelListPending, Supported: true})
- if err != nil {
- t.Fatalf("marshal live: %v", err)
- }
- var liveFields map[string]any
- if err := json.Unmarshal(live, &liveFields); err != nil {
- t.Fatalf("unmarshal live: %v", err)
- }
- if _, ok := liveFields["cached"]; ok {
- t.Error("live responses must omit the cached marker")
- }
- if _, ok := liveFields["cached_at"]; ok {
- t.Error("live responses must omit cached_at")
- }
-}
-
// TestInMemoryModelCatalogCache_RoundTripsUnavailableModels covers the advisory
// list (MUL-6961). Without it, a warm cache hit would silently drop the greyed
// "needs a newer CLI" rows for the whole serve window, so the same runtime would
diff --git a/server/internal/handler/runtime_models_test.go b/server/internal/handler/runtime_models_test.go
index b7705b152a..fb80dc5fc7 100644
--- a/server/internal/handler/runtime_models_test.go
+++ b/server/internal/handler/runtime_models_test.go
@@ -4,8 +4,6 @@ import (
"bytes"
"context"
"encoding/json"
- "net/http"
- "net/http/httptest"
"testing"
"time"
)
@@ -126,34 +124,6 @@ func TestReportModelListResult_PreservesDefault(t *testing.T) {
}
}
-// TestReportModelListResult_DecodesJSONBodyDefault verifies the
-// handler's request-body parsing accepts the `default` bool from
-// the daemon POST — not just through the store API.
-func TestReportModelListResult_DecodesJSONBodyDefault(t *testing.T) {
- // Simulate the shape the daemon POSTs: status + models + supported
- // with `default` on one entry.
- payload := `{"status":"completed","supported":true,"models":[{"id":"a","label":"A","default":true,"supports_explicit_standard_service_tier":true},{"id":"b","label":"B"}]}`
- r := httptest.NewRequest(http.MethodPost, "/api/daemon/runtimes/rt/models/req/result", bytes.NewBufferString(payload))
-
- var body struct {
- Status string `json:"status"`
- Models []ModelEntry `json:"models"`
- Supported *bool `json:"supported"`
- }
- if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
- t.Fatalf("decode: %v", err)
- }
- if len(body.Models) != 2 {
- t.Fatalf("want 2 models, got %d", len(body.Models))
- }
- if !body.Models[0].Default {
- t.Errorf("default flag lost on model[0]: %+v", body.Models[0])
- }
- if !body.Models[0].SupportsExplicitStandardServiceTier {
- t.Errorf("explicit-standard capability lost on model[0]: %+v", body.Models[0])
- }
-}
-
// TestInMemoryModelListStore_HasPending pins the cheap probe used by the
// heartbeat hot path. Empty queue → false; pending request → true; after
// PopPending claims the record → false again.
diff --git a/server/internal/handler/squad_briefing_test.go b/server/internal/handler/squad_briefing_test.go
index c0007c4b3a..1e1e0b66bc 100644
--- a/server/internal/handler/squad_briefing_test.go
+++ b/server/internal/handler/squad_briefing_test.go
@@ -13,51 +13,6 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// TestSquadOperatingProtocolRecordsAgainstTheTurnsIssue locks the recording
-// contract the protocol teaches (MUL-6622 / GH #7487): record against the issue
-// this turn runs on — squad assignment of that issue is irrelevant — and, when
-// the call fails, leave a trace WITHOUT breaking one-comment-per-turn. The
-// conditional matters: on the `action` path a delegation comment already exists,
-// so an unconditional "post a comment on failure" would demand a second one.
-func TestSquadOperatingProtocolRecordsAgainstTheTurnsIssue(t *testing.T) {
- for _, ownsStatus := range []bool{true, false} {
- compact := strings.Join(strings.Fields(squadOperatingProtocolFor(ownsStatus)), " ")
- for _, want := range []string{
- "Record it against the issue THIS turn is running on",
- "It does not need to be assigned to your squad",
- "without breaking the one-comment-per-turn rule",
- "ONLY if you have not already commented this turn",
- "do not add a second one",
- "never post a second comment just to report the error",
- } {
- if !strings.Contains(compact, want) {
- t.Errorf("owns_status=%v: expected squad operating protocol to contain %q\n--- protocol ---\n%s",
- ownsStatus, want, compact)
- }
- }
- }
-}
-
-// TestSquadOperatingProtocolOwnsParentStatus locks the parent-issue status
-// contract: first dispatch moves todo→in_progress and stays there; only a
-// later confirmation of overall completion may advance to in_review; done is
-// left to humans / integrations.
-func TestSquadOperatingProtocolOwnsParentStatus(t *testing.T) {
- protocol := squadOperatingProtocolFor(true)
- compact := strings.Join(strings.Fields(protocol), " ")
- for _, want := range []string{
- "Own the parent issue status",
- "move the parent to `in_progress`",
- "successful dispatch is not completion",
- "multica issue status <issue-id> in_review",
- "Leave `done` to a human reviewer",
- } {
- if !strings.Contains(compact, want) {
- t.Errorf("expected squad operating protocol to contain %q\n--- protocol ---\n%s", want, protocol)
- }
- }
-}
-
// TestSquadOperatingProtocolScopesParentStatusOwnership is the guard for the
// MUL-5156 review finding: the briefing is injected on every leader path,
// including an @squad mention on an issue assigned to someone else. Status
@@ -110,25 +65,6 @@ func TestSquadOperatingProtocolScopesParentStatusOwnership(t *testing.T) {
}
}
-// TestSquadOperatingProtocolWarnsAgainstDualTrigger locks in the rule
-// added for #3033: the protocol must tell the squad leader that a `todo`
-// child issue with an agent assignee already fires that agent, so they
-// must not also @mention the same agent on the parent issue for the
-// same work. Asserts behavior, not exact wording — keep the substrings
-// narrow so harmless rewording doesn't break the test.
-func TestSquadOperatingProtocolWarnsAgainstDualTrigger(t *testing.T) {
- protocol := squadOperatingProtocolFor(true)
- compact := strings.Join(strings.Fields(protocol), " ")
- for _, want := range []string{
- "--status todo` and an agent assignee already fires that agent automatically",
- "Never both for the same work.",
- } {
- if !strings.Contains(compact, want) {
- t.Errorf("expected squad operating protocol to contain %q\n--- protocol ---\n%s", want, protocol)
- }
- }
-}
-
// seedSquadForBriefing creates a squad with the seeded test agent as
// leader. Returns the loaded db.Squad and a cleanup-registered ID.
func seedSquadForBriefing(t *testing.T, leaderID string, name, instructions string) db.Squad {
diff --git a/server/internal/handler/webhook_rate_limiter_test.go b/server/internal/handler/webhook_rate_limiter_test.go
index ebaa0e3686..f4da78d180 100644
--- a/server/internal/handler/webhook_rate_limiter_test.go
+++ b/server/internal/handler/webhook_rate_limiter_test.go
@@ -2,7 +2,6 @@ package handler
import (
"context"
- "strings"
"testing"
"time"
)
@@ -102,32 +101,6 @@ func TestMemoryWebhookRateLimiter_CheckDoesNotConsumeBudget(t *testing.T) {
}
}
-// TestWebhookLimiterLuaScript_StructureGuard pins the Lua script so any future
-// edit that reorders trim/count/insert (or drops EXPIRE) is caught even when
-// no live Redis is available to the test process. The per-pod race the script
-// guards against ("two pods both see count = limit-1 and both insert") only
-// triggers if the three calls run atomically; this regression guard is the
-// cheap-but-effective complement to the live-Redis test below.
-func TestWebhookLimiterLuaScript_StructureGuard(t *testing.T) {
- // redis.NewScript stores the body, so we just sanity-check ordering by
- // matching the source string. The exact whitespace is brittle but the
- // alternative (Lua AST parsing) is overkill for a 10-line script.
- src := webhookLimiterAllowSource()
- mustBefore := func(a, b string) {
- t.Helper()
- ia, ib := strings.Index(src, a), strings.Index(src, b)
- if ia < 0 || ib < 0 {
- t.Fatalf("script must contain %q and %q, src=%s", a, b, src)
- }
- if ia >= ib {
- t.Fatalf("expected %q to appear before %q, src=%s", a, b, src)
- }
- }
- mustBefore("ZREMRANGEBYSCORE", "ZCARD")
- mustBefore("ZCARD", "ZADD")
- mustBefore("ZADD", "EXPIRE")
-}
-
func TestRedisWebhookRateLimiter_RejectsAboveLimit(t *testing.T) {
rdb := newRedisTestClient(t)
defer rdb.Close()
diff --git a/server/internal/handler/workspace_delete_fence_test.go b/server/internal/handler/workspace_delete_fence_test.go
index b85fcedfc1..362a694523 100644
--- a/server/internal/handler/workspace_delete_fence_test.go
+++ b/server/internal/handler/workspace_delete_fence_test.go
@@ -3,9 +3,6 @@ package handler
import (
"context"
"errors"
- "os"
- "path/filepath"
- "regexp"
"strconv"
"strings"
"sync"
@@ -61,87 +58,6 @@ SELECT EXISTS (
t.Fatalf("backend %d never parked on a lock; the race was not set up", pid)
}
-// TestTaskOwnershipWritesCallTheFence is the guard that keeps the fence from being
-// a convention. Every statement that inserts an agent_task_queue row, or assigns
-// one of its ownership columns, has to call lock_task_owner_rows — a new
-// write path that forgets it would silently reopen the insert-after-sweep window
-// that MUL-5999's teardown depends on being closed.
-//
-// This is the trade for not using a row trigger: the write path names its own
-// fence, and CI checks that it did.
-func TestTaskOwnershipWritesCallTheFence(t *testing.T) {
- queryDir := filepath.Join("..", "..", "pkg", "db", "queries")
- entries, err := os.ReadDir(queryDir)
- if err != nil {
- t.Fatalf("read query dir: %v", err)
- }
-
- nameRe := regexp.MustCompile(`(?m)^-- name: (\S+)`)
- // Go's regexp has no lookahead, so the SET clause is isolated first and its
- // ownership assignments are inspected individually. Clearing runtime_id cannot
- // move a task into another workspace, so `= NULL` is exempt; teardown's own
- // detach only touches parent_task_id.
- setClauseRe := regexp.MustCompile(`(?is)\bSET\b(.*?)(?:\bWHERE\b|\bFROM\b|\bRETURNING\b|;)`)
- ownerAssignRe := regexp.MustCompile(`(?i)\b(agent_id|issue_id|runtime_id)\s*=\s*(\S+)`)
-
- assignsOwner := func(code string) bool {
- for _, clause := range setClauseRe.FindAllStringSubmatch(code, -1) {
- for _, assign := range ownerAssignRe.FindAllStringSubmatch(clause[1], -1) {
- if !strings.EqualFold(strings.TrimSuffix(assign[2], ","), "NULL") {
- return true
- }
- }
- }
- return false
- }
-
- checked := 0
- for _, entry := range entries {
- if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
- continue
- }
- body, err := os.ReadFile(filepath.Join(queryDir, entry.Name()))
- if err != nil {
- t.Fatalf("read %s: %v", entry.Name(), err)
- }
- text := string(body)
- matches := nameRe.FindAllStringSubmatchIndex(text, -1)
- for i, m := range matches {
- stop := len(text)
- if i+1 < len(matches) {
- stop = matches[i+1][0]
- }
- stmt := text[m[0]:stop]
- name := text[m[2]:m[3]]
- // Strip comment lines so prose cannot satisfy or trip the check.
- var sqlOnly strings.Builder
- for _, line := range strings.Split(stmt, "\n") {
- if strings.HasPrefix(strings.TrimSpace(line), "--") {
- continue
- }
- sqlOnly.WriteString(line)
- sqlOnly.WriteString("\n")
- }
- code := sqlOnly.String()
-
- writesOwnership := strings.Contains(code, "INSERT INTO agent_task_queue") ||
- (strings.Contains(code, "UPDATE agent_task_queue") && assignsOwner(code))
- if !writesOwnership {
- continue
- }
- checked++
- if !strings.Contains(code, "lock_task_owner_rows(") {
- t.Errorf("%s: %s writes agent_task_queue ownership without calling "+
- "lock_task_owner_rows; that reopens the workspace-delete race "+
- "(see migration 284)", entry.Name(), name)
- }
- }
- }
- if checked < 9 {
- t.Errorf("only %d ownership-writing statements found; the detector probably stopped matching", checked)
- }
-}
-
// TestTaskWriteFence_BlocksOnWorkspaceLockAlone shows the fence, and only the
// fence, standing between a concurrent enqueue and a workspace being torn down.
//
diff --git a/server/internal/integrations/channel/message_test.go b/server/internal/integrations/channel/message_test.go
deleted file mode 100644
index 19e30f5d6c..0000000000
--- a/server/internal/integrations/channel/message_test.go
+++ /dev/null
@@ -1,82 +0,0 @@
-package channel
-
-import (
- "encoding/json"
- "testing"
-)
-
-// TestInboundMessage_RawIsOpaque proves the boundary contract: a
-// platform-specific payload survives a JSON round-trip through Raw
-// byte-for-byte, so an adapter can stash anything there and read it back
-// while the core leaves it untouched.
-func TestInboundMessage_RawIsOpaque(t *testing.T) {
- raw := json.RawMessage(`{"msg_type":"merge_forward","parent_id":"om_x","mentions":[{"id":"ou_1"}]}`)
- in := InboundMessage{
- EventID: "evt_1",
- MessageID: "om_1",
- Source: Source{
- ChannelType: TypeFeishu,
- ChatID: "oc_1",
- ChatType: ChatTypeGroup,
- SenderID: "ou_sender",
- SenderStableID: "on_union",
- ThreadID: "omt_1",
- },
- Type: MsgTypeText,
- Text: "hello",
- AddressedToBot: true,
- ReplyTo: &ReplyCtx{MessageID: "om_parent", RootID: "om_root"},
- Raw: raw,
- }
-
- encoded, err := json.Marshal(in)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- var got InboundMessage
- if err := json.Unmarshal(encoded, &got); err != nil {
- t.Fatalf("Unmarshal: %v", err)
- }
-
- if got.Source != in.Source {
- t.Errorf("Source round-trip mismatch:\n got %+v\nwant %+v", got.Source, in.Source)
- }
- if got.ReplyTo == nil || *got.ReplyTo != *in.ReplyTo {
- t.Errorf("ReplyTo round-trip mismatch: got %+v", got.ReplyTo)
- }
- if !got.AddressedToBot {
- t.Errorf("AddressedToBot lost in round-trip")
- }
-
- // Raw must be semantically identical (compare as parsed JSON to be
- // whitespace-insensitive).
- var a, b any
- if err := json.Unmarshal(got.Raw, &a); err != nil {
- t.Fatalf("Raw not valid JSON after round-trip: %v", err)
- }
- if err := json.Unmarshal(raw, &b); err != nil {
- t.Fatalf("seed Raw not valid JSON: %v", err)
- }
- if string(mustMarshal(t, a)) != string(mustMarshal(t, b)) {
- t.Errorf("Raw payload changed across round-trip:\n got %s\nwant %s", got.Raw, raw)
- }
-}
-
-func mustMarshal(t *testing.T, v any) []byte {
- t.Helper()
- b, err := json.Marshal(v)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- return b
-}
-
-// TestOutboundMessage_Minimal documents that the outbound envelope is the
-// minimal text reply (decision §6): a text body, optionally threaded or
-// quoting, and nothing card/media-shaped.
-func TestOutboundMessage_Minimal(t *testing.T) {
- out := OutboundMessage{ChatID: "oc_1", Text: "hi", ThreadID: "omt_1", ReplyTo: "om_1"}
- if out.ChatID == "" || out.Text == "" {
- t.Fatalf("ChatID and Text are the required fields")
- }
-}
diff --git a/server/internal/integrations/composio/service_test.go b/server/internal/integrations/composio/service_test.go
index 4a3a503003..bd01b0935d 100644
--- a/server/internal/integrations/composio/service_test.go
+++ b/server/internal/integrations/composio/service_test.go
@@ -568,22 +568,6 @@ func TestCompleteCallback_UnknownAccountRejected(t *testing.T) {
}
}
-func TestListConnections(t *testing.T) {
- t.Parallel()
- store := newFakeStore()
- svc := newTestService(t, &fakeSDK{}, store)
- userID := mintUUID(5)
- seedActive(store, userID, "notion", "ca_a")
-
- conns, err := svc.ListConnections(context.Background(), userID)
- if err != nil {
- t.Fatalf("ListConnections: %v", err)
- }
- if len(conns) != 1 || conns[0].ToolkitSlug != "notion" || conns[0].Status != "active" {
- t.Fatalf("conns = %+v", conns)
- }
-}
-
func TestDisconnect_OwnerRevokeIdempotentAndFilter(t *testing.T) {
t.Parallel()
store := newFakeStore()
diff --git a/server/internal/integrations/dingtalk/inbound_test.go b/server/internal/integrations/dingtalk/inbound_test.go
index 96ff8cd9e6..3093558442 100644
--- a/server/internal/integrations/dingtalk/inbound_test.go
+++ b/server/internal/integrations/dingtalk/inbound_test.go
@@ -356,9 +356,3 @@ func TestInboundFromCallback_DropsOnlySenderless(t *testing.T) {
t.Fatal("nil callback must be dropped")
}
}
-
-func TestCapabilitiesIncludeAttachment(t *testing.T) {
- if c := (&dingtalkChannel{}).Capabilities(); !c.Has(channel.CapText | channel.CapAttachment) {
- t.Fatalf("capabilities = %v", c)
- }
-}
diff --git a/server/internal/integrations/dingtalk/replier_test.go b/server/internal/integrations/dingtalk/replier_test.go
index 08db8a0053..eb39f903f0 100644
--- a/server/internal/integrations/dingtalk/replier_test.go
+++ b/server/internal/integrations/dingtalk/replier_test.go
@@ -29,15 +29,6 @@ func TestIssueDuplicateText(t *testing.T) {
}
}
-func TestIssueUsageCopy(t *testing.T) {
- if issueUsageText != "Please include an issue title. Use:\n\n`/issue <title>`\n\n`[description]` (optional)" {
- t.Fatalf("plain issue usage copy = %q", issueUsageText)
- }
- if issueUsageWithMediaText != "Please add a title and resend with the image (*image can come before or after the command*):\n\n`/issue <title>`\n\n`[description]` (optional)" {
- t.Fatalf("media issue usage copy = %q", issueUsageWithMediaText)
- }
-}
-
func TestDroppedReplyText(t *testing.T) {
issueMsg := channel.InboundMessage{Text: "[Image]", CommandText: "/issue login is broken", AddressedToBot: true}
cases := []struct {
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
index 3182c270d1..23d502523c 100644
--- a/server/internal/integrations/dingtalk/resolvers_test.go
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -113,13 +113,6 @@ func (c *captureChatSession) BindMediaRefs(_ context.Context, in engine.BindMedi
return nil
}
-func TestNewDingTalkResolverSetUsesDatabaseBackedIssueOrigin(t *testing.T) {
- set := NewDingTalkResolverSet(nil, nil, nil, nil, nil, nil)
- if set.OriginType != originDingTalkChat {
- t.Fatalf("OriginType = %q, want %q", set.OriginType, originDingTalkChat)
- }
-}
-
func TestSessionBinder_MapsCommandTextAndMediaDeadline(t *testing.T) {
var session, sender, inst, claim pgtype.UUID
session.Bytes[0], sender.Bytes[0], inst.Bytes[0], claim.Bytes[0] = 2, 3, 4, 5
diff --git a/server/internal/integrations/lark/binding_token_test.go b/server/internal/integrations/lark/binding_token_test.go
index fbe91b28e9..4ca921e396 100644
--- a/server/internal/integrations/lark/binding_token_test.go
+++ b/server/internal/integrations/lark/binding_token_test.go
@@ -2,7 +2,6 @@ package lark
import (
"context"
- "errors"
"strings"
"testing"
"time"
@@ -68,28 +67,6 @@ func TestRedeemAndBindRequiresTxStarter(t *testing.T) {
}
}
-// TestBindingErrorSentinelsAreDistinct guards against accidentally
-// collapsing the three rejection sentinels (e.g. someone making
-// ErrBindingNotWorkspaceMember an alias of ErrBindingTokenInvalid to
-// "hide" the workspace-membership signal). The HTTP handler maps
-// each to a distinct status code (410/409/403); if errors.Is started
-// matching the wrong sentinel, the response code would silently
-// regress without any other test catching it.
-func TestBindingErrorSentinelsAreDistinct(t *testing.T) {
- if errors.Is(ErrBindingAlreadyAssigned, ErrBindingTokenInvalid) ||
- errors.Is(ErrBindingTokenInvalid, ErrBindingAlreadyAssigned) {
- t.Fatal("ErrBindingAlreadyAssigned and ErrBindingTokenInvalid must not alias")
- }
- if errors.Is(ErrBindingNotWorkspaceMember, ErrBindingTokenInvalid) ||
- errors.Is(ErrBindingTokenInvalid, ErrBindingNotWorkspaceMember) {
- t.Fatal("ErrBindingNotWorkspaceMember and ErrBindingTokenInvalid must not alias")
- }
- if errors.Is(ErrBindingAlreadyAssigned, ErrBindingNotWorkspaceMember) ||
- errors.Is(ErrBindingNotWorkspaceMember, ErrBindingAlreadyAssigned) {
- t.Fatal("ErrBindingAlreadyAssigned and ErrBindingNotWorkspaceMember must not alias")
- }
-}
-
func TestHashTokenDeterministic(t *testing.T) {
a := hashToken("hello")
b := hashToken("hello")
diff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.go
index e1996af528..2cfd8dbc2a 100644
--- a/server/internal/integrations/lark/feishu_channel_test.go
+++ b/server/internal/integrations/lark/feishu_channel_test.go
@@ -200,22 +200,6 @@ func TestFeishuFactory_MissingConnectorFails(t *testing.T) {
}
}
-func TestFeishuChannel_Capabilities(t *testing.T) {
- fc := &feishuChannel{}
- caps := fc.Capabilities()
- for _, want := range []channel.Capability{
- channel.CapText, channel.CapRichCard, channel.CapThreadReply,
- channel.CapQuoteReply, channel.CapAttachment, channel.CapTypingIndicator, channel.CapMessageEdit,
- } {
- if !caps.Has(want) {
- t.Fatalf("Capabilities missing %s", want)
- }
- }
- if caps.Has(channel.CapVoice) {
- t.Fatalf("Feishu adapter does not declare voice")
- }
-}
-
func TestFeishuChannel_SendMapsTextAndReplyTarget(t *testing.T) {
sender := &fakeSender{msgID: "om_sent"}
fc := &feishuChannel{
@@ -870,28 +854,3 @@ func TestChannelMsgType(t *testing.T) {
}
}
}
-
-func TestDispatchResultFromEngine(t *testing.T) {
- res := dispatchResultFromEngine(engine.Result{
- Outcome: engine.OutcomeNeedsBinding,
- Sender: "ou_user",
- IssueIdentifier: "MUL-7",
- IssueDuplicate: true,
- IssueUsageHadMedia: true,
- })
- if res.Outcome != OutcomeNeedsBinding {
- t.Fatalf("outcome not mapped: %q", res.Outcome)
- }
- if res.SenderOpenID != "ou_user" {
- t.Fatalf("sender not mapped: %q", res.SenderOpenID)
- }
- if res.IssueIdentifier != "MUL-7" {
- t.Fatalf("issue identifier not mapped: %q", res.IssueIdentifier)
- }
- if !res.IssueDuplicate {
- t.Fatal("issue duplicate flag not mapped")
- }
- if !res.IssueUsageHadMedia {
- t.Fatal("issue usage media flag not mapped")
- }
-}
diff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.go
index 796b9b807d..b6ee769492 100644
--- a/server/internal/integrations/lark/http_client_test.go
+++ b/server/internal/integrations/lark/http_client_test.go
@@ -234,13 +234,6 @@ func testCreds() InstallationCredentials {
return InstallationCredentials{AppID: "cli_app_xx", AppSecret: "secret_xx"}
}
-func TestHTTPClient_IsConfigured(t *testing.T) {
- c := NewHTTPAPIClient(HTTPClientConfig{})
- if !c.IsConfigured() {
- t.Fatalf("real client must report IsConfigured()=true")
- }
-}
-
func TestHTTPClient_DownloadMessageResource(t *testing.T) {
fake := newLarkFake(t)
fake.stubToken("tok_resource", 7200)
@@ -436,16 +429,6 @@ func TestHTTPClient_DownloadMessageResourceBusinessError(t *testing.T) {
}
}
-// TestHTTPClient_StubReportsNotConfigured pins that the stub never
-// claims wired outbound — handlers gate install / management UI on
-// this signal.
-func TestHTTPClient_StubReportsNotConfigured(t *testing.T) {
- s := NewStubAPIClient(nil)
- if s.IsConfigured() {
- t.Errorf("stub IsConfigured must be false")
- }
-}
-
// TestHTTPClient_SendInteractiveCard_DefaultRendererBodyHasUpdateMulti
// is the send-side half of the must-fix wire check: when the Patcher
// uses NewDefaultRenderer to produce a card and ships it via
diff --git a/server/internal/integrations/lark/store_test.go b/server/internal/integrations/lark/store_test.go
index 00d8473a45..2ed42e32f7 100644
--- a/server/internal/integrations/lark/store_test.go
+++ b/server/internal/integrations/lark/store_test.go
@@ -206,26 +206,3 @@ func TestBindingConfigNullStrip(t *testing.T) {
t.Fatalf("expected empty union_id to encode as {}, got %q", got)
}
}
-
-func TestChatSessionBindingFromRow(t *testing.T) {
- row := db.ChannelChatSessionBinding{
- ID: uuidFrom(0x77),
- ChatSessionID: uuidFrom(0x88),
- InstallationID: uuidFrom(0x11),
- ChannelType: "feishu",
- ChannelChatID: "oc_chat_1",
- ChatType: "group",
- LastMessageID: pgtype.Text{String: "om_last", Valid: true},
- LastThreadID: pgtype.Text{String: "omt_thread", Valid: true},
- }
- got := chatSessionBindingFromRow(row)
- if got.ChannelChatID != "oc_chat_1" || got.ChatType != "group" {
- t.Fatalf("chat fields mismatch: %+v", got)
- }
- if got.LastMessageID != row.LastMessageID || got.LastThreadID != row.LastThreadID {
- t.Fatalf("reply-target fields mismatch: %+v", got)
- }
- if got.ChatSessionID != row.ChatSessionID || got.InstallationID != row.InstallationID {
- t.Fatalf("id fields mismatch: %+v", got)
- }
-}
diff --git a/server/internal/integrations/lark/ws_connector_test.go b/server/internal/integrations/lark/ws_connector_test.go
index f8f65fe32d..9b1b3b2050 100644
--- a/server/internal/integrations/lark/ws_connector_test.go
+++ b/server/internal/integrations/lark/ws_connector_test.go
@@ -787,19 +787,3 @@ func TestGorillaDialerProxyURLApplied(t *testing.T) {
// The error should be about the proxy connection (refused / timeout),
// not about the URL parsing.
}
-
-func TestGorillaDialerEmptyProxyURLDefaultsToEnv(t *testing.T) {
- t.Parallel()
- d := NewGorillaDialer()
- if d.ProxyURL != "" {
- t.Fatalf("NewGorillaDialer ProxyURL should be empty, got %q", d.ProxyURL)
- }
- // DialContext with empty ProxyURL should not panic or error on the
- // proxy path — the underlying gorilla dialer uses ProxyFromEnvironment.
- ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
- defer cancel()
- _, _, _ = d.DialContext(ctx, "wss://127.0.0.1:1/ws", nil)
- // We don't assert on the error (it'll be a connection error), we just
- // verify that DialContext with empty ProxyURL doesn't panic or return
- // a parse error.
-}
diff --git a/server/internal/integrations/telegram/binding_test.go b/server/internal/integrations/telegram/binding_test.go
index 9a8772a97d..21960827b6 100644
--- a/server/internal/integrations/telegram/binding_test.go
+++ b/server/internal/integrations/telegram/binding_test.go
@@ -2,7 +2,6 @@ package telegram
import (
"context"
- "errors"
"regexp"
"testing"
@@ -45,18 +44,3 @@ func TestRedeemAndBindRequiresTransactionStarter(t *testing.T) {
t.Fatalf("error = %v", err)
}
}
-
-func TestBindingErrorSentinelsRemainDistinct(t *testing.T) {
- errs := []error{
- ErrBindingTokenInvalid,
- ErrBindingAlreadyAssigned,
- ErrBindingNotWorkspaceMember,
- }
- for i := range errs {
- for j := range errs {
- if i != j && errors.Is(errs[i], errs[j]) {
- t.Fatalf("binding errors %v and %v overlap", errs[i], errs[j])
- }
- }
- }
-}
diff --git a/server/internal/integrations/telegram/install_error_test.go b/server/internal/integrations/telegram/install_error_test.go
index 451230b0a1..5f71c6fdd0 100644
--- a/server/internal/integrations/telegram/install_error_test.go
+++ b/server/internal/integrations/telegram/install_error_test.go
@@ -4,16 +4,8 @@ import (
"errors"
"net/http"
"testing"
- "time"
)
-func TestCredentialVerificationClientHasBoundedTimeout(t *testing.T) {
- client := newCredentialVerificationClient()
- if client.Timeout != 15*time.Second {
- t.Fatalf("verification timeout = %s, want 15s", client.Timeout)
- }
-}
-
func TestClassifyCredentialVerificationError(t *testing.T) {
tests := []struct {
name string
diff --git a/server/internal/integrations/wecom/binding_test.go b/server/internal/integrations/wecom/binding_test.go
index 665b3ae66c..6760e7a1e9 100644
--- a/server/internal/integrations/wecom/binding_test.go
+++ b/server/internal/integrations/wecom/binding_test.go
@@ -207,11 +207,3 @@ func TestMintIgnoresAConsumedToken(t *testing.T) {
t.Fatalf("%d rows written, want 2", fake.creates)
}
}
-
-// TestMintThrottleWindowIsShorterThanTheTTL — a throttle at or past the TTL
-// would leave a user with no valid link and no way to get one.
-func TestMintThrottleWindowIsShorterThanTheTTL(t *testing.T) {
- if BindingTokenMintInterval >= BindingTokenTTL {
- t.Fatalf("throttle %v must stay inside the %v token TTL", BindingTokenMintInterval, BindingTokenTTL)
- }
-}
diff --git a/server/internal/integrations/wecom/credential_probe_test.go b/server/internal/integrations/wecom/credential_probe_test.go
index aa527b2beb..71245de651 100644
--- a/server/internal/integrations/wecom/credential_probe_test.go
+++ b/server/internal/integrations/wecom/credential_probe_test.go
@@ -252,14 +252,3 @@ func TestUpsertRefusesWithoutAProbe(t *testing.T) {
t.Fatalf("Upsert without a probe = %v, want ErrProbeRequired", err)
}
}
-
-func TestWithCredentialProbeSetsIt(t *testing.T) {
- t.Parallel()
-
- p := &fakeProbe{}
- svc := &InstallationService{}
- WithCredentialProbe(p)(svc)
- if svc.probe != p {
- t.Fatal("WithCredentialProbe did not install the probe")
- }
-}
diff --git a/server/internal/integrations/wecom/dispatch_test.go b/server/internal/integrations/wecom/dispatch_test.go
index c467ce3982..c44b62b59a 100644
--- a/server/internal/integrations/wecom/dispatch_test.go
+++ b/server/internal/integrations/wecom/dispatch_test.go
@@ -122,23 +122,6 @@ func TestDispatchFrame_HandlerErrorPropagates(t *testing.T) {
}
}
-func TestChannelGetters(t *testing.T) {
- t.Parallel()
- c := testChannel(nil)
- if c.Type() != TypeWecom {
- t.Errorf("Type() = %v, want %v", c.Type(), TypeWecom)
- }
- if c.Capabilities()&channel.CapText == 0 {
- t.Error("Capabilities() should include CapText")
- }
- if err := c.Disconnect(context.Background()); err != nil {
- t.Errorf("Disconnect() = %v, want nil", err)
- }
- if _, err := c.Send(context.Background(), channel.OutboundMessage{}); !errors.Is(err, ErrSendNotSupported) {
- t.Errorf("Send() = %v, want ErrSendNotSupported", err)
- }
-}
-
// TestSend_NeverGuessesChatType pins the fix for the removed len(ChatID)>32
// heuristic: Send must reject regardless of ChatID length — a long id must not
// route as a group send, a short one must not route as a private send. If a
diff --git a/server/internal/integrations/wecom/installation_params_test.go b/server/internal/integrations/wecom/installation_params_test.go
index bbba3b1e27..fb050a7c03 100644
--- a/server/internal/integrations/wecom/installation_params_test.go
+++ b/server/internal/integrations/wecom/installation_params_test.go
@@ -55,11 +55,3 @@ func TestCompleteParamsPass(t *testing.T) {
t.Fatalf("complete params rejected: %v", err)
}
}
-
-// A failure that is NOT a validation failure must not match the sentinel —
-// otherwise a database outage is reported to the admin as bad credentials.
-func TestAnUnrelatedFailureIsNotTheCallersToFix(t *testing.T) {
- if errors.Is(errors.New("dial tcp: connection refused"), ErrInvalidInstallationParams) {
- t.Fatal("an infrastructure error matched the caller-error sentinel")
- }
-}
diff --git a/server/internal/integrations/wecom/outbound_outcome_test.go b/server/internal/integrations/wecom/outbound_outcome_test.go
index c51d9241ea..5eb5c31a88 100644
--- a/server/internal/integrations/wecom/outbound_outcome_test.go
+++ b/server/internal/integrations/wecom/outbound_outcome_test.go
@@ -213,39 +213,6 @@ func TestNilMetricsSinkIsSafe(t *testing.T) {
o.handleEvent(outcomeEvent()) // no socket registered: takes the drop path
}
-// TestReasonStringsArePinned — these are metric label values. Renaming one
-// silently retires whatever alert or dashboard reads it, and the rename would
-// otherwise pass every test in this package: nothing else asserts the strings
-// themselves, only that some reason was recorded.
-func TestReasonStringsArePinned(t *testing.T) {
- t.Parallel()
- for want, got := range map[string]dropReason{
- "no_live_connection": dropNoConnection,
- "task_missing": dropTaskMissing,
- "platform_refused": dropPlatformRefused,
- "transport_error": dropTransport,
- "attachment_not_admitted": dropAttachmentNotAdmitted,
- } {
- if string(got) != want {
- t.Errorf("reason = %q, want %q", got, want)
- }
- }
-}
-
-// TestSkipReasonStringsArePinned — the skipped set is a metric label too.
-func TestSkipReasonStringsArePinned(t *testing.T) {
- t.Parallel()
- for want, got := range map[string]skipReason{
- "origin_not_channel": skipOriginNotChannel,
- "installation_inactive": skipInstallationInactive,
- "nothing_to_say": skipNothingToSay,
- } {
- if string(got) != want {
- t.Errorf("skip reason = %q, want %q", got, want)
- }
- }
-}
-
// TestNotOwedIsSkippedNotDropped — the review finding. A question typed in the
// web UI on a WeCom-bound session was never owed to a WeCom user, so counting
// it as a failed delivery makes ordinary web usage read as an outage.
@@ -279,20 +246,6 @@ func TestNotOwedIsSkippedNotDropped(t *testing.T) {
}
}
-// TestActionableSplitIsPinned — every drop reaches an operator now that the
-// ordinary outcomes have their own counter.
-func TestActionableSplitIsPinned(t *testing.T) {
- t.Parallel()
- for _, r := range []dropReason{
- dropNoConnection, dropTaskMissing, dropPlatformRefused,
- dropTransport, dropAttachmentNotAdmitted,
- } {
- if !r.actionable() {
- t.Errorf("%s is a drop and must reach an operator", r)
- }
- }
-}
-
// TestCompletionWithNoTaskIdIsCounted — the origin gate cannot run without a
// task to read the provenance stamp off, so the turn is withheld. Rare, but it
// used to be the quietest branch of all: no log, no counter, nothing.
diff --git a/server/internal/integrations/wecom/relay_ordering_db_test.go b/server/internal/integrations/wecom/relay_ordering_db_test.go
index e1a2339d31..7327b09ce6 100644
--- a/server/internal/integrations/wecom/relay_ordering_db_test.go
+++ b/server/internal/integrations/wecom/relay_ordering_db_test.go
@@ -455,20 +455,6 @@ func TestRelayRetryPlan_DefaultsCoverTheDefaultPollInterval(t *testing.T) {
}
}
-// The drain runs inside the process's own shutdown, so its budget has to fit
-// under the channel supervisor's — the thing that is joined after it. A drain
-// budget larger than that would push shutdown past the supervisor's own bound
-// and cost the final lease release, which is what makes the next replica wait
-// out a whole LeaseTTL after a redeploy.
-func TestRelayDrainBudget_FitsUnderTheSupervisorShutdownTimeout(t *testing.T) {
- t.Parallel()
- cfg := RelayConfig{}.withDefaults()
- if cfg.DrainBudget >= engine.DefaultShutdownTimeout {
- t.Fatalf("drain budget %s does not fit under the supervisor's shutdown timeout %s",
- cfg.DrainBudget, engine.DefaultShutdownTimeout)
- }
-}
-
// The claim has to outlive the replay window it guards, at every grace an
// operator can set — including one longer than the floor.
func TestDedupeTTL_OutlivesEveryReplayWindow(t *testing.T) {
diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.go
index 6edeca2958..c72ec51bed 100644
--- a/server/internal/integrations/wecom/ws_frame_test.go
+++ b/server/internal/integrations/wecom/ws_frame_test.go
@@ -166,34 +166,3 @@ func TestSendMsgTextBody_ShapeAndChatTypeValidation(t *testing.T) {
t.Error("chat_type 3 should be rejected (must be 1 or 2)")
}
}
-
-// TestIssueCommandDetectionMatchesTheEngine: the adapter sets SkipAgentRun
-// from its own answer, and the engine files the issue from its own. Any input
-// they disagree on is a message that reaches nobody — no agent run because
-// this side said "command", no issue because that side said "prose".
-//
-// U+3000 is the case that mattered: it is what a Chinese IME emits for the
-// space bar in full-width mode, so it opens real messages.
-func TestIssueCommandDetectionMatchesTheEngine(t *testing.T) {
- cases := []string{
- "/issue the login redirect is broken",
- "/issue",
- "/issue\tthe title after a tab",
- " /issue leading halfwidth spaces",
- " /issue after an ideographic space",
- "  /issue after two",
- "/issuewithoutspace",
- "not a command at all",
- "",
- "\n\n/issue after blank lines",
- "prose first\n/issue not at the front",
- " /issue after a non-breaking space",
- }
- for _, body := range cases {
- _, engineSays := engine.ParseIssueCommand(body)
- if got := isIssueCommand(body); got != engineSays {
- t.Errorf("isIssueCommand(%q) = %v but engine.ParseIssueCommand says %v — SkipAgentRun and the issue decision disagree, so this message reaches nobody",
- body, got, engineSays)
- }
- }
-}
diff --git a/server/internal/metrics/agent_runtime_lookup_test.go b/server/internal/metrics/agent_runtime_lookup_test.go
index 0707315667..3738f50fcd 100644
--- a/server/internal/metrics/agent_runtime_lookup_test.go
+++ b/server/internal/metrics/agent_runtime_lookup_test.go
@@ -1,11 +1,6 @@
package metrics_test
import (
- "go/ast"
- "go/parser"
- "go/token"
- "io/fs"
- "path/filepath"
"sort"
"strings"
"testing"
@@ -85,72 +80,6 @@ func TestRecordAgentRuntimeLookupNormalizesLabels(t *testing.T) {
}
}
-// TestNoDirectGetAgentRuntimeCalls walks every non-test Go file under
-// server/internal and server/cmd and asserts nothing calls the sqlc
-// GetAgentRuntime method except service.RuntimeLookup.Get.
-//
-// The metric is only worth reading if it counts every read. A call site that
-// goes straight to Queries.GetAgentRuntime does not fail, does not warn, and
-// does not show up — it silently shrinks whichever source it belonged to, which
-// is exactly the kind of quiet undercount that would send the follow-up
-// optimisation work after the wrong caller.
-func TestNoDirectGetAgentRuntimeCalls(t *testing.T) {
- t.Parallel()
-
- root := repoRoot(t)
- // The wrapper itself, keyed by path relative to server/ and by the name of
- // the one function allowed to make the call.
- wrapper := filepath.Join(root, "internal", "service", "agent_runtime_lookup.go")
-
- var offenders []string
- fset := token.NewFileSet()
- for _, dir := range []string{"internal", "cmd"} {
- err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
- return nil
- }
- f, parseErr := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
- if parseErr != nil {
- return parseErr
- }
- for _, decl := range f.Decls {
- fn, ok := decl.(*ast.FuncDecl)
- if !ok || fn.Body == nil {
- continue
- }
- if path == wrapper && fn.Name.Name == "Get" {
- continue
- }
- ast.Inspect(fn.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok || sel.Sel.Name != "GetAgentRuntime" {
- return true
- }
- offenders = append(offenders, fset.Position(call.Pos()).String()+" (in "+fn.Name.Name+")")
- return true
- })
- }
- return nil
- })
- if err != nil {
- t.Fatalf("walk %s: %v", dir, err)
- }
- }
-
- if len(offenders) > 0 {
- sort.Strings(offenders)
- t.Errorf("found %d direct GetAgentRuntime call(s) — read through service.RuntimeLookup with a source label so %s stays complete:\n %s",
- len(offenders), runtimeLookupMetric, strings.Join(offenders, "\n "))
- }
-}
-
// ---- helpers --------------------------------------------------------------
func runtimeLookupCounts(t *testing.T, m *metrics.BusinessMetrics) map[string]float64 {
diff --git a/server/internal/metrics/business_pairing_test.go b/server/internal/metrics/business_pairing_test.go
deleted file mode 100644
index 07e7243dd8..0000000000
--- a/server/internal/metrics/business_pairing_test.go
+++ /dev/null
@@ -1,445 +0,0 @@
-package metrics_test
-
-// PR3 lint test: enforces that every PostHog event constant declared in
-// server/internal/analytics/events.go has a paired Prometheus counter
-// reachable through metrics.RecordEvent — and that every
-// h.Analytics.Capture(analytics.<Helper>(...)) call site goes through
-// metrics.RecordEvent (no naked Capture allowed). The agent task lifecycle is
-// no longer an analytics.Event — it is recorded straight to Prometheus via the
-// typed BusinessMetrics.RecordTask* methods — so there is no longer an
-// AgentTask* allow-list here.
-
-import (
- "go/ast"
- "go/parser"
- "go/token"
- "path/filepath"
- "runtime"
- "sort"
- "strings"
- "testing"
-
- "github.com/multica-ai/multica/server/internal/analytics"
- "github.com/multica-ai/multica/server/internal/metrics"
-)
-
-// frontendOnlyEvents are declared in events.go but emitted from the frontend,
-// not from server code. They still need a Prometheus counter (so a future
-// server-side emission point lights up the same label set) but the server
-// has no Capture call site to lint.
-var frontendOnlyEvents = map[string]bool{
- analytics.EventOnboardingStarted: true,
-}
-
-// TestEveryAnalyticsEventHasPrometheusCounter asserts that every Event*
-// constant declared in analytics/events.go is dispatched by
-// metrics.IncForEvent (verified by sending a synthetic event through
-// RecordEvent and observing a counter delta).
-//
-// Note: agent_task_* lifecycle telemetry is Prometheus-only via the typed
-// BusinessMetrics.RecordTask* methods and is no longer declared as an
-// analytics.Event, so there are no agent_task constants to exempt here.
-func TestEveryAnalyticsEventHasPrometheusCounter(t *testing.T) {
- t.Parallel()
-
- declared := analyticsEventNames(t)
-
- m := metrics.NewBusinessMetrics()
- for name := range declared {
- // Build a minimal event with the required label properties that the
- // dispatcher reads. Since IncForEvent reads via stringProp helpers,
- // a nil Properties map is acceptable for events with empty label
- // sets and is normalised by the helpers for the others.
- ev := analytics.Event{
- Name: name,
- DistinctID: "test",
- Properties: defaultPropsForEvent(name),
- }
- ok := dispatchIncrementsCounter(m, ev)
- if !ok {
- t.Errorf("analytics.%s (%q) is not paired with a Prometheus counter via metrics.IncForEvent — add a case in business_events.go", constantNameForEvent(name), name)
- }
- }
-}
-
-// TestNoNakedAnalyticsCaptureInHandlersOrServices walks every Go file under
-// server/internal/handler and server/internal/service and asserts that every
-// `<x>.Analytics.Capture(analytics.<Helper>(...))` call goes through
-// metrics.RecordEvent. There are no exceptions: every server-side PostHog
-// event must flow through RecordEvent so the Prometheus and PostHog sides
-// cannot drift.
-func TestNoNakedAnalyticsCaptureInHandlersOrServices(t *testing.T) {
- t.Parallel()
-
- roots := []string{
- filepath.Join(repoRoot(t), "internal", "handler"),
- filepath.Join(repoRoot(t), "internal", "service"),
- filepath.Join(repoRoot(t), "cmd", "server"),
- }
- // allowedFunctions is keyed by absolute file path, valued by the set of
- // function names whose bodies are allowed to call Analytics.Capture
- // directly. Granularity is per-function, not per-file. Currently empty —
- // no server code is permitted to call Analytics.Capture outside
- // metrics.RecordEvent.
- allowedFunctions := map[string]map[string]struct{}{}
-
- var offenders []string
- fset := token.NewFileSet()
- for _, root := range roots {
- matches, err := filepath.Glob(filepath.Join(root, "*.go"))
- if err != nil {
- t.Fatalf("glob %s: %v", root, err)
- }
- for _, file := range matches {
- if strings.HasSuffix(file, "_test.go") {
- continue
- }
- f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution)
- if err != nil {
- t.Fatalf("parse %s: %v", file, err)
- }
- fileAllowedFns := allowedFunctions[file]
- for _, decl := range f.Decls {
- fn, ok := decl.(*ast.FuncDecl)
- if !ok {
- continue
- }
- if _, allowed := fileAllowedFns[fn.Name.Name]; allowed {
- continue
- }
- if fn.Body == nil {
- continue
- }
- ast.Inspect(fn.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- if !isAnalyticsCapture(call) {
- return true
- }
- offenders = append(offenders, fset.Position(call.Pos()).String()+" (in "+fn.Name.Name+")")
- return true
- })
- }
- }
- }
-
- if len(offenders) > 0 {
- sort.Strings(offenders)
- t.Errorf("found %d naked Analytics.Capture(...) calls — wrap them in metrics.RecordEvent so the Prometheus and PostHog sides cannot drift:\n %s", len(offenders), strings.Join(offenders, "\n "))
- }
-}
-
-// TestEveryAnalyticsRecordEventTakesAnalyticsHelper enforces the inverse of
-// TestNoNakedAnalyticsCaptureInHandlersOrServices: every call site that
-// DOES go through metrics.RecordEvent must take an analytics.* event helper
-// as its third argument. Local idents are accepted only when def-use
-// tracking inside the same function body proves the value originated from
-// an `analytics.<Helper>(...)` call — bare strings or unresolved values
-// fail CI.
-func TestEveryAnalyticsRecordEventTakesAnalyticsHelper(t *testing.T) {
- t.Parallel()
-
- roots := []string{
- filepath.Join(repoRoot(t), "internal", "handler"),
- filepath.Join(repoRoot(t), "internal", "service"),
- filepath.Join(repoRoot(t), "cmd", "server"),
- }
-
- var offenders []string
- fset := token.NewFileSet()
- for _, root := range roots {
- matches, err := filepath.Glob(filepath.Join(root, "*.go"))
- if err != nil {
- t.Fatalf("glob %s: %v", root, err)
- }
- for _, file := range matches {
- if strings.HasSuffix(file, "_test.go") {
- continue
- }
- f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution)
- if err != nil {
- t.Fatalf("parse %s: %v", file, err)
- }
- for _, decl := range f.Decls {
- fn, ok := decl.(*ast.FuncDecl)
- if !ok || fn.Body == nil {
- continue
- }
- analyticsLocals := analyticsBackedIdents(fn.Body)
- ast.Inspect(fn.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- if !isMetricsRecordEvent(call) {
- return true
- }
- if len(call.Args) < 3 {
- offenders = append(offenders, fset.Position(call.Pos()).String()+" (RecordEvent must be called with 3 args: client, metrics, event)")
- return true
- }
- ev := call.Args[2]
- if analyticsHelperCall(ev) {
- return true
- }
- if id, ok := ev.(*ast.Ident); ok {
- if _, traced := analyticsLocals[id.Name]; traced {
- return true
- }
- offenders = append(offenders, fset.Position(call.Pos()).String()+" (third arg "+id.Name+" was not assigned from an analytics.* helper in this function)")
- return true
- }
- offenders = append(offenders, fset.Position(call.Pos()).String()+" (third arg must be an analytics.* helper call or a local assigned from one)")
- return true
- })
- }
- }
- }
-
- if len(offenders) > 0 {
- sort.Strings(offenders)
- t.Errorf("metrics.RecordEvent call sites must take an analytics.* event:\n %s", strings.Join(offenders, "\n "))
- }
-}
-
-// analyticsBackedIdents walks a function body and returns the set of local
-// identifiers whose initial value came from an analytics.<Helper>(...) call.
-// Both `:=` short declarations and `=` assignments at any nesting depth are
-// recognised. The set is conservative — re-assignments to non-analytics
-// values keep the ident in the set (we only track the originating
-// definition); call sites that cared could rewrite to use the helper inline.
-//
-// KNOWN LIMITATION (tracked as PR3 follow-up; see PR description):
-// matching is by ident NAME, not by SSA def-use. A pathological function
-// that shadows an analytics-backed name with a non-analytics binding in a
-// nested scope (e.g. an `if`/`for` re-declaration via `:=`) would still
-// pass this check, because the outer-scope name is in the allow-set. This
-// is rare in practice — every current call site assigns once at the same
-// scope as the RecordEvent call — but a future hardening pass should
-// switch to a real go/types or go/ssa walk so the lint is type-aware
-// rather than name-aware.
-func analyticsBackedIdents(body *ast.BlockStmt) map[string]struct{} {
- out := map[string]struct{}{}
- if body == nil {
- return out
- }
- ast.Inspect(body, func(n ast.Node) bool {
- switch stmt := n.(type) {
- case *ast.AssignStmt:
- // Match either lhs[i] = analytics.X(...) or lhs[i], _ := analytics.X(...).
- if len(stmt.Rhs) == 0 {
- return true
- }
- for i, lhs := range stmt.Lhs {
- if i >= len(stmt.Rhs) {
- // Multi-return-from-single-call shape (e.g. a, b := f())
- // — there is exactly one Rhs and we can't tell which
- // returned position the ident binds without type info.
- // Fall back to checking the single Rhs.
- if len(stmt.Rhs) == 1 && analyticsHelperCall(stmt.Rhs[0]) {
- if id, ok := lhs.(*ast.Ident); ok {
- out[id.Name] = struct{}{}
- }
- }
- continue
- }
- if id, ok := lhs.(*ast.Ident); ok && analyticsHelperCall(stmt.Rhs[i]) {
- out[id.Name] = struct{}{}
- }
- }
- case *ast.ValueSpec:
- // `var x = analytics.X(...)` and the like.
- for i, name := range stmt.Names {
- if i < len(stmt.Values) && analyticsHelperCall(stmt.Values[i]) {
- out[name.Name] = struct{}{}
- }
- }
- }
- return true
- })
- return out
-}
-
-// ---- helpers --------------------------------------------------------------
-
-// repoRoot returns the absolute path to server/. The test sources live in
-// server/internal/metrics/ so two parents up is the server root.
-func repoRoot(t *testing.T) string {
- _, thisFile, _, ok := runtime.Caller(0)
- if !ok {
- t.Fatalf("runtime.Caller failed")
- }
- // .../server/internal/metrics/business_pairing_test.go → .../server
- return filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", ".."))
-}
-
-// analyticsEventNames parses analytics/events.go and returns every Event*
-// constant value (the literal string passed to PostHog).
-func analyticsEventNames(t *testing.T) map[string]struct{} {
- t.Helper()
-
- path := filepath.Join(repoRoot(t), "internal", "analytics", "events.go")
- fset := token.NewFileSet()
- f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
- if err != nil {
- t.Fatalf("parse %s: %v", path, err)
- }
-
- out := map[string]struct{}{}
- for _, decl := range f.Decls {
- gen, ok := decl.(*ast.GenDecl)
- if !ok || gen.Tok != token.CONST {
- continue
- }
- for _, spec := range gen.Specs {
- vs, ok := spec.(*ast.ValueSpec)
- if !ok || len(vs.Values) == 0 {
- continue
- }
- for i, name := range vs.Names {
- if !strings.HasPrefix(name.Name, "Event") {
- continue
- }
- lit, ok := vs.Values[i].(*ast.BasicLit)
- if !ok || lit.Kind != token.STRING {
- continue
- }
- out[strings.Trim(lit.Value, "\"")] = struct{}{}
- }
- }
- }
- if len(out) == 0 {
- t.Fatalf("no Event* constants found in %s", path)
- }
- return out
-}
-
-// constantNameForEvent reverse-maps an event string to its Go constant name
-// for nicer error messages. Stable for the constants we ship.
-func constantNameForEvent(name string) string {
- parts := strings.Split(name, "_")
- for i, p := range parts {
- if len(p) == 0 {
- continue
- }
- parts[i] = strings.ToUpper(p[:1]) + p[1:]
- }
- return "Event" + strings.Join(parts, "")
-}
-
-// dispatchIncrementsCounter sends ev through RecordEvent (with a noop
-// PostHog client) and returns true when at least one Prometheus counter
-// receives a non-zero increment. We use a fresh BusinessMetrics per event
-// so a leftover prewarm value from another counter cannot mask a missing
-// dispatch case.
-func dispatchIncrementsCounter(m *metrics.BusinessMetrics, ev analytics.Event) bool {
- before := metrics.SumAllCounters(m)
- metrics.RecordEvent(analytics.NoopClient{}, m, ev)
- after := metrics.SumAllCounters(m)
- return after > before
-}
-
-// defaultPropsForEvent returns a properties map populated with the label
-// values the dispatcher reads, so the synthetic test event lights up its
-// matching counter without relying on the analytics helper plumbing.
-func defaultPropsForEvent(name string) map[string]any {
- switch name {
- case analytics.EventSignup:
- return map[string]any{"signup_source": "test"}
- case analytics.EventWorkspaceCreated:
- return map[string]any{"source": "manual"}
- case analytics.EventOnboardingStarted:
- return map[string]any{"platform": "web"}
- case analytics.EventOnboardingCompleted:
- return map[string]any{"completion_path": "full"}
- case analytics.EventIssueCreated:
- return map[string]any{"source": "manual", "platform": "web"}
- case analytics.EventChatMessageSent:
- return map[string]any{"platform": "web"}
- case analytics.EventAgentCreated:
- return map[string]any{"runtime_mode": "local", "source": "manual"}
- case analytics.EventAutopilotCreated:
- return map[string]any{"cadence": "manual"}
- case analytics.EventIssueExecuted:
- return map[string]any{"source": "manual"}
- case analytics.EventRuntimeRegistered, analytics.EventRuntimeReady, analytics.EventRuntimeOffline:
- return map[string]any{"runtime_mode": "local", "provider": "claude"}
- case analytics.EventRuntimeFailed:
- return map[string]any{"runtime_mode": "local", "provider": "claude", "failure_reason": "unknown", "recoverable": false}
- case analytics.EventAutopilotRunStarted, analytics.EventAutopilotRunCompleted, analytics.EventAutopilotRunFailed:
- return map[string]any{"cadence": "manual", "trigger_kind": "manual"}
- case analytics.EventFeedbackSubmitted:
- return map[string]any{"kind": "general", "platform": "web"}
- case analytics.EventContactSalesSubmitted:
- return map[string]any{"form_source": "page"}
- }
- return map[string]any{}
-}
-
-func isAnalyticsCapture(call *ast.CallExpr) bool {
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return false
- }
- if sel.Sel == nil || sel.Sel.Name != "Capture" {
- return false
- }
- // Receiver must be a selector ending in `.Analytics`.
- rec, ok := sel.X.(*ast.SelectorExpr)
- if !ok {
- return false
- }
- if rec.Sel == nil || rec.Sel.Name != "Analytics" {
- return false
- }
- // Must be passing an analytics helper or a local built from one — but
- // the lint principle is "no direct Capture", so any shape fails.
- return true
-}
-
-// isMetricsRecordEvent reports whether call is a metrics.RecordEvent
-// invocation. Recognises the two import aliases used in this codebase:
-// `obsmetrics` (everywhere outside the metrics package itself) and the
-// natural package name `metrics`.
-//
-// KNOWN LIMITATION (tracked as PR3 follow-up; see PR description):
-// the alias set is HARD-CODED. A future caller that imports the metrics
-// package under a third alias (`mx "..."`, etc.) would slip past this
-// check. The follow-up plan is to walk the file's import declarations
-// and resolve the alias for `server/internal/metrics` per-file, so any
-// alias works as long as the canonical import path matches. We leave it
-// hard-coded here because every current import in handler/, service/,
-// and cmd/server/ uses one of the two names, and goimports/`gofmt`
-// guidance keeps it that way.
-func isMetricsRecordEvent(call *ast.CallExpr) bool {
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return false
- }
- if sel.Sel == nil || sel.Sel.Name != "RecordEvent" {
- return false
- }
- pkg, ok := sel.X.(*ast.Ident)
- if !ok {
- return false
- }
- return pkg.Name == "obsmetrics" || pkg.Name == "metrics"
-}
-
-func analyticsHelperCall(expr ast.Expr) bool {
- call, ok := expr.(*ast.CallExpr)
- if !ok {
- return false
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return false
- }
- pkg, ok := sel.X.(*ast.Ident)
- if !ok {
- return false
- }
- return pkg.Name == "analytics" && sel.Sel != nil && len(sel.Sel.Name) > 0
-}
diff --git a/server/internal/metrics/channel_lease_test.go b/server/internal/metrics/channel_lease_test.go
deleted file mode 100644
index 5e2c9ea904..0000000000
--- a/server/internal/metrics/channel_lease_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package metrics
-
-import (
- "testing"
- "time"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-func TestChannelLeaseMetricsRegisterAndRecord(t *testing.T) {
- m := NewChannelLeaseMetrics()
- reg := prometheus.NewPedanticRegistry()
- reg.MustRegister(m.Collectors()...)
- m.RecordLeaseOperation("renew", "error")
- m.SetActiveLeaseOwners(2)
- m.SetOwnersWithRenewalErrors(1)
- m.SetLastSuccessfulRenewal(time.Unix(123, 0))
- m.ObserveTakeoverLatency(30 * time.Second)
-
- families, err := reg.Gather()
- if err != nil {
- t.Fatal(err)
- }
- want := map[string]bool{
- "multica_channel_lease_operations_total": false,
- "multica_channel_lease_active_owners": false,
- "multica_channel_lease_owners_with_renewal_errors": false,
- "multica_channel_lease_last_successful_renewal_timestamp_seconds": false,
- "multica_channel_lease_takeover_latency_seconds": false,
- }
- for _, family := range families {
- if _, ok := want[family.GetName()]; ok {
- want[family.GetName()] = true
- }
- }
- for name, seen := range want {
- if !seen {
- t.Fatalf("metric %s was not gathered", name)
- }
- }
-}
diff --git a/server/internal/metrics/labels_test.go b/server/internal/metrics/labels_test.go
index d4b1343907..e9bcf9d147 100644
--- a/server/internal/metrics/labels_test.go
+++ b/server/internal/metrics/labels_test.go
@@ -45,16 +45,3 @@ func TestNormalizeLabelsCollapseUnknownValues(t *testing.T) {
t.Fatalf("NormalizeTaskSource unknown = %q, want other", got)
}
}
-
-// TestForbiddenLabelsCoverChannelIdentifiers: the channel adapters (slack,
-// lark, dingtalk, wecom) all carry an installation id at every metric call
-// site, so it is the natural label to reach for. One series per installation
-// grows with tenants, not with the deployment — the same reason workspace_id
-// and session_id are on this list.
-func TestForbiddenLabelsCoverChannelIdentifiers(t *testing.T) {
- for _, label := range []string{"installation_id", "workspace_id", "session_id"} {
- if _, forbidden := forbiddenMetricLabels[label]; !forbidden {
- t.Errorf("%s is not forbidden — a per-tenant identifier will eventually be used as a metric label and multiply the series count by the tenant count", label)
- }
- }
-}
diff --git a/server/internal/metrics/wecom_test.go b/server/internal/metrics/wecom_test.go
index f0a53eeec7..701089ecda 100644
--- a/server/internal/metrics/wecom_test.go
+++ b/server/internal/metrics/wecom_test.go
@@ -4,60 +4,17 @@ import (
"testing"
"github.com/prometheus/client_golang/prometheus"
- dto "github.com/prometheus/client_model/go"
)
-// Every collector has to be registrable together. A duplicate name or a
-// malformed help string only surfaces at MustRegister, which in production is
-// process start.
-func TestWecomMetricsRegisterCleanly(t *testing.T) {
- reg := prometheus.NewRegistry()
- for _, c := range NewWecomMetrics().Collectors() {
- if err := reg.Register(c); err != nil {
- t.Fatalf("register: %v", err)
- }
- }
-}
-
-// The adapter's Metrics interface and this implementation must not drift. The
-// compile-time check lives in the adapter; this one catches a method that
-// exists but does nothing.
-func TestEveryWecomCounterActuallyCounts(t *testing.T) {
- reg := prometheus.NewRegistry()
- m := NewWecomMetrics()
- for _, c := range m.Collectors() {
- if err := reg.Register(c); err != nil {
- t.Fatalf("register: %v", err)
- }
- }
-
- m.RecordConnectFailure()
- m.RecordAuthFailure()
- m.RecordCallbackQueued()
- m.RecordCallbackQueueBlocked()
-
- seen := gatherWecomValues(t, reg)
- for _, want := range []string{
- "multica_wecom_connect_failures_total",
- "multica_wecom_auth_failures_total",
- "multica_wecom_inbound_callbacks_total",
- "multica_wecom_inbound_queue_blocked_total",
- } {
- if seen[want] != 1 {
- t.Errorf("%s = %v, want 1 — the counter is wired to nothing", want, seen[want])
- }
- }
-}
-
-// The whole point of two connection counters is that an operator can tell a
-// wrong secret from a dead network. Sharing a series would put them back to
-// guessing.
+// Authentication failures require an operator to fix the installation;
+// connection failures usually recover. Keep them as independently actionable
+// Prometheus series rather than allowing both methods to increment one counter.
func TestAuthAndConnectFailuresAreSeparateSeries(t *testing.T) {
reg := prometheus.NewRegistry()
m := NewWecomMetrics()
- for _, c := range m.Collectors() {
- if err := reg.Register(c); err != nil {
- t.Fatalf("register: %v", err)
+ for _, collector := range m.Collectors() {
+ if err := reg.Register(collector); err != nil {
+ t.Fatalf("register WeCom collector: %v", err)
}
}
@@ -65,159 +22,28 @@ func TestAuthAndConnectFailuresAreSeparateSeries(t *testing.T) {
m.RecordAuthFailure()
m.RecordConnectFailure()
- seen := gatherWecomValues(t, reg)
- if got := seen["multica_wecom_auth_failures_total"]; got != 2 {
+ values := gatherWecomCounterValues(t, reg)
+ if got := values["multica_wecom_auth_failures_total"]; got != 2 {
t.Errorf("auth failures = %v, want 2", got)
}
- if got := seen["multica_wecom_connect_failures_total"]; got != 1 {
+ if got := values["multica_wecom_connect_failures_total"]; got != 1 {
t.Errorf("connect failures = %v, want 1", got)
}
}
-// No metric here may carry an unbounded identifier as a label — the same rule
-// labels.go enforces for the rest of the codebase. installation_id is the one
-// that would be tempting to add, and it belongs in the logs instead. Those
-// carry it for the two connection failures, which reach the Supervisor as a
-// returned error; the two inbound counters have no log line beside them, so
-// leaving the label off really does cost the answer to "which bot" on those
-// two. That is the trade this test pins, not a free win.
-func TestWecomMetricsCarryNoUnboundedLabels(t *testing.T) {
- reg := prometheus.NewRegistry()
- m := NewWecomMetrics()
- for _, c := range m.Collectors() {
- if err := reg.Register(c); err != nil {
- t.Fatalf("register: %v", err)
- }
- }
- m.RecordConnectFailure()
- m.RecordAuthFailure()
- m.RecordCallbackQueued()
- m.RecordCallbackQueueBlocked()
-
- families, err := reg.Gather()
- if err != nil {
- t.Fatalf("gather: %v", err)
- }
- for _, f := range families {
- for _, metric := range f.GetMetric() {
- for _, l := range metric.GetLabel() {
- if _, forbidden := forbiddenMetricLabels[l.GetName()]; forbidden {
- t.Errorf("%s carries the unbounded label %q", f.GetName(), l.GetName())
- }
- if l.GetName() == "installation_id" {
- t.Errorf("%s labels by installation_id; that belongs in the logs", f.GetName())
- }
- }
- }
- }
-}
-
-// The registry is what production actually scrapes; a collector that is built
-// but never registered exports nothing.
-func TestTheRegistryExposesTheWecomCounters(t *testing.T) {
- r := NewRegistry(RegistryOptions{})
- if r.Wecom == nil {
- t.Fatal("Registry.Wecom is nil; nothing can report through it")
- }
- r.Wecom.RecordAuthFailure()
-
- families, err := r.Gatherer.Gather()
- if err != nil {
- t.Fatalf("gather: %v", err)
- }
- for _, f := range families {
- if f.GetName() == "multica_wecom_auth_failures_total" {
- return
- }
- }
- t.Fatal("multica_wecom_auth_failures_total is not on the registry the metrics server scrapes")
-}
-
-func gatherWecomValues(t *testing.T, reg prometheus.Gatherer) map[string]float64 {
+func gatherWecomCounterValues(t *testing.T, reg prometheus.Gatherer) map[string]float64 {
t.Helper()
families, err := reg.Gather()
if err != nil {
- t.Fatalf("gather: %v", err)
- }
- out := map[string]float64{}
- for _, f := range families {
- for _, metric := range f.GetMetric() {
- out[f.GetName()] = wecomValueOf(metric)
- }
- }
- return out
-}
-
-func wecomValueOf(m *dto.Metric) float64 {
- if c := m.GetCounter(); c != nil {
- return c.GetValue()
- }
- if g := m.GetGauge(); g != nil {
- return g.GetValue()
- }
- return 0
-}
-
-// TestWecomOutboundMetricsAreExported covers the EXPORTED contract, not the
-// adapter's test double: the names Prometheus will scrape, the reason label,
-// and that every collector is actually registered. A dashboard reads these
-// strings; a rename that only the double knows about is a silent outage of
-// whatever alert watches them.
-func TestWecomOutboundMetricsAreExported(t *testing.T) {
- m := NewWecomMetrics()
- reg := prometheus.NewRegistry()
- for _, c := range m.Collectors() {
- if err := reg.Register(c); err != nil {
- t.Fatalf("register: %v", err)
- }
- }
-
- m.RecordOutboundDelivered()
- m.RecordOutboundDropped("no_live_connection")
- m.RecordOutboundSkipped("origin_not_channel")
- m.RecordAttachmentDelivered()
- m.RecordAttachmentDropped("platform_refused")
- m.RecordAttachmentDeliveryShed()
- m.RecordOutboundUnconfirmed("ack_timeout")
- m.RecordAttachmentUnconfirmed("write_attempted")
-
- got, err := reg.Gather()
- if err != nil {
- t.Fatalf("gather: %v", err)
+ t.Fatalf("gather WeCom metrics: %v", err)
}
- seen := map[string]bool{}
- labels := map[string]string{}
- for _, mf := range got {
- seen[mf.GetName()] = true
- for _, mm := range mf.GetMetric() {
- for _, l := range mm.GetLabel() {
- labels[mf.GetName()+"/"+l.GetName()] = l.GetValue()
+ values := make(map[string]float64, len(families))
+ for _, family := range families {
+ for _, metric := range family.GetMetric() {
+ if counter := metric.GetCounter(); counter != nil {
+ values[family.GetName()] += counter.GetValue()
}
}
}
- for _, want := range []string{
- "multica_wecom_outbound_delivered_total",
- "multica_wecom_outbound_dropped_total",
- "multica_wecom_outbound_skipped_total",
- "multica_wecom_outbound_attachment_delivered_total",
- "multica_wecom_outbound_attachment_dropped_total",
- "multica_wecom_outbound_attachment_delivery_shed_total",
- "multica_wecom_outbound_unconfirmed_total",
- "multica_wecom_outbound_attachment_unconfirmed_total",
- } {
- if !seen[want] {
- t.Errorf("%s was not exported", want)
- }
- }
- for name, want := range map[string]string{
- "multica_wecom_outbound_dropped_total/reason": "no_live_connection",
- "multica_wecom_outbound_skipped_total/reason": "origin_not_channel",
- "multica_wecom_outbound_attachment_dropped_total/reason": "platform_refused",
- "multica_wecom_outbound_unconfirmed_total/reason": "ack_timeout",
- "multica_wecom_outbound_attachment_unconfirmed_total/reason": "write_attempted",
- } {
- if labels[name] != want {
- t.Errorf("%s = %q, want %q", name, labels[name], want)
- }
- }
+ return values
}
diff --git a/server/internal/middleware/client_test.go b/server/internal/middleware/client_test.go
index 94eafb7b60..b34b59adaa 100644
--- a/server/internal/middleware/client_test.go
+++ b/server/internal/middleware/client_test.go
@@ -42,13 +42,3 @@ func TestClientMetadataMissingHeadersReturnEmpty(t *testing.T) {
t.Errorf("expected empty metadata, got (%q,%q,%q)", gotPlatform, gotVersion, gotOS)
}
}
-
-func TestSetClientMetadataAttachesValues(t *testing.T) {
- req := httptest.NewRequest(http.MethodGet, "/", nil)
- ctx := SetClientMetadata(req.Context(), "cli", "0.5.1", "linux")
-
- platform, version, os := ClientMetadataFromContext(ctx)
- if platform != "cli" || version != "0.5.1" || os != "linux" {
- t.Errorf("got (%q,%q,%q), want (cli,0.5.1,linux)", platform, version, os)
- }
-}
diff --git a/server/internal/migrations/migrations_lint_test.go b/server/internal/migrations/migrations_lint_test.go
index 48c932c190..9fda137217 100644
--- a/server/internal/migrations/migrations_lint_test.go
+++ b/server/internal/migrations/migrations_lint_test.go
@@ -3,57 +3,12 @@ package migrations
import (
"fmt"
"path/filepath"
- "reflect"
- "regexp"
"runtime"
"sort"
- "strconv"
"strings"
"testing"
)
-const maxLegacyMigrationPrefix = 148
-
-// legacyDuplicateMigrationStems lists prefixes that were already duplicated
-// before this lint existed. It is a frozen historical record, not an escape
-// hatch: a new collision must be renumbered instead of added here. Prefix 362
-// was briefly listed and is deliberately absent again — the later of the two
-// migrations was renumbered to 376, which its idempotent DDL made safe.
-var legacyDuplicateMigrationStems = map[string][]string{
- "020": {"020_issue_number", "020_task_session"},
- "026": {"026_comment_reactions", "026_task_messages"},
- "029": {"029_attachment", "029_daemon_token", "029_drop_daemon_pairing"},
- "032": {"032_drop_agent_triggers", "032_issue_search_index", "032_runtime_owner", "032_task_usage"},
- "033": {"033_chat", "033_comment_search_index"},
- "035": {"035_project_priority", "035_task_queue_issue_id_index"},
- "040": {"040_agent_custom_env", "040_chat_unread_since"},
- "041": {"041_agent_custom_args", "041_workspace_invitation"},
- "043": {"043_audit_reserved_slugs", "043_fix_orphaned_autopilot_runs"},
- "046": {"046_agent_mcp_config", "046_agent_unique_name", "046_drop_runtime_usage"},
- "050": {"050_add_onboarded_at_to_users", "050_agent_model", "050_issue_first_executed_at"},
- "060": {"060_add_user_language", "060_agent_description_length", "060_chat_session_runtime_id", "060_issue_origin_quick_create"},
- "065": {"065_backfill_onboarded_at", "065_project_resources"},
- "069": {"069_comment_resolved_at", "069_drop_task_last_heartbeat"},
- "079": {"079_autopilot_run_skipped_status", "079_backfill_api_invalid_request", "079_github_integration"},
- "083": {"083_attachment_chat_columns", "083_runtime_visibility"},
- "084": {"084_squad", "084_task_usage_dashboard_rollup"},
- "091": {"091_autopilot_webhook_triggers", "091_issue_start_date", "091_pr_ci_conflict"},
- "095": {"095_agent_thinking_level", "095_backfill_starter_content_state"},
- "096": {"096_autopilot_squad_assignee", "096_pending_check_suite", "096_user_profile_description"},
- "098": {"098_contact_sales_inquiries", "098_user_onboarding_runtime_choice"},
- "109": {"109_agent_task_waiting_local_directory", "109_drop_agent_skills_local", "109_issue_pull_request_close_intent", "109_lark_integration"},
- "111": {"111_issue_origin_lark_chat", "111_workspace_avatar"},
- "112": {"112_issue_dates_to_date", "112_lark_installation_bot_union_id"},
- "113": {"113_lark_inbound_dedup_per_installation", "113_sys_cron_executions"},
- "120": {"120_autopilot_subscriber", "120_comment_source_task_id", "120_github_pending_installation", "120_runtime_profile"},
- "122": {"122_lark_chat_session_binding_thread_reply", "122_task_handoff_note"},
- "124": {"124_autopilot_run_planned_at", "124_channel_generalization", "124_task_prepare_lease"},
- "127": {"127_issue_pull_request_reference_only", "127_task_squad_id", "127_user_composio_connection"},
- "128": {"128_agent_task_queue_runtime_mcp_overlay", "128_autopilot_collaborator", "128_comment_routing_escalation"},
-}
-
-var migrationPrefixPattern = regexp.MustCompile(`^(\d+)_`)
-
func TestMigrationFilesHaveMatchingDirections(t *testing.T) {
files := migrationFilesForLint(t, "*.sql")
@@ -76,58 +31,6 @@ func TestMigrationFilesHaveMatchingDirections(t *testing.T) {
}
}
-func TestMigrationNumericPrefixesStayUniqueAfterLegacySet(t *testing.T) {
- stemsByPrefix := migrationStemsByPrefix(t)
-
- for prefix, stems := range stemsByPrefix {
- sort.Strings(stems)
-
- legacyStems, isLegacyDuplicate := legacyDuplicateMigrationStems[prefix]
- if isLegacyDuplicate {
- expected := append([]string(nil), legacyStems...)
- sort.Strings(expected)
- if !reflect.DeepEqual(stems, expected) {
- t.Errorf("legacy duplicate migration prefix %s changed: got %v, want %v; do not add to or rename historical duplicate-prefix migrations", prefix, stems, expected)
- }
- continue
- }
-
- if len(stems) > 1 {
- t.Errorf("migration prefix %s is reused by %v; use the next unique prefix instead", prefix, stems)
- }
- }
-}
-
-func TestNewMigrationPrefixesStartAfterLegacyRange(t *testing.T) {
- stemsByPrefix := migrationStemsByPrefix(t)
-
- for prefix, stems := range stemsByPrefix {
- n, err := strconv.Atoi(prefix)
- if err != nil {
- t.Fatalf("parse migration prefix %q: %v", prefix, err)
- }
- if n <= maxLegacyMigrationPrefix && !isKnownLegacyPrefix(prefix) {
- t.Errorf("migration prefix %s is in the frozen legacy range 001-%03d: %v; new migrations must start at %03d", prefix, maxLegacyMigrationPrefix, stems, maxLegacyMigrationPrefix+1)
- }
- }
-}
-
-func migrationStemsByPrefix(t *testing.T) map[string][]string {
- t.Helper()
-
- files := migrationFilesForLint(t, "*.up.sql")
- stemsByPrefix := make(map[string][]string)
- for _, file := range files {
- stem := strings.TrimSuffix(filepath.Base(file), ".up.sql")
- match := migrationPrefixPattern.FindStringSubmatch(stem)
- if match == nil {
- t.Fatalf("migration %s does not start with a numeric prefix followed by underscore", stem)
- }
- stemsByPrefix[match[1]] = append(stemsByPrefix[match[1]], stem)
- }
- return stemsByPrefix
-}
-
func migrationFilesForLint(t *testing.T, pattern string) []string {
t.Helper()
@@ -162,27 +65,3 @@ func splitMigrationFilename(name string) (stem, direction string, ok bool) {
}
return "", "", false
}
-
-func isKnownLegacyPrefix(prefix string) bool {
- if _, ok := legacyDuplicateMigrationStems[prefix]; ok {
- return true
- }
-
- switch prefix {
- case "001", "002", "003", "004", "005", "006", "007", "008", "009", "010",
- "011", "012", "013", "014", "015", "016", "017", "018", "019", "021",
- "022", "023", "024", "025", "027", "028", "030", "031", "034", "036",
- "037", "038", "039", "042", "044", "045", "047", "048", "049", "051",
- "052", "053", "054", "055", "056", "057", "058", "059", "061", "062",
- "063", "064", "066", "067", "068", "072", "073", "074", "075", "076",
- "077", "078", "080", "081", "082", "085", "086", "087", "088", "089",
- "090", "092", "093", "094", "097", "100", "101", "102", "103", "104",
- "105", "106", "107", "108", "110", "114", "115", "116", "117", "118",
- "119", "121", "123", "125", "126", "129", "130", "131", "132", "133",
- "134", "135", "136", "137", "138", "139", "140", "141", "142", "143",
- "144", "145", "146", "147", "148":
- return true
- default:
- return false
- }
-}
diff --git a/server/internal/realtime/metrics_test.go b/server/internal/realtime/metrics_test.go
index c7fa35b87e..8f8908b2ff 100644
--- a/server/internal/realtime/metrics_test.go
+++ b/server/internal/realtime/metrics_test.go
@@ -90,9 +90,3 @@ func TestMetricsAggregatesStreamsWithoutTTLAcrossRelayModes(t *testing.T) {
t.Fatalf("streams without TTL after sharded repair = %d, want 2", got)
}
}
-
-// Compile-time guarantee that *Hub continues to satisfy Broadcaster, in case
-// someone changes hub.go method signatures without updating the interface.
-func TestHubImplementsBroadcaster(t *testing.T) {
- var _ Broadcaster = NewHub()
-}
diff --git a/server/internal/seatcapacity/workspace_locker_test.go b/server/internal/seatcapacity/workspace_locker_test.go
deleted file mode 100644
index b83cf2aaa9..0000000000
--- a/server/internal/seatcapacity/workspace_locker_test.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package seatcapacity
-
-import (
- "testing"
-
- "github.com/google/uuid"
-)
-
-func TestWorkspaceAdvisoryLockKeyIsStableAndWorkspaceScoped(t *testing.T) {
- workspaceA := uuid.MustParse("0193f876-4f3a-7d9c-8d8e-cb944847a001")
- workspaceB := uuid.MustParse("0193f876-4f3a-7d9c-8d8e-cb944847a002")
- if workspaceAdvisoryLockKey(workspaceA) != workspaceAdvisoryLockKey(workspaceA) {
- t.Fatal("workspace advisory lock key is not stable")
- }
- if workspaceAdvisoryLockKey(workspaceA) == workspaceAdvisoryLockKey(workspaceB) {
- t.Fatal("different workspaces share an advisory lock key")
- }
-}
diff --git a/server/internal/service/autopilot_squad_test.go b/server/internal/service/autopilot_squad_test.go
index ed08e30541..0798746714 100644
--- a/server/internal/service/autopilot_squad_test.go
+++ b/server/internal/service/autopilot_squad_test.go
@@ -82,15 +82,3 @@ func TestErrDispatchSkippedUnwraps(t *testing.T) {
t.Fatal("pgx.ErrNoRows wrongly satisfied errDispatchSkipped")
}
}
-
-func TestResolveAutopilotLeaderSentinels(t *testing.T) {
- // Sanity-check the sentinel exported via errors.Is so callers can branch
- // on "archived" without string-matching the failure reason.
- if !errors.Is(errSquadArchived, errSquadArchived) {
- t.Fatal("errSquadArchived must satisfy errors.Is itself")
- }
- wrapped := fmt.Errorf("wrap: %w", errSquadArchived)
- if !errors.Is(wrapped, errSquadArchived) {
- t.Fatal("errSquadArchived must unwrap through fmt.Errorf")
- }
-}
diff --git a/server/internal/service/channel_media_reconciler_test.go b/server/internal/service/channel_media_reconciler_test.go
index 376ab17320..df29ad98ee 100644
--- a/server/internal/service/channel_media_reconciler_test.go
+++ b/server/internal/service/channel_media_reconciler_test.go
@@ -325,27 +325,6 @@ func TestChannelMediaReconciler_LeavesFreshPendingToBind(t *testing.T) {
}
}
-func TestChannelMediaReconciler_SettleInvariantDwarfsPipelineBudgets(t *testing.T) {
- // The settle delay is an operational buffer with NO correctness weight —
- // correctness comes from the 'deleting' state flip. This invariant only
- // guarantees the reconciler is never doing wasted work while a healthy
- // pipeline is still running: it must dwarf every inline budget.
- const maxPipelineBudget = 45 * time.Second // engine media budget / lark download cap (see cmd/server invariant test for the cross-package assertion)
- if ChannelMediaReconcileSettleDelay < 10*maxPipelineBudget {
- t.Fatalf("settle %v must be >= 10x the largest pipeline budget %v", ChannelMediaReconcileSettleDelay, maxPipelineBudget)
- }
- if channelMediaReconcileLease <= 0 || channelMediaReconcileLease >= ChannelMediaReconcileSettleDelay {
- t.Fatalf("lease %v must be positive and well under settle %v", channelMediaReconcileLease, ChannelMediaReconcileSettleDelay)
- }
- // A row is claimed immediately before its own settle, so the lease only
- // ever needs to cover ONE row's worst case (a delete at its full timeout
- // plus DB round-trips) — never a whole sweep. 2x margin keeps the owner
- // comfortably ahead of expiry.
- if channelMediaReconcileLease < 2*channelMediaReconcileDeleteTimeout {
- t.Fatalf("lease %v must be >= 2x the per-delete timeout %v", channelMediaReconcileLease, channelMediaReconcileDeleteTimeout)
- }
-}
-
// Storage initialization can fail at boot (no S3, unwritable local dir) while
// ledger rows pre-exist from an earlier boot where storage worked. A nil
// deleter must never panic the worker — and must not claim rows either, or
diff --git a/server/internal/service/plugin_test.go b/server/internal/service/plugin_test.go
index 0691b8d123..423c92248d 100644
--- a/server/internal/service/plugin_test.go
+++ b/server/internal/service/plugin_test.go
@@ -311,60 +311,6 @@ func TestCapabilityMessageNamesTheMissingCapabilities(t *testing.T) {
}
}
-// Binds every shipped capability to the host code that actually runs it.
-//
-// The gate is only meaningful if it tracks what renders. A capability enabled
-// here with no mount point installs successfully and then never appears — the
-// exact silent failure the gate exists to prevent — and nothing else in the
-// build would notice, because the manifest is valid and the install succeeds.
-//
-// Each line names the host code that makes it true. Flipping one on means
-// changing this file too, in the same commit as its runtime.
-func TestShippedHostCapabilitiesRunTheSurfacesTheHostMounts(t *testing.T) {
- shipped := plugincontract.HostCapabilities()
-
- // packages/views/plugins/plugin-panel-section.tsx
- if !shipped.SurfaceTypes[plugincontract.SurfaceIssuePanel] {
- t.Fatal("issue_panel is mounted by PluginPanelSection and must be shipped")
- }
- // packages/views/plugins/plugin-modal-surface.tsx, opened from the issue
- // actions menu by a person — never on the plugin's own initiative.
- if !shipped.SurfaceTypes[plugincontract.SurfaceModal] {
- t.Fatal("modal is mounted by PluginModalSurface and must be shipped")
- }
- // No host location exists for this one. Enabling it would install surfaces
- // that never render.
- if shipped.SurfaceTypes[plugincontract.SurfaceSidebarPanel] {
- t.Fatal("sidebar_panel has no mount point yet; enabling it would install surfaces that never render")
- }
-
- // handler.InvokePluginHook serves ui and manual; service.PluginEventDispatcher
- // serves event off the internal bus; daemon/plugin_hook_mcp.go renders
- // agent-trigger hooks as MCP tools.
- for _, trigger := range []string{
- plugincontract.TriggerUI, plugincontract.TriggerManual,
- plugincontract.TriggerEvent, plugincontract.TriggerAgent,
- } {
- if !shipped.HookTriggers[trigger] {
- t.Fatalf("hook trigger %q has a host call site and must be shipped", trigger)
- }
- }
-
- // service.callHookEndpoint speaks http; service.AgentMCPConnections turns an
- // approved mcp hook into a broker connection.
- for _, transport := range []string{plugincontract.TransportHTTP, plugincontract.TransportMCP} {
- if !shipped.HookTransport[transport] {
- t.Fatalf("hook transport %q has an implementation and must be shipped", transport)
- }
- }
-
- // service.InstallSkillResources writes these into the skill table, and
- // Uninstall removes them again.
- if !shipped.ResourceTypes[plugincontract.ResourceSkill] {
- t.Fatal("skill resources are installed by InstallSkillResources and must be shipped")
- }
-}
-
func TestEnforceStorageQuota(t *testing.T) {
// Canonical layer for the three storage limits. SetStorageValue only wires
// the usage query to this function; plugin_storage_db_test.go covers the
@@ -434,24 +380,3 @@ func TestEnforceStorageQuotaCountsBytesNotCharacters(t *testing.T) {
t.Fatal("fixture does not distinguish characters from bytes")
}
}
-
-func TestOrphanedSecretFieldsAreDetectedByType(t *testing.T) {
- // The pure half of upgrade-time secret pruning: which stored keys the new
- // manifest no longer declares as a secret. A field that changed type away
- // from secret counts as orphaned — its ciphertext is unreachable too.
- manifest := testManifest(t)
- for _, tc := range []struct {
- key string
- want bool
- }{
- {"token", false},
- {"repo", true},
- {"removed_field", true},
- } {
- field, ok := manifest.Config.Field(tc.key)
- orphaned := !ok || field.Type != plugincontract.ConfigSecret
- if orphaned != tc.want {
- t.Fatalf("%q orphaned = %v, want %v", tc.key, orphaned, tc.want)
- }
- }
-}
diff --git a/server/pkg/agent/agent_supported_types_test.go b/server/pkg/agent/agent_supported_types_test.go
index f4dfcb143c..e81917be7f 100644
--- a/server/pkg/agent/agent_supported_types_test.go
+++ b/server/pkg/agent/agent_supported_types_test.go
@@ -32,23 +32,3 @@ func TestSupportedTypesLockstepWithNew(t *testing.T) {
t.Errorf("New(%q) succeeded, want error for an unsupported type", bogus)
}
}
-
-// TestSupportedTypesMatchesMigrationWhitelist pins the exact set so a drift
-// from the runtime_profile.protocol_family CHECK fails loudly.
-func TestSupportedTypesMatchesMigrationWhitelist(t *testing.T) {
- want := map[string]bool{
- "claude": true, "codebuddy": true, "codex": true, "copilot": true,
- "opencode": true, "codearts": true, "deveco": true, "openclaw": true, "hermes": true,
- "pi": true, "cursor": true, "kimi": true, "reasonix": true, "dsh": true, "kiro": true, "antigravity": true,
- "qoder": true, "qoderclicn": true, "traecli": true, "grok": true, "qwen": true, "qwenpaw": true, "mcode": true,
- "dim": true, "zeroclaw": true,
- }
- if len(SupportedTypes) != len(want) {
- t.Fatalf("SupportedTypes has %d entries, migration whitelist has %d; keep them in lockstep", len(SupportedTypes), len(want))
- }
- for _, typ := range SupportedTypes {
- if !want[typ] {
- t.Errorf("SupportedTypes contains %q which is not in the latest protocol_family CHECK", typ)
- }
- }
-}
diff --git a/server/pkg/agent/agent_test.go b/server/pkg/agent/agent_test.go
index bce872b30f..9e49efa706 100644
--- a/server/pkg/agent/agent_test.go
+++ b/server/pkg/agent/agent_test.go
@@ -12,28 +12,6 @@ import (
"time"
)
-func TestNewReturnsClaudeBackend(t *testing.T) {
- t.Parallel()
- b, err := New("claude", Config{ExecutablePath: "/nonexistent/claude"})
- if err != nil {
- t.Fatalf("New(claude) error: %v", err)
- }
- if _, ok := b.(*claudeBackend); !ok {
- t.Fatalf("expected *claudeBackend, got %T", b)
- }
-}
-
-func TestNewReturnsCodexBackend(t *testing.T) {
- t.Parallel()
- b, err := New("codex", Config{ExecutablePath: "/nonexistent/codex"})
- if err != nil {
- t.Fatalf("New(codex) error: %v", err)
- }
- if _, ok := b.(*codexBackend); !ok {
- t.Fatalf("expected *codexBackend, got %T", b)
- }
-}
-
func TestNewReturnsCodebuddyBackend(t *testing.T) {
t.Parallel()
b, err := New("codebuddy", Config{ExecutablePath: "/nonexistent/codebuddy"})
@@ -45,17 +23,6 @@ func TestNewReturnsCodebuddyBackend(t *testing.T) {
}
}
-func TestNewReturnsCopilotBackend(t *testing.T) {
- t.Parallel()
- b, err := New("copilot", Config{ExecutablePath: "/nonexistent/copilot"})
- if err != nil {
- t.Fatalf("New(copilot) error: %v", err)
- }
- if _, ok := b.(*copilotBackend); !ok {
- t.Fatalf("expected *copilotBackend, got %T", b)
- }
-}
-
func TestNewReturnsQoderBackend(t *testing.T) {
t.Parallel()
b, err := New("qoder", Config{ExecutablePath: "/nonexistent/qodercli"})
@@ -86,17 +53,6 @@ func TestNewReturnsQoderCNBackend(t *testing.T) {
}
}
-func TestNewReturnsAntigravityBackend(t *testing.T) {
- t.Parallel()
- b, err := New("antigravity", Config{ExecutablePath: "/nonexistent/agy"})
- if err != nil {
- t.Fatalf("New(antigravity) error: %v", err)
- }
- if _, ok := b.(*antigravityBackend); !ok {
- t.Fatalf("expected *antigravityBackend, got %T", b)
- }
-}
-
func TestNewRejectsUnknownType(t *testing.T) {
t.Parallel()
_, err := New("gpt", Config{})
@@ -198,18 +154,6 @@ func TestLaunchHeaderCoversAllSupportedBackends(t *testing.T) {
}
}
-func TestLaunchHeaderAntigravityAvoidsTextOnlyPrintModeLabel(t *testing.T) {
- t.Parallel()
-
- header := LaunchHeader("antigravity")
- if header != "agy -p (non-interactive)" {
- t.Fatalf("unexpected Antigravity launch header: %q", header)
- }
- if strings.Contains(header, "print mode") {
- t.Fatalf("Antigravity launch header must not imply a text-only mode: %q", header)
- }
-}
-
func TestLaunchHeaderReturnsEmptyForUnknownType(t *testing.T) {
t.Parallel()
if header := LaunchHeader("made-up-agent"); header != "" {
diff --git a/server/pkg/agent/browser_mcp_config_test.go b/server/pkg/agent/browser_mcp_config_test.go
index 91ad7cbdef..2305875ca3 100644
--- a/server/pkg/agent/browser_mcp_config_test.go
+++ b/server/pkg/agent/browser_mcp_config_test.go
@@ -2,7 +2,6 @@ package agent
import (
"encoding/json"
- "errors"
"os"
"path/filepath"
"strings"
@@ -179,11 +178,3 @@ func TestWindowsChromiumFallbackExecutablePropagatesOverride(t *testing.T) {
t.Fatalf("fallback executable = %q, %v; want %q, true", got, ok, override)
}
}
-
-func TestWithBrowserMcpTestHostUsesMissingStat(t *testing.T) {
- withBrowserMcpTestHost(t, "windows", nil, nil)
- _, err := browserMcpStat("missing")
- if !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("browserMcpStat missing error = %v, want os.ErrNotExist", err)
- }
-}
diff --git a/server/pkg/agent/cursor_test.go b/server/pkg/agent/cursor_test.go
index 6151765b25..c9be588656 100644
--- a/server/pkg/agent/cursor_test.go
+++ b/server/pkg/agent/cursor_test.go
@@ -8,17 +8,6 @@ import (
"testing"
)
-func TestNewReturnsCursorBackend(t *testing.T) {
- t.Parallel()
- b, err := New("cursor", Config{ExecutablePath: "/nonexistent/cursor-agent"})
- if err != nil {
- t.Fatalf("New(cursor) error: %v", err)
- }
- if _, ok := b.(*cursorBackend); !ok {
- t.Fatalf("expected *cursorBackend, got %T", b)
- }
-}
-
func TestBuildCursorArgs(t *testing.T) {
t.Parallel()
diff --git a/server/pkg/agent/dim_test.go b/server/pkg/agent/dim_test.go
index 1096baae8c..1020923932 100644
--- a/server/pkg/agent/dim_test.go
+++ b/server/pkg/agent/dim_test.go
@@ -12,25 +12,6 @@ import (
"time"
)
-func TestNewReturnsDimBackend(t *testing.T) {
- t.Parallel()
- b, err := New("dim", Config{ExecutablePath: "/nonexistent/dim"})
- if err != nil {
- t.Fatalf("New(dim) error: %v", err)
- }
- if _, ok := b.(*dimBackend); !ok {
- t.Fatalf("expected *dimBackend, got %T", b)
- }
-}
-
-func TestDimModelSelectionSupported(t *testing.T) {
- t.Parallel()
- // Dim's session/set_model is session-scoped, so model override works.
- if !ModelSelectionSupported("dim") {
- t.Fatal("ModelSelectionSupported(dim) should return true")
- }
-}
-
// fakeDimACPScript impersonates `dim acp` for unit tests. Dim 0.3.10+
// releases its per-process session lock shortly after the owning process
// exits, so a follow-up run resumes via the standard ACP session/load. This
diff --git a/server/pkg/agent/dsh_test.go b/server/pkg/agent/dsh_test.go
index 4908206049..ea2c7adf5c 100644
--- a/server/pkg/agent/dsh_test.go
+++ b/server/pkg/agent/dsh_test.go
@@ -12,16 +12,6 @@ import (
"time"
)
-func TestNewDshBackend(t *testing.T) {
- b, err := New("dsh", Config{ExecutablePath: "/nonexistent/dsh"})
- if err != nil {
- t.Fatalf("New(dsh): %v", err)
- }
- if _, ok := b.(*dshBackend); !ok {
- t.Fatalf("New(dsh) returned %T", b)
- }
-}
-
func TestParseDshModelID(t *testing.T) {
got, err := parseDshModelID("deepseek-official/deepseek-v4%2Fflash")
if err != nil {
diff --git a/server/pkg/agent/grok_test.go b/server/pkg/agent/grok_test.go
index 7c41013729..80f3fd4ab1 100644
--- a/server/pkg/agent/grok_test.go
+++ b/server/pkg/agent/grok_test.go
@@ -11,17 +11,6 @@ import (
"time"
)
-func TestNewReturnsGrokBackend(t *testing.T) {
- t.Parallel()
- b, err := New("grok", Config{ExecutablePath: "/nonexistent/grok"})
- if err != nil {
- t.Fatalf("New(grok) error: %v", err)
- }
- if _, ok := b.(*grokBackend); !ok {
- t.Fatalf("expected *grokBackend, got %T", b)
- }
-}
-
// fakeGrokACPScript impersonates `grok agent --always-approve stdio` for unit
// tests. Wire format mirrors other Multica ACP fakes (traecli/kimi): method
// "session/update" with update.sessionUpdate discriminators, session/new
diff --git a/server/pkg/agent/hermes_model_discovery_test.go b/server/pkg/agent/hermes_model_discovery_test.go
index 37f59f3aa8..de543a76fc 100644
--- a/server/pkg/agent/hermes_model_discovery_test.go
+++ b/server/pkg/agent/hermes_model_discovery_test.go
@@ -4,7 +4,6 @@ import (
"fmt"
"strings"
"testing"
- "time"
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
@@ -101,46 +100,6 @@ func TestHermesDiscoveryHintDoesNotReclassifyTheFailure(t *testing.T) {
}
}
-// TestHermesDiscoveryTimeoutLeavesRoomForReportRetryBackoffs is the reason the
-// per-provider knob exists, and pins both ends of it.
-//
-// Lower bound: measured against hermes 0.20.0, a healthy session/new returns in
-// ~2s but a hermes whose configured provider cannot be resolved spends ~25s
-// before reporting "No LLM provider configured" — the exact case MUL-6606 is
-// about. Under the shared 15s default that diagnosis was replaced by "context
-// deadline exceeded", so the budget must clear ~25s with margin.
-//
-// Upper bound: the server closes a CLAIMED request after
-// handler.modelListRunningTimeout (60s), measured from RunStartedAt — which
-// PopPending sets at claim time. Heartbeat pickup happens BEFORE the claim and
-// is bounded separately by modelListPendingTimeout, so it does not eat into this
-// 60s; what does share it is the daemon's report-retry backoff schedule
-// (runtimeReportBackoffs, ≈6.5s). Discovery plus those scheduled sleeps must
-// leave room inside 60s for report attempts. This test deliberately does not
-// model the HTTP attempts themselves; those have a separate client timeout.
-func TestHermesDiscoveryTimeoutLeavesRoomForReportRetryBackoffs(t *testing.T) {
- t.Parallel()
-
- // Mirrors internal/handler.modelListRunningTimeout and
- // internal/daemon.runtimeReportBackoffs. Duplicated rather than imported
- // because pkg/agent must not depend on either package; the comment above is
- // the contract, and this test is what notices when it drifts.
- const serverRunningWindow = 60 * time.Second
- const reportRetryBackoffBudget = 6500 * time.Millisecond
-
- if hermesDiscoveryTimeout <= acpDiscoveryDefaultTimeout {
- t.Fatalf("hermes budget %s must exceed the shared default %s; its failure path needs ~25s",
- hermesDiscoveryTimeout, acpDiscoveryDefaultTimeout)
- }
- if hermesDiscoveryTimeout < 30*time.Second {
- t.Errorf("hermes budget %s leaves no margin over the ~25s failure path", hermesDiscoveryTimeout)
- }
- if got := hermesDiscoveryTimeout + reportRetryBackoffBudget; got > serverRunningWindow {
- t.Errorf("discovery (%s) plus report retry backoffs (%s) = %s, which outlives the server's %s claimed-request window",
- hermesDiscoveryTimeout, reportRetryBackoffBudget, got, serverRunningWindow)
- }
-}
-
type errString string
func (e errString) Error() string { return string(e) }
diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.go
index b6129c7c00..e81ebe02cb 100644
--- a/server/pkg/agent/hermes_test.go
+++ b/server/pkg/agent/hermes_test.go
@@ -16,17 +16,6 @@ import (
"time"
)
-func TestNewReturnsHermesBackend(t *testing.T) {
- t.Parallel()
- b, err := New("hermes", Config{ExecutablePath: "/nonexistent/hermes"})
- if err != nil {
- t.Fatalf("New(hermes) error: %v", err)
- }
- if _, ok := b.(*hermesBackend); !ok {
- t.Fatalf("expected *hermesBackend, got %T", b)
- }
-}
-
// ── extractACPSessionID ──
func TestExtractACPSessionID(t *testing.T) {
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index 03b9dd6a53..2d32d01817 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -16,17 +16,6 @@ import (
"github.com/multica-ai/multica/server/pkg/taskfailure"
)
-func TestNewReturnsKimiBackend(t *testing.T) {
- t.Parallel()
- b, err := New("kimi", Config{ExecutablePath: "/nonexistent/kimi"})
- if err != nil {
- t.Fatalf("New(kimi) error: %v", err)
- }
- if _, ok := b.(*kimiBackend); !ok {
- t.Fatalf("expected *kimiBackend, got %T", b)
- }
-}
-
func TestKimiToolNameFromTitle(t *testing.T) {
t.Parallel()
tests := []struct {
diff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.go
index bb319041f8..d15560f068 100644
--- a/server/pkg/agent/kiro_test.go
+++ b/server/pkg/agent/kiro_test.go
@@ -11,17 +11,6 @@ import (
"time"
)
-func TestNewReturnsKiroBackend(t *testing.T) {
- t.Parallel()
- b, err := New("kiro", Config{ExecutablePath: "/nonexistent/kiro-cli"})
- if err != nil {
- t.Fatalf("New(kiro) error: %v", err)
- }
- if _, ok := b.(*kiroBackend); !ok {
- t.Fatalf("expected *kiroBackend, got %T", b)
- }
-}
-
func TestKiroToolNameFromTitle(t *testing.T) {
t.Parallel()
tests := []struct {
diff --git a/server/pkg/agent/launch_test.go b/server/pkg/agent/launch_test.go
index 47a0739a47..8a054abc7b 100644
--- a/server/pkg/agent/launch_test.go
+++ b/server/pkg/agent/launch_test.go
@@ -3,9 +3,6 @@ package agent
import (
"bytes"
"context"
- "go/ast"
- "go/parser"
- "go/token"
"log/slog"
"os"
"os/exec"
@@ -123,26 +120,6 @@ func TestNewFiltersLaunchPrefixOnce(t *testing.T) {
}
}
-// TestLaunchPrefixReachesACPFamilies is the regression guard for the half of
-// the bug the report did not name: fixed_args used to ride on ExtraArgs, which
-// the ACP backends never read, so on those families it was silently dropped
-// rather than merely misordered. The prefix must land ahead of the hardcoded
-// `acp` subcommand.
-func TestLaunchPrefixReachesACPFamilies(t *testing.T) {
- t.Parallel()
-
- for _, family := range []string{"kimi", "hermes", "kiro", "reasonix", "qwenpaw", "dim", "zeroclaw"} {
- t.Run(family, func(t *testing.T) {
- t.Parallel()
- cfg := Config{LaunchPrefix: []string{"start", "q36"}, Logger: slog.Default()}
- argv := cfg.commandAt("wrapper").Argv("acp")
- if idx := prefixIndex(argv, []string{"start", "q36", "acp"}); idx != 0 {
- t.Fatalf("%s: prefix must precede the acp subcommand, got %v", family, argv)
- }
- })
- }
-}
-
// TestDiscoveryCacheKeySeparatesLaunchPrefixes: one binary behind two
// different prefixes is two different catalogs.
func TestDiscoveryCacheKeySeparatesLaunchPrefixes(t *testing.T) {
@@ -316,413 +293,6 @@ func TestBackendFactoriesSetCommandLogProvider(t *testing.T) {
}
}
-// TestOnlyLaunchGoSpawnsRuntimeProcesses is the structural half of this fix.
-//
-// Distributed opt-in is what let ExtraArgs rot: it was honoured by six of
-// twenty-one backends, and MULTICA_QWENPAW_ARGS shipped plumbed-but-dropped
-// because nothing failed when a backend forgot to read it. Re-establishing the
-// same convention for the launch prefix would rot the same way, so the rule is
-// mechanical instead: every runtime process in this package is constructed in
-// launch.go, which is the one place that applies the prefix.
-//
-// A new backend that calls os/exec directly fails here rather than silently
-// reintroducing GH #7046.
-func TestOnlyLaunchGoSpawnsRuntimeProcesses(t *testing.T) {
- t.Parallel()
-
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatalf("read package dir: %v", err)
- }
-
- fset := token.NewFileSet()
- var offenders []string
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
- continue
- }
- // launch.go owns the boundary. The platform invocation rewrites resolve
- // a PowerShell host with exec.LookPath but never spawn the runtime.
- if name == "launch.go" {
- continue
- }
- src, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("read %s: %v", name, err)
- }
- file, err := parser.ParseFile(fset, name, src, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", name, err)
- }
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return true
- }
- pkg, ok := sel.X.(*ast.Ident)
- if !ok || pkg.Name != "exec" {
- return true
- }
- if sel.Sel.Name != "Command" && sel.Sel.Name != "CommandContext" {
- return true
- }
- offenders = append(offenders,
- fset.Position(call.Pos()).String()+": exec."+sel.Sel.Name)
- return true
- })
- }
-
- if len(offenders) > 0 {
- t.Fatalf("runtime processes must be built through Command.exec / Command.execVia in launch.go, "+
- "otherwise a custom runtime's fixed_args are dropped (GH #7046). Offending sites:\n%s",
- strings.Join(offenders, "\n"))
- }
-}
-
-// bareProcessStartCalls reports every os/exec call in file that starts a
-// process without going through startOwnedProcessTree.
-//
-// Run, Output and CombinedOutput are on the list because they call Start
-// themselves: a probe written with cmd.Output() never reaches the ownership
-// boundary at all, which is how the `--version` and model-discovery probes
-// stayed unowned on Windows after the first pass at GH #7522.
-func bareProcessStartCalls(fset *token.FileSet, file *ast.File) []string {
- unowned := map[string]bool{"Start": true, "Run": true, "Output": true, "CombinedOutput": true}
- var offenders []string
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok || len(call.Args) != 0 || !unowned[sel.Sel.Name] {
- return true
- }
- offenders = append(offenders, fset.Position(call.Pos()).String()+": ."+sel.Sel.Name+"()")
- return true
- })
- return offenders
-}
-
-// unreleasedProcessTrees reports every function in file that takes ownership of
-// a process tree without dropping it.
-//
-// The rule is one owned start per function, paired with at least one release in
-// the same function. Equal counts would be the obvious rule and is the wrong
-// one: dsh's Execute has one start and two releases because it has two exit
-// paths, and both have to release. Capping starts at one is what makes the
-// "at least one release" side meaningful — without it, a function could add a
-// second, unreleased start and still pass on the strength of the first one's
-// release.
-func unreleasedProcessTrees(fset *token.FileSet, file *ast.File) []string {
- var offenders []string
- for _, decl := range file.Decls {
- fn, ok := decl.(*ast.FuncDecl)
- if !ok {
- continue
- }
- starts, releases := 0, 0
- ast.Inspect(fn, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- ident, ok := call.Fun.(*ast.Ident)
- if !ok {
- return true
- }
- switch ident.Name {
- case "startOwnedProcessTree":
- starts++
- case "releaseProcessGroup":
- releases++
- }
- return true
- })
- where := fset.Position(fn.Pos()).String() + ": " + fn.Name.Name
- switch {
- case starts > 1:
- offenders = append(offenders, where+" starts more than one owned process tree; "+
- "split it so each start has a checkable release")
- case starts == 1 && releases == 0:
- offenders = append(offenders, where+" takes ownership of a process tree and never releases it")
- }
- }
- return offenders
-}
-
-// TestOnlyOwnedProcessTreesAreStarted is the structural half of GH #7522.
-//
-// Whole-tree ownership shipped as an opt-in each backend had to remember, and
-// it rotted exactly the way distributed opt-in always does here: of the 23
-// backends in this package, 3 called startOwnedProcessTree and 20 called
-// cmd.Start. On Windows those 20 own nothing, so cancelling a task kills the
-// direct child — often a cmd.exe shim — and leaves the real CLI running. One of
-// them kept working for forty minutes after it was cancelled.
-//
-// Fixing the reported backend alone would have left 19. So the rule is
-// mechanical instead: startOwnedProcessTree is the only way this package starts
-// a runtime process, and a new backend that reaches for cmd.Start — or for the
-// Run/Output/CombinedOutput that call it — fails here.
-//
-// The exemptions are the two platform implementations of that function, which
-// is where the real Start lives.
-func TestOnlyOwnedProcessTreesAreStarted(t *testing.T) {
- t.Parallel()
-
- var offenders []string
- forEachPackageFile(t, func(name string, fset *token.FileSet, file *ast.File) {
- if strings.HasPrefix(name, "proc_") {
- return
- }
- offenders = append(offenders, bareProcessStartCalls(fset, file)...)
- })
-
- if len(offenders) > 0 {
- t.Fatalf("runtime processes must be started through startOwnedProcessTree (use runOwned / "+
- "outputOwned / combinedOutputOwned for synchronous probes), otherwise cancelling or timing "+
- "out leaves the CLI's descendants running (GH #7522). Offending sites:\n%s",
- strings.Join(offenders, "\n"))
- }
-}
-
-// TestBareProcessStartCallsAreDetected proves the guard above fails closed,
-// without needing a real regression committed to a backend to find out.
-func TestBareProcessStartCallsAreDetected(t *testing.T) {
- t.Parallel()
-
- for _, tc := range []struct {
- name string
- body string
- want bool
- }{
- {"start", "cmd.Start()", true},
- {"run", "cmd.Run()", true},
- {"output", "_, _ = cmd.Output()", true},
- {"combined output", "_, _ = cmd.CombinedOutput()", true},
- {"owned start", "_ = startOwnedProcessTree(cmd, nil)", false},
- {"owned output", "_, _ = outputOwned(cmd, nil)", false},
- } {
- t.Run(tc.name, func(t *testing.T) {
- fset := token.NewFileSet()
- src := "package agent\nfunc f(cmd *exec.Cmd) {\n" + tc.body + "\n}\n"
- file, err := parser.ParseFile(fset, "synthetic.go", src, 0)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if got := len(bareProcessStartCalls(fset, file)) > 0; got != tc.want {
- t.Errorf("bareProcessStartCalls(%q) flagged = %v, want %v", tc.body, got, tc.want)
- }
- })
- }
-}
-
-// TestEveryOwnedProcessTreeIsReleased is the other half of the same invariant.
-// Taking ownership without dropping it leaks a Job Object handle per task on
-// Windows, and the release is also what kills whatever outlived the reap — so a
-// backend that starts an owned tree and never releases it is worse off than one
-// that owns nothing.
-func TestEveryOwnedProcessTreeIsReleased(t *testing.T) {
- t.Parallel()
-
- var offenders []string
- forEachPackageFile(t, func(name string, fset *token.FileSet, file *ast.File) {
- if strings.HasPrefix(name, "proc_") {
- return
- }
- offenders = append(offenders, unreleasedProcessTrees(fset, file)...)
- })
-
- if len(offenders) > 0 {
- t.Fatalf("an owned process tree must be released after the reap, which drops the Windows Job "+
- "Object handle and kills anything that outlived it:\n%s", strings.Join(offenders, "\n"))
- }
-}
-
-// TestUnreleasedProcessTreesAreDetected covers the case a per-file counter
-// misses, and which the first version of this guard did miss: a file that
-// already contains a correctly paired start and release, plus a second start
-// that releases nothing. models.go is exactly that shape today — two starts in
-// two functions — so the guard has to reason per function, not per file.
-func TestUnreleasedProcessTreesAreDetected(t *testing.T) {
- t.Parallel()
-
- const paired = `package agent
-func good(cmd *exec.Cmd) {
- _ = startOwnedProcessTree(cmd, nil)
- defer releaseProcessGroup(cmd)
-}
-`
- for _, tc := range []struct {
- name string
- src string
- want bool
- }{
- {"paired start and release", paired, false},
- {"second unreleased start in a file that already pairs one", paired + `
-func added(cmd *exec.Cmd) {
- _ = startOwnedProcessTree(cmd, nil)
-}
-`, true},
- {"second unreleased start in the same function", `package agent
-func two(a, b *exec.Cmd) {
- _ = startOwnedProcessTree(a, nil)
- _ = startOwnedProcessTree(b, nil)
- defer releaseProcessGroup(a)
-}
-`, true},
- {"release from a nested closure counts", `package agent
-func closure(cmd *exec.Cmd) {
- _ = startOwnedProcessTree(cmd, nil)
- go func() {
- _ = cmdWait()
- releaseProcessGroup(cmd)
- }()
-}
-`, false},
- {"two exit paths may release twice", `package agent
-func twoPaths(cmd *exec.Cmd) error {
- _ = startOwnedProcessTree(cmd, nil)
- if err := send(); err != nil {
- releaseProcessGroup(cmd)
- return err
- }
- releaseProcessGroup(cmd)
- return nil
-}
-`, false},
- } {
- t.Run(tc.name, func(t *testing.T) {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, "synthetic.go", tc.src, 0)
- if err != nil {
- t.Fatalf("parse: %v", err)
- }
- if got := len(unreleasedProcessTrees(fset, file)) > 0; got != tc.want {
- t.Errorf("unreleasedProcessTrees flagged = %v, want %v", got, tc.want)
- }
- })
- }
-}
-
-// forEachPackageFile parses every non-test source file in this package and
-// hands it to fn.
-func forEachPackageFile(t *testing.T, fn func(name string, fset *token.FileSet, file *ast.File)) {
- t.Helper()
-
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatalf("read package dir: %v", err)
- }
- fset := token.NewFileSet()
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
- continue
- }
- src, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("read %s: %v", name, err)
- }
- file, err := parser.ParseFile(fset, name, src, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", name, err)
- }
- fn(name, fset, file)
- }
-}
-
-func containsRuntimeArgReference(expr ast.Expr) bool {
- found := false
- ast.Inspect(expr, func(n ast.Node) bool {
- switch node := n.(type) {
- case *ast.SelectorExpr:
- if node.Sel.Name == "Args" {
- found = true
- return false
- }
- case *ast.Ident:
- switch strings.ToLower(node.Name) {
- case "args", "cmdargs", "argv":
- found = true
- return false
- }
- }
- return !found
- })
- return found
-}
-
-// TestOnlyLaunchGoLogsAgentCommandArgs keeps raw argv out of adapter-local log
-// calls. Every runtime process log must flow through Config.logAgentCommand in
-// launch.go, where values are redacted consistently for text and JSON handlers.
-// The guard checks both common field labels and the expressions themselves, so
-// renaming an "args" field to "argv" cannot bypass it while still passing
-// cmd.Args, args, cmdArgs, or argv to a logger.
-func TestOnlyLaunchGoLogsAgentCommandArgs(t *testing.T) {
- t.Parallel()
-
- entries, err := os.ReadDir(".")
- if err != nil {
- t.Fatalf("read package dir: %v", err)
- }
-
- fset := token.NewFileSet()
- var offenders []string
- for _, entry := range entries {
- name := entry.Name()
- if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") || name == "launch.go" {
- continue
- }
- src, err := os.ReadFile(name)
- if err != nil {
- t.Fatalf("read %s: %v", name, err)
- }
- file, err := parser.ParseFile(fset, name, src, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", name, err)
- }
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return true
- }
- switch sel.Sel.Name {
- case "Debug", "Info", "Warn", "Error", "Log", "LogAttrs":
- default:
- return true
- }
- for _, arg := range call.Args {
- literal, ok := arg.(*ast.BasicLit)
- if ok && literal.Kind == token.STRING &&
- (literal.Value == `"args"` || literal.Value == `"argv"` || literal.Value == `"agent command"`) {
- offenders = append(offenders, fset.Position(call.Pos()).String())
- break
- }
- if containsRuntimeArgReference(arg) {
- offenders = append(offenders, fset.Position(call.Pos()).String())
- break
- }
- }
- return true
- })
- }
-
- if len(offenders) > 0 {
- t.Fatalf("runtime argv logs must use Config.logAgentCommand in launch.go so values are redacted. Offending sites:\n%s",
- strings.Join(offenders, "\n"))
- }
-}
-
// TestClaudeBackendLaunchesWrapperSubcommandFirst is the end-to-end proof:
// a real subprocess, spawned through the real backend, records the argv it was
// handed. The fake wrapper stands in for `ccms` and never touches a
diff --git a/server/pkg/agent/mcode_test.go b/server/pkg/agent/mcode_test.go
index 891040579f..08fe81103c 100644
--- a/server/pkg/agent/mcode_test.go
+++ b/server/pkg/agent/mcode_test.go
@@ -116,17 +116,6 @@ done
return bin
}
-func TestNewReturnsMcodeBackend(t *testing.T) {
- t.Parallel()
- backend, err := New("mcode", Config{ExecutablePath: "/nonexistent/mcode"})
- if err != nil {
- t.Fatalf("New(mcode) error: %v", err)
- }
- if _, ok := backend.(*mcodeBackend); !ok {
- t.Fatalf("New(mcode) = %T, want *mcodeBackend", backend)
- }
-}
-
func TestMcodeModelSelectionIsRuntimeManaged(t *testing.T) {
t.Parallel()
if ModelSelectionSupported("mcode") {
diff --git a/server/pkg/agent/models_test.go b/server/pkg/agent/models_test.go
index 92f4a1dd96..485a46314c 100644
--- a/server/pkg/agent/models_test.go
+++ b/server/pkg/agent/models_test.go
@@ -12,17 +12,19 @@ import (
"time"
)
-func TestStaticModelCatalogsHaveValidEntries(t *testing.T) {
+func TestStaticModelCatalogsAreValid(t *testing.T) {
t.Parallel()
catalogs := map[string][]Model{
- "claude": claudeStaticModels(),
- "codex": codexStaticModels(),
- "cursor": cursorStaticModels(),
+ "claude": claudeStaticModels(),
+ "codex": codexStaticModels(),
+ "cursor": cursorStaticModels(),
+ "copilot": copilotStaticModels(),
}
for provider, models := range catalogs {
if len(models) == 0 {
t.Errorf("%s static catalog returned no models", provider)
}
+ defaultCount := 0
for i, model := range models {
if model.ID == "" {
t.Errorf("%s static catalog[%d] has empty ID", provider, i)
@@ -30,6 +32,12 @@ func TestStaticModelCatalogsHaveValidEntries(t *testing.T) {
if model.Label == "" {
t.Errorf("%s static catalog[%d] has empty Label", provider, i)
}
+ if model.Default {
+ defaultCount++
+ }
+ }
+ if defaultCount > 1 {
+ t.Errorf("%s: %d models marked Default, want 0 or 1", provider, defaultCount)
}
}
}
@@ -466,176 +474,6 @@ func thinkingValues(thinking *ModelThinking) []string {
return values
}
-func TestClaudeStaticModelsExposesFable5(t *testing.T) {
- models := claudeStaticModels()
- ids := map[string]Model{}
- defaults := 0
- for _, m := range models {
- ids[m.ID] = m
- if m.Default {
- defaults++
- }
- }
-
- fable, ok := ids["claude-fable-5"]
- if !ok {
- t.Fatalf("missing Claude Fable 5 in: %+v", models)
- }
- if fable.Label != "Claude Fable 5" || fable.Provider != "anthropic" || fable.Default {
- t.Errorf("unexpected Fable entry: %+v", fable)
- }
- if defaults != 1 || !ids["claude-sonnet-4-6"].Default {
- t.Errorf("expected Sonnet 4.6 to remain the sole default, got defaults=%d models=%+v", defaults, models)
- }
-}
-
-func TestClaudeStaticModelsExposesFable51(t *testing.T) {
- models := claudeStaticModels()
- ids := map[string]Model{}
- defaults := 0
- for _, m := range models {
- ids[m.ID] = m
- if m.Default {
- defaults++
- }
- }
-
- fable, ok := ids["claude-fable-5-1"]
- if !ok {
- t.Fatalf("missing Claude Fable 5.1 in: %+v", models)
- }
- if fable.Label != "Claude Fable 5.1" || fable.Provider != "anthropic" || fable.Default {
- t.Errorf("unexpected Fable 5.1 entry: %+v", fable)
- }
- if defaults != 1 || !ids["claude-sonnet-4-6"].Default {
- t.Errorf("expected Sonnet 4.6 to remain the sole default, got defaults=%d models=%+v", defaults, models)
- }
-}
-
-func TestClaudeStaticModelsExposesSonnet5(t *testing.T) {
- models := claudeStaticModels()
- ids := map[string]Model{}
- defaults := 0
- for _, m := range models {
- ids[m.ID] = m
- if m.Default {
- defaults++
- }
- }
-
- sonnet, ok := ids["claude-sonnet-5"]
- if !ok {
- t.Fatalf("missing Claude Sonnet 5 in: %+v", models)
- }
- if sonnet.Label != "Claude Sonnet 5" || sonnet.Provider != "anthropic" || sonnet.Default {
- t.Errorf("unexpected Sonnet 5 entry: %+v", sonnet)
- }
- if defaults != 1 || !ids["claude-sonnet-4-6"].Default {
- t.Errorf("expected Sonnet 4.6 to remain the sole default, got defaults=%d models=%+v", defaults, models)
- }
-}
-
-func TestClaudeStaticModelsExposesOpus5(t *testing.T) {
- models := claudeStaticModels()
- ids := map[string]Model{}
- defaults := 0
- for _, m := range models {
- ids[m.ID] = m
- if m.Default {
- defaults++
- }
- }
-
- opus, ok := ids["claude-opus-5"]
- if !ok {
- t.Fatalf("missing Claude Opus 5 in: %+v", models)
- }
- if opus.Label != "Claude Opus 5" || opus.Provider != "anthropic" || opus.Default {
- t.Errorf("unexpected Opus 5 entry: %+v", opus)
- }
- // Opus stays a deliberate opt-in: Sonnet remains the everyday workhorse
- // the catalog badges as its default pick.
- if defaults != 1 || !ids["claude-sonnet-4-6"].Default {
- t.Errorf("expected Sonnet 4.6 to remain the sole default, got defaults=%d models=%+v", defaults, models)
- }
-}
-
-// TestClaudeOpus5AcceptedByProviderCompatibilityGate pins the other half of
-// catalog membership: ModelKnownIncompatibleWithProvider erases a saved model
-// that a runtime's maintained catalog doesn't advertise, so an unlisted
-// `claude-opus-5` would be silently dropped from an agent on save.
-func TestClaudeOpus5AcceptedByProviderCompatibilityGate(t *testing.T) {
- t.Parallel()
- if ModelKnownIncompatibleWithProvider("claude", "claude-opus-5") {
- t.Error("claude-opus-5 must be accepted by the claude provider gate")
- }
- if !ModelKnownIncompatibleWithProvider("codex", "claude-opus-5") {
- t.Error("claude-opus-5 must still be rejected for the codex provider")
- }
-}
-
-func TestCodexStaticModelsMatchVerifiedFallbackCatalog(t *testing.T) {
- // This fallback is used for Codex <0.122.0 and whenever dynamic bundled
- // discovery fails. Keep the latest verified visible models plus 5.3 Codex
- // for older installations, but do not resurrect guessed/nonexistent IDs.
- models := codexStaticModels()
- ids := map[string]Model{}
- for _, m := range models {
- ids[m.ID] = m
- }
- for _, want := range []string{
- "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna",
- "gpt-5.5", "gpt-5.4", "gpt-5.4-mini",
- "gpt-5.3-codex", "gpt-5.2",
- } {
- if _, ok := ids[want]; !ok {
- t.Errorf("missing expected Codex model %q in: %+v", want, models)
- }
- }
- for _, unwanted := range []string{"gpt-5.5-mini", "gpt-5", "o3", "o3-mini"} {
- if _, ok := ids[unwanted]; ok {
- t.Errorf("unexpected stale/invalid Codex model %q in fallback: %+v", unwanted, models)
- }
- }
- latest, ok := ids["gpt-5.6-sol"]
- if !ok || !latest.Default {
- t.Errorf("expected `gpt-5.6-sol` to be the default Codex entry, got %+v", latest)
- }
- defaults := 0
- for _, m := range models {
- if m.Default {
- defaults++
- }
- if m.Provider != "openai" {
- t.Errorf("all Codex entries must carry Provider=openai, got %+v", m)
- }
- }
- if defaults != 1 {
- t.Errorf("expected exactly one default Codex entry, got %d", defaults)
- }
- if got := ids["gpt-5.6-sol"].Thinking; got == nil || got.DefaultLevel != "low" || !hasThinkingLevel(got, "max") || !hasThinkingLevel(got, "ultra") {
- t.Errorf("unexpected gpt-5.6-sol thinking catalog: %+v", got)
- }
- if got := ids["gpt-5.6-luna"].Thinking; got == nil || !hasThinkingLevel(got, "max") || hasThinkingLevel(got, "ultra") {
- t.Errorf("unexpected gpt-5.6-luna thinking catalog: %+v", got)
- }
- if got := ids["gpt-5.3-codex"].Thinking; got == nil || !hasThinkingLevel(got, "xhigh") || hasThinkingLevel(got, "max") || hasThinkingLevel(got, "ultra") {
- t.Errorf("unexpected gpt-5.3-codex thinking catalog: %+v", got)
- }
- for id, label := range map[string]string{
- "gpt-5.6-sol": "GPT-5.6 Sol",
- "gpt-5.6-terra": "GPT-5.6 Terra",
- "gpt-5.6-luna": "GPT-5.6 Luna",
- } {
- if got := ids[id].Label; got != label {
- t.Errorf("Codex model %q label = %q, want %q", id, got, label)
- }
- if ModelKnownIncompatibleWithProvider("codex", id) {
- t.Errorf("Codex model %q must be accepted by the provider compatibility gate", id)
- }
- }
-}
-
func TestModelKnownIncompatibleWithProvider(t *testing.T) {
cases := []struct {
name string
@@ -764,49 +602,6 @@ func TestInferCopilotProvider(t *testing.T) {
}
}
-func TestCopilotStaticModelsExposesFullCatalog(t *testing.T) {
- // GitHub Copilot CLI has no `models list` subcommand, so the
- // catalog is hand-maintained from the official supported-models
- // docs. Regression guard for multica-ai/multica#1948 — the
- // dropdown previously shipped only 2 models and used dashed IDs
- // (`claude-sonnet-4-6`) which the CLI rejects. IDs must use the
- // dotted form (`claude-sonnet-4.6`) that `copilot --model <id>`
- // actually accepts, and cover both OpenAI and Anthropic families.
- models := copilotStaticModels()
- ids := map[string]Model{}
- for _, m := range models {
- ids[m.ID] = m
- }
- for _, want := range []string{
- "gpt-5.5", "gpt-5.4", "gpt-5.4-mini",
- "gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.2",
- "gpt-5-mini", "gpt-4.1",
- "claude-opus-4.7", "claude-sonnet-4.6",
- "claude-sonnet-4.5", "claude-haiku-4.5",
- } {
- if _, ok := ids[want]; !ok {
- t.Errorf("missing expected Copilot model %q in: %+v", want, models)
- }
- }
- // Dashed legacy IDs must not reappear — `copilot --model
- // claude-sonnet-4-6` errors with "Model ... is not available".
- for _, banned := range []string{"claude-sonnet-4-6", "claude-sonnet-4-5"} {
- if _, ok := ids[banned]; ok {
- t.Errorf("Copilot catalog must not use dashed model id %q; use dotted form", banned)
- }
- }
- for _, m := range models {
- switch m.Provider {
- case "openai", "anthropic":
- default:
- t.Errorf("Copilot entry %q has unexpected Provider %q", m.ID, m.Provider)
- }
- if m.Default {
- t.Errorf("Copilot entries should not set Default; account routing decides. got %+v", m)
- }
- }
-}
-
func TestListModelsHermesWithoutBinary(t *testing.T) {
// Hermes reports discovery failures instead of swallowing them into an
// empty list, unlike the kiro / qoder cases below (MUL-6606). Those two
@@ -892,29 +687,6 @@ func TestListModelsUnknownProvider(t *testing.T) {
}
}
-func TestStaticCatalogsHaveAtMostOneDefault(t *testing.T) {
- // Each catalog should tag at most one entry as the display
- // default so the UI badge is unambiguous. More than one
- // usually means a copy/paste slip when adding new models.
- catalogs := map[string][]Model{
- "claude": claudeStaticModels(),
- "codex": codexStaticModels(),
- "cursor": cursorStaticModels(),
- "copilot": copilotStaticModels(),
- }
- for provider, models := range catalogs {
- count := 0
- for _, m := range models {
- if m.Default {
- count++
- }
- }
- if count > 1 {
- t.Errorf("%s: %d models marked Default, want 0 or 1", provider, count)
- }
- }
-}
-
func TestParseOpenCodeModels(t *testing.T) {
input := `PROVIDER/MODEL CONTEXT MAX_OUT
openai/gpt-4o 128000 16384
@@ -1796,26 +1568,6 @@ func TestACPResultTopLevelKeys(t *testing.T) {
}
}
-func TestHermesModelSelectionSupported(t *testing.T) {
- // Regression guard: hermes now supports model selection via
- // the ACP session/set_model RPC, so the UI dropdown should
- // not be disabled for it.
- if !ModelSelectionSupported("hermes") {
- t.Error("hermes should be model-selection-supported now that set_session_model is wired")
- }
-}
-
-// TestAntigravityModelSelectionSupported pins that the antigravity provider
-// now reports model selection as supported: agy 1.0.6 added a `--model` flag
-// (MUL-3125) and buildAntigravityArgs wires opts.Model through, so the UI
-// must render the live picker rather than a disabled "Managed by runtime"
-// label.
-func TestAntigravityModelSelectionSupported(t *testing.T) {
- if !ModelSelectionSupported("antigravity") {
- t.Error("antigravity should be model-selection-supported now that agy 1.0.6 has --model")
- }
-}
-
// TestParseAntigravityModels covers the legacy single-column `agy models`
// format (pre-1.1.11): each non-blank tab-free line becomes a Model whose ID
// and Label are that verbatim value, duplicates collapse, and blanks drop.
@@ -2119,21 +1871,3 @@ func TestModelSelectorMustBeProviderQualifiedIsAnExecutionContract(t *testing.T)
})
}
}
-
-// omp is a built-in runtime identity rather than a protocol family, so the
-// predicate must resolve it through its descriptor. This is what keeps "add a
-// fork" a descriptor entry instead of a change here.
-func TestModelSelectorContractFollowsProtocolFamily(t *testing.T) {
- t.Parallel()
-
- desc, ok := BuiltinRuntimeByID("omp")
- if !ok {
- t.Fatal("omp is no longer a built-in runtime identity; this test needs a new subject")
- }
- if desc.ProtocolFamily != "pi" {
- t.Fatalf("omp protocol family = %q, want pi", desc.ProtocolFamily)
- }
- if ModelSelectorMustBeProviderQualified("omp") != ModelSelectorMustBeProviderQualified(desc.ProtocolFamily) {
- t.Error("omp does not inherit its selector contract from the pi protocol family")
- }
-}
diff --git a/server/pkg/agent/omp_test.go b/server/pkg/agent/omp_test.go
index b289968c67..5fcd299e27 100644
--- a/server/pkg/agent/omp_test.go
+++ b/server/pkg/agent/omp_test.go
@@ -482,37 +482,3 @@ func TestOmpAndPiRegisterSideBySide(t *testing.T) {
})
}
}
-
-// TestBuiltinRuntimeDescriptorFieldsAreConsumed guards against descriptor
-// fields going unused (the round-3 review caught this). Every field in
-// BuiltinRuntime must have at least one consumer outside the descriptor file
-// itself, or it's dead code.
-func TestBuiltinRuntimeDescriptorFieldsAreConsumed(t *testing.T) {
- // The omp descriptor must have all fields populated.
- desc, ok := BuiltinRuntimeByID("omp")
- if !ok {
- t.Fatal("omp descriptor not found")
- }
- // Every field must be non-empty (they're all consumed by daemon code).
- checks := map[string]string{
- "ID": desc.ID,
- "ProtocolFamily": desc.ProtocolFamily,
- "DefaultCommand": desc.DefaultCommand,
- "EnvPrefix": desc.EnvPrefix,
- "DisplayName": desc.DisplayName,
- "SkillsDir": desc.SkillsDir,
- "UserSkillsDir": desc.UserSkillsDir,
- "LaunchHeader": desc.LaunchHeader,
- "DefaultExecutable": desc.DefaultExecutable,
- "ProviderLabel": desc.ProviderLabel,
- }
- for name, val := range checks {
- if val == "" {
- t.Errorf("descriptor field %s is empty", name)
- }
- }
- // ModelDiscovery must be set (omp uses a different discovery command).
- if desc.ModelDiscovery == nil {
- t.Error("descriptor field ModelDiscovery is nil")
- }
-}
diff --git a/server/pkg/agent/openclaw_test.go b/server/pkg/agent/openclaw_test.go
index 9ebbc1d138..3222ef6e2d 100644
--- a/server/pkg/agent/openclaw_test.go
+++ b/server/pkg/agent/openclaw_test.go
@@ -12,17 +12,6 @@ import (
"time"
)
-func TestNewReturnsOpenclawBackend(t *testing.T) {
- t.Parallel()
- b, err := New("openclaw", Config{ExecutablePath: "/nonexistent/openclaw"})
- if err != nil {
- t.Fatalf("New(openclaw) error: %v", err)
- }
- if _, ok := b.(*openclawBackend); !ok {
- t.Fatalf("expected *openclawBackend, got %T", b)
- }
-}
-
// ── Legacy result format tests (processOutput with final JSON blob) ──
func TestOpenclawProcessOutputHappyPath(t *testing.T) {
diff --git a/server/pkg/agent/opencode_test.go b/server/pkg/agent/opencode_test.go
index ed8c45f0c4..5f16b299c6 100644
--- a/server/pkg/agent/opencode_test.go
+++ b/server/pkg/agent/opencode_test.go
@@ -13,17 +13,6 @@ import (
"time"
)
-func TestNewReturnsOpencodeBackend(t *testing.T) {
- t.Parallel()
- b, err := New("opencode", Config{ExecutablePath: "/nonexistent/opencode"})
- if err != nil {
- t.Fatalf("New(opencode) error: %v", err)
- }
- if _, ok := b.(*opencodeBackend); !ok {
- t.Fatalf("expected *opencodeBackend, got %T", b)
- }
-}
-
// ── Text event tests ──
func TestOpencodeHandleTextEvent(t *testing.T) {
diff --git a/server/pkg/agent/proc_windows_test.go b/server/pkg/agent/proc_windows_test.go
index b0e4c7fece..bb938d1cab 100644
--- a/server/pkg/agent/proc_windows_test.go
+++ b/server/pkg/agent/proc_windows_test.go
@@ -76,18 +76,6 @@ func TestHideAgentWindowPreservesExistingSysProcAttr(t *testing.T) {
}
}
-// TestCodexInitializeRetrySupportedWithOwnedProcessTree pins the inverse of the
-// invariant this file used to hold. Now that a launched Codex is assigned to a
-// Job Object, descendant termination is observable, so the retry is no longer
-// categorically suppressed on Windows. The cleanup_confirmed gate at the call
-// site still suppresses it whenever ownership could not be taken, so a host
-// where the assignment fails behaves exactly as it did before.
-func TestCodexInitializeRetrySupportedWithOwnedProcessTree(t *testing.T) {
- if !codexInitializeRetrySupported() {
- t.Fatal("Codex initialize retry should be available once the process tree is owned by a Job Object")
- }
-}
-
// TestStartOwnedProcessTreeCapturesImmediateDescendants is the pre-attach
// window: Windows grants job membership only to processes created after the
// assignment and never retroactively, so a child that spawns its real work
diff --git a/server/pkg/agent/qwen_invocation_test.go b/server/pkg/agent/qwen_invocation_test.go
index cdc1ec909d..87bcc47c61 100644
--- a/server/pkg/agent/qwen_invocation_test.go
+++ b/server/pkg/agent/qwen_invocation_test.go
@@ -1,9 +1,6 @@
package agent
import (
- "go/ast"
- "go/parser"
- "go/token"
"io"
"log/slog"
"path/filepath"
@@ -32,43 +29,3 @@ func TestChooseQwenInvocation_PassthroughForNonLauncher(t *testing.T) {
t.Errorf("argv changed unexpectedly:\n got %#v\n want %#v", gotArgs, args)
}
}
-
-// TestQwenLaunchesThroughTheInvocationChooser pins the wiring half of #6082.
-// The chooser only protects a run that goes through it, and a qwen.go that
-// builds its process with Command.exec spawns the npm qwen.cmd launcher
-// directly again — every symptom returns while the Windows tests in
-// qwen_invocation_windows_test.go keep passing, because they exercise the
-// chooser rather than the backend. The assertion is on the source since the
-// two launch paths are indistinguishable at runtime on macOS/Linux, where the
-// chooser is a passthrough.
-func TestQwenLaunchesThroughTheInvocationChooser(t *testing.T) {
- t.Parallel()
-
- file, err := parser.ParseFile(token.NewFileSet(), "qwen.go", nil, 0)
- if err != nil {
- t.Fatalf("parse qwen.go: %v", err)
- }
-
- routed := false
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok || sel.Sel.Name != "execVia" {
- return true
- }
- for _, arg := range call.Args {
- if ident, ok := arg.(*ast.Ident); ok && ident.Name == "chooseQwenInvocation" {
- routed = true
- }
- }
- return true
- })
-
- if !routed {
- t.Fatal("qwen.go must spawn through Command.execVia with chooseQwenInvocation; " +
- "launching the resolved executable directly hands the managed argv back to cmd.exe re-tokenisation on Windows (GH #6082)")
- }
-}
diff --git a/server/pkg/agent/qwenpaw_test.go b/server/pkg/agent/qwenpaw_test.go
index 95e9d89a7d..6e46a02cde 100644
--- a/server/pkg/agent/qwenpaw_test.go
+++ b/server/pkg/agent/qwenpaw_test.go
@@ -22,17 +22,6 @@ func TestQwenpawModelSelectionUnsupported(t *testing.T) {
}
}
-func TestNewReturnsQwenpawBackend(t *testing.T) {
- t.Parallel()
- b, err := New("qwenpaw", Config{ExecutablePath: "/nonexistent/qwenpaw"})
- if err != nil {
- t.Fatalf("New(qwenpaw) error: %v", err)
- }
- if _, ok := b.(*qwenpawBackend); !ok {
- t.Fatalf("expected *qwenpawBackend, got %T", b)
- }
-}
-
// fakeQwenpawACPScript impersonates `qwenpaw acp` for unit tests.
// Wire format mirrors other Multica ACP fakes (grok/kimi):
// session/new returns sessionId, session/load accepts an existing session,
@@ -802,16 +791,3 @@ done
t.Fatalf("expected daemon-injected workspace path in command args, got:\n%s", args)
}
}
-
-func TestQwenpawBackendJSON(t *testing.T) {
- // Verify that the qwenpawBackend type is registered in the
- // backend constructor map.
- t.Parallel()
- b, err := New("qwenpaw", Config{ExecutablePath: "/test/qwenpaw"})
- if err != nil {
- t.Fatalf("New(qwenpaw) error: %v", err)
- }
- if _, ok := b.(*qwenpawBackend); !ok {
- t.Fatalf("expected *qwenpawBackend, got %T", b)
- }
-}
diff --git a/server/pkg/agent/reasonix_test.go b/server/pkg/agent/reasonix_test.go
index a6e73a0b4c..f3eebb933a 100644
--- a/server/pkg/agent/reasonix_test.go
+++ b/server/pkg/agent/reasonix_test.go
@@ -10,17 +10,6 @@ import (
"testing"
)
-func TestNewReturnsReasonixBackend(t *testing.T) {
- t.Parallel()
- b, err := New("reasonix", Config{ExecutablePath: "/nonexistent/reasonix"})
- if err != nil {
- t.Fatalf("New(reasonix) error: %v", err)
- }
- if _, ok := b.(*reasonixBackend); !ok {
- t.Fatalf("expected *reasonixBackend, got %T", b)
- }
-}
-
func TestReasonixPermissionPolicy(t *testing.T) {
t.Parallel()
tests := []struct {
diff --git a/server/pkg/agent/thinking_test.go b/server/pkg/agent/thinking_test.go
index 1b541ed28c..19fdd34ac3 100644
--- a/server/pkg/agent/thinking_test.go
+++ b/server/pkg/agent/thinking_test.go
@@ -142,19 +142,6 @@ func TestProjectClaudeLevels_PerModelSubset(t *testing.T) {
// binary on PATH and verifies that what *actually* reaches the
// process matches the pinned argv, not just what the var holds.
-func TestCodexDebugModelsArgs_Pinned(t *testing.T) {
- t.Parallel()
- want := []string{"debug", "models", "--bundled"}
- if !reflect.DeepEqual(codexDebugModelsArgs, want) {
- t.Fatalf("codexDebugModelsArgs drifted: got %v, want %v", codexDebugModelsArgs, want)
- }
- for _, arg := range codexDebugModelsArgs {
- if arg == "--output" || arg == "-o" {
- t.Errorf("--output / -o leaked back into argv (codex CLI does not accept it): %v", codexDebugModelsArgs)
- }
- }
-}
-
// TestRunCodexDebugModels_ArgvSeenByBinary executes runCodexDebugModels
// against a shell-script stand-in for `codex` that records its argv to
// a file and prints a minimal valid JSON payload. The check is on what
diff --git a/server/pkg/agent/traecli_test.go b/server/pkg/agent/traecli_test.go
index 7a08b470ef..622c957265 100644
--- a/server/pkg/agent/traecli_test.go
+++ b/server/pkg/agent/traecli_test.go
@@ -11,17 +11,6 @@ import (
"log/slog"
)
-func TestNewReturnsTraecliBackend(t *testing.T) {
- t.Parallel()
- b, err := New("traecli", Config{ExecutablePath: "/nonexistent/traecli"})
- if err != nil {
- t.Fatalf("New(traecli) error: %v", err)
- }
- if _, ok := b.(*traecliBackend); !ok {
- t.Fatalf("expected *traecliBackend, got %T", b)
- }
-}
-
// fakeTraecliACPScript impersonates the official `traecli acp serve` for unit
// tests. It speaks the SAME wire format the real traecli v0.120.42 emits
// (captured live): method "session/update" with an "update.sessionUpdate"
diff --git a/server/pkg/agent/worktree_capability_contract_test.go b/server/pkg/agent/worktree_capability_contract_test.go
index cd3ef26897..94ad42c32f 100644
--- a/server/pkg/agent/worktree_capability_contract_test.go
+++ b/server/pkg/agent/worktree_capability_contract_test.go
@@ -9,35 +9,21 @@ import (
"github.com/multica-ai/multica/server/pkg/protocol"
)
-// What the two sides must agree on is the capability TOKEN, not a version.
-//
-// This replaces a test that pinned MinLocalWorktreeCLIVersion against a
-// frontend twin. That twin is gone: since MUL-5707 nothing on either side gates
-// on the version, and the frontend no longer even quotes it (#7113), so the old
-// contract was pinning a number the UI does not show. The server constant stays
-// because the 422 payload still carries it, but it has no counterpart to match.
-//
-// The token does have one, and it is load-bearing in a way a version never was:
-// the daemon advertises this exact string, the server stores it, and the UI
-// looks for it. A typo on either side silently disables worktree mode for
-// everyone, with no error anywhere — which is precisely the failure this whole
-// area keeps producing.
-// This test reads OUT of the Go module, so CI's backend path filter has to
-// list the frontend file explicitly (`backend` in .github/workflows/ci.yml).
-// Without it, a PR that only edits the frontend token skips the very test
-// that would catch the mismatch. Move or rename the path below and the
-// filter must move with it.
+// The capability token is a cross-version protocol contract: the daemon
+// advertises it, the server persists it, and installed clients look for it.
+// A typo on either side silently hides worktree mode. This file is also why
+// packages/core/runtimes/cli-version.ts belongs in CI's backend path filter.
func TestWorktreeCapabilityTokenMatchesFrontend(t *testing.T) {
path := filepath.Join("..", "..", "..", "packages", "core", "runtimes", "cli-version.ts")
src, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
- m := regexp.MustCompile(`LOCAL_WORKTREE_CAPABILITY\s*=\s*"([^"]+)"`).FindSubmatch(src)
- if m == nil {
+ match := regexp.MustCompile(`LOCAL_WORKTREE_CAPABILITY\s*=\s*"([^"]+)"`).FindSubmatch(src)
+ if match == nil {
t.Fatal("LOCAL_WORKTREE_CAPABILITY not found in packages/core/runtimes/cli-version.ts")
}
- if got := string(m[1]); got != protocol.DaemonCapabilityLocalWorktreeV1 {
+ if got := string(match[1]); got != protocol.DaemonCapabilityLocalWorktreeV1 {
t.Errorf("frontend looks for %q but the daemon advertises %q; worktree mode would be invisible to the UI",
got, protocol.DaemonCapabilityLocalWorktreeV1)
}
diff --git a/server/pkg/agent/zeroclaw_test.go b/server/pkg/agent/zeroclaw_test.go
index 1229fcdd2e..605303eea1 100644
--- a/server/pkg/agent/zeroclaw_test.go
+++ b/server/pkg/agent/zeroclaw_test.go
@@ -11,17 +11,6 @@ import (
"time"
)
-func TestNewReturnsZeroclawBackend(t *testing.T) {
- t.Parallel()
- b, err := New("zeroclaw", Config{ExecutablePath: "/nonexistent/zeroclaw"})
- if err != nil {
- t.Fatalf("New(zeroclaw) error: %v", err)
- }
- if _, ok := b.(*zeroclawBackend); !ok {
- t.Fatalf("expected *zeroclawBackend, got %T", b)
- }
-}
-
// fakeZeroclawACPScript impersonates `zeroclaw acp` for unit tests. Unlike a
// generic ACP fake, this one reproduces the frames a real ZeroClaw 0.8.4
// binary was observed to send, because several of the bugs this suite guards
diff --git a/server/pkg/db/generated/comment_row_test.go b/server/pkg/db/generated/comment_row_test.go
deleted file mode 100644
index 890eee7d57..0000000000
--- a/server/pkg/db/generated/comment_row_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package db
-
-import (
- "testing"
-
- "github.com/jackc/pgx/v5/pgtype"
-)
-
-func TestCreateCommentRowCommentPreservesCanonicalFields(t *testing.T) {
- viaPluginID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
- row := CreateCommentRow{
- Content: "created comment",
- Revision: 7,
- ViaPluginID: viaPluginID,
- IssueRevision: 11,
- }
-
- comment := row.Comment()
- if comment.Content != row.Content {
- t.Fatalf("content = %q, want %q", comment.Content, row.Content)
- }
- if comment.Revision != row.Revision {
- t.Fatalf("revision = %d, want %d", comment.Revision, row.Revision)
- }
- if comment.ViaPluginID != viaPluginID {
- t.Fatalf("via_plugin_id = %#v, want %#v", comment.ViaPluginID, viaPluginID)
- }
-}
-
-func TestUpdateCommentRowCommentPreservesCanonicalFields(t *testing.T) {
- viaPluginID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
- row := UpdateCommentRow{
- Content: "updated comment",
- Revision: 8,
- ViaPluginID: viaPluginID,
- IssueRevision: 12,
- }
-
- comment := row.Comment()
- if comment.Content != row.Content || comment.Revision != row.Revision {
- t.Fatalf("comment = (%q, %d), want (%q, %d)", comment.Content, comment.Revision, row.Content, row.Revision)
- }
- if comment.ViaPluginID != viaPluginID {
- t.Fatalf("via_plugin_id = %#v, want %#v", comment.ViaPluginID, viaPluginID)
- }
-}
diff --git a/server/pkg/dbid/writes_test.go b/server/pkg/dbid/writes_test.go
deleted file mode 100644
index a1751a1d14..0000000000
--- a/server/pkg/dbid/writes_test.go
+++ /dev/null
@@ -1,261 +0,0 @@
-package dbid
-
-import (
- "fmt"
- "go/ast"
- "go/parser"
- "go/token"
- "os"
- "path/filepath"
- "regexp"
- "runtime"
- "strconv"
- "strings"
- "testing"
-)
-
-// The tables whose primary keys the application mints as UUIDv7, and the sqlc
-// query that inserts each one. Keeping the list here — rather than deriving it —
-// is deliberate: adding a table to the v7 set is a decision, and it should show
-// up as an edit to this list in review.
-//
-// query is the sqlc query name; arg is the parameter name the query binds the id
-// to (CreateRetryTask already had an `id` parameter for the PARENT task, so its
-// new id is named new_task_id); field is the Go field on the params struct.
-var v7Writes = []struct {
- table string
- file string
- query string
- arg string
- field string
-}{
- {"activity_log", "activity.sql", "CreateActivity", "id", "ID"},
- {"agent_task_queue", "agent.sql", "CreateAgentTask", "id", "ID"},
- {"agent_task_queue", "agent.sql", "CreateDeferredChannelIssueTask", "id", "ID"},
- {"agent_task_queue", "agent.sql", "CreateQuickCreateTask", "id", "ID"},
- {"agent_task_queue", "agent.sql", "CreateDeferredAgentTask", "id", "ID"},
- {"agent_task_queue", "agent.sql", "CreateRetryTask", "new_task_id", "NewTaskID"},
- {"agent_task_queue", "autopilot.sql", "CreateAutopilotTask", "id", "ID"},
- {"agent_task_queue", "chat.sql", "CreateChatTask", "id", "ID"},
- {"autopilot_run", "autopilot.sql", "CreateAutopilotRun", "id", "ID"},
- {"channel_inbound_audit", "channel.sql", "RecordChannelInboundDrop", "id", "ID"},
- {"chat_message", "chat.sql", "CreateChatMessage", "id", "ID"},
- {"chat_message", "chat.sql", "CreateMikaOnboardingOpening", "id", "ID"},
- {"chat_session", "chat.sql", "CreateChatSession", "id", "ID"},
- {"comment", "comment.sql", "CreateComment", "id", "ID"},
- {"inbox_item", "inbox.sql", "CreateInboxItem", "id", "ID"},
- {"issue", "issue.sql", "CreateIssue", "id", "ID"},
- {"issue", "issue.sql", "CreateIssueWithOrigin", "id", "ID"},
- {"task_token", "task_token.sql", "CreateTaskToken", "id", "ID"},
- {"webhook_delivery", "webhook_delivery.sql", "CreateWebhookDelivery", "id", "ID"},
-}
-
-var queryNameRE = regexp.MustCompile(`(?m)^--\s*name:\s*(\w+)\s*:(\w+)`)
-
-// TestV7QueriesBindAnIDWithADatabaseFallback locks in the shape of every
-// converted INSERT: it must accept an id from the application AND keep
-// gen_random_uuid() as the fallback, so a caller that leaves the parameter unset
-// degrades to the pre-change behaviour instead of violating NOT NULL.
-func TestV7QueriesBindAnIDWithADatabaseFallback(t *testing.T) {
- for _, w := range v7Writes {
- t.Run(w.query, func(t *testing.T) {
- block := queryBlock(t, w.file, w.query)
-
- want := fmt.Sprintf("COALESCE(sqlc.narg('%s')::uuid, gen_random_uuid())", w.arg)
- if !strings.Contains(block, want) {
- t.Errorf("%s in %s does not bind its id as %s\n%s", w.query, w.file, want, block)
- }
-
- insert := fmt.Sprintf("INSERT INTO %s (", w.table)
- i := strings.Index(block, insert)
- if i < 0 {
- t.Fatalf("%s does not INSERT INTO %s", w.query, w.table)
- }
- cols := block[i+len(insert):]
- cols = cols[:strings.Index(cols, ")")]
- if !hasColumn(cols, "id") {
- t.Errorf("%s does not list the id column:\ncolumns: %s", w.query, strings.Join(strings.Fields(cols), " "))
- }
- })
- }
-}
-
-const (
- dbImportPath = "github.com/multica-ai/multica/server/pkg/db/generated"
- dbidImportPath = "github.com/multica-ai/multica/server/pkg/dbid"
-)
-
-// TestEveryV7ParamsLiteralSetsAnIDAndImportsDBID walks production Go sources
-// and fails if a converted params literal leaves its id unset or lives in a file
-// that does not import dbid. The AST-based check deliberately does not prescribe
-// whether the value is an inline dbid.NewV7 call or a local variable, so routine
-// refactors do not weaken this guard by forcing one source spelling.
-func TestEveryV7ParamsLiteralSetsAnIDAndImportsDBID(t *testing.T) {
- fields := map[string]string{}
- for _, w := range v7Writes {
- fields[w.query+"Params"] = w.field
- }
-
- found := map[string]int{}
- for _, path := range productionGoFiles(t) {
- fset := token.NewFileSet()
- file, err := parser.ParseFile(fset, path, nil, 0)
- if err != nil {
- t.Fatalf("parse %s: %v", path, err)
- }
-
- dbAliases, importsDBID := relevantImports(t, path, file)
- ast.Inspect(file, func(node ast.Node) bool {
- literal, ok := node.(*ast.CompositeLit)
- if !ok {
- return true
- }
- selector, ok := literal.Type.(*ast.SelectorExpr)
- if !ok {
- return true
- }
- pkg, ok := selector.X.(*ast.Ident)
- if !ok || !dbAliases[pkg.Name] {
- return true
- }
- field, tracked := fields[selector.Sel.Name]
- if !tracked {
- return true
- }
-
- found[selector.Sel.Name]++
- if !compositeLiteralSetsField(literal, field) {
- position := fset.Position(literal.Pos())
- t.Errorf("%s:%d: %s literal does not set %s; mint it with dbid.NewV7()",
- path, position.Line, selector.Sel.Name, field)
- }
- if !importsDBID {
- position := fset.Position(literal.Pos())
- t.Errorf("%s:%d: %s literal is in a file that does not import %s; add the import and call dbid.NewV7()",
- path, position.Line, selector.Sel.Name, dbidImportPath)
- }
- return true
- })
- }
-
- for typ := range fields {
- if found[typ] == 0 {
- t.Errorf("no production call site found for %s — was the query removed or renamed?", typ)
- }
- }
-}
-
-func relevantImports(t *testing.T, path string, file *ast.File) (map[string]bool, bool) {
- t.Helper()
-
- dbAliases := map[string]bool{}
- importsDBID := false
- for _, spec := range file.Imports {
- importPath, err := strconv.Unquote(spec.Path.Value)
- if err != nil {
- t.Fatalf("parse import in %s: %v", path, err)
- }
- switch importPath {
- case dbImportPath:
- name := "db"
- if spec.Name != nil {
- name = spec.Name.Name
- }
- dbAliases[name] = true
- case dbidImportPath:
- importsDBID = true
- }
- }
- return dbAliases, importsDBID
-}
-
-func compositeLiteralSetsField(literal *ast.CompositeLit, field string) bool {
- for _, element := range literal.Elts {
- pair, ok := element.(*ast.KeyValueExpr)
- if !ok {
- continue
- }
- name, ok := pair.Key.(*ast.Ident)
- if ok && name.Name == field {
- return true
- }
- }
- return false
-}
-
-// queryBlock returns the text of one named sqlc query, from its `-- name:`
-// comment to the start of the next one.
-func queryBlock(t *testing.T, file, query string) string {
- t.Helper()
-
- path := filepath.Join(serverDir(t), "pkg", "db", "queries", file)
- src, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
- text := string(src)
- marks := queryNameRE.FindAllStringSubmatchIndex(text, -1)
- for i, m := range marks {
- if text[m[2]:m[3]] != query {
- continue
- }
- end := len(text)
- if i+1 < len(marks) {
- end = marks[i+1][0]
- }
- return text[m[0]:end]
- }
- t.Fatalf("query %s not found in %s", query, file)
- return ""
-}
-
-func productionGoFiles(t *testing.T) []string {
- t.Helper()
-
- var out []string
- root := serverDir(t)
- err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() {
- // generated/ holds the sqlc output, which never constructs its own
- // params structs, and testdata/ is not compiled.
- if d.Name() == "generated" || d.Name() == "testdata" || d.Name() == "node_modules" {
- return filepath.SkipDir
- }
- return nil
- }
- if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") {
- out = append(out, path)
- }
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- if len(out) == 0 {
- t.Fatalf("no production Go files found under %s", root)
- }
- return out
-}
-
-func serverDir(t *testing.T) string {
- t.Helper()
-
- _, self, _, ok := runtime.Caller(0)
- if !ok {
- t.Fatal("resolve this test's path")
- }
- // .../server/pkg/dbid/writes_test.go -> .../server
- return filepath.Dir(filepath.Dir(filepath.Dir(self)))
-}
-
-func hasColumn(list, name string) bool {
- for _, part := range strings.Split(list, ",") {
- if strings.TrimSpace(part) == name {
- return true
- }
- }
- return false
-}
diff --git a/server/pkg/featureflag/eval_context_test.go b/server/pkg/featureflag/eval_context_test.go
index 6d40e03399..620746cb12 100644
--- a/server/pkg/featureflag/eval_context_test.go
+++ b/server/pkg/featureflag/eval_context_test.go
@@ -62,30 +62,6 @@ func TestEvalContextFromNilContext(t *testing.T) {
}
}
-func TestPercentBucketStable(t *testing.T) {
- t.Parallel()
- // Hash stability is part of the public contract: the same (key, id)
- // MUST produce the same bucket forever, otherwise users will flip
- // in and out of experiments. We pin a handful of values so a future
- // refactor that swaps the hash will fail loudly here.
- cases := []struct {
- key, id string
- want int
- }{
- {"feature_a", "user-1", bucketFor("feature_a", "user-1")},
- {"feature_b", "", bucketFor("feature_b", "")},
- }
- for _, tc := range cases {
- got := bucketFor(tc.key, tc.id)
- if got != tc.want {
- t.Fatalf("bucketFor(%q, %q) = %d, want %d", tc.key, tc.id, got, tc.want)
- }
- if got < 0 || got >= 100 {
- t.Fatalf("bucket out of range: %d", got)
- }
- }
-}
-
func TestPercentBucketSeparator(t *testing.T) {
t.Parallel()
// Without a separator, ("ab", "c") and ("a", "bc") would collide.
diff --git a/server/pkg/llm/outbound_contract_test.go b/server/pkg/llm/outbound_contract_test.go
index 2bbe8df74d..320e00d837 100644
--- a/server/pkg/llm/outbound_contract_test.go
+++ b/server/pkg/llm/outbound_contract_test.go
@@ -3,14 +3,7 @@ package llm
import (
"context"
"errors"
- "go/ast"
- "go/parser"
- "go/token"
- "io/fs"
"net/http"
- "path/filepath"
- "sort"
- "strings"
"sync/atomic"
"testing"
@@ -110,177 +103,3 @@ func TestUnconfiguredClientMakesZeroUpstreamRequests(t *testing.T) {
t.Fatal("configured client sent nothing through the test transport: the HTTPClient seam is not wired, so the zero-request assertions above prove nothing")
}
}
-
-// llmPackageDir is this package's path relative to the server module root. The
-// two source scans below exempt it: it is the layer they are guarding, not a
-// caller of it.
-const llmPackageDir = "pkg/llm"
-
-const openAISDKImportPrefix = "github.com/openai/openai-go"
-
-// documentedConsumers is the inventory this package's doc comment,
-// .env.example and the environment-variables docs pages all publish to
-// operators: these files, and only these, ask this layer to send something
-// upstream. The value is the summary each one is documented with.
-var documentedConsumers = map[string]string{
- "internal/handler/chat_title.go": "chat auto-titling: the first user message of a new chat session",
- "internal/service/chat_quick_actions_generate.go": "chat follow-up questions: the tail of the conversation",
-}
-
-// clientCallSurface is every method on Client that can produce an upstream
-// request. Enabled and DefaultModel are deliberately absent: asking whether the
-// layer is on sends nothing, and consumers are expected to call it.
-var clientCallSurface = map[string]bool{
- "Chat": true,
- "ChatStream": true,
- "GenerateText": true,
- "GenerateJSON": true,
-}
-
-// methodNameCollisions are call sites the scan below flags by name without
-// being consumers of this layer — some unrelated type that happens to have a
-// method called Chat or GenerateText. The scan matches on selector name alone,
-// which cannot tell the two apart.
-//
-// This is deliberately NOT part of documentedConsumers. That map is published
-// to operators as "what this deployment sends to a third party"; parking a
-// name collision there to quiet a test would corrupt a privacy disclosure to
-// save a line. Empty today — the repository has no collisions.
-var methodNameCollisions = map[string]bool{}
-
-// TestDocumentedConsumersAreTheOnlyCallers keeps the published consumer
-// inventory from going quietly stale.
-//
-// The operator-facing copy does not merely say this layer can be turned off; it
-// enumerates what is sent, feature by feature, so an admin can decide whether
-// to turn it on. That list is a promise about the whole server, and a third
-// feature calling GenerateText would break it silently: nothing in the build
-// notices, the docs keep naming two consumers, and the deployment starts
-// sending something no one disclosed.
-//
-// The import guard below cannot catch that case — a new consumer goes through
-// this package exactly as the existing two do, importing no SDK. So this test
-// scans production call sites instead and requires the set to match the
-// inventory in both directions: an undocumented caller fails, and so does a
-// documented one that stopped calling.
-func TestDocumentedConsumersAreTheOnlyCallers(t *testing.T) {
- found := map[string][]string{}
- scanServerModule(t, skipTestFiles, func(rel string, file *ast.File) {
- ast.Inspect(file, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- if sel, ok := call.Fun.(*ast.SelectorExpr); ok && clientCallSurface[sel.Sel.Name] && !methodNameCollisions[rel] {
- found[rel] = append(found[rel], sel.Sel.Name)
- }
- return true
- })
- })
-
- for rel, methods := range found {
- if _, documented := documentedConsumers[rel]; !documented {
- t.Errorf("undocumented consumer of this layer: %s calls %v.\n"+
- "If it sends content upstream, it must be disclosed before it ships: add it to "+
- "documentedConsumers, to this package's doc comment, and to the operator copy in "+
- ".env.example and apps/docs/content/docs/environment-variables*.mdx (all four locales).\n"+
- "If it is an unrelated type that merely shares a method name, add it to "+
- "methodNameCollisions — never to documentedConsumers, which operators read as the "+
- "list of things that send their chat content somewhere.", rel, methods)
- }
- }
- for rel, summary := range documentedConsumers {
- if _, still := found[rel]; !still {
- t.Errorf("%s no longer calls this layer, but is still published as a consumer (%q).\n"+
- "Drop it from documentedConsumers, this package's doc comment, and the operator copy — "+
- "an inventory that overstates what is sent is as misleading as one that understates it.",
- rel, summary)
- }
- }
-}
-
-// TestOpenAISDKIsImportedOnlyByThisPackage enforces the import half of the
-// single-entry-point rule: nothing outside pkg/llm reaches the OpenAI SDK.
-//
-// This is narrower than it sounds, and deliberately paired with the inventory
-// test above. On its own it proves only that the SDK has one door; it says
-// nothing about how many callers walk through it. Together the two mean the
-// package doc's consumer list can be trusted: no one can bypass this layer, and
-// no one can join it unannounced.
-//
-// It asserts on source rather than behaviour because the regression is the
-// existence of a call site, and no runtime assertion can observe a request the
-// test never triggers.
-func TestOpenAISDKIsImportedOnlyByThisPackage(t *testing.T) {
- var offenders []string
- scanServerModule(t, includeTestFiles, func(rel string, file *ast.File) {
- for _, imp := range file.Imports {
- if strings.HasPrefix(strings.Trim(imp.Path.Value, `"`), openAISDKImportPrefix) {
- offenders = append(offenders, rel)
- return
- }
- }
- })
-
- if len(offenders) > 0 {
- sort.Strings(offenders)
- t.Fatalf("these files import the OpenAI SDK directly, bypassing pkg/llm:\n %s\n"+
- "Call this package instead (add a helper here if it lacks what you need), so what this "+
- "deployment's assist layer sends to a third party stays answerable by reading one package.",
- strings.Join(offenders, "\n "))
- }
-}
-
-const (
- skipTestFiles = false
- includeTestFiles = true
-)
-
-// scanServerModule parses every Go file in the server module except this
-// package's own, calling visit with the file's module-relative path. Test files
-// are included only when withTests is set: a stub in a _test.go is not a
-// product feature sending chat content anywhere.
-func scanServerModule(t *testing.T, withTests bool, visit func(rel string, file *ast.File)) {
- t.Helper()
-
- // Tests run in their package directory, so the server module root is two
- // levels up from pkg/llm.
- moduleRoot := filepath.Join("..", "..")
- exempt := filepath.Join(moduleRoot, filepath.FromSlash(llmPackageDir))
-
- err := filepath.WalkDir(moduleRoot, func(path string, d fs.DirEntry, err error) error {
- if err != nil {
- return err
- }
- if d.IsDir() {
- name := d.Name()
- if path != moduleRoot && (strings.HasPrefix(name, ".") || name == "vendor" || name == "testdata") {
- return fs.SkipDir
- }
- if path == exempt {
- return fs.SkipDir
- }
- return nil
- }
- if !strings.HasSuffix(d.Name(), ".go") {
- return nil
- }
- if !withTests && strings.HasSuffix(d.Name(), "_test.go") {
- return nil
- }
-
- file, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, parser.SkipObjectResolution)
- if parseErr != nil {
- return parseErr
- }
- rel, relErr := filepath.Rel(moduleRoot, path)
- if relErr != nil {
- return relErr
- }
- visit(filepath.ToSlash(rel), file)
- return nil
- })
- if err != nil {
- t.Fatalf("scan server module: %v", err)
- }
-}
diff --git a/server/pkg/remotemcp/remotemcptest/fixture_test.go b/server/pkg/remotemcp/remotemcptest/fixture_test.go
deleted file mode 100644
index b75bb3fdba..0000000000
--- a/server/pkg/remotemcp/remotemcptest/fixture_test.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package remotemcptest
-
-import (
- "bytes"
- "encoding/json"
- "net/http"
- "testing"
-)
-
-func TestFixtureExposesReadAndSideEffectingWrite(t *testing.T) {
- fixture := NewServer()
- defer fixture.Close()
-
- call := func(method, params string) map[string]any {
- t.Helper()
- body := []byte(`{"jsonrpc":"2.0","id":1,"method":"` + method + `","params":` + params + `}`)
- request, err := http.NewRequest(http.MethodPost, fixture.URL, bytes.NewReader(body))
- if err != nil {
- t.Fatal(err)
- }
- request.Header.Set("Authorization", "Bearer "+Credential)
- response, err := http.DefaultClient.Do(request)
- if err != nil {
- t.Fatal(err)
- }
- defer response.Body.Close()
- var decoded map[string]any
- if err := json.NewDecoder(response.Body).Decode(&decoded); err != nil {
- t.Fatal(err)
- }
- return decoded
- }
-
- listed := call("tools/list", `{}`)
- if listed["result"] == nil {
- t.Fatalf("tools/list = %#v", listed)
- }
- call("tools/call", `{"name":"fixture.write","arguments":{"value":"one"}}`)
- if writes := fixture.Writes(); len(writes) != 1 || writes[0] != "one" {
- t.Fatalf("writes = %#v", writes)
- }
-}
diff --git a/server/pkg/taskfailure/failure_test.go b/server/pkg/taskfailure/failure_test.go
index 1c2abade08..55fba041db 100644
--- a/server/pkg/taskfailure/failure_test.go
+++ b/server/pkg/taskfailure/failure_test.go
@@ -1,178 +1,9 @@
package taskfailure
import (
- "strings"
"testing"
)
-// TestReasonStringWireValues pins the on-the-wire string for every
-// canonical reason. These strings are persisted into
-// agent_task_queue.failure_reason and surfaced as Prometheus labels —
-// renaming any of them is a breaking change. If this test fails because
-// you intended to rename a value, also update the SQL classifier in
-// MUL-1949 and ship a backfill migration before changing the constant.
-func TestReasonStringWireValues(t *testing.T) {
- t.Parallel()
-
- cases := []struct {
- reason Reason
- want string
- }{
- // Platform-side.
- {ReasonQueuedExpired, "queued_expired"},
- {ReasonRuntimeOffline, "runtime_offline"},
- {ReasonRuntimeReconnectTimeout, "runtime_reconnect_timeout"},
- {ReasonRuntimeRecovery, "runtime_recovery"},
- {ReasonTimeout, "timeout"},
- {ReasonIterationLimit, "iteration_limit"},
- {ReasonAgentBlocked, "agent_blocked"},
- {ReasonAPIInvalidRequest, "api_invalid_request"},
- {ReasonSkillBundleUnavailable, "skill_bundle_unavailable"},
- {ReasonRuntimeCLITimeout, "runtime_cli_timeout"},
- {ReasonEnvironmentPrepareFailed, "environment_prepare_failed"},
- {ReasonInvalidTaskIdentity, "invalid_task_identity"},
- // Agent-side.
- {ReasonAgentProviderAuthOrAccess, "agent_error.provider_auth_or_access"},
- {ReasonAgentProviderQuotaLimit, "agent_error.provider_quota_limit"},
- {ReasonAgentProviderCapacityOrRateLimit, "agent_error.provider_capacity_or_rate_limit"},
- {ReasonAgentProviderServerError, "agent_error.provider_server_error"},
- {ReasonAgentProviderNetwork, "agent_error.provider_network"},
- {ReasonAgentProcessFailure, "agent_error.process_failure"},
- {ReasonAgentEmptyOrUnparseableOutput, "agent_error.empty_or_unparseable_output"},
- {ReasonAgentTimeout, "agent_error.agent_timeout"},
- {ReasonAgentContextOverflow, "agent_error.context_overflow"},
- {ReasonAgentMissingConfig, "agent_error.missing_config"},
- {ReasonAgentModelNotFoundOrUnavailable, "agent_error.model_not_found_or_unavailable"},
- {ReasonAgentRuntimeVersionUnsupported, "agent_error.runtime_version_unsupported"},
- {ReasonAgentRuntimeMissingExecutable, "agent_error.runtime_missing_executable"},
- {ReasonAgentUnknown, "agent_error.unknown"},
- }
-
- if got, want := len(cases), 26; got != want {
- t.Fatalf("constant count = %d, want %d (canonical taxonomy size)", got, want)
- }
-
- for _, c := range cases {
- t.Run(c.want, func(t *testing.T) {
- if got := c.reason.String(); got != c.want {
- t.Errorf("Reason(%q).String() = %q, want %q", c.reason, got, c.want)
- }
- })
- }
-}
-
-// TestIsAgentError pins the platform-side vs agent-side split so a
-// future Prometheus collector / retry policy can rely on the prefix
-// rather than maintaining a parallel allow-list.
-func TestIsAgentError(t *testing.T) {
- t.Parallel()
-
- platformSide := []Reason{
- ReasonQueuedExpired,
- ReasonRuntimeOffline,
- ReasonRuntimeReconnectTimeout,
- ReasonRuntimeRecovery,
- ReasonTimeout,
- ReasonIterationLimit,
- ReasonAgentBlocked,
- ReasonAPIInvalidRequest,
- ReasonSkillBundleUnavailable,
- ReasonRuntimeCLITimeout,
- ReasonEnvironmentPrepareFailed,
- ReasonInvalidTaskIdentity,
- }
- for _, r := range platformSide {
- if r.IsAgentError() {
- t.Errorf("%q.IsAgentError() = true, want false (platform-side)", r)
- }
- }
-
- agentSide := []Reason{
- ReasonAgentProviderAuthOrAccess,
- ReasonAgentProviderQuotaLimit,
- ReasonAgentProviderCapacityOrRateLimit,
- ReasonAgentProviderServerError,
- ReasonAgentProviderNetwork,
- ReasonAgentProcessFailure,
- ReasonAgentEmptyOrUnparseableOutput,
- ReasonAgentTimeout,
- ReasonAgentContextOverflow,
- ReasonAgentMissingConfig,
- ReasonAgentModelNotFoundOrUnavailable,
- ReasonAgentRuntimeVersionUnsupported,
- ReasonAgentRuntimeMissingExecutable,
- ReasonAgentUnknown,
- }
- for _, r := range agentSide {
- if !r.IsAgentError() {
- t.Errorf("%q.IsAgentError() = false, want true (agent-side)", r)
- }
- if !strings.HasPrefix(r.String(), "agent_error.") {
- t.Errorf("%q missing required agent_error. prefix", r)
- }
- }
-}
-
-// TestAllReasonsContents verifies that AllReasons() returns the
-// complete canonical taxonomy with no duplicates and no surprise
-// values. Prometheus pre-warming relies on this fixture being stable.
-func TestAllReasonsContents(t *testing.T) {
- t.Parallel()
-
- got := AllReasons()
- if len(got) != 26 {
- t.Fatalf("AllReasons() returned %d entries, want 26", len(got))
- }
-
- seen := make(map[Reason]bool, len(got))
- var platformCount, agentCount int
- for _, r := range got {
- if seen[r] {
- t.Errorf("AllReasons() returned duplicate %q", r)
- }
- seen[r] = true
- if r.IsAgentError() {
- agentCount++
- } else {
- platformCount++
- }
- }
-
- if platformCount != 12 {
- t.Errorf("AllReasons(): platform-side count = %d, want 12", platformCount)
- }
- if agentCount != 14 {
- t.Errorf("AllReasons(): agent-side count = %d, want 14", agentCount)
- }
-
- // Sanity-check that every constant declared at package level
- // shows up in AllReasons. This catches a future drift where
- // someone adds a constant but forgets to register it in the
- // allReasons slice.
- required := []Reason{
- ReasonQueuedExpired, ReasonRuntimeOffline, ReasonRuntimeReconnectTimeout,
- ReasonRuntimeRecovery,
- ReasonTimeout, ReasonIterationLimit, ReasonAgentBlocked,
- ReasonAPIInvalidRequest, ReasonSkillBundleUnavailable,
- ReasonRuntimeCLITimeout, ReasonEnvironmentPrepareFailed,
- ReasonInvalidTaskIdentity,
- ReasonAgentProviderAuthOrAccess, ReasonAgentProviderQuotaLimit,
- ReasonAgentProviderCapacityOrRateLimit, ReasonAgentProviderServerError,
- ReasonAgentProviderNetwork, ReasonAgentProcessFailure,
- ReasonAgentEmptyOrUnparseableOutput, ReasonAgentTimeout,
- ReasonAgentContextOverflow, ReasonAgentMissingConfig,
- ReasonAgentModelNotFoundOrUnavailable,
- ReasonAgentRuntimeVersionUnsupported,
- ReasonAgentRuntimeMissingExecutable,
- ReasonAgentUnknown,
- }
- for _, r := range required {
- if !seen[r] {
- t.Errorf("AllReasons() missing canonical reason %q", r)
- }
- }
-}
-
// TestAllReasonsIsDefensiveCopy guards the contract that mutating the
// returned slice cannot corrupt the package-level fixture. Without
// this, two callers (e.g. two Prometheus collectors at startup) could