Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

test: raise coverage across web/email-worker/shared/app

Gus24ddfd7477d2
diff --git a/src/app/test/install.test.ts b/src/app/test/install.test.ts
new file mode 100644
index 000000000..ea0aa864c
--- /dev/null
+++ b/src/app/test/install.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { mkdirSync, existsSync, rmSync, writeFileSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+
+const testDir = join(tmpdir(), `alook-test-install-${process.pid}`);
+
+vi.mock("../src/lib/constants.js", () => ({ SELF_HOSTED_DIR: testDir }));
+
+describe("install", () => {
+ beforeEach(() => mkdirSync(testDir, { recursive: true }));
+ afterEach(() => {
+ if (existsSync(testDir)) rmSync(testDir, { recursive: true, force: true });
+ vi.resetModules();
+ });
+
+ describe("isInstalled", () => {
+ it("returns false when web/wrangler.toml is absent", async () => {
+ const { isInstalled } = await import("../src/lib/install.js");
+ expect(isInstalled()).toBe(false);
+ });
+
+ it("returns true once web/wrangler.toml exists", async () => {
+ mkdirSync(join(testDir, "web"), { recursive: true });
+ writeFileSync(join(testDir, "web", "wrangler.toml"), "name = 'x'");
+ const { isInstalled } = await import("../src/lib/install.js");
+ expect(isInstalled()).toBe(true);
+ });
+ });
+});
diff --git a/src/app/test/migrate.test.ts b/src/app/test/migrate.test.ts
new file mode 100644
index 000000000..ac6998f59
--- /dev/null
+++ b/src/app/test/migrate.test.ts
@@ -0,0 +1,43 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+
+const mockExecSync = vi.fn();
+vi.mock("child_process", () => ({ execSync: (...a: unknown[]) => mockExecSync(...a) }));
+vi.mock("../src/lib/constants.js", () => ({ SELF_HOSTED_DIR: "/tmp/alook-test" }));
+
+import { runMigrations } from "../src/lib/migrate.js";
+
+let logs: string[];
+beforeEach(() => {
+ vi.clearAllMocks();
+ logs = [];
+ vi.spyOn(console, "log").mockImplementation((m?: unknown) => { logs.push(String(m)); });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe("runMigrations", () => {
+ it("sums applied command counts from wrangler output", () => {
+ mockExecSync.mockReturnValue(Buffer.from("3 commands executed successfully\n5 commands executed successfully"));
+ runMigrations();
+ expect(logs.join("\n")).toContain("8 migration commands applied");
+ });
+
+ it("reports up-to-date when there is nothing to apply", () => {
+ mockExecSync.mockReturnValue(Buffer.from("No migrations to apply"));
+ runMigrations();
+ expect(logs.join("\n")).toContain("Already up to date");
+ });
+
+ it("falls back to a generic 'complete' message for unrecognized output", () => {
+ mockExecSync.mockReturnValue(Buffer.from("some other output"));
+ runMigrations();
+ expect(logs.join("\n")).toContain("Migrations complete");
+ });
+
+ it("exits on migration failure", () => {
+ mockExecSync.mockImplementation(() => { const e = new Error("fail") as Error & { stderr?: Buffer }; e.stderr = Buffer.from("D1 error"); throw e; });
+ const exit = vi.spyOn(process, "exit").mockImplementation((() => { throw new Error("exit"); }) as never);
+ expect(() => runMigrations()).toThrow("exit");
+ expect(exit).toHaveBeenCalledWith(1);
+ });
+});
diff --git a/src/app/test/register.test.ts b/src/app/test/register.test.ts
new file mode 100644
index 000000000..281bb99d2
--- /dev/null
+++ b/src/app/test/register.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+
+vi.mock("@alook/shared", () => ({ DEV_PASSWORD: "dev-pw" }));
+vi.mock("../src/lib/constants.js", () => ({ SELF_HOSTED_DIR: "/tmp/alook-test" }));
+
+import {
+ registerUser,
+ createWorkspace,
+ createMachineToken,
+ waitForServer,
+} from "../src/lib/register.js";
+
+const BASE = "http://localhost:3000";
+
+/** Build a fetch Response with a Set-Cookie session header. */
+function sessionResponse(ok = true, status = 200) {
+ const headers = new Headers();
+ // jsdom-less node Headers supports getSetCookie via append
+ headers.append("set-cookie", "better-auth.session_token=abc; Path=/");
+ return {
+ ok,
+ status,
+ headers,
+ text: async () => "",
+ json: async () => ({}),
+ } as unknown as Response;
+}
+
+beforeEach(() => {
+ vi.restoreAllMocks();
+ // Make console quiet and prevent process.exit from killing the test runner.
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("registerUser", () => {
+ it("returns a session cookie on successful signup", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(sessionResponse()));
+ const result = await registerUser(BASE, "[email protected]");
+ expect(result.sessionCookie).toContain("better-auth.session_token");
+ });
+
+ it("falls back to sign-in when the account already exists", async () => {
+ const fetchMock = vi
+ .fn()
+ // signup fails with "already exists"
+ .mockResolvedValueOnce({ ok: false, status: 400, text: async () => "User already exists", headers: new Headers() } as unknown as Response)
+ // sign-in succeeds with a session cookie
+ .mockResolvedValueOnce(sessionResponse());
+ vi.stubGlobal("fetch", fetchMock);
+
+ const result = await registerUser(BASE, "[email protected]");
+ expect(result.sessionCookie).toContain("better-auth.session_token");
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[1]![0]).toContain("/api/auth/sign-in/email");
+ });
+
+ it("exits when signup fails for a non-conflict reason", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false, status: 500, text: async () => "boom", headers: new Headers() } as unknown as Response));
+ const exit = vi.spyOn(process, "exit").mockImplementation((() => { throw new Error("exit"); }) as never);
+ await expect(registerUser(BASE, "[email protected]")).rejects.toThrow("exit");
+ expect(exit).toHaveBeenCalledWith(1);
+ });
+});
+
+describe("createWorkspace", () => {
+ it("returns the created workspace", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
+ ok: true, status: 200, headers: new Headers(),
+ json: async () => ({ id: "w1", name: "Personal", slug: "personal" }),
+ } as unknown as Response));
+ const ws = await createWorkspace(BASE, "cookie");
+ expect(ws.id).toBe("w1");
+ });
+
+ it("falls back to the first existing workspace when creation fails", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: false, status: 409, headers: new Headers() } as unknown as Response)
+ .mockResolvedValueOnce({ ok: true, status: 200, headers: new Headers(), json: async () => [{ id: "w-existing", name: "Old", slug: "old" }] } as unknown as Response);
+ vi.stubGlobal("fetch", fetchMock);
+ const ws = await createWorkspace(BASE, "cookie");
+ expect(ws.id).toBe("w-existing");
+ });
+});
+
+describe("createMachineToken", () => {
+ it("returns the token payload", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({
+ ok: true, status: 200, headers: new Headers(), json: async () => ({ token: "al_x", id: "mt1" }),
+ } as unknown as Response));
+ const tok = await createMachineToken(BASE, "cookie", "w1");
+ expect(tok.token).toBe("al_x");
+ });
+
+ it("exits when token creation fails", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false, status: 500, text: async () => "no", headers: new Headers() } as unknown as Response));
+ vi.spyOn(process, "exit").mockImplementation((() => { throw new Error("exit"); }) as never);
+ await expect(createMachineToken(BASE, "cookie", "w1")).rejects.toThrow("exit");
+ });
+});
+
+describe("waitForServer", () => {
+ it("returns once the server responds below 500", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ status: 200 } as unknown as Response));
+ await expect(waitForServer(BASE, 5000)).resolves.toBeUndefined();
+ });
+
+ it("exits when the server never comes up before the deadline", async () => {
+ // A non-positive timeout makes the deadline already-past, so the poll loop is
+ // skipped and the not-started exit(1) path runs — no timer plumbing needed.
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("ECONNREFUSED")));
+ vi.spyOn(process, "exit").mockImplementation((() => { throw new Error("exit"); }) as never);
+ await expect(waitForServer(BASE, 0)).rejects.toThrow("exit");
+ });
+});
diff --git a/src/app/test/services.test.ts b/src/app/test/services.test.ts
index 3a8baf42a..2d959358a 100644
--- a/src/app/test/services.test.ts
+++ b/src/app/test/services.test.ts
@@ -66,4 +66,20 @@ describe("services", () => {
expect(existsSync(PID_FILE)).toBe(false);
});
});
+
+ describe("startServices", () => {
+ it("early-returns without spawning when a service pid is already alive", async () => {
+ const { writePids } = await import("../src/lib/pid.js");
+ const { startServices } = await import("../src/lib/services.js");
+
+ // current process pid is guaranteed alive → the anyAlive guard short-circuits
+ writePids({ web: process.pid });
+ const logs: string[] = [];
+ const spy = vi.spyOn(console, "log").mockImplementation((m?: unknown) => { logs.push(String(m)); });
+
+ startServices({ web: 3000, emailWorker: 8787, wsDo: 8789 });
+ expect(logs.join("\n")).toContain("already running");
+ spy.mockRestore();
+ });
+ });
});
diff --git a/src/email-worker/src/__mocks__/cf.ts b/src/email-worker/src/__mocks__/cf.ts
index e342d59c0..a99c4d6fc 100644
--- a/src/email-worker/src/__mocks__/cf.ts
+++ b/src/email-worker/src/__mocks__/cf.ts
@@ -1,5 +1,79 @@
import { vi } from "vitest"
+// --- cloudflare:sockets Mock ---
+
+export interface MockSocket {
+ /** The fake Socket to hand back from `connect()` / `startTls()`. */
+ socket: Socket
+ /** Push a raw server response chunk into the readable stream (caller usually appends \r\n). */
+ pushData: (text: string) => void
+ /** Signal end-of-stream so a pending read resolves `{ done: true }`. */
+ close: () => void
+ /** All payloads written by the client, decoded to strings. */
+ writes: string[]
+ /** Spy on socket.close(). */
+ onClose: ReturnType<typeof vi.fn>
+ /** Spy on socket.startTls() (returns the same socket). */
+ onStartTls: ReturnType<typeof vi.fn>
+}
+
+/**
+ * Build a controllable fake `Socket` for testing code that talks IMAP/SMTP over
+ * `cloudflare:sockets`. The readable side is driven by `pushData()`/`close()`;
+ * the writable side records every chunk into `writes`.
+ *
+ * Usage:
+ * const m = createMockSocket()
+ * vi.mock("cloudflare:sockets", () => ({ connect: vi.fn(() => m.socket) }))
+ * m.pushData("* OK greeting\r\n")
+ */
+export function createMockSocket(): MockSocket {
+ const decoder = new TextDecoder()
+ const writes: string[] = []
+ let controller: ReadableStreamDefaultController<Uint8Array> | null = null
+ // Buffer data pushed before the consumer attaches a reader/controller.
+ const pending: Uint8Array[] = []
+ let closed = false
+
+ const readable = new ReadableStream<Uint8Array>({
+ start(c) {
+ controller = c
+ for (const chunk of pending) c.enqueue(chunk)
+ pending.length = 0
+ if (closed) c.close()
+ },
+ })
+
+ const writable = new WritableStream<Uint8Array>({
+ write(chunk) {
+ writes.push(decoder.decode(chunk))
+ },
+ })
+
+ const pushData = (text: string) => {
+ const bytes = new TextEncoder().encode(text)
+ if (controller) controller.enqueue(bytes)
+ else pending.push(bytes)
+ }
+
+ const close = () => {
+ closed = true
+ try { controller?.close() } catch { /* already closed */ }
+ }
+
+ const onClose = vi.fn(async () => {})
+ const onStartTls = vi.fn(() => socket)
+
+ const socket = {
+ readable,
+ writable,
+ close: onClose,
+ startTls: onStartTls,
+ } as unknown as Socket
+
+ return { socket, pushData, close, writes, onClose, onStartTls }
+}
+
// --- R2 Mock ---
export function createMockR2() {
diff --git a/src/email-worker/src/lib/imap-client.test.ts b/src/email-worker/src/lib/imap-client.test.ts
new file mode 100644
index 000000000..0e11d2e93
--- /dev/null
+++ b/src/email-worker/src/lib/imap-client.test.ts
@@ -0,0 +1,192 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+import { createMockSocket, type MockSocket } from "../__mocks__/cf"
+
+// Hoisted holder so the cloudflare:sockets mock can hand back the current socket.
+const h = vi.hoisted(() => ({ current: null as MockSocket | null }))
+
+vi.mock("cloudflare:sockets", () => ({
+ connect: vi.fn(() => h.current!.socket),
+}))
+
+import { ImapClient, ImapError, ImapAuthError } from "./imap-client"
+import { connect } from "cloudflare:sockets"
+
+const mockConnect = connect as unknown as ReturnType<typeof vi.fn>
+
+function newClient(opts?: Partial<ConstructorParameters<typeof ImapClient>[0]>) {
+ return new ImapClient({
+ host: "imap.example.com",
+ port: 993,
+ tls: true,
+ auth: { username: "[email protected]", password: "secret" },
+ ...opts,
+ })
+}
+
+describe("ImapClient", () => {
+ beforeEach(() => {
+ h.current = createMockSocket()
+ mockConnect.mockClear()
+ })
+
+ it("connects and logs in successfully", async () => {
+ const m = h.current!
+ m.pushData("* OK IMAP4rev1 ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+
+ const client = newClient()
+ await client.connect()
+
+ // greeting consumed, LOGIN issued with quoted credentials
+ expect(m.writes.join("")).toContain("A1 LOGIN")
+ expect(m.writes.join("")).toContain('"[email protected]"')
+ expect(m.writes.join("")).toContain('"secret"')
+ })
+
+ it("calls startTls when tls is enabled", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+
+ await newClient({ tls: true }).connect()
+ expect(m.onStartTls).toHaveBeenCalledOnce()
+ })
+
+ it("does NOT call startTls when tls is disabled", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+
+ await newClient({ tls: false }).connect()
+ expect(m.onStartTls).not.toHaveBeenCalled()
+ })
+
+ it("throws ImapAuthError with permanent=true on AUTHENTICATIONFAILED", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 NO [AUTHENTICATIONFAILED] Invalid credentials\r\n")
+
+ const client = newClient()
+ const err = await client.connect().catch((e) => e)
+ expect(err).toBeInstanceOf(ImapAuthError)
+ expect((err as ImapAuthError).permanent).toBe(true)
+ })
+
+ it("throws ImapAuthError with permanent=true on 'invalid credentials' text", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 NO Invalid credentials provided\r\n")
+
+ const err = await newClient().connect().catch((e) => e)
+ expect(err).toBeInstanceOf(ImapAuthError)
+ expect((err as ImapAuthError).permanent).toBe(true)
+ })
+
+ it("throws ImapAuthError with permanent=false on a transient login failure", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 NO temporary server error, try again\r\n")
+
+ const err = await newClient().connect().catch((e) => e)
+ expect(err).toBeInstanceOf(ImapAuthError)
+ expect((err as ImapAuthError).permanent).toBe(false)
+ })
+
+ it("throws ImapError when server sends BYE greeting", async () => {
+ const m = h.current!
+ m.pushData("* BYE server too busy\r\n")
+
+ const err = await newClient().connect().catch((e) => e)
+ expect(err).toBeInstanceOf(ImapError)
+ expect((err as ImapError).message).toContain("Server rejected connection")
+ })
+
+ it("throws ImapError when the stream closes before the greeting", async () => {
+ const m = h.current!
+ m.close() // no greeting at all
+
+ const err = await newClient().connect().catch((e) => e)
+ expect(err).toBeInstanceOf(ImapError)
+ expect((err as ImapError).message).toContain("Connection closed before greeting")
+ })
+
+ it("times out a read that never arrives", async () => {
+ vi.useFakeTimers()
+ try {
+ const m = h.current!
+ // greeting arrives, but the LOGIN response never does
+ m.pushData("* OK ready\r\n")
+
+ const client = newClient({ readTimeoutMs: 1000 })
+ const promise = client.connect().catch((e) => e)
+ // let the greeting read resolve and the LOGIN write fire, then trip the timeout
+ await vi.advanceTimersByTimeAsync(1001)
+ const err = await promise
+ expect(err).toBeInstanceOf(ImapError)
+ expect((err as ImapError).message).toContain("read timeout")
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("SELECT parses the EXISTS count", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+ const client = newClient()
+ await client.connect()
+
+ m.pushData("* 42 EXISTS\r\n")
+ m.pushData("A2 OK SELECT completed\r\n")
+ const result = await client.select("INBOX")
+ expect(result.exists).toBe(42)
+ })
+
+ it("SELECT returns 0 when no EXISTS line is present", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+ const client = newClient()
+ await client.connect()
+
+ m.pushData("A2 OK SELECT completed\r\n")
+ const result = await client.select("INBOX")
+ expect(result.exists).toBe(0)
+ })
+
+ it("throws ImapError on a tagged NO/BAD for a generic command", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+ const client = newClient()
+ await client.connect()
+
+ m.pushData("B1 BAD syntax error\r\n")
+ const err = await client.command("B1", "BOGUS").catch((e) => e)
+ expect(err).toBeInstanceOf(ImapError)
+ expect((err as ImapError).message).toContain("B1 failed")
+ })
+
+ it("close() releases locks and closes the socket", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+ const client = newClient()
+ await client.connect()
+
+ await client.close()
+ expect(m.onClose).toHaveBeenCalled()
+ })
+
+ it("logout() sends LOGOUT then closes", async () => {
+ const m = h.current!
+ m.pushData("* OK ready\r\n")
+ m.pushData("A1 OK LOGIN completed\r\n")
+ const client = newClient()
+ await client.connect()
+
+ await client.logout()
+ expect(m.writes.join("")).toContain("LOGOUT")
+ expect(m.onClose).toHaveBeenCalled()
+ })
+})
diff --git a/src/email-worker/src/lib/imap-client.ts b/src/email-worker/src/lib/imap-client.ts
index 53ecfd97f..c17c3000e 100644
--- a/src/email-worker/src/lib/imap-client.ts
+++ b/src/email-worker/src/lib/imap-client.ts
@@ -8,7 +8,7 @@ export interface ImapClientOptions {
readTimeoutMs?: number
}
-class ImapError extends Error {
+export class ImapError extends Error {
constructor(message: string) {
super(message)
this.name = "ImapError"
diff --git a/src/shared/test/browser/caption-helpers.test.ts b/src/shared/test/browser/caption-helpers.test.ts
new file mode 100644
index 000000000..77544598e
--- /dev/null
+++ b/src/shared/test/browser/caption-helpers.test.ts
@@ -0,0 +1,168 @@
+import { describe, it, expect } from "vitest"
+import {
+ parseCaptionElements,
+ deduplicateCaptions,
+ formatTranscript,
+ createTimestamp,
+ groupIntoBlocks,
+} from "../../src/browser/index"
+import type { TranscriptEntry } from "../../src/browser/transcript"
+
+describe("parseCaptionElements", () => {
+ it("strips HTML tags from speaker and text", () => {
+ const result = parseCaptionElements([
+ { speakerHtml: "<span>Alice</span>", textHtml: "<b>Hello</b> world" },
+ ])
+ expect(result).toEqual([{ speaker: "Alice", text: "Hello world" }])
+ })
+
+ it("trims surrounding whitespace", () => {
+ const result = parseCaptionElements([
+ { speakerHtml: " Bob ", textHtml: " hi there " },
+ ])
+ expect(result).toEqual([{ speaker: "Bob", text: "hi there" }])
+ })
+
+ it("skips entries with empty speaker", () => {
+ const result = parseCaptionElements([
+ { speakerHtml: "", textHtml: "orphan text" },
+ { speakerHtml: "<div></div>", textHtml: "also orphan" },
+ ])
+ expect(result).toEqual([])
+ })
+
+ it("skips entries with empty text", () => {
+ const result = parseCaptionElements([{ speakerHtml: "Carol", textHtml: "<br/>" }])
+ expect(result).toEqual([])
+ })
+
+ it("returns empty array for empty input", () => {
+ expect(parseCaptionElements([])).toEqual([])
+ })
+
+ it("preserves order and handles multiple entries", () => {
+ const result = parseCaptionElements([
+ { speakerHtml: "Alice", textHtml: "one" },
+ { speakerHtml: "Bob", textHtml: "two" },
+ ])
+ expect(result).toEqual([
+ { speaker: "Alice", text: "one" },
+ { speaker: "Bob", text: "two" },
+ ])
+ })
+})
+
+describe("createTimestamp", () => {
+ it("formats elapsed time as HH:MM:SS", () => {
+ expect(createTimestamp(0, 0)).toBe("00:00:00")
+ expect(createTimestamp(0, 5_000)).toBe("00:00:05")
+ expect(createTimestamp(0, 65_000)).toBe("00:01:05")
+ expect(createTimestamp(0, 3_661_000)).toBe("01:01:01")
+ })
+
+ it("clamps negative elapsed to zero", () => {
+ expect(createTimestamp(10_000, 5_000)).toBe("00:00:00")
+ })
+})
+
+describe("deduplicateCaptions", () => {
+ const START = 0
+ const NOW = 12_000 // -> 00:00:12
+
+ it("appends a brand new caption", () => {
+ const result = deduplicateCaptions([], [{ speaker: "Alice", text: "hi" }], START, NOW)
+ expect(result).toEqual([{ speaker: "Alice", text: "hi", timestamp: "00:00:12" }])
+ })
+
+ it("drops an exact duplicate of the last entry", () => {
+ const existing: TranscriptEntry[] = [{ speaker: "Alice", text: "hi", timestamp: "00:00:01" }]
+ const result = deduplicateCaptions(existing, [{ speaker: "Alice", text: "hi" }], START, NOW)
+ expect(result).toHaveLength(1)
+ expect(result[0]!.timestamp).toBe("00:00:01")
+ })
+
+ it("extends the last entry when same speaker and incoming text is a superset", () => {
+ const existing: TranscriptEntry[] = [{ speaker: "Alice", text: "hello", timestamp: "00:00:01" }]
+ const result = deduplicateCaptions(existing, [{ speaker: "Alice", text: "hello world" }], START, NOW)
+ expect(result).toHaveLength(1)
+ expect(result[0]!.text).toBe("hello world")
+ // extension keeps the original timestamp
+ expect(result[0]!.timestamp).toBe("00:00:01")
+ })
+
+ it("creates a new entry when the speaker changes", () => {
+ const existing: TranscriptEntry[] = [{ speaker: "Alice", text: "hello", timestamp: "00:00:01" }]
+ const result = deduplicateCaptions(existing, [{ speaker: "Bob", text: "hello" }], START, NOW)
+ expect(result).toHaveLength(2)
+ expect(result[1]).toEqual({ speaker: "Bob", text: "hello", timestamp: "00:00:12" })
+ })
+
+ it("only extends against pre-existing entries, not ones pushed in the same call", () => {
+ // `last` is read from `existing` only; entries pushed during this call land in a
+ // separate buffer, so the "superset extends last" rule does NOT apply transitively
+ // within a single invocation. Documents the actual contract.
+ const result = deduplicateCaptions(
+ [],
+ [
+ { speaker: "Alice", text: "a" },
+ { speaker: "Alice", text: "a b" },
+ { speaker: "Bob", text: "c" },
+ ],
+ START,
+ NOW,
+ )
+ expect(result.map((e) => `${e.speaker}:${e.text}`)).toEqual(["Alice:a", "Alice:a b", "Bob:c"])
+ })
+
+ it("extends across calls when the superset arrives in a later batch", () => {
+ const first = deduplicateCaptions([], [{ speaker: "Alice", text: "hello" }], START, NOW)
+ const second = deduplicateCaptions(first, [{ speaker: "Alice", text: "hello world" }], START, NOW)
+ expect(second).toHaveLength(1)
+ expect(second[0]!.text).toBe("hello world")
+ })
+
+ it("returns existing unchanged for empty incoming", () => {
+ const existing: TranscriptEntry[] = [{ speaker: "Alice", text: "hi", timestamp: "00:00:01" }]
+ expect(deduplicateCaptions(existing, [], START, NOW)).toEqual(existing)
+ })
+})
+
+describe("groupIntoBlocks", () => {
+ it("groups consecutive same-speaker entries into one block", () => {
+ const blocks = groupIntoBlocks([
+ { speaker: "Alice", text: "one", timestamp: "00:00:01" },
+ { speaker: "Alice", text: "two", timestamp: "00:00:02" },
+ { speaker: "Bob", text: "three", timestamp: "00:00:03" },
+ ])
+ expect(blocks).toEqual([
+ { speaker: "Alice", lines: ["one", "two"], startTimestamp: "00:00:01" },
+ { speaker: "Bob", lines: ["three"], startTimestamp: "00:00:03" },
+ ])
+ })
+
+ it("returns empty for empty input", () => {
+ expect(groupIntoBlocks([])).toEqual([])
+ })
+})
+
+describe("formatTranscript", () => {
+ it("returns empty string for no entries", () => {
+ expect(formatTranscript([])).toBe("")
+ })
+
+ it("formats a single speaker block", () => {
+ const out = formatTranscript([
+ { speaker: "Alice", text: "hello", timestamp: "00:00:01" },
+ { speaker: "Alice", text: "again", timestamp: "00:00:02" },
+ ])
+ expect(out).toBe("[00:00:01] Alice:\nhello\nagain")
+ })
+
+ it("separates speaker blocks with a blank line and keeps ordering", () => {
+ const out = formatTranscript([
+ { speaker: "Alice", text: "hi", timestamp: "00:00:01" },
+ { speaker: "Bob", text: "yo", timestamp: "00:00:05" },
+ ])
+ expect(out).toBe("[00:00:01] Alice:\nhi\n\n[00:00:05] Bob:\nyo")
+ })
+})
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts
new file mode 100644
index 000000000..193eebf06
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts
@@ -0,0 +1,131 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockEmailWorkerFetch = vi.fn().mockResolvedValue(new Response("ok"));
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },
+ })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("@alook/shared/crypto", () => ({ encrypt: vi.fn((v: string) => `enc(${v})`) }));
+
+const mockGetScoped = vi.fn();
+const mockUpdate = vi.fn();
+const mockDelete = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ emailAccount: {
+ getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a),
+ updateEmailAccount: (...a: unknown[]) => mockUpdate(...a),
+ deleteEmailAccount: (...a: unknown[]) => mockDelete(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: {
+ allEmailAccounts: (w: string) => `ea:${w}`,
+ overviewEmailAccounts: (w: string) => `ov_ea:${w}`,
+ },
+}));
+
+import { PATCH, DELETE } from "./route";
+
+const ROW = {
+ id: "acc1", agentId: "a1", workspaceId: "w1", emailAddress: "[email protected]", displayName: "X",
+ imapHost: "imap", imapPort: 993, imapTls: 1, smtpHost: "smtp", smtpPort: 465, smtpTls: 1,
+ pollIntervalSeconds: 60, lastSyncedAt: null, status: "active", errorMessage: null,
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+const params = { id: "a1", accountId: "acc1" };
+
+describe("PATCH /api/agents/[id]/email-accounts/[accountId]", () => {
+ function patch(body: unknown, p = params) {
+ return PATCH(
+ new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1", {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ { params: p },
+ );
+ }
+
+ it("updates a scoped account (display name only, no worker restart)", async () => {
+ mockGetScoped.mockResolvedValue(ROW);
+ mockUpdate.mockResolvedValue(ROW);
+ const res = await patch({ displayName: "New" });
+ expect(res.status).toBe(200);
+ expect(mockGetScoped).toHaveBeenCalledWith({}, "acc1", "a1", "w1");
+ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();
+ });
+
+ it("restarts the worker when credentials change", async () => {
+ mockGetScoped.mockResolvedValue(ROW);
+ mockUpdate.mockResolvedValue(ROW);
+ const res = await patch({ imapPassword: "newpass" });
+ expect(res.status).toBe(200);
+ // stop + start
+ expect(mockEmailWorkerFetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("400 when params missing", async () => {
+ const res = await patch({ displayName: "x" }, { id: "a1" } as any);
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when account not scoped to agent/workspace (IDOR guard)", async () => {
+ mockGetScoped.mockResolvedValue(null);
+ const res = await patch({ displayName: "x" });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe("DELETE /api/agents/[id]/email-accounts/[accountId]", () => {
+ function del(p = params) {
+ return DELETE(
+ new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1", { method: "DELETE" }),
+ { params: p },
+ );
+ }
+
+ it("stops the worker and deletes a scoped account", async () => {
+ mockGetScoped.mockResolvedValue(ROW);
+ mockDelete.mockResolvedValue(ROW);
+ const res = await del();
+ expect(res.status).toBe(200);
+ expect((await res.json()).ok).toBe(true);
+ expect(mockDelete).toHaveBeenCalledWith({}, "acc1", "w1");
+ expect(mockEmailWorkerFetch).toHaveBeenCalled();
+ });
+
+ it("404 when account not scoped", async () => {
+ mockGetScoped.mockResolvedValue(null);
+ const res = await del();
+ expect(res.status).toBe(404);
+ });
+
+ it("400 when params missing", async () => {
+ const res = await del({ id: "a1" } as any);
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts
new file mode 100644
index 000000000..266172b31
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts
@@ -0,0 +1,66 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockEmailWorkerFetch = vi.fn().mockResolvedValue(new Response("ok"));
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: { DB: {}, EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },
+ })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetScoped = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: { emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) } },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+function post(params: Record<string, string>) {
+ return POST(
+ new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1/sync", { method: "POST" }),
+ { params },
+ );
+}
+
+describe("POST .../email-accounts/[accountId]/sync", () => {
+ it("triggers a worker sync for a scoped account", async () => {
+ mockGetScoped.mockResolvedValue({ id: "acc1" });
+ const res = await post({ id: "a1", accountId: "acc1" });
+ expect(res.status).toBe(200);
+ expect((await res.json()).ok).toBe(true);
+ expect(mockGetScoped).toHaveBeenCalledWith({}, "acc1", "a1", "w1");
+ expect(mockEmailWorkerFetch).toHaveBeenCalledWith(
+ expect.stringContaining("/imap/sync?accountId=acc1"),
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
+
+ it("400 when params missing", async () => {
+ const res = await post({ id: "a1" });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when account not scoped (IDOR guard)", async () => {
+ mockGetScoped.mockResolvedValue(null);
+ const res = await post({ id: "a1", accountId: "acc1" });
+ expect(res.status).toBe(404);
+ expect(mockEmailWorkerFetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts
new file mode 100644
index 000000000..875accda6
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts
@@ -0,0 +1,72 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockEmailWorkerFetch = vi.fn();
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: { DB: {}, EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },
+ })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetScoped = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: { emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) } },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+function post(params: Record<string, string>) {
+ return POST(
+ new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1/test", { method: "POST" }),
+ { params },
+ );
+}
+
+describe("POST .../email-accounts/[accountId]/test", () => {
+ it("forwards the worker test result and its status", async () => {
+ mockGetScoped.mockResolvedValue({ id: "acc1" });
+ mockEmailWorkerFetch.mockResolvedValue(
+ new Response(JSON.stringify({ ok: true, folders: 3 }), { status: 200 }),
+ );
+ const res = await post({ id: "a1", accountId: "acc1" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ ok: true, folders: 3 });
+ });
+
+ it("propagates a non-200 worker status (e.g. failed auth → 401)", async () => {
+ mockGetScoped.mockResolvedValue({ id: "acc1" });
+ mockEmailWorkerFetch.mockResolvedValue(
+ new Response(JSON.stringify({ error: "auth failed" }), { status: 401 }),
+ );
+ const res = await post({ id: "a1", accountId: "acc1" });
+ expect(res.status).toBe(401);
+ });
+
+ it("400 when params missing", async () => {
+ const res = await post({ id: "a1" });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when account not scoped", async () => {
+ mockGetScoped.mockResolvedValue(null);
+ const res = await post({ id: "a1", accountId: "acc1" });
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts
new file mode 100644
index 000000000..79cded18b
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts
@@ -0,0 +1,125 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockEmailWorkerFetch = vi.fn().mockResolvedValue(new Response("ok"));
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({
+ env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },
+ })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("@alook/shared/crypto", () => ({ encrypt: vi.fn((v: string) => `enc(${v})`) }));
+
+const mockGetAgent = vi.fn();
+const mockGetAccounts = vi.fn();
+const mockCreateAccount = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ emailAccount: {
+ getEmailAccountsByAgent: (...a: unknown[]) => mockGetAccounts(...a),
+ createEmailAccount: (...a: unknown[]) => mockCreateAccount(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: {
+ allEmailAccounts: (w: string) => `ea:${w}`,
+ overviewEmailAccounts: (w: string) => `ov_ea:${w}`,
+ },
+}));
+
+import { GET, POST } from "./route";
+
+const ACCOUNT_ROW = {
+ id: "acc1", agentId: "a1", workspaceId: "w1", emailAddress: "[email protected]", displayName: "X",
+ imapHost: "imap", imapPort: 993, imapTls: 1, smtpHost: "smtp", smtpPort: 465, smtpTls: 1,
+ pollIntervalSeconds: 60, lastSyncedAt: null, status: "active", errorMessage: null,
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
+};
+
+const VALID_BODY = {
+ emailAddress: "[email protected]", displayName: "X", imapHost: "imap", imapPort: 993,
+ imapUsername: "u", imapPassword: "p", imapTls: true, smtpHost: "smtp", smtpPort: 465,
+ smtpUsername: "su", smtpPassword: "sp", smtpTls: 1, pollIntervalSeconds: 60,
+};
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/agents/[id]/email-accounts", () => {
+ it("lists accounts scoped to agent + workspace", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockGetAccounts.mockResolvedValue([ACCOUNT_ROW]);
+ const req = new NextRequest("http://localhost/api/agents/a1/email-accounts");
+ const res = await GET(req, { params: { id: "a1" } });
+ const body = await res.json();
+ expect(res.status).toBe(200);
+ expect(body[0].id).toBe("acc1");
+ expect(mockGetAccounts).toHaveBeenCalledWith({}, "a1", "w1");
+ });
+
+ it("400 when agent id missing", async () => {
+ const req = new NextRequest("http://localhost/api/agents/x/email-accounts");
+ const res = await GET(req, { params: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when agent not in workspace", async () => {
+ mockGetAgent.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/agents/a1/email-accounts");
+ const res = await GET(req, { params: { id: "a1" } });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe("POST /api/agents/[id]/email-accounts", () => {
+ function post(body: unknown) {
+ return POST(
+ new NextRequest("http://localhost/api/agents/a1/email-accounts", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ { params: { id: "a1" } },
+ );
+ }
+
+ it("creates an account, encrypts credentials, starts the worker (201)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockCreateAccount.mockResolvedValue(ACCOUNT_ROW);
+ const res = await post(VALID_BODY);
+ expect(res.status).toBe(201);
+ const createArgs = mockCreateAccount.mock.calls[0]![1] as Record<string, unknown>;
+ expect(createArgs.workspaceId).toBe("w1");
+ expect(createArgs.imapPassword).toBe("enc(p)");
+ expect(mockEmailWorkerFetch).toHaveBeenCalled();
+ });
+
+ it("404 when agent not in workspace", async () => {
+ mockGetAgent.mockResolvedValue(null);
+ const res = await post(VALID_BODY);
+ expect(res.status).toBe(404);
+ });
+
+ it("400 on invalid body", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ const res = await post({ emailAddress: "[email protected]" });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts
new file mode 100644
index 000000000..46ccc269c
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+import { MeetingStatus } from "@alook/shared";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGet = vi.fn();
+const mockUpdate = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ meetingSession: {
+ getMeetingSession: (...a: unknown[]) => mockGet(...a),
+ updateMeetingSession: (...a: unknown[]) => mockUpdate(...a),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id, status: m.status }) }));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const params = { id: "a1", meetingId: "m1" };
+const post = () => POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });
+
+describe("POST .../meetings/[meetingId]/approve", () => {
+ it("approves a pending meeting → scheduled", async () => {
+ mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.PENDING });
+ mockUpdate.mockResolvedValue({ id: "m1", status: MeetingStatus.SCHEDULED });
+ const res = await post();
+ expect(res.status).toBe(200);
+ expect(mockUpdate).toHaveBeenCalledWith({}, "m1", "w1", { status: MeetingStatus.SCHEDULED });
+ });
+
+ it("400 when meeting id missing", async () => {
+ const res = await POST(new NextRequest("http://localhost/x", { method: "POST" }), { params: { id: "a1" } });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when meeting not in workspace", async () => {
+ mockGet.mockResolvedValue(null);
+ const res = await post();
+ expect(res.status).toBe(404);
+ });
+
+ it("400 when meeting is not pending", async () => {
+ mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.SCHEDULED });
+ const res = await post();
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("only pending meetings can be approved");
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts
new file mode 100644
index 000000000..7b79d6224
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGet = vi.fn();
+const mockDelete = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ meetingSession: {
+ getMeetingSession: (...a: unknown[]) => mockGet(...a),
+ deleteMeetingSession: (...a: unknown[]) => mockDelete(...a),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id }) }));
+
+import { GET, DELETE } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/agents/[id]/meetings/[meetingId]", () => {
+ it("returns a meeting scoped to workspace", async () => {
+ mockGet.mockResolvedValue({ id: "m1" });
+ const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "a1", meetingId: "m1" } });
+ expect(res.status).toBe(200);
+ expect(mockGet).toHaveBeenCalledWith({}, "m1", "w1");
+ });
+
+ it("400 when meeting id missing", async () => {
+ const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "a1" } });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when meeting not in workspace (IDOR guard)", async () => {
+ mockGet.mockResolvedValue(null);
+ const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "a1", meetingId: "m1" } });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe("DELETE /api/agents/[id]/meetings/[meetingId]", () => {
+ it("deletes a scoped meeting", async () => {
+ mockDelete.mockResolvedValue({ id: "m1" });
+ const res = await DELETE(new NextRequest("http://localhost/x", { method: "DELETE" }), {
+ params: { id: "a1", meetingId: "m1" },
+ });
+ expect(res.status).toBe(200);
+ expect((await res.json()).ok).toBe(true);
+ expect(mockDelete).toHaveBeenCalledWith({}, "m1", "w1");
+ });
+
+ it("404 when meeting not found in workspace", async () => {
+ mockDelete.mockResolvedValue(null);
+ const res = await DELETE(new NextRequest("http://localhost/x", { method: "DELETE" }), {
+ params: { id: "a1", meetingId: "m1" },
+ });
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts
new file mode 100644
index 000000000..b86a81c00
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+import { MeetingStatus } from "@alook/shared";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGet = vi.fn();
+const mockUpdate = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ meetingSession: {
+ getMeetingSession: (...a: unknown[]) => mockGet(...a),
+ updateMeetingSession: (...a: unknown[]) => mockUpdate(...a),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id, status: m.status }) }));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const params = { id: "a1", meetingId: "m1" };
+const post = () => POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });
+
+describe("POST .../meetings/[meetingId]/stop", () => {
+ it("stops a recording meeting → completed", async () => {
+ mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.RECORDING });
+ mockUpdate.mockResolvedValue({ id: "m1", status: MeetingStatus.COMPLETED });
+ const res = await post();
+ expect(res.status).toBe(200);
+ expect(mockUpdate.mock.calls[0]![3]).toMatchObject({ status: MeetingStatus.COMPLETED });
+ });
+
+ it("stops a joining meeting too", async () => {
+ mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.JOINING });
+ mockUpdate.mockResolvedValue({ id: "m1", status: MeetingStatus.COMPLETED });
+ const res = await post();
+ expect(res.status).toBe(200);
+ });
+
+ it("400 when meeting is not active (e.g. scheduled)", async () => {
+ mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.SCHEDULED });
+ const res = await post();
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("meeting is not active");
+ });
+
+ it("404 when meeting not in workspace", async () => {
+ mockGet.mockResolvedValue(null);
+ const res = await post();
+ expect(res.status).toBe(404);
+ });
+
+ it("400 when meeting id missing", async () => {
+ const res = await POST(new NextRequest("http://localhost/x", { method: "POST" }), { params: { id: "a1" } });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/meetings/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/route.test.ts
new file mode 100644
index 000000000..3b12dabaa
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/meetings/route.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockList = vi.fn();
+const mockGetAgent = vi.fn();
+const mockCreate = vi.fn();
+const mockGet = vi.fn();
+const mockGetRuntime = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ meetingSession: {
+ listMeetingSessions: (...a: unknown[]) => mockList(...a),
+ createMeetingSession: (...a: unknown[]) => mockCreate(...a),
+ getMeetingSession: (...a: unknown[]) => mockGet(...a),
+ },
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ runtime: { getAgentRuntime: (...a: unknown[]) => mockGetRuntime(...a) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id, status: m.status }) }));
+vi.mock("@/lib/broadcast", () => ({ broadcastToDaemon: vi.fn().mockResolvedValue(undefined) }));
+
+import { GET, POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const VALID_URL = "https://meet.google.com/abc-defg-hij";
+
+describe("GET /api/agents/[id]/meetings", () => {
+ it("lists meetings scoped to agent + workspace", async () => {
+ mockList.mockResolvedValue([{ id: "m1", status: "completed" }]);
+ const req = new NextRequest("http://localhost/api/agents/a1/meetings");
+ const res = await GET(req, { params: { id: "a1" } });
+ expect(res.status).toBe(200);
+ expect(mockList).toHaveBeenCalledWith({}, "a1", "w1");
+ });
+
+ it("400 when agent id missing", async () => {
+ const req = new NextRequest("http://localhost/api/agents/x/meetings");
+ const res = await GET(req, { params: {} });
+ expect(res.status).toBe(400);
+ });
+});
+
+describe("POST /api/agents/[id]/meetings", () => {
+ function post(body: unknown, id = "a1") {
+ return POST(
+ new NextRequest("http://localhost/api/agents/a1/meetings", {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ { params: { id } },
+ );
+ }
+
+ it("creates a scheduled meeting with a valid Meet URL (201)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: null, name: "A" });
+ mockCreate.mockResolvedValue({ id: "m1" });
+ mockGet.mockResolvedValue({ id: "m1", status: "scheduled", meetingUrl: VALID_URL, participants: [] });
+
+ const res = await post({ meetingUrl: VALID_URL });
+ expect(res.status).toBe(201);
+ expect(mockCreate.mock.calls[0]![1]).toMatchObject({ workspaceId: "w1", agentId: "a1" });
+ });
+
+ it("404 when agent not in workspace", async () => {
+ mockGetAgent.mockResolvedValue(null);
+ const res = await post({ meetingUrl: VALID_URL });
+ expect(res.status).toBe(404);
+ });
+
+ it("400 when meetingUrl missing", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ const res = await post({});
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("meetingUrl is required");
+ });
+
+ it("400 for a malformed Meet URL", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ const res = await post({ meetingUrl: "https://zoom.us/j/123" });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("invalid Google Meet URL format");
+ });
+
+ it("400 on invalid JSON body", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ const req = new NextRequest("http://localhost/api/agents/a1/meetings", {
+ method: "POST",
+ body: "not json",
+ });
+ const res = await POST(req, { params: { id: "a1" } });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/skills/route.test.ts b/src/web/src/app/api/agents/[id]/skills/route.test.ts
new file mode 100644
index 000000000..bc6a6ebb6
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/skills/route.test.ts
@@ -0,0 +1,82 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetAgent = vi.fn();
+const mockGetRuntime = vi.fn();
+const mockGetSkills = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ runtime: { getAgentRuntime: (...a: unknown[]) => mockGetRuntime(...a) },
+ agentSkill: { getSkills: (...a: unknown[]) => mockGetSkills(...a) },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+function get(url: string, params: Record<string, string>) {
+ return GET(new NextRequest(url), { params });
+}
+
+describe("GET /api/agents/[id]/skills", () => {
+ it("400 when agent id missing", async () => {
+ const res = await get("http://localhost/x?workspace_id=w1", {});
+ expect(res.status).toBe(400);
+ });
+
+ it("400 when workspace_id missing", async () => {
+ const res = await get("http://localhost/x", { id: "a1" });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when agent not found in workspace", async () => {
+ mockGetAgent.mockResolvedValue(null);
+ const res = await get("http://localhost/x?workspace_id=w1", { id: "a1" });
+ expect(res.status).toBe(404);
+ expect(mockGetAgent).toHaveBeenCalledWith({}, "a1", "w1", "u1");
+ });
+
+ it("returns skills for the agent's runtime provider", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: "rt1" });
+ mockGetRuntime.mockResolvedValue({ provider: "codex" });
+ mockGetSkills.mockResolvedValue([{ name: "skill-a" }]);
+ const res = await get("http://localhost/x?workspace_id=w1", { id: "a1" });
+ const body = await res.json();
+ expect(res.status).toBe(200);
+ expect(body.skills).toEqual([{ name: "skill-a" }]);
+ expect(mockGetSkills).toHaveBeenCalledWith({}, "a1", "codex", "w1");
+ });
+
+ it("defaults to claude when the runtime provider is unknown", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: "rt1" });
+ mockGetRuntime.mockResolvedValue({ provider: "weird-runtime" });
+ mockGetSkills.mockResolvedValue([]);
+ await get("http://localhost/x?workspace_id=w1", { id: "a1" });
+ expect(mockGetSkills).toHaveBeenCalledWith({}, "a1", "claude", "w1");
+ });
+
+ it("defaults to claude when agent has no runtimeId", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: null });
+ mockGetSkills.mockResolvedValue([]);
+ await get("http://localhost/x?workspace_id=w1", { id: "a1" });
+ expect(mockGetSkills).toHaveBeenCalledWith({}, "a1", "claude", "w1");
+ expect(mockGetRuntime).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/web/src/app/api/agents/active-tasks/route.test.ts b/src/web/src/app/api/agents/active-tasks/route.test.ts
new file mode 100644
index 000000000..fb9e93b3d
--- /dev/null
+++ b/src/web/src/app/api/agents/active-tasks/route.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockListActive = vi.fn();
+const mockGetAllAgents = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ task: { listActiveTasksByWorkspace: (...a: unknown[]) => mockListActive(...a) },
+ agent: { getAllAgentsForWorkspace: (...a: unknown[]) => mockGetAllAgents(...a) },
+ agentAccess: { getAllAgentAccessForWorkspace: vi.fn().mockResolvedValue([]) },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),
+ cacheKeys: { allAgents: (w: string) => `ag:${w}`, allAgentAccess: (w: string) => `aa:${w}` },
+}));
+vi.mock("@/lib/agent-visibility", () => ({ filterVisibleAgents: vi.fn((a: any[]) => a) }));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/agents/active-tasks", () => {
+ it("returns active tasks joined with visible agent info", async () => {
+ mockListActive.mockResolvedValue([
+ { id: "t1", agentId: "a1", prompt: "do x", status: "running", type: "dm", conversationId: "c1", channel: null, createdAt: "2026-05-30" },
+ ]);
+ mockGetAllAgents.mockResolvedValue([{ id: "a1", name: "Agent 1", avatarUrl: "u" }]);
+
+ const res = await GET(new NextRequest("http://localhost/x"), {});
+ const body = await res.json();
+ expect(res.status).toBe(200);
+ expect(body.tasks[0]).toMatchObject({
+ id: "t1", agent_id: "a1", agent: { name: "Agent 1", avatarUrl: "u" }, channel: "default",
+ });
+ expect(mockListActive).toHaveBeenCalledWith({}, "w1");
+ });
+
+ it("yields null agent when the task's agent isn't visible", async () => {
+ mockListActive.mockResolvedValue([
+ { id: "t1", agentId: "hidden", prompt: "x", status: "running", type: "dm", conversationId: "c1", channel: "ops", createdAt: "d" },
+ ]);
+ mockGetAllAgents.mockResolvedValue([]);
+ const res = await GET(new NextRequest("http://localhost/x"), {});
+ const body = await res.json();
+ expect(body.tasks[0].agent).toBeNull();
+ expect(body.tasks[0].channel).toBe("ops");
+ });
+});
diff --git a/src/web/src/app/api/agents/pins/reorder/route.test.ts b/src/web/src/app/api/agents/pins/reorder/route.test.ts
new file mode 100644
index 000000000..b8eb815a4
--- /dev/null
+++ b/src/web/src/app/api/agents/pins/reorder/route.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockListPins = vi.fn();
+const mockReorderPins = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agentPin: {
+ listPins: (...a: unknown[]) => mockListPins(...a),
+ reorderPins: (...a: unknown[]) => mockReorderPins(...a),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: { pins: (w: string, u: string) => `pins:${w}:${u}` },
+}));
+
+import { PUT } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+function put(body: unknown) {
+ return PUT(new NextRequest("http://localhost/x", { method: "PUT", body: JSON.stringify(body) }), {});
+}
+
+describe("PUT /api/agents/pins/reorder", () => {
+ it("reorders pins when all ids are pinned (204)", async () => {
+ mockListPins.mockResolvedValue([{ agentId: "a1" }, { agentId: "a2" }]);
+ const res = await put({ ordered_agent_ids: ["a2", "a1"] });
+ expect(res.status).toBe(204);
+ expect(mockReorderPins).toHaveBeenCalledWith({}, "w1", "u1", ["a2", "a1"]);
+ });
+
+ it("400 on invalid JSON body", async () => {
+ const res = await PUT(new NextRequest("http://localhost/x", { method: "PUT", body: "nope" }), {});
+ expect(res.status).toBe(400);
+ });
+
+ it("400 when ordered_agent_ids is not a non-empty string array", async () => {
+ const res = await put({ ordered_agent_ids: [] });
+ expect(res.status).toBe(400);
+ });
+
+ it("400 when an id is not pinned", async () => {
+ mockListPins.mockResolvedValue([{ agentId: "a1" }]);
+ const res = await put({ ordered_agent_ids: ["a1", "a2"] });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("not pinned");
+ });
+});
diff --git a/src/web/src/app/api/agents/recruit/route.test.ts b/src/web/src/app/api/agents/recruit/route.test.ts
new file mode 100644
index 000000000..e347f44bb
--- /dev/null
+++ b/src/web/src/app/api/agents/recruit/route.test.ts
@@ -0,0 +1,126 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { put: vi.fn() }, WORKER_SELF_REFERENCE: { fetch: vi.fn() } } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "id123") }));
+vi.mock("unique-names-generator", () => ({
+ uniqueNamesGenerator: vi.fn(() => "Robin"),
+ names: [],
+}));
+vi.mock("@/components/avatar", () => ({
+ randomConfig: vi.fn(() => ({})),
+ serializeAvatarConfig: vi.fn(() => "avatar-url"),
+}));
+
+const mockGetAgent = vi.fn();
+const mockGetRuntimeForWs = vi.fn();
+const mockGetAllHandles = vi.fn();
+const mockCreateAgent = vi.fn();
+const mockLinkCreate = vi.fn();
+const mockAddWhitelist = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: {
+ getAgent: (...a: unknown[]) => mockGetAgent(...a),
+ getAllHandlesForWorkspace: (...a: unknown[]) => mockGetAllHandles(...a),
+ createAgent: (...a: unknown[]) => mockCreateAgent(...a),
+ },
+ runtime: { getAgentRuntimeForWorkspace: (...a: unknown[]) => mockGetRuntimeForWs(...a) },
+ agentLink: { create: (...a: unknown[]) => mockLinkCreate(...a) },
+ whitelist: { addWhitelist: (...a: unknown[]) => mockAddWhitelist(...a) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({
+ agentToResponse: (a: any) => ({ id: a.id, name: a.name }),
+ agentLinkToResponse: (l: any) => ({ id: l.id }),
+}));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),
+ cacheKeys: {
+ allAgents: () => "a", allHandles: () => "h", allAgentAccess: () => "aa",
+ allColleagues: () => "c", agentLinks: () => "al",
+ },
+}));
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const VALID = { instructions: "do things", relationship: "reports to me" };
+
+function post(body: unknown, qs = "?agentId=caller") {
+ return POST(
+ new NextRequest(`http://localhost/api/agents/recruit${qs}`, {
+ method: "POST",
+ body: JSON.stringify(body),
+ }),
+ {},
+ );
+}
+
+describe("POST /api/agents/recruit", () => {
+ it("400 when agentId query param missing", async () => {
+ const res = await post(VALID, "");
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("agentId");
+ });
+
+ it("400 on invalid body (missing instructions/relationship)", async () => {
+ const res = await post({ name: "X" });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when calling agent not in workspace", async () => {
+ mockGetAgent.mockResolvedValue(null);
+ const res = await post(VALID);
+ expect(res.status).toBe(404);
+ expect(mockGetAgent).toHaveBeenCalledWith({}, "caller", "w1");
+ });
+
+ it("400 when calling agent has no runtime", async () => {
+ mockGetAgent.mockResolvedValue({ id: "caller", runtimeId: "rt1", emailHandle: null });
+ mockGetRuntimeForWs.mockResolvedValue(null);
+ const res = await post(VALID);
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("no runtime");
+ });
+
+ it("creates a recruited agent + link, scoped to workspace (201)", async () => {
+ mockGetAgent.mockResolvedValue({ id: "caller", runtimeId: "rt1", emailHandle: null, name: "Caller" });
+ mockGetRuntimeForWs.mockResolvedValue({ runtimeMode: "local", machineLastSeenAt: null });
+ mockGetAllHandles.mockResolvedValue([]);
+ mockCreateAgent.mockResolvedValue({ id: "new1", name: "Robin" });
+ mockLinkCreate.mockResolvedValue({ id: "link1" });
+
+ const res = await post(VALID);
+ const body = await res.json();
+ expect(res.status).toBe(201);
+ expect(body.agent.id).toBe("new1");
+ expect(body.agent.email).toBe("[email protected]");
+ expect(body.link.id).toBe("link1");
+ expect(mockCreateAgent.mock.calls[0]![1]).toMatchObject({ workspaceId: "w1", ownerId: "u1" });
+ expect(mockLinkCreate.mock.calls[0]![1]).toMatchObject({
+ workspaceId: "w1", sourceAgentId: "caller", targetAgentId: "new1",
+ });
+ });
+});
diff --git a/src/web/src/app/api/agents/sidebar/reorder/route.test.ts b/src/web/src/app/api/agents/sidebar/reorder/route.test.ts
new file mode 100644
index 000000000..cf90c470a
--- /dev/null
+++ b/src/web/src/app/api/agents/sidebar/reorder/route.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetAllAgents = vi.fn();
+const mockListPins = vi.fn();
+const mockReorder = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: { getAllAgentsForWorkspace: (...a: unknown[]) => mockGetAllAgents(...a) },
+ agentPin: { listPins: (...a: unknown[]) => mockListPins(...a) },
+ agentSidebarOrder: { reorder: (...a: unknown[]) => mockReorder(...a) },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: { allAgents: (w: string) => `ag:${w}`, pins: (w: string, u: string) => `pins:${w}:${u}` },
+}));
+
+import { PUT } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const put = (body: unknown) =>
+ PUT(new NextRequest("http://localhost/x", { method: "PUT", body: JSON.stringify(body) }), {});
+
+describe("PUT /api/agents/sidebar/reorder", () => {
+ it("reorders sidebar for unpinned workspace agents (204)", async () => {
+ mockGetAllAgents.mockResolvedValue([{ id: "a1" }, { id: "a2" }]);
+ mockListPins.mockResolvedValue([]);
+ const res = await put({ ordered_agent_ids: ["a2", "a1"] });
+ expect(res.status).toBe(204);
+ expect(mockReorder).toHaveBeenCalledWith({}, "w1", "u1", ["a2", "a1"]);
+ });
+
+ it("400 when an id is not a workspace agent", async () => {
+ mockGetAllAgents.mockResolvedValue([{ id: "a1" }]);
+ mockListPins.mockResolvedValue([]);
+ const res = await put({ ordered_agent_ids: ["a1", "ghost"] });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("not found");
+ });
+
+ it("400 when an id is pinned (pinned agents are excluded from sidebar order)", async () => {
+ mockGetAllAgents.mockResolvedValue([{ id: "a1" }, { id: "a2" }]);
+ mockListPins.mockResolvedValue([{ agentId: "a1" }]);
+ const res = await put({ ordered_agent_ids: ["a1", "a2"] });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("is pinned");
+ });
+
+ it("400 on empty array", async () => {
+ const res = await put({ ordered_agent_ids: [] });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/artifacts/route.test.ts b/src/web/src/app/api/artifacts/route.test.ts
new file mode 100644
index 000000000..bbea0d463
--- /dev/null
+++ b/src/web/src/app/api/artifacts/route.test.ts
@@ -0,0 +1,52 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockList = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ artifact: {
+ listArtifactsByConversation: (...a: unknown[]) => mockList(...a),
+ artifactToResponse: (a: any) => ({ id: a.id }),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/artifacts", () => {
+ it("lists artifacts for a conversation scoped to workspace", async () => {
+ mockList.mockResolvedValue([{ id: "art_1" }, { id: "art_2" }]);
+ const req = new NextRequest("http://localhost/api/artifacts?conversation_id=c1");
+ const res = await GET(req, {});
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual([{ id: "art_1" }, { id: "art_2" }]);
+ expect(mockList).toHaveBeenCalledWith({}, "c1", "w1");
+ });
+
+ it("400 when conversation_id missing", async () => {
+ const req = new NextRequest("http://localhost/api/artifacts");
+ const res = await GET(req, {});
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("conversation_id is required");
+ });
+});
diff --git a/src/web/src/app/api/artifacts/upload/route.test.ts b/src/web/src/app/api/artifacts/upload/route.test.ts
new file mode 100644
index 000000000..a72c4f1f6
--- /dev/null
+++ b/src/web/src/app/api/artifacts/upload/route.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockPut = vi.fn().mockResolvedValue(undefined);
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { put: mockPut } } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "xyz") }));
+
+const mockGetConversation = vi.fn();
+const mockCreateArtifact = vi.fn();
+const mockGetAgent = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },
+ artifact: {
+ createArtifact: (...a: unknown[]) => mockCreateArtifact(...a),
+ artifactToResponse: (a: any) => ({ id: a.id }),
+ },
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
+
+import { POST } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+function formReq(fields: Record<string, string | File>) {
+ const fd = new FormData();
+ for (const [k, v] of Object.entries(fields)) fd.append(k, v as any);
+ return new NextRequest("http://localhost/api/artifacts/upload", { method: "POST", body: fd });
+}
+
+describe("POST /api/artifacts/upload", () => {
+ it("uploads a file to R2 and creates an artifact record", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockCreateArtifact.mockResolvedValue({ id: "art_xyz" });
+ mockGetAgent.mockResolvedValue({ ownerId: "owner1" });
+
+ const file = new File(["hello"], "note.txt", { type: "text/plain" });
+ const res = await POST(formReq({ file, conversation_id: "c1" }), {});
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ id: "art_xyz" });
+ expect(mockPut).toHaveBeenCalled();
+ expect(mockCreateArtifact.mock.calls[0]![1]).toMatchObject({ workspaceId: "w1", conversationId: "c1" });
+ });
+
+ it("400 when file missing", async () => {
+ const res = await POST(formReq({ conversation_id: "c1" }), {});
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("file is required");
+ });
+
+ it("400 when conversation_id missing", async () => {
+ const file = new File(["x"], "a.txt", { type: "text/plain" });
+ const res = await POST(formReq({ file }), {});
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("conversation_id is required");
+ });
+
+ it("413 when file exceeds the size limit", async () => {
+ // 10 MB + 1 byte
+ const big = new File([new Uint8Array(10 * 1024 * 1024 + 1)], "big.bin", { type: "application/octet-stream" });
+ const res = await POST(formReq({ file: big, conversation_id: "c1" }), {});
+ expect(res.status).toBe(413);
+ });
+
+ it("404 when conversation not in workspace", async () => {
+ mockGetConversation.mockResolvedValue(null);
+ const file = new File(["x"], "a.txt", { type: "text/plain" });
+ const res = await POST(formReq({ file, conversation_id: "c1" }), {});
+ expect(res.status).toBe(404);
+ });
+
+ it("400 on non-multipart body (invalid form data)", async () => {
+ const req = new NextRequest("http://localhost/api/artifacts/upload", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: "{}",
+ });
+ const res = await POST(req, {});
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/channels/reorder/route.test.ts b/src/web/src/app/api/channels/reorder/route.test.ts
new file mode 100644
index 000000000..fd2a0374a
--- /dev/null
+++ b/src/web/src/app/api/channels/reorder/route.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockListChannels = vi.fn();
+const mockReorderChannels = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ channel: {
+ listChannels: (...a: unknown[]) => mockListChannels(...a),
+ reorderChannels: (...a: unknown[]) => mockReorderChannels(...a),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { PUT } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const put = (body: unknown) =>
+ PUT(new NextRequest("http://localhost/x", { method: "PUT", body: JSON.stringify(body) }), {});
+
+describe("PUT /api/channels/reorder", () => {
+ it("reorders existing workspace channels (204)", async () => {
+ mockListChannels.mockResolvedValue([{ id: "ch1" }, { id: "ch2" }]);
+ const res = await put({ ordered_channel_ids: ["ch2", "ch1"] });
+ expect(res.status).toBe(204);
+ expect(mockReorderChannels).toHaveBeenCalledWith({}, "w1", ["ch2", "ch1"]);
+ });
+
+ it("400 when trying to reorder the default channel", async () => {
+ const res = await put({ ordered_channel_ids: ["ch_default", "ch1"] });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("default channel");
+ });
+
+ it("400 when a channel id does not exist in the workspace", async () => {
+ mockListChannels.mockResolvedValue([{ id: "ch1" }]);
+ const res = await put({ ordered_channel_ids: ["ch1", "ghost"] });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toContain("not found");
+ });
+
+ it("400 on invalid body", async () => {
+ const res = await put({ ordered_channel_ids: "nope" });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.test.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.test.ts
new file mode 100644
index 000000000..e5a248409
--- /dev/null
+++ b/src/web/src/app/api/conversations/[id]/buffered-messages/[messageId]/route.test.ts
@@ -0,0 +1,93 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetConversation = vi.fn();
+const mockGetMessage = vi.fn();
+const mockDeleteBuffered = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },
+ message: {
+ getMessage: (...a: unknown[]) => mockGetMessage(...a),
+ deleteBufferedMessage: (...a: unknown[]) => mockDeleteBuffered(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
+
+import { DELETE } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+function del(params: Record<string, string>) {
+ const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages/m1", {
+ method: "DELETE",
+ });
+ return DELETE(req, { params });
+}
+
+describe("DELETE /api/conversations/[id]/buffered-messages/[messageId]", () => {
+ it("deletes a buffered message scoped to the workspace conversation", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1" });
+ mockGetMessage.mockResolvedValue({ id: "m1", conversationId: "c1", status: "buffered" });
+ mockDeleteBuffered.mockResolvedValue(undefined);
+
+ const res = await del({ id: "c1", messageId: "m1" });
+ expect(res.status).toBe(204);
+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
+ expect(mockDeleteBuffered).toHaveBeenCalledWith({}, "m1");
+ });
+
+ it("400 when conversation id missing", async () => {
+ const res = await del({ messageId: "m1" });
+ expect(res.status).toBe(400);
+ });
+
+ it("400 when message id missing", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1" });
+ const res = await del({ id: "c1" });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when conversation not in workspace", async () => {
+ mockGetConversation.mockResolvedValue(null);
+ const res = await del({ id: "c1", messageId: "m1" });
+ expect(res.status).toBe(404);
+ });
+
+ it("404 when message not found or belongs to a different conversation (IDOR guard)", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1" });
+ mockGetMessage.mockResolvedValue({ id: "m1", conversationId: "OTHER", status: "buffered" });
+ const res = await del({ id: "c1", messageId: "m1" });
+ expect(res.status).toBe(404);
+ expect(mockDeleteBuffered).not.toHaveBeenCalled();
+ });
+
+ it("400 when message is not in buffered status", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1" });
+ mockGetMessage.mockResolvedValue({ id: "m1", conversationId: "c1", status: "sent" });
+ const res = await del({ id: "c1", messageId: "m1" });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("message is not buffered");
+ });
+});
diff --git a/src/web/src/app/api/conversations/[id]/buffered-messages/route.test.ts b/src/web/src/app/api/conversations/[id]/buffered-messages/route.test.ts
new file mode 100644
index 000000000..4bbd12759
--- /dev/null
+++ b/src/web/src/app/api/conversations/[id]/buffered-messages/route.test.ts
@@ -0,0 +1,164 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { put: vi.fn() } } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "xyz") }));
+
+const mockGetConversation = vi.fn();
+const mockListBuffered = vi.fn();
+const mockCountBuffered = vi.fn();
+const mockCreateBuffered = vi.fn();
+const mockDeleteAllBuffered = vi.fn();
+const mockGetActiveTask = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ parsePromptMentions: vi.fn((c: string) => ({ enrichedPrompt: c })),
+ queries: {
+ conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },
+ message: {
+ listBufferedMessages: (...a: unknown[]) => mockListBuffered(...a),
+ countBufferedMessages: (...a: unknown[]) => mockCountBuffered(...a),
+ createBufferedMessage: (...a: unknown[]) => mockCreateBuffered(...a),
+ deleteAllBufferedMessages: (...a: unknown[]) => mockDeleteAllBuffered(...a),
+ },
+ task: { getActiveTaskByConversation: (...a: unknown[]) => mockGetActiveTask(...a) },
+ artifact: { createArtifact: vi.fn() },
+ agent: { listAgents: vi.fn().mockResolvedValue([]) },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({
+ messageToResponse: vi.fn((m: any) => ({ id: m.id, content: m.content })),
+}));
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: { overviewTaskStats: (w: string, d: string) => `ov:${w}:${d}` },
+}));
+const mockDispatch = vi.fn().mockResolvedValue(null);
+vi.mock("@/lib/services/task", () => ({
+ TaskService: function () { return { dispatchNextBufferedMessage: mockDispatch }; },
+}));
+
+import { GET, POST, DELETE } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/conversations/[id]/buffered-messages", () => {
+ it("lists buffered messages for a workspace conversation", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockListBuffered.mockResolvedValue([{ id: "m1", content: "hi" }]);
+
+ const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages");
+ const res = await GET(req, { params: { id: "c1" } });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual([{ id: "m1", content: "hi" }]);
+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
+ });
+
+ it("400 when id missing", async () => {
+ const req = new NextRequest("http://localhost/api/conversations/x/buffered-messages");
+ const res = await GET(req, { params: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when conversation not in workspace", async () => {
+ mockGetConversation.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages");
+ const res = await GET(req, { params: { id: "c1" } });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe("POST /api/conversations/[id]/buffered-messages (JSON)", () => {
+ function post(body: unknown, id = "c1") {
+ const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ return POST(req, { params: { id } });
+ }
+
+ it("creates a buffered message and dispatches when no active task", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockCountBuffered.mockResolvedValue(0);
+ mockCreateBuffered.mockResolvedValue({ id: "m1", content: "hello" });
+ mockGetActiveTask.mockResolvedValue(null);
+
+ const res = await post({ content: "hello" });
+ expect(res.status).toBe(201);
+ expect((await res.json()).message).toEqual({ id: "m1", content: "hello" });
+ expect(mockDispatch).toHaveBeenCalledWith("c1", "w1");
+ });
+
+ it("does NOT dispatch when an active task already exists", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockCountBuffered.mockResolvedValue(0);
+ mockCreateBuffered.mockResolvedValue({ id: "m1", content: "hello" });
+ mockGetActiveTask.mockResolvedValue({ id: "t1" });
+
+ const res = await post({ content: "hello" });
+ expect(res.status).toBe(201);
+ expect(mockDispatch).not.toHaveBeenCalled();
+ });
+
+ it("404 when conversation not in workspace", async () => {
+ mockGetConversation.mockResolvedValue(null);
+ const res = await post({ content: "hello" });
+ expect(res.status).toBe(404);
+ });
+
+ it("429 when buffered limit reached", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockCountBuffered.mockResolvedValue(20);
+ const res = await post({ content: "hello" });
+ expect(res.status).toBe(429);
+ });
+
+ it("400 on invalid JSON body (schema validation)", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockCountBuffered.mockResolvedValue(0);
+ const res = await post({ notContent: 1 });
+ expect(res.status).toBe(400);
+ });
+});
+
+describe("DELETE /api/conversations/[id]/buffered-messages", () => {
+ it("clears all buffered messages (204)", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1" });
+ mockDeleteAllBuffered.mockResolvedValue([{ id: "m1" }, { id: "m2" }]);
+
+ const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages", {
+ method: "DELETE",
+ });
+ const res = await DELETE(req, { params: { id: "c1" } });
+ expect(res.status).toBe(204);
+ expect(mockDeleteAllBuffered).toHaveBeenCalledWith({}, "c1");
+ });
+
+ it("404 when conversation not in workspace", async () => {
+ mockGetConversation.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/conversations/c1/buffered-messages", {
+ method: "DELETE",
+ });
+ const res = await DELETE(req, { params: { id: "c1" } });
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/conversations/[id]/init/route.test.ts b/src/web/src/app/api/conversations/[id]/init/route.test.ts
new file mode 100644
index 000000000..103266e2a
--- /dev/null
+++ b/src/web/src/app/api/conversations/[id]/init/route.test.ts
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const m = {
+ getConversation: vi.fn(),
+ getNewestMessageId: vi.fn(),
+ getActiveMessageCount: vi.fn(),
+ listMessages: vi.fn(),
+ listArtifactsByConversation: vi.fn(),
+ listBufferedMessages: vi.fn(),
+ getActiveTaskByConversation: vi.fn(),
+ listFlaggedMessageIds: vi.fn(),
+ hasPreviousConversations: vi.fn(),
+ listTaskMessages: vi.fn(),
+ countTextMessagesByTaskIds: vi.fn(),
+};
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ conversation: {
+ getConversation: (...a: unknown[]) => m.getConversation(...a),
+ hasPreviousConversations: (...a: unknown[]) => m.hasPreviousConversations(...a),
+ },
+ message: {
+ getNewestMessageId: (...a: unknown[]) => m.getNewestMessageId(...a),
+ getActiveMessageCount: (...a: unknown[]) => m.getActiveMessageCount(...a),
+ listMessages: (...a: unknown[]) => m.listMessages(...a),
+ listBufferedMessages: (...a: unknown[]) => m.listBufferedMessages(...a),
+ },
+ artifact: {
+ listArtifactsByConversation: (...a: unknown[]) => m.listArtifactsByConversation(...a),
+ artifactToResponse: (a: any) => a,
+ },
+ task: { getActiveTaskByConversation: (...a: unknown[]) => m.getActiveTaskByConversation(...a) },
+ messageFlag: { listFlaggedMessageIds: (...a: unknown[]) => m.listFlaggedMessageIds(...a) },
+ taskMessage: {
+ listTaskMessages: (...a: unknown[]) => m.listTaskMessages(...a),
+ countTextMessagesByTaskIds: (...a: unknown[]) => m.countTextMessagesByTaskIds(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({
+ conversationToResponse: (c: any) => ({ id: c.id }),
+ messageToResponse: (m: any) => ({ id: m.id }),
+ taskToResponse: (t: any) => ({ id: t.id }),
+ taskMessageToResponse: (tm: any) => ({ id: tm.id }),
+}));
+vi.mock("@/lib/services/task", () => ({
+ TaskService: function () { return { dispatchNextBufferedMessage: vi.fn().mockResolvedValue(null) }; },
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ m.listMessages.mockResolvedValue({ messages: [], has_more: false });
+ m.listArtifactsByConversation.mockResolvedValue([]);
+ m.listBufferedMessages.mockResolvedValue([]);
+ m.getActiveTaskByConversation.mockResolvedValue(null);
+ m.listFlaggedMessageIds.mockResolvedValue([]);
+ m.hasPreviousConversations.mockResolvedValue(false);
+ m.getActiveMessageCount.mockResolvedValue(0);
+ m.getNewestMessageId.mockResolvedValue(null);
+});
+
+describe("GET /api/conversations/[id]/init", () => {
+ it("400 when conversation id missing", async () => {
+ const req = new NextRequest("http://localhost/api/conversations/x/init");
+ const res = await GET(req, { params: {} });
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when conversation not in workspace", async () => {
+ m.getConversation.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/conversations/c1/init");
+ const res = await GET(req, { params: { id: "c1" } });
+ expect(res.status).toBe(404);
+ expect(mockScoped()).toBe(true);
+ });
+
+ it("returns the init payload with messages when no cache hint", async () => {
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.listMessages.mockResolvedValue({ messages: [{ id: "m1", role: "user" }], has_more: true });
+
+ const req = new NextRequest("http://localhost/api/conversations/c1/init");
+ const res = await GET(req, { params: { id: "c1" } });
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.conversation).toEqual({ id: "c1" });
+ expect(body.messages).toEqual([{ id: "m1" }]);
+ expect(body.has_more_messages).toBe(true);
+ expect(body.cache_valid).toBe(false);
+ });
+
+ it("returns cache_valid=true and null messages when client cache matches", async () => {
+ m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null });
+ m.getNewestMessageId.mockResolvedValue("m9");
+ m.getActiveMessageCount.mockResolvedValue(5);
+ m.listMessages.mockResolvedValue({ messages: [{ id: "m9", role: "user" }], has_more: false });
+
+ const req = new NextRequest(
+ "http://localhost/api/conversations/c1/init?newest_message_id=m9&message_count=5",
+ );
+ const res = await GET(req, { params: { id: "c1" } });
+ const body = await res.json();
+
+ expect(body.cache_valid).toBe(true);
+ expect(body.messages).toBeNull();
+ });
+});
+
+// helper: confirm the conversation lookup was scoped to the authed workspace
+function mockScoped() {
+ return m.getConversation.mock.calls.every((c) => c[2] === "w1");
+}
diff --git a/src/web/src/app/api/conversations/check-fresh/route.test.ts b/src/web/src/app/api/conversations/check-fresh/route.test.ts
new file mode 100644
index 000000000..2067f1290
--- /dev/null
+++ b/src/web/src/app/api/conversations/check-fresh/route.test.ts
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetConversation = vi.fn();
+const mockGetOrCreate = vi.fn();
+const mockGetNewestMessageId = vi.fn();
+const mockGetActiveMessageCount = vi.fn();
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ conversation: {
+ getConversation: (...a: unknown[]) => mockGetConversation(...a),
+ getOrCreateAgentConversation: (...a: unknown[]) => mockGetOrCreate(...a),
+ },
+ message: {
+ getNewestMessageId: (...a: unknown[]) => mockGetNewestMessageId(...a),
+ getActiveMessageCount: (...a: unknown[]) => mockGetActiveMessageCount(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("GET /api/conversations/check-fresh", () => {
+ it("returns freshness for an existing conversation_id (scoped to workspace)", async () => {
+ mockGetConversation.mockResolvedValue({ id: "c1" });
+ mockGetNewestMessageId.mockResolvedValue("m9");
+ mockGetActiveMessageCount.mockResolvedValue(3);
+
+ const req = new NextRequest("http://localhost/api/conversations/check-fresh?conversation_id=c1");
+ const res = await GET(req, {});
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body).toEqual({ conversation_id: "c1", newest_message_id: "m9", message_count: 3 });
+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");
+ });
+
+ it("404 when conversation_id not found in workspace", async () => {
+ mockGetConversation.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/conversations/check-fresh?conversation_id=cX");
+ const res = await GET(req, {});
+ expect(res.status).toBe(404);
+ expect((await res.json()).error).toBe("conversation not found");
+ });
+
+ it("resolves via agent_id when no conversation_id given", async () => {
+ mockGetOrCreate.mockResolvedValue({ id: "c2" });
+ mockGetNewestMessageId.mockResolvedValue(null);
+ mockGetActiveMessageCount.mockResolvedValue(0);
+
+ const req = new NextRequest("http://localhost/api/conversations/check-fresh?agent_id=a1&channel=general");
+ const res = await GET(req, {});
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.conversation_id).toBe("c2");
+ expect(mockGetOrCreate).toHaveBeenCalledWith({}, "w1", "u1", "a1", "general");
+ });
+
+ it("400 when neither conversation_id nor agent_id provided", async () => {
+ const req = new NextRequest("http://localhost/api/conversations/check-fresh");
+ const res = await GET(req, {});
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("conversation_id or agent_id is required");
+ });
+});
diff --git a/src/web/src/app/api/daemon/skills/sync/route.test.ts b/src/web/src/app/api/daemon/skills/sync/route.test.ts
new file mode 100644
index 000000000..457c94294
--- /dev/null
+++ b/src/web/src/app/api/daemon/skills/sync/route.test.ts
@@ -0,0 +1,79 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({
+ getDb: vi.fn(() => ({})),
+ withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),
+}));
+
+const mockSyncGlobal = vi.fn();
+const mockSyncAgent = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agentSkill: {
+ syncGlobalSkills: (...a: unknown[]) => mockSyncGlobal(...a),
+ syncAgentSkills: (...a: unknown[]) => mockSyncAgent(...a),
+ },
+ },
+ };
+});
+
+// withAuth here injects a machine-token context that includes workspaceId.
+let injectWorkspaceId: string | undefined = "w1";
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });
+ }),
+}));
+
+import { POST } from "./route";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ injectWorkspaceId = "w1";
+});
+
+function post(body: unknown) {
+ return POST(
+ new NextRequest("http://localhost/x", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ {},
+ );
+}
+
+describe("POST /api/daemon/skills/sync", () => {
+ it("403 when no workspace (session token, not a machine token)", async () => {
+ injectWorkspaceId = undefined;
+ const res = await post({ scope: "global", runtime: "claude", skills: [], daemon_id: "d1" });
+ expect(res.status).toBe(403);
+ });
+
+ it("syncs global skills", async () => {
+ const skills = [{ name: "s", description: "d" }];
+ const res = await post({ scope: "global", runtime: "claude", skills, daemon_id: "d1" });
+ expect(res.status).toBe(200);
+ expect((await res.json()).status).toBe("ok");
+ expect(mockSyncGlobal).toHaveBeenCalledWith({}, "w1", "claude", skills, "d1");
+ });
+
+ it("syncs agent skills when scope=agent", async () => {
+ const res = await post({ scope: "agent", agent_id: "a1", runtime: "claude", skills: [], daemon_id: "d1" });
+ expect(res.status).toBe(200);
+ expect(mockSyncAgent).toHaveBeenCalledWith({}, "a1", "claude", "w1", []);
+ });
+
+ it("400 when scope=agent without agent_id", async () => {
+ const res = await post({ scope: "agent", runtime: "claude", skills: [], daemon_id: "d1" });
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts
new file mode 100644
index 000000000..43f2b4a2b
--- /dev/null
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockSupersede = vi.fn();
+vi.mock("@/lib/services/task", () => ({
+ TaskService: function () { return { supersedeTask: mockSupersede }; },
+}));
+vi.mock("@/lib/api/responses", () => ({ taskToResponse: (t: any) => ({ id: t.id, status: t.status }) }));
+vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));
+vi.mock("@/lib/cache", () => ({
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ invalidateInboxCounts: vi.fn().mockResolvedValue(undefined),
+ cacheKeys: { overviewTaskStats: (w: string, d: string) => `ts:${w}:${d}` },
+}));
+
+let injectWorkspaceId: string | undefined = "w1";
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });
+ }),
+}));
+
+import { POST } from "./route";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ injectWorkspaceId = "w1";
+});
+
+const post = (params: Record<string, string>) =>
+ POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });
+
+describe("POST /api/daemon/tasks/[taskId]/supersede", () => {
+ it("403 when no workspace (machine token required)", async () => {
+ injectWorkspaceId = undefined;
+ const res = await post({ taskId: "t1" });
+ expect(res.status).toBe(403);
+ });
+
+ it("400 when taskId missing", async () => {
+ const res = await post({});
+ expect(res.status).toBe(400);
+ });
+
+ it("supersedes a task scoped to the token workspace", async () => {
+ mockSupersede.mockResolvedValue({ id: "t1", agentId: "a1", status: "superseded" });
+ const res = await post({ taskId: "t1" });
+ expect(res.status).toBe(200);
+ expect(mockSupersede).toHaveBeenCalledWith("t1", "w1");
+ expect((await res.json()).id).toBe("t1");
+ });
+
+ it("400 when supersede throws (e.g. task not in workspace)", async () => {
+ mockSupersede.mockRejectedValue(new Error("task not found"));
+ const res = await post({ taskId: "t1" });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("task not found");
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
new file mode 100644
index 000000000..9dd029476
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockBucketGet = vi.fn();
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { get: mockBucketGet } } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockParse = vi.fn();
+vi.mock("postal-mime", () => ({ default: { parse: (...a: unknown[]) => mockParse(...a) } }));
+
+const mockGetById = vi.fn();
+const mockFilter = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ filterDownloadableAttachments: (...a: unknown[]) => mockFilter(...a),
+ queries: { email: { getEmailById: (...a: unknown[]) => mockGetById(...a) } },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const get = (params: Record<string, string>) => GET(new NextRequest("http://localhost/x"), { params });
+
+describe("GET /api/email/[id]/attachment/[index]", () => {
+ it("400 when email id missing", async () => {
+ const res = await get({ index: "0" });
+ expect(res.status).toBe(400);
+ });
+
+ it("400 when index is not a valid number", async () => {
+ const res = await get({ id: "e1", index: "abc" });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe("invalid attachment index");
+ });
+
+ it("404 when email not in workspace", async () => {
+ mockGetById.mockResolvedValue(null);
+ const res = await get({ id: "e1", index: "0" });
+ expect(res.status).toBe(404);
+ expect(mockGetById).toHaveBeenCalledWith({}, "e1", "w1");
+ });
+
+ it("404 when R2 object is missing", async () => {
+ mockGetById.mockResolvedValue({ id: "e1", r2Key: "k" });
+ mockBucketGet.mockResolvedValue(null);
+ const res = await get({ id: "e1", index: "0" });
+ expect(res.status).toBe(404);
+ expect((await res.json()).error).toBe("email content not available");
+ });
+
+ it("404 when the index is out of range", async () => {
+ mockGetById.mockResolvedValue({ id: "e1", r2Key: "k" });
+ mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });
+ mockParse.mockResolvedValue({ attachments: [] });
+ mockFilter.mockReturnValue([]);
+ const res = await get({ id: "e1", index: "0" });
+ expect(res.status).toBe(404);
+ expect((await res.json()).error).toBe("attachment not found");
+ });
+
+ it("streams the attachment with content headers", async () => {
+ mockGetById.mockResolvedValue({ id: "e1", r2Key: "k" });
+ mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });
+ mockParse.mockResolvedValue({ attachments: [{}] });
+ mockFilter.mockReturnValue([
+ { filename: "report.pdf", mimeType: "application/pdf", content: new ArrayBuffer(3) },
+ ]);
+ const res = await get({ id: "e1", index: "0" });
+ expect(res.status).toBe(200);
+ expect(res.headers.get("Content-Type")).toBe("application/pdf");
+ expect(res.headers.get("Content-Disposition")).toContain("report.pdf");
+ });
+});
diff --git a/src/web/src/app/api/email/[id]/thread/route.test.ts b/src/web/src/app/api/email/[id]/thread/route.test.ts
new file mode 100644
index 000000000..c7c55d617
--- /dev/null
+++ b/src/web/src/app/api/email/[id]/thread/route.test.ts
@@ -0,0 +1,78 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const mockGetById = vi.fn();
+const mockGetByMessageId = vi.fn();
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ email: {
+ getEmailById: (...a: unknown[]) => mockGetById(...a),
+ getEmailByMessageId: (...a: unknown[]) => mockGetByMessageId(...a),
+ },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/api/responses", () => ({ emailToResponse: (e: any) => ({ id: e.id }) }));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const get = (params: Record<string, string>) => GET(new NextRequest("http://localhost/x"), { params });
+
+describe("GET /api/email/[id]/thread", () => {
+ it("400 when email id missing", async () => {
+ const res = await get({});
+ expect(res.status).toBe(400);
+ });
+
+ it("404 when email not in workspace", async () => {
+ mockGetById.mockResolvedValue(null);
+ const res = await get({ id: "e1" });
+ expect(res.status).toBe(404);
+ expect(mockGetById).toHaveBeenCalledWith({}, "e1", "w1");
+ });
+
+ it("returns [] when the email has no parent", async () => {
+ mockGetById.mockResolvedValue({ id: "e1", inReplyTo: null });
+ const res = await get({ id: "e1" });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual([]);
+ });
+
+ it("walks the reply chain oldest-first", async () => {
+ mockGetById.mockResolvedValue({ id: "e3", inReplyTo: "msg2" });
+ mockGetByMessageId
+ .mockResolvedValueOnce({ id: "e2", inReplyTo: "msg1" })
+ .mockResolvedValueOnce({ id: "e1", inReplyTo: null });
+ const res = await get({ id: "e3" });
+ expect(await res.json()).toEqual([{ id: "e1" }, { id: "e2" }]);
+ });
+
+ it("stops at a cycle without infinite looping", async () => {
+ mockGetById.mockResolvedValue({ id: "e2", inReplyTo: "msgSelf" });
+ // parent points back to a message id already seen → loop guard breaks
+ mockGetByMessageId.mockResolvedValue({ id: "e1", inReplyTo: "msgSelf" });
+ const res = await get({ id: "e2" });
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(Array.isArray(body)).toBe(true);
+ });
+});
diff --git a/src/web/src/app/api/workspaces/[id]/overview/route.test.ts b/src/web/src/app/api/workspaces/[id]/overview/route.test.ts
new file mode 100644
index 000000000..8251ff7f6
--- /dev/null
+++ b/src/web/src/app/api/workspaces/[id]/overview/route.test.ts
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+const q = {
+ getAllAgents: vi.fn(),
+ getAllAccess: vi.fn(),
+ emailStats: vi.fn(),
+ emailAccounts: vi.fn(),
+ taskStats: vi.fn(),
+ recentTasks: vi.fn(),
+ convCounts: vi.fn(),
+ members: vi.fn(),
+ invites: vi.fn(),
+ calendar: vi.fn(),
+};
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: { getAllAgentsForWorkspace: (...a: unknown[]) => q.getAllAgents(...a) },
+ agentAccess: { getAllAgentAccessForWorkspace: (...a: unknown[]) => q.getAllAccess(...a) },
+ overview: {
+ getEmailStatsByWorkspace: (...a: unknown[]) => q.emailStats(...a),
+ getEmailAccountsByWorkspace: (...a: unknown[]) => q.emailAccounts(...a),
+ getTaskStatsByWorkspace: (...a: unknown[]) => q.taskStats(...a),
+ getRecentTerminalTasks: (...a: unknown[]) => q.recentTasks(...a),
+ getConversationCountsByAgent: (...a: unknown[]) => q.convCounts(...a),
+ },
+ member: { listMembers: (...a: unknown[]) => q.members(...a) },
+ workspaceInvite: { listActiveInvites: (...a: unknown[]) => q.invites(...a) },
+ calendarEvent: { listCalendarEvents: (...a: unknown[]) => q.calendar(...a) },
+ },
+ };
+});
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+vi.mock("@/lib/cache", () => ({
+ cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),
+ cacheKeys: {
+ allAgents: (w: string) => `ag:${w}`, allAgentAccess: (w: string) => `aa:${w}`,
+ overviewEmailStats: (w: string) => `es:${w}`, overviewEmailAccounts: (w: string) => `ea:${w}`,
+ overviewTaskStats: (w: string, d: string) => `ts:${w}:${d}`, allMembers: (w: string) => `mem:${w}`,
+ },
+}));
+vi.mock("@/lib/agent-visibility", () => ({ filterVisibleAgents: vi.fn((a: any[]) => a) }));
+
+import { GET } from "./route";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ q.getAllAgents.mockResolvedValue([{ id: "a1" }]);
+ q.getAllAccess.mockResolvedValue([]);
+ q.emailStats.mockResolvedValue({ total: 5 });
+ q.emailAccounts.mockResolvedValue([{ id: "ea1", agentId: "a1", emailAddress: "[email protected]", status: "ok", errorMessage: null, lastSyncedAt: null }]);
+ q.taskStats.mockResolvedValue({ done: 2 });
+ q.recentTasks.mockResolvedValue([{ id: "t1", agentId: "a1", type: "dm", status: "completed", prompt: "p", createdAt: "d", completedAt: "d", error: null }]);
+ q.convCounts.mockResolvedValue([{ agentId: "a1", cnt: 3 }]);
+ q.members.mockResolvedValue([{ id: "m1", userId: "u1", role: "owner", userName: "U", userEmail: "[email protected]", userImage: null, createdAt: "d" }]);
+ q.invites.mockResolvedValue([{ id: "i1" }, { id: "i2" }]);
+ q.calendar.mockResolvedValue([{ id: "c1", agentId: "a1", title: "T", description: "", scheduledAt: "d", repeatInterval: null, repeatStopAt: null, lastTriggeredAt: null }]);
+});
+
+describe("GET /api/workspaces/[id]/overview", () => {
+ it("aggregates the workspace dashboard payload", async () => {
+ const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "w1" } });
+ const body = await res.json();
+ expect(res.status).toBe(200);
+ expect(body.email_stats).toEqual({ total: 5 });
+ expect(body.conversation_counts).toEqual({ a1: 3 });
+ expect(body.pending_invites).toBe(2);
+ expect(body.recent_tasks[0].id).toBe("t1");
+ expect(body.calendar_events[0].title).toBe("T");
+ // visible-agent scoping passed to recent tasks / conv counts
+ expect(q.recentTasks).toHaveBeenCalledWith({}, "w1", ["a1"], 15);
+ });
+});
diff --git a/src/web/src/lib/session.test.ts b/src/web/src/lib/session.test.ts
new file mode 100644
index 000000000..cda17c22f
--- /dev/null
+++ b/src/web/src/lib/session.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(async () => ({ env: {} })),
+}));
+
+vi.mock("next/headers", () => ({
+ headers: vi.fn(async () => new Headers()),
+}));
+
+const mockGetSession = vi.fn();
+vi.mock("@/lib/auth", () => ({
+ createAuth: vi.fn(() => ({ api: { getSession: mockGetSession } })),
+}));
+
+import { getSession, requireSession } from "./session";
+
+describe("session", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("getSession returns the resolved session", async () => {
+ const session = { user: { id: "u1", email: "[email protected]" } };
+ mockGetSession.mockResolvedValue(session);
+ await expect(getSession()).resolves.toEqual(session);
+ });
+
+ it("getSession returns null when no session", async () => {
+ mockGetSession.mockResolvedValue(null);
+ await expect(getSession()).resolves.toBeNull();
+ });
+
+ it("requireSession returns the session when present", async () => {
+ const session = { user: { id: "u1", email: "[email protected]" } };
+ mockGetSession.mockResolvedValue(session);
+ await expect(requireSession()).resolves.toEqual(session);
+ });
+
+ it("requireSession throws Unauthorized when session is absent", async () => {
+ mockGetSession.mockResolvedValue(null);
+ await expect(requireSession()).rejects.toThrow("Unauthorized");
+ });
+});