Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

test: raise coverage above 80% and release 0.9.7

Yuting Zhong96a1b34c590f
diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.md
index 196f2c71..6dd9b053 100644
--- a/notfair/CHANGELOG.md
+++ b/notfair/CHANGELOG.md
@@ -1,11 +1,13 @@
# NotFair
-## Unreleased
+## 0.9.7 — 2026-07-21
**`notfair update` — one command from "there's a newer version" to running it.** Checks npm, installs globally, and restarts whatever is running: launchd-managed servers restart through the (freshly rewritten) LaunchAgent, background daemons are stopped and relaunched on the same port and data dir, and source checkouts are pointed at `git pull && pnpm build` instead of being paved over.
**In-app updates actually work now — and finish with one click.** The sidebar's update check had been dead since the rebrand: it asked the npm registry for `NotFair`, but the registry is case-sensitive and the package is `notfair`, so the "update available" button never appeared. Fixed — and upgraded: after installing an update, background and launchd-managed servers now show **Restart now**, restart themselves, and reload the page on the new version. No more "go restart it in your terminal" (that note remains only for foreground/dev runs, which the app never kills).
+**Search Console setup now handles accounts with no reachable properties.** Empty `sites` and `siteEntry` responses are valid and render as an empty property list instead of being rejected as malformed. The test suite now covers 80%+ of executable statements and lines, with enforced coverage thresholds to prevent regression.
+
## 0.9.6 — 2026-07-21
**NotFair now runs in the background — and survives reboots.** `notfair` (or `notfair start`) detaches the server, waits for it to answer, and opens the UI; your terminal stays free and closing it no longer kills the loop. New lifecycle commands: `notfair status` (pid, port, uptime, health), `notfair stop` (finally implemented), and `notfair logs -f` (server log lives at `~/.notfair/logs/server.log`). `notfair autostart enable` installs a macOS LaunchAgent that starts NotFair at login and restarts it if it crashes — launchd becomes the single owner, so `start`/`stop` delegate to it instead of racing it for the port, the agent captures your shell's PATH so `claude`/`codex` stay reachable at login, and `start` self-heals the entry when an upgrade moves the package on disk. `--foreground` keeps the old attached behavior.
diff --git a/notfair/package.json b/notfair/package.json
index 83f3d095..fcedd47c 100644
--- a/notfair/package.json
+++ b/notfair/package.json
@@ -1,6 +1,6 @@
{
"name": "notfair",
- "version": "0.9.6",
+ "version": "0.9.7",
"description": "Goal-driven, loop-powered marketing agents that crush your business goals 24/7 — on your own machine. Say 'cut CAC to $30' and a dedicated agent turns it into a server-verified metric, then moves the number check after check while you sleep. Rides your existing Claude Code or Codex login.",
"license": "MIT",
"bin": {
diff --git a/notfair/src/components/chat/composer.test.tsx b/notfair/src/components/chat/composer.test.tsx
new file mode 100644
index 00000000..4aca7382
--- /dev/null
+++ b/notfair/src/components/chat/composer.test.tsx
@@ -0,0 +1,147 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ filter: vi.fn() }));
+
+vi.mock("@/lib/slash-commands", () => ({
+ filterSlashCommands: mocks.filter,
+}));
+vi.mock("@/components/slash-command-popover", () => ({
+ SlashCommandPopover: ({ commands, selectedIndex, onSelect, onHover }: {
+ commands: Array<{ name: string; insert?: string }>;
+ selectedIndex: number;
+ onSelect: (command: { name: string; insert?: string }) => void;
+ onHover: (index: number) => void;
+ }) => (
+ <div data-testid="slash" data-selected={selectedIndex}>
+ {commands.map((command, index) => (
+ <button key={command.name} onMouseEnter={() => onHover(index)} onClick={() => onSelect(command)}>
+ {command.name}
+ </button>
+ ))}
+ </div>
+ ),
+}));
+vi.mock("@/components/running-dot", () => ({ RunningDot: () => <span data-testid="running-dot" /> }));
+vi.mock("@/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DropdownMenuRadioGroup: ({ children, value }: { children: React.ReactNode; value: string }) => <div data-value={value}>{children}</div>,
+ DropdownMenuRadioItem: ({ children, value }: { children: React.ReactNode; value: string }) => <span data-value={value}>{children}</span>,
+}));
+
+import { ChatComposer } from "./composer";
+
+const props = {
+ busy: false,
+ sendingChat: false,
+ placeholder: "Message agent",
+ model: "",
+ onPickModel: vi.fn(),
+ onSubmit: vi.fn(),
+ onStop: vi.fn(),
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.filter.mockImplementation(() => [
+ { name: "new" },
+ { name: "clear", insert: "/clear" },
+ ]);
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ });
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+it("submits trimmed text by form submit and Enter, then clears", () => {
+ render(<ChatComposer {...props} />);
+ const textbox = screen.getByPlaceholderText("Message agent");
+ Object.defineProperty(textbox, "scrollHeight", { configurable: true, value: 80 });
+ fireEvent.change(textbox, { target: { value: " hello " } });
+ expect(textbox).toHaveStyle({ height: "80px" });
+ fireEvent.submit(textbox.closest("form")!);
+ expect(props.onSubmit).toHaveBeenCalledWith("hello");
+ expect(textbox).toHaveValue("");
+ fireEvent.change(textbox, { target: { value: "again" } });
+ fireEvent.keyDown(textbox, { key: "Enter", shiftKey: false });
+ expect(props.onSubmit).toHaveBeenLastCalledWith("again");
+});
+
+it("allows Shift+Enter and blocks empty submissions", () => {
+ render(<ChatComposer {...props} />);
+ const textbox = screen.getByRole("textbox");
+ fireEvent.keyDown(textbox, { key: "Enter", shiftKey: true });
+ fireEvent.submit(textbox.closest("form")!);
+ expect(props.onSubmit).not.toHaveBeenCalled();
+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();
+});
+
+it("shows model labels for selected, default, and stale values", () => {
+ const options = [
+ { value: "fast", label: "Fast", is_default: true },
+ { value: "deep", label: "Deep" },
+ ];
+ const { rerender } = render(<ChatComposer {...props} modelOptions={options} model="deep" />);
+ expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Deep");
+ rerender(<ChatComposer {...props} modelOptions={options} model="missing" />);
+ expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Fast");
+ rerender(<ChatComposer {...props} modelOptions={[{ value: "x", label: "X" }]} model="" />);
+ expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent("Default");
+});
+
+it("navigates slash matches with arrows and inserts via Tab", () => {
+ render(<ChatComposer {...props} />);
+ const textbox = screen.getByRole("textbox");
+ fireEvent.change(textbox, { target: { value: "/" } });
+ expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "0");
+ fireEvent.keyDown(textbox, { key: "ArrowDown" });
+ expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "1");
+ fireEvent.keyDown(textbox, { key: "ArrowDown" });
+ expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "0");
+ fireEvent.keyDown(textbox, { key: "ArrowUp" });
+ expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "1");
+ fireEvent.keyDown(textbox, { key: "Tab" });
+ expect(textbox).toHaveValue("/clear");
+ expect(textbox).toHaveFocus();
+});
+
+it("inserts slash choices via click/Enter and dismisses with Escape", () => {
+ render(<ChatComposer {...props} />);
+ const textbox = screen.getByRole("textbox");
+ fireEvent.change(textbox, { target: { value: "/" } });
+ fireEvent.mouseEnter(screen.getByRole("button", { name: "clear" }));
+ expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "1");
+ fireEvent.click(screen.getByRole("button", { name: "new" }));
+ expect(textbox).toHaveValue("/new ");
+ fireEvent.change(textbox, { target: { value: "/" } });
+ fireEvent.keyDown(textbox, { key: "Enter" });
+ expect(textbox).toHaveValue("/new ");
+ fireEvent.change(textbox, { target: { value: "/" } });
+ fireEvent.keyDown(textbox, { key: "Escape" });
+ expect(textbox).toHaveValue("");
+});
+
+it("hides slash choices after a space, while sending, or when disabled", () => {
+ const { rerender } = render(<ChatComposer {...props} />);
+ const textbox = screen.getByRole("textbox");
+ fireEvent.change(textbox, { target: { value: "/new title" } });
+ expect(screen.queryByTestId("slash")).not.toBeInTheDocument();
+ rerender(<ChatComposer {...props} sendingChat busy />);
+ expect(screen.queryByTestId("slash")).not.toBeInTheDocument();
+ rerender(<ChatComposer {...props} disabled />);
+ expect(screen.queryByText(/Enter to send/)).not.toBeInTheDocument();
+});
+
+it("renders local/remote busy copy and stops the turn", () => {
+ const { rerender } = render(<ChatComposer {...props} busy sendingChat />);
+ expect(screen.getByText(/Streaming/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Stop" }));
+ expect(props.onStop).toHaveBeenCalled();
+ rerender(<ChatComposer {...props} busy sendingChat={false} />);
+ expect(screen.getByText(/Agent is working/)).toBeInTheDocument();
+});
diff --git a/notfair/src/components/chat/use-chat-stream.test.tsx b/notfair/src/components/chat/use-chat-stream.test.tsx
new file mode 100644
index 00000000..63ad0d0e
--- /dev/null
+++ b/notfair/src/components/chat/use-chat-stream.test.tsx
@@ -0,0 +1,258 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useChatStream } from "./use-chat-stream";
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
+
+const base = {
+ projectSlug: "acme co",
+ agentSlug: "goal-1",
+ threadId: "main",
+ initialEvents: [] as TranscriptEvent[],
+ initialCursor: 0,
+ model: "",
+};
+
+class FakeEventSource {
+ static instances: FakeEventSource[] = [];
+ readonly url: string;
+ readyState = 1;
+ close = vi.fn();
+ private listeners = new Map<string, Array<(event: MessageEvent) => void>>();
+
+ constructor(url: string) {
+ this.url = url;
+ FakeEventSource.instances.push(this);
+ }
+
+ addEventListener(name: string, listener: EventListener) {
+ const entries = this.listeners.get(name) ?? [];
+ entries.push(listener as (event: MessageEvent) => void);
+ this.listeners.set(name, entries);
+ }
+
+ emit(name: string, data = "") {
+ for (const listener of this.listeners.get(name) ?? []) {
+ listener(new MessageEvent(name, { data }));
+ }
+ }
+}
+
+function pollResponse(events: TranscriptEvent[] = [], cursor = 0) {
+ return {
+ ok: true,
+ json: vi.fn(async () => ({ events, cursor })),
+ };
+}
+
+function streamResponse(chunks: string[], afterChunks?: Promise<void>) {
+ const encoder = new TextEncoder();
+ let index = 0;
+ return {
+ ok: true,
+ status: 200,
+ body: {
+ getReader: () => ({
+ read: vi.fn(async () => {
+ if (index < chunks.length) return { value: encoder.encode(chunks[index++]!), done: false };
+ if (afterChunks) await afterChunks;
+ return { value: undefined, done: true };
+ }),
+ }),
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ FakeEventSource.instances = [];
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(pollResponse()));
+ vi.stubGlobal("EventSource", FakeEventSource);
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "groupCollapsed").mockImplementation(() => {});
+ vi.spyOn(console, "table").mockImplementation(() => {});
+ vi.spyOn(console, "groupEnd").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+it("exposes initial events, derives remote-turn state, and clears the local view", () => {
+ const now = Date.now();
+ const initialEvents: TranscriptEvent[] = [
+ { kind: "lifecycle", id: "start", ts: now, phase: "start" },
+ { kind: "assistant_text", id: "delta", ts: now + 1, body: "working" },
+ ];
+ const { result } = renderHook(() => useChatStream({ ...base, initialEvents, initialCursor: 2 }));
+ expect(result.current.events).toEqual(initialEvents);
+ expect(result.current.openTurn).toMatchObject({ startedAt: now });
+ expect(result.current.remoteTurnActive).toBe(true);
+ act(() => result.current.clearLocal());
+ expect(result.current.events).toEqual([]);
+ expect(result.current.openTurn).toBeNull();
+});
+
+it("polls, advances the cursor, and deduplicates by id and content signature", async () => {
+ vi.useFakeTimers();
+ const original: TranscriptEvent = { kind: "assistant_text", id: "one", ts: 1, body: "same" };
+ const fresh: TranscriptEvent = { kind: "assistant_text", id: "three", ts: 3, body: "fresh" };
+ vi.mocked(fetch).mockResolvedValue(
+ pollResponse([
+ original,
+ { ...original, id: "two", ts: 2 },
+ fresh,
+ ], 3) as never,
+ );
+ const { result } = renderHook(() => useChatStream({ ...base, initialEvents: [original], initialCursor: 1 }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(2_000); });
+ expect(result.current.events).toEqual([original, fresh]);
+ expect(fetch).toHaveBeenCalledWith(
+ "/api/agents/goal-1/threads/main/transcript?offset=1&project=acme%20co",
+ { cache: "no-store" },
+ );
+});
+
+it("ignores failed and throwing polls", async () => {
+ vi.useFakeTimers();
+ vi.mocked(fetch)
+ .mockResolvedValueOnce({ ok: false } as Response)
+ .mockRejectedValueOnce(new Error("offline"));
+ const { result } = renderHook(() => useChatStream(base));
+ await act(async () => { await vi.advanceTimersByTimeAsync(2_000); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(2_000); });
+ expect(result.current.events).toEqual([]);
+});
+
+it("merges live bridge events, rejects bad payloads, logs lifecycle events, and closes", () => {
+ const { result, unmount } = renderHook(() => useChatStream(base));
+ const source = FakeEventSource.instances[0]!;
+ expect(source.url).toContain("/live?project=acme%20co");
+ act(() => {
+ source.emit("open");
+ source.emit("ready", "ready");
+ source.emit("transcript", "not json");
+ source.emit("transcript", JSON.stringify({ events: "bad" }));
+ source.emit("error", "oops");
+ source.emit("transcript", JSON.stringify({
+ events: [{ kind: "assistant_text", id: "live-1", ts: 1, body: "live" }],
+ }));
+ });
+ expect(result.current.events).toMatchObject([{ id: "live-1", body: "live" }]);
+ unmount();
+ expect(source.close).toHaveBeenCalled();
+});
+
+it("skips the bridge when EventSource is unavailable", () => {
+ vi.unstubAllGlobals();
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(pollResponse()));
+ renderHook(() => useChatStream(base));
+ expect(FakeEventSource.instances).toHaveLength(0);
+});
+
+it("streams text, tools, lifecycle, error, meta, and perf events", async () => {
+ let finish!: () => void;
+ const blocked = new Promise<void>((resolve) => { finish = resolve; });
+ const sse = [
+ 'event: text\ndata: {"chunk":"Hello "}',
+ 'event: text\ndata: {"chunk":"world"}',
+ 'event: tool\ndata: {"phase":"start","tool_call_id":"tc1","name":"search","label":"Searching"}',
+ 'event: tool\ndata: {"phase":"result","tool_call_id":"tc1","name":"search"}',
+ 'event: lifecycle\ndata: {"phase":"run.warming"}',
+ 'event: error\ndata: {"message":"soft warning"}',
+ 'event: meta\ndata: {"agent":"a","session_id":"s","message_chars":5,"is_kickoff":true}',
+ 'event: perf\ndata: {"marks":[{"name":"done","at":10.4,"delta":2.6}]}',
+ ].join("\n\n") + "\n\n";
+ vi.mocked(fetch).mockImplementation((url) => {
+ if (url === "/api/chat") return Promise.resolve(streamResponse([sse], blocked) as never);
+ return Promise.resolve(pollResponse() as never);
+ });
+ const { result } = renderHook(() => useChatStream({ ...base, model: "gpt-test" }));
+ let sendPromise!: ReturnType<typeof result.current.send>;
+ act(() => { sendPromise = result.current.send("hello"); });
+ await waitFor(() => expect(result.current.pendingAssistant).toBe("Hello world"));
+ expect(result.current.sendingChat).toBe(true);
+ expect(result.current.pendingUserMsg).toBe("hello");
+ expect(result.current.pendingTools).toMatchObject([{ toolCallId: "tc1", done: true }]);
+ expect(result.current.pendingLifecycle).toBe("run.warming");
+ expect(result.current.pendingError).toBe("soft warning");
+ expect(JSON.parse(String(vi.mocked(fetch).mock.calls.find(([u]) => u === "/api/chat")?.[1]?.body))).toMatchObject({
+ message: "hello",
+ model: "gpt-test",
+ });
+ finish();
+ await act(async () => {
+ await sendPromise;
+ });
+ expect(result.current.sendingChat).toBe(false);
+ expect(result.current.pendingLifecycle).toBeNull();
+ expect(console.groupCollapsed).toHaveBeenCalled();
+});
+
+it("supports hidden sends and clears optimistic state when polling catches up", async () => {
+ vi.useFakeTimers();
+ const committed: TranscriptEvent = { kind: "assistant_text", id: "db-1", ts: 2, body: "done" };
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(streamResponse([]) as never)
+ .mockResolvedValueOnce(pollResponse([committed], 1) as never);
+ const { result } = renderHook(() => useChatStream(base));
+ let promise!: ReturnType<typeof result.current.send>;
+ act(() => { promise = result.current.send("secret", { hidden: true }); });
+ expect(result.current.pendingUserMsg).toBeNull();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ await promise;
+ });
+ expect(result.current.events).toEqual([committed]);
+ expect(result.current.pendingAssistant).toBe("");
+});
+
+it("returns response and thrown errors to the caller", async () => {
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: false,
+ status: 503,
+ body: {},
+ text: vi.fn(async () => "server sad"),
+ } as never);
+ const { result } = renderHook(() => useChatStream(base));
+ await act(async () => {
+ await expect(result.current.send("hello")).resolves.toEqual({ error: "server sad" });
+ });
+ expect(result.current.pendingError).toBe("server sad");
+
+ vi.mocked(fetch).mockRejectedValueOnce("string failure");
+ await act(async () => {
+ await expect(result.current.send("again")).resolves.toEqual({ error: "string failure" });
+ });
+});
+
+it("ignores empty/concurrent sends and stops both the local and server turn", async () => {
+ let rejectChat!: (error: unknown) => void;
+ vi.mocked(fetch).mockImplementation((url, init) => {
+ if (url === "/api/chat/stop") return Promise.reject(new Error("best effort"));
+ if (url === "/api/chat") {
+ return new Promise((_resolve, reject) => {
+ rejectChat = reject;
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
+ });
+ }
+ return Promise.resolve(pollResponse() as never);
+ });
+ const { result } = renderHook(() => useChatStream(base));
+ await expect(result.current.send("")).resolves.toBeUndefined();
+ let first!: ReturnType<typeof result.current.send>;
+ act(() => { first = result.current.send("go"); });
+ await waitFor(() => expect(result.current.sendingChat).toBe(true));
+ await expect(result.current.send("duplicate")).resolves.toBeUndefined();
+ act(() => result.current.stopTurn());
+ await act(async () => { await first; });
+ expect(result.current.sendingChat).toBe(false);
+ expect(fetch).toHaveBeenCalledWith("/api/chat/stop", expect.objectContaining({
+ body: JSON.stringify({ project: "acme co", agent: "goal-1", thread: "main" }),
+ }));
+ void rejectChat;
+});
diff --git a/notfair/src/components/codebase-path-card.test.tsx b/notfair/src/components/codebase-path-card.test.tsx
new file mode 100644
index 00000000..6027db68
--- /dev/null
+++ b/notfair/src/components/codebase-path-card.test.tsx
@@ -0,0 +1,142 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { CodebasePathCard } from "@/components/codebase-path-card";
+
+// Mock at the server-action boundary, per repo test conventions.
+const setPath = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/projects", () => ({
+ setProjectCodebasePathAction: setPath,
+}));
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({
+ toast: { success: toastSuccess, error: toastError },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function renderCard(currentPath: string | null = null) {
+ return render(
+ <CodebasePathCard projectSlug="acme" currentPath={currentPath} />,
+ );
+}
+
+describe("CodebasePathCard", () => {
+ it("seeds the field from the current path and keeps Save disabled until dirty", () => {
+ renderCard("/repo/site");
+ expect(screen.getByLabelText("Local codebase folder")).toHaveValue(
+ "/repo/site",
+ );
+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
+
+ fireEvent.change(screen.getByLabelText("Local codebase folder"), {
+ target: { value: "/repo/other" },
+ });
+ expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();
+ });
+
+ it("fills the field from the folder picker result", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ json: async () => ({ ok: true, path: "/picked/dir" }),
+ }),
+ );
+ renderCard();
+ fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));
+ await waitFor(() =>
+ expect(screen.getByLabelText("Local codebase folder")).toHaveValue(
+ "/picked/dir",
+ ),
+ );
+ expect(fetch).toHaveBeenCalledWith("/api/fs/pick-folder", {
+ method: "POST",
+ });
+ });
+
+ it("silently ignores a cancelled folder pick", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ json: async () => ({ ok: false, kind: "cancelled" }),
+ }),
+ );
+ renderCard();
+ fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));
+ await waitFor(() => expect(fetch).toHaveBeenCalled());
+ expect(screen.getByLabelText("Local codebase folder")).toHaveValue("");
+ expect(toastError).not.toHaveBeenCalled();
+ });
+
+ it("toasts the picker's message on an unsupported/error result", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ json: async () => ({ ok: false, kind: "unsupported", message: "no zenity" }),
+ }),
+ );
+ renderCard();
+ fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith("no zenity"));
+ });
+
+ it("toasts a thrown fetch error", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockRejectedValue(new Error("network down")),
+ );
+ renderCard();
+ fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith("network down"));
+ });
+
+ it("saves a path and confirms agents can now propose changes", async () => {
+ setPath.mockResolvedValue({ ok: true, codebase_path: "/repo/site" });
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Local codebase folder"), {
+ target: { value: "/repo/site" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => {
+ expect(setPath).toHaveBeenCalledWith({
+ project_slug: "acme",
+ codebase_path: "/repo/site",
+ });
+ expect(toastSuccess).toHaveBeenCalledWith(
+ "Codebase folder saved — agents can now propose code changes via pull requests.",
+ );
+ });
+ });
+
+ it("confirms clearing when the saved path comes back null", async () => {
+ setPath.mockResolvedValue({ ok: true, codebase_path: null });
+ renderCard("/repo/site");
+ fireEvent.change(screen.getByLabelText("Local codebase folder"), {
+ target: { value: "" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() =>
+ expect(toastSuccess).toHaveBeenCalledWith(
+ "Codebase folder cleared — agents can no longer change code.",
+ ),
+ );
+ });
+
+ it("surfaces a save error as a toast", async () => {
+ setPath.mockResolvedValue({ ok: false, error: "bad path" });
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Local codebase folder"), {
+ target: { value: "/x" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith("bad path"));
+ });
+});
diff --git a/notfair/src/components/goal-progress-chart.test.tsx b/notfair/src/components/goal-progress-chart.test.tsx
new file mode 100644
index 00000000..99e0e492
--- /dev/null
+++ b/notfair/src/components/goal-progress-chart.test.tsx
@@ -0,0 +1,95 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import { GoalProgressChart, type ChartAction, type ChartFailure, type ChartPoint } from "./goal-progress-chart";
+
+const now = Date.UTC(2026, 0, 10);
+const points: ChartPoint[] = [
+ { t: now - 3_000, v: 1000, source: "backfill" },
+ { t: now - 1_000, v: 1250.25, source: "live" },
+];
+const actions: ChartAction[] = [
+ { t: now - 2_000, kind: "change", label: "Ship page", expected: "+10%", observed: "+12%", reviewUntil: now + 5_000 },
+ { t: now - 1_500, kind: "change", label: "Wait", expected: "+5%", observed: null, reviewUntil: now + 2_000 },
+];
+const failures: ChartFailure[] = [{ t: now - 500, error: "API offline" }];
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(now);
+});
+
+afterEach(() => vi.useRealTimers());
+
+it("shows the empty state until there are two readings", () => {
+ const { rerender } = render(
+ <GoalProgressChart points={[]} actions={[]} failures={[]} target={null} baseline={null} deadline={null} />,
+ );
+ expect(screen.getByText(/chart appears after a couple of readings/)).toBeInTheDocument();
+ rerender(<GoalProgressChart points={[points[0]!]} actions={[]} failures={[]} target={null} baseline={null} deadline={null} />);
+ expect(screen.getByText(/chart appears/)).toBeInTheDocument();
+});
+
+it("renders metric, references, action windows, failures, and a deadline", () => {
+ const { container } = render(
+ <GoalProgressChart
+ points={points}
+ actions={actions}
+ failures={failures}
+ target={1500}
+ baseline={1000}
+ deadline={now - 250}
+ />,
+ );
+ expect(screen.getByRole("img")).toHaveAttribute("aria-label", "Metric over time. Latest 1.3k, target 1.5k.");
+ expect(screen.getByText("target 1.5k")).toBeInTheDocument();
+ expect(screen.getByText("⚑ deadline")).toBeInTheDocument();
+ expect(screen.getByText("✕")).toBeInTheDocument();
+ expect(container.querySelectorAll("svg rect").length).toBeGreaterThan(2);
+ expect(container.querySelector("svg path[d^='M']")).toBeInTheDocument();
+});
+
+it("handles a flat series by adding vertical padding", () => {
+ render(
+ <GoalProgressChart
+ points={[{ ...points[0]!, v: 7 }, { ...points[1]!, v: 7 }]}
+ actions={[]}
+ failures={[]}
+ target={null}
+ baseline={null}
+ deadline={now + 50_000}
+ />,
+ );
+ expect(screen.getByRole("img")).toHaveAttribute("aria-label", "Metric over time. Latest 7.");
+ expect(screen.queryByText("⚑ deadline")).not.toBeInTheDocument();
+});
+
+it("shows nearest point details and clears a distant hover", () => {
+ render(<GoalProgressChart points={points} actions={[]} failures={[]} target={null} baseline={null} deadline={null} />);
+ const svg = screen.getByRole("img");
+ vi.spyOn(svg, "getBoundingClientRect").mockReturnValue({ left: 0, width: 340, top: 0, height: 170 } as DOMRect);
+ fireEvent.mouseMove(svg, { clientX: 34 });
+ expect(screen.getAllByText("1.0k")).toHaveLength(2);
+ expect(screen.getByText(/history/)).toBeInTheDocument();
+ fireEvent.mouseMove(svg, { clientX: 330 });
+ fireEvent.mouseLeave(svg);
+ expect(screen.queryByText(/history/)).not.toBeInTheDocument();
+});
+
+it("shows observed, measuring, and failure tooltips", () => {
+ const { container } = render(
+ <GoalProgressChart points={points} actions={actions} failures={failures} target={null} baseline={null} deadline={null} />,
+ );
+ const hoverGroups = container.querySelectorAll("g.cursor-help");
+ fireEvent.mouseEnter(hoverGroups[0]!);
+ expect(screen.getByText(/Ship page/)).toBeInTheDocument();
+ expect(screen.getByText(/observed: \+12%/)).toBeInTheDocument();
+ fireEvent.mouseLeave(hoverGroups[0]!);
+ fireEvent.mouseEnter(hoverGroups[1]!);
+ expect(screen.getByText(/measuring until/)).toBeInTheDocument();
+ fireEvent.mouseEnter(hoverGroups[2]!);
+ expect(screen.getByText("API offline")).toBeInTheDocument();
+ fireEvent.mouseLeave(hoverGroups[2]!);
+ expect(screen.queryByText("API offline")).not.toBeInTheDocument();
+});
diff --git a/notfair/src/components/onboarding-flow.test.tsx b/notfair/src/components/onboarding-flow.test.tsx
new file mode 100644
index 00000000..07f769dc
--- /dev/null
+++ b/notfair/src/components/onboarding-flow.test.tsx
@@ -0,0 +1,191 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ push: vi.fn(),
+ replace: vi.fn(),
+ params: new Map<string, string>(),
+ createProject: vi.fn(),
+ getCards: vi.fn(),
+ toastError: vi.fn(),
+ mcpCardProps: [] as Array<Record<string, unknown>>,
+ goalFormProps: vi.fn(),
+ menuProps: vi.fn(),
+ bannerProps: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: mocks.push, replace: mocks.replace }),
+ useSearchParams: () => ({ get: (key: string) => mocks.params.get(key) ?? null }),
+}));
+vi.mock("next/link", () => ({
+ default: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { href: string }) => (
+ <a href={href} {...props}>{children}</a>
+ ),
+}));
+vi.mock("sonner", () => ({ toast: { error: mocks.toastError } }));
+vi.mock("@/server/actions/projects", () => ({
+ createProjectForOnboardingAction: mocks.createProject,
+}));
+vi.mock("@/server/onboarding/accounts", () => ({
+ getOnboardingConnectCardsAction: mocks.getCards,
+}));
+vi.mock("@/components/mcp-flash-banner", () => ({
+ McpFlashBanner: (props: Record<string, unknown>) => {
+ mocks.bannerProps(props);
+ return <div data-testid="flash-banner" />;
+ },
+}));
+vi.mock("@/components/add-mcp-server-card", () => ({
+ AddMcpServerMenu: (props: { trigger: React.ReactNode; connectedKeys: string[] }) => {
+ mocks.menuProps(props);
+ return <div data-testid="mcp-menu">{props.trigger}</div>;
+ },
+}));
+vi.mock("@/components/mcp-card", () => ({
+ McpCard: (props: Record<string, unknown> & { spec: { key: string }; onMutated: () => void }) => {
+ mocks.mcpCardProps.push(props);
+ return <button onClick={props.onMutated}>card:{props.spec.key}</button>;
+ },
+}));
+vi.mock("@/components/new-goal-form", () => ({
+ NewGoalForm: (props: Record<string, unknown>) => {
+ mocks.goalFormProps(props);
+ return <div data-testid="new-goal-form" />;
+ },
+}));
+
+import { OnboardingFlow } from "./onboarding-flow";
+
+const cards = [
+ {
+ spec: { key: "notfair-googleads", name: "Google Ads" },
+ status: { state: "connected" },
+ selected_id: "123",
+ },
+ {
+ spec: { key: "notfair-metaads", name: "Meta Ads" },
+ status: { state: "not_configured" },
+ selected_id: null,
+ },
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.params.clear();
+ mocks.mcpCardProps.length = 0;
+ mocks.getCards.mockResolvedValue({ ok: true, cards, any_connected: true });
+ mocks.createProject.mockResolvedValue({ ok: true, data: { slug: "acme", display_name: "Acme" } });
+ vi.stubGlobal("fetch", vi.fn());
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("workspace step", () => {
+ it("renders defaults, edits fields, and switches harnesses", () => {
+ render(<OnboardingFlow />);
+ expect(screen.getByRole("heading", { name: /set up your workspace/i })).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText("Workspace name"), { target: { value: "Acme" } });
+ fireEvent.change(screen.getByLabelText(/Website URL/), { target: { value: "https://acme.test" } });
+ expect(screen.getByRole("button", { name: /^Codex/ })).toHaveAttribute("aria-pressed", "true");
+ fireEvent.click(screen.getByRole("button", { name: /^Claude Code/ }));
+ expect(screen.getByRole("button", { name: /^Claude Code/ })).toHaveAttribute("aria-pressed", "true");
+ expect(document.querySelector('input[name="harness_adapter"]')).toHaveValue("claude-code-local");
+ expect(mocks.bannerProps).toHaveBeenCalledWith(expect.objectContaining({ analyzing: false }));
+ });
+
+ it("fills a picked codebase folder", async () => {
+ vi.mocked(fetch).mockResolvedValue({ json: async () => ({ ok: true, path: "/repo/acme" }) } as never);
+ render(<OnboardingFlow />);
+ fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));
+ await waitFor(() => expect(screen.getByLabelText("Local codebase folder")).toHaveValue("/repo/acme"));
+ fireEvent.change(screen.getByLabelText("Local codebase folder"), { target: { value: "/other" } });
+ expect(screen.getByLabelText("Local codebase folder")).toHaveValue("/other");
+ });
+
+ it("silently handles cancellation and toasts picker failures", async () => {
+ vi.mocked(fetch)
+ .mockResolvedValueOnce({ json: async () => ({ ok: false, kind: "cancelled" }) } as never)
+ .mockResolvedValueOnce({ json: async () => ({ ok: false, kind: "unsupported" }) } as never)
+ .mockRejectedValueOnce("network down");
+ render(<OnboardingFlow />);
+ const browse = screen.getByRole("button", { name: "Browse for a folder" });
+ fireEvent.click(browse);
+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ fireEvent.click(browse);
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Couldn't open the folder picker."));
+ fireEvent.click(browse);
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("network down"));
+ });
+});
+
+describe("connect step", () => {
+ beforeEach(() => {
+ mocks.params.set("step", "connect");
+ mocks.params.set("slug", "acme co");
+ mocks.params.set("mcp_connected", "google");
+ mocks.params.set("mcp_analyzing", "1");
+ });
+
+ it("shows loading, then cards, passes picker state, and advances", async () => {
+ let resolve!: (value: unknown) => void;
+ mocks.getCards.mockReturnValueOnce(new Promise((r) => { resolve = r; }));
+ render(
+ <OnboardingFlow
+ pickerMcpKey="notfair-googleads"
+ pickerPrefetch={{ ok: true, items: [], selected_id: "123" } as never}
+ />,
+ );
+ expect(screen.getByText(/Loading your connections/)).toBeInTheDocument();
+ resolve({ ok: true, cards, any_connected: true });
+ await screen.findByRole("heading", { name: /Connect your data sources/i });
+ expect(screen.getByText("card:notfair-googleads")).toBeInTheDocument();
+ expect(mocks.mcpCardProps[0]).toMatchObject({
+ projectSlug: "acme co",
+ selectedAccountId: "123",
+ pickerPrefetch: { ok: true, items: [], selected_id: "123" },
+ });
+ expect(mocks.mcpCardProps[1]?.pickerPrefetch).toBeNull();
+ expect(mocks.menuProps).toHaveBeenCalledWith(expect.objectContaining({ connectedKeys: ["notfair-googleads"] }));
+ fireEvent.click(screen.getByRole("button", { name: /Next/ }));
+ expect(mocks.push).toHaveBeenCalledWith("/onboarding?step=goal&slug=acme%20co");
+ });
+
+ it("reloads card state after a card mutation", async () => {
+ render(<OnboardingFlow />);
+ await screen.findByText("card:notfair-googleads");
+ fireEvent.click(screen.getByText("card:notfair-googleads"));
+ await waitFor(() => expect(mocks.getCards).toHaveBeenCalledTimes(2));
+ });
+
+ it("shows load errors", async () => {
+ mocks.getCards.mockResolvedValue({ ok: false, error: "MCP unavailable" });
+ render(<OnboardingFlow />);
+ expect(await screen.findByRole("alert")).toHaveTextContent("MCP unavailable");
+ expect(screen.getByRole("link", { name: "Start over" })).toHaveAttribute("href", "/onboarding");
+ });
+
+ it("skips directly into the workspace when nothing is connected", async () => {
+ mocks.getCards.mockResolvedValue({ ok: true, cards: [], any_connected: false });
+ render(<OnboardingFlow />);
+ fireEvent.click(await screen.findByRole("button", { name: "Skip" }));
+ expect(mocks.replace).toHaveBeenCalledWith("/acme co");
+ });
+});
+
+it("renders the first-goal step and forwards connected keys", () => {
+ mocks.params.set("step", "goal");
+ mocks.params.set("slug", "acme");
+ render(<OnboardingFlow connectedMcpKeys={["google", "meta"]} />);
+ expect(screen.getByRole("heading", { name: /Create your first goal/ })).toBeInTheDocument();
+ expect(mocks.goalFormProps).toHaveBeenCalledWith({ projectSlug: "acme", connectedMcpKeys: ["google", "meta"] });
+ expect(screen.getByRole("link", { name: "Skip for now" })).toHaveAttribute("href", "/acme");
+});
+
+it("renders a recovery path when a later step has no slug", () => {
+ mocks.params.set("step", "goal");
+ render(<OnboardingFlow />);
+ expect(screen.getByText(/This step needs a workspace/)).toBeInTheDocument();
+});
diff --git a/notfair/src/components/project-rename-card.test.tsx b/notfair/src/components/project-rename-card.test.tsx
new file mode 100644
index 00000000..f94ad23e
--- /dev/null
+++ b/notfair/src/components/project-rename-card.test.tsx
@@ -0,0 +1,175 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { ProjectRenameCard } from "@/components/project-rename-card";
+
+// Mock at the server-action boundary, per repo test conventions.
+const renameFull = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/projects", () => ({
+ renameProjectFullAction: renameFull,
+}));
+
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh, push: vi.fn() }),
+}));
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({
+ toast: { success: toastSuccess, error: toastError },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+function renderCard(over: Partial<React.ComponentProps<typeof ProjectRenameCard>> = {}) {
+ return render(
+ <ProjectRenameCard
+ currentSlug="acme"
+ currentDisplayName="Acme"
+ {...over}
+ />,
+ );
+}
+
+describe("ProjectRenameCard", () => {
+ it("starts with the display name and a disabled save when nothing changed", () => {
+ renderCard();
+ expect(screen.getByLabelText("Display name")).toHaveValue("Acme");
+ expect(
+ screen.getByText("Same slug — only the display name changes."),
+ ).toBeInTheDocument();
+ const btn = screen.getByRole("button", { name: "Save name" });
+ expect(btn).toBeDisabled();
+ });
+
+ it("previews a slug change and switches the primary action to rename", () => {
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "Acme Rockets" },
+ });
+ // Slug-change preview names both the old and derived slug.
+ expect(screen.getByText(/Slug changes from/)).toBeInTheDocument();
+ expect(screen.getByText("acme")).toBeInTheDocument();
+ expect(screen.getByText("acme-rockets")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Rename workspace" }),
+ ).toBeEnabled();
+ });
+
+ it("flags an unslug-able name and blocks saving", () => {
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "!!!" },
+ });
+ expect(screen.getByText(/Invalid name:/)).toBeInTheDocument();
+ expect(screen.getByLabelText("Display name")).toHaveAttribute(
+ "aria-invalid",
+ "true",
+ );
+ expect(screen.getByRole("button", { name: "Save name" })).toBeDisabled();
+ });
+
+ it("enables a display-name-only save when the slug is unchanged", () => {
+ renderCard();
+ // Same slug ("acme") but different display name.
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "ACME" },
+ });
+ expect(
+ screen.getByText("Same slug — only the display name changes."),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Save name" })).toBeEnabled();
+ });
+
+ it("reports a full rename with relocated agents on success", async () => {
+ renameFull.mockResolvedValue({
+ ok: true,
+ data: {
+ display_name: "Acme Rockets",
+ full_rename: true,
+ agents_relocated: ["a1", "a2"],
+ agents_failed: [],
+ },
+ });
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "Acme Rockets" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));
+ await waitFor(() => {
+ expect(renameFull).toHaveBeenCalledWith({
+ current_slug: "acme",
+ new_display_name: "Acme Rockets",
+ });
+ expect(toastSuccess).toHaveBeenCalledWith(
+ 'Renamed to "Acme Rockets" (2 agents moved)',
+ );
+ expect(refresh).toHaveBeenCalled();
+ });
+ });
+
+ it("notes failed agent relocations in the success toast", async () => {
+ renameFull.mockResolvedValue({
+ ok: true,
+ data: {
+ display_name: "Acme Rockets",
+ full_rename: true,
+ agents_relocated: ["a1"],
+ agents_failed: [{ agent_id: "a2", error: "locked" }],
+ },
+ });
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "Acme Rockets" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));
+ await waitFor(() =>
+ expect(toastSuccess).toHaveBeenCalledWith(
+ 'Renamed to "Acme Rockets" (1 agents moved, 1 failed)',
+ ),
+ );
+ });
+
+ it("uses the plain toast for a display-name-only rename", async () => {
+ renameFull.mockResolvedValue({
+ ok: true,
+ data: {
+ display_name: "ACME",
+ full_rename: false,
+ agents_relocated: [],
+ agents_failed: [],
+ },
+ });
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "ACME" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save name" }));
+ await waitFor(() =>
+ expect(toastSuccess).toHaveBeenCalledWith('Renamed to "ACME"'),
+ );
+ });
+
+ it("surfaces a server error and does not refresh", async () => {
+ renameFull.mockResolvedValue({ ok: false, error: "slug taken" });
+ renderCard();
+ fireEvent.change(screen.getByLabelText("Display name"), {
+ target: { value: "Acme Rockets" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith("slug taken"));
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
+ it("syncs the field when the current display name prop changes", () => {
+ const { rerender } = renderCard();
+ rerender(
+ <ProjectRenameCard currentSlug="acme" currentDisplayName="Renamed Co" />,
+ );
+ expect(screen.getByLabelText("Display name")).toHaveValue("Renamed Co");
+ });
+});
diff --git a/notfair/src/lib/display-helpers.test.ts b/notfair/src/lib/display-helpers.test.ts
new file mode 100644
index 00000000..ba78cd80
--- /dev/null
+++ b/notfair/src/lib/display-helpers.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+
+import { colorForAgentSlug } from "./agent-colors";
+import { cadenceLabel, CADENCE_OPTIONS, DEFAULT_CADENCE } from "./goal-cadence";
+import { formatMetric } from "./format-metric";
+import { goalLabel } from "./goal-label";
+import { buildCheckSquares, currentStreak, heldAtTarget } from "./goal-streak";
+
+describe("display helpers", () => {
+ it("assigns deterministic, varied agent colors", () => {
+ expect(colorForAgentSlug("goal-one")).toEqual(colorForAgentSlug("goal-one"));
+ expect(colorForAgentSlug("goal-one")).not.toEqual(colorForAgentSlug("goal-two"));
+ expect(colorForAgentSlug("").chip).toContain("surface-2");
+ });
+
+ it("prefers short labels and trims statement fallbacks at words", () => {
+ expect(goalLabel({ short_label: " Revenue ", statement: "ignored" })).toBe("Revenue");
+ expect(goalLabel({ short_label: " ", statement: " Short ambition " })).toBe("Short ambition");
+ expect(goalLabel({ statement: "This statement is deliberately much longer than forty two characters total" })).toBe(
+ "This statement is deliberately much…",
+ );
+ expect(goalLabel({ statement: "Averylongstatementwithnospacesandmorethanfortytwocharacters" })).toHaveLength(43);
+ expect(goalLabel({})).toBe("New goal");
+ });
+
+ it("formats metrics and cadence presets", () => {
+ expect(formatMetric(null)).toBe("—");
+ expect(formatMetric(undefined)).toBe("—");
+ expect(formatMetric(82065.857142)).toBe("82,065.86");
+ expect(DEFAULT_CADENCE).toBe(CADENCE_OPTIONS[0]!.value);
+ expect(cadenceLabel(DEFAULT_CADENCE)).toContain("Hourly");
+ expect(cadenceLabel("custom cron")).toBe("custom cron");
+ });
+});
+
+describe("goal streaks", () => {
+ it("evaluates increase/decrease targets and null values", () => {
+ expect(heldAtTarget(null, 1, "increase")).toBe(false);
+ expect(heldAtTarget(1, null, "decrease")).toBe(false);
+ expect(heldAtTarget(10, 10, "increase")).toBe(true);
+ expect(heldAtTarget(9, 10, "increase")).toBe(false);
+ expect(heldAtTarget(9, 10, "decrease")).toBe(true);
+ expect(heldAtTarget(11, 10, "decrease")).toBe(false);
+ });
+
+ it("sorts checks and classifies failed, acted, and held squares", () => {
+ const squares = buildCheckSquares([
+ { tick_number: 3, started_at: "2026-01-03T00:00:00Z", metric_value: 12, status: "complete", acted: false },
+ { tick_number: 1, started_at: "2026-01-01T00:00:00Z", metric_value: 8, status: "complete", acted: false },
+ { tick_number: 2, started_at: "2026-01-02T00:00:00Z", metric_value: 11, status: "complete", acted: true },
+ { tick_number: 4, started_at: "2026-01-04T00:00:00Z", metric_value: 20, status: "failed", acted: false },
+ ], 10, "increase");
+ expect(squares.map((square) => [square.tick_number, square.state])).toEqual([
+ [1, "failed"],
+ [2, "acted"],
+ [3, "held"],
+ [4, "failed"],
+ ]);
+ });
+
+ it("computes no, broken, and active streaks", () => {
+ expect(currentStreak([])).toBeNull();
+ expect(currentStreak([{ tick_number: 1, t: 1, state: "failed" }], 100)).toEqual({ holding: false, days: 0 });
+ const day = 86_400_000;
+ expect(currentStreak([
+ { tick_number: 1, t: day, state: "failed" },
+ { tick_number: 2, t: 2 * day, state: "acted" },
+ { tick_number: 3, t: 3 * day, state: "held" },
+ ], 5 * day)).toEqual({ holding: true, days: 3 });
+ expect(currentStreak([{ tick_number: 1, t: 10 * day, state: "held" }], 5 * day)).toEqual({ holding: true, days: 0 });
+ });
+});
diff --git a/notfair/src/server/actions/chat-threads.test.ts b/notfair/src/server/actions/chat-threads.test.ts
new file mode 100644
index 00000000..77d830fb
--- /dev/null
+++ b/notfair/src/server/actions/chat-threads.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ resolveAgentBySlug: vi.fn(),
+ getProject: vi.fn(),
+ deleteSession: vi.fn(),
+ setSessionPinned: vi.fn(),
+ setSessionTitle: vi.fn(),
+ findSession: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/server/agent-meta", () => ({ resolveAgentBySlug: mocks.resolveAgentBySlug }));
+vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));
+vi.mock("@/server/sessions", () => ({
+ deleteSession: mocks.deleteSession,
+ setSessionPinned: mocks.setSessionPinned,
+ setSessionTitle: mocks.setSessionTitle,
+}));
+vi.mock("@/server/sessions/view", () => ({ findSessionBySessionId: mocks.findSession }));
+
+import { deleteThreadAction, renameThreadAction, setThreadPinnedAction } from "./chat-threads";
+
+const base = { projectSlug: "acme", agentSlug: "goal-1", threadLabel: "thread-1" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getProject.mockReturnValue({ slug: "acme", archived_at: null });
+ mocks.resolveAgentBySlug.mockResolvedValue({ agent_id: "agent-1" });
+ mocks.findSession.mockReturnValue({ sessionKey: "db-session-1" });
+});
+
+it("renames, pins, and deletes an owned thread", async () => {
+ await expect(renameThreadAction({ ...base, title: "New" })).resolves.toEqual({ ok: true });
+ expect(mocks.setSessionTitle).toHaveBeenCalledWith("db-session-1", "New");
+ await expect(setThreadPinnedAction({ ...base, pinned: true })).resolves.toEqual({ ok: true });
+ expect(mocks.setSessionPinned).toHaveBeenCalledWith("db-session-1", true);
+ await expect(deleteThreadAction(base)).resolves.toEqual({ ok: true });
+ expect(mocks.deleteSession).toHaveBeenCalledWith("db-session-1");
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+});
+
+it.each([null, { slug: "acme", archived_at: "yesterday" }])("rejects missing/archived project %#", async (project) => {
+ mocks.getProject.mockReturnValue(project);
+ await expect(renameThreadAction({ ...base, title: "New" })).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+});
+
+it("rejects unknown agents and threads", async () => {
+ mocks.resolveAgentBySlug.mockResolvedValue(null);
+ await expect(setThreadPinnedAction({ ...base, pinned: false })).resolves.toEqual({
+ ok: false,
+ error: "Unknown agent 'goal-1'",
+ });
+ mocks.resolveAgentBySlug.mockResolvedValue({ agent_id: "agent-1" });
+ mocks.findSession.mockReturnValue(null);
+ await expect(deleteThreadAction(base)).resolves.toEqual({ ok: false, error: "Thread not found." });
+});
diff --git a/notfair/src/server/actions/context.test.ts b/notfair/src/server/actions/context.test.ts
new file mode 100644
index 00000000..941ac80b
--- /dev/null
+++ b/notfair/src/server/actions/context.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ readFile: vi.fn(),
+ workspaceDirFor: vi.fn((id: string) => `/agents/${id}`),
+ resolveSessionForThread: vi.fn(),
+ listTranscriptEvents: vi.fn(),
+ listProjectMcpTokens: vi.fn(),
+ mcpRpcAutoRefresh: vi.fn(),
+ getSecret: vi.fn(() => "loopback-secret"),
+}));
+
+vi.mock("node:fs/promises", () => ({ readFile: mocks.readFile }));
+vi.mock("@/server/agents/provisioning", () => ({ workspaceDirFor: mocks.workspaceDirFor }));
+vi.mock("@/server/sessions/transcript-tail", () => ({
+ resolveSessionForThread: mocks.resolveSessionForThread,
+}));
+vi.mock("@/server/sessions/index", () => ({ listTranscriptEvents: mocks.listTranscriptEvents }));
+vi.mock("@/server/mcp/tokens", () => ({ listProjectMcpTokens: mocks.listProjectMcpTokens }));
+vi.mock("@/server/mcp/rpc", () => ({ mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh }));
+vi.mock("@/server/mcp-server/secret", () => ({
+ getOrCreateMcpServerSecret: mocks.getSecret,
+}));
+
+import { getGoalContextAction } from "./context";
+
+function response(text: string) {
+ return { text: vi.fn(async () => text) };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.NOTFAIR_PORT;
+ mocks.readFile.mockRejectedValue(new Error("missing"));
+ mocks.listProjectMcpTokens.mockReturnValue([]);
+ mocks.resolveSessionForThread.mockReturnValue(null);
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response("{}")));
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("getGoalContextAction", () => {
+ it("splits shared context out of identity and estimates tokens", async () => {
+ const identity = "# Identity\nintro\n## Shared workspace context\nAcme brief\n## Protocol\nDo work";
+ mocks.readFile.mockResolvedValue(identity);
+ const result = await getGoalContextAction({ project_slug: "acme", agent_id: "agent-1", thread: "main" });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.chunks.map((c) => c.key)).toEqual(["identity", "shared-context"]);
+ expect(result.chunks[0]!.content).toContain("## Protocol");
+ expect(result.chunks[0]!.content).not.toContain("Acme brief");
+ expect(result.chunks[1]!.content).toContain("Acme brief");
+ expect(result.total_tokens).toBe(result.chunks.reduce((sum, c) => sum + c.tokens, 0));
+ });
+
+ it("handles shared context as the final identity section", async () => {
+ mocks.readFile.mockResolvedValue("intro\n## Shared workspace context\nlast section");
+ const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });
+ expect(result).toMatchObject({ ok: true });
+ if (!result.ok) return;
+ expect(result.chunks).toHaveLength(2);
+ expect(result.chunks[0]!.content).toBe("intro");
+ });
+
+ it("keeps an identity without the marker as one chunk", async () => {
+ mocks.readFile.mockResolvedValue("plain identity");
+ const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });
+ if (!result.ok) throw new Error(result.error);
+ expect(result.chunks).toMatchObject([{ key: "identity", content: "plain identity" }]);
+ });
+
+ it("collects loopback tools from JSON and SSE responses", async () => {
+ process.env.NOTFAIR_PORT = "4444";
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(response(JSON.stringify({ result: { tools: [{ name: "goal", description: "d" }] } })) as never)
+ .mockResolvedValueOnce(response("event: message\ndata:{\"result\":{\"tools\":[{\"name\":\"browser\"}]}}\n\n") as never);
+ const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });
+ if (!result.ok) throw new Error(result.error);
+ expect(result.chunks.map((c) => c.key)).toEqual(["tools:notfair-goals", "tools:notfair-browser"]);
+ expect(result.chunks[0]).toMatchObject({ format: "json", group: "tools" });
+ expect(fetch).toHaveBeenCalledWith(
+ "http://127.0.0.1:4444/api/mcp/goals",
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.objectContaining({ Authorization: "Bearer loopback-secret" }),
+ }),
+ );
+ });
+
+ it("ignores empty, invalid, and failed internal tool responses", async () => {
+ vi.mocked(fetch)
+ .mockResolvedValueOnce(response("event: message\nnot-data") as never)
+ .mockRejectedValueOnce(new Error("offline"));
+ const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });
+ expect(result).toEqual({ ok: true, chunks: [], total_tokens: 0 });
+ });
+
+ it("includes successful external MCP schemas and skips failures/empty lists", async () => {
+ mocks.listProjectMcpTokens.mockReturnValue([
+ { server_name: "one" },
+ { server_name: "two" },
+ { server_name: "three" },
+ ]);
+ mocks.mcpRpcAutoRefresh
+ .mockResolvedValueOnce({ ok: true, result: { tools: [{ name: "search", inputSchema: { type: "object" } }] } })
+ .mockResolvedValueOnce({ ok: false, kind: "timeout" })
+ .mockResolvedValueOnce({ ok: true, result: { tools: [] } });
+ const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });
+ if (!result.ok) throw new Error(result.error);
+ expect(result.chunks.map((c) => c.key)).toEqual(["tools:one"]);
+ expect(mocks.mcpRpcAutoRefresh).toHaveBeenCalledWith(
+ "p", "one", "tools/list", {}, { timeoutMs: 10_000 },
+ );
+ });
+
+ it("groups transcript events into briefs, user messages, replies, and tools", async () => {
+ mocks.resolveSessionForThread.mockReturnValue({ id: "session-1" });
+ mocks.listTranscriptEvents.mockReturnValue([
+ { kind: "user", payload_json: JSON.stringify({ text: "[TICK] inspect", source: "goal-tick" }) },
+ { kind: "user", payload_json: JSON.stringify({ text: "hello", source: "human" }) },
+ { kind: "user", payload_json: "not-json" },
+ { kind: "final", payload_json: JSON.stringify({ text: "done" }) },
+ { kind: "final", payload_json: JSON.stringify({ text: 42 }) },
+ { kind: "tool", payload_json: JSON.stringify({ name: "fetch" }) },
+ { kind: "meta", payload_json: "{}" },
+ ]);
+ const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "thread-1" });
+ if (!result.ok) throw new Error(result.error);
+ expect(result.chunks.map((c) => c.key)).toEqual(["briefs", "user", "replies", "tool-activity"]);
+ expect(result.chunks.find((c) => c.key === "user")?.content).toBe("hello");
+ expect(result.chunks.find((c) => c.key === "tool-activity")?.format).toBe("json");
+ expect(mocks.listTranscriptEvents).toHaveBeenCalledWith("session-1", { limit: 10_000 });
+ });
+
+ it.each([new Error("database down"), "unexpected"])("returns a safe top-level error for %#", async (failure) => {
+ mocks.listProjectMcpTokens.mockImplementation(() => { throw failure; });
+ await expect(getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" })).resolves.toEqual({
+ ok: false,
+ error: failure instanceof Error ? failure.message : failure,
+ });
+ });
+});
diff --git a/notfair/src/server/actions/goal-groups.test.ts b/notfair/src/server/actions/goal-groups.test.ts
new file mode 100644
index 00000000..7e289cb8
--- /dev/null
+++ b/notfair/src/server/actions/goal-groups.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ create: vi.fn(),
+ remove: vi.fn(),
+ get: vi.fn(),
+ rename: vi.fn(),
+ save: vi.fn(),
+ setMembership: vi.fn(),
+ getGoal: vi.fn(),
+ getProject: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/server/db/goal-groups", () => ({
+ createGoalGroup: mocks.create,
+ deleteGoalGroup: mocks.remove,
+ getGoalGroup: mocks.get,
+ renameGoalGroup: mocks.rename,
+ saveGoalGroup: mocks.save,
+ setGoalGroupMembership: mocks.setMembership,
+}));
+vi.mock("@/server/db/goals", () => ({ getGoal: mocks.getGoal }));
+vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));
+
+import {
+ createGoalGroupAction,
+ deleteGoalGroupAction,
+ moveGoalToGroupAction,
+ renameGoalGroupAction,
+ saveGoalGroupAction,
+} from "./goal-groups";
+
+const group = { id: "group-1" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getProject.mockReturnValue({ slug: "acme" });
+ mocks.get.mockReturnValue(group);
+ mocks.getGoal.mockReturnValue({ id: "goal-1" });
+ mocks.create.mockReturnValue(group);
+ mocks.save.mockReturnValue(group);
+ mocks.rename.mockReturnValue(group);
+ mocks.remove.mockReturnValue(true);
+});
+
+it("creates a trimmed group with default goal ids", async () => {
+ await expect(createGoalGroupAction({ project_slug: "acme", name: " Growth ", description: " focus " })).resolves.toEqual({
+ ok: true,
+ group_id: "group-1",
+ });
+ expect(mocks.create).toHaveBeenCalledWith({
+ project_slug: "acme",
+ name: "Growth",
+ description: "focus",
+ goal_ids: [],
+ });
+});
+
+it("validates project, name, and description lengths", async () => {
+ mocks.getProject.mockReturnValue(null);
+ await expect(createGoalGroupAction({ project_slug: "x", name: "a" })).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue({});
+ await expect(createGoalGroupAction({ project_slug: "x", name: " " })).resolves.toMatchObject({ error: expect.stringContaining("empty") });
+ await expect(createGoalGroupAction({ project_slug: "x", name: "a".repeat(81) })).resolves.toMatchObject({ error: expect.stringContaining("80") });
+ await expect(createGoalGroupAction({ project_slug: "x", name: "a", description: "d".repeat(241) })).resolves.toMatchObject({ error: expect.stringContaining("240") });
+});
+
+it.each([
+ [new Error("UNIQUE constraint failed: groups.name"), "already exists"],
+ [new Error("database down"), "database down"],
+ ["plain failure", "plain failure"],
+])("maps create errors %#", async (failure, message) => {
+ mocks.create.mockImplementation(() => { throw failure; });
+ await expect(createGoalGroupAction({ project_slug: "acme", name: "Growth" })).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining(message),
+ });
+});
+
+it("saves, renames, moves, and deletes groups", async () => {
+ await expect(saveGoalGroupAction({ group_id: "group-1", name: " New ", goal_ids: ["g1"] })).resolves.toMatchObject({ ok: true });
+ expect(mocks.save).toHaveBeenCalledWith({ id: "group-1", name: "New", description: "", goal_ids: ["g1"] });
+ await expect(renameGoalGroupAction("group-1", " Renamed ")).resolves.toMatchObject({ ok: true });
+ await expect(moveGoalToGroupAction("goal-1", "group-1")).resolves.toEqual({ ok: true, group_id: "group-1" });
+ await expect(moveGoalToGroupAction("goal-1", null)).resolves.toEqual({ ok: true, group_id: undefined });
+ await expect(deleteGoalGroupAction("group-1")).resolves.toEqual({ ok: true });
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+});
+
+it("returns missing-row outcomes from mutations", async () => {
+ mocks.get.mockReturnValue(null);
+ await expect(saveGoalGroupAction({ group_id: "x", name: "A", goal_ids: [] })).resolves.toMatchObject({ ok: false });
+ mocks.get.mockReturnValue(group);
+ mocks.save.mockReturnValue(null);
+ await expect(saveGoalGroupAction({ group_id: "x", name: "A", goal_ids: [] })).resolves.toMatchObject({ ok: false });
+ mocks.rename.mockReturnValue(null);
+ await expect(renameGoalGroupAction("x", "A")).resolves.toMatchObject({ ok: false });
+ mocks.getGoal.mockReturnValue(null);
+ await expect(moveGoalToGroupAction("x", null)).resolves.toMatchObject({ ok: false });
+ mocks.remove.mockReturnValue(false);
+ await expect(deleteGoalGroupAction("x")).resolves.toMatchObject({ ok: false });
+});
+
+it("maps save, rename, and membership exceptions", async () => {
+ mocks.save.mockImplementation(() => { throw new Error("save failed"); });
+ await expect(saveGoalGroupAction({ group_id: "x", name: "A", goal_ids: [] })).resolves.toMatchObject({ error: "save failed" });
+ mocks.rename.mockImplementation(() => { throw "rename failed"; });
+ await expect(renameGoalGroupAction("x", "A")).resolves.toMatchObject({ error: "rename failed" });
+ mocks.setMembership.mockImplementation(() => { throw new Error("move failed"); });
+ await expect(moveGoalToGroupAction("goal-1", "x")).resolves.toMatchObject({ error: "move failed" });
+});
diff --git a/notfair/src/server/actions/goals.test.ts b/notfair/src/server/actions/goals.test.ts
new file mode 100644
index 00000000..62797437
--- /dev/null
+++ b/notfair/src/server/actions/goals.test.ts
@@ -0,0 +1,251 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ createGoal: vi.fn(),
+ deleteGoalsForAgent: vi.fn(),
+ endActionObservation: vi.fn(),
+ getGoal: vi.fn(),
+ getGoalAction: vi.fn(),
+ getGoalForAgent: vi.fn(),
+ renameGoal: vi.fn(),
+ reviewGoalAction: vi.fn(),
+ setGoalPinned: vi.fn(),
+ setGoalStatus: vi.fn(),
+ cascadeDeleteAgentArtifacts: vi.fn(),
+ getProject: vi.fn(),
+ provisionGoalAgent: vi.fn(),
+ agentExistsOnDisk: vi.fn(),
+ listProjectAgents: vi.fn(),
+ runGoalIntake: vi.fn(),
+ runGoalTick: vi.fn(),
+ listCheckRows: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/server/db/goals", () => ({
+ createGoal: mocks.createGoal,
+ deleteGoalsForAgent: mocks.deleteGoalsForAgent,
+ endActionObservation: mocks.endActionObservation,
+ getGoal: mocks.getGoal,
+ getGoalAction: mocks.getGoalAction,
+ getGoalForAgent: mocks.getGoalForAgent,
+ renameGoal: mocks.renameGoal,
+ reviewGoalAction: mocks.reviewGoalAction,
+ setGoalPinned: mocks.setGoalPinned,
+ setGoalStatus: mocks.setGoalStatus,
+ USER_ACTION_PREFIX: "[USER ACTION] ",
+}));
+vi.mock("@/server/agents/cascade-delete", () => ({
+ cascadeDeleteAgentArtifacts: mocks.cascadeDeleteAgentArtifacts,
+}));
+vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));
+vi.mock("@/server/goals/provision", () => ({
+ goalAgentIdFor: (slug: string, n: number) => `${slug}--goal-${n}`,
+ goalAgentUrlSlug: (n: number) => `goal-${n}`,
+ provisionGoalAgent: mocks.provisionGoalAgent,
+}));
+vi.mock("@/server/agent-meta", () => ({
+ agentExistsOnDisk: mocks.agentExistsOnDisk,
+ listProjectAgents: mocks.listProjectAgents,
+}));
+vi.mock("@/server/goals/intake", () => ({ runGoalIntake: mocks.runGoalIntake }));
+vi.mock("@/server/goals/tick", () => ({ runGoalTick: mocks.runGoalTick }));
+vi.mock("@/server/goals/checks", () => ({ listCheckRows: mocks.listCheckRows }));
+
+import {
+ createGoalAgentAction,
+ deleteGoalAction,
+ getAgentGoalAction,
+ killGoalAction,
+ loadMoreGoalChecksAction,
+ markUserActionHandledAction,
+ pauseGoalAction,
+ releaseLockAction,
+ renameGoalAction,
+ resumeGoalAction,
+ runTickNowAction,
+ setGoalPinnedAction,
+} from "./goals";
+
+const goal = {
+ id: "goal-db-1",
+ project_slug: "acme",
+ agent_id: "acme--goal-3",
+ status: "active",
+ statement: "Grow",
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getProject.mockReturnValue({ slug: "acme" });
+ mocks.listProjectAgents.mockResolvedValue([]);
+ mocks.agentExistsOnDisk.mockResolvedValue(false);
+ mocks.createGoal.mockReturnValue(goal);
+ mocks.provisionGoalAgent.mockResolvedValue(undefined);
+ mocks.runGoalIntake.mockResolvedValue(undefined);
+ mocks.runGoalTick.mockResolvedValue(undefined);
+ mocks.getGoal.mockReturnValue(goal);
+ mocks.setGoalStatus.mockReturnValue(goal);
+ mocks.renameGoal.mockReturnValue(goal);
+});
+
+describe("createGoalAgentAction", () => {
+ it("validates the project and non-empty statement", async () => {
+ mocks.getProject.mockReturnValue(null);
+ await expect(createGoalAgentAction({ project_slug: "x", statement: "hi" })).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ mocks.getProject.mockReturnValue({ slug: "acme" });
+ await expect(createGoalAgentAction({ project_slug: "acme", statement: " " })).resolves.toEqual({
+ ok: false,
+ error: "Say what you want to achieve.",
+ });
+ });
+
+ it("allocates after the largest sequential agent and skips orphaned dirs", async () => {
+ mocks.listProjectAgents.mockResolvedValue([
+ { slug: "goal-2" },
+ { slug: "goal-7" },
+ { slug: "named-agent" },
+ ]);
+ mocks.agentExistsOnDisk
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false);
+ const result = await createGoalAgentAction({
+ project_slug: "acme",
+ statement: " Grow now ",
+ focus: "SEO",
+ });
+ expect(mocks.createGoal).toHaveBeenCalledWith({
+ project_slug: "acme",
+ agent_id: "acme--goal-9",
+ statement: "Grow now",
+ });
+ expect(mocks.provisionGoalAgent).toHaveBeenCalledWith({ goal, urlSlug: "goal-9" });
+ expect(mocks.runGoalIntake).toHaveBeenCalledWith(goal, { focus: "SEO" });
+ expect(result).toEqual({ ok: true, goal_id: goal.id, agent_slug: "goal-9" });
+ });
+
+ it.each([new Error("duplicate"), "string failure"])("surfaces create failure %#", async (failure) => {
+ mocks.createGoal.mockImplementation(() => { throw failure; });
+ await expect(createGoalAgentAction({ project_slug: "acme", statement: "Grow" })).resolves.toEqual({
+ ok: false,
+ error: failure instanceof Error ? failure.message : failure,
+ });
+ });
+
+ it.each([new Error("disk full"), "bad provision"])("kills a stranded goal on provision failure %#", async (failure) => {
+ mocks.provisionGoalAgent.mockRejectedValue(failure);
+ const result = await createGoalAgentAction({ project_slug: "acme", statement: "Grow" });
+ expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "killed", "provisioning failed");
+ expect(result).toMatchObject({
+ ok: false,
+ error: expect.stringContaining(failure instanceof Error ? failure.message : failure),
+ });
+ });
+});
+
+describe("goal lifecycle actions", () => {
+ it("pauses, kills, renames, and pins existing goals", async () => {
+ await expect(pauseGoalAction(goal.id)).resolves.toEqual({ ok: true });
+ await expect(killGoalAction(goal.id, " done ")).resolves.toEqual({ ok: true });
+ expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "killed", "done");
+ await expect(killGoalAction(goal.id, " ")).resolves.toEqual({ ok: true });
+ expect(mocks.setGoalStatus).toHaveBeenLastCalledWith(goal.id, "killed", "closed by user");
+ await expect(renameGoalAction(goal.id, " Better label ")).resolves.toEqual({ ok: true });
+ expect(mocks.renameGoal).toHaveBeenCalledWith(goal.id, "Better label");
+ await expect(setGoalPinnedAction(goal.id, true)).resolves.toEqual({ ok: true });
+ expect(mocks.setGoalPinned).toHaveBeenCalledWith(goal.id, true);
+ });
+
+ it("returns not-found and validation errors", async () => {
+ mocks.setGoalStatus.mockReturnValue(null);
+ await expect(pauseGoalAction("missing")).resolves.toMatchObject({ ok: false });
+ await expect(killGoalAction("missing")).resolves.toMatchObject({ ok: false });
+ await expect(renameGoalAction(goal.id, " ")).resolves.toMatchObject({ ok: false });
+ mocks.renameGoal.mockReturnValue(null);
+ await expect(renameGoalAction("missing", "Name")).resolves.toMatchObject({ ok: false });
+ mocks.getGoal.mockReturnValue(null);
+ await expect(setGoalPinnedAction("missing", true)).resolves.toMatchObject({ ok: false });
+ });
+
+ it("resumes only paused goals", async () => {
+ mocks.getGoal.mockReturnValue(null);
+ await expect(resumeGoalAction("missing")).resolves.toMatchObject({ ok: false });
+ mocks.getGoal.mockReturnValue({ ...goal, status: "active" });
+ await expect(resumeGoalAction(goal.id)).resolves.toEqual({
+ ok: false,
+ error: "Goal is active, not paused.",
+ });
+ mocks.getGoal.mockReturnValue({ ...goal, status: "paused" });
+ await expect(resumeGoalAction(goal.id)).resolves.toEqual({ ok: true });
+ expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "active", "resumed by user");
+ });
+});
+
+describe("deletion, locks, and escalations", () => {
+ it("deletes agent artifacts before database rows", async () => {
+ mocks.cascadeDeleteAgentArtifacts.mockResolvedValue(undefined);
+ await expect(deleteGoalAction(goal.id)).resolves.toEqual({ ok: true });
+ expect(mocks.cascadeDeleteAgentArtifacts).toHaveBeenCalledWith("acme", "acme--goal-3");
+ expect(mocks.deleteGoalsForAgent).toHaveBeenCalledWith("acme--goal-3");
+ expect(mocks.cascadeDeleteAgentArtifacts.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.deleteGoalsForAgent.mock.invocationCallOrder[0]!,
+ );
+ mocks.getGoal.mockReturnValue(null);
+ await expect(deleteGoalAction("missing")).resolves.toMatchObject({ ok: false });
+ });
+
+ it("releases existing observation locks", async () => {
+ mocks.endActionObservation.mockReturnValue(false);
+ await expect(releaseLockAction("x")).resolves.toMatchObject({ ok: false });
+ mocks.endActionObservation.mockReturnValue({ id: "x" });
+ await expect(releaseLockAction("x")).resolves.toEqual({ ok: true });
+ });
+
+ it("only marks open prefixed decision actions handled", async () => {
+ for (const action of [
+ null,
+ { kind: "mutation", description: "[USER ACTION] fix" },
+ { kind: "decision", description: "ordinary" },
+ ]) {
+ mocks.getGoalAction.mockReturnValue(action);
+ await expect(markUserActionHandledAction("a")).resolves.toMatchObject({ ok: false });
+ }
+ mocks.getGoalAction.mockReturnValue({ kind: "decision", description: "[USER ACTION] fix billing" });
+ mocks.reviewGoalAction.mockReturnValue(null);
+ await expect(markUserActionHandledAction("a")).resolves.toEqual({ ok: false, error: "Already closed." });
+ mocks.reviewGoalAction.mockReturnValue({ id: "a" });
+ await expect(markUserActionHandledAction("a")).resolves.toEqual({ ok: true });
+ });
+});
+
+describe("ticks and read helpers", () => {
+ it("runs manual ticks only for active goals", async () => {
+ mocks.getGoal.mockReturnValue(null);
+ await expect(runTickNowAction("missing")).resolves.toMatchObject({ ok: false });
+ mocks.getGoal.mockReturnValue({ ...goal, status: "paused" });
+ await expect(runTickNowAction(goal.id)).resolves.toEqual({
+ ok: false,
+ error: "Goal is paused — only active goals tick.",
+ });
+ mocks.getGoal.mockReturnValue(goal);
+ await expect(runTickNowAction(goal.id)).resolves.toEqual({ ok: true });
+ expect(mocks.runGoalTick).toHaveBeenCalledWith(goal, "manual");
+ });
+
+ it("returns the agent goal and paginated check rows", async () => {
+ mocks.getGoalForAgent.mockReturnValue(goal);
+ await expect(getAgentGoalAction(goal.agent_id)).resolves.toBe(goal);
+ mocks.listCheckRows.mockReturnValue({ rows: [{ tick_number: 4 }], hasMore: true });
+ await expect(loadMoreGoalChecksAction(goal.id, 5, "action")).resolves.toEqual({
+ rows: [{ tick_number: 4 }],
+ hasMore: true,
+ });
+ expect(mocks.listCheckRows).toHaveBeenCalledWith(goal.id, { beforeTick: 5, filter: "action" });
+ mocks.getGoal.mockReturnValue(null);
+ await expect(loadMoreGoalChecksAction("missing")).resolves.toEqual({ rows: [], hasMore: false });
+ });
+});
diff --git a/notfair/src/server/actions/harness.test.ts b/notfair/src/server/actions/harness.test.ts
new file mode 100644
index 00000000..b12bfbce
--- /dev/null
+++ b/notfair/src/server/actions/harness.test.ts
@@ -0,0 +1,62 @@
+import { EventEmitter } from "node:events";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ homedir: vi.fn(() => "/home/user"),
+ spawn: vi.fn(),
+ refreshUsage: vi.fn(),
+}));
+
+vi.mock("node:os", () => ({ default: { homedir: mocks.homedir } }));
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+vi.mock("@/server/harness-usage", () => ({ refreshHarnessUsage: mocks.refreshUsage }));
+
+import { refreshCodexUsageAction, startCodexLoginAction } from "./harness";
+
+function child() {
+ const proc = new EventEmitter() as EventEmitter & { unref: ReturnType<typeof vi.fn> };
+ proc.unref = vi.fn();
+ return proc;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.refreshUsage.mockResolvedValue({ kind: "codex", auth: "signed-out" });
+});
+
+it.each(["signed-in", "expired"])("does not spawn when auth is %s", async (auth) => {
+ mocks.refreshUsage.mockResolvedValue({ kind: "codex", auth });
+ await expect(startCodexLoginAction()).resolves.toEqual({ ok: true, alreadySignedIn: true });
+ expect(mocks.spawn).not.toHaveBeenCalled();
+});
+
+it.each([{ kind: "claude", auth: "signed-in" }, { kind: "codex", auth: "unknown" }])("starts detached login for %#", async (usage) => {
+ mocks.refreshUsage.mockResolvedValue(usage);
+ const proc = child();
+ mocks.spawn.mockReturnValue(proc);
+ const promise = startCodexLoginAction();
+ await vi.waitFor(() => expect(mocks.spawn).toHaveBeenCalled());
+ proc.emit("spawn");
+ await expect(promise).resolves.toEqual({ ok: true, alreadySignedIn: false });
+ expect(mocks.spawn).toHaveBeenCalledWith("codex", ["login"], expect.objectContaining({ cwd: "/home/user", detached: true, stdio: "ignore" }));
+ expect(proc.unref).toHaveBeenCalled();
+});
+
+it("maps spawn errors and synchronous throws", async () => {
+ let proc = child();
+ mocks.spawn.mockReturnValue(proc);
+ let promise = startCodexLoginAction();
+ await vi.waitFor(() => expect(mocks.spawn).toHaveBeenCalled());
+ proc.emit("error", new Error("denied"));
+ await expect(promise).resolves.toEqual({ ok: false, error: "denied" });
+
+ mocks.spawn.mockImplementation(() => { throw "no binary"; });
+ await expect(startCodexLoginAction()).resolves.toEqual({ ok: false, error: "no binary" });
+});
+
+it("refreshes Codex usage", async () => {
+ const usage = { kind: "codex", auth: "signed-in" };
+ mocks.refreshUsage.mockResolvedValue(usage);
+ await expect(refreshCodexUsageAction()).resolves.toBe(usage);
+ expect(mocks.refreshUsage).toHaveBeenCalledWith("codex-local");
+});
diff --git a/notfair/src/server/actions/shared-context.test.ts b/notfair/src/server/actions/shared-context.test.ts
new file mode 100644
index 00000000..edbbd60b
--- /dev/null
+++ b/notfair/src/server/actions/shared-context.test.ts
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ getProject: vi.fn(),
+ writeBrief: vi.fn(),
+ syncAgents: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));
+vi.mock("@/server/onboarding/project-brief", () => ({
+ writeProjectBrief: mocks.writeBrief,
+ PROJECT_BRIEF_MAX_BYTES: 16,
+}));
+vi.mock("@/server/goals/provision", () => ({ syncProjectAgents: mocks.syncAgents }));
+
+import { saveSharedContextAction } from "./shared-context";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getProject.mockReturnValue({ slug: "acme" });
+ mocks.writeBrief.mockResolvedValue(undefined);
+ mocks.syncAgents.mockResolvedValue(3);
+});
+
+it("validates project, content, and UTF-8 byte length", async () => {
+ mocks.getProject.mockReturnValue(null);
+ await expect(saveSharedContextAction({ project_slug: "x", content: "brief" })).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue({});
+ await expect(saveSharedContextAction({ project_slug: "x", content: " " })).resolves.toMatchObject({ error: expect.stringContaining("empty") });
+ await expect(saveSharedContextAction({ project_slug: "x", content: "🌍🌍🌍🌍🌍" })).resolves.toMatchObject({ error: expect.stringContaining("Too long") });
+});
+
+it("writes trimmed content, syncs agents, and revalidates", async () => {
+ await expect(saveSharedContextAction({ project_slug: "acme", content: " company brief " })).resolves.toEqual({
+ ok: true,
+ synced_agents: 3,
+ });
+ expect(mocks.writeBrief).toHaveBeenCalledWith("acme", "company brief");
+ expect(mocks.syncAgents).toHaveBeenCalledWith("acme");
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+});
+
+it.each([new Error("disk full"), "sync failed"])("maps write failure %#", async (failure) => {
+ mocks.writeBrief.mockRejectedValue(failure);
+ await expect(saveSharedContextAction({ project_slug: "acme", content: "brief" })).resolves.toEqual({
+ ok: false,
+ error: failure instanceof Error ? failure.message : failure,
+ });
+});
diff --git a/notfair/src/server/actions/suggestions.test.ts b/notfair/src/server/actions/suggestions.test.ts
new file mode 100644
index 00000000..1cbf0e40
--- /dev/null
+++ b/notfair/src/server/actions/suggestions.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ getSuggestion: vi.fn(),
+ markAccepted: vi.fn(),
+ markDismissed: vi.fn(),
+ analyzableSources: vi.fn(),
+ generate: vi.fn(),
+ createGoal: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/server/db/suggestions", () => ({
+ getSuggestion: mocks.getSuggestion,
+ markSuggestionAccepted: mocks.markAccepted,
+ markSuggestionDismissed: mocks.markDismissed,
+}));
+vi.mock("@/server/suggestions/engine", () => ({
+ analyzableSources: mocks.analyzableSources,
+ generateSuggestionsForSource: mocks.generate,
+}));
+vi.mock("@/server/actions/goals", () => ({ createGoalAgentAction: mocks.createGoal }));
+
+import { acceptSuggestionAction, dismissSuggestionAction, refreshSuggestionsAction } from "./suggestions";
+
+const suggestion = { id: "s1", status: "open", project_slug: "acme", statement: "Grow" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getSuggestion.mockReturnValue(suggestion);
+ mocks.createGoal.mockResolvedValue({ ok: true, goal_id: "g1" });
+ mocks.analyzableSources.mockReturnValue(["google", "meta"]);
+});
+
+it("accepts an open suggestion after creating its goal", async () => {
+ await expect(acceptSuggestionAction("s1")).resolves.toEqual({ ok: true, goal_id: "g1" });
+ expect(mocks.createGoal).toHaveBeenCalledWith({ project_slug: "acme", statement: "Grow" });
+ expect(mocks.markAccepted).toHaveBeenCalledWith("s1", "g1");
+});
+
+it("rejects missing/handled suggestions and leaves failed goal creation open", async () => {
+ mocks.getSuggestion.mockReturnValue(null);
+ await expect(acceptSuggestionAction("x")).resolves.toMatchObject({ ok: false });
+ mocks.getSuggestion.mockReturnValue({ ...suggestion, status: "dismissed" });
+ await expect(acceptSuggestionAction("s1")).resolves.toMatchObject({ ok: false });
+ mocks.getSuggestion.mockReturnValue(suggestion);
+ mocks.createGoal.mockResolvedValue({ ok: false, error: "no" });
+ await expect(acceptSuggestionAction("s1")).resolves.toMatchObject({ ok: false });
+ expect(mocks.markAccepted).not.toHaveBeenCalled();
+});
+
+it("dismisses only open suggestions", async () => {
+ await expect(dismissSuggestionAction("s1")).resolves.toEqual({ ok: true });
+ expect(mocks.markDismissed).toHaveBeenCalledWith("s1");
+ mocks.getSuggestion.mockReturnValue({ ...suggestion, status: "accepted" });
+ await expect(dismissSuggestionAction("s1")).resolves.toEqual({ ok: false });
+ mocks.getSuggestion.mockReturnValue(null);
+ await expect(dismissSuggestionAction("x")).resolves.toEqual({ ok: false });
+});
+
+it("fires suggestion generation for each analyzable source", async () => {
+ await expect(refreshSuggestionsAction("acme")).resolves.toEqual({ ok: true, sources: 2 });
+ expect(mocks.generate).toHaveBeenCalledWith("acme", "google");
+ expect(mocks.generate).toHaveBeenCalledWith("acme", "meta");
+});
diff --git a/notfair/src/server/agents/files.test.ts b/notfair/src/server/agents/files.test.ts
new file mode 100644
index 00000000..a33b9428
--- /dev/null
+++ b/notfair/src/server/agents/files.test.ts
@@ -0,0 +1,34 @@
+import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeAll, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ workspace: "" }));
+vi.mock("./provisioning", () => ({ workspaceDirFor: () => mocks.workspace }));
+
+import { getAgentFile, listAgentFiles } from "./files";
+
+beforeAll(async () => {
+ mocks.workspace = await mkdtemp(join(tmpdir(), "notfair-files-"));
+ await writeFile(join(mocks.workspace, "README.md"), "hello", "utf8");
+ await mkdir(join(mocks.workspace, "folder"));
+});
+
+it("returns an empty list for a missing workspace", async () => {
+ const saved = mocks.workspace;
+ mocks.workspace = join(saved, "missing");
+ await expect(listAgentFiles("a")).resolves.toEqual({ files: [], workspace: mocks.workspace });
+ mocks.workspace = saved;
+});
+
+it("lists only regular files with metadata", async () => {
+ const result = await listAgentFiles("a");
+ expect(result.workspace).toBe(mocks.workspace);
+ expect(result.files).toEqual([expect.objectContaining({ name: "README.md", size: 5, missing: false })]);
+});
+
+it("reads a file and rejects path traversal", async () => {
+ await expect(getAgentFile("a", "README.md")).resolves.toMatchObject({ file: { name: "README.md", content: "hello", size: 5 } });
+ await expect(getAgentFile("a", "../secret")).rejects.toThrow(/Invalid file name/);
+ await expect(getAgentFile("a", "nested/file")).rejects.toThrow(/Invalid file name/);
+});
diff --git a/notfair/src/server/browser/actions.test.ts b/notfair/src/server/browser/actions.test.ts
new file mode 100644
index 00000000..f6d6b5dc
--- /dev/null
+++ b/notfair/src/server/browser/actions.test.ts
@@ -0,0 +1,152 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ back,
+ click,
+ navigate,
+ press,
+ scroll,
+ snapshot,
+ type as typeText,
+} from "./actions";
+
+function locator() {
+ return {
+ click: vi.fn(async () => {}),
+ dblclick: vi.fn(async () => {}),
+ fill: vi.fn(async () => {}),
+ press: vi.fn(async () => {}),
+ };
+}
+
+function page() {
+ const loc = locator();
+ return {
+ goto: vi.fn(async () => {}),
+ url: vi.fn(() => "https://example.com/final"),
+ title: vi.fn(async () => "Example"),
+ locator: vi.fn(() => loc),
+ keyboard: { press: vi.fn(async () => {}) },
+ evaluate: vi.fn(async (fn: (arg: never) => unknown, arg: never) => fn(arg)),
+ goBack: vi.fn(async () => null),
+ loc,
+ };
+}
+
+beforeEach(() => {
+ document.body.innerHTML = "";
+ Object.defineProperty(HTMLElement.prototype, "getBoundingClientRect", {
+ configurable: true,
+ value: () => ({ width: 100, height: 20 }),
+ });
+ Object.defineProperty(HTMLElement.prototype, "innerText", {
+ configurable: true,
+ get() { return this.textContent ?? ""; },
+ });
+ vi.stubGlobal("CSS", { escape: (value: string) => value });
+ vi.spyOn(window, "scrollBy").mockImplementation(() => {});
+ vi.spyOn(window, "getComputedStyle").mockReturnValue({ visibility: "visible", display: "block" } as CSSStyleDeclaration);
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+it("navigates with defaults and tolerates a title failure", async () => {
+ const p = page();
+ await expect(navigate(p as never, { url: "https://example.com" })).resolves.toEqual({
+ url: "https://example.com/final",
+ title: "Example",
+ });
+ expect(p.goto).toHaveBeenCalledWith("https://example.com", { waitUntil: "load", timeout: 30_000 });
+ p.title.mockRejectedValueOnce(new Error("gone"));
+ await expect(navigate(p as never, { url: "x", waitUntil: "commit", timeoutMs: 5 })).resolves.toMatchObject({ title: "" });
+});
+
+it("snapshots visible interactive elements and replaces stale refs", async () => {
+ document.title = "Snapshot";
+ document.body.innerHTML = `
+ <button data-notfair-ref="old" aria-label="Save" disabled>Ignored text</button>
+ <span id="labelled">Account name</span><input id="account" aria-labelledby="labelled" value="123">
+ <label for="email">Email address</label><input id="email" value="[email protected]">
+ <input placeholder="Fallback placeholder" value="x">
+ <a href="/next">Next page</a>
+ <textarea>notes</textarea>
+ <button id="hidden">Hidden</button>
+ `;
+ vi.spyOn(window, "getComputedStyle").mockImplementation((el) => ({
+ visibility: el.id === "hidden" ? "hidden" : "visible",
+ display: "block",
+ }) as CSSStyleDeclaration);
+ const p = page();
+ const result = await snapshot(p as never);
+ expect(result.title).toBe("Snapshot");
+ expect(result.elements).toEqual(expect.arrayContaining([
+ expect.objectContaining({ ref: "e1", role: "button", name: "Save", disabled: true }),
+ expect.objectContaining({ name: "Account name", value: "123" }),
+ expect.objectContaining({ name: "Email address", value: "[email protected]" }),
+ expect.objectContaining({ name: "Fallback placeholder" }),
+ expect.objectContaining({ role: "a", href: expect.stringContaining("/next") }),
+ ]));
+ expect(document.querySelector("[data-notfair-ref=old]")).toBeNull();
+ expect(document.querySelector("#hidden")?.hasAttribute("data-notfair-ref")).toBe(false);
+});
+
+it("filters zero-size and display-none elements", async () => {
+ document.body.innerHTML = `<button id="zero">Zero</button><button id="none">None</button>`;
+ vi.spyOn(window, "getComputedStyle").mockImplementation((el) => ({
+ visibility: "visible",
+ display: el.id === "none" ? "none" : "block",
+ }) as CSSStyleDeclaration);
+ vi.spyOn(document.querySelector("#zero")!, "getBoundingClientRect").mockReturnValue({ width: 0, height: 10 } as DOMRect);
+ const result = await snapshot(page() as never);
+ expect(result.elements).toEqual([]);
+});
+
+it("clicks and double-clicks refs with options", async () => {
+ let p = page();
+ await click(p as never, { ref: "e2", button: "right", modifiers: ["Meta"], timeoutMs: 50 });
+ expect(p.locator).toHaveBeenCalledWith('[data-notfair-ref="e2"]');
+ expect(p.loc.click).toHaveBeenCalledWith({ button: "right", modifiers: ["Meta"], timeout: 50 });
+ p = page();
+ await click(p as never, { ref: "e1", doubleClick: true });
+ expect(p.loc.dblclick).toHaveBeenCalledWith({ button: undefined, modifiers: undefined, timeout: 10_000 });
+ await expect(click(p as never, { ref: "bad" })).rejects.toThrow(/Invalid ref/);
+});
+
+it("clears, types, and optionally submits", async () => {
+ let p = page();
+ await typeText(p as never, { ref: "e3", text: "hello", submit: true });
+ expect(p.loc.fill).toHaveBeenNthCalledWith(1, "", { timeout: 10_000 });
+ expect(p.loc.fill).toHaveBeenNthCalledWith(2, "hello", { timeout: 10_000 });
+ expect(p.loc.press).toHaveBeenCalledWith("Enter", { timeout: 10_000 });
+ p = page();
+ await typeText(p as never, { ref: "e1", text: "append", clearFirst: false, timeoutMs: 1 });
+ expect(p.loc.fill).toHaveBeenCalledTimes(1);
+});
+
+it("presses on a ref or at page level", async () => {
+ const p = page();
+ await press(p as never, { key: "Tab", ref: "e1", timeoutMs: 9 });
+ expect(p.loc.press).toHaveBeenCalledWith("Tab", { timeout: 9 });
+ await press(p as never, { key: "Escape" });
+ expect(p.keyboard.press).toHaveBeenCalledWith("Escape");
+});
+
+it.each([
+ ["left", 25, { x: -25, y: 0 }],
+ ["right", 25, { x: 25, y: 0 }],
+ ["up", 25, { x: 0, y: -25 }],
+ ["down", undefined, { x: 0, y: 600 }],
+])("scrolls %s", async (direction, amount, expected) => {
+ const p = page();
+ await scroll(p as never, { direction: direction as never, amount });
+ expect(p.evaluate).toHaveBeenCalledWith(expect.any(Function), expected);
+});
+
+it("goes back and ignores navigation failures", async () => {
+ const p = page();
+ await back(p as never);
+ expect(p.goBack).toHaveBeenCalledWith({ waitUntil: "load" });
+ p.goBack.mockRejectedValueOnce(new Error("no history"));
+ await expect(back(p as never)).resolves.toBeUndefined();
+});
diff --git a/notfair/src/server/browser/chrome.test.ts b/notfair/src/server/browser/chrome.test.ts
new file mode 100644
index 00000000..7fe49c0c
--- /dev/null
+++ b/notfair/src/server/browser/chrome.test.ts
@@ -0,0 +1,170 @@
+import { EventEmitter } from "node:events";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ existsSync: vi.fn(),
+ rmSync: vi.fn(),
+ mkdirSync: vi.fn(),
+ spawn: vi.fn(),
+}));
+
+vi.mock("node:fs", () => ({
+ default: {
+ existsSync: mocks.existsSync,
+ rmSync: mocks.rmSync,
+ mkdirSync: mocks.mkdirSync,
+ },
+}));
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+
+import {
+ buildChromeLaunchArgs,
+ clearChromeSingletonArtifacts,
+ findChromeExecutable,
+ launchChrome,
+ stopChrome,
+ waitForCdpReady,
+} from "./chrome";
+
+function child() {
+ const events = new EventEmitter();
+ const stderr = new EventEmitter();
+ const proc = events as EventEmitter & {
+ stderr: EventEmitter;
+ exitCode: number | null;
+ killed: boolean;
+ kill: ReturnType<typeof vi.fn>;
+ };
+ proc.stderr = stderr;
+ proc.exitCode = null;
+ proc.killed = false;
+ proc.kill = vi.fn(() => true);
+ return proc;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.existsSync.mockReturnValue(false);
+ mocks.rmSync.mockReturnValue(undefined);
+ vi.stubGlobal("fetch", vi.fn());
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("Chrome discovery and args", () => {
+ it("prefers a valid explicit path", () => {
+ const exists = vi.fn((p: string) => p === "/custom/chrome");
+ expect(findChromeExecutable({ NOTFAIR_CHROME_PATH: " /custom/chrome " }, "darwin", exists)).toBe("/custom/chrome");
+ expect(exists).toHaveBeenCalledTimes(1);
+ });
+
+ it("falls back to platform candidates and returns null on unsupported platforms", () => {
+ const exists = vi.fn((p: string) => p.includes("Chromium.app"));
+ expect(findChromeExecutable({}, "darwin", exists)).toContain("Chromium.app");
+ expect(findChromeExecutable({}, "win32", exists)).toBeNull();
+ expect(findChromeExecutable({ NOTFAIR_CHROME_PATH: "/missing" }, "linux", () => false)).toBeNull();
+ });
+
+ it("builds headed/headless platform-specific args", () => {
+ const base = buildChromeLaunchArgs({ executablePath: "chrome", userDataDir: "/profile", cdpPort: 9222, platform: "darwin" });
+ expect(base).toContain("--remote-debugging-port=9222");
+ expect(base).not.toContain("--headless=new");
+ const linux = buildChromeLaunchArgs({
+ executablePath: "chrome",
+ userDataDir: "/profile",
+ cdpPort: 9222,
+ platform: "linux",
+ headless: true,
+ extraArgs: ["--proxy-server=x"],
+ });
+ expect(linux).toEqual(expect.arrayContaining(["--headless=new", "--disable-gpu", "--disable-dev-shm-usage", "--proxy-server=x"]));
+ });
+
+ it("removes every singleton artifact and tolerates failures", () => {
+ mocks.rmSync.mockImplementationOnce(() => { throw new Error("locked"); });
+ expect(() => clearChromeSingletonArtifacts("/profile")).not.toThrow();
+ expect(mocks.rmSync).toHaveBeenCalledTimes(3);
+ expect(mocks.rmSync).toHaveBeenCalledWith("/profile/SingletonSocket", { force: true });
+ });
+});
+
+describe("CDP readiness and lifecycle", () => {
+ it("returns as soon as the endpoint is ready", async () => {
+ vi.mocked(fetch).mockResolvedValue({ ok: true, status: 200 } as Response);
+ await expect(waitForCdpReady("http://cdp", 100)).resolves.toBeUndefined();
+ expect(fetch).toHaveBeenCalledWith("http://cdp/json/version", expect.objectContaining({ signal: expect.any(AbortSignal) }));
+ });
+
+ it("includes the last HTTP or network error when timing out", async () => {
+ await expect(waitForCdpReady("http://cdp", 0)).rejects.toThrow(/did not become ready/);
+ vi.mocked(fetch).mockResolvedValue({ ok: false, status: 503 } as Response);
+ await expect(waitForCdpReady("http://cdp", 2, 0)).rejects.toThrow(/status 503/);
+ vi.mocked(fetch).mockRejectedValue(new Error("refused"));
+ await expect(waitForCdpReady("http://cdp", 2, 0)).rejects.toThrow(/refused/);
+ });
+
+ it("launches Chrome and returns its CDP metadata", async () => {
+ const proc = child();
+ mocks.spawn.mockReturnValue(proc);
+ vi.mocked(fetch).mockResolvedValue({ ok: true } as Response);
+ const launched = await launchChrome({
+ executablePath: "/chrome",
+ userDataDir: "/profile",
+ cdpPort: 9333,
+ platform: "darwin",
+ });
+ expect(mocks.mkdirSync).toHaveBeenCalledWith("/profile", { recursive: true });
+ expect(mocks.spawn).toHaveBeenCalledWith("/chrome", expect.arrayContaining(["--remote-debugging-port=9333"]), {
+ stdio: ["ignore", "pipe", "pipe"],
+ detached: false,
+ });
+ expect(launched).toMatchObject({ cdpPort: 9333, cdpHttpUrl: "http://127.0.0.1:9333", userDataDir: "/profile" });
+ });
+
+ it("kills Chrome and surfaces an early exit with stderr tail", async () => {
+ const proc = child();
+ mocks.spawn.mockReturnValue(proc);
+ vi.mocked(fetch).mockImplementation(() => new Promise(() => {}));
+ const promise = launchChrome({ executablePath: "/chrome", userDataDir: "/profile", cdpPort: 9444 });
+ proc.stderr.emit("data", Buffer.from("startup failed"));
+ proc.emit("exit", 2, "SIGABRT");
+ await expect(promise).rejects.toThrow(/code=2.*startup failed/);
+ expect(proc.kill).toHaveBeenCalledWith("SIGKILL");
+ });
+
+ it("stops an already-exited process with cleanup only", async () => {
+ const proc = child();
+ proc.exitCode = 0;
+ await stopChrome({ process: proc as never, cdpPort: 1, cdpHttpUrl: "x", userDataDir: "/profile" });
+ expect(proc.kill).not.toHaveBeenCalled();
+ expect(mocks.rmSync).toHaveBeenCalledTimes(3);
+ });
+
+ it("uses SIGTERM for a live process that exits promptly", async () => {
+ const proc = child();
+ proc.kill.mockImplementation((signal: string) => {
+ if (signal === "SIGTERM") queueMicrotask(() => { proc.exitCode = 0; proc.emit("exit", 0, null); });
+ return true;
+ });
+ await stopChrome({ process: proc as never, cdpPort: 1, cdpHttpUrl: "x", userDataDir: "/profile" }, 50);
+ expect(proc.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(proc.kill).not.toHaveBeenCalledWith("SIGKILL");
+ });
+
+ it("falls back to SIGKILL after the graceful timeout", async () => {
+ vi.useFakeTimers();
+ const proc = child();
+ proc.kill.mockImplementation((signal: string) => {
+ if (signal === "SIGKILL") queueMicrotask(() => { proc.exitCode = 1; proc.emit("exit", 1, signal); });
+ return true;
+ });
+ const promise = stopChrome({ process: proc as never, cdpPort: 1, cdpHttpUrl: "x", userDataDir: "/profile" }, 10);
+ await vi.advanceTimersByTimeAsync(10);
+ await promise;
+ expect(proc.kill).toHaveBeenNthCalledWith(1, "SIGTERM");
+ expect(proc.kill).toHaveBeenNthCalledWith(2, "SIGKILL");
+ });
+});
diff --git a/notfair/src/server/browser/paths.test.ts b/notfair/src/server/browser/paths.test.ts
new file mode 100644
index 00000000..216c6433
--- /dev/null
+++ b/notfair/src/server/browser/paths.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from "vitest";
+
+// Point NOTFAIR_DATA_DIR at a tmpdir before importing the module under test.
+vi.hoisted(() => {
+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
+ const { tmpdir } = require("node:os") as typeof import("node:os");
+ const { join } = require("node:path") as typeof import("node:path");
+ process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-paths-"));
+});
+
+import {
+ CDP_PORT_RANGE_START,
+ CDP_PORT_RANGE_END,
+ allocateCdpPort,
+ isValidProjectSlug,
+ notfairDataDir,
+ resolveBrowserProfileDir,
+ resolveUserDataDir,
+} from "./paths";
+
+describe("notfairDataDir", () => {
+ it("uses NOTFAIR_DATA_DIR when set", () => {
+ expect(notfairDataDir()).toBe(process.env.NOTFAIR_DATA_DIR);
+ });
+
+ it("falls back to ~/.notfair when unset", async () => {
+ const saved = process.env.NOTFAIR_DATA_DIR;
+ delete process.env.NOTFAIR_DATA_DIR;
+ try {
+ const { homedir } = await import("node:os");
+ const { join } = await import("node:path");
+ expect(notfairDataDir()).toBe(join(homedir(), ".notfair"));
+ } finally {
+ process.env.NOTFAIR_DATA_DIR = saved;
+ }
+ });
+});
+
+describe("isValidProjectSlug", () => {
+ it("accepts lowercase alphanumeric + hyphen slugs", () => {
+ expect(isValidProjectSlug("proj")).toBe(true);
+ expect(isValidProjectSlug("my-project-1")).toBe(true);
+ expect(isValidProjectSlug("a")).toBe(true);
+ });
+
+ it("rejects empty, too-long, uppercase, leading-hyphen and invalid chars", () => {
+ expect(isValidProjectSlug("")).toBe(false);
+ expect(isValidProjectSlug("a".repeat(65))).toBe(false);
+ expect(isValidProjectSlug("Proj")).toBe(false);
+ expect(isValidProjectSlug("-proj")).toBe(false);
+ expect(isValidProjectSlug("proj_x")).toBe(false);
+ expect(isValidProjectSlug("proj space")).toBe(false);
+ });
+
+ it("accepts a 64-char slug (boundary)", () => {
+ expect(isValidProjectSlug("a".repeat(64))).toBe(true);
+ });
+});
+
+describe("resolveBrowserProfileDir / resolveUserDataDir", () => {
+ it("builds paths under the data dir", () => {
+ const dir = resolveBrowserProfileDir("proj");
+ expect(dir).toContain("projects");
+ expect(dir).toContain("proj");
+ expect(dir.endsWith("browser")).toBe(true);
+ expect(resolveUserDataDir("proj").endsWith("user-data")).toBe(true);
+ });
+
+ it("throws on an invalid slug", () => {
+ expect(() => resolveBrowserProfileDir("BAD SLUG")).toThrow(/Invalid project slug/);
+ expect(() => resolveUserDataDir("_bad")).toThrow(/Invalid project slug/);
+ });
+});
+
+describe("allocateCdpPort", () => {
+ it("is deterministic and within range", () => {
+ const p1 = allocateCdpPort("proj");
+ const p2 = allocateCdpPort("proj");
+ expect(p1).toBe(p2);
+ expect(p1).toBeGreaterThanOrEqual(CDP_PORT_RANGE_START);
+ expect(p1).toBeLessThanOrEqual(CDP_PORT_RANGE_END);
+ });
+
+ it("throws on an invalid slug", () => {
+ expect(() => allocateCdpPort("Bad")).toThrow(/Invalid project slug/);
+ });
+
+ it("maps different slugs across the range", () => {
+ const ports = new Set(
+ ["alpha", "beta", "gamma", "delta", "omega"].map(allocateCdpPort),
+ );
+ for (const p of ports) {
+ expect(p).toBeGreaterThanOrEqual(CDP_PORT_RANGE_START);
+ expect(p).toBeLessThanOrEqual(CDP_PORT_RANGE_END);
+ }
+ });
+});
diff --git a/notfair/src/server/browser/session.test.ts b/notfair/src/server/browser/session.test.ts
new file mode 100644
index 00000000..29135dc4
--- /dev/null
+++ b/notfair/src/server/browser/session.test.ts
@@ -0,0 +1,269 @@
+import { EventEmitter } from "node:events";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.hoisted(() => {
+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
+ const { tmpdir } = require("node:os") as typeof import("node:os");
+ const { join } = require("node:path") as typeof import("node:path");
+ process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-session-"));
+});
+
+const mocks = vi.hoisted(() => ({
+ findChromeExecutable: vi.fn(),
+ launchChrome: vi.fn(),
+ stopChrome: vi.fn(),
+}));
+
+vi.mock("./chrome", () => ({
+ findChromeExecutable: mocks.findChromeExecutable,
+ launchChrome: mocks.launchChrome,
+ stopChrome: mocks.stopChrome,
+}));
+
+import {
+ _sessionsByProject,
+ _stopIdleChecker,
+ checkIdleSessions,
+ ensureIdleChecker,
+ getOrLaunchBrowser,
+ getSessionStatus,
+ registerShutdownHooks,
+ stopAllBrowsers,
+ stopBrowser,
+ type BrowserSession,
+} from "./session";
+
+function launched(over: Record<string, unknown> = {}) {
+ const process = new EventEmitter() as EventEmitter & {
+ exitCode: number | null;
+ killed: boolean;
+ };
+ process.exitCode = null;
+ process.killed = false;
+ return {
+ process,
+ cdpPort: 19_223,
+ cdpHttpUrl: "http://127.0.0.1:19223",
+ userDataDir: "/tmp/profile",
+ ...over,
+ };
+}
+
+function browser(contexts: unknown[] = [{}]) {
+ return {
+ contexts: vi.fn(() => contexts),
+ close: vi.fn(async () => {}),
+ };
+}
+
+function cachedSession(slug: string, over: Partial<BrowserSession> = {}): BrowserSession {
+ const launchedChrome = launched();
+ return {
+ projectSlug: slug,
+ cdpPort: 19_223,
+ cdpHttpUrl: launchedChrome.cdpHttpUrl,
+ userDataDir: launchedChrome.userDataDir,
+ launched: launchedChrome as never,
+ browser: browser() as never,
+ context: {} as never,
+ launchedAt: 1_000,
+ lastActivityAt: 2_000,
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ _sessionsByProject.clear();
+ _stopIdleChecker();
+ delete process.env.NOTFAIR_BROWSER_HEADLESS;
+ delete process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS;
+ mocks.findChromeExecutable.mockReturnValue("/Applications/Chrome");
+ mocks.stopChrome.mockResolvedValue(undefined);
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ await stopAllBrowsers();
+ _sessionsByProject.clear();
+ _stopIdleChecker();
+});
+
+describe("getOrLaunchBrowser", () => {
+ it("launches, attaches to the default context, and caches the session", async () => {
+ const chrome = launched();
+ const attached = browser([{ name: "default" }]);
+ const launch = vi.fn(async () => chrome as never);
+ const connect = vi.fn(async () => attached as never);
+
+ const first = await getOrLaunchBrowser("acme", {
+ headless: true,
+ executablePath: "/custom/chrome",
+ extraArgs: ["--foo"],
+ launch,
+ connectOverCDP: connect,
+ });
+ expect(launch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ executablePath: "/custom/chrome",
+ headless: true,
+ extraArgs: ["--foo"],
+ }),
+ );
+ expect(connect).toHaveBeenCalledWith(chrome.cdpHttpUrl);
+ expect(first.context).toEqual({ name: "default" });
+
+ vi.setSystemTime(9_000);
+ const second = await getOrLaunchBrowser("acme", { launch, connectOverCDP: connect });
+ expect(second).toBe(first);
+ expect(second.lastActivityAt).toBe(9_000);
+ expect(launch).toHaveBeenCalledTimes(1);
+ });
+
+ it("deduplicates concurrent launches", async () => {
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const chrome = launched();
+ const launch = vi.fn(async () => {
+ await gate;
+ return chrome as never;
+ });
+ const connect = vi.fn(async () => browser() as never);
+ const a = getOrLaunchBrowser("parallel", { launch, connectOverCDP: connect });
+ const b = getOrLaunchBrowser("parallel", { launch, connectOverCDP: connect });
+ expect(launch).toHaveBeenCalledTimes(1);
+ release();
+ const [one, two] = await Promise.all([a, b]);
+ expect(one).toBe(two);
+ });
+
+ it("drops a dead cached session and relaunches", async () => {
+ const dead = cachedSession("dead");
+ Object.defineProperty(dead.launched.process, "exitCode", { value: 1 });
+ _sessionsByProject.set("dead", dead);
+ const fresh = launched();
+ const result = await getOrLaunchBrowser("dead", {
+ launch: vi.fn(async () => fresh as never),
+ connectOverCDP: vi.fn(async () => browser() as never),
+ });
+ expect(result).not.toBe(dead);
+ });
+
+ it("fails clearly when Chrome cannot be found", async () => {
+ mocks.findChromeExecutable.mockReturnValue(null);
+ await expect(getOrLaunchBrowser("acme")).rejects.toThrow(/Could not find Chrome/);
+ });
+
+ it("stops Chrome if CDP attachment fails", async () => {
+ const chrome = launched();
+ await expect(
+ getOrLaunchBrowser("acme", {
+ launch: vi.fn(async () => chrome as never),
+ connectOverCDP: vi.fn(async () => { throw new Error("refused"); }),
+ }),
+ ).rejects.toThrow(/Failed to attach.*refused/);
+ expect(mocks.stopChrome).toHaveBeenCalledWith(chrome);
+ });
+
+ it("closes both handles when CDP has no default context", async () => {
+ const chrome = launched();
+ const attached = browser([]);
+ await expect(
+ getOrLaunchBrowser("acme", {
+ launch: vi.fn(async () => chrome as never),
+ connectOverCDP: vi.fn(async () => attached as never),
+ }),
+ ).rejects.toThrow(/no default context/);
+ expect(attached.close).toHaveBeenCalled();
+ expect(mocks.stopChrome).toHaveBeenCalledWith(chrome);
+ });
+
+ it.each([
+ ["1", true],
+ ["TRUE", true],
+ ["0", false],
+ ["false", false],
+ ])("honors NOTFAIR_BROWSER_HEADLESS=%s", async (value, expected) => {
+ process.env.NOTFAIR_BROWSER_HEADLESS = value;
+ const launch = vi.fn(async () => launched() as never);
+ await getOrLaunchBrowser(`env-${value.toLowerCase()}`, {
+ launch,
+ connectOverCDP: vi.fn(async () => browser() as never),
+ });
+ expect(launch).toHaveBeenCalledWith(expect.objectContaining({ headless: expected }));
+ });
+
+ it("evicts a session when Chrome exits", async () => {
+ const chrome = launched();
+ await getOrLaunchBrowser("evict", {
+ launch: vi.fn(async () => chrome as never),
+ connectOverCDP: vi.fn(async () => browser() as never),
+ });
+ chrome.process.emit("exit", 1);
+ expect(_sessionsByProject.has("evict")).toBe(false);
+ });
+});
+
+describe("shutdown and status", () => {
+ it("stopBrowser is a no-op for missing sessions and tolerates close failures", async () => {
+ await expect(stopBrowser("missing")).resolves.toBeUndefined();
+ const session = cachedSession("acme");
+ vi.mocked(session.browser.close).mockRejectedValue(new Error("dead"));
+ mocks.stopChrome.mockRejectedValueOnce(new Error("already stopped"));
+ _sessionsByProject.set("acme", session);
+ await expect(stopBrowser("acme")).resolves.toBeUndefined();
+ expect(_sessionsByProject.has("acme")).toBe(false);
+ });
+
+ it("stops all registered projects", async () => {
+ _sessionsByProject.set("one", cachedSession("one"));
+ _sessionsByProject.set("two", cachedSession("two"));
+ await stopAllBrowsers();
+ expect(_sessionsByProject.size).toBe(0);
+ expect(mocks.stopChrome).toHaveBeenCalledTimes(2);
+ });
+
+ it("reports stopped and running session details", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(5_000);
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1234";
+ expect(getSessionStatus("none")).toMatchObject({
+ running: false,
+ idleTimeoutMs: 1234,
+ });
+ _sessionsByProject.set("acme", cachedSession("acme"));
+ expect(getSessionStatus("acme")).toMatchObject({
+ running: true,
+ launchedAt: 1_000,
+ uptimeMs: 4_000,
+ idleMs: 3_000,
+ idleTimeoutMs: 1234,
+ });
+ });
+
+ it("uses the default idle timeout for empty, invalid, and nonpositive values", () => {
+ for (const value of [undefined, "nope", "0", "-4"]) {
+ if (value === undefined) delete process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS;
+ else process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = value;
+ expect(getSessionStatus("acme").idleTimeoutMs).toBe(300_000);
+ }
+ });
+
+ it("stops only sessions at or beyond the idle threshold", async () => {
+ process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";
+ _sessionsByProject.set("idle", cachedSession("idle", { lastActivityAt: 1_000 }));
+ _sessionsByProject.set("active", cachedSession("active", { lastActivityAt: 1_001 }));
+ await expect(checkIdleSessions(2_000)).resolves.toEqual(["idle"]);
+ expect(_sessionsByProject.has("idle")).toBe(false);
+ expect(_sessionsByProject.has("active")).toBe(true);
+ });
+
+ it("installs maintenance hooks and starts only one idle timer", () => {
+ registerShutdownHooks();
+ registerShutdownHooks();
+ vi.useFakeTimers();
+ ensureIdleChecker();
+ ensureIdleChecker();
+ expect(vi.getTimerCount()).toBe(1);
+ });
+});
diff --git a/notfair/src/server/browser/tabs.test.ts b/notfair/src/server/browser/tabs.test.ts
new file mode 100644
index 00000000..8da06e58
--- /dev/null
+++ b/notfair/src/server/browser/tabs.test.ts
@@ -0,0 +1,152 @@
+import { EventEmitter } from "node:events";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ getOrLaunchBrowser: vi.fn() }));
+vi.mock("./session", () => ({ getOrLaunchBrowser: mocks.getOrLaunchBrowser }));
+
+import {
+ _resetTabRegistries,
+ assertValidLabel,
+ closeTab,
+ getTab,
+ listTabs,
+ openTab,
+} from "./tabs";
+
+function fakePage(url = "about:blank", title = "Blank") {
+ const events = new EventEmitter();
+ let closed = false;
+ return {
+ url: vi.fn(() => url),
+ title: vi.fn(async () => title),
+ goto: vi.fn(async () => {}),
+ isClosed: vi.fn(() => closed),
+ close: vi.fn(async () => { closed = true; events.emit("close"); }),
+ once: events.once.bind(events),
+ emitClose: () => events.emit("close"),
+ setClosed: (value: boolean) => { closed = value; },
+ };
+}
+
+function fakeSession(initialPages: ReturnType<typeof fakePage>[] = []) {
+ const events = new EventEmitter();
+ const pages = [...initialPages];
+ return {
+ context: {
+ pages: vi.fn(() => pages),
+ newPage: vi.fn(async () => {
+ const p = fakePage();
+ pages.push(p);
+ return p;
+ }),
+ on: events.on.bind(events),
+ },
+ pages,
+ closeContext: () => events.emit("close"),
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ _resetTabRegistries();
+ mocks.getOrLaunchBrowser.mockResolvedValue(fakeSession() as never);
+});
+
+it("validates labels at both boundaries", () => {
+ for (const valid of ["a", "Goal_1", "tab-2", "a".repeat(64)]) {
+ expect(() => assertValidLabel(valid)).not.toThrow();
+ }
+ for (const invalid of ["", "-bad", "has space", "a".repeat(65)]) {
+ expect(() => assertValidLabel(invalid)).toThrow(/Invalid tab label/);
+ }
+});
+
+it("adopts initial pages and opens auto-numbered tabs", async () => {
+ const initial = fakePage("https://initial", "Initial");
+ const session = fakeSession([initial]);
+ mocks.getOrLaunchBrowser.mockResolvedValue(session as never);
+ expect(await getTab("acme", "t1")).toBe(initial);
+ const opened = await openTab("acme");
+ expect(opened).toMatchObject({ id: "t2", label: "t2", url: "about:blank" });
+ expect(session.context.newPage).toHaveBeenCalled();
+});
+
+it("opens and reuses a labeled tab with navigation options", async () => {
+ const session = fakeSession();
+ mocks.getOrLaunchBrowser.mockResolvedValue(session as never);
+ const first = await openTab("acme", {
+ label: "reports",
+ url: "https://example.com",
+ waitUntil: "networkidle",
+ timeoutMs: 55,
+ });
+ const created = session.pages[0]!;
+ expect(first.id).toBe("reports");
+ expect(created.goto).toHaveBeenCalledWith("https://example.com", { waitUntil: "networkidle", timeout: 55 });
+ await openTab("acme", { label: "reports", url: "https://next" });
+ expect(session.context.newPage).toHaveBeenCalledTimes(1);
+ expect(created.goto).toHaveBeenLastCalledWith("https://next", { waitUntil: "load", timeout: 30_000 });
+ await expect(openTab("acme", { label: " bad" })).rejects.toThrow(/Invalid tab label/);
+});
+
+it("reconciles external pages and returns fresh titles", async () => {
+ const known = fakePage("https://known", "Known");
+ const session = fakeSession([known]);
+ mocks.getOrLaunchBrowser.mockResolvedValue(session as never);
+ await listTabs("acme");
+ const external = fakePage("https://external", "External");
+ session.pages.push(external);
+ const handles = await listTabs("acme");
+ expect(handles).toEqual([
+ { id: "t1", label: "t1", url: "https://known", title: "Known" },
+ { id: "t2", label: "t2", url: "https://external", title: "External" },
+ ]);
+});
+
+it("drops closed pages and falls back when URL/title access throws", async () => {
+ const closed = fakePage();
+ closed.setClosed(true);
+ const broken = fakePage();
+ broken.url.mockImplementation(() => { throw new Error("detached"); });
+ broken.title.mockRejectedValue(new Error("detached"));
+ const session = fakeSession([closed, broken]);
+ mocks.getOrLaunchBrowser.mockResolvedValue(session as never);
+ await expect(listTabs("acme")).resolves.toEqual([
+ { id: "t2", label: "t2", url: "", title: "" },
+ ]);
+});
+
+it("returns false for missing tabs and closes live tabs", async () => {
+ const session = fakeSession();
+ mocks.getOrLaunchBrowser.mockResolvedValue(session as never);
+ await expect(closeTab("acme", "missing")).resolves.toBe(false);
+ await openTab("acme", { label: "one" });
+ await expect(closeTab("acme", "one")).resolves.toBe(true);
+ expect(session.pages[0]!.close).toHaveBeenCalled();
+ await expect(getTab("acme", "one")).resolves.toBeNull();
+});
+
+it("tolerates close failures and cleans up event-driven closures", async () => {
+ const p = fakePage();
+ p.close.mockRejectedValue(new Error("already gone"));
+ const session = fakeSession([p]);
+ mocks.getOrLaunchBrowser.mockResolvedValue(session as never);
+ await expect(closeTab("acme", "t1")).resolves.toBe(true);
+
+ _resetTabRegistries();
+ p.close.mockResolvedValue(undefined);
+ p.setClosed(false);
+ await getTab("acme", "t1");
+ p.emitClose();
+ await expect(getTab("acme", "t1")).resolves.toBeNull();
+});
+
+it("rebuilds the registry when the browser session changes and clears on context close", async () => {
+ const first = fakeSession([fakePage("first")]);
+ const second = fakeSession([fakePage("second")]);
+ mocks.getOrLaunchBrowser.mockResolvedValueOnce(first as never).mockResolvedValue(second as never);
+ expect(await getTab("acme", "t1")).toBe(first.pages[0]);
+ expect(await getTab("acme", "t1")).toBe(second.pages[0]);
+ second.closeContext();
+ expect(await getTab("acme", "t1")).toBeNull();
+});
diff --git a/notfair/src/server/db/suggestions.test.ts b/notfair/src/server/db/suggestions.test.ts
new file mode 100644
index 00000000..94a22b4b
--- /dev/null
+++ b/notfair/src/server/db/suggestions.test.ts
@@ -0,0 +1,144 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Real better-sqlite3 against a tmpdir DB. MUST be hoisted before imports.
+vi.hoisted(() => {
+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
+ const { tmpdir } = require("node:os") as typeof import("node:os");
+ const { join } = require("node:path") as typeof import("node:path");
+ process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-db-suggestions-"));
+});
+
+import { getDb } from "@/server/db/db";
+import {
+ getSuggestion,
+ hasSuggestionsForSource,
+ listOpenSuggestions,
+ markSuggestionAccepted,
+ markSuggestionDismissed,
+ replaceOpenSuggestions,
+ type SuggestionDraft,
+} from "./suggestions";
+
+const SLUG = "sugproj";
+
+function seedProject(slug: string): void {
+ getDb()
+ .prepare(
+ "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",
+ )
+ .run(slug, slug, slug, new Date().toISOString());
+}
+
+function draft(kind: string, over: Partial<SuggestionDraft> = {}): SuggestionDraft {
+ return {
+ kind,
+ title: `title-${kind}`,
+ statement: `statement-${kind}`,
+ mode: "achieve",
+ rationale: `rationale-${kind}`,
+ ...over,
+ };
+}
+
+beforeAll(() => {
+ seedProject(SLUG);
+});
+
+beforeEach(() => {
+ getDb().prepare("DELETE FROM goal_suggestions WHERE project_slug = ?").run(SLUG);
+});
+
+describe("replaceOpenSuggestions", () => {
+ it("inserts a fresh batch of open rows", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);
+ const rows = listOpenSuggestions(SLUG);
+ expect(rows.map((r) => r.kind).sort()).toEqual(["k1", "k2"]);
+ expect(rows[0]!.status).toBe("open");
+ });
+
+ it("refreshes an open row in place on conflict (same kind)", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1", { title: "first" })]);
+ const before = listOpenSuggestions(SLUG)[0]!;
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1", { title: "second" })]);
+ const after = getSuggestion(before.id)!;
+ expect(after.id).toBe(before.id); // same row, updated in place
+ expect(after.title).toBe("second");
+ });
+
+ it("deletes open rows whose kind is absent from the new batch", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);
+ expect(listOpenSuggestions(SLUG).map((r) => r.kind)).toEqual(["k1"]);
+ });
+
+ it("deletes all open rows for the source when the batch is empty", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);
+ replaceOpenSuggestions(SLUG, "src-a", []);
+ expect(listOpenSuggestions(SLUG)).toEqual([]);
+ });
+
+ it("never touches accepted or dismissed rows", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);
+ const rows = listOpenSuggestions(SLUG);
+ const accepted = rows.find((r) => r.kind === "k1")!;
+ const dismissed = rows.find((r) => r.kind === "k2")!;
+ markSuggestionAccepted(accepted.id, "goal-x");
+ markSuggestionDismissed(dismissed.id);
+
+ // A regen with neither kind must not delete the terminal rows, and the
+ // ON CONFLICT WHERE status='open' guard must not resurrect them.
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);
+
+ expect(getSuggestion(accepted.id)!.status).toBe("accepted");
+ expect(getSuggestion(accepted.id)!.accepted_goal_id).toBe("goal-x");
+ expect(getSuggestion(dismissed.id)!.status).toBe("dismissed");
+ // The fresh batch only produced open rows for kinds that were free.
+ expect(listOpenSuggestions(SLUG)).toEqual([]);
+ });
+
+ it("scopes deletes to (project, source)", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);
+ replaceOpenSuggestions(SLUG, "src-b", [draft("k1")]);
+ replaceOpenSuggestions(SLUG, "src-a", []); // clears only src-a
+ expect(listOpenSuggestions(SLUG).map((r) => r.source_key)).toEqual(["src-b"]);
+ });
+});
+
+describe("listOpenSuggestions", () => {
+ it("orders by created_at then kind and only returns open rows", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("b"), draft("a")]);
+ const open = listOpenSuggestions(SLUG);
+ // Same created_at → tiebreak on kind ASC.
+ expect(open.map((r) => r.kind)).toEqual(["a", "b"]);
+ });
+});
+
+describe("getSuggestion", () => {
+ it("returns null for an unknown id", () => {
+ expect(getSuggestion("nope")).toBeNull();
+ });
+});
+
+describe("hasSuggestionsForSource", () => {
+ it("is true once any row exists (even after acceptance) and false otherwise", () => {
+ expect(hasSuggestionsForSource(SLUG, "src-a")).toBe(false);
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);
+ expect(hasSuggestionsForSource(SLUG, "src-a")).toBe(true);
+ const row = listOpenSuggestions(SLUG)[0]!;
+ markSuggestionDismissed(row.id);
+ expect(hasSuggestionsForSource(SLUG, "src-a")).toBe(true);
+ expect(hasSuggestionsForSource(SLUG, "other-src")).toBe(false);
+ });
+});
+
+describe("markSuggestionAccepted / markSuggestionDismissed", () => {
+ it("stamps status and accepted_goal_id", () => {
+ replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);
+ const row = listOpenSuggestions(SLUG)[0]!;
+ markSuggestionAccepted(row.id, "goal-42");
+ const after = getSuggestion(row.id)!;
+ expect(after.status).toBe("accepted");
+ expect(after.accepted_goal_id).toBe("goal-42");
+ expect(after.updated_at >= after.created_at).toBe(true);
+ });
+});
diff --git a/notfair/src/server/live-events/emitter.test.ts b/notfair/src/server/live-events/emitter.test.ts
new file mode 100644
index 00000000..88812347
--- /dev/null
+++ b/notfair/src/server/live-events/emitter.test.ts
@@ -0,0 +1,18 @@
+import { expect, it, vi } from "vitest";
+
+import { publishSessionEvent, subscribeSessionEvents } from "./emitter";
+
+it("publishes only to the matching session and unsubscribes", () => {
+ const one = vi.fn();
+ const two = vi.fn();
+ const offOne = subscribeSessionEvents("one", one);
+ const offTwo = subscribeSessionEvents("two", two);
+ const event = { id: "e", session_id: "one", seq: 1, kind: "user", payload_json: "{}", created_at: "now" } as const;
+ publishSessionEvent("one", event);
+ expect(one).toHaveBeenCalledWith(event);
+ expect(two).not.toHaveBeenCalled();
+ offOne();
+ publishSessionEvent("one", event);
+ expect(one).toHaveBeenCalledTimes(1);
+ offTwo();
+});
diff --git a/notfair/src/server/mcp-server/jsonrpc.test.ts b/notfair/src/server/mcp-server/jsonrpc.test.ts
new file mode 100644
index 00000000..3684277f
--- /dev/null
+++ b/notfair/src/server/mcp-server/jsonrpc.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { handleJsonRpc, type McpServerInfo } from "./jsonrpc";
+import type { ToolDefinition } from "./tools";
+import { z } from "zod";
+
+function makeTool(over: Partial<ToolDefinition> = {}): ToolDefinition {
+ return {
+ name: "echo",
+ description: "echoes",
+ inputSchema: z.object({ text: z.string() }),
+ handler: vi.fn(async () => ({
+ ok: true as const,
+ content: [{ type: "text" as const, text: "hi" }],
+ })),
+ ...over,
+ };
+}
+
+function server(tools: ToolDefinition[]): McpServerInfo {
+ return { name: "notfair-goals", version: "1.2.3", tools };
+}
+
+describe("handleJsonRpc", () => {
+ it("returns null for notifications (no id)", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", method: "notifications/initialized" },
+ server([]),
+ );
+ expect(res).toBeNull();
+ });
+
+ it("returns null when id is explicitly null", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: null, method: "initialize" },
+ server([]),
+ );
+ expect(res).toBeNull();
+ });
+
+ it("answers initialize with protocol + serverInfo", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 1, method: "initialize" },
+ server([]),
+ );
+ expect(res).toMatchObject({
+ id: 1,
+ result: {
+ protocolVersion: "2025-06-18",
+ serverInfo: { name: "notfair-goals", version: "1.2.3" },
+ capabilities: { tools: {} },
+ },
+ });
+ });
+
+ it("answers tools/list with described tools", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: "a", method: "tools/list" },
+ server([makeTool()]),
+ );
+ expect(res).toMatchObject({ id: "a" });
+ const result = (res as { result: { tools: { name: string }[] } }).result;
+ expect(result.tools[0]!.name).toBe("echo");
+ });
+
+ it("answers ping with an empty result", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 2, method: "ping" },
+ server([]),
+ );
+ expect(res).toMatchObject({ id: 2, result: {} });
+ });
+
+ it("returns -32601 for an unknown method", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 3, method: "does/not/exist" },
+ server([]),
+ );
+ expect(res).toMatchObject({ id: 3, error: { code: -32601 } });
+ });
+
+ it("executes tools/call and wraps ok results", async () => {
+ const tool = makeTool();
+ const res = await handleJsonRpc(
+ {
+ jsonrpc: "2.0",
+ id: 4,
+ method: "tools/call",
+ params: { name: "echo", arguments: { text: "x" } },
+ },
+ server([tool]),
+ );
+ expect(tool.handler).toHaveBeenCalledWith({ text: "x" }, {});
+ expect(res).toMatchObject({
+ id: 4,
+ result: { isError: false, content: [{ type: "text", text: "hi" }] },
+ });
+ });
+
+ it("defaults arguments to {} when omitted", async () => {
+ const tool = makeTool();
+ await handleJsonRpc(
+ { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "echo" } },
+ server([tool]),
+ );
+ expect(tool.handler).toHaveBeenCalledWith({}, {});
+ });
+
+ it("surfaces a failed tool result via isError:true", async () => {
+ const tool = makeTool({
+ handler: vi.fn(async () => ({ ok: false as const, error: "boom" })),
+ });
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 6, method: "tools/call", params: { name: "echo" } },
+ server([tool]),
+ );
+ expect(res).toMatchObject({
+ id: 6,
+ result: { isError: true, content: [{ type: "text", text: "boom" }] },
+ });
+ });
+
+ it("returns -32602 when name is not a string", async () => {
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: 123 } },
+ server([makeTool()]),
+ );
+ expect(res).toMatchObject({ id: 7, error: { code: -32602 } });
+ });
+
+ it("returns -32601 for an unknown tool name", async () => {
+ const res = await handleJsonRpc(
+ {
+ jsonrpc: "2.0",
+ id: 8,
+ method: "tools/call",
+ params: { name: "nope" },
+ },
+ server([makeTool()]),
+ );
+ expect(res).toMatchObject({
+ id: 8,
+ error: { code: -32601, message: expect.stringContaining("Unknown tool") },
+ });
+ });
+
+ it("maps a throwing handler to -32603 internal error", async () => {
+ const tool = makeTool({
+ handler: vi.fn(async () => {
+ throw new Error("kaboom");
+ }),
+ });
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "echo" } },
+ server([tool]),
+ );
+ expect(res).toMatchObject({
+ id: 9,
+ error: { code: -32603, message: expect.stringContaining("kaboom") },
+ });
+ });
+
+ it("stringifies non-Error throws in the internal-error message", async () => {
+ const tool = makeTool({
+ handler: vi.fn(async () => {
+ throw "stringy";
+ }),
+ });
+ const res = await handleJsonRpc(
+ { jsonrpc: "2.0", id: 10, method: "tools/call", params: { name: "echo" } },
+ server([tool]),
+ );
+ expect(res).toMatchObject({
+ id: 10,
+ error: { code: -32603, message: expect.stringContaining("stringy") },
+ });
+ });
+});
diff --git a/notfair/src/server/mcp-server/registration.test.ts b/notfair/src/server/mcp-server/registration.test.ts
new file mode 100644
index 00000000..cbe68afa
--- /dev/null
+++ b/notfair/src/server/mcp-server/registration.test.ts
@@ -0,0 +1,190 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ requireAdapter: vi.fn(),
+ getProject: vi.fn(),
+ listProjectAgents: vi.fn(),
+ mcpSpecByKey: vi.fn(),
+ findMcpToken: vi.fn(),
+ getOrCreateMcpServerSecret: vi.fn(() => "shared-secret"),
+ registerMcp: vi.fn(async () => {}),
+}));
+
+vi.mock("@/server/adapters/registry", () => ({
+ requireAdapter: mocks.requireAdapter,
+}));
+vi.mock("@/server/db/projects", () => ({
+ getProject: mocks.getProject,
+}));
+vi.mock("@/server/agent-meta", () => ({
+ listProjectAgents: mocks.listProjectAgents,
+}));
+vi.mock("@/server/mcp-catalog", () => ({
+ mcpSpecByKey: mocks.mcpSpecByKey,
+}));
+vi.mock("@/server/mcp/tokens", () => ({
+ findMcpToken: mocks.findMcpToken,
+}));
+vi.mock("./secret", () => ({
+ getOrCreateMcpServerSecret: mocks.getOrCreateMcpServerSecret,
+}));
+
+import {
+ BROWSER_MCP_KEY,
+ GOALS_MCP_KEY,
+ registerBrowserMcpForAgent,
+ registerCatalogMcpForAgent,
+ registerCatalogMcpForProject,
+ registerGoalsMcpForAgent,
+} from "./registration";
+
+const PROJECT = { slug: "proj", harness_adapter: "claude-code-local" };
+const SPEC = { key: "notfair-googleads", resource_url: "https://srv/mcp" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ delete process.env.NOTFAIR_MCP_URL;
+ delete process.env.NOTFAIR_BROWSER_MCP_URL;
+ delete process.env.NOTFAIR_PORT;
+ mocks.getProject.mockReturnValue(PROJECT);
+ mocks.requireAdapter.mockReturnValue({ registerMcp: mocks.registerMcp });
+ mocks.mcpSpecByKey.mockReturnValue(SPEC);
+ mocks.findMcpToken.mockReturnValue({ access_token_enc: "enc-token" });
+ mocks.getOrCreateMcpServerSecret.mockReturnValue("shared-secret");
+});
+
+describe("registerGoalsMcpForAgent", () => {
+ it("registers with default goals URL + bearer secret", async () => {
+ const r = await registerGoalsMcpForAgent("proj", "agent-1");
+ expect(r).toEqual({
+ ok: true,
+ key: GOALS_MCP_KEY,
+ url: "http://127.0.0.1:3326/api/mcp/goals",
+ });
+ expect(mocks.registerMcp).toHaveBeenCalledWith({
+ serverName: GOALS_MCP_KEY,
+ agentId: "agent-1",
+ projectSlug: "proj",
+ transport: {
+ type: "http",
+ url: "http://127.0.0.1:3326/api/mcp/goals",
+ headers: { Authorization: "Bearer shared-secret" },
+ },
+ });
+ });
+
+ it("honors NOTFAIR_PORT and NOTFAIR_MCP_URL overrides", async () => {
+ process.env.NOTFAIR_PORT = "9999";
+ let r = await registerGoalsMcpForAgent("proj", "a");
+ expect(r.url).toBe("http://127.0.0.1:9999/api/mcp/goals");
+
+ process.env.NOTFAIR_MCP_URL = "https://custom/mcp";
+ r = await registerGoalsMcpForAgent("proj", "a");
+ expect(r.url).toBe("https://custom/mcp");
+ });
+
+ it("fails when the project is unknown", async () => {
+ mocks.getProject.mockReturnValue(null);
+ const r = await registerGoalsMcpForAgent("proj", "a");
+ expect(r).toMatchObject({ ok: false, error: expect.stringContaining("Unknown project") });
+ expect(mocks.registerMcp).not.toHaveBeenCalled();
+ });
+
+ it("fails when the adapter throws", async () => {
+ mocks.requireAdapter.mockImplementation(() => {
+ throw new Error("no adapter");
+ });
+ const r = await registerGoalsMcpForAgent("proj", "a");
+ expect(r).toMatchObject({ ok: false, error: "no adapter" });
+ });
+
+ it("stringifies non-Error throws from the adapter", async () => {
+ mocks.requireAdapter.mockImplementation(() => {
+ throw "weird";
+ });
+ const r = await registerGoalsMcpForAgent("proj", "a");
+ expect(r).toMatchObject({ ok: false, error: "weird" });
+ });
+});
+
+describe("registerBrowserMcpForAgent", () => {
+ it("registers with the default browser URL", async () => {
+ const r = await registerBrowserMcpForAgent("proj", "a");
+ expect(r).toEqual({
+ ok: true,
+ key: BROWSER_MCP_KEY,
+ url: "http://127.0.0.1:3326/api/mcp/browser",
+ });
+ });
+
+ it("honors NOTFAIR_BROWSER_MCP_URL", async () => {
+ process.env.NOTFAIR_BROWSER_MCP_URL = "https://custom/browser";
+ const r = await registerBrowserMcpForAgent("proj", "a");
+ expect(r.url).toBe("https://custom/browser");
+ });
+});
+
+describe("registerCatalogMcpForAgent", () => {
+ it("registers using the catalog resource URL + token bearer", async () => {
+ const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "agent-1");
+ expect(r).toEqual({ ok: true, key: "notfair-googleads", url: SPEC.resource_url });
+ expect(mocks.registerMcp).toHaveBeenCalledWith(
+ expect.objectContaining({
+ serverName: "notfair-googleads",
+ transport: expect.objectContaining({
+ url: SPEC.resource_url,
+ headers: { Authorization: "Bearer enc-token" },
+ }),
+ }),
+ );
+ });
+
+ it("fails on unknown catalog key", async () => {
+ mocks.mcpSpecByKey.mockReturnValue(undefined);
+ const r = await registerCatalogMcpForAgent("proj", "nope", "a");
+ expect(r).toMatchObject({ ok: false, url: "", error: expect.stringContaining("Unknown catalog key") });
+ });
+
+ it("fails on unknown project (with spec url echoed)", async () => {
+ mocks.getProject.mockReturnValue(null);
+ const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");
+ expect(r).toMatchObject({ ok: false, url: SPEC.resource_url, error: expect.stringContaining("Unknown project") });
+ });
+
+ it("fails when no token is stored", async () => {
+ mocks.findMcpToken.mockReturnValue(null);
+ const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");
+ expect(r).toMatchObject({ ok: false, error: expect.stringContaining("No token stored") });
+ });
+
+ it("fails when the adapter throws", async () => {
+ mocks.registerMcp.mockRejectedValueOnce(new Error("register failed"));
+ const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");
+ expect(r).toMatchObject({ ok: false, error: "register failed" });
+ });
+
+ it("stringifies non-Error throws", async () => {
+ mocks.registerMcp.mockRejectedValueOnce("boom");
+ const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");
+ expect(r).toMatchObject({ ok: false, error: "boom" });
+ });
+});
+
+describe("registerCatalogMcpForProject", () => {
+ it("registers for each agent and collects results", async () => {
+ mocks.listProjectAgents.mockResolvedValue([
+ { agent_id: "a1" },
+ { agent_id: "a2" },
+ ]);
+ const results = await registerCatalogMcpForProject("proj", "notfair-googleads");
+ expect(results).toHaveLength(2);
+ expect(results.every((r) => r.ok)).toBe(true);
+ expect(mocks.registerMcp).toHaveBeenCalledTimes(2);
+ });
+
+ it("returns an empty array when the project has no agents", async () => {
+ mocks.listProjectAgents.mockResolvedValue([]);
+ const results = await registerCatalogMcpForProject("proj", "notfair-googleads");
+ expect(results).toEqual([]);
+ });
+});
diff --git a/notfair/src/server/mcp/probe-cache.test.ts b/notfair/src/server/mcp/probe-cache.test.ts
new file mode 100644
index 00000000..e1e30e89
--- /dev/null
+++ b/notfair/src/server/mcp/probe-cache.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ _clearProbeCacheForTests,
+ getCachedProbe,
+ invalidateProbe,
+ setCachedProbe,
+} from "./probe-cache";
+import type { McpRuntimeStatus } from "./state";
+
+const connected: McpRuntimeStatus = {
+ state: "connected",
+ url: "https://x",
+ tools_count: null,
+ last_checked_at: "now",
+};
+const unreachable: McpRuntimeStatus = {
+ state: "unreachable",
+ url: "https://x",
+ error: "down",
+ last_checked_at: "now",
+};
+const staleToken: McpRuntimeStatus = {
+ state: "stale_token",
+ url: "https://x",
+ http_status: 401,
+ last_checked_at: "now",
+};
+
+beforeEach(() => _clearProbeCacheForTests());
+afterEach(() => {
+ vi.useRealTimers();
+ _clearProbeCacheForTests();
+});
+
+describe("probe-cache", () => {
+ it("misses on an empty cache", () => {
+ expect(getCachedProbe("p", "k")).toBeNull();
+ });
+
+ it("caches connected results and reads them back", () => {
+ setCachedProbe("p", "k", connected);
+ expect(getCachedProbe("p", "k")).toEqual(connected);
+ });
+
+ it("caches unreachable results", () => {
+ setCachedProbe("p", "k", unreachable);
+ expect(getCachedProbe("p", "k")).toEqual(unreachable);
+ });
+
+ it("does not cache stale_token (ttl 0) and clears a prior entry", () => {
+ setCachedProbe("p", "k", connected);
+ setCachedProbe("p", "k", staleToken);
+ expect(getCachedProbe("p", "k")).toBeNull();
+ });
+
+ it("does not cache not_configured", () => {
+ setCachedProbe("p", "k", { state: "not_configured" });
+ expect(getCachedProbe("p", "k")).toBeNull();
+ });
+
+ it("keys entries by project + catalog", () => {
+ setCachedProbe("p1", "k", connected);
+ expect(getCachedProbe("p2", "k")).toBeNull();
+ expect(getCachedProbe("p1", "k2")).toBeNull();
+ });
+
+ it("expires connected entries after 60s", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ setCachedProbe("p", "k", connected);
+ vi.setSystemTime(59_999);
+ expect(getCachedProbe("p", "k")).toEqual(connected);
+ vi.setSystemTime(60_001);
+ expect(getCachedProbe("p", "k")).toBeNull();
+ });
+
+ it("expires unreachable entries after 10s", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(0);
+ setCachedProbe("p", "k", unreachable);
+ vi.setSystemTime(10_001);
+ expect(getCachedProbe("p", "k")).toBeNull();
+ });
+
+ it("invalidateProbe drops the entry", () => {
+ setCachedProbe("p", "k", connected);
+ invalidateProbe("p", "k");
+ expect(getCachedProbe("p", "k")).toBeNull();
+ });
+});
diff --git a/notfair/src/server/mcp/state.test.ts b/notfair/src/server/mcp/state.test.ts
new file mode 100644
index 00000000..e55f727a
--- /dev/null
+++ b/notfair/src/server/mcp/state.test.ts
@@ -0,0 +1,173 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ findMcpToken: vi.fn(),
+ upsertMcpToken: vi.fn(),
+ deleteMcpToken: vi.fn(),
+ mcpSpecByKey: vi.fn(),
+ mcpRpcAutoRefresh: vi.fn(),
+ getCachedProbe: vi.fn(),
+ setCachedProbe: vi.fn(),
+ invalidateProbe: vi.fn(),
+}));
+
+vi.mock("./tokens", () => ({
+ findMcpToken: mocks.findMcpToken,
+ upsertMcpToken: mocks.upsertMcpToken,
+ deleteMcpToken: mocks.deleteMcpToken,
+}));
+vi.mock("@/server/mcp-catalog", () => ({
+ mcpSpecByKey: mocks.mcpSpecByKey,
+}));
+vi.mock("./rpc", () => ({
+ mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh,
+}));
+vi.mock("./probe-cache", () => ({
+ getCachedProbe: mocks.getCachedProbe,
+ setCachedProbe: mocks.setCachedProbe,
+ invalidateProbe: mocks.invalidateProbe,
+}));
+
+import { disconnectMcp, getMcpStatus, setMcpBearer } from "./state";
+
+const SPEC = { resource_url: "https://srv/mcp", key: "notfair-googleads" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.mcpSpecByKey.mockReturnValue(SPEC);
+ mocks.findMcpToken.mockReturnValue({ id: "tok-1" });
+ mocks.getCachedProbe.mockReturnValue(null);
+});
+
+describe("getMcpStatus short-circuits", () => {
+ it("returns not_configured when no spec", async () => {
+ mocks.mcpSpecByKey.mockReturnValue(undefined);
+ expect(await getMcpStatus("p", "k")).toEqual({ state: "not_configured" });
+ });
+
+ it("returns not_configured when no token", async () => {
+ mocks.findMcpToken.mockReturnValue(null);
+ expect(await getMcpStatus("p", "k")).toEqual({ state: "not_configured" });
+ });
+
+ it("returns the cached probe without hitting rpc", async () => {
+ const cached = { state: "connected" as const, url: "u", tools_count: null, last_checked_at: "t" };
+ mocks.getCachedProbe.mockReturnValue(cached);
+ expect(await getMcpStatus("p", "k")).toBe(cached);
+ expect(mocks.mcpRpcAutoRefresh).not.toHaveBeenCalled();
+ });
+});
+
+describe("getMcpStatus probe outcomes", () => {
+ it("connected on rpc ok, and caches the result", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: true, result: {} });
+ const r = await getMcpStatus("p", "k");
+ expect(r).toMatchObject({ state: "connected", url: SPEC.resource_url, tools_count: null });
+ expect(mocks.setCachedProbe).toHaveBeenCalledWith("p", "k", r);
+ });
+
+ it("stale_token on 401", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 401 });
+ expect(await getMcpStatus("p", "k")).toMatchObject({ state: "stale_token", http_status: 401 });
+ });
+
+ it("stale_token on 403", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 403 });
+ expect(await getMcpStatus("p", "k")).toMatchObject({ state: "stale_token", http_status: 403 });
+ });
+
+ it("unreachable on other http_error with body", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 500, body: "oops" });
+ expect(await getMcpStatus("p", "k")).toMatchObject({
+ state: "unreachable",
+ error: "HTTP 500: oops",
+ });
+ });
+
+ it("unreachable on http_error without body", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 502 });
+ expect(await getMcpStatus("p", "k")).toMatchObject({ state: "unreachable", error: "HTTP 502" });
+ });
+
+ it("unreachable on timeout", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "timeout" });
+ expect(await getMcpStatus("p", "k")).toMatchObject({ state: "unreachable", error: "timed out" });
+ });
+
+ it("unreachable on aborted", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "aborted" });
+ expect(await getMcpStatus("p", "k")).toMatchObject({ state: "unreachable", error: "aborted" });
+ });
+
+ it("unreachable on rpc_error", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "rpc_error", code: -1, message: "bad" });
+ expect(await getMcpStatus("p", "k")).toMatchObject({
+ state: "unreachable",
+ error: "rpc error -1: bad",
+ });
+ });
+
+ it("unreachable on malformed_response", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "malformed_response", message: "junk" });
+ expect(await getMcpStatus("p", "k")).toMatchObject({
+ state: "unreachable",
+ error: "malformed response: junk",
+ });
+ });
+
+ it("unreachable fallthrough on network_error", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "network_error", message: "econnrefused" });
+ expect(await getMcpStatus("p", "k")).toMatchObject({
+ state: "unreachable",
+ error: "econnrefused",
+ });
+ });
+});
+
+describe("disconnectMcp", () => {
+ it("deletes the token and invalidates the probe when a token exists", async () => {
+ mocks.findMcpToken.mockReturnValue({ id: "tok-9" });
+ await disconnectMcp("p", "k");
+ expect(mocks.deleteMcpToken).toHaveBeenCalledWith("tok-9");
+ expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "k");
+ });
+
+ it("only invalidates when there is no token", async () => {
+ mocks.findMcpToken.mockReturnValue(null);
+ await disconnectMcp("p", "k");
+ expect(mocks.deleteMcpToken).not.toHaveBeenCalled();
+ expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "k");
+ });
+});
+
+describe("setMcpBearer", () => {
+ it("upserts with all fields and invalidates the probe", async () => {
+ await setMcpBearer("p", "k", "secret", {
+ scope: "s",
+ expires_at: "later",
+ refresh_token: "r",
+ token_endpoint: "te",
+ client_id: "ci",
+ client_secret: "cs",
+ });
+ expect(mocks.upsertMcpToken).toHaveBeenCalledWith({
+ project_slug: "p",
+ server_name: "k",
+ access_token: "secret",
+ scope: "s",
+ expires_at: "later",
+ refresh_token: "r",
+ token_endpoint: "te",
+ client_id: "ci",
+ client_secret: "cs",
+ });
+ expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "k");
+ });
+
+ it("works with default (empty) options", async () => {
+ await setMcpBearer("p", "k", "secret");
+ expect(mocks.upsertMcpToken).toHaveBeenCalledWith(
+ expect.objectContaining({ access_token: "secret", scope: undefined }),
+ );
+ });
+});
diff --git a/notfair/src/server/onboarding/accounts.test.ts b/notfair/src/server/onboarding/accounts.test.ts
new file mode 100644
index 00000000..95d151e5
--- /dev/null
+++ b/notfair/src/server/onboarding/accounts.test.ts
@@ -0,0 +1,341 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ getMcpConfig: vi.fn(),
+ mcpRpcAutoRefresh: vi.fn(),
+ getProject: vi.fn(),
+ setGoogle: vi.fn(),
+ setMeta: vi.fn(),
+ setGsc: vi.fn(),
+ getMcpCatalog: vi.fn(),
+ getMcpStatus: vi.fn(),
+ accountPickerFor: vi.fn(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("@/server/mcp/rpc", () => ({
+ getMcpConfig: mocks.getMcpConfig,
+ mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh,
+}));
+vi.mock("@/server/db/projects", () => ({
+ getProject: mocks.getProject,
+ setProjectGoogleAdsAccount: mocks.setGoogle,
+ setProjectMetaAdsAccount: mocks.setMeta,
+ setProjectGscProperty: mocks.setGsc,
+}));
+vi.mock("@/server/mcp-catalog", () => ({
+ getMcpCatalog: mocks.getMcpCatalog,
+}));
+vi.mock("@/server/mcp/state", () => ({ getMcpStatus: mocks.getMcpStatus }));
+vi.mock("@/lib/mcp-account-pickers", () => ({
+ accountPickerFor: mocks.accountPickerFor,
+}));
+
+import {
+ getOnboardingConnectCardsAction,
+ listGoogleAdsAccounts,
+ listGscProperties,
+ listMetaAdsAccounts,
+ setOnboardingAccountAction,
+ setOnboardingGscPropertyAction,
+ setOnboardingMetaAdsAccountAction,
+} from "./accounts";
+
+const project = {
+ slug: "acme",
+ google_ads_account_id: "g-selected",
+ meta_ads_account_id: "m-selected",
+ gsc_property_url: "https://selected.example/",
+};
+
+function toolResult(body: unknown) {
+ return {
+ ok: true,
+ result: { content: [{ type: "text", text: JSON.stringify(body) }] },
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getMcpConfig.mockReturnValue({ url: "https://mcp.example" });
+ mocks.getProject.mockReturnValue(project);
+ mocks.setGoogle.mockReturnValue(project);
+ mocks.setMeta.mockReturnValue(project);
+ mocks.setGsc.mockReturnValue(project);
+});
+
+describe("listGoogleAdsAccounts", () => {
+ it("reports a missing MCP configuration without making an RPC", async () => {
+ mocks.getMcpConfig.mockReturnValue(null);
+ await expect(listGoogleAdsAccounts("acme")).resolves.toMatchObject({
+ ok: false,
+ kind: "mcp_not_configured",
+ });
+ expect(mocks.mcpRpcAutoRefresh).not.toHaveBeenCalled();
+ });
+
+ it("normalizes accounts, names, ids, and the default hint", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(
+ toolResult({
+ accounts: [
+ { id: 123, name: " Main " },
+ { id: "fallback", name: "" },
+ { id: "", name: "ignored" },
+ null,
+ ],
+ defaultAccountId: 123,
+ }),
+ );
+ await expect(listGoogleAdsAccounts("acme")).resolves.toEqual({
+ ok: true,
+ accounts: [
+ { id: "123", name: "Main" },
+ { id: "fallback", name: "fallback" },
+ ],
+ default_account_id: "123",
+ });
+ expect(mocks.mcpRpcAutoRefresh).toHaveBeenCalledWith(
+ "acme",
+ "notfair-googleads",
+ "tools/call",
+ { name: "listConnectedAccounts", arguments: {} },
+ { timeoutMs: 8_000 },
+ );
+ });
+
+ it.each([
+ [{ kind: "http_error", status: 503 }, "HTTP 503"],
+ [{ kind: "rpc_error", code: -1, message: "bad" }, "RPC -1: bad"],
+ [{ kind: "timeout" }, "MCP call timed out"],
+ [{ kind: "aborted" }, "MCP call aborted"],
+ [{ kind: "malformed_response", message: "junk" }, "junk"],
+ [{ kind: "network_error", message: "offline" }, "offline"],
+ ])("formats RPC failure %o", async (failure, message) => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, ...failure });
+ await expect(listGoogleAdsAccounts("acme")).resolves.toEqual({
+ ok: false,
+ kind: "rpc",
+ error: message,
+ });
+ });
+
+ it.each([
+ null,
+ { isError: true, content: [{ text: "{}" }] },
+ { content: [] },
+ { content: [{ text: "not json" }] },
+ { content: [{ text: "{}" }] },
+ ])("rejects malformed tool result %#", async (result) => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: true, result });
+ await expect(listGoogleAdsAccounts("acme")).resolves.toMatchObject({
+ ok: false,
+ kind: "shape",
+ });
+ });
+});
+
+describe("setOnboardingAccountAction", () => {
+ it("validates required input and project existence", async () => {
+ await expect(setOnboardingAccountAction(" ", "id")).resolves.toMatchObject({ ok: false });
+ await expect(setOnboardingAccountAction("acme", " ")).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue(null);
+ await expect(setOnboardingAccountAction("acme", "id")).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ });
+
+ it("rejects failed verification and unreachable account ids", async () => {
+ mocks.getMcpConfig.mockReturnValue(null);
+ await expect(setOnboardingAccountAction("acme", "id")).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining("Couldn't verify account"),
+ });
+
+ mocks.getMcpConfig.mockReturnValue({});
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ accounts: [{ id: "other" }] }));
+ await expect(setOnboardingAccountAction("acme", "id")).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining("isn't in"),
+ });
+ });
+
+ it("persists a verified account and revalidates the layout", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ accounts: [{ id: "id", name: "A" }] }));
+ await expect(setOnboardingAccountAction("acme", "id")).resolves.toEqual({
+ ok: true,
+ project,
+ });
+ expect(mocks.setGoogle).toHaveBeenCalledWith("acme", "id");
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+ });
+
+ it("handles a project disappearing during the write", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ accounts: [{ id: "id" }] }));
+ mocks.setGoogle.mockReturnValue(null);
+ await expect(setOnboardingAccountAction("acme", "id")).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ });
+});
+
+describe("Meta Ads account onboarding", () => {
+ it("supports Graph data and fallback accounts shapes", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(
+ toolResult({ data: [{ id: "act_1", name: " Primary " }, { id: "act_2" }, null] }),
+ );
+ await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({
+ ok: true,
+ accounts: [
+ { id: "act_1", name: "Primary" },
+ { id: "act_2", name: "act_2" },
+ ],
+ });
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(
+ toolResult({ accounts: [{ id: "act_3", name: "Third" }], defaultAccountId: "act_3" }),
+ );
+ await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({
+ ok: true,
+ default_account_id: "act_3",
+ });
+ });
+
+ it("handles missing config, RPC failure, and malformed payloads", async () => {
+ mocks.getMcpConfig.mockReturnValue(null);
+ await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({ kind: "mcp_not_configured" });
+ mocks.getMcpConfig.mockReturnValue({});
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "timeout" });
+ await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({ kind: "rpc" });
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ nope: [] }));
+ await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({ kind: "shape" });
+ });
+
+ it("validates and persists the selected Meta account", async () => {
+ await expect(setOnboardingMetaAdsAccountAction("", "act_1")).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue(null);
+ await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue(project);
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ data: [{ id: "act_1" }] }));
+ await expect(setOnboardingMetaAdsAccountAction("acme", "missing")).resolves.toMatchObject({ ok: false });
+ await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toEqual({ ok: true, project });
+ expect(mocks.setMeta).toHaveBeenCalledWith("acme", "act_1");
+ });
+
+ it("surfaces verification and disappearing-project failures", async () => {
+ mocks.getMcpConfig.mockReturnValue(null);
+ await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toMatchObject({
+ error: expect.stringContaining("Meta Ads MCP"),
+ });
+ mocks.getMcpConfig.mockReturnValue({});
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ data: [{ id: "act_1" }] }));
+ mocks.setMeta.mockReturnValue(null);
+ await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ });
+});
+
+describe("Search Console property onboarding", () => {
+ it("normalizes bare, siteEntry, and sites payloads with readable labels", async () => {
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(
+ toolResult([
+ { siteUrl: "sc-domain:example.com", permissionLevel: "siteOwner" },
+ { siteUrl: "https://example.com/blog/" },
+ { id: "not a url", name: " Custom " },
+ { siteUrl: "" },
+ null,
+ ]),
+ );
+ await expect(listGscProperties("acme")).resolves.toMatchObject({
+ ok: true,
+ properties: [
+ { id: "sc-domain:example.com", name: "example.com", permission: "siteOwner" },
+ { id: "https://example.com/blog/", name: "example.com/blog/" },
+ { id: "not a url", name: "Custom" },
+ ],
+ default_property_id: null,
+ });
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(
+ toolResult({ siteEntry: [{ siteUrl: "https://one.example/" }], defaultPropertyId: "one" }),
+ );
+ await expect(listGscProperties("acme")).resolves.toMatchObject({ default_property_id: "one" });
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ sites: [] }));
+ await expect(listGscProperties("acme")).resolves.toMatchObject({ ok: true, properties: [] });
+ });
+
+ it("handles missing config, RPC errors, and malformed object payloads", async () => {
+ mocks.getMcpConfig.mockReturnValue(null);
+ await expect(listGscProperties("acme")).resolves.toMatchObject({ kind: "mcp_not_configured" });
+ mocks.getMcpConfig.mockReturnValue({});
+ mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "aborted" });
+ await expect(listGscProperties("acme")).resolves.toMatchObject({ kind: "rpc", error: "MCP call aborted" });
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ unknown: [] }));
+ await expect(listGscProperties("acme")).resolves.toMatchObject({ kind: "shape" });
+ });
+
+ it("validates and persists a selected property", async () => {
+ await expect(setOnboardingGscPropertyAction("acme", " ")).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue(null);
+ await expect(setOnboardingGscPropertyAction("acme", "x")).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue(project);
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult([{ siteUrl: "https://example.com/" }]));
+ await expect(setOnboardingGscPropertyAction("acme", "missing")).resolves.toMatchObject({ ok: false });
+ await expect(setOnboardingGscPropertyAction("acme", "https://example.com/")).resolves.toEqual({ ok: true, project });
+ expect(mocks.setGsc).toHaveBeenCalledWith("acme", "https://example.com/");
+ });
+
+ it("surfaces verification and disappearing-project failures", async () => {
+ mocks.getMcpConfig.mockReturnValue(null);
+ await expect(setOnboardingGscPropertyAction("acme", "x")).resolves.toMatchObject({
+ error: expect.stringContaining("GSC MCP"),
+ });
+ mocks.getMcpConfig.mockReturnValue({});
+ mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult([{ siteUrl: "x" }]));
+ mocks.setGsc.mockReturnValue(null);
+ await expect(setOnboardingGscPropertyAction("acme", "x")).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ });
+});
+
+describe("getOnboardingConnectCardsAction", () => {
+ it("validates the project", async () => {
+ await expect(getOnboardingConnectCardsAction(" ")).resolves.toMatchObject({ ok: false });
+ mocks.getProject.mockReturnValue(null);
+ await expect(getOnboardingConnectCardsAction("acme")).resolves.toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ });
+
+ it("keeps recommended cards plus connected extras and derives selections", async () => {
+ const catalog = [
+ { key: "notfair-googleads" },
+ { key: "custom-connected" },
+ { key: "custom-idle" },
+ ];
+ mocks.getMcpCatalog.mockReturnValue(catalog);
+ mocks.getMcpStatus
+ .mockResolvedValueOnce({ state: "not_configured" })
+ .mockResolvedValueOnce({ state: "connected" })
+ .mockResolvedValueOnce({ state: "unreachable" });
+ mocks.accountPickerFor.mockImplementation((key: string) =>
+ key === "notfair-googleads"
+ ? { selectedId: (p: typeof project) => p.google_ads_account_id }
+ : null,
+ );
+ const result = await getOnboardingConnectCardsAction("acme");
+ expect(result).toMatchObject({ ok: true, any_connected: true });
+ if (!result.ok) throw new Error("expected cards");
+ expect(result.cards.map((card) => card.spec.key)).toEqual([
+ "notfair-googleads",
+ "custom-connected",
+ ]);
+ expect(result.cards[0]!.selected_id).toBe("g-selected");
+ expect(result.cards[1]!.selected_id).toBeNull();
+ });
+});
diff --git a/notfair/src/server/onboarding/accounts.ts b/notfair/src/server/onboarding/accounts.ts
index 841b46be..08a8cf92 100644
--- a/notfair/src/server/onboarding/accounts.ts
+++ b/notfair/src/server/onboarding/accounts.ts
@@ -381,17 +381,16 @@ function parseGscPropertiesPayload(
}
// Normalize all three accepted shapes down to a single row list.
- const rows: GscSiteRow[] = Array.isArray(body)
+ const rows: GscSiteRow[] | null = Array.isArray(body)
? body
: Array.isArray(body?.siteEntry)
? body.siteEntry
: Array.isArray(body?.sites)
? body.sites
- : [];
- if (rows.length === 0 && !Array.isArray(body)) {
- // Object with neither `siteEntry` nor `sites` — genuinely unexpected.
- return null;
- }
+ : null;
+ // Empty arrays are valid: a connected bearer can legitimately have no
+ // reachable properties. Only reject objects with neither supported key.
+ if (!rows) return null;
const properties: GscProperty[] = [];
for (const s of rows) {
diff --git a/notfair/src/server/scheduler/tick.test.ts b/notfair/src/server/scheduler/tick.test.ts
new file mode 100644
index 00000000..b5e88884
--- /dev/null
+++ b/notfair/src/server/scheduler/tick.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ runTicks: vi.fn(), syncPrs: vi.fn() }));
+vi.mock("@/server/goals/tick", () => ({ runDueGoalTicks: mocks.runTicks }));
+vi.mock("@/server/goals/pr-sync", () => ({ syncDueGoalPrs: mocks.syncPrs }));
+
+import { ensureSchedulerRunning, stopScheduler } from "./tick";
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ mocks.runTicks.mockResolvedValue(undefined);
+ mocks.syncPrs.mockResolvedValue(undefined);
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ stopScheduler();
+});
+
+afterEach(() => {
+ stopScheduler();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+it("runs immediately, repeats every 30s, and starts only once", async () => {
+ ensureSchedulerRunning();
+ ensureSchedulerRunning();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.runTicks).toHaveBeenCalledTimes(1);
+ expect(mocks.syncPrs).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.runTicks).toHaveBeenCalledTimes(2);
+ stopScheduler();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mocks.runTicks).toHaveBeenCalledTimes(2);
+});
+
+it("logs independent tick and PR sweep failures", async () => {
+ mocks.runTicks.mockRejectedValue(new Error("tick failed"));
+ mocks.syncPrs.mockRejectedValue(new Error("pr failed"));
+ ensureSchedulerRunning();
+ await vi.advanceTimersByTimeAsync(0);
+ await Promise.resolve();
+ expect(console.error).toHaveBeenCalledWith("[scheduler] goal tick sweep failed:", expect.any(Error));
+ expect(console.error).toHaveBeenCalledWith("[scheduler] PR freshness sweep failed:", expect.any(Error));
+});
diff --git a/notfair/src/server/secrets/cipher.test.ts b/notfair/src/server/secrets/cipher.test.ts
new file mode 100644
index 00000000..79d2fbee
--- /dev/null
+++ b/notfair/src/server/secrets/cipher.test.ts
@@ -0,0 +1,62 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ // Fixed 32-byte AES-256 key so the round-trip is deterministic.
+ getMasterKey: vi.fn(async () => Buffer.alloc(32, 7)),
+}));
+
+vi.mock("./master-key", () => ({ getMasterKey: mocks.getMasterKey }));
+
+import { decrypt, encrypt } from "./cipher";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("encrypt / decrypt round-trip", () => {
+ it("recovers the original plaintext", async () => {
+ const secret = "hello world 🌍 token=abc123";
+ const blob = await encrypt(secret);
+ expect(blob).not.toContain(secret);
+ expect(await decrypt(blob)).toBe(secret);
+ });
+
+ it("recovers an empty string", async () => {
+ const blob = await encrypt("");
+ expect(await decrypt(blob)).toBe("");
+ });
+
+ it("produces a distinct ciphertext each time (random IV)", async () => {
+ const a = await encrypt("same");
+ const b = await encrypt("same");
+ expect(a).not.toBe(b);
+ expect(await decrypt(a)).toBe("same");
+ expect(await decrypt(b)).toBe("same");
+ });
+
+ it("outputs valid base64 wrapping iv|ciphertext|tag", async () => {
+ const blob = await encrypt("x");
+ const buf = Buffer.from(blob, "base64");
+ // 12-byte IV + 16-byte tag + >=1 ciphertext byte
+ expect(buf.length).toBeGreaterThanOrEqual(12 + 16 + 1);
+ });
+});
+
+describe("decrypt error handling", () => {
+ it("throws on a blob too short to hold iv+tag", async () => {
+ await expect(decrypt(Buffer.alloc(5).toString("base64"))).rejects.toThrow(
+ /malformed/,
+ );
+ });
+
+ it("throws when the auth tag does not verify (tampered ciphertext)", async () => {
+ const blob = await encrypt("tamper me");
+ const buf = Buffer.from(blob, "base64");
+ buf[13] = buf[13]! ^ 0xff; // flip a ciphertext byte
+ await expect(decrypt(buf.toString("base64"))).rejects.toThrow();
+ });
+
+ it("throws when decrypted with a different key", async () => {
+ const blob = await encrypt("wrong key");
+ mocks.getMasterKey.mockResolvedValueOnce(Buffer.alloc(32, 9));
+ await expect(decrypt(blob)).rejects.toThrow();
+ });
+});
diff --git a/notfair/src/server/sessions/transcript-tail.test.ts b/notfair/src/server/sessions/transcript-tail.test.ts
new file mode 100644
index 00000000..560fa785
--- /dev/null
+++ b/notfair/src/server/sessions/transcript-tail.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ getDb: vi.fn() }));
+vi.mock("@/server/db/db", () => ({ getDb: mocks.getDb }));
+
+import { readTranscriptTail, resolveSessionForThread } from "./transcript-tail";
+
+const session = { id: "session-1", project_slug: "acme", agent_id: "agent-1", label: "main" };
+
+function dbWith(rows: Array<Record<string, unknown>>, found: unknown = session) {
+ return {
+ prepare: vi.fn((sql: string) => ({
+ get: vi.fn(() => found),
+ all: vi.fn(() => sql.includes("transcript_events") ? rows : []),
+ })),
+ };
+}
+
+beforeEach(() => vi.clearAllMocks());
+
+it("resolves sessions with all ownership keys and returns null when absent", () => {
+ let db = dbWith([], session);
+ mocks.getDb.mockReturnValue(db);
+ expect(resolveSessionForThread("acme", "agent-1", "main")).toBe(session);
+ expect(db.prepare.mock.results[0]!.value.get).toHaveBeenCalledWith("acme", "agent-1", "main");
+ mocks.getDb.mockReturnValue(dbWith([], null));
+ expect(resolveSessionForThread("acme", "agent-1", "missing")).toBeNull();
+});
+
+it("returns the incoming cursor when no session exists", () => {
+ mocks.getDb.mockReturnValue(dbWith([], null));
+ expect(readTranscriptTail("p", "a", "t", 7)).toEqual({ events: [], cursor: 7 });
+});
+
+it("normalizes every transcript event kind and advances the cursor", () => {
+ const rows = [
+ { id: "u1", seq: 1, kind: "user", payload_json: '{"text":"hello","source":"human"}', created_at: "2026-01-01T00:00:00Z" },
+ { id: "u2", seq: 2, kind: "user", payload_json: '{"text":"brief","source":"goal-tick"}', created_at: "bad" },
+ { id: "d", seq: 3, kind: "delta", payload_json: '{"text":42}', created_at: "2026-01-01" },
+ { id: "tc", seq: 4, kind: "tool", payload_json: '{"phase":"start","toolCallId":"c1","name":"search","label":"Searching"}', created_at: "2026-01-01" },
+ { id: "tc2", seq: 5, kind: "tool", payload_json: '{}', created_at: "2026-01-01" },
+ { id: "tr", seq: 6, kind: "tool", payload_json: '{"phase":"result","toolCallId":"c1","name":"search"}', created_at: "2026-01-01" },
+ { id: "life", seq: 7, kind: "lifecycle", payload_json: '{}', created_at: "2026-01-01" },
+ { id: "fin", seq: 8, kind: "final", payload_json: '{}', created_at: "2026-01-01" },
+ { id: "err", seq: 9, kind: "error", payload_json: '{"message":"boom"}', created_at: "2026-01-01" },
+ { id: "err2", seq: 10, kind: "error", payload_json: 'null', created_at: "2026-01-01" },
+ { id: "x", seq: 11, kind: "other", payload_json: 'not json', created_at: "2026-01-01" },
+ ];
+ mocks.getDb.mockReturnValue(dbWith(rows));
+ const result = readTranscriptTail("p", "a", "t", 0);
+ expect(result.cursor).toBe(11);
+ expect(result.events).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: "user_message", id: "u1", body: "hello", system: false }),
+ expect.objectContaining({ kind: "user_message", id: "u2", system: true }),
+ expect.objectContaining({ kind: "assistant_text", id: "d", body: "" }),
+ expect.objectContaining({ kind: "tool_call", id: "tc", tool_call_id: "c1", label: "Searching" }),
+ expect.objectContaining({ kind: "tool_call", id: "tc2", name: "tool", label: null }),
+ expect.objectContaining({ kind: "tool_result", id: "tr", ok: true, summary: null }),
+ expect.objectContaining({ kind: "lifecycle", id: "life", phase: "unknown" }),
+ expect.objectContaining({ kind: "lifecycle", id: "fin", phase: "done" }),
+ expect.objectContaining({ kind: "assistant_text", id: "err", body: "⚠ boom" }),
+ expect.objectContaining({ kind: "lifecycle", id: "err:done", phase: "done" }),
+ expect.objectContaining({ kind: "unknown", id: "x", raw_type: "other" }),
+ ]));
+ expect(result.events).toHaveLength(13);
+});
diff --git a/notfair/src/server/sessions/view.test.ts b/notfair/src/server/sessions/view.test.ts
new file mode 100644
index 00000000..ce82a7f5
--- /dev/null
+++ b/notfair/src/server/sessions/view.test.ts
@@ -0,0 +1,100 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getDb: vi.fn(),
+ getProject: vi.fn(),
+ getOrCreateSession: vi.fn(),
+ listAgentSessions: vi.fn(),
+}));
+vi.mock("@/server/db/db", () => ({ getDb: mocks.getDb }));
+vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));
+vi.mock("./index", () => ({
+ getOrCreateSession: mocks.getOrCreateSession,
+ listAgentSessions: mocks.listAgentSessions,
+}));
+
+import {
+ classifySessions,
+ findSessionBySessionId,
+ isSystemSession,
+ listSessionsForAgent,
+ materializeSession,
+ newSessionId,
+ pickLatestChatSession,
+ type SessionView,
+} from "./view";
+
+const row = {
+ id: "s1", label: "main", updated_at: "2026-01-02T00:00:00Z", title: "Title", pinned_at: "2026-01-01",
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+it("maps DB sessions to UI views", () => {
+ mocks.listAgentSessions.mockReturnValue([row, { ...row, id: "s2", label: "other", updated_at: "bad", title: null, pinned_at: null }]);
+ expect(listSessionsForAgent("p", "a")).toEqual([
+ expect.objectContaining({ sessionId: "main", sessionKey: "s1", pending: false, pinned: true, title: "Title" }),
+ expect.objectContaining({ sessionId: "other", lastInteractionAt: 0, pinned: false }),
+ ]);
+ expect(newSessionId()).toMatch(/^[0-9a-f-]{36}$/);
+});
+
+it("finds an owned session and handles missing rows", () => {
+ const get = vi.fn().mockReturnValueOnce(row).mockReturnValueOnce(undefined);
+ mocks.getDb.mockReturnValue({ prepare: vi.fn(() => ({ get })) });
+ expect(findSessionBySessionId("p", "a", "main")).toMatchObject({ sessionKey: "s1" });
+ expect(findSessionBySessionId("p", "a", "missing")).toBeNull();
+ expect(get).toHaveBeenCalledWith("p", "a", "main");
+});
+
+it("materializes with the project harness or the default", () => {
+ mocks.getOrCreateSession.mockReturnValue(row);
+ mocks.getProject.mockReturnValue({ harness_adapter: "codex-local" });
+ expect(materializeSession({ project_slug: "p", agent_id: "a", label: "main" })).toBe(row);
+ expect(mocks.getOrCreateSession).toHaveBeenLastCalledWith(expect.objectContaining({ harness_adapter: "codex-local" }));
+ mocks.getProject.mockReturnValue(null);
+ materializeSession({ project_slug: "p", agent_id: "a", label: "other" });
+ expect(mocks.getOrCreateSession).toHaveBeenLastCalledWith(expect.objectContaining({ harness_adapter: "claude-code-local" }));
+});
+
+it("detects tick sessions and picks the latest chat", () => {
+ expect(isSystemSession("tick-12")).toBe(true);
+ expect(isSystemSession("tick-x")).toBe(false);
+ expect(pickLatestChatSession([{ label: "tick-2" }, { label: "main" }, { label: "other" }])).toEqual({ label: "main" });
+ expect(pickLatestChatSession([{ label: "tick-2" }])).toBeUndefined();
+});
+
+it("classifies tick, pending, kickoff, normal, long, and malformed chats", async () => {
+ const sessions: SessionView[] = [
+ { sessionId: "tick-4", label: "tick-4", sessionKey: "1", lastInteractionAt: 0, pending: false, title: null, pinned: false },
+ { sessionId: "pending", label: "pending", sessionKey: "2", lastInteractionAt: 0, pending: true, title: null, pinned: false },
+ { sessionId: "kick", label: "kick", sessionKey: "3", lastInteractionAt: 0, pending: false, title: null, pinned: false },
+ { sessionId: "chat", label: "chat", sessionKey: "4", lastInteractionAt: 0, pending: false, title: null, pinned: false },
+ { sessionId: "long", label: "long", sessionKey: "5", lastInteractionAt: 0, pending: false, title: null, pinned: false },
+ { sessionId: "missing", label: "missing", sessionKey: "6", lastInteractionAt: 0, pending: false, title: null, pinned: false },
+ { sessionId: "bad", label: "bad", sessionKey: "7", lastInteractionAt: 0, pending: false, title: null, pinned: false },
+ ];
+ const payloadBySession: Record<string, unknown> = {
+ kick: { payload_json: JSON.stringify({ text: "[INTAKE] begin" }) },
+ chat: { payload_json: JSON.stringify({ text: " Hello\n world " }) },
+ long: { payload_json: JSON.stringify({ text: "x".repeat(150) }) },
+ bad: { payload_json: "not-json" },
+ };
+ mocks.getDb.mockReturnValue({
+ prepare: vi.fn((sql: string) => ({
+ get: vi.fn((...args: string[]) => {
+ if (sql.includes("SELECT id FROM")) return args[2] === "missing" ? undefined : { id: args[2] };
+ return payloadBySession[args[0]!];
+ }),
+ })),
+ });
+ const result = await classifySessions("a", "p", sessions);
+ expect(result.get("tick-4")).toEqual({ kind: "tick", tick_number: 4 });
+ expect(result.has("pending")).toBe(false);
+ expect(result.get("kick")).toEqual({ kind: "chat", preview: "Goal kickoff" });
+ expect(result.get("chat")).toEqual({ kind: "chat", preview: "Hello world" });
+ expect((result.get("long") as { preview: string }).preview).toHaveLength(140);
+ expect(result.get("missing")).toEqual({ kind: "chat", preview: "" });
+ expect(result.get("bad")).toEqual({ kind: "chat", preview: "" });
+ expect(await classifySessions("a", "p", [])).toEqual(new Map());
+});
diff --git a/notfair/vitest.config.ts b/notfair/vitest.config.ts
index ba3610a8..d9c0c165 100644
--- a/notfair/vitest.config.ts
+++ b/notfair/vitest.config.ts
@@ -32,6 +32,10 @@ export default defineConfig({
"src/**/*.d.ts",
"src/types.ts",
],
+ thresholds: {
+ statements: 80,
+ lines: 80,
+ },
},
},
});
diff --git a/notfair/vitest.setup.ts b/notfair/vitest.setup.ts
index f149f27a..1cac1383 100644
--- a/notfair/vitest.setup.ts
+++ b/notfair/vitest.setup.ts
@@ -1 +1,34 @@
import "@testing-library/jest-dom/vitest";
+
+// Node 25 exposes an experimental, path-dependent global localStorage that can
+// shadow jsdom's implementation. Keep component tests independent of the Node
+// invocation flags by installing the small, standards-compatible subset they
+// need in every DOM test environment.
+if (typeof window !== "undefined") {
+ const values = new Map<string, string>();
+ const localStorage: Storage = {
+ get length() {
+ return values.size;
+ },
+ clear() {
+ values.clear();
+ },
+ getItem(key) {
+ return values.get(String(key)) ?? null;
+ },
+ key(index) {
+ return [...values.keys()][index] ?? null;
+ },
+ removeItem(key) {
+ values.delete(String(key));
+ },
+ setItem(key, value) {
+ values.set(String(key), String(value));
+ },
+ };
+
+ Object.defineProperty(window, "localStorage", {
+ configurable: true,
+ value: localStorage,
+ });
+}