Open-source SEO, GEO, and marketing skills for AI agents.
test: broad coverage sweep + v8 coverage tooling
Yuting Zhong0d5fd2bdff5a
diff --git a/.gitignore b/.gitignoreindex b95e255f..fd724ec4 100644--- a/.gitignore+++ b/.gitignore@@ -10,6 +10,7 @@ dist/out/tsconfig.tsbuildinfo*.tsbuildinfo+coverage/# OS / editor.vscode/diff --git a/package.json b/package.jsonindex 7e2fd1ff..d92a5b96 100644--- a/package.json+++ b/package.json@@ -22,6 +22,7 @@"test": "vitest run","test:watch": "vitest","test:ui": "vitest --ui",+ "test:coverage": "vitest run --coverage","eval": "vitest run --config vitest.evals.config.ts"},"dependencies": {@@ -61,6 +62,7 @@"@types/react-dom": "^19.0.0","@types/ws": "^8.18.1","@vitejs/plugin-react": "^6.0.2",+ "@vitest/coverage-v8": "^4.1.7","@vitest/ui": "^4.1.6","eslint": "^9.0.0","eslint-config-next": "^16.2.6",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b14f90fc..2e2659f7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -111,6 +111,9 @@ importers:'@vitejs/plugin-react':specifier: ^6.0.2version: 6.0.2([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ '@vitest/coverage-v8':+ specifier: ^4.1.7+ version: 4.1.7([email protected])'@vitest/ui':specifier: ^4.1.6version: 4.1.6([email protected])@@ -137,7 +140,7 @@ importers:version: 5.9.3vitest:specifier: ^4.1.6- version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))packages:@@ -272,6 +275,10 @@ packages:resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}engines: {node: '>=6.9.0'}+ '@bcoe/[email protected]':+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}+ engines: {node: '>=18'}+'@bramus/[email protected]':resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}hasBin: true@@ -1982,6 +1989,15 @@ packages:babel-plugin-react-compiler:optional: true+ '@vitest/[email protected]':+ resolution: {integrity: sha512-qsYPeXc5Q9dFLd1i8Ap+Bx8sQgcp+rFVQo4R0dDsWNBzl26ldVF1qOO+RL24K7FDrR6pA+50XedRLSoSG24bVQ==}+ peerDependencies:+ '@vitest/browser': 4.1.7+ vitest: 4.1.7+ peerDependenciesMeta:+ '@vitest/browser':+ optional: true+'@vitest/[email protected]':resolution: {integrity: sha512-7EHDquPthALSV0jhhjgEW8FXaviMx7rSqu8W6oqCoAuOhKov814P99QDV1pxMA3QPv21YudvJngIhjrNI4opLg==}@@ -1999,6 +2015,9 @@ packages:'@vitest/[email protected]':resolution: {integrity: sha512-h5SxD/IzNhZYnrSZRsUZQIC+vD0GY8cUvq0iwsmkFKixRCKLLWqCXa/FIQ4S1R+sI+PGoojkHsdNrbZiM9Qpgw==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-umgCarTOYQWIaDMvGDRZij+6b9oVeLIyJzfN+AS88e0ZOU3QTgNNSTtjQOpcvWr3np1N0j4WgZj+sb3oYBDscw==}+'@vitest/[email protected]':resolution: {integrity: sha512-nOPCmn2+yD0ZNmKdsXGv/UxMMWbMuKeD6GyYncNwdkYDxpQvrPSKYj2rWuDjC2Y4b6w6hjip5dBKFzEUuZe3vA==}@@ -2016,6 +2035,9 @@ packages:'@vitest/[email protected]':resolution: {integrity: sha512-FxIY+U81R3LGKCxaHHFRQ5+g6/iRgGLmeHWdp2Amj4ljQRrEIWHmZyDfDYBRZlpyqA7qKxtS9DD1dhk8RnRIVQ==}+ '@vitest/[email protected]':+ resolution: {integrity: sha512-T532WBu791cBxJlCl6SO+J14l81DQx6uQHm1bQbmCDY7nqlEIgkza/UFnSBNaUtSf41unldDFjdOBYEQC4b5Hw==}+resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}peerDependencies:@@ -2104,6 +2126,9 @@ packages:resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==}+ resolution: {integrity: sha512-1fSfIwuDICFA4LKkCzRPO7F0hzFf0B7+Xqrl27ynQaa+Rh0e1Es0v6kWHPott3lU10AyAr7oKHa65OppjLn3Rg==}+resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}engines: {node: '>= 0.4'}@@ -2753,6 +2778,9 @@ packages:resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}+resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}@@ -2934,6 +2962,18 @@ packages:resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}engines: {node: '>= 0.4'}@@ -2942,6 +2982,9 @@ packages:resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}hasBin: true+ resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}+resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}@@ -3121,6 +3164,13 @@ packages:resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}+ resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==}++ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}@@ -4349,6 +4399,8 @@ snapshots:'@babel/helper-string-parser': 7.27.1'@babel/helper-validator-identifier': 7.28.5+ '@bcoe/[email protected]': {}+'@bramus/[email protected]':dependencies:css-tree: 3.2.1@@ -5865,6 +5917,20 @@ snapshots:'@rolldown/pluginutils': 1.0.1+ '@vitest/[email protected]([email protected])':+ dependencies:+ '@bcoe/v8-coverage': 1.0.2+ '@vitest/utils': 4.1.7+ ast-v8-to-istanbul: 1.0.0+ istanbul-lib-coverage: 3.2.2+ istanbul-lib-report: 3.0.1+ istanbul-reports: 3.2.0+ magicast: 0.5.3+ obug: 2.1.1+ std-env: 4.1.0+ tinyrainbow: 3.1.0+ vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+'@vitest/[email protected]':dependencies:'@standard-schema/spec': 1.1.0@@ -5886,6 +5952,10 @@ snapshots:dependencies:tinyrainbow: 3.1.0+ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 3.1.0+'@vitest/[email protected]':dependencies:'@vitest/utils': 4.1.6@@ -5909,7 +5979,7 @@ snapshots:sirv: 3.0.2tinyglobby: 0.2.16tinyrainbow: 3.1.0- vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -5917,6 +5987,12 @@ snapshots:convert-source-map: 2.0.0tinyrainbow: 3.1.0+ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 4.1.7+ convert-source-map: 2.0.0+ tinyrainbow: 3.1.0+dependencies:acorn: 8.16.0@@ -6033,6 +6109,12 @@ snapshots:+ dependencies:+ '@jridgewell/trace-mapping': 0.3.31+ estree-walker: 3.0.3+ js-tokens: 10.0.0+@@ -6834,6 +6916,8 @@ snapshots:transitivePeerDependencies:- '@noble/hashes'+ [email protected]: {}+@@ -7004,6 +7088,19 @@ snapshots:+ [email protected]: {}++ dependencies:+ istanbul-lib-coverage: 3.2.2+ make-dir: 4.0.0+ supports-color: 7.2.0++ dependencies:+ html-escaper: 2.0.2+ istanbul-lib-report: 3.0.1+dependencies:define-data-property: 1.1.4@@ -7015,6 +7112,8 @@ snapshots:+ [email protected]: {}+@@ -7175,6 +7274,16 @@ snapshots:dependencies:'@jridgewell/sourcemap-codec': 1.5.5+ dependencies:+ '@babel/parser': 7.29.3+ '@babel/types': 7.29.0+ source-map-js: 1.2.1++ dependencies:+ semver: 7.8.0+@@ -8513,7 +8622,7 @@ snapshots:jiti: 2.7.0tsx: 4.22.1- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.6'@vitest/mocker': 4.1.6([email protected](@types/[email protected])([email protected])([email protected])([email protected]))@@ -8538,6 +8647,7 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 22.19.19+ '@vitest/coverage-v8': 4.1.7([email protected])'@vitest/ui': 4.1.6([email protected])jsdom: 29.1.1transitivePeerDependencies:diff --git a/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts b/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.tsnew file mode 100644index 00000000..5d0d8863--- /dev/null+++ b/src/app/api/agents/[agent]/threads/[thread]/transcript/route.test.ts@@ -0,0 +1,210 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Project } from "@/types";++const getActiveProjectMock = vi.fn();+vi.mock("@/server/active-project", () => ({+ getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),+}));++const getProjectMock = vi.fn();+vi.mock("@/server/db/projects", () => ({+ getProject: (...args: unknown[]) => getProjectMock(...args),+}));++const resolveAgentBySlugMock = vi.fn();+vi.mock("@/server/agent-meta", () => ({+ resolveAgentBySlug: (...args: unknown[]) => resolveAgentBySlugMock(...args),+}));++const readTranscriptTailMock = vi.fn();+vi.mock("@/server/openclaw/transcript-tail", () => ({+ readTranscriptTail: (...args: unknown[]) => readTranscriptTailMock(...args),+}));++import { GET } from "./route";++function makeProject(overrides: Partial<Project> = {}): Project {+ return {+ id: "id",+ slug: "acme",+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ ...overrides,+ };+}++function makeReq(url: string): Request {+ return new Request(url, { method: "GET" });+}++describe("GET /api/agents/[agent]/threads/[thread]/transcript", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns 400 when no project param and no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const res = await GET(+ makeReq("http://localhost/api/agents/cmo/threads/t1/transcript"),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(res.status).toBe(400);+ const body = (await res.json()) as { error: string };+ expect(body.error).toBe("no active project");+ });++ it("uses explicit project query param when present", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ readTranscriptTailMock.mockReturnValueOnce({+ events: [],+ byteOffset: 0,+ fileSize: 0,+ });+ await GET(+ makeReq(+ "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme",+ ),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(getProjectMock).toHaveBeenCalledWith("acme");+ expect(getActiveProjectMock).not.toHaveBeenCalled();+ });++ it("falls back to active project when no query param", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ readTranscriptTailMock.mockReturnValueOnce({+ events: [],+ byteOffset: 0,+ fileSize: 0,+ });+ await GET(+ makeReq("http://localhost/api/agents/cmo/threads/t1/transcript"),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(getActiveProjectMock).toHaveBeenCalled();+ expect(getProjectMock).not.toHaveBeenCalled();+ });++ it("returns 404 when agent slug cannot be resolved", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce(null);+ const res = await GET(+ makeReq(+ "http://localhost/api/agents/ghost/threads/t1/transcript?project=acme",+ ),+ { params: Promise.resolve({ agent: "ghost", thread: "t1" }) },+ );+ expect(res.status).toBe(404);+ const body = (await res.json()) as { error: string };+ expect(body.error).toBe("unknown agent");+ });++ it("returns events + byte offset + file size on success", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ const events = [+ { kind: "user_message", id: "1", ts: 0, body: "hi" },+ ];+ readTranscriptTailMock.mockReturnValueOnce({+ events,+ byteOffset: 100,+ fileSize: 100,+ });+ const res = await GET(+ makeReq(+ "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme&offset=50",+ ),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(res.status).toBe(200);+ const body = (await res.json()) as {+ events: unknown[];+ byteOffset: number;+ file_size: number;+ };+ expect(body.events).toEqual(events);+ expect(body.byteOffset).toBe(100);+ expect(body.file_size).toBe(100);+ expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 50);+ });++ it("treats missing offset query param as 0", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ readTranscriptTailMock.mockReturnValueOnce({+ events: [],+ byteOffset: 0,+ fileSize: 0,+ });+ await GET(+ makeReq(+ "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme",+ ),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 0);+ });++ it("clamps negative offset to 0", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ readTranscriptTailMock.mockReturnValueOnce({+ events: [],+ byteOffset: 0,+ fileSize: 0,+ });+ await GET(+ makeReq(+ "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme&offset=-5",+ ),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 0);+ });++ it("clamps non-numeric offset to 0", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ readTranscriptTailMock.mockReturnValueOnce({+ events: [],+ byteOffset: 0,+ fileSize: 0,+ });+ await GET(+ makeReq(+ "http://localhost/api/agents/cmo/threads/t1/transcript?project=acme&offset=notanumber",+ ),+ { params: Promise.resolve({ agent: "cmo", thread: "t1" }) },+ );+ expect(readTranscriptTailMock).toHaveBeenCalledWith("acme-cmo", "t1", 0);+ });+});diff --git a/src/app/api/chat/route.test.ts b/src/app/api/chat/route.test.tsnew file mode 100644index 00000000..7bf9a28b--- /dev/null+++ b/src/app/api/chat/route.test.ts@@ -0,0 +1,532 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Project } from "@/types";++const getActiveProjectMock = vi.fn();+vi.mock("@/server/active-project", () => ({+ getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),+}));++const getProjectMock = vi.fn();+vi.mock("@/server/db/projects", () => ({+ getProject: (...args: unknown[]) => getProjectMock(...args),+}));++const resolveAgentBySlugMock = vi.fn();+vi.mock("@/server/agent-meta", () => ({+ resolveAgentBySlug: (...args: unknown[]) => resolveAgentBySlugMock(...args),+}));++const findSessionBySessionIdMock = vi.fn();+const buildPendingSessionKeyMock = vi.fn(+ (agent: string, sessionId: string) => `agent:${agent}:${sessionId}`,+);+vi.mock("@/server/openclaw/sessions", () => ({+ findSessionBySessionId: (...args: unknown[]) =>+ findSessionBySessionIdMock(...args),+ buildPendingSessionKey: (...args: unknown[]) =>+ buildPendingSessionKeyMock(...(args as [string, string])),+}));++const streamChatViaGatewayMock = vi.fn();+vi.mock("@/server/openclaw/gateway-client", () => ({+ streamChatViaGateway: (...args: unknown[]) => streamChatViaGatewayMock(...args),+}));++const processOrchestrationBlocksMock = vi.fn();+vi.mock("@/server/orchestration/process-blocks", () => ({+ processOrchestrationBlocks: (...args: unknown[]) =>+ processOrchestrationBlocksMock(...args),+}));++import { POST } from "./route";++function makeProject(overrides: Partial<Project> = {}): Project {+ return {+ id: "id",+ slug: "acme",+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ ...overrides,+ };+}++function makeReq(body: unknown): Request {+ return new Request("http://localhost/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: typeof body === "string" ? body : JSON.stringify(body),+ });+}++async function readSse(res: Response): Promise<{+ events: Array<{ event: string; data: unknown }>;+ raw: string;+}> {+ const reader = res.body!.getReader();+ const decoder = new TextDecoder();+ let raw = "";+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ raw += decoder.decode(value, { stream: true });+ }+ const events: Array<{ event: string; data: unknown }> = [];+ for (const chunk of raw.split("\n\n")) {+ const lines = chunk.split("\n");+ let event = "message";+ let data: unknown = null;+ for (const line of lines) {+ if (line.startsWith("event: ")) event = line.slice("event: ".length);+ else if (line.startsWith("data: ")) {+ try {+ data = JSON.parse(line.slice("data: ".length));+ } catch {+ data = line.slice("data: ".length);+ }+ }+ }+ if (lines.length > 0 && lines[0]) events.push({ event, data });+ }+ return { events, raw };+}++function emptyOrchestrationOutcome() {+ return {+ tasks_created: [],+ task_status_updates: [],+ comments_added: [],+ ask_user: [],+ approvals_requested: [],+ errors: [],+ };+}++// Stream-builder helper: yields the given events one at a time.+async function* makeAgentStream(+ evts: Array<{+ kind: "delta" | "tool" | "lifecycle" | "error" | "final";+ [k: string]: unknown;+ }>,+) {+ for (const e of evts) yield e;+}++describe("POST /api/chat", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ streamChatViaGatewayMock.mockReset();+ processOrchestrationBlocksMock.mockReset();+ });++ it("returns 400 when body is not valid JSON", async () => {+ const res = await POST(+ new Request("http://localhost/api/chat", {+ method: "POST",+ body: "not json",+ }),+ );+ expect(res.status).toBe(400);+ const body = (await res.json()) as { error: string };+ expect(body.error).toMatch(/Invalid JSON/);+ });++ it("returns 400 when message is missing", async () => {+ const res = await POST(makeReq({ sessionId: "s1" }));+ expect(res.status).toBe(400);+ const body = (await res.json()) as { error: string };+ expect(body.error).toMatch(/message is required/);+ });++ it("returns 400 when message is whitespace-only", async () => {+ const res = await POST(makeReq({ message: " ", sessionId: "s1" }));+ expect(res.status).toBe(400);+ });++ it("returns 400 when no active project resolves", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ expect(res.status).toBe(400);+ const body = (await res.json()) as { error: string };+ expect(body.error).toMatch(/No active project/);+ });++ it("uses explicit project param over active-project cookie", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce(null); // short-circuit at 404++ const res = await POST(+ makeReq({ message: "hi", sessionId: "s1", project: "acme" }),+ );+ expect(res.status).toBe(404);+ expect(getProjectMock).toHaveBeenCalledWith("acme");+ expect(getActiveProjectMock).not.toHaveBeenCalled();+ });++ it("returns 404 when agent slug cannot be resolved", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce(null);+ const res = await POST(+ makeReq({ message: "hi", sessionId: "s1", agent: "ghost" }),+ );+ expect(res.status).toBe(404);+ const body = (await res.json()) as { error: string };+ expect(body.error).toMatch(/ghost/);+ });++ it("defaults agent to 'cmo' when not specified", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce(null);+ await POST(makeReq({ message: "hi", sessionId: "s1" }));+ expect(resolveAgentBySlugMock).toHaveBeenCalledWith("acme", "cmo");+ });++ it("returns 400 when sessionId is missing", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ const res = await POST(makeReq({ message: "hi" }));+ expect(res.status).toBe(400);+ const body = (await res.json()) as { error: string };+ expect(body.error).toMatch(/sessionId is required/);+ });++ it("uses provided sessionKey verbatim when present", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(+ makeReq({+ message: "hello",+ sessionId: "s1",+ sessionKey: "agent:acme-cmo:custom-label",+ }),+ );+ expect(res.status).toBe(200);+ await readSse(res); // drain+ expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);+ const call = streamChatViaGatewayMock.mock.calls[0]![0] as {+ sessionKey: string;+ sessionId: string;+ message: string;+ };+ expect(call.sessionKey).toBe("agent:acme-cmo:custom-label");+ expect(call.sessionId).toBe("s1");+ expect(call.message).toBe("hello");+ // No fallback lookup needed when sessionKey is explicit.+ expect(findSessionBySessionIdMock).not.toHaveBeenCalled();+ });++ it("looks up sessionKey from sessions store when not provided", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce({+ sessionId: "s1",+ sessionKey: "agent:acme-cmo:s1",+ label: "s1",+ lastInteractionAt: 0,+ pending: false,+ });+ streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ await readSse(res);+ expect(findSessionBySessionIdMock).toHaveBeenCalledWith("acme-cmo", "s1");+ const call = streamChatViaGatewayMock.mock.calls[0]![0] as {+ sessionKey: string;+ };+ expect(call.sessionKey).toBe("agent:acme-cmo:s1");+ });++ it("falls back to buildPendingSessionKey for unknown sessions", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "new-id" }));+ await readSse(res);+ expect(buildPendingSessionKeyMock).toHaveBeenCalledWith(+ "acme-cmo",+ "new-id",+ );+ const call = streamChatViaGatewayMock.mock.calls[0]![0] as {+ sessionKey: string;+ };+ expect(call.sessionKey).toBe("agent:acme-cmo:new-id");+ });++ it("streams meta + text + done events for a happy-path chat", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([+ { kind: "delta", text: "Hello, " },+ { kind: "delta", text: "world!" },+ ]),+ );+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ expect(res.status).toBe(200);+ expect(res.headers.get("Content-Type")).toBe("text/event-stream");+ expect(res.headers.get("Cache-Control")).toBe("no-cache");++ const { events } = await readSse(res);+ const eventNames = events.map((e) => e.event);+ expect(eventNames[0]).toBe("meta");+ expect(eventNames).toContain("text");+ expect(eventNames).toContain("done");++ const meta = events.find((e) => e.event === "meta")!.data as {+ project_slug: string;+ agent: string;+ session_id: string;+ };+ expect(meta.project_slug).toBe("acme");+ expect(meta.agent).toBe("acme-cmo");+ expect(meta.session_id).toBe("s1");++ const textEvents = events+ .filter((e) => e.event === "text")+ .map((e) => (e.data as { chunk: string }).chunk);+ expect(textEvents).toEqual(["Hello, ", "world!"]);+ });++ it("emits tool + lifecycle events through to the SSE stream", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([+ { kind: "lifecycle", phase: "start" },+ {+ kind: "tool",+ phase: "start",+ toolCallId: "tc1",+ name: "exec",+ label: "ls",+ },+ {+ kind: "tool",+ phase: "result",+ toolCallId: "tc1",+ name: "exec",+ },+ { kind: "lifecycle", phase: "end" },+ ]),+ );+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ const { events } = await readSse(res);++ const toolEvents = events.filter((e) => e.event === "tool");+ expect(toolEvents).toHaveLength(2);+ expect((toolEvents[0]!.data as { phase: string }).phase).toBe("start");+ expect((toolEvents[1]!.data as { phase: string }).phase).toBe("result");++ const lifecycleEvents = events.filter((e) => e.event === "lifecycle");+ expect(lifecycleEvents).toHaveLength(2);+ });++ it("emits an error event when the gateway stream yields an error", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([{ kind: "error", message: "gateway is down" }]),+ );+ // The route only invokes orchestration when assistantBuffer has content;+ // an error-only stream skips orchestration entirely.+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ const { events } = await readSse(res);+ const errEvent = events.find((e) => e.event === "error");+ expect(errEvent).toBeDefined();+ expect((errEvent!.data as { message: string }).message).toBe(+ "gateway is down",+ );+ });++ it("emits an error event when the gateway iterator throws", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);++ async function* throwingStream() {+ yield { kind: "delta" as const, text: "partial" };+ throw new Error("ws disconnected");+ }+ streamChatViaGatewayMock.mockReturnValueOnce(throwingStream());+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ const { events } = await readSse(res);+ const errEvent = events.find((e) => e.event === "error");+ expect(errEvent).toBeDefined();+ expect((errEvent!.data as { message: string }).message).toBe(+ "ws disconnected",+ );+ });++ it("emits orchestration event when orchestration produces outcomes", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([{ kind: "delta", text: "I'll create a task." }]),+ );+ processOrchestrationBlocksMock.mockResolvedValueOnce({+ tasks_created: [+ {+ id: "task-1",+ title: "Install conversion tracking",+ agent_id: "acme-google-ads",+ status: "running",+ },+ ],+ task_status_updates: [],+ comments_added: [],+ ask_user: [],+ approvals_requested: [],+ errors: [],+ });++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ const { events } = await readSse(res);+ const orch = events.find((e) => e.event === "orchestration");+ expect(orch).toBeDefined();+ const data = orch!.data as {+ tasks_created: Array<{ id: string; assignee: string }>;+ };+ expect(data.tasks_created[0]!.id).toBe("task-1");+ expect(data.tasks_created[0]!.assignee).toBe("acme-google-ads");++ expect(processOrchestrationBlocksMock).toHaveBeenCalledWith(+ "I'll create a task.",+ { project_slug: "acme", agent_id: "acme-cmo" },+ );+ });++ it("skips orchestration when the assistant produced no text", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([+ { kind: "lifecycle", phase: "start" },+ { kind: "lifecycle", phase: "end" },+ ]),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ await readSse(res);+ expect(processOrchestrationBlocksMock).not.toHaveBeenCalled();+ });++ it("does NOT emit orchestration event when outcome is empty", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([{ kind: "delta", text: "Just chatting." }]),+ );+ processOrchestrationBlocksMock.mockResolvedValueOnce(+ emptyOrchestrationOutcome(),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ const { events } = await readSse(res);+ expect(events.find((e) => e.event === "orchestration")).toBeUndefined();+ // Still ends cleanly with done.+ expect(events.find((e) => e.event === "done")).toBeDefined();+ });++ it("survives orchestration throwing — chat reply still completes", async () => {+ getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));+ resolveAgentBySlugMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ display_name: "CMO",+ slug: "cmo",+ });+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ streamChatViaGatewayMock.mockReturnValueOnce(+ makeAgentStream([{ kind: "delta", text: "hello" }]),+ );+ processOrchestrationBlocksMock.mockRejectedValueOnce(+ new Error("parse failure"),+ );++ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));+ const { events } = await readSse(res);+ expect(events.find((e) => e.event === "done")).toBeDefined();+ // No orchestration event when it failed.+ expect(events.find((e) => e.event === "orchestration")).toBeUndefined();+ });+});diff --git a/src/app/api/mcp-oauth/callback/route.test.ts b/src/app/api/mcp-oauth/callback/route.test.tsnew file mode 100644index 00000000..6115f88f--- /dev/null+++ b/src/app/api/mcp-oauth/callback/route.test.ts@@ -0,0 +1,254 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const consumePendingMock = vi.fn();+vi.mock("@/server/mcp-pending", () => ({+ consumePending: (...args: unknown[]) => consumePendingMock(...args),+}));++const setMcpBearerMock = vi.fn();+vi.mock("@/server/mcp-state", () => ({+ setMcpBearer: (...args: unknown[]) => setMcpBearerMock(...args),+}));++import { GET } from "./route";++function makeReq(url: string): Request {+ return new Request(url, { method: "GET" });+}++function makePending(overrides: Record<string, unknown> = {}) {+ return {+ catalog_key: "notfair-googleads",+ stored_key: "acme-notfair-googleads",+ display_name: "NotFair Google Ads",+ resource_url: "https://mcp.example.com/sse",+ issuer: "https://auth.example.com",+ token_endpoint: "https://auth.example.com/token",+ client_id: "client-123",+ client_secret: "secret-456",+ code_verifier: "verifier",+ redirect_uri: "http://localhost/api/mcp-oauth/callback",+ project_slug: "acme",+ return_to: "/acme/agents/cmo/mcp",+ created_at: Date.now(),+ ...overrides,+ };+}++describe("GET /api/mcp-oauth/callback", () => {+ const fetchMock = vi.fn();+ const originalFetch = globalThis.fetch;++ beforeEach(() => {+ vi.clearAllMocks();+ fetchMock.mockReset();+ globalThis.fetch = fetchMock as unknown as typeof fetch;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ it("returns 400 HTML when state param is missing", async () => {+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?code=abc"),+ );+ expect(res.status).toBe(400);+ expect(res.headers.get("Content-Type")).toContain("text/html");+ const text = await res.text();+ expect(text).toContain("Missing state parameter");+ });++ it("returns 400 HTML when pending flow is not found / expired", async () => {+ consumePendingMock.mockReturnValueOnce(null);+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=ghost&code=abc"),+ );+ expect(res.status).toBe(400);+ const text = await res.text();+ expect(text).toContain("expired or was already used");+ });++ it("redirects with mcp_error when upstream returned an error param", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ const res = await GET(+ makeReq(+ "http://localhost/api/mcp-oauth/callback?state=s1&error=access_denied",+ ),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.pathname).toBe("/acme/agents/cmo/mcp");+ expect(location.searchParams.get("mcp_error")).toContain("access_denied");+ });++ it("redirects with mcp_error when code is missing", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1"),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.searchParams.get("mcp_error")).toContain("no code");+ });++ it("redirects with mcp_error when token exchange returns non-2xx", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ fetchMock.mockResolvedValueOnce(new Response("bad", { status: 400 }));+ const res = await GET(+ makeReq(+ "http://localhost/api/mcp-oauth/callback?state=s1&code=abc",+ ),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.searchParams.get("mcp_error")).toContain("HTTP 400");+ expect(location.searchParams.get("mcp_error")).toContain("bad");+ });++ it("redirects with mcp_error when token response is missing access_token", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ token_type: "Bearer" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.searchParams.get("mcp_error")).toContain(+ "no access_token",+ );+ });++ it("redirects with mcp_error when fetch throws", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ fetchMock.mockRejectedValueOnce(new TypeError("network fail"));+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.searchParams.get("mcp_error")).toContain("network fail");+ });++ it("redirects with mcp_error when setMcpBearer throws (and scrubs bearer + oat_ tokens)", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: "the-token" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ setMcpBearerMock.mockRejectedValueOnce(+ new Error(+ "Failed: Bearer abc.DEF-123_456 and oat_aBcDeF leaked here",+ ),+ );+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ const errMsg = location.searchParams.get("mcp_error")!;+ expect(errMsg).toContain("Saving MCP config failed");+ expect(errMsg).toContain("Bearer [redacted]");+ expect(errMsg).toContain("oat_[redacted]");+ expect(errMsg).not.toContain("abc.DEF-123_456");+ expect(errMsg).not.toContain("oat_aBcDeF");+ });++ it("redirects with mcp_connected on full success and includes client_secret in token body", async () => {+ const pending = makePending();+ consumePendingMock.mockReturnValueOnce(pending);+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: "live-token" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ setMcpBearerMock.mockResolvedValueOnce(undefined);++ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.pathname).toBe("/acme/agents/cmo/mcp");+ expect(location.searchParams.get("mcp_connected")).toBe(+ "NotFair Google Ads",+ );++ expect(setMcpBearerMock).toHaveBeenCalledWith(+ "acme-notfair-googleads",+ "https://mcp.example.com/sse",+ "live-token",+ );++ const [tokenUrl, init] = fetchMock.mock.calls[0]!;+ expect(tokenUrl).toBe("https://auth.example.com/token");+ const body = (init as RequestInit).body as string;+ expect(body).toContain("grant_type=authorization_code");+ expect(body).toContain("code=abc");+ expect(body).toContain("client_id=client-123");+ expect(body).toContain("client_secret=secret-456");+ expect(body).toContain("code_verifier=verifier");+ });++ it("omits client_secret when pending flow has none (public client)", async () => {+ const pending = makePending({ client_secret: undefined });+ consumePendingMock.mockReturnValueOnce(pending);+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: "tok" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ setMcpBearerMock.mockResolvedValueOnce(undefined);++ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const body = fetchMock.mock.calls[0]![1].body as string;+ expect(body).not.toContain("client_secret");+ });++ it("defaults return_to to '/' when pending flow has no return_to", async () => {+ const pending = makePending({ return_to: undefined });+ consumePendingMock.mockReturnValueOnce(pending);+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ access_token: "tok" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ setMcpBearerMock.mockResolvedValueOnce(undefined);++ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const location = new URL(res.headers.get("location")!);+ expect(location.pathname).toBe("/");+ });++ it("truncates very long token-exchange error responses in the redirect URL", async () => {+ consumePendingMock.mockReturnValueOnce(makePending());+ const longBody = "x".repeat(500);+ fetchMock.mockResolvedValueOnce(new Response(longBody, { status: 500 }));+ const res = await GET(+ makeReq("http://localhost/api/mcp-oauth/callback?state=s1&code=abc"),+ );+ expect(res.status).toBe(307);+ const errMsg = new URL(res.headers.get("location")!).searchParams.get(+ "mcp_error",+ )!;+ // We truncate at 200 chars plus an ellipsis.+ expect(errMsg).toContain("…");+ expect(errMsg.length).toBeLessThan(longBody.length);+ });+});diff --git a/src/app/api/oauth/[provider]/callback/route.test.ts b/src/app/api/oauth/[provider]/callback/route.test.tsnew file mode 100644index 00000000..d691216a--- /dev/null+++ b/src/app/api/oauth/[provider]/callback/route.test.ts@@ -0,0 +1,239 @@+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const storeOAuthTokenMock = vi.fn();+vi.mock("@/server/db/oauth", () => ({+ storeOAuthToken: (...args: unknown[]) => storeOAuthTokenMock(...args),+}));++// vi.hoisted runs before any ESM `import` statement, so TOKEN_CONFIG can+// snapshot a properly-configured process.env at module-load time.+const { ORIGINAL_ENV } = vi.hoisted(() => {+ const orig = { ...process.env };+ process.env.GOOGLE_ADS_CLIENT_ID = "id";+ process.env.GOOGLE_ADS_CLIENT_SECRET = "secret";+ delete process.env.GSC_CLIENT_ID;+ delete process.env.GSC_CLIENT_SECRET;+ return { ORIGINAL_ENV: orig };+});++import { GET } from "./route";++function makeReq(url: string): Request {+ return new Request(url, { method: "GET" });+}++function buildState(project: string): string {+ return Buffer.from(JSON.stringify({ project, ts: Date.now() })).toString(+ "base64url",+ );+}++describe("GET /api/oauth/[provider]/callback", () => {+ const fetchMock = vi.fn();+ const originalFetch = globalThis.fetch;++ beforeEach(() => {+ vi.clearAllMocks();+ fetchMock.mockReset();+ globalThis.fetch = fetchMock as unknown as typeof fetch;+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ });++ afterAll(() => {+ process.env = { ...ORIGINAL_ENV };+ });++ it("returns 400 HTML when provider sends an error param", async () => {+ const res = await GET(+ makeReq(+ "http://localhost/api/oauth/google_ads/callback?error=access_denied",+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(400);+ expect(res.headers.get("Content-Type")).toContain("text/html");+ const text = await res.text();+ expect(text).toContain("OAuth denied");+ expect(text).toContain("access_denied");+ });++ it("escapes HTML in the error param", async () => {+ const res = await GET(+ makeReq(+ "http://localhost/api/oauth/google_ads/callback?error=" ++ encodeURIComponent("<script>x</script>"),+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ const text = await res.text();+ expect(text).not.toContain("<script>x</script>");+ expect(text).toContain("<script>");+ });++ it("returns 400 when code or state is missing", async () => {+ const res = await GET(+ makeReq("http://localhost/api/oauth/google_ads/callback?code=abc"),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(400);+ const text = await res.text();+ expect(text).toContain("Missing code or state");+ });++ it("returns 400 when state token is malformed base64", async () => {+ const res = await GET(+ makeReq(+ "http://localhost/api/oauth/google_ads/callback?code=abc&state=not-base64-json!!!",+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(400);+ const text = await res.text();+ expect(text).toContain("Invalid state token");+ });++ it("returns 503 when provider is known but client id is not configured (gsc)", async () => {+ const res = await GET(+ makeReq(+ `http://localhost/api/oauth/gsc/callback?code=abc&state=${buildState("acme")}`,+ ),+ { params: Promise.resolve({ provider: "gsc" }) },+ );+ expect(res.status).toBe(503);+ const text = await res.text();+ expect(text).toContain("OAuth not configured");+ expect(text).toContain("GSC_CLIENT_ID");+ });++ it("returns 503 when provider key is entirely unknown (config undefined)", async () => {+ const res = await GET(+ makeReq(+ `http://localhost/api/oauth/whatever/callback?code=abc&state=${buildState("acme")}`,+ ),+ { params: Promise.resolve({ provider: "whatever" }) },+ );+ expect(res.status).toBe(503);+ const text = await res.text();+ expect(text).toContain("OAuth not configured");+ });++ it("returns 502 when token exchange request fails", async () => {+ fetchMock.mockResolvedValueOnce(+ new Response("invalid_grant detail", { status: 400 }),+ );+ const res = await GET(+ makeReq(+ `http://localhost/api/oauth/google_ads/callback?code=abc&state=${buildState("acme")}`,+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(502);+ const text = await res.text();+ expect(text).toContain("Token exchange failed");+ expect(text).toContain("invalid_grant detail");+ });++ it("returns 400 when token response is missing refresh_token", async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ access_token: "at",+ expires_in: 3600,+ scope: "scope",+ token_type: "Bearer",+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ const res = await GET(+ makeReq(+ `http://localhost/api/oauth/google_ads/callback?code=abc&state=${buildState("acme")}`,+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(400);+ const text = await res.text();+ expect(text).toContain("No refresh token");+ });++ it("returns 500 when token storage fails", async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ access_token: "at",+ refresh_token: "rt",+ expires_in: 3600,+ scope: "scope",+ token_type: "Bearer",+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ storeOAuthTokenMock.mockRejectedValueOnce(new Error("keychain failed"));++ const res = await GET(+ makeReq(+ `http://localhost/api/oauth/google_ads/callback?code=abc&state=${buildState("acme")}`,+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(500);+ const text = await res.text();+ expect(text).toContain("Could not store token");+ expect(text).toContain("keychain failed");+ });++ it("redirects to /<project>/connections on full success", async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ access_token: "at",+ refresh_token: "rt",+ expires_in: 3600,+ scope: "scope1 scope2",+ token_type: "Bearer",+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ storeOAuthTokenMock.mockResolvedValueOnce(undefined);++ const res = await GET(+ makeReq(+ `http://localhost/api/oauth/google_ads/callback?code=mycode&state=${buildState("acme")}`,+ ),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(307);+ expect(res.headers.get("location")).toBe(+ "http://localhost/acme/connections?connected=google_ads",+ );++ expect(storeOAuthTokenMock).toHaveBeenCalledTimes(1);+ const stored = storeOAuthTokenMock.mock.calls[0]![0] as {+ project_slug: string;+ provider: string;+ access_token: string;+ refresh_token: string;+ scope: string;+ };+ expect(stored.project_slug).toBe("acme");+ expect(stored.provider).toBe("google_ads");+ expect(stored.access_token).toBe("at");+ expect(stored.refresh_token).toBe("rt");+ expect(stored.scope).toBe("scope1 scope2");++ const [tokenUrl, init] = fetchMock.mock.calls[0]!;+ expect(tokenUrl).toBe("https://oauth2.googleapis.com/token");+ expect((init as RequestInit).method).toBe("POST");+ const bodyAsString = ((init as RequestInit).body as URLSearchParams).toString();+ expect(bodyAsString).toContain("code=mycode");+ expect(bodyAsString).toContain("grant_type=authorization_code");+ expect(bodyAsString).toContain(+ "redirect_uri=http%3A%2F%2Flocalhost%2Fapi%2Foauth%2Fgoogle_ads%2Fcallback",+ );+ });+});diff --git a/src/app/api/oauth/[provider]/start/route.test.ts b/src/app/api/oauth/[provider]/start/route.test.tsnew file mode 100644index 00000000..b37fe877--- /dev/null+++ b/src/app/api/oauth/[provider]/start/route.test.ts@@ -0,0 +1,87 @@+import { afterAll, describe, expect, it, vi } from "vitest";++// Set env BEFORE the route is imported. vi.hoisted runs before any ESM+// `import` statement, including the import below — without this the+// OAUTH_CONFIG closure snapshots an empty env and every google_ads test+// hits the 503 "not configured" branch.+const { ORIGINAL_ENV } = vi.hoisted(() => {+ const orig = { ...process.env };+ process.env.GOOGLE_ADS_CLIENT_ID = "my-google-client-id";+ process.env.GOOGLE_ADS_CLIENT_SECRET = "my-secret";+ delete process.env.GSC_CLIENT_ID;+ delete process.env.GSC_CLIENT_SECRET;+ return { ORIGINAL_ENV: orig };+});++import { GET } from "./route";++function makeReq(url: string): Request {+ return new Request(url, { method: "GET" });+}++describe("GET /api/oauth/[provider]/start", () => {+ afterAll(() => {+ process.env = { ...ORIGINAL_ENV };+ });++ it("returns 400 when project query param is missing", async () => {+ const res = await GET(+ makeReq("http://localhost/api/oauth/google_ads/start"),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(400);+ const body = (await res.json()) as { error: string };+ expect(body.error).toContain("project");+ });++ it("returns 404 when provider is unknown", async () => {+ const res = await GET(+ makeReq("http://localhost/api/oauth/unknown_provider/start?project=acme"),+ { params: Promise.resolve({ provider: "unknown_provider" }) },+ );+ expect(res.status).toBe(404);+ const body = (await res.json()) as { error: string };+ expect(body.error).toMatch(/unknown_provider/i);+ });++ it("returns 503 with helpful text for a known-but-unconfigured provider (gsc)", async () => {+ const res = await GET(+ makeReq("http://localhost/api/oauth/gsc/start?project=acme"),+ { params: Promise.resolve({ provider: "gsc" }) },+ );+ expect(res.status).toBe(503);+ expect(res.headers.get("Content-Type")).toContain("text/plain");+ const text = await res.text();+ expect(text).toContain("GSC_CLIENT_ID");+ expect(text).toContain("GSC_CLIENT_SECRET");+ });++ it("redirects to Google's OAuth consent screen for google_ads when configured", async () => {+ const res = await GET(+ makeReq("http://localhost/api/oauth/google_ads/start?project=acme"),+ { params: Promise.resolve({ provider: "google_ads" }) },+ );+ expect(res.status).toBe(307);+ const location = res.headers.get("location");+ expect(location).toBeTruthy();+ const redirect = new URL(location!);+ expect(redirect.origin).toBe("https://accounts.google.com");+ expect(redirect.pathname).toBe("/o/oauth2/v2/auth");+ expect(redirect.searchParams.get("client_id")).toBe("my-google-client-id");+ expect(redirect.searchParams.get("redirect_uri")).toBe(+ "http://localhost/api/oauth/google_ads/callback",+ );+ expect(redirect.searchParams.get("response_type")).toBe("code");+ expect(redirect.searchParams.get("scope")).toContain("adwords");+ expect(redirect.searchParams.get("access_type")).toBe("offline");+ expect(redirect.searchParams.get("prompt")).toBe("consent");++ const state = redirect.searchParams.get("state");+ expect(state).toBeTruthy();+ const decoded = JSON.parse(+ Buffer.from(state!, "base64url").toString("utf8"),+ ) as { project: string; ts: number };+ expect(decoded.project).toBe("acme");+ expect(typeof decoded.ts).toBe("number");+ });+});diff --git a/src/app/api/projects/[slug]/provision/route.test.ts b/src/app/api/projects/[slug]/provision/route.test.tsnew file mode 100644index 00000000..3a0f45f7--- /dev/null+++ b/src/app/api/projects/[slug]/provision/route.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Project } from "@/types";++const getProjectMock = vi.fn();+vi.mock("@/server/db/projects", () => ({+ getProject: (...args: unknown[]) => getProjectMock(...args),+}));++const ensureProjectAgentsMock = vi.fn();+vi.mock("@/server/agent-templates", () => ({+ ensureProjectAgents: (...args: unknown[]) => ensureProjectAgentsMock(...args),+}));++import { POST } from "./route";++function makeProject(overrides: Partial<Project> = {}): Project {+ return {+ id: "uuid",+ slug: "acme",+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ ...overrides,+ };+}++function makeReq(): Request {+ return new Request("http://localhost/api/projects/acme/provision", {+ method: "POST",+ });+}++describe("POST /api/projects/[slug]/provision", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns 404 when project not found", async () => {+ getProjectMock.mockReturnValueOnce(null);+ const res = await POST(makeReq(), { params: Promise.resolve({ slug: "ghost" }) });+ expect(res.status).toBe(404);+ const body = (await res.json()) as { error: string };+ expect(body.error).toBe("Project not found");+ expect(ensureProjectAgentsMock).not.toHaveBeenCalled();+ });++ it("returns ok with ensureProjectAgents result on success", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ ensureProjectAgentsMock.mockResolvedValueOnce({+ created: ["acme-cmo"],+ existed: [],+ failed: [],+ });+ const res = await POST(makeReq(), { params: Promise.resolve({ slug: "acme" }) });+ expect(res.status).toBe(200);+ const body = (await res.json()) as {+ ok: boolean;+ created: string[];+ existed: string[];+ failed: unknown[];+ };+ expect(body).toEqual({+ ok: true,+ created: ["acme-cmo"],+ existed: [],+ failed: [],+ });+ expect(ensureProjectAgentsMock).toHaveBeenCalledWith("acme");+ });++ it("returns ok even when ensureProjectAgents reports partial failures", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "acme" }));+ ensureProjectAgentsMock.mockResolvedValueOnce({+ created: [],+ existed: ["acme-cmo"],+ failed: [{ name: "acme-google-ads", error: "boom" }],+ });+ const res = await POST(makeReq(), { params: Promise.resolve({ slug: "acme" }) });+ expect(res.status).toBe(200);+ const body = (await res.json()) as {+ ok: boolean;+ failed: Array<{ name: string; error: string }>;+ };+ expect(body.ok).toBe(true);+ expect(body.failed).toHaveLength(1);+ });++ it("propagates the slug from params to getProject + ensureProjectAgents", async () => {+ getProjectMock.mockReturnValueOnce(makeProject({ slug: "other" }));+ ensureProjectAgentsMock.mockResolvedValueOnce({ created: [], existed: [], failed: [] });+ await POST(makeReq(), { params: Promise.resolve({ slug: "other" }) });+ expect(getProjectMock).toHaveBeenCalledWith("other");+ expect(ensureProjectAgentsMock).toHaveBeenCalledWith("other");+ });+});diff --git a/src/components/agent-danger-zone.test.tsx b/src/components/agent-danger-zone.test.tsxnew file mode 100644index 00000000..f41f1b09--- /dev/null+++ b/src/components/agent-danger-zone.test.tsx@@ -0,0 +1,200 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const router = {+ push: vi.fn(),+ refresh: vi.fn(),+};+const getAgentDeletionSummaryAction = vi.fn();+const deleteAgentCascadeAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+};++vi.mock("next/navigation", () => ({+ useRouter: () => router,+}));++vi.mock("@/server/actions/agents", () => ({+ getAgentDeletionSummaryAction: (...args: unknown[]) =>+ getAgentDeletionSummaryAction(...args),+ deleteAgentCascadeAction: (...args: unknown[]) =>+ deleteAgentCascadeAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ warning: (...args: unknown[]) => toast.warning(...args),+ },+}));++import { AgentDangerZone } from "./agent-danger-zone";++const fullSummary = {+ agent_id: "proj-cmo",+ template_key: "cmo",+ source_agent_id: "src",+ exists_in_openclaw: true,+ crons: [+ { id: "c1", name: "proj/cmo/daily", disabled: false },+ { id: "c2", name: "proj/cmo/weekly", disabled: true },+ ],+ threads: [+ { session_id: "s1", label: "main", last_interaction_at: Date.now() - 30_000 },+ { session_id: "s2", label: "another-thread-name-that-is-much-too-long", last_interaction_at: 0 },+ ],+};++beforeEach(() => {+ router.push.mockReset();+ router.refresh.mockReset();+ getAgentDeletionSummaryAction.mockReset();+ deleteAgentCascadeAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+ toast.warning.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("AgentDangerZone", () => {+ it("renders the delete-agent CTA", () => {+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ expect(screen.getByText("Delete this agent")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /delete agent/i })).toBeInTheDocument();+ });++ it("opens the confirm dialog and shows loading state", async () => {+ getAgentDeletionSummaryAction.mockImplementation(+ () => new Promise(() => {}),+ );+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ expect(+ await screen.findByText(/counting what will be removed/i),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("heading", { name: /Delete .*CMO/i }),+ ).toBeInTheDocument();+ });++ it("shows the summary error when loading the summary fails", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: false,+ error: "could not load",+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ expect(await screen.findByText("could not load")).toBeInTheDocument();+ });++ it("renders cron jobs and thread rows from the deletion summary", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: true,+ data: fullSummary,+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ expect(await screen.findByText(/Cron jobs \(2\)/)).toBeInTheDocument();+ expect(screen.getByText(/Threads \(2\)/)).toBeInTheDocument();+ expect(screen.getByText("proj/cmo/daily")).toBeInTheDocument();+ expect(screen.getByText("disabled")).toBeInTheDocument();+ expect(screen.getByText("Main thread")).toBeInTheDocument();+ expect(screen.getByText("new")).toBeInTheDocument();+ });++ it("shows the empty-state hint when an item list is empty", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: true,+ data: { ...fullSummary, crons: [], threads: [] },+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ expect(+ await screen.findByText(/No scheduled jobs target this agent/i),+ ).toBeInTheDocument();+ expect(screen.getByText(/No chat threads yet/i)).toBeInTheDocument();+ });++ it("calls deleteAgentCascadeAction and routes home on success", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: true,+ data: fullSummary,+ });+ deleteAgentCascadeAction.mockResolvedValue({+ ok: true,+ data: { crons_removed: 2, crons_failed: 0 },+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ await screen.findByText(/Cron jobs \(2\)/);+ fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));+ await waitFor(() =>+ expect(deleteAgentCascadeAction).toHaveBeenCalledWith("proj-cmo"),+ );+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith(+ "Deleted CMO. 2 crons removed.",+ ),+ );+ await waitFor(() => expect(router.push).toHaveBeenCalledWith("/"));+ });++ it("warns when some crons fail to remove during delete", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: true,+ data: fullSummary,+ });+ deleteAgentCascadeAction.mockResolvedValue({+ ok: true,+ data: { crons_removed: 1, crons_failed: 1 },+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ await screen.findByText(/Cron jobs \(2\)/);+ fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));+ await waitFor(() =>+ expect(toast.warning).toHaveBeenCalledWith(+ "Deleted CMO. 1 crons removed, 1 failed.",+ ),+ );+ });++ it("toasts the server error when delete fails", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: true,+ data: fullSummary,+ });+ deleteAgentCascadeAction.mockResolvedValue({+ ok: false,+ error: "nope",+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ await screen.findByText(/Cron jobs \(2\)/);+ fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("nope"));+ expect(router.push).not.toHaveBeenCalled();+ });++ it("closes the dialog when Cancel is clicked", async () => {+ getAgentDeletionSummaryAction.mockResolvedValue({+ ok: true,+ data: fullSummary,+ });+ render(<AgentDangerZone agentId="proj-cmo" agentDisplayName="CMO" />);+ fireEvent.click(screen.getByRole("button", { name: /delete agent/i }));+ await screen.findByText(/Cron jobs \(2\)/);+ fireEvent.click(screen.getByRole("button", { name: /cancel/i }));+ await waitFor(() =>+ expect(screen.queryByText(/Cron jobs/)).not.toBeInTheDocument(),+ );+ });+});diff --git a/src/components/agent-nav.test.tsx b/src/components/agent-nav.test.tsxnew file mode 100644index 00000000..e7577bc1--- /dev/null+++ b/src/components/agent-nav.test.tsx@@ -0,0 +1,115 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, cleanup } from "@testing-library/react";++const pathnameRef: { current: string } = { current: "/proj" };++vi.mock("next/navigation", () => ({+ usePathname: () => pathnameRef.current,+}));++vi.mock("@/components/ui/sidebar", () => ({+ SidebarMenu: ({ children }: { children: React.ReactNode }) => <ul>{children}</ul>,+ SidebarMenuItem: ({ children }: { children: React.ReactNode }) => <li>{children}</li>,+ SidebarMenuButton: ({+ children,+ isActive,+ }: {+ children: React.ReactNode;+ isActive?: boolean;+ asChild?: boolean;+ }) => (+ <div data-active={isActive ? "true" : "false"} data-testid="sidebar-button">+ {children}+ </div>+ ),+}));++import { AgentNav } from "./agent-nav";++const agents = [+ {+ key: "proj-cmo",+ slug: "cmo",+ display_name: "CMO",+ template_key: "cmo" as const,+ },+ {+ key: "proj-google-ads",+ slug: "google-ads",+ display_name: "Google Ads",+ template_key: "google_ads" as const,+ },+ {+ key: "proj-custom",+ slug: "custom",+ display_name: "Custom Bot",+ },+];++beforeEach(() => {+ pathnameRef.current = "/proj";+});++afterEach(() => {+ cleanup();+});++describe("AgentNav", () => {+ it("renders one entry per agent linking to the tasks tab", () => {+ render(<AgentNav projectSlug="proj" agents={agents} />);+ expect(screen.getByRole("link", { name: /CMO/i })).toHaveAttribute(+ "href",+ "/proj/agents/cmo/tasks",+ );+ expect(screen.getByRole("link", { name: /Google Ads/i })).toHaveAttribute(+ "href",+ "/proj/agents/google-ads/tasks",+ );+ expect(screen.getByRole("link", { name: /Custom Bot/i })).toHaveAttribute(+ "href",+ "/proj/agents/custom/tasks",+ );+ });++ it("marks the active agent when the pathname equals the agent base", () => {+ pathnameRef.current = "/proj/agents/cmo";+ render(<AgentNav projectSlug="proj" agents={agents} />);+ const buttons = screen.getAllByTestId("sidebar-button");+ const cmoButton = buttons.find((b) => b.textContent?.includes("CMO"));+ expect(cmoButton?.getAttribute("data-active")).toBe("true");+ const customButton = buttons.find((b) => b.textContent?.includes("Custom Bot"));+ expect(customButton?.getAttribute("data-active")).toBe("false");+ });++ it("marks the active agent when the pathname is nested under the agent base", () => {+ pathnameRef.current = "/proj/agents/google-ads/skills";+ render(<AgentNav projectSlug="proj" agents={agents} />);+ const buttons = screen.getAllByTestId("sidebar-button");+ const target = buttons.find((b) => b.textContent?.includes("Google Ads"));+ expect(target?.getAttribute("data-active")).toBe("true");+ });++ it("renders the in-flight count badge when count > 0", () => {+ render(+ <AgentNav+ projectSlug="proj"+ agents={agents}+ inFlightCounts={{ "proj-cmo": 3 }}+ />,+ );+ expect(screen.getByText("3")).toBeInTheDocument();+ expect(screen.getByLabelText("3 running")).toBeInTheDocument();+ });++ it("does not render a count when in-flight is 0", () => {+ render(+ <AgentNav+ projectSlug="proj"+ agents={agents}+ inFlightCounts={{ "proj-cmo": 0 }}+ />,+ );+ expect(screen.queryByLabelText(/running/i)).not.toBeInTheDocument();+ });+});diff --git a/src/components/agent-rename-card.test.tsx b/src/components/agent-rename-card.test.tsxnew file mode 100644index 00000000..4cea2c96--- /dev/null+++ b/src/components/agent-rename-card.test.tsx@@ -0,0 +1,148 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const router = {+ push: vi.fn(),+ refresh: vi.fn(),+};+const renameAgentAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("next/navigation", () => ({+ useRouter: () => router,+}));++vi.mock("@/server/actions/agents", () => ({+ renameAgentAction: (...args: unknown[]) => renameAgentAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++import { AgentRenameCard } from "./agent-rename-card";++beforeEach(() => {+ router.push.mockReset();+ router.refresh.mockReset();+ renameAgentAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => {+ cleanup();+});++function defaultProps() {+ return {+ agentId: "proj-bot",+ projectSlug: "proj",+ currentDisplayName: "Bot",+ currentSlug: "bot",+ };+}++describe("AgentRenameCard", () => {+ it("seeds the input with the current display name", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ expect(screen.getByLabelText(/display name/i)).toHaveValue("Bot");+ });++ it("renders the project slug as a non-editable prefix", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ expect(screen.getByText("proj-")).toBeInTheDocument();+ });++ it("disables Save when the name is unchanged", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ const btn = screen.getByRole("button", { name: /save name/i });+ expect(btn).toBeDisabled();+ });++ it("shows 'same slug' hint when only display-name casing changes (same slug)", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "BOT" } });+ expect(screen.getByText(/same slug/i)).toBeInTheDocument();+ });++ it("enables Save with a 'Save name' label when only the display name changes (same slug)", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "BOT" } });+ const btn = screen.getByRole("button", { name: /save name/i });+ expect(btn).not.toBeDisabled();+ });++ it("switches the button label to 'Rename agent' when the slug changes", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "marketing-lead" } });+ expect(+ screen.getByRole("button", { name: /rename agent/i }),+ ).toBeInTheDocument();+ expect(screen.getByText(/slug changes from/i)).toBeInTheDocument();+ });++ it("flags invalid slug input and disables the button", () => {+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "!!!" } });+ expect(screen.getByText(/invalid name/i)).toBeInTheDocument();+ const btn = screen.getByRole("button", { name: /save name|rename agent/i });+ expect(btn).toBeDisabled();+ });++ it("calls renameAgentAction and routes on a full-rename success", async () => {+ renameAgentAction.mockResolvedValue({+ ok: true,+ data: { full_rename: true, slug: "marketer", display_name: "Marketer" },+ });+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "Marketer" } });+ fireEvent.click(screen.getByRole("button", { name: /rename agent/i }));+ await waitFor(() =>+ expect(renameAgentAction).toHaveBeenCalledWith({+ agent_id: "proj-bot",+ new_display_name: "Marketer",+ }),+ );+ await waitFor(() =>+ expect(router.push).toHaveBeenCalledWith("/proj/agents/marketer/settings"),+ );+ expect(toast.success).toHaveBeenCalled();+ });++ it("only refreshes (no push) on a same-slug rename success", async () => {+ renameAgentAction.mockResolvedValue({+ ok: true,+ data: { full_rename: false, slug: "bot", display_name: "BOT" },+ });+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "BOT" } });+ fireEvent.click(screen.getByRole("button", { name: /save name/i }));+ await waitFor(() => expect(renameAgentAction).toHaveBeenCalled());+ expect(router.push).not.toHaveBeenCalled();+ await waitFor(() => expect(router.refresh).toHaveBeenCalled());+ });++ it("toasts the server error when rename fails", async () => {+ renameAgentAction.mockResolvedValue({ ok: false, error: "name taken" });+ render(<AgentRenameCard {...defaultProps()} />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "x-newname" } });+ fireEvent.click(screen.getByRole("button", { name: /rename agent/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("name taken"));+ expect(router.push).not.toHaveBeenCalled();+ });+});diff --git a/src/components/agent-tabs.test.tsx b/src/components/agent-tabs.test.tsxnew file mode 100644index 00000000..f1cd640c--- /dev/null+++ b/src/components/agent-tabs.test.tsx@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, cleanup } from "@testing-library/react";++const pathnameRef: { current: string } = { current: "/proj/agents/cmo/tasks" };++vi.mock("next/navigation", () => ({+ usePathname: () => pathnameRef.current,+}));++import { AgentTabs } from "./agent-tabs";++beforeEach(() => {+ pathnameRef.current = "/proj/agents/cmo/tasks";+});++afterEach(() => {+ cleanup();+});++describe("AgentTabs", () => {+ it("renders all six tabs as links pointing under the agent base path", () => {+ render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);+ const tasks = screen.getByRole("link", { name: /tasks/i });+ const chat = screen.getByRole("link", { name: /chat/i });+ const files = screen.getByRole("link", { name: /files/i });+ const skills = screen.getByRole("link", { name: /skills/i });+ const cron = screen.getByRole("link", { name: /cron/i });+ const settings = screen.getByRole("link", { name: /settings/i });+ expect(tasks).toHaveAttribute("href", "/proj/agents/cmo/tasks");+ expect(chat).toHaveAttribute("href", "/proj/agents/cmo/chat");+ expect(files).toHaveAttribute("href", "/proj/agents/cmo/files");+ expect(skills).toHaveAttribute("href", "/proj/agents/cmo/skills");+ expect(cron).toHaveAttribute("href", "/proj/agents/cmo/cron");+ expect(settings).toHaveAttribute("href", "/proj/agents/cmo/settings");+ });++ it("marks the tab as active when the pathname equals the tab href", () => {+ pathnameRef.current = "/proj/agents/cmo/chat";+ render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);+ const chat = screen.getByRole("link", { name: /chat/i });+ expect(chat.className).toContain("text-foreground");+ expect(chat.className).not.toContain("text-muted-foreground");+ const tasks = screen.getByRole("link", { name: /tasks/i });+ expect(tasks.className).toContain("text-muted-foreground");+ });++ it("marks the tab as active for nested subpaths under it", () => {+ pathnameRef.current = "/proj/agents/cmo/tasks/abc123";+ render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);+ const tasks = screen.getByRole("link", { name: /tasks/i });+ expect(tasks.className).toContain("text-foreground");+ });++ it("renders the underline indicator span only for the active tab", () => {+ pathnameRef.current = "/proj/agents/cmo/skills";+ const { container } = render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);+ const indicators = container.querySelectorAll('span[aria-hidden="true"]');+ expect(indicators.length).toBe(1);+ });++ it("treats no-match pathname as no active tab", () => {+ pathnameRef.current = "/some/other/place";+ render(<AgentTabs projectSlug="proj" agentSlug="cmo" />);+ const tasks = screen.getByRole("link", { name: /tasks/i });+ expect(tasks.className).toContain("text-muted-foreground");+ });+});diff --git a/src/components/agent-task-workspace.test.tsx b/src/components/agent-task-workspace.test.tsxnew file mode 100644index 00000000..726c5fba--- /dev/null+++ b/src/components/agent-task-workspace.test.tsx@@ -0,0 +1,395 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";++// ── next/navigation -------------------------------------------------------+const replaceMock = vi.fn();+const refreshMock = vi.fn();+const searchParamsState: { qs: string } = { qs: "" };+vi.mock("next/navigation", () => ({+ useRouter: () => ({ replace: replaceMock, refresh: refreshMock, push: vi.fn() }),+ useSearchParams: () => new URLSearchParams(searchParamsState.qs),+}));++// next/link → plain anchor (no router behavior in jsdom).+vi.mock("next/link", () => ({+ default: ({+ href,+ children,+ ...rest+ }: {+ href: string;+ children: React.ReactNode;+ }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++// ── server actions --------------------------------------------------------+const cancelTaskMock = vi.fn();+vi.mock("@/server/actions/tasks", () => ({+ cancelTaskAction: (...a: unknown[]) => cancelTaskMock(...a),+ // StartAllTasksButton imports this too — give it a benign default.+ startAllProposedTasksAction: vi.fn().mockResolvedValue({+ ok: true,+ data: { started: 0, task_ids: [] },+ }),+}));++// ── sonner toasts ---------------------------------------------------------+const toastMocks = { success: vi.fn(), error: vi.fn(), info: vi.fn() };+vi.mock("sonner", () => ({+ toast: {+ success: (...a: unknown[]) => toastMocks.success(...a),+ error: (...a: unknown[]) => toastMocks.error(...a),+ info: (...a: unknown[]) => toastMocks.info(...a),+ },+}));++// ── LiveTranscript: heavy fetch / SSE component. Stub to a marker so we+// can assert it mounts with the right props without dragging in its+// polling machinery.+vi.mock("@/components/live-transcript", () => ({+ LiveTranscript: (props: Record<string, unknown>) => (+ <div+ data-testid="live-transcript"+ data-thread={String(props.threadId)}+ data-disabled={String(props.composerDisabled)}+ >+ LiveTranscript stub+ </div>+ ),+}));++import { AgentTaskWorkspace } from "./agent-task-workspace";+import type { Task } from "@/types";++function makeTask(overrides: Partial<Task> = {}): Task {+ return {+ id: "uuid-1",+ display_id: "demo-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ title: "Set up daily anomaly check",+ brief: "Detect daily spend anomalies",+ success_criteria: "Send slack alert on 3σ deviation",+ deadline_iso: null,+ status: "proposed",+ result_json: null,+ error_message: null,+ thread_id: null,+ assigner_agent_id: "demo-cmo",+ created_at: new Date(Date.now() - 5 * 60_000).toISOString(),+ updated_at: new Date(Date.now() - 60_000).toISOString(),+ ...overrides,+ };+}++function baseProps(overrides: Partial<Parameters<typeof AgentTaskWorkspace>[0]> = {}) {+ return {+ projectSlug: "demo",+ agentSlug: "google-ads",+ agentFullId: "demo-google-ads",+ agentDisplayName: "Google Ads",+ tasks: [] as Task[],+ selected: null,+ proposedCount: 0,+ ...overrides,+ };+}++beforeEach(() => {+ replaceMock.mockReset();+ refreshMock.mockReset();+ cancelTaskMock.mockReset();+ toastMocks.success.mockReset();+ toastMocks.error.mockReset();+ toastMocks.info.mockReset();+ searchParamsState.qs = "";+});++describe("AgentTaskWorkspace empty state", () => {+ it("shows 'Nothing assigned yet.' subtitle and zero count when tasks is empty", () => {+ render(<AgentTaskWorkspace {...baseProps()} />);+ expect(screen.getByText("Nothing assigned yet.")).toBeInTheDocument();+ expect(screen.getByText("The CMO will delegate tasks here.")).toBeInTheDocument();+ // Right pane empty state for hasTasks=false.+ expect(screen.getByText(/Google Ads has no tasks yet/)).toBeInTheDocument();+ });++ it("renders the 'Select a task' right-pane state when tasks exist but none selected", () => {+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [makeTask({ status: "succeeded" })],+ })}+ />,+ );+ expect(screen.getByText("Select a task")).toBeInTheDocument();+ expect(screen.getByText(/Pick one from the left/)).toBeInTheDocument();+ });+});++describe("AgentTaskWorkspace in-flight summary + StartAllTasksButton", () => {+ it("counts running + proposed + approved as 'in flight' and hides the start-all button when proposedCount=0", () => {+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [+ makeTask({ id: "a", display_id: "demo-1", status: "running" }),+ makeTask({ id: "b", display_id: "demo-2", status: "approved" }),+ makeTask({ id: "c", display_id: "demo-3", status: "succeeded" }),+ ],+ proposedCount: 0,+ })}+ />,+ );+ expect(screen.getByText(/in flight/)).toBeInTheDocument();+ // The summary "2 in flight" text is split across nodes; just look for "2".+ const inFlightPara = screen.getByText(/in flight/).closest("p");+ expect(inFlightPara?.textContent).toContain("2");+ expect(screen.queryByRole("button", { name: /Start all/ })).not.toBeInTheDocument();+ });++ it("renders the StartAllTasksButton when proposedCount > 0", () => {+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [makeTask({ status: "proposed" })],+ proposedCount: 1,+ })}+ />,+ );+ expect(screen.getByRole("button", { name: /Start all 1 task/ })).toBeInTheDocument();+ });++ it("falls back to 'All quiet.' when there are tasks but none in flight", () => {+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [makeTask({ status: "succeeded" })],+ })}+ />,+ );+ expect(screen.getByText("All quiet.")).toBeInTheDocument();+ });+});++describe("AgentTaskWorkspace task list grouping", () => {+ it("groups tasks by status and labels each group", () => {+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [+ makeTask({ id: "1", display_id: "demo-1", status: "running" }),+ makeTask({ id: "2", display_id: "demo-2", status: "proposed" }),+ makeTask({ id: "3", display_id: "demo-3", status: "succeeded" }),+ makeTask({ id: "4", display_id: "demo-4", status: "failed", error_message: "boom" }),+ ],+ })}+ />,+ );+ expect(screen.getByText("Running")).toBeInTheDocument();+ expect(screen.getByText("Proposed")).toBeInTheDocument();+ expect(screen.getByText("Done")).toBeInTheDocument();+ expect(screen.getByText("Failed")).toBeInTheDocument();+ // Failed task surfaces the error message in the row.+ expect(screen.getByText("boom")).toBeInTheDocument();+ });++ it("falls back to brief.slice(0,80) when task.title is null", () => {+ const brief = "This is a fallback brief shown when the task has no title field at all and we need text.";+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [makeTask({ title: null, brief })],+ })}+ />,+ );+ expect(screen.getByText(brief.slice(0, 80))).toBeInTheDocument();+ });++ it("clicking a task row calls router.replace with the display_id as ?task=", () => {+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [makeTask({ display_id: "demo-7", status: "proposed" })],+ })}+ />,+ );+ fireEvent.click(screen.getByText("Set up daily anomaly check"));+ expect(replaceMock).toHaveBeenCalledTimes(1);+ expect(replaceMock).toHaveBeenCalledWith(+ "?task=demo-7",+ { scroll: false },+ );+ });++ it("marks selected row via aria-current when ?task= matches display_id", () => {+ searchParamsState.qs = "task=demo-9";+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [+ makeTask({ id: "x", display_id: "demo-9", status: "proposed", title: "alpha" }),+ makeTask({ id: "y", display_id: "demo-10", status: "proposed", title: "beta" }),+ ],+ })}+ />,+ );+ const alphaBtn = screen.getByText("alpha").closest("button");+ const betaBtn = screen.getByText("beta").closest("button");+ expect(alphaBtn).toHaveAttribute("aria-current", "true");+ expect(betaBtn).not.toHaveAttribute("aria-current");+ });+});++describe("AgentTaskWorkspace selected-task panel", () => {+ it("renders title, display_id, status badge, and the live transcript stub", () => {+ const task = makeTask({+ display_id: "demo-42",+ title: "Audit yesterday's spend",+ status: "running",+ });+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [task],+ selected: {+ task,+ threadId: "thr-1",+ sessionKey: "agent:demo-google-ads:thr-1",+ initialEvents: [],+ initialByteOffset: 0,+ },+ })}+ />,+ );+ expect(screen.getAllByText("demo-42").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Audit yesterday's spend").length).toBeGreaterThan(0);+ expect(screen.getAllByText("running").length).toBeGreaterThan(0);+ const stub = screen.getByTestId("live-transcript");+ expect(stub.getAttribute("data-thread")).toBe("thr-1");+ expect(stub.getAttribute("data-disabled")).toBe("true");+ });++ it("renders '(untitled task)' fallback when selected task title is null", () => {+ const task = makeTask({ title: null });+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [task],+ selected: {+ task,+ threadId: "thr-1",+ sessionKey: "agent:demo-google-ads:thr-1",+ initialEvents: [],+ initialByteOffset: 0,+ },+ })}+ />,+ );+ expect(screen.getByText("(untitled task)")).toBeInTheDocument();+ });++ it("expanding the Brief details surfaces brief + success criteria", () => {+ const task = makeTask({+ brief: "Brief body text",+ success_criteria: "Success criteria text",+ status: "succeeded",+ });+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [task],+ selected: {+ task,+ threadId: "thr-1",+ sessionKey: "k",+ initialEvents: [],+ initialByteOffset: 0,+ },+ })}+ />,+ );+ expect(screen.getByText(/Brief body text/)).toBeInTheDocument();+ expect(screen.getByText("Success criteria:")).toBeInTheDocument();+ expect(screen.getByText(/Success criteria text/)).toBeInTheDocument();+ });++ it("does not render the Cancel button on terminal-status tasks", () => {+ const task = makeTask({ status: "succeeded" });+ render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [task],+ selected: {+ task,+ threadId: "thr-1",+ sessionKey: "k",+ initialEvents: [],+ initialByteOffset: 0,+ },+ })}+ />,+ );+ expect(screen.queryByRole("button", { name: /Cancel/ })).not.toBeInTheDocument();+ });+});++describe("AgentTaskWorkspace CancelTaskButton", () => {+ function renderWithRunningSelected() {+ const task = makeTask({ display_id: "demo-77", status: "running" });+ return render(+ <AgentTaskWorkspace+ {...baseProps({+ tasks: [task],+ selected: {+ task,+ threadId: "thr",+ sessionKey: "k",+ initialEvents: [],+ initialByteOffset: 0,+ },+ })}+ />,+ );+ }++ it("first click toggles to confirm state without calling the action", () => {+ renderWithRunningSelected();+ const btn = screen.getByRole("button", { name: /Cancel/ });+ fireEvent.click(btn);+ expect(screen.getByRole("button", { name: /Click again to cancel/ })).toBeInTheDocument();+ expect(cancelTaskMock).not.toHaveBeenCalled();+ });++ it("second click calls cancelTaskAction with display_id and refreshes on success", async () => {+ cancelTaskMock.mockResolvedValue({ ok: true });+ renderWithRunningSelected();+ fireEvent.click(screen.getByRole("button", { name: /Cancel/ }));+ fireEvent.click(screen.getByRole("button", { name: /Click again to cancel/ }));+ await waitFor(() => {+ expect(cancelTaskMock).toHaveBeenCalledWith("demo-77");+ expect(toastMocks.success).toHaveBeenCalledWith("Task cancelled.");+ expect(refreshMock).toHaveBeenCalled();+ });+ });++ it("surfaces server error via toast and resets the confirm state", async () => {+ cancelTaskMock.mockResolvedValue({ ok: false, error: "nope" });+ renderWithRunningSelected();+ fireEvent.click(screen.getByRole("button", { name: /Cancel/ }));+ fireEvent.click(screen.getByRole("button", { name: /Click again to cancel/ }));+ await waitFor(() => {+ expect(toastMocks.error).toHaveBeenCalledWith("nope");+ });+ expect(refreshMock).not.toHaveBeenCalled();+ // Confirm state cleared.+ await waitFor(() => {+ expect(screen.getByRole("button", { name: /Cancel/ })).toBeInTheDocument();+ });+ });+});diff --git a/src/components/app-sidebar.test.tsx b/src/components/app-sidebar.test.tsxnew file mode 100644index 00000000..2e2d540d--- /dev/null+++ b/src/components/app-sidebar.test.tsx@@ -0,0 +1,272 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, cleanup } from "@testing-library/react";++const listProjects = vi.fn();+const getActiveProject = vi.fn();+const pendingApprovalCount = vi.fn();+const listProjectAgents = vi.fn();+const inFlightCountsByAgent = vi.fn();+const discoverGateway = vi.fn();++vi.mock("@/server/db/projects", () => ({+ listProjects: (...args: unknown[]) => listProjects(...args),+}));++vi.mock("@/server/active-project", () => ({+ getActiveProject: (...args: unknown[]) => getActiveProject(...args),+}));++vi.mock("@/server/db/approvals", () => ({+ pendingApprovalCount: (...args: unknown[]) => pendingApprovalCount(...args),+}));++vi.mock("@/server/agent-meta", () => ({+ listProjectAgents: (...args: unknown[]) => listProjectAgents(...args),+}));++vi.mock("@/server/db/tasks", () => ({+ inFlightCountsByAgent: (...args: unknown[]) => inFlightCountsByAgent(...args),+}));++vi.mock("@/server/openclaw/gateway-client", () => ({+ discoverGateway: (...args: unknown[]) => discoverGateway(...args),+}));++vi.mock("./project-switcher", () => ({+ ProjectSwitcher: ({+ projects,+ activeSlug,+ }: {+ projects: Array<{ slug: string; display_name: string }>;+ activeSlug: string | null;+ }) => (+ <div data-testid="project-switcher">+ switcher:{activeSlug ?? "-"}/{projects.length}+ </div>+ ),+}));++vi.mock("./agent-nav", () => ({+ AgentNav: ({+ projectSlug,+ agents,+ inFlightCounts,+ }: {+ projectSlug: string;+ agents: Array<{ slug: string; display_name: string }>;+ inFlightCounts?: Record<string, number>;+ }) => (+ <div data-testid="agent-nav">+ nav:{projectSlug}:{agents.map((a) => a.slug).join(",")}:+ {JSON.stringify(inFlightCounts ?? {})}+ </div>+ ),+}));++vi.mock("./create-agent-button", () => ({+ CreateAgentButton: ({ projectSlug }: { projectSlug: string }) => (+ <button data-testid="create-agent-button">create:{projectSlug}</button>+ ),+}));++vi.mock("./global-liveness-poller", () => ({+ GlobalLivenessPoller: ({ hasInFlight }: { hasInFlight: boolean }) => (+ <div data-testid="liveness-poller">live:{String(hasInFlight)}</div>+ ),+}));++vi.mock("@/components/ui/sidebar", () => {+ const Pass = ({ children }: { children?: React.ReactNode }) => <div>{children}</div>;+ return {+ Sidebar: Pass,+ SidebarContent: Pass,+ SidebarFooter: Pass,+ SidebarGroup: Pass,+ SidebarGroupContent: Pass,+ SidebarGroupLabel: Pass,+ SidebarHeader: Pass,+ SidebarMenu: ({ children }: { children: React.ReactNode }) => <ul>{children}</ul>,+ SidebarMenuButton: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ SidebarMenuItem: ({ children }: { children: React.ReactNode }) => <li>{children}</li>,+ SidebarSeparator: () => <hr />,+ SidebarTrigger: () => <button data-testid="sidebar-trigger">trigger</button>,+ };+});++import { AppSidebar } from "./app-sidebar";++const projects = [+ {+ id: "1",+ slug: "alpha",+ display_name: "Alpha",+ created_at: "",+ archived_at: null,+ google_ads_account_id: null,+ },+ {+ id: "2",+ slug: "beta",+ display_name: "Beta",+ created_at: "",+ archived_at: null,+ google_ads_account_id: null,+ },+];++beforeEach(() => {+ listProjects.mockReset();+ getActiveProject.mockReset();+ pendingApprovalCount.mockReset();+ listProjectAgents.mockReset();+ inFlightCountsByAgent.mockReset();+ discoverGateway.mockReset();+ discoverGateway.mockImplementation(() => {+ throw new Error("no gateway");+ });+});++afterEach(() => {+ cleanup();+});++async function renderSidebar() {+ const tree = await AppSidebar();+ return render(tree);+}++describe("AppSidebar", () => {+ it("renders the project switcher with the active slug", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map());+ await renderSidebar();+ expect(screen.getByTestId("project-switcher").textContent).toBe(+ "switcher:alpha/2",+ );+ });++ it("hides the agent + project nav sections when no project is active", async () => {+ listProjects.mockReturnValue([]);+ getActiveProject.mockResolvedValue(null);+ await renderSidebar();+ expect(screen.queryByTestId("agent-nav")).not.toBeInTheDocument();+ expect(screen.queryByText("Agents")).not.toBeInTheDocument();+ expect(screen.queryByText("Project")).not.toBeInTheDocument();+ });++ it("renders project navigation links scoped to the active slug", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map());+ await renderSidebar();+ expect(screen.getByRole("link", { name: /home/i })).toHaveAttribute(+ "href",+ "/alpha",+ );+ expect(screen.getByRole("link", { name: /approvals/i })).toHaveAttribute(+ "href",+ "/alpha/approvals",+ );+ expect(screen.getByRole("link", { name: /tasks/i })).toHaveAttribute(+ "href",+ "/alpha/tasks",+ );+ expect(screen.getByRole("link", { name: /crons/i })).toHaveAttribute(+ "href",+ "/alpha/crons",+ );+ expect(screen.getByRole("link", { name: /activity/i })).toHaveAttribute(+ "href",+ "/alpha/activity",+ );+ expect(screen.getByRole("link", { name: /connections/i })).toHaveAttribute(+ "href",+ "/alpha/connections",+ );+ expect(screen.getByRole("link", { name: /settings/i })).toHaveAttribute(+ "href",+ "/alpha/settings",+ );+ });++ it("shows the approvals badge with the pending count when non-zero", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(7);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map());+ await renderSidebar();+ expect(screen.getByText("7")).toBeInTheDocument();+ });++ it("omits the badge when approvals are zero", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map());+ await renderSidebar();+ expect(screen.queryByText("0")).not.toBeInTheDocument();+ });++ it("forwards agents and in-flight counts to AgentNav", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([+ {+ agent_id: "alpha-cmo",+ slug: "cmo",+ display_name: "CMO",+ description: "",+ template_key: "cmo",+ },+ ]);+ inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 2]]));+ await renderSidebar();+ const nav = screen.getByTestId("agent-nav");+ expect(nav.textContent).toContain("nav:alpha:cmo:");+ expect(nav.textContent).toContain("alpha-cmo");+ expect(nav.textContent).toContain("2");+ });++ it("flips the liveness flag on when any agent has in-flight work", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 1]]));+ await renderSidebar();+ expect(screen.getByTestId("liveness-poller").textContent).toBe("live:true");+ });++ it("keeps the liveness flag off when nothing is running", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map([["alpha-cmo", 0]]));+ await renderSidebar();+ expect(screen.getByTestId("liveness-poller").textContent).toBe("live:false");+ });++ it("shows the CreateAgentButton when a project is active", async () => {+ listProjects.mockReturnValue(projects);+ getActiveProject.mockResolvedValue(projects[0]);+ pendingApprovalCount.mockReturnValue(0);+ listProjectAgents.mockResolvedValue([]);+ inFlightCountsByAgent.mockReturnValue(new Map());+ await renderSidebar();+ expect(screen.getByTestId("create-agent-button").textContent).toBe(+ "create:alpha",+ );+ });+});diff --git a/src/components/approval-card.test.tsx b/src/components/approval-card.test.tsxnew file mode 100644index 00000000..c1eeb3ab--- /dev/null+++ b/src/components/approval-card.test.tsx@@ -0,0 +1,153 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";++const approveMock = vi.fn();+const rejectMock = vi.fn();+const toastErrorMock = vi.fn();+const toastSuccessMock = vi.fn();++vi.mock("@/server/actions/approvals", () => ({+ approveAction: (...a: unknown[]) => approveMock(...a),+ rejectAction: (...a: unknown[]) => rejectMock(...a),+}));++vi.mock("sonner", () => ({+ toast: {+ error: (...a: unknown[]) => toastErrorMock(...a),+ success: (...a: unknown[]) => toastSuccessMock(...a),+ },+}));++import { ApprovalCard } from "./approval-card";+import type { Approval } from "@/types";++function makeApproval(overrides: Partial<Approval> = {}): Approval {+ return {+ id: "ap-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ action_summary: "Raise CPC bid on /signup keyword",+ action_type: "bid_change",+ cost_estimate_usd: 12.5,+ reasoning: null,+ payload_json: "{}",+ status: "pending",+ created_at: new Date(Date.now() - 90_000).toISOString(),+ resolved_at: null,+ ...overrides,+ };+}++beforeEach(() => {+ approveMock.mockReset();+ rejectMock.mockReset();+ toastErrorMock.mockReset();+ toastSuccessMock.mockReset();+});++describe("ApprovalCard", () => {+ it("renders summary, action-type label, cost, agent, and a relative timestamp", () => {+ render(<ApprovalCard approval={makeApproval()} />);+ expect(screen.getByText("Raise CPC bid on /signup keyword")).toBeInTheDocument();+ expect(screen.getByText("Bid change")).toBeInTheDocument();+ expect(screen.getByText("$12.50")).toBeInTheDocument();+ expect(screen.getByText("demo-google-ads")).toBeInTheDocument();+ expect(screen.getByText(/m ago|s ago/)).toBeInTheDocument();+ });++ it("hides the cost line when cost_estimate_usd is zero", () => {+ render(<ApprovalCard approval={makeApproval({ cost_estimate_usd: 0 })} />);+ expect(screen.queryByText(/Cost:/)).not.toBeInTheDocument();+ });++ it("hides the Why? toggle when reasoning is null", () => {+ render(<ApprovalCard approval={makeApproval({ reasoning: null })} />);+ expect(screen.queryByText("Why?")).not.toBeInTheDocument();+ });++ it("toggles reasoning visibility when Why? is clicked", () => {+ render(+ <ApprovalCard+ approval={makeApproval({ reasoning: "Predicted +18% CTR" })}+ />,+ );+ expect(screen.queryByText("Predicted +18% CTR")).not.toBeInTheDocument();+ fireEvent.click(screen.getByText("Why?"));+ expect(screen.getByText("Predicted +18% CTR")).toBeInTheDocument();+ fireEvent.click(screen.getByText("Why?"));+ expect(screen.queryByText("Predicted +18% CTR")).not.toBeInTheDocument();+ });++ it("approve button calls approveAction and shows success toast on ok", async () => {+ approveMock.mockResolvedValue({ ok: true });+ render(<ApprovalCard approval={makeApproval()} />);+ fireEvent.click(screen.getByRole("button", { name: "Approve" }));+ await waitFor(() => {+ expect(approveMock).toHaveBeenCalledWith("ap-1");+ expect(toastSuccessMock).toHaveBeenCalledWith("Approved — running now");+ });+ });++ it("approve button surfaces server error via toast", async () => {+ approveMock.mockResolvedValue({ ok: false, error: "boom" });+ render(<ApprovalCard approval={makeApproval()} />);+ fireEvent.click(screen.getByRole("button", { name: "Approve" }));+ await waitFor(() => {+ expect(toastErrorMock).toHaveBeenCalledWith("boom");+ });+ expect(toastSuccessMock).not.toHaveBeenCalled();+ });++ it("approve uses fallback error string when server omits one", async () => {+ approveMock.mockResolvedValue({ ok: false });+ render(<ApprovalCard approval={makeApproval()} />);+ fireEvent.click(screen.getByRole("button", { name: "Approve" }));+ await waitFor(() => {+ expect(toastErrorMock).toHaveBeenCalledWith("Failed to approve");+ });+ });++ it("reject button calls rejectAction and shows success toast", async () => {+ rejectMock.mockResolvedValue({ ok: true });+ render(<ApprovalCard approval={makeApproval()} />);+ fireEvent.click(screen.getByRole("button", { name: "Reject" }));+ await waitFor(() => {+ expect(rejectMock).toHaveBeenCalledWith("ap-1");+ expect(toastSuccessMock).toHaveBeenCalledWith("Rejected");+ });+ });++ it("reject surfaces server error with fallback string", async () => {+ rejectMock.mockResolvedValue({ ok: false });+ render(<ApprovalCard approval={makeApproval()} />);+ fireEvent.click(screen.getByRole("button", { name: "Reject" }));+ await waitFor(() => {+ expect(toastErrorMock).toHaveBeenCalledWith("Failed to reject");+ });+ });++ it("renders different action-type labels", () => {+ const { rerender } = render(+ <ApprovalCard approval={makeApproval({ action_type: "spend" })} />,+ );+ expect(screen.getByText("Spend")).toBeInTheDocument();+ rerender(+ <ApprovalCard approval={makeApproval({ action_type: "content_publishing" })} />,+ );+ expect(screen.getByText("Content")).toBeInTheDocument();+ rerender(+ <ApprovalCard approval={makeApproval({ action_type: "new_channel" })} />,+ );+ expect(screen.getByText("New channel")).toBeInTheDocument();+ rerender(<ApprovalCard approval={makeApproval({ action_type: "other" })} />);+ expect(screen.getByText("Other")).toBeInTheDocument();+ });++ it("sets the region aria-label to action_summary", () => {+ render(<ApprovalCard approval={makeApproval({ action_summary: "X-summary" })} />);+ expect(+ screen.getByRole("region", { name: "X-summary" }),+ ).toBeInTheDocument();+ });+});diff --git a/src/components/client-mount-gate.test.tsx b/src/components/client-mount-gate.test.tsxnew file mode 100644index 00000000..768b9c22--- /dev/null+++ b/src/components/client-mount-gate.test.tsx@@ -0,0 +1,66 @@+// @vitest-environment jsdom+import { afterEach, describe, it, expect } from "vitest";+import { act, cleanup, render, screen } from "@testing-library/react";+import { renderToString } from "react-dom/server";++import { ClientMountGate } from "./client-mount-gate";++afterEach(() => cleanup());++describe("ClientMountGate", () => {+ it("renders the fallback during SSR (no useEffect has fired yet)", () => {+ const html = renderToString(+ <ClientMountGate fallback={<span>loading skeleton</span>}>+ <span>real content</span>+ </ClientMountGate>,+ );+ expect(html).toContain("loading skeleton");+ expect(html).not.toContain("real content");+ });++ it("renders an empty shell during SSR when no fallback is supplied", () => {+ const html = renderToString(+ <ClientMountGate>+ <span>real content</span>+ </ClientMountGate>,+ );+ expect(html).not.toContain("real content");+ expect(html.replace(/<!--.*?-->/g, "")).toBe("");+ });++ it("swaps the fallback for the children after the client mounts", () => {+ render(+ <ClientMountGate fallback={<span data-testid="fallback">loading…</span>}>+ <span data-testid="content">real content</span>+ </ClientMountGate>,+ );+ expect(screen.getByTestId("content")).toBeInTheDocument();+ expect(screen.queryByTestId("fallback")).not.toBeInTheDocument();+ });++ it("renders children even with no fallback once mounted", () => {+ render(+ <ClientMountGate>+ <span data-testid="content">visible</span>+ </ClientMountGate>,+ );+ expect(screen.getByTestId("content")).toBeInTheDocument();+ });++ it("remains rendering children across re-renders", () => {+ const { rerender } = render(+ <ClientMountGate>+ <span data-testid="content">first</span>+ </ClientMountGate>,+ );+ expect(screen.getByTestId("content").textContent).toBe("first");+ act(() => {+ rerender(+ <ClientMountGate>+ <span data-testid="content">second</span>+ </ClientMountGate>,+ );+ });+ expect(screen.getByTestId("content").textContent).toBe("second");+ });+});diff --git a/src/components/create-agent-button.test.tsx b/src/components/create-agent-button.test.tsxnew file mode 100644index 00000000..6fb067c4--- /dev/null+++ b/src/components/create-agent-button.test.tsx@@ -0,0 +1,77 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, cleanup } from "@testing-library/react";++const dialogCalls: Array<{ open: boolean; projectSlug: string }> = [];++vi.mock("./create-agent-dialog", () => ({+ CreateAgentDialog: ({+ open,+ onOpenChange,+ projectSlug,+ }: {+ open: boolean;+ onOpenChange: (o: boolean) => void;+ projectSlug: string;+ }) => {+ dialogCalls.push({ open, projectSlug });+ return open ? (+ <div data-testid="dialog-stub">+ dialog-open-for-{projectSlug}+ <button onClick={() => onOpenChange(false)}>close</button>+ </div>+ ) : null;+ },+}));++import { CreateAgentButton } from "./create-agent-button";++beforeEach(() => {+ dialogCalls.length = 0;+});++afterEach(() => {+ cleanup();+});++describe("CreateAgentButton", () => {+ it("renders a plus button with an accessible name", () => {+ render(<CreateAgentButton projectSlug="proj" />);+ expect(+ screen.getByRole("button", { name: /create or clone agent/i }),+ ).toBeInTheDocument();+ });++ it("starts with the dialog closed", () => {+ render(<CreateAgentButton projectSlug="proj" />);+ expect(screen.queryByTestId("dialog-stub")).not.toBeInTheDocument();+ expect(dialogCalls.at(-1)?.open).toBe(false);+ });++ it("opens the dialog when the button is clicked", () => {+ render(<CreateAgentButton projectSlug="proj" />);+ fireEvent.click(+ screen.getByRole("button", { name: /create or clone agent/i }),+ );+ expect(screen.getByTestId("dialog-stub")).toBeInTheDocument();+ expect(screen.getByText("dialog-open-for-proj")).toBeInTheDocument();+ });++ it("forwards the projectSlug prop to the dialog", () => {+ render(<CreateAgentButton projectSlug="alpha-beta" />);+ fireEvent.click(+ screen.getByRole("button", { name: /create or clone agent/i }),+ );+ expect(dialogCalls.at(-1)?.projectSlug).toBe("alpha-beta");+ });++ it("closes the dialog when the child fires onOpenChange(false)", () => {+ render(<CreateAgentButton projectSlug="proj" />);+ fireEvent.click(+ screen.getByRole("button", { name: /create or clone agent/i }),+ );+ expect(screen.getByTestId("dialog-stub")).toBeInTheDocument();+ fireEvent.click(screen.getByText("close"));+ expect(screen.queryByTestId("dialog-stub")).not.toBeInTheDocument();+ });+});diff --git a/src/components/create-agent-dialog.test.tsx b/src/components/create-agent-dialog.test.tsxnew file mode 100644index 00000000..c94717f8--- /dev/null+++ b/src/components/create-agent-dialog.test.tsx@@ -0,0 +1,291 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const router = {+ push: vi.fn(),+ refresh: vi.fn(),+};++const listOpenClawAgentsAction = vi.fn();+const listProjectAgentsAction = vi.fn();+const createAgentAction = vi.fn();+const cloneAgentAction = vi.fn();++const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("next/navigation", () => ({+ useRouter: () => router,+}));++vi.mock("@/server/actions/agents", () => ({+ listOpenClawAgentsAction: (...args: unknown[]) =>+ listOpenClawAgentsAction(...args),+ listProjectAgentsAction: (...args: unknown[]) =>+ listProjectAgentsAction(...args),+ createAgentAction: (...args: unknown[]) => createAgentAction(...args),+ cloneAgentAction: (...args: unknown[]) => cloneAgentAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++vi.mock("./disable-source-crons-dialog", () => ({+ DisableSourceCronsDialog: ({+ sourceLabel,+ sourceCrons,+ onDone,+ }: {+ sourceLabel: string;+ sourceCrons: Array<{ id: string }>;+ onDone: () => void;+ }) => (+ <div data-testid="disable-source-crons-dialog">+ from {sourceLabel} with {sourceCrons.length} crons+ <button onClick={onDone}>finish</button>+ </div>+ ),+}));++import { CreateAgentDialog } from "./create-agent-dialog";++const choices = [+ {+ agent_id: "other-cmo",+ display_name: "Other CMO",+ in_current_project: false,+ },+ {+ agent_id: "proj-existing",+ display_name: "Existing",+ in_current_project: true,+ },+];++const projectAgents = [+ { agent_id: "proj-existing", slug: "existing", display_name: "Existing" },+];++beforeEach(() => {+ router.push.mockReset();+ router.refresh.mockReset();+ listOpenClawAgentsAction.mockReset();+ listProjectAgentsAction.mockReset();+ createAgentAction.mockReset();+ cloneAgentAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+ listOpenClawAgentsAction.mockResolvedValue({ ok: true, data: choices });+ listProjectAgentsAction.mockResolvedValue({ ok: true, data: projectAgents });+});++afterEach(() => {+ cleanup();+});++describe("CreateAgentDialog — create mode", () => {+ it("renders nothing visible when closed", () => {+ const onOpenChange = vi.fn();+ render(+ <CreateAgentDialog open={false} onOpenChange={onOpenChange} projectSlug="proj" />,+ );+ expect(screen.queryByText("New agent")).not.toBeInTheDocument();+ });++ it("renders create-mode UI with the project prefix when open", () => {+ render(+ <CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />,+ );+ expect(screen.getByText("New agent")).toBeInTheDocument();+ expect(screen.getByText("proj-")).toBeInTheDocument();+ expect(screen.getByLabelText(/Agent name/i)).toBeInTheDocument();+ });++ it("disables Create when the name is empty", () => {+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ expect(+ screen.getByRole("button", { name: /create agent/i }),+ ).toBeDisabled();+ });++ it("flags an in-project name collision and disables Create", async () => {+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ await waitFor(() => expect(listProjectAgentsAction).toHaveBeenCalled());+ const input = screen.getByLabelText(/Agent name/i);+ fireEvent.change(input, { target: { value: "existing" } });+ await waitFor(() =>+ expect(+ screen.getByText(/already exists in this project/i),+ ).toBeInTheDocument(),+ );+ expect(+ screen.getByRole("button", { name: /create agent/i }),+ ).toBeDisabled();+ });++ it("flags an invalid (reserved) name", async () => {+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ const input = screen.getByLabelText(/Agent name/i);+ fireEvent.change(input, { target: { value: "settings" } });+ await waitFor(() =>+ expect(screen.getByText(/invalid name/i)).toBeInTheDocument(),+ );+ expect(+ screen.getByRole("button", { name: /create agent/i }),+ ).toBeDisabled();+ });++ it("calls createAgentAction on submit and routes to the new agent", async () => {+ createAgentAction.mockResolvedValue({+ ok: true,+ data: { slug: "new-agent" },+ });+ const onOpenChange = vi.fn();+ render(+ <CreateAgentDialog open onOpenChange={onOpenChange} projectSlug="proj" />,+ );+ await waitFor(() => expect(listProjectAgentsAction).toHaveBeenCalled());+ fireEvent.change(screen.getByLabelText(/Agent name/i), {+ target: { value: "new-agent" },+ });+ fireEvent.click(screen.getByRole("button", { name: /create agent/i }));+ await waitFor(() =>+ expect(createAgentAction).toHaveBeenCalledWith({+ display_name: "new-agent",+ }),+ );+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ await waitFor(() =>+ expect(router.push).toHaveBeenCalledWith("/proj/agents/new-agent/chat"),+ );+ });++ it("toasts the server error when create fails", async () => {+ createAgentAction.mockResolvedValue({ ok: false, error: "denied" });+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ await waitFor(() => expect(listProjectAgentsAction).toHaveBeenCalled());+ fireEvent.change(screen.getByLabelText(/Agent name/i), {+ target: { value: "new-agent" },+ });+ fireEvent.click(screen.getByRole("button", { name: /create agent/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("denied"));+ });++ it("closes when Cancel is clicked", () => {+ const onOpenChange = vi.fn();+ render(+ <CreateAgentDialog open onOpenChange={onOpenChange} projectSlug="proj" />,+ );+ fireEvent.click(screen.getByRole("button", { name: /cancel/i }));+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+});++describe("CreateAgentDialog — clone mode", () => {+ function openInCloneMode() {+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ fireEvent.click(screen.getByRole("button", { name: /clone existing/i }));+ }++ it("shows the source picker once choices have loaded", async () => {+ openInCloneMode();+ await waitFor(() => expect(listOpenClawAgentsAction).toHaveBeenCalled());+ expect(await screen.findByLabelText(/source agent/i)).toBeInTheDocument();+ });++ it("renders a loading indicator while fetching the catalog", async () => {+ listOpenClawAgentsAction.mockImplementation(() => new Promise(() => {}));+ listProjectAgentsAction.mockImplementation(() => new Promise(() => {}));+ openInCloneMode();+ expect(await screen.findByText(/loading agents/i)).toBeInTheDocument();+ });++ it("renders the error message when the catalog fails to load", async () => {+ listOpenClawAgentsAction.mockResolvedValue({ ok: false, error: "boom" });+ openInCloneMode();+ expect(await screen.findByText("boom")).toBeInTheDocument();+ });++ it("disables Clone when source not picked or name is empty", async () => {+ openInCloneMode();+ await waitFor(() => expect(listOpenClawAgentsAction).toHaveBeenCalled());+ expect(+ screen.getByRole("button", { name: /clone agent/i }),+ ).toBeDisabled();+ });++ it("invokes cloneAgentAction with the chosen source and name", async () => {+ cloneAgentAction.mockResolvedValue({+ ok: true,+ data: { new_slug: "clone-x", new_agent_id: "proj-clone-x", source_crons: [] },+ });+ const onOpenChange = vi.fn();+ render(<CreateAgentDialog open onOpenChange={onOpenChange} projectSlug="proj" />);+ fireEvent.click(screen.getByRole("button", { name: /clone existing/i }));+ await waitFor(() => expect(listOpenClawAgentsAction).toHaveBeenCalled());+ fireEvent.change(await screen.findByLabelText(/source agent/i), {+ target: { value: "other-cmo" },+ });+ fireEvent.change(screen.getByLabelText(/new agent name/i), {+ target: { value: "clone-x" },+ });+ fireEvent.click(screen.getByRole("button", { name: /clone agent/i }));+ await waitFor(() =>+ expect(cloneAgentAction).toHaveBeenCalledWith({+ source_agent_id: "other-cmo",+ new_display_name: "clone-x",+ }),+ );+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ await waitFor(() =>+ expect(router.push).toHaveBeenCalledWith("/proj/agents/clone-x/chat"),+ );+ });++ it("opens the disable-crons follow-up dialog when the source had crons", async () => {+ cloneAgentAction.mockResolvedValue({+ ok: true,+ data: {+ new_slug: "clone-x",+ new_agent_id: "proj-clone-x",+ source_crons: [{ id: "c1" }, { id: "c2" }],+ },+ });+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ fireEvent.click(screen.getByRole("button", { name: /clone existing/i }));+ await waitFor(() => expect(listOpenClawAgentsAction).toHaveBeenCalled());+ fireEvent.change(await screen.findByLabelText(/source agent/i), {+ target: { value: "other-cmo" },+ });+ fireEvent.change(screen.getByLabelText(/new agent name/i), {+ target: { value: "clone-x" },+ });+ fireEvent.click(screen.getByRole("button", { name: /clone agent/i }));+ const followUp = await screen.findByTestId("disable-source-crons-dialog");+ expect(followUp).toBeInTheDocument();+ expect(followUp.textContent).toMatch(/Other CMO/i);+ expect(followUp.textContent).toMatch(/2 crons/i);+ });++ it("toasts a server error when clone fails", async () => {+ cloneAgentAction.mockResolvedValue({ ok: false, error: "no space" });+ render(<CreateAgentDialog open onOpenChange={vi.fn()} projectSlug="proj" />);+ fireEvent.click(screen.getByRole("button", { name: /clone existing/i }));+ await waitFor(() => expect(listOpenClawAgentsAction).toHaveBeenCalled());+ fireEvent.change(await screen.findByLabelText(/source agent/i), {+ target: { value: "other-cmo" },+ });+ fireEvent.change(screen.getByLabelText(/new agent name/i), {+ target: { value: "clone-x" },+ });+ fireEvent.click(screen.getByRole("button", { name: /clone agent/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("no space"));+ });+});diff --git a/src/components/cron-calendar.test.tsx b/src/components/cron-calendar.test.tsxnew file mode 100644index 00000000..bfb31b19--- /dev/null+++ b/src/components/cron-calendar.test.tsx@@ -0,0 +1,566 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup, within } from "@testing-library/react";++if (typeof Element !== "undefined") {+ // @ts-expect-error - jsdom shim+ Element.prototype.hasPointerCapture ??= () => false;+ // @ts-expect-error - jsdom shim+ Element.prototype.setPointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.releasePointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.scrollIntoView ??= () => {};+}++const pauseCronAction = vi.fn();+const resumeCronAction = vi.fn();+const deleteCronAction = vi.fn();+const updateCronPromptAction = vi.fn();+const getCronRunsAction = vi.fn();++const toast = { success: vi.fn(), error: vi.fn() };++vi.mock("@/server/actions/crons", () => ({+ pauseCronAction: (...a: unknown[]) => pauseCronAction(...a),+ resumeCronAction: (...a: unknown[]) => resumeCronAction(...a),+ deleteCronAction: (...a: unknown[]) => deleteCronAction(...a),+ updateCronPromptAction: (...a: unknown[]) => updateCronPromptAction(...a),+}));++vi.mock("@/server/actions/cron-runs", () => ({+ getCronRunsAction: (...a: unknown[]) => getCronRunsAction(...a),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...a: unknown[]) => toast.success(...a),+ error: (...a: unknown[]) => toast.error(...a),+ },+}));++import { CronCalendar, type CalendarCron, type CalendarOccurrence } from "./cron-calendar";++beforeEach(() => {+ pauseCronAction.mockReset();+ resumeCronAction.mockReset();+ deleteCronAction.mockReset();+ updateCronPromptAction.mockReset();+ getCronRunsAction.mockReset();+ getCronRunsAction.mockResolvedValue({ ok: true, runs: [] });+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => cleanup());++// Build a fixed test world. startOfFirstDay is 14 days ago at local midnight,+// so we can have past + future occurrences relative to a stable "now".+function todayStart(): number {+ const d = new Date();+ d.setHours(0, 0, 0, 0);+ return d.getTime();+}++const DAY = 24 * 60 * 60 * 1000;+const HOUR = 60 * 60 * 1000;++function buildWorld() {+ const start = todayStart() - 3 * DAY; // window covers 3 days before today through day 3 (today is day 3)+ const todayAt9 = todayStart() + 9 * HOUR;+ const todayAt15 = todayStart() + 15 * HOUR;+ const yesterdayAt9 = todayStart() - 1 * DAY + 9 * HOUR;+ const tomorrowAt9 = todayStart() + 1 * DAY + 9 * HOUR;++ const cronsById: Record<string, CalendarCron> = {+ "cron-a": {+ id: "cron-a",+ short_name: "daily-opt",+ full_name: "acme/google-ads/daily-opt",+ agent_id: "acme-google-ads",+ agent_slug: "google-ads",+ schedule_text: "0 9 * * *",+ disabled: false,+ status_text: "ok",+ message: "Run the daily optimization sweep.",+ description: "Tunes bids each morning.",+ schedule_raw: { kind: "cron", expr: "0 9 * * *", tz: "America/Los_Angeles" },+ },+ "cron-b": {+ id: "cron-b",+ short_name: "weekly-review",+ full_name: "acme/seo/weekly-review",+ agent_id: "acme-seo",+ agent_slug: "seo",+ schedule_text: "0 9 * * 1",+ disabled: true,+ status_text: "paused",+ message: "Weekly SEO review.",+ schedule_raw: null,+ },+ "cron-c": {+ id: "cron-c",+ short_name: "hourly-ping",+ full_name: "acme/cmo/hourly-ping",+ agent_id: "acme-cmo",+ agent_slug: "cmo",+ schedule_text: "every 1h",+ disabled: false,+ status_text: "ok",+ // No message — the Prompt section should NOT render+ schedule_raw: { kind: "every", everyMs: 3_600_000 },+ },+ };++ const occurrences: CalendarOccurrence[] = [+ {+ at: yesterdayAt9,+ cron_id: "cron-a",+ cron_name: cronsById["cron-a"]!.full_name,+ short_name: "daily-opt",+ agent_id: "acme-google-ads",+ agent_slug: "google-ads",+ schedule_text: "0 9 * * *",+ run_status: "ok",+ },+ {+ at: todayAt9,+ cron_id: "cron-a",+ cron_name: cronsById["cron-a"]!.full_name,+ short_name: "daily-opt",+ agent_id: "acme-google-ads",+ agent_slug: "google-ads",+ schedule_text: "0 9 * * *",+ run_status: "error",+ },+ {+ at: todayAt15,+ cron_id: "cron-b",+ cron_name: cronsById["cron-b"]!.full_name,+ short_name: "weekly-review",+ agent_id: "acme-seo",+ agent_slug: "seo",+ schedule_text: "0 9 * * 1",+ cron_disabled: true,+ },+ {+ at: tomorrowAt9,+ cron_id: "cron-c",+ cron_name: cronsById["cron-c"]!.full_name,+ short_name: "hourly-ping",+ agent_id: "acme-cmo",+ agent_slug: "cmo",+ schedule_text: "every 1h",+ },+ ];++ return {+ start,+ numDays: 14,+ occurrences,+ cronsById,+ agentSlugs: ["cmo", "google-ads", "seo"],+ todayAt9,+ todayAt15,+ yesterdayAt9,+ tomorrowAt9,+ };+}++function renderCalendar() {+ const w = buildWorld();+ render(+ <CronCalendar+ startOfFirstDay={w.start}+ numDays={w.numDays}+ occurrences={w.occurrences}+ cronsById={w.cronsById}+ agentSlugs={w.agentSlugs}+ />,+ );+ return w;+}++describe("CronCalendar — filter chips", () => {+ it("defaults to 'Enabled' filter and hides disabled crons", () => {+ renderCalendar();+ const enabledTab = screen.getByRole("tab", { name: "Enabled" });+ expect(enabledTab).toHaveAttribute("aria-selected", "true");+ // disabled cron-b's chip should not be on the board+ expect(screen.queryAllByText("weekly-review")).toHaveLength(0);+ // enabled chips visible+ expect(screen.getAllByText("daily-opt").length).toBeGreaterThan(0);+ expect(screen.getByText("hourly-ping")).toBeInTheDocument();+ });++ it("switching to 'Disabled' shows only disabled crons", () => {+ renderCalendar();+ fireEvent.click(screen.getByRole("tab", { name: "Disabled" }));+ expect(screen.getByText("weekly-review")).toBeInTheDocument();+ expect(screen.queryAllByText("daily-opt")).toHaveLength(0);+ expect(screen.queryByText("hourly-ping")).not.toBeInTheDocument();+ });++ it("switching to 'All' shows enabled and disabled chips together", () => {+ renderCalendar();+ fireEvent.click(screen.getByRole("tab", { name: "All" }));+ expect(screen.getByText("weekly-review")).toBeInTheDocument();+ expect(screen.getAllByText("daily-opt").length).toBeGreaterThan(0);+ expect(screen.getByText("hourly-ping")).toBeInTheDocument();+ });++ it("shows an empty-state when the active filter has no occurrences", () => {+ render(+ <CronCalendar+ startOfFirstDay={todayStart()}+ numDays={14}+ occurrences={[]}+ cronsById={{}}+ agentSlugs={[]}+ />,+ );+ expect(screen.getByText(/Nothing to show with this filter/i)).toBeInTheDocument();+ });+});++describe("CronCalendar — legend", () => {+ it("shows only the slugs that are currently visible (filtered by enabled crons)", () => {+ renderCalendar();+ // Enabled filter: cron-a (google-ads) + cron-c (cmo). Not seo.+ // Legend entries are font-mono spans with the slug text.+ const legend = screen.getAllByText(/^(google-ads|cmo|seo)$/i);+ const slugs = legend.map((el) => el.textContent);+ expect(slugs).toContain("google-ads");+ expect(slugs).toContain("cmo");+ expect(slugs).not.toContain("seo");+ });++ it("legend updates when filter switches to 'Disabled'", () => {+ renderCalendar();+ fireEvent.click(screen.getByRole("tab", { name: "Disabled" }));+ const legend = screen.getAllByText(/^(google-ads|cmo|seo)$/i);+ const slugs = legend.map((el) => el.textContent);+ expect(slugs).toContain("seo");+ expect(slugs).not.toContain("cmo");+ expect(slugs).not.toContain("google-ads");+ });+});++describe("CronCalendar — week navigator", () => {+ it("Prev is disabled at offset 0 (window already at start)", () => {+ renderCalendar();+ expect(screen.getByLabelText("Previous week")).toBeDisabled();+ });++ it("Next becomes disabled once we scroll one week (numDays=14, visible=7)", () => {+ renderCalendar();+ const next = screen.getByLabelText("Next week");+ expect(next).not.toBeDisabled();+ fireEvent.click(next);+ expect(next).toBeDisabled();+ });++ it("'Today' button resets back to offset 0", () => {+ renderCalendar();+ fireEvent.click(screen.getByLabelText("Next week"));+ expect(screen.getByLabelText("Previous week")).not.toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: /^today$/i }));+ expect(screen.getByLabelText("Previous week")).toBeDisabled();+ });+});++describe("CronCalendar — occurrence detail dialog", () => {+ it("clicking an occurrence chip opens the detail dialog with cron metadata", async () => {+ renderCalendar();+ const chips = screen.getAllByText("daily-opt");+ fireEvent.click(chips[0]!.closest("button")!);+ await waitFor(() => {+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });+ // Heading uses the short_name+ expect(screen.getAllByText("daily-opt").length).toBeGreaterThan(0);+ expect(screen.getByText("Tunes bids each morning.")).toBeInTheDocument();+ // Details rows+ expect(screen.getByText("acme/google-ads/daily-opt")).toBeInTheDocument();+ expect(screen.getByText("acme-google-ads")).toBeInTheDocument();+ expect(screen.getByText("0 9 * * *")).toBeInTheDocument();+ });++ it("loads runs via getCronRunsAction when a cron is selected", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt")[0]!.closest("button")!);+ await waitFor(() => {+ expect(getCronRunsAction).toHaveBeenCalledWith(+ "cron-a",+ { kind: "cron", expr: "0 9 * * *", tz: "America/Los_Angeles" },+ 200,+ );+ });+ });++ it("shows past-tick fallback when no matched run and time is in the past", async () => {+ renderCalendar();+ // yesterday's tick had run_status="ok" but our mocked runs are empty, so+ // matchedRun is null AND occ.at < Date.now() → "No run log for this occurrence."+ const chips = screen.getAllByText("daily-opt").map((n) => n.closest("button")!);+ fireEvent.click(chips[0]!); // first one is the older occurrence (yesterday)+ await waitFor(() => expect(getCronRunsAction).toHaveBeenCalled());+ // Result section should reflect "no run log" — first matching node wins.+ expect(await screen.findByText(/No run log for this occurrence|Not fired yet/i)).toBeInTheDocument();+ });++ it("shows 'Not fired yet' for future occurrences with no matched run", async () => {+ renderCalendar();+ // Click the tomorrow chip (hourly-ping)+ fireEvent.click(screen.getByText("hourly-ping").closest("button")!);+ await waitFor(() => expect(getCronRunsAction).toHaveBeenCalled());+ expect(await screen.findByText(/Not fired yet/i)).toBeInTheDocument();+ });++ it("shows 'scheduled' badge for future occurrences", async () => {+ renderCalendar();+ fireEvent.click(screen.getByText("hourly-ping").closest("button")!);+ expect(await screen.findByText("scheduled")).toBeInTheDocument();+ });++ it("shows 'past' badge for past occurrences with no matching run", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ expect(await screen.findByText("past")).toBeInTheDocument();+ });++ it("shows raw status badge for a past occurrence with a matching run (exact tick)", async () => {+ const w = buildWorld();+ getCronRunsAction.mockResolvedValue({+ ok: true,+ runs: [+ {+ status: "ok",+ run_at_ms: w.yesterdayAt9,+ finished_at_ms: w.yesterdayAt9 + 30_000,+ duration_ms: 30_000,+ owning_occurrence_at_ms: w.yesterdayAt9,+ model: "claude-opus",+ provider: "anthropic",+ usage: { total_tokens: 12345 },+ summary: "Bid changes applied.",+ },+ ],+ });+ render(+ <CronCalendar+ startOfFirstDay={w.start}+ numDays={w.numDays}+ occurrences={w.occurrences}+ cronsById={w.cronsById}+ agentSlugs={w.agentSlugs}+ />,+ );+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ await waitFor(() => expect(getCronRunsAction).toHaveBeenCalled());+ // Badge shows raw status "ok"+ const badges = await screen.findAllByText(/^ok$/);+ expect(badges.length).toBeGreaterThan(0);+ // Result section shows the summary+ expect(await screen.findByText("Bid changes applied.")).toBeInTheDocument();+ // Tokens row+ expect(await screen.findByText("12,345")).toBeInTheDocument();+ // Model row+ expect(await screen.findByText(/claude-opus/)).toBeInTheDocument();+ });++ it("renders an Error section when the matched run has an error", async () => {+ const w = buildWorld();+ getCronRunsAction.mockResolvedValue({+ ok: true,+ runs: [+ {+ status: "error",+ run_at_ms: w.yesterdayAt9,+ finished_at_ms: w.yesterdayAt9 + 1_000,+ duration_ms: 1_000,+ owning_occurrence_at_ms: w.yesterdayAt9,+ error: "MCP token missing",+ },+ ],+ });+ render(+ <CronCalendar+ startOfFirstDay={w.start}+ numDays={w.numDays}+ occurrences={w.occurrences}+ cronsById={w.cronsById}+ agentSlugs={w.agentSlugs}+ />,+ );+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ expect(await screen.findByText("MCP token missing")).toBeInTheDocument();+ });++ it("renders the runs-error message when getCronRunsAction returns ok=false", async () => {+ getCronRunsAction.mockResolvedValue({ ok: false, error: "DB locked" });+ renderCalendar();+ fireEvent.click(screen.getByText("hourly-ping").closest("button")!);+ expect(await screen.findByText("DB locked")).toBeInTheDocument();+ });++ it("does NOT render a Prompt section when cron.message is undefined", async () => {+ renderCalendar();+ fireEvent.click(screen.getByText("hourly-ping").closest("button")!);+ await screen.findByRole("dialog");+ // No "Prompt" section header+ expect(screen.queryByRole("button", { name: /^prompt$/i, expanded: true })).not.toBeInTheDocument();+ });++ it("renders the prompt text in read-only mode by default", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ expect(await screen.findByText(/Run the daily optimization sweep\./)).toBeInTheDocument();+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ });++ it("clicking Edit reveals the textarea; Cancel restores read-only without calling the action", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ expect(textarea.value).toBe("Run the daily optimization sweep.");+ fireEvent.change(textarea, { target: { value: "totally new prompt" } });+ fireEvent.click(screen.getByRole("button", { name: /cancel/i }));+ expect(updateCronPromptAction).not.toHaveBeenCalled();+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ });++ it("Save with empty prompt toasts an error and does not call the action", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: " " } });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Prompt cannot be empty."));+ expect(updateCronPromptAction).not.toHaveBeenCalled();+ });++ it("Save with unchanged prompt closes the editor without calling the action", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));+ // value unchanged+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));+ expect(updateCronPromptAction).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.queryByRole("textbox")).not.toBeInTheDocument());+ });++ it("Save with new prompt calls updateCronPromptAction and toasts success", async () => {+ updateCronPromptAction.mockResolvedValue({ ok: true });+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "new prompt text" } });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));+ await waitFor(() =>+ expect(updateCronPromptAction).toHaveBeenCalledWith("cron-a", "new prompt text"),+ );+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Prompt updated"));+ });++ it("Save with server error toasts the error and keeps the editor open", async () => {+ updateCronPromptAction.mockResolvedValue({ ok: false, error: "openclaw rejected" });+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /^edit$/i }));+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "another" } });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("openclaw rejected"));+ // editor still mounted+ expect(screen.getByRole("textbox")).toBeInTheDocument();+ });+});++describe("CronCalendar — collapsible sections", () => {+ it("a section's chevron button toggles open/closed", async () => {+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ const detailsHeader = await screen.findByRole("button", { name: /details/i, expanded: true });+ fireEvent.click(detailsHeader);+ expect(detailsHeader).toHaveAttribute("aria-expanded", "false");+ fireEvent.click(detailsHeader);+ expect(detailsHeader).toHaveAttribute("aria-expanded", "true");+ });+});++describe("CronCalendar — cron actions (footer)", () => {+ it("shows Disable on an enabled cron and pauses it", async () => {+ pauseCronAction.mockResolvedValue({ ok: true });+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /disable/i }));+ await waitFor(() => expect(pauseCronAction).toHaveBeenCalledWith("cron-a"));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Disabled: daily-opt"));+ });++ it("shows Enable on a disabled cron and resumes it", async () => {+ resumeCronAction.mockResolvedValue({ ok: true });+ renderCalendar();+ fireEvent.click(screen.getByRole("tab", { name: "Disabled" }));+ fireEvent.click(screen.getByText("weekly-review").closest("button")!);+ fireEvent.click(await screen.findByRole("button", { name: /enable/i }));+ await waitFor(() => expect(resumeCronAction).toHaveBeenCalledWith("cron-b"));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Enabled: weekly-review"));+ });++ it("Delete prompts for confirmation; cancel skips the action", async () => {+ const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /delete/i }));+ expect(deleteCronAction).not.toHaveBeenCalled();+ confirmSpy.mockRestore();+ });++ it("Delete invokes the action when confirmed", async () => {+ const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);+ deleteCronAction.mockResolvedValue({ ok: true });+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /delete/i }));+ await waitFor(() => expect(deleteCronAction).toHaveBeenCalledWith("cron-a"));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Deleted: daily-opt"));+ confirmSpy.mockRestore();+ });++ it("toasts the server error when the cron action fails", async () => {+ pauseCronAction.mockResolvedValue({ ok: false, error: "nope" });+ renderCalendar();+ fireEvent.click(screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!);+ fireEvent.click(await screen.findByRole("button", { name: /disable/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("nope"));+ });+});++describe("CronCalendar — chip rendering", () => {+ it("disabled occurrences render a strike-through time", () => {+ renderCalendar();+ fireEvent.click(screen.getByRole("tab", { name: "All" }));+ // Disabled chip wraps its time in a span with line-through class+ const allChips = screen.getAllByRole("button");+ const disabledChip = allChips.find((b) => b.textContent?.includes("weekly-review"));+ expect(disabledChip).toBeDefined();+ const timeSpan = within(disabledChip!).getAllByText(/\d/)[0];+ expect(timeSpan?.className).toMatch(/line-through/);+ });++ it("ok status occurrence has aria-label='success' glyph", () => {+ renderCalendar();+ const yesterdayChip = screen.getAllByText("daily-opt").map((n) => n.closest("button")!)[0]!;+ expect(within(yesterdayChip).getByLabelText("success")).toBeInTheDocument();+ });++ it("error status occurrence has aria-label='error' glyph", () => {+ renderCalendar();+ const chips = screen.getAllByText("daily-opt").map((n) => n.closest("button")!);+ // The second daily-opt is today's "error" run+ expect(within(chips[1]!).getByLabelText("error")).toBeInTheDocument();+ });+});diff --git a/src/components/cron-row-actions.test.tsx b/src/components/cron-row-actions.test.tsxnew file mode 100644index 00000000..e49764f4--- /dev/null+++ b/src/components/cron-row-actions.test.tsx@@ -0,0 +1,130 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++// Radix DropdownMenu / Dialog depend on a few DOM APIs jsdom doesn't ship.+// Polyfill them on Element so Radix can mount and respond to pointer events.+if (typeof Element !== "undefined") {+ // @ts-expect-error - jsdom shim+ Element.prototype.hasPointerCapture ??= () => false;+ // @ts-expect-error - jsdom shim+ Element.prototype.setPointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.releasePointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.scrollIntoView ??= () => {};+}++const pauseCronAction = vi.fn();+const resumeCronAction = vi.fn();+const deleteCronAction = vi.fn();++const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("@/server/actions/crons", () => ({+ pauseCronAction: (...args: unknown[]) => pauseCronAction(...args),+ resumeCronAction: (...args: unknown[]) => resumeCronAction(...args),+ deleteCronAction: (...args: unknown[]) => deleteCronAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++import { CronRowActions } from "./cron-row-actions";++function openMenu() {+ const trigger = screen.getByRole("button", { name: /cron actions/i });+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });+ fireEvent.click(trigger);+}++beforeEach(() => {+ pauseCronAction.mockReset();+ resumeCronAction.mockReset();+ deleteCronAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("CronRowActions", () => {+ it("shows a 'Pause' menu item when the cron is enabled", () => {+ render(<CronRowActions cronId="c1" cronName="daily-bid-opt" disabled={false} />);+ openMenu();+ expect(screen.getByText("Pause")).toBeInTheDocument();+ expect(screen.queryByText("Resume")).not.toBeInTheDocument();+ });++ it("shows a 'Resume' menu item when the cron is disabled", () => {+ render(<CronRowActions cronId="c1" cronName="daily-bid-opt" disabled={true} />);+ openMenu();+ expect(screen.getByText("Resume")).toBeInTheDocument();+ expect(screen.queryByText("Pause")).not.toBeInTheDocument();+ });++ it("calls pauseCronAction and toasts success when Pause is clicked", async () => {+ pauseCronAction.mockResolvedValue({ ok: true });+ render(<CronRowActions cronId="c-pause" cronName="hourly-sweep" disabled={false} />);+ openMenu();+ fireEvent.click(screen.getByText("Pause"));+ await waitFor(() => expect(pauseCronAction).toHaveBeenCalledWith("c-pause"));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Paused: hourly-sweep"));+ });++ it("calls resumeCronAction and toasts success when Resume is clicked", async () => {+ resumeCronAction.mockResolvedValue({ ok: true });+ render(<CronRowActions cronId="c-resume" cronName="weekly-roundup" disabled={true} />);+ openMenu();+ fireEvent.click(screen.getByText("Resume"));+ await waitFor(() => expect(resumeCronAction).toHaveBeenCalledWith("c-resume"));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Resumed: weekly-roundup"));+ });++ it("toasts the server error when pause fails", async () => {+ pauseCronAction.mockResolvedValue({ ok: false, error: "openclaw exploded" });+ render(<CronRowActions cronId="c1" cronName="x" disabled={false} />);+ openMenu();+ fireEvent.click(screen.getByText("Pause"));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("openclaw exploded"));+ expect(toast.success).not.toHaveBeenCalled();+ });++ it("falls back to a generic error when the action returns ok=false without a message", async () => {+ resumeCronAction.mockResolvedValue({ ok: false });+ render(<CronRowActions cronId="c1" cronName="x" disabled={true} />);+ openMenu();+ fireEvent.click(screen.getByText("Resume"));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Failed to Resumed"));+ });++ it("deletes when the user confirms the prompt", async () => {+ const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true);+ deleteCronAction.mockResolvedValue({ ok: true });+ render(<CronRowActions cronId="c-del" cronName="goner" disabled={false} />);+ openMenu();+ fireEvent.click(screen.getByText("Delete"));+ expect(confirmSpy).toHaveBeenCalledWith('Delete cron "goner"?');+ await waitFor(() => expect(deleteCronAction).toHaveBeenCalledWith("c-del"));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Deleted: goner"));+ confirmSpy.mockRestore();+ });++ it("does not call deleteCronAction when the user cancels the confirm prompt", () => {+ const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(false);+ render(<CronRowActions cronId="c-del" cronName="lucky" disabled={false} />);+ openMenu();+ fireEvent.click(screen.getByText("Delete"));+ expect(deleteCronAction).not.toHaveBeenCalled();+ confirmSpy.mockRestore();+ });+});diff --git a/src/components/danger-zone.test.tsx b/src/components/danger-zone.test.tsxnew file mode 100644index 00000000..a43a1d63--- /dev/null+++ b/src/components/danger-zone.test.tsx@@ -0,0 +1,181 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const router = {+ push: vi.fn(),+ refresh: vi.fn(),+};+const getProjectDeletionSummaryAction = vi.fn();+const deleteProjectAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+};++vi.mock("next/navigation", () => ({+ useRouter: () => router,+}));++vi.mock("@/server/actions/projects", () => ({+ getProjectDeletionSummaryAction: (...args: unknown[]) =>+ getProjectDeletionSummaryAction(...args),+ deleteProjectAction: (...args: unknown[]) => deleteProjectAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ warning: (...args: unknown[]) => toast.warning(...args),+ },+}));++import { DangerZone } from "./danger-zone";++const summary = {+ totals: { agents: 3, threads: 5, crons: 2, mcps: 1 },+ agents: [+ {+ agentId: "proj-cmo",+ display_name: "CMO",+ threadCount: 4,+ exists: true,+ },+ {+ agentId: "proj-old",+ display_name: "Old",+ threadCount: 0,+ exists: false,+ },+ ],+};++beforeEach(() => {+ router.push.mockReset();+ router.refresh.mockReset();+ getProjectDeletionSummaryAction.mockReset();+ deleteProjectAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+ toast.warning.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("DangerZone (project)", () => {+ it("renders the delete-project CTA card", () => {+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ expect(screen.getByText("Delete this project")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /delete project/i }),+ ).toBeInTheDocument();+ });++ it("opens the confirm dialog with loading state", async () => {+ getProjectDeletionSummaryAction.mockImplementation(+ () => new Promise(() => {}),+ );+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ expect(+ await screen.findByText(/counting what will be removed/i),+ ).toBeInTheDocument();+ });++ it("shows summary stats and existing agents in the dialog", async () => {+ getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ expect(await screen.findByText("3")).toBeInTheDocument();+ expect(screen.getByText("Agents")).toBeInTheDocument();+ expect(screen.getByText("Threads")).toBeInTheDocument();+ expect(screen.getByText("Crons")).toBeInTheDocument();+ expect(screen.getByText("MCPs")).toBeInTheDocument();+ expect(screen.getByText("CMO")).toBeInTheDocument();+ expect(screen.getByText("proj-cmo")).toBeInTheDocument();+ expect(screen.getByText(/4 threads/)).toBeInTheDocument();+ expect(screen.queryByText("Old")).not.toBeInTheDocument();+ });++ it("renders the error message when summary load fails", async () => {+ getProjectDeletionSummaryAction.mockResolvedValue({+ ok: false,+ error: "boom",+ });+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ expect(+ await screen.findByText(/could not load deletion summary: boom/i),+ ).toBeInTheDocument();+ });++ it("deletes the project and routes home on success", async () => {+ getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });+ deleteProjectAction.mockResolvedValue({+ ok: true,+ data: {+ agents: [{ agentId: "a" }, { agentId: "b" }],+ crons: 2,+ agentsFailed: [],+ cronsFailed: 0,+ },+ });+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ await screen.findByText("CMO");+ fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));+ await waitFor(() =>+ expect(deleteProjectAction).toHaveBeenCalledWith("alpha", "alpha"),+ );+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith(+ "Deleted Alpha. 2 agents, 2 crons removed.",+ ),+ );+ await waitFor(() => expect(router.push).toHaveBeenCalledWith("/"));+ });++ it("warns when partial failures happen on delete", async () => {+ getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });+ deleteProjectAction.mockResolvedValue({+ ok: true,+ data: {+ agents: [{ agentId: "a" }],+ crons: 1,+ agentsFailed: ["x"],+ cronsFailed: 2,+ },+ });+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ await screen.findByText("CMO");+ fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));+ await waitFor(() =>+ expect(toast.warning.mock.calls[0][0]).toMatch(/3 issues/),+ );+ });++ it("toasts the server error on delete failure", async () => {+ getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });+ deleteProjectAction.mockResolvedValue({ ok: false, error: "denied" });+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ await screen.findByText("CMO");+ fireEvent.click(screen.getByRole("button", { name: /delete forever/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("denied"));+ expect(router.push).not.toHaveBeenCalled();+ });++ it("closes the dialog on Cancel", async () => {+ getProjectDeletionSummaryAction.mockResolvedValue({ ok: true, data: summary });+ render(<DangerZone projectSlug="alpha" projectName="Alpha" />);+ fireEvent.click(screen.getByRole("button", { name: /delete project/i }));+ await screen.findByText("CMO");+ fireEvent.click(screen.getByRole("button", { name: /cancel/i }));+ await waitFor(() => expect(screen.queryByText("CMO")).not.toBeInTheDocument());+ });+});diff --git a/src/components/disable-source-crons-dialog.test.tsx b/src/components/disable-source-crons-dialog.test.tsxnew file mode 100644index 00000000..a354dcf0--- /dev/null+++ b/src/components/disable-source-crons-dialog.test.tsx@@ -0,0 +1,161 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++if (typeof Element !== "undefined") {+ // @ts-expect-error - jsdom shim+ Element.prototype.hasPointerCapture ??= () => false;+ // @ts-expect-error - jsdom shim+ Element.prototype.setPointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.releasePointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.scrollIntoView ??= () => {};+}++const disableCronsAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+ warning: vi.fn(),+};++vi.mock("@/server/actions/agents", () => ({+ disableCronsAction: (...args: unknown[]) => disableCronsAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ warning: (...args: unknown[]) => toast.warning(...args),+ },+}));++import { DisableSourceCronsDialog } from "./disable-source-crons-dialog";++beforeEach(() => {+ disableCronsAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+ toast.warning.mockReset();+});++afterEach(() => cleanup());++function renderDialog(overrides: Partial<Parameters<typeof DisableSourceCronsDialog>[0]> = {}) {+ const onOpenChange = vi.fn();+ const onDone = vi.fn();+ const sourceCrons = overrides.sourceCrons ?? [+ { id: "c1", name: "daily-sweep", disabled: false },+ { id: "c2", name: "weekly-report", disabled: false },+ { id: "c3", name: "already-off", disabled: true },+ ];+ render(+ <DisableSourceCronsDialog+ open+ onOpenChange={onOpenChange}+ sourceLabel="acme-ads"+ newAgentId="new-ads"+ sourceCrons={sourceCrons}+ onDone={onDone}+ {...overrides}+ />,+ );+ return { onOpenChange, onDone };+}++describe("DisableSourceCronsDialog", () => {+ it("renders the source label, count, and new agent id in the description", () => {+ renderDialog();+ // dialog title escapes apostrophe+ expect(screen.getByRole("heading", { name: /Disable acme-ads.*cron jobs\?/i })).toBeInTheDocument();+ expect(screen.getByText(/We just copied 3 cron jobs/)).toBeInTheDocument();+ expect(screen.getByText("acme-ads")).toBeInTheDocument();+ expect(screen.getByText("new-ads")).toBeInTheDocument();+ });++ it("uses singular 'cron job' when there is exactly one", () => {+ renderDialog({ sourceCrons: [{ id: "c1", name: "just-one", disabled: false }] });+ expect(screen.getByText(/We just copied 1 cron job(?!s)/)).toBeInTheDocument();+ });++ it("lists each source cron's name and marks the already-disabled ones", () => {+ renderDialog();+ expect(screen.getByText("daily-sweep")).toBeInTheDocument();+ expect(screen.getByText("weekly-report")).toBeInTheDocument();+ expect(screen.getByText("already-off")).toBeInTheDocument();+ expect(screen.getByText(/already off/i)).toBeInTheDocument();+ });++ it("hides the list when there are no source crons", () => {+ renderDialog({ sourceCrons: [] });+ // No <ul> rendered → the rows should not exist+ expect(screen.queryByRole("list")).not.toBeInTheDocument();+ });++ it('"Keep them running" closes the dialog and signals done without calling the action', () => {+ const { onOpenChange, onDone } = renderDialog();+ fireEvent.click(screen.getByRole("button", { name: /keep them running/i }));+ expect(disableCronsAction).not.toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onDone).toHaveBeenCalled();+ });++ it('"Disable on source" only disables the currently-enabled source crons', async () => {+ disableCronsAction.mockResolvedValue({ ok: true, data: { disabled: 2, failed: 0 } });+ const { onOpenChange, onDone } = renderDialog();+ fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));+ await waitFor(() => expect(disableCronsAction).toHaveBeenCalledWith(["c1", "c2"]));+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Disabled 2 crons on acme-ads"));+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onDone).toHaveBeenCalled();+ });++ it("uses singular wording when only one cron is disabled", async () => {+ disableCronsAction.mockResolvedValue({ ok: true, data: { disabled: 1, failed: 0 } });+ renderDialog({ sourceCrons: [{ id: "only", name: "only-one", disabled: false }] });+ fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith("Disabled 1 cron on acme-ads"),+ );+ });++ it("emits a warning toast when some disables fail", async () => {+ disableCronsAction.mockResolvedValue({ ok: true, data: { disabled: 1, failed: 1 } });+ renderDialog({+ sourceCrons: [+ { id: "c1", name: "ok-one", disabled: false },+ { id: "c2", name: "bad-one", disabled: false },+ ],+ });+ fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));+ await waitFor(() =>+ expect(toast.warning).toHaveBeenCalledWith("Disabled 1 crons (1 failed)"),+ );+ expect(toast.success).not.toHaveBeenCalled();+ });++ it("toasts the server error when the action returns ok=false", async () => {+ disableCronsAction.mockResolvedValue({ ok: false, error: "Permission denied" });+ const { onOpenChange, onDone } = renderDialog();+ fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("Permission denied"));+ // Returns early — dialog stays open+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ expect(onDone).not.toHaveBeenCalled();+ });++ it("short-circuits and closes when every source cron is already disabled", () => {+ const { onOpenChange, onDone } = renderDialog({+ sourceCrons: [+ { id: "c1", name: "off1", disabled: true },+ { id: "c2", name: "off2", disabled: true },+ ],+ });+ fireEvent.click(screen.getByRole("button", { name: /disable on source/i }));+ expect(disableCronsAction).not.toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onDone).toHaveBeenCalled();+ });+});diff --git a/src/components/global-liveness-poller.test.tsx b/src/components/global-liveness-poller.test.tsxnew file mode 100644index 00000000..eb9e1feb--- /dev/null+++ b/src/components/global-liveness-poller.test.tsx@@ -0,0 +1,92 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";+import { act, cleanup, render } from "@testing-library/react";++const refresh = vi.fn();++vi.mock("next/navigation", () => ({+ useRouter: () => ({ refresh }),+}));++import { GlobalLivenessPoller } from "./global-liveness-poller";++beforeEach(() => {+ refresh.mockReset();+ vi.useFakeTimers();+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("GlobalLivenessPoller", () => {+ it("renders nothing in the DOM", () => {+ const { container } = render(<GlobalLivenessPoller hasInFlight={true} />);+ expect(container.firstChild).toBeNull();+ });++ it("does not start a timer when hasInFlight is false", () => {+ render(<GlobalLivenessPoller hasInFlight={false} />);+ act(() => {+ vi.advanceTimersByTime(20_000);+ });+ expect(refresh).not.toHaveBeenCalled();+ });++ it("polls router.refresh() every 5 seconds while hasInFlight is true", () => {+ render(<GlobalLivenessPoller hasInFlight={true} />);+ expect(refresh).not.toHaveBeenCalled();+ act(() => {+ vi.advanceTimersByTime(5_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ act(() => {+ vi.advanceTimersByTime(5_000);+ });+ expect(refresh).toHaveBeenCalledTimes(2);+ act(() => {+ vi.advanceTimersByTime(5_000);+ });+ expect(refresh).toHaveBeenCalledTimes(3);+ });++ it("tears the interval down when hasInFlight flips to false", () => {+ const { rerender } = render(<GlobalLivenessPoller hasInFlight={true} />);+ act(() => {+ vi.advanceTimersByTime(5_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ rerender(<GlobalLivenessPoller hasInFlight={false} />);+ act(() => {+ vi.advanceTimersByTime(30_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ });++ it("clears the interval on unmount so no stray refreshes fire", () => {+ const { unmount } = render(<GlobalLivenessPoller hasInFlight={true} />);+ act(() => {+ vi.advanceTimersByTime(5_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ unmount();+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ });++ it("starts a fresh interval if hasInFlight flips back to true after being false", () => {+ const { rerender } = render(<GlobalLivenessPoller hasInFlight={false} />);+ act(() => {+ vi.advanceTimersByTime(10_000);+ });+ expect(refresh).not.toHaveBeenCalled();+ rerender(<GlobalLivenessPoller hasInFlight={true} />);+ act(() => {+ vi.advanceTimersByTime(5_000);+ });+ expect(refresh).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/components/google-ads-mcp-banner.test.tsx b/src/components/google-ads-mcp-banner.test.tsxnew file mode 100644index 00000000..fa9670ca--- /dev/null+++ b/src/components/google-ads-mcp-banner.test.tsx@@ -0,0 +1,213 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const { startMcpConnect, toastFns } = vi.hoisted(() => ({+ startMcpConnect: vi.fn(),+ toastFns: {+ success: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock("@/server/actions/mcp", () => ({+ startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),+}));++vi.mock("sonner", () => ({+ toast: toastFns,+}));++import { GoogleAdsMcpBanner } from "./google-ads-mcp-banner";+import type { McpRuntimeStatus } from "@/server/mcp-state";++const SLUG = "acme";++function setLocation(href: string) {+ const url = new URL(href);+ const fake = {+ pathname: url.pathname,+ search: url.search,+ href: url.href,+ } as Location;+ Object.defineProperty(window, "location", {+ writable: true,+ configurable: true,+ value: fake,+ });+ return fake;+}++beforeEach(() => {+ startMcpConnect.mockReset();+ toastFns.success.mockReset();+ toastFns.error.mockReset();+ setLocation("http://localhost:3000/acme/agents/google_ads/chat?task=t1");+});++afterEach(() => {+ cleanup();+});++describe("GoogleAdsMcpBanner", () => {+ it("renders nothing when status is connected", () => {+ const { container } = render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{+ state: "connected",+ url: "https://x",+ tools_count: 5,+ last_checked_at: new Date().toISOString(),+ }}+ />,+ );+ expect(container.firstChild).toBeNull();+ });++ it("renders the 'connect' copy for not_configured status", () => {+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "not_configured" }}+ />,+ );+ expect(+ screen.getByText(/Connect NotFair Google Ads to go live/i),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /^Connect$/ })).toBeInTheDocument();+ });++ it("renders the 'reconnect' copy for stale_token status", () => {+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{+ state: "stale_token",+ url: "https://x",+ http_status: 401,+ last_checked_at: new Date().toISOString(),+ }}+ />,+ );+ expect(+ screen.getByText(/Google Ads connection expired/i),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Reconnect/i })).toBeInTheDocument();+ });++ it("renders the 'unreachable' copy with reconnect action", () => {+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{+ state: "unreachable",+ url: "https://x",+ error: "ECONNRESET",+ last_checked_at: new Date().toISOString(),+ }}+ />,+ );+ expect(+ screen.getByText(/Google Ads connection is unreachable/i),+ ).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Reconnect/i })).toBeInTheDocument();+ });++ it("renders the 'configured_no_token' headline", () => {+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "configured_no_token", url: "https://x" }}+ />,+ );+ expect(+ screen.getByText(/Google Ads MCP needs a token/i),+ ).toBeInTheDocument();+ });++ it("links Manage connections to the project-scoped connections page", () => {+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "not_configured" }}+ />,+ );+ const link = screen.getByRole("link", { name: /Manage connections/i });+ expect(link).toHaveAttribute("href", `/${SLUG}/connections`);+ });++ it("posts the current URL as return_to and redirects on Connect success", async () => {+ startMcpConnect.mockResolvedValue({+ ok: true,+ authorize_url: "https://issuer.example/oauth?state=zzz",+ });+ const loc = setLocation(+ "http://localhost:3000/acme/agents/google_ads/chat?task=abc",+ );+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "not_configured" }}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /^Connect$/ }));+ await waitFor(() =>+ expect(startMcpConnect).toHaveBeenCalledWith({+ mcp_key: "notfair-googleads",+ return_to: "/acme/agents/google_ads/chat?task=abc",+ }),+ );+ await waitFor(() =>+ expect(loc.href).toBe("https://issuer.example/oauth?state=zzz"),+ );+ });++ it("toasts and re-enables the button when Connect returns ok=false", async () => {+ startMcpConnect.mockResolvedValue({ ok: false, error: "discovery failed" });+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "not_configured" }}+ />,+ );+ const button = screen.getByRole("button", { name: /^Connect$/ });+ fireEvent.click(button);+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("discovery failed"),+ );+ expect(button).not.toBeDisabled();+ });++ it("toasts the thrown error message when Connect throws", async () => {+ startMcpConnect.mockRejectedValue(new Error("boom"));+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "not_configured" }}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: /^Connect$/ }));+ await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("boom"));+ });++ it("disables the Connect button while a request is in flight", async () => {+ let resolve: (v: { ok: true; authorize_url: string }) => void = () => {};+ startMcpConnect.mockImplementation(+ () =>+ new Promise<{ ok: true; authorize_url: string }>((res) => {+ resolve = res;+ }),+ );+ render(+ <GoogleAdsMcpBanner+ projectSlug={SLUG}+ status={{ state: "not_configured" }}+ />,+ );+ const button = screen.getByRole("button", { name: /^Connect$/ });+ fireEvent.click(button);+ await waitFor(() => expect(button).toBeDisabled());+ resolve({ ok: true, authorize_url: "https://issuer.example" });+ });+});diff --git a/src/components/live-transcript.test.tsx b/src/components/live-transcript.test.tsxnew file mode 100644index 00000000..a176d77c--- /dev/null+++ b/src/components/live-transcript.test.tsx@@ -0,0 +1,672 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, act, cleanup } from "@testing-library/react";++const { routerPush, toastFns } = vi.hoisted(() => ({+ routerPush: vi.fn(),+ toastFns: {+ info: vi.fn(),+ error: vi.fn(),+ message: vi.fn(),+ },+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: routerPush,+ replace: vi.fn(),+ refresh: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ }),+}));++vi.mock("sonner", () => ({+ toast: toastFns,+}));++vi.mock("@/components/markdown", () => ({+ Markdown: ({ children }: { children: string }) => (+ <div data-testid="markdown">{children}</div>+ ),+}));++vi.mock("@/server/orchestration/blocks", () => ({+ stripOrchestrationBlocks: (s: string) => s,+}));++import { LiveTranscript } from "./live-transcript";+import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";++type FetchHandler = (url: string, init?: RequestInit) => Promise<Response>;++function setFetch(handler: FetchHandler) {+ // @ts-expect-error vitest jsdom env+ global.fetch = vi.fn(handler);+}++function defaultProps(overrides: Partial<React.ComponentProps<typeof LiveTranscript>> = {}) {+ return {+ projectSlug: "demo",+ agentSlug: "cmo",+ agentDisplayName: "CMO",+ threadId: "t1",+ sessionKey: "agent:cmo:t1",+ initialEvents: [] as TranscriptEvent[],+ initialByteOffset: 0,+ ...overrides,+ };+}++function makeEmptyTranscriptResponse(byteOffset = 0) {+ return new Response(+ JSON.stringify({ events: [], byteOffset, file_size: byteOffset }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+}++beforeEach(() => {+ routerPush.mockClear();+ toastFns.info.mockClear();+ toastFns.error.mockClear();+ toastFns.message.mockClear();+ setFetch(async () => makeEmptyTranscriptResponse());+ // jsdom doesn't implement scrollIntoView; the slash popover calls it inside+ // a useEffect after render. Polyfill once to avoid spurious crashes.+ // @ts-expect-error jsdom polyfill+ if (!Element.prototype.scrollIntoView) {+ // @ts-expect-error jsdom polyfill+ Element.prototype.scrollIntoView = () => {};+ }+ // Stable threadId per test won't pollute KICKOFF_FIRED guard for other tests.+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe("LiveTranscript empty state", () => {+ it("renders the empty state when no events and composer is idle", () => {+ render(<LiveTranscript {...defaultProps()} />);+ expect(+ screen.getByText(/no messages yet\. say hi to cmo/i),+ ).toBeInTheDocument();+ });++ it("hides the empty state when composerDisabled (task in flight)", () => {+ render(<LiveTranscript {...defaultProps({ composerDisabled: true, threadId: "t-disabled" })} />);+ expect(+ screen.queryByText(/no messages yet/i),+ ).not.toBeInTheDocument();+ // WorkingStatus pulse is shown via the role="status" RunningDot.+ expect(screen.getByText(/Starting CMO/i)).toBeInTheDocument();+ });+});++describe("LiveTranscript rendering events", () => {+ it("renders user, assistant text and tool group bubbles", () => {+ const events: TranscriptEvent[] = [+ { kind: "user_message", id: "u1", ts: 1, body: "hello there" },+ { kind: "assistant_text", id: "a1", ts: 2, body: "hi back" },+ {+ kind: "tool_call",+ id: "t1",+ ts: 3,+ tool_call_id: "call-1",+ name: "read",+ label: "/etc/passwd",+ },+ {+ kind: "tool_result",+ id: "r1",+ ts: 4,+ tool_call_id: "call-1",+ name: "read",+ summary: "ok output",+ ok: true,+ },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-render" })} />);+ expect(screen.getByText("hello there")).toBeInTheDocument();+ expect(screen.getByTestId("markdown")).toHaveTextContent("hi back");+ // Tool name "read" appears both in the group headline and in the per-row.+ expect(screen.getAllByText("read").length).toBeGreaterThanOrEqual(1);+ expect(screen.getAllByText("/etc/passwd").length).toBeGreaterThanOrEqual(1);+ expect(screen.getByText(/ok output/)).toBeInTheDocument();+ expect(screen.getByText(/→ result/)).toBeInTheDocument();+ });++ it("renders kickoff-style user messages as a collapsible task brief block", () => {+ const events: TranscriptEvent[] = [+ { kind: "user_message", id: "u1", ts: 1, body: "(task assignment) audit the account" },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-kickoff" })} />);+ expect(screen.getByText(/Task brief sent to agent/i)).toBeInTheDocument();+ expect(screen.getByText(/audit the account/)).toBeInTheDocument();+ });++ it("shows error-status icon when the latest tool result failed", () => {+ const events: TranscriptEvent[] = [+ {+ kind: "tool_call",+ id: "t1",+ ts: 1,+ tool_call_id: "call-1",+ name: "fetch",+ label: "https://example.com",+ },+ {+ kind: "tool_result",+ id: "r1",+ ts: 2,+ tool_call_id: "call-1",+ name: "fetch",+ summary: "boom",+ ok: false,+ },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-err" })} />);+ expect(screen.getByText(/→ error/)).toBeInTheDocument();+ expect(screen.getByText("boom")).toBeInTheDocument();+ });++ it("groups multiple consecutive tool calls into a single tool group with step count", () => {+ const events: TranscriptEvent[] = [+ {+ kind: "tool_call",+ id: "t1",+ ts: 1,+ tool_call_id: "c1",+ name: "read",+ label: "a.txt",+ },+ {+ kind: "tool_result",+ id: "r1",+ ts: 2,+ tool_call_id: "c1",+ name: "read",+ summary: "result a",+ ok: true,+ },+ {+ kind: "tool_call",+ id: "t2",+ ts: 3,+ tool_call_id: "c2",+ name: "read",+ label: "b.txt",+ },+ {+ kind: "tool_result",+ id: "r2",+ ts: 4,+ tool_call_id: "c2",+ name: "read",+ summary: "result b",+ ok: true,+ },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-grp" })} />);+ expect(screen.getByText(/2 steps/i)).toBeInTheDocument();+ });++ it("ignores assistant text that becomes empty after orchestration stripping", async () => {+ // Override the mock just for this test by temporarily replacing strip fn.+ const blocks = await import("@/server/orchestration/blocks");+ const spy = vi+ .spyOn(blocks, "stripOrchestrationBlocks")+ .mockImplementation(() => " ");+ const events: TranscriptEvent[] = [+ { kind: "assistant_text", id: "a1", ts: 1, body: "<task>only block</task>" },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-strip" })} />);+ expect(screen.queryByTestId("markdown")).not.toBeInTheDocument();+ spy.mockRestore();+ });++ it("returns null for system 'unknown' events (renders no row)", () => {+ const events: TranscriptEvent[] = [+ { kind: "unknown", id: "x1", ts: 1, raw_type: "session_metadata" },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-unknown" })} />);+ // No empty state (events.length > 0) and no rendered content.+ expect(screen.queryByText(/no messages yet/i)).not.toBeInTheDocument();+ expect(screen.queryByText("session_metadata")).not.toBeInTheDocument();+ });+});++describe("LiveTranscript composer", () => {+ it("disables submit button when input is empty", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-sub" })} />);+ const submit = screen.getByRole("button", { name: /send/i });+ expect(submit).toBeDisabled();+ });++ it("enables submit once the user types", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-typ" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "hi" } });+ expect(screen.getByRole("button", { name: /send/i })).not.toBeDisabled();+ });++ it("disables the composer textarea when composerDisabled is true", () => {+ render(<LiveTranscript {...defaultProps({ composerDisabled: true, threadId: "t-cd" })} />);+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ expect(textarea).toBeDisabled();+ expect(textarea.placeholder).toMatch(/CMO is on a task/i);+ });++ it("submitting Shift+Enter inserts a newline and does NOT send", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-shift" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "line 1" } });+ fireEvent.keyDown(textarea, { key: "Enter", shiftKey: true });+ // Should NOT have called fetch with /api/chat — only background poll URLs.+ const f = global.fetch as ReturnType<typeof vi.fn>;+ const chatCalls = f.mock.calls.filter(+ ([u]) => typeof u === "string" && u.includes("/api/chat"),+ );+ expect(chatCalls.length).toBe(0);+ });+});++describe("LiveTranscript slash commands", () => {+ it("opens slash popover and filters as user types", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-slash" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "/" } });+ expect(screen.getByRole("listbox", { name: /slash commands/i })).toBeInTheDocument();+ // /clear should appear in essential local commands+ expect(screen.getByText("/clear")).toBeInTheDocument();+ });++ it("clicking a slash command inserts the canonical text into the input", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-slash-click" })} />);+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "/cle" } });+ const option = screen.getByRole("option", { name: /\/clear/i });+ fireEvent.click(option);+ expect(textarea.value).toBe("/clear ");+ });++ it("clears the local view when /clear is submitted", async () => {+ const events: TranscriptEvent[] = [+ { kind: "user_message", id: "u1", ts: 1, body: "old turn" },+ { kind: "assistant_text", id: "a1", ts: 2, body: "old reply" },+ ];+ render(<LiveTranscript {...defaultProps({ initialEvents: events, threadId: "t-clear" })} />);+ expect(screen.getByText("old turn")).toBeInTheDocument();+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "/clear" } });+ // Close popover by adding a trailing space so the form-submit path runs.+ fireEvent.change(textarea, { target: { value: "/clear " } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => {+ expect(screen.queryByText("old turn")).not.toBeInTheDocument();+ });+ expect(toastFns.info).toHaveBeenCalled();+ // After clearing, idle empty state should reappear.+ expect(screen.getByText(/no messages yet/i)).toBeInTheDocument();+ });++ it("pushes a new chat URL when /new is submitted", async () => {+ // jsdom doesn't ship crypto.randomUUID in older versions — guarantee it.+ if (typeof crypto.randomUUID !== "function") {+ // @ts-expect-error patch for jsdom+ crypto.randomUUID = () => "11111111-1111-1111-1111-111111111111";+ }+ render(<LiveTranscript {...defaultProps({ threadId: "t-new" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "/new " } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => {+ expect(routerPush).toHaveBeenCalled();+ });+ const target = routerPush.mock.calls[0]![0];+ expect(target).toMatch(/^\/demo\/agents\/cmo\/chat\//);+ });++ it("renders the help toast when /help is submitted", async () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-help" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "/help " } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => expect(toastFns.message).toHaveBeenCalled());+ });++ it("escape closes the popover and clears the input", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-esc" })} />);+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "/cl" } });+ expect(screen.getByRole("listbox")).toBeInTheDocument();+ fireEvent.keyDown(textarea, { key: "Escape" });+ expect(textarea.value).toBe("");+ });++ it("arrow keys cycle the slash command selection", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-arrow" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "/" } });+ const items = screen.getAllByRole("option");+ expect(items.length).toBeGreaterThan(1);+ // First option is selected initially.+ expect(items[0]).toHaveAttribute("aria-selected", "true");+ fireEvent.keyDown(textarea, { key: "ArrowDown" });+ const afterDown = screen.getAllByRole("option");+ expect(afterDown[1]).toHaveAttribute("aria-selected", "true");+ fireEvent.keyDown(textarea, { key: "ArrowUp" });+ const afterUp = screen.getAllByRole("option");+ expect(afterUp[0]).toHaveAttribute("aria-selected", "true");+ });++ it("Tab in the popover inserts the highlighted command", () => {+ render(<LiveTranscript {...defaultProps({ threadId: "t-tab" })} />);+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "/" } });+ fireEvent.keyDown(textarea, { key: "Tab" });+ expect(textarea.value).toMatch(/^\/\S+\s$/);+ });+});++describe("LiveTranscript /api/chat send path", () => {+ it("posts the user message, streams SSE text into a pending bubble, and shows a stop button", async () => {+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(+ encoder.encode("event: text\ndata: {\"chunk\":\"Hello \"}\n\n"),+ );+ controller.enqueue(+ encoder.encode("event: text\ndata: {\"chunk\":\"world\"}\n\n"),+ );+ controller.close();+ },+ });++ setFetch(async (url) => {+ if (url.includes("/api/chat")) {+ return new Response(stream, { status: 200 });+ }+ return makeEmptyTranscriptResponse();+ });++ render(<LiveTranscript {...defaultProps({ threadId: "t-send" })} />);+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;+ fireEvent.change(textarea, { target: { value: "Hi agent" } });+ fireEvent.submit(textarea.closest("form")!);++ // Optimistic user bubble appears immediately.+ await waitFor(() => {+ expect(screen.getByText("Hi agent")).toBeInTheDocument();+ });+ // Stream chunks should be rendered through Markdown stub.+ await waitFor(() => {+ const md = screen.getAllByTestId("markdown").pop();+ expect(md?.textContent).toContain("Hello world");+ });+ // Stop button is visible while sending.+ expect(screen.getByRole("button", { name: /stop/i })).toBeInTheDocument();+ });++ it("renders an SSE-reported error and toasts when the stream emits an error event", async () => {+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ "event: error\ndata: {\"message\":\"upstream failed\"}\n\n",+ ),+ );+ controller.close();+ },+ });+ setFetch(async (url) => {+ if (url.includes("/api/chat")) {+ return new Response(stream, { status: 200 });+ }+ return makeEmptyTranscriptResponse();+ });++ render(<LiveTranscript {...defaultProps({ threadId: "t-sse-err" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "go" } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => {+ expect(screen.getByText("upstream failed")).toBeInTheDocument();+ });+ expect(screen.getByText(/Couldn.t reach CMO/i)).toBeInTheDocument();+ });++ it("renders a thrown fetch error and surfaces a toast", async () => {+ setFetch(async (url) => {+ if (url.includes("/api/chat")) {+ return new Response("kaboom", { status: 500 });+ }+ return makeEmptyTranscriptResponse();+ });+ render(<LiveTranscript {...defaultProps({ threadId: "t-http-err" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "go" } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => {+ expect(toastFns.error).toHaveBeenCalled();+ });+ expect(screen.getByText("kaboom")).toBeInTheDocument();+ });++ it("streams a tool start event into the live tool group", async () => {+ const encoder = new TextEncoder();+ let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;+ const stream = new ReadableStream({+ start(controller) {+ controllerRef = controller;+ controller.enqueue(+ encoder.encode(+ "event: tool\ndata: {\"phase\":\"start\",\"tool_call_id\":\"c-1\",\"name\":\"shell\",\"label\":\"ls\"}\n\n",+ ),+ );+ },+ });+ setFetch(async (url) => {+ if (url.includes("/api/chat")) {+ return new Response(stream, { status: 200 });+ }+ return makeEmptyTranscriptResponse();+ });+ render(<LiveTranscript {...defaultProps({ threadId: "t-tool-stream" })} />);+ const textarea = screen.getByRole("textbox");+ fireEvent.change(textarea, { target: { value: "ls" } });+ fireEvent.submit(textarea.closest("form")!);+ await waitFor(() => {+ expect(screen.getAllByText("shell").length).toBeGreaterThanOrEqual(1);+ expect(screen.getAllByText("ls").length).toBeGreaterThanOrEqual(1);+ });+ // Wrap up the stream so the send promise finishes before unmount.+ controllerRef!.close();+ });+});++describe("LiveTranscript polling", () => {+ it("polls the transcript endpoint and appends fresh events", async () => {+ const calls: string[] = [];+ let polled = 0;+ setFetch(async (url) => {+ const u = String(url);+ calls.push(u);+ if (u.includes("/transcript")) {+ polled++;+ if (polled === 1) {+ const fresh: TranscriptEvent[] = [+ { kind: "assistant_text", id: "poll-a1", ts: 5, body: "polled in" },+ ];+ return new Response(+ JSON.stringify({ events: fresh, byteOffset: 200, file_size: 200 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ }+ return makeEmptyTranscriptResponse(200);+ }+ return makeEmptyTranscriptResponse();+ });++ vi.useFakeTimers();+ render(<LiveTranscript {...defaultProps({ threadId: "t-poll" })} />);+ // Advance past the default poll interval.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_100);+ });+ vi.useRealTimers();+ await waitFor(() => {+ expect(screen.getByTestId("markdown")).toHaveTextContent("polled in");+ });+ expect(calls.some((u) => u.includes("/transcript"))).toBe(true);+ });++ it("invokes onPolled with new event counts and stops polling when it returns true", async () => {+ let polled = 0;+ setFetch(async (url) => {+ if (String(url).includes("/transcript")) {+ polled++;+ return new Response(+ JSON.stringify({ events: [], byteOffset: 0, file_size: 42 }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ }+ return makeEmptyTranscriptResponse();+ });+ const onPolled = vi.fn(() => true);+ vi.useFakeTimers();+ render(+ <LiveTranscript+ {...defaultProps({ threadId: "t-onpolled", onPolled })}+ />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_100);+ });+ expect(onPolled).toHaveBeenCalledWith({ newEvents: 0, fileSize: 42 });+ // After stop, additional ticks shouldn't add more polls.+ const before = polled;+ await act(async () => {+ await vi.advanceTimersByTimeAsync(5_000);+ });+ vi.useRealTimers();+ expect(polled).toBe(before);+ });++ it("dedupes events by id across overlapping poll cycles", async () => {+ let polled = 0;+ setFetch(async (url) => {+ if (String(url).includes("/transcript")) {+ polled++;+ // Always return the same single event — second poll would duplicate.+ return new Response(+ JSON.stringify({+ events: [+ { kind: "assistant_text", id: "dup-1", ts: 1, body: "once" },+ ],+ byteOffset: 0,+ file_size: 1,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ );+ }+ return makeEmptyTranscriptResponse();+ });+ vi.useFakeTimers();+ render(<LiveTranscript {...defaultProps({ threadId: "t-dedupe" })} />);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_100);+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_100);+ });+ vi.useRealTimers();+ await waitFor(() => {+ const mds = screen.getAllByTestId("markdown");+ expect(mds.filter((m) => m.textContent === "once").length).toBe(1);+ });+ expect(polled).toBeGreaterThanOrEqual(2);+ });++ it("tolerates a non-OK transcript poll response", async () => {+ setFetch(async (url) => {+ if (String(url).includes("/transcript")) {+ return new Response("nope", { status: 500 });+ }+ return makeEmptyTranscriptResponse();+ });+ vi.useFakeTimers();+ render(<LiveTranscript {...defaultProps({ threadId: "t-poll-500" })} />);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(2_100);+ });+ vi.useRealTimers();+ // No crash, empty state still rendered.+ expect(screen.getByText(/no messages yet/i)).toBeInTheDocument();+ });+});++describe("LiveTranscript autoKickoff", () => {+ it("fires a hidden first message via /api/chat when autoKickoff is true and transcript is empty", async () => {+ const encoder = new TextEncoder();+ let chatCalled = false;+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(+ encoder.encode("event: text\ndata: {\"chunk\":\"hi\"}\n\n"),+ );+ controller.close();+ },+ });+ setFetch(async (url, init) => {+ if (String(url).includes("/api/chat")) {+ chatCalled = true;+ const body = JSON.parse((init?.body as string) ?? "{}");+ // Carries the kickoff override.+ expect(body.message).toBe("kickoff!");+ return new Response(stream, { status: 200 });+ }+ return makeEmptyTranscriptResponse();+ });+ render(+ <LiveTranscript+ {...defaultProps({+ autoKickoff: true,+ kickoffMessage: "kickoff!",+ threadId: "t-kickoff-unique-1",+ })}+ />,+ );+ await waitFor(() => expect(chatCalled).toBe(true));+ // Hidden: no visible user bubble should show the kickoff text.+ expect(screen.queryByText("kickoff!")).not.toBeInTheDocument();+ });++ it("does not auto-kickoff a second time for the same threadId (module guard)", async () => {+ // Re-uses the same threadId as the previous test which already added to KICKOFF_FIRED.+ let chatCalled = false;+ setFetch(async (url) => {+ if (String(url).includes("/api/chat")) {+ chatCalled = true;+ return new Response("", { status: 200 });+ }+ return makeEmptyTranscriptResponse();+ });+ render(+ <LiveTranscript+ {...defaultProps({+ autoKickoff: true,+ kickoffMessage: "kickoff!",+ threadId: "t-kickoff-unique-1",+ })}+ />,+ );+ // Give the effect a tick to run.+ await new Promise((r) => setTimeout(r, 20));+ expect(chatCalled).toBe(false);+ });+});diff --git a/src/components/markdown.test.tsx b/src/components/markdown.test.tsxnew file mode 100644index 00000000..e9e24674--- /dev/null+++ b/src/components/markdown.test.tsx@@ -0,0 +1,111 @@+// @vitest-environment jsdom+import { describe, it, expect } from "vitest";+import { render } from "@testing-library/react";++import { Markdown } from "./markdown";++describe("Markdown", () => {+ it("renders a paragraph with leading-relaxed styling", () => {+ const { container } = render(<Markdown>Hello **world**</Markdown>);+ const p = container.querySelector("p");+ expect(p).not.toBeNull();+ expect(p?.className).toContain("leading-relaxed");+ expect(p?.querySelector("strong")?.textContent).toBe("world");+ });++ it("renders unordered and ordered lists", () => {+ const { container } = render(<Markdown>{"- a\n- b\n\n1. one\n2. two"}</Markdown>);+ const ul = container.querySelector("ul");+ const ol = container.querySelector("ol");+ expect(ul?.querySelectorAll("li").length).toBe(2);+ expect(ol?.querySelectorAll("li").length).toBe(2);+ expect(ul?.className).toContain("list-disc");+ expect(ol?.className).toContain("list-decimal");+ });++ it("renders headings h1-h4 as semibold elements", () => {+ const { container } = render(+ <Markdown>{"# H1\n\n## H2\n\n### H3\n\n#### H4"}</Markdown>,+ );+ expect(container.querySelector("h1")?.textContent).toBe("H1");+ expect(container.querySelector("h2")?.textContent).toBe("H2");+ expect(container.querySelector("h3")?.textContent).toBe("H3");+ expect(container.querySelector("h4")?.textContent).toBe("H4");+ expect(container.querySelector("h1")?.className).toContain("font-semibold");+ });++ it("links open in a new tab with noopener/noreferrer", () => {+ const { container } = render(+ <Markdown>{"[click](https://example.com)"}</Markdown>,+ );+ const a = container.querySelector("a");+ expect(a).not.toBeNull();+ expect(a?.getAttribute("href")).toBe("https://example.com");+ expect(a?.getAttribute("target")).toBe("_blank");+ expect(a?.getAttribute("rel")).toBe("noopener noreferrer");+ });++ it("renders inline code with rounded muted background", () => {+ const { container } = render(<Markdown>{"Use `npm` here"}</Markdown>);+ const code = container.querySelector("code");+ expect(code).not.toBeNull();+ expect(code?.textContent).toBe("npm");+ // Inline (no language-) -> uses rounded bg-muted; fenced uses leading-relaxed only.+ expect(code?.className).toContain("rounded");+ expect(code?.className).toContain("bg-muted");+ });++ it("renders fenced code blocks inside <pre> with language hint", () => {+ const md = "```json\n{\"a\":1}\n```";+ const { container } = render(<Markdown>{md}</Markdown>);+ const pre = container.querySelector("pre");+ const code = pre?.querySelector("code");+ expect(pre).not.toBeNull();+ expect(code?.className).toContain("language-json");+ expect(code?.className).toContain("font-mono");+ expect(pre?.className).toContain("overflow-x-auto");+ });++ it("renders blockquote, hr, and gfm table elements", () => {+ const md = [+ "> quoted",+ "",+ "---",+ "",+ "| a | b |",+ "| --- | --- |",+ "| 1 | 2 |",+ ].join("\n");+ const { container } = render(<Markdown>{md}</Markdown>);+ expect(container.querySelector("blockquote")?.textContent).toContain("quoted");+ expect(container.querySelector("hr")).not.toBeNull();+ const table = container.querySelector("table");+ expect(table).not.toBeNull();+ expect(table?.parentElement?.className).toContain("overflow-x-auto");+ expect(container.querySelectorAll("th").length).toBe(2);+ expect(container.querySelectorAll("td").length).toBe(2);+ });++ it("emphasis renders as <em>", () => {+ const { container } = render(<Markdown>{"This is *italic* text"}</Markdown>);+ expect(container.querySelector("em")?.textContent).toBe("italic");+ });++ it("does not render raw HTML (script tags are escaped, not executed)", () => {+ const { container } = render(+ <Markdown>{"hi <script>alert(1)</script> bye"}</Markdown>,+ );+ // react-markdown without rehype-raw renders HTML as literal text.+ expect(container.querySelector("script")).toBeNull();+ expect(container.textContent).toContain("alert(1)");+ });++ it("applies a user-supplied className to the wrapper", () => {+ const { container } = render(+ <Markdown className="custom-x">hello</Markdown>,+ );+ const wrapper = container.firstChild as HTMLElement;+ expect(wrapper.className).toContain("custom-x");+ expect(wrapper.className).toContain("text-sm");+ });+});diff --git a/src/components/mcp-card.test.tsx b/src/components/mcp-card.test.tsxnew file mode 100644index 00000000..342fdc30--- /dev/null+++ b/src/components/mcp-card.test.tsx@@ -0,0 +1,246 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const { startMcpConnect, disconnectMcpAction, routerRefresh, toastFns } = vi.hoisted(() => ({+ startMcpConnect: vi.fn(),+ disconnectMcpAction: vi.fn(),+ routerRefresh: vi.fn(),+ toastFns: {+ success: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock("@/server/actions/mcp", () => ({+ startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),+ disconnectMcpAction: (...args: unknown[]) => disconnectMcpAction(...args),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: vi.fn(),+ replace: vi.fn(),+ refresh: routerRefresh,+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ }),+}));++vi.mock("sonner", () => ({+ toast: toastFns,+}));++import { McpCard } from "./mcp-card";+import type { McpSpec } from "@/server/mcp-catalog";+import type { McpRuntimeStatus } from "@/server/mcp-state";++const spec: McpSpec = {+ key: "notfair-googleads",+ display_name: "NotFair Google Ads",+ description: "Live Google Ads operations.",+ resource_url: "https://notfair.co/api/mcp/google_ads",+ discovery_url:+ "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",+};++function connected(overrides: Partial<Extract<McpRuntimeStatus, { state: "connected" }>> = {}): McpRuntimeStatus {+ return {+ state: "connected",+ url: "https://notfair.co/api/mcp/google_ads",+ tools_count: 12,+ last_checked_at: new Date().toISOString(),+ ...overrides,+ };+}++function setLocationHref() {+ const original = window.location;+ const fake = { ...original, href: "" } as Location & { href: string };+ Object.defineProperty(window, "location", {+ writable: true,+ configurable: true,+ value: fake,+ });+ return fake;+}++beforeEach(() => {+ startMcpConnect.mockReset();+ disconnectMcpAction.mockReset();+ routerRefresh.mockReset();+ toastFns.success.mockReset();+ toastFns.error.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("McpCard", () => {+ it("shows spec metadata (name, description, resource_url)", () => {+ render(<McpCard spec={spec} status={{ state: "not_configured" }} />);+ expect(screen.getByText(spec.display_name)).toBeInTheDocument();+ expect(screen.getByText(spec.description)).toBeInTheDocument();+ expect(screen.getByText(spec.resource_url)).toBeInTheDocument();+ });++ it("renders a 'connected' badge and tool count when status is connected", () => {+ render(<McpCard spec={spec} status={connected({ tools_count: 12 })} />);+ expect(screen.getByText("connected")).toBeInTheDocument();+ expect(screen.getByText(/12 tools available/)).toBeInTheDocument();+ });++ it("uses the singular 'tool' wording when tools_count is 1", () => {+ render(<McpCard spec={spec} status={connected({ tools_count: 1 })} />);+ expect(screen.getByText(/1 tool available/)).toBeInTheDocument();+ });++ it("falls back to 'Live.' when tools_count is null", () => {+ render(<McpCard spec={spec} status={connected({ tools_count: null })} />);+ expect(screen.getByText(/Live\./)).toBeInTheDocument();+ });++ it("shows a Disconnect button when connected and a Connect button otherwise", () => {+ const { rerender } = render(+ <McpCard spec={spec} status={connected()} />,+ );+ expect(+ screen.getByRole("button", { name: /disconnect/i }),+ ).toBeInTheDocument();+ rerender(<McpCard spec={spec} status={{ state: "not_configured" }} />);+ expect(+ screen.getByRole("button", { name: /^connect$/i }),+ ).toBeInTheDocument();+ });++ it("labels the action button 'Reconnect' on stale_token", () => {+ render(+ <McpCard+ spec={spec}+ status={{+ state: "stale_token",+ url: "https://x",+ http_status: 401,+ last_checked_at: new Date().toISOString(),+ }}+ />,+ );+ expect(+ screen.getByRole("button", { name: /reconnect/i }),+ ).toBeInTheDocument();+ expect(screen.getByText(/token expired/i)).toBeInTheDocument();+ expect(screen.getByText(/HTTP 401/)).toBeInTheDocument();+ });++ it("renders the unreachable status with the underlying error", () => {+ render(+ <McpCard+ spec={spec}+ status={{+ state: "unreachable",+ url: "https://x",+ error: "ECONNREFUSED",+ last_checked_at: new Date().toISOString(),+ }}+ />,+ );+ expect(screen.getByText(/unreachable/i)).toBeInTheDocument();+ expect(screen.getByText(/ECONNREFUSED/)).toBeInTheDocument();+ });++ it("renders the configured_no_token status with helper text", () => {+ render(+ <McpCard+ spec={spec}+ status={{ state: "configured_no_token", url: "https://x" }}+ />,+ );+ expect(screen.getByText(/no token/i)).toBeInTheDocument();+ expect(+ screen.getByText(/Config exists but has no bearer token/i),+ ).toBeInTheDocument();+ });++ it("redirects the browser to authorize_url when Connect succeeds", async () => {+ const loc = setLocationHref();+ startMcpConnect.mockResolvedValue({+ ok: true,+ authorize_url: "https://issuer.example/oauth?state=abc",+ });+ render(<McpCard spec={spec} status={{ state: "not_configured" }} />);+ fireEvent.click(screen.getByRole("button", { name: /^connect$/i }));+ await waitFor(() =>+ expect(startMcpConnect).toHaveBeenCalledWith({ mcp_key: spec.key }),+ );+ await waitFor(() =>+ expect(loc.href).toBe("https://issuer.example/oauth?state=abc"),+ );+ expect(toastFns.error).not.toHaveBeenCalled();+ });++ it("toasts and stays on-page when Connect returns ok=false", async () => {+ startMcpConnect.mockResolvedValue({ ok: false, error: "discovery failed" });+ render(<McpCard spec={spec} status={{ state: "not_configured" }} />);+ fireEvent.click(screen.getByRole("button", { name: /^connect$/i }));+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("discovery failed"),+ );+ // Button is re-enabled.+ expect(screen.getByRole("button", { name: /^connect$/i })).not.toBeDisabled();+ });++ it("toasts the thrown error message when Connect throws", async () => {+ startMcpConnect.mockRejectedValue(new Error("network down"));+ render(<McpCard spec={spec} status={{ state: "not_configured" }} />);+ fireEvent.click(screen.getByRole("button", { name: /^connect$/i }));+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("network down"),+ );+ });++ it("disconnects, toasts success, and refreshes the router", async () => {+ disconnectMcpAction.mockResolvedValue({ ok: true });+ render(<McpCard spec={spec} status={connected()} />);+ fireEvent.click(screen.getByRole("button", { name: /disconnect/i }));+ await waitFor(() =>+ expect(disconnectMcpAction).toHaveBeenCalledWith({ mcp_key: spec.key }),+ );+ await waitFor(() =>+ expect(toastFns.success).toHaveBeenCalledWith(+ `${spec.display_name} disconnected`,+ ),+ );+ expect(routerRefresh).toHaveBeenCalled();+ });++ it("toasts the error and skips router.refresh when Disconnect returns ok=false", async () => {+ disconnectMcpAction.mockResolvedValue({+ ok: false,+ error: "openclaw permission denied",+ });+ render(<McpCard spec={spec} status={connected()} />);+ fireEvent.click(screen.getByRole("button", { name: /disconnect/i }));+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("openclaw permission denied"),+ );+ expect(routerRefresh).not.toHaveBeenCalled();+ });++ it("disables the Connect button while the connect call is in flight", async () => {+ setLocationHref();+ let resolve: (v: { ok: true; authorize_url: string }) => void = () => {};+ startMcpConnect.mockImplementation(+ () =>+ new Promise<{ ok: true; authorize_url: string }>((res) => {+ resolve = res;+ }),+ );+ render(<McpCard spec={spec} status={{ state: "not_configured" }} />);+ const button = screen.getByRole("button", { name: /^connect$/i });+ fireEvent.click(button);+ await waitFor(() => expect(button).toBeDisabled());+ resolve({ ok: true, authorize_url: "https://issuer.example" });+ });+});diff --git a/src/components/mcp-flash-banner.test.tsx b/src/components/mcp-flash-banner.test.tsxnew file mode 100644index 00000000..1c00bcde--- /dev/null+++ b/src/components/mcp-flash-banner.test.tsx@@ -0,0 +1,94 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, cleanup, waitFor } from "@testing-library/react";++const { routerReplace, toastFns } = vi.hoisted(() => ({+ routerReplace: vi.fn(),+ toastFns: {+ success: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: vi.fn(),+ replace: routerReplace,+ refresh: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ }),+}));++vi.mock("sonner", () => ({+ toast: toastFns,+}));++import { McpFlashBanner } from "./mcp-flash-banner";++function setLocation(href: string) {+ Object.defineProperty(window, "location", {+ writable: true,+ value: new URL(href),+ });+}++beforeEach(() => {+ routerReplace.mockReset();+ toastFns.success.mockReset();+ toastFns.error.mockReset();+ setLocation(+ "http://localhost:3000/connections?mcp_connected=NotFair&other=keep",+ );+});++afterEach(() => {+ cleanup();+});++describe("McpFlashBanner", () => {+ it("renders nothing (returns null)", () => {+ const { container } = render(<McpFlashBanner />);+ expect(container.firstChild).toBeNull();+ });++ it("toasts a success message and strips ?mcp_connected from the URL", async () => {+ render(<McpFlashBanner connected="NotFair Google Ads" />);+ await waitFor(() =>+ expect(toastFns.success).toHaveBeenCalledWith(+ "Connected: NotFair Google Ads",+ ),+ );+ expect(routerReplace).toHaveBeenCalledWith("/connections?other=keep");+ });++ it("toasts an error and strips ?mcp_error when an error is provided", async () => {+ setLocation("http://localhost:3000/connections?mcp_error=boom&keep=1");+ render(<McpFlashBanner error="boom" />);+ await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("boom"));+ expect(toastFns.success).not.toHaveBeenCalled();+ expect(routerReplace).toHaveBeenCalledWith("/connections?keep=1");+ });++ it("prefers the error toast when both connected and error are supplied", async () => {+ render(<McpFlashBanner connected="x" error="bad" />);+ await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("bad"));+ expect(toastFns.success).not.toHaveBeenCalled();+ });++ it("does nothing when neither connected nor error is supplied", () => {+ render(<McpFlashBanner />);+ expect(toastFns.success).not.toHaveBeenCalled();+ expect(toastFns.error).not.toHaveBeenCalled();+ expect(routerReplace).not.toHaveBeenCalled();+ });++ it("returns a pathname-only URL when no query params remain after stripping", async () => {+ setLocation("http://localhost:3000/connections?mcp_connected=x");+ render(<McpFlashBanner connected="x" />);+ await waitFor(() =>+ expect(routerReplace).toHaveBeenCalledWith("/connections"),+ );+ });+});diff --git a/src/components/onboarding-flow.test.tsx b/src/components/onboarding-flow.test.tsxnew file mode 100644index 00000000..d01fa247--- /dev/null+++ b/src/components/onboarding-flow.test.tsx@@ -0,0 +1,478 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup, act } from "@testing-library/react";++const {+ createProjectForOnboardingAction,+ startMcpConnect,+ listGoogleAdsAccounts,+ setOnboardingAccountAction,+ routerPush,+ routerReplace,+ toastFns,+ searchParamsRef,+} = vi.hoisted(() => ({+ createProjectForOnboardingAction: vi.fn(),+ startMcpConnect: vi.fn(),+ listGoogleAdsAccounts: vi.fn(),+ setOnboardingAccountAction: vi.fn(),+ routerPush: vi.fn(),+ routerReplace: vi.fn(),+ toastFns: {+ success: vi.fn(),+ error: vi.fn(),+ },+ searchParamsRef: { current: new URLSearchParams() },+}));++vi.mock("@/server/actions/projects", () => ({+ createProjectForOnboardingAction: (...args: unknown[]) =>+ createProjectForOnboardingAction(...args),+}));++vi.mock("@/server/actions/mcp", () => ({+ startMcpConnect: (...args: unknown[]) => startMcpConnect(...args),+}));++vi.mock("@/server/onboarding/accounts", () => ({+ listGoogleAdsAccounts: (...args: unknown[]) => listGoogleAdsAccounts(...args),+ setOnboardingAccountAction: (...args: unknown[]) =>+ setOnboardingAccountAction(...args),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ push: routerPush,+ replace: routerReplace,+ refresh: vi.fn(),+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ }),+ useSearchParams: () => searchParamsRef.current,+}));++vi.mock("sonner", () => ({+ toast: toastFns,+}));++import { OnboardingFlow } from "./onboarding-flow";++function setStep(step: string | null, slug?: string | null) {+ const p = new URLSearchParams();+ if (step) p.set("step", step);+ if (slug) p.set("slug", slug);+ searchParamsRef.current = p;+}++function setLocationHref() {+ const fake = { href: "" } as Location & { href: string };+ Object.defineProperty(window, "location", {+ writable: true,+ configurable: true,+ value: fake,+ });+ return fake;+}++beforeEach(() => {+ createProjectForOnboardingAction.mockReset();+ startMcpConnect.mockReset();+ listGoogleAdsAccounts.mockReset();+ setOnboardingAccountAction.mockReset();+ routerPush.mockReset();+ routerReplace.mockReset();+ toastFns.success.mockReset();+ toastFns.error.mockReset();+ searchParamsRef.current = new URLSearchParams();+});++afterEach(() => {+ cleanup();+});++describe("OnboardingFlow — NameStep (default step)", () => {+ it("renders the project-name form when no step param is set", () => {+ render(<OnboardingFlow />);+ expect(+ screen.getByRole("heading", { name: /Let.s set up your CMO/i }),+ ).toBeInTheDocument();+ expect(screen.getByLabelText(/Name/i)).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Continue/i })).toBeInTheDocument();+ });++ it("renders the skip-to-content link for keyboard users", () => {+ render(<OnboardingFlow />);+ const skip = screen.getByText(/Skip to content/i);+ expect(skip).toHaveAttribute("href", "#onboarding-main");+ });++ it("invokes createProjectForOnboardingAction and pushes to ?step=connect on success", async () => {+ createProjectForOnboardingAction.mockResolvedValue({+ ok: true,+ data: { slug: "acme-q4", display_name: "Acme Q4" },+ });+ render(<OnboardingFlow />);+ fireEvent.change(screen.getByLabelText(/Name/i), {+ target: { value: "Acme Q4" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Continue/i }));+ await waitFor(() =>+ expect(createProjectForOnboardingAction).toHaveBeenCalled(),+ );+ await waitFor(() =>+ expect(routerPush).toHaveBeenCalledWith(+ "/onboarding?step=connect&slug=acme-q4",+ ),+ );+ });++ it("renders an inline error alert when the server action returns ok=false", async () => {+ createProjectForOnboardingAction.mockResolvedValue({+ ok: false,+ error: "Please enter a project name.",+ });+ render(<OnboardingFlow />);+ fireEvent.change(screen.getByLabelText(/Name/i), {+ target: { value: "x" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Continue/i }));+ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Please enter a project name.");+ expect(routerPush).not.toHaveBeenCalled();+ });++ it("URL-encodes the slug returned from the server action", async () => {+ createProjectForOnboardingAction.mockResolvedValue({+ ok: true,+ data: { slug: "weird slug/with chars", display_name: "Weird" },+ });+ render(<OnboardingFlow />);+ fireEvent.change(screen.getByLabelText(/Name/i), {+ target: { value: "Weird" },+ });+ fireEvent.click(screen.getByRole("button", { name: /Continue/i }));+ await waitFor(() =>+ expect(routerPush).toHaveBeenCalledWith(+ `/onboarding?step=connect&slug=${encodeURIComponent("weird slug/with chars")}`,+ ),+ );+ });+});++describe("OnboardingFlow — MissingSlug", () => {+ it("renders the missing-slug card when step=connect but no slug", () => {+ setStep("connect", null);+ render(<OnboardingFlow />);+ expect(+ screen.getByText(/This step needs a project. Start from the beginning./i),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Start over/i }),+ ).toHaveAttribute("href", "/onboarding");+ });++ it("renders the missing-slug card when step=account but no slug", () => {+ setStep("account", null);+ render(<OnboardingFlow />);+ expect(+ screen.getByText(/This step needs a project. Start from the beginning./i),+ ).toBeInTheDocument();+ });+});++describe("OnboardingFlow — ConnectStep", () => {+ it("renders the connect headline + Connect/Skip buttons", () => {+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ expect(+ screen.getByRole("heading", { name: /Connect your Google Ads/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Connect Google Ads/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Skip Google Ads/i }),+ ).toBeInTheDocument();+ });++ it("calls startMcpConnect with the onboarding return_to and redirects on success", async () => {+ const loc = setLocationHref();+ startMcpConnect.mockResolvedValue({+ ok: true,+ authorize_url: "https://issuer.example/oauth",+ });+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ fireEvent.click(screen.getByRole("button", { name: /Connect Google Ads/i }));+ await waitFor(() =>+ expect(startMcpConnect).toHaveBeenCalledWith({+ mcp_key: "notfair-googleads",+ return_to: "/onboarding?step=account&slug=acme",+ }),+ );+ await waitFor(() =>+ expect(loc.href).toBe("https://issuer.example/oauth"),+ );+ });++ it("toasts and re-enables the button when startMcpConnect returns ok=false", async () => {+ startMcpConnect.mockResolvedValue({ ok: false, error: "registration failed" });+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ const btn = screen.getByRole("button", { name: /Connect Google Ads/i });+ fireEvent.click(btn);+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("registration failed"),+ );+ expect(btn).not.toBeDisabled();+ });++ it("toasts the thrown error when startMcpConnect throws", async () => {+ startMcpConnect.mockRejectedValue(new Error("offline"));+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ fireEvent.click(screen.getByRole("button", { name: /Connect Google Ads/i }));+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("offline"),+ );+ });++ it("pushes the CMO tasks URL when the user clicks Skip", () => {+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ fireEvent.click(screen.getByRole("button", { name: /Skip Google Ads/i }));+ expect(routerPush).toHaveBeenCalledWith("/acme/agents/cmo/tasks");+ });+});++describe("OnboardingFlow — AccountStep", () => {+ it("shows a loading card while listGoogleAdsAccounts is pending", () => {+ listGoogleAdsAccounts.mockReturnValue(new Promise(() => {}));+ setStep("account", "acme");+ render(<OnboardingFlow />);+ expect(+ screen.getByText(/Loading your Google Ads accounts/i),+ ).toBeInTheDocument();+ });++ it("renders an error card with retry + skip when listGoogleAdsAccounts fails", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: false,+ kind: "rpc",+ error: "HTTP 500",+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ expect(+ await screen.findByText(/Couldn.t load your Google Ads accounts/i),+ ).toBeInTheDocument();+ expect(screen.getByText(/HTTP 500/)).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Retry from start/i }),+ ).toHaveAttribute("href", "/onboarding");+ expect(+ screen.getByRole("link", { name: /Skip to chat/i }),+ ).toHaveAttribute("href", "/acme/agents/cmo/chat");+ });++ it("renders the no-accounts state with reconnect link when the list is empty", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [],+ default_account_id: null,+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ expect(+ await screen.findByText(/No Google Ads accounts found/i),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Reconnect/i }),+ ).toHaveAttribute(+ "href",+ "/onboarding?step=connect&slug=acme",+ );+ });++ it("auto-selects the only account and replaces the URL with the task display id", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [{ id: "123-456-7890", name: "Solo Account" }],+ default_account_id: "123-456-7890",+ });+ setOnboardingAccountAction.mockResolvedValue({+ ok: true,+ project: {},+ task_display_id: "AUDIT-1",+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ await waitFor(() =>+ expect(setOnboardingAccountAction).toHaveBeenCalledWith("acme", "123-456-7890"),+ );+ await waitFor(() =>+ expect(routerReplace).toHaveBeenCalledWith(+ "/acme/agents/cmo/tasks?task=AUDIT-1",+ ),+ );+ });++ it("falls back to the error state when auto-select setOnboardingAccountAction fails", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [{ id: "1", name: "Solo" }],+ default_account_id: null,+ });+ setOnboardingAccountAction.mockResolvedValue({+ ok: false,+ error: "permission denied",+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ expect(+ await screen.findByText(/Couldn.t load your Google Ads accounts/i),+ ).toBeInTheDocument();+ expect(toastFns.error).toHaveBeenCalledWith("permission denied");+ });++ it("renders the picker with a 'default' badge when multiple accounts are returned", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [+ { id: "111", name: "Alpha" },+ { id: "222", name: "Bravo" },+ ],+ default_account_id: "222",+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ expect(+ await screen.findByRole("heading", { name: /Which Google Ads account/i }),+ ).toBeInTheDocument();+ expect(screen.getByText("Alpha")).toBeInTheDocument();+ expect(screen.getByText("Bravo")).toBeInTheDocument();+ expect(screen.getByText("default")).toBeInTheDocument();+ expect(screen.getByText(/Customer ID 111/)).toBeInTheDocument();+ expect(screen.getByText(/Customer ID 222/)).toBeInTheDocument();+ });++ it("picks the chosen account and replaces the URL with the task display id", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [+ { id: "111", name: "Alpha" },+ { id: "222", name: "Bravo" },+ ],+ default_account_id: null,+ });+ setOnboardingAccountAction.mockResolvedValue({+ ok: true,+ project: {},+ task_display_id: "TASK-9",+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ const alphaBtn = await screen.findByRole("button", {+ name: /Audit Alpha \(111\)/,+ });+ fireEvent.click(alphaBtn);+ await waitFor(() =>+ expect(setOnboardingAccountAction).toHaveBeenCalledWith("acme", "111"),+ );+ await waitFor(() =>+ expect(routerReplace).toHaveBeenCalledWith(+ "/acme/agents/cmo/tasks?task=TASK-9",+ ),+ );+ });++ it("toasts and re-enables the pick buttons when setOnboardingAccountAction returns ok=false", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [+ { id: "111", name: "Alpha" },+ { id: "222", name: "Bravo" },+ ],+ default_account_id: null,+ });+ setOnboardingAccountAction.mockResolvedValue({+ ok: false,+ error: "boom",+ });+ setStep("account", "acme");+ render(<OnboardingFlow />);+ const alphaBtn = await screen.findByRole("button", {+ name: /Audit Alpha/,+ });+ fireEvent.click(alphaBtn);+ await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("boom"));+ expect(alphaBtn).not.toBeDisabled();+ });++ it("toasts the thrown error when onPick throws", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [+ { id: "111", name: "Alpha" },+ { id: "222", name: "Bravo" },+ ],+ default_account_id: null,+ });+ setOnboardingAccountAction.mockRejectedValue(new Error("network"));+ setStep("account", "acme");+ render(<OnboardingFlow />);+ const alphaBtn = await screen.findByRole("button", {+ name: /Audit Alpha/,+ });+ fireEvent.click(alphaBtn);+ await waitFor(() => expect(toastFns.error).toHaveBeenCalledWith("network"));+ });++ it("disables all picker buttons while one selection is in flight", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [+ { id: "111", name: "Alpha" },+ { id: "222", name: "Bravo" },+ ],+ default_account_id: null,+ });+ let resolve: (v: { ok: true; project: object; task_display_id: string }) => void = () => {};+ setOnboardingAccountAction.mockImplementation(+ () =>+ new Promise<{ ok: true; project: object; task_display_id: string }>(+ (res) => {+ resolve = res;+ },+ ),+ );+ setStep("account", "acme");+ render(<OnboardingFlow />);+ const alphaBtn = await screen.findByRole("button", {+ name: /Audit Alpha/,+ });+ const bravoBtn = screen.getByRole("button", { name: /Audit Bravo/ });+ fireEvent.click(alphaBtn);+ await waitFor(() => expect(alphaBtn).toBeDisabled());+ expect(bravoBtn).toBeDisabled();+ act(() => {+ resolve({ ok: true, project: {}, task_display_id: "TASK-1" });+ });+ });++ it("renders the auto-select loading card when exactly one account exists", async () => {+ listGoogleAdsAccounts.mockResolvedValue({+ ok: true,+ accounts: [{ id: "1", name: "Solo" }],+ default_account_id: null,+ });+ // setOnboardingAccountAction never resolves: keeps the auto-select card visible.+ setOnboardingAccountAction.mockReturnValue(new Promise(() => {}));+ setStep("account", "acme");+ render(<OnboardingFlow />);+ expect(+ await screen.findByText(/Using your only Google Ads account/i),+ ).toBeInTheDocument();+ });+});diff --git a/src/components/paired-openclaw-pill.test.tsx b/src/components/paired-openclaw-pill.test.tsxnew file mode 100644index 00000000..c58170c2--- /dev/null+++ b/src/components/paired-openclaw-pill.test.tsx@@ -0,0 +1,69 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";++const discoverGateway = vi.fn();++vi.mock("@/server/openclaw/gateway-client", () => ({+ discoverGateway: () => discoverGateway(),+}));++import { PairedOpenclawPill } from "./paired-openclaw-pill";++afterEach(() => cleanup());++beforeEach(() => {+ discoverGateway.mockReset();+});++describe("PairedOpenclawPill", () => {+ it("renders the pill linking to the dashboard with a token fragment when the gateway is paired", () => {+ discoverGateway.mockReturnValue({+ url: "ws://127.0.0.1:7788",+ token: "secret/token+abc",+ configFile: "/tmp/openclaw.json",+ });+ render(<PairedOpenclawPill />);+ const link = screen.getByRole("link");+ expect(link).toBeInTheDocument();+ expect(link).toHaveAttribute(+ "href",+ `http://127.0.0.1:7788/#token=${encodeURIComponent("secret/token+abc")}`,+ );+ expect(link).toHaveAttribute("target", "_blank");+ expect(link).toHaveAttribute("rel", "noopener noreferrer");+ expect(link).toHaveAttribute("title", "Open OpenClaw dashboard");+ expect(screen.getByText("Paired OpenClaw")).toBeInTheDocument();+ });++ it("rewrites a wss:// gateway url to https:// for the dashboard link", () => {+ discoverGateway.mockReturnValue({+ url: "wss://gateway.example:8443",+ token: "t",+ configFile: "/tmp/openclaw.json",+ });+ render(<PairedOpenclawPill />);+ const link = screen.getByRole("link");+ expect(link.getAttribute("href")).toMatch(/^https:\/\/gateway\.example:8443\/#token=t$/);+ });++ it("omits the token fragment when the gateway has no token", () => {+ discoverGateway.mockReturnValue({+ url: "ws://127.0.0.1:7788",+ configFile: "/tmp/openclaw.json",+ });+ render(<PairedOpenclawPill />);+ const link = screen.getByRole("link");+ expect(link).toHaveAttribute("href", "http://127.0.0.1:7788/");+ expect(link.getAttribute("href")).not.toContain("#token=");+ });++ it("renders nothing when discoverGateway throws (no OpenClaw config)", () => {+ discoverGateway.mockImplementation(() => {+ throw new Error("config not found");+ });+ const { container } = render(<PairedOpenclawPill />);+ expect(container.firstChild).toBeNull();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ });+});diff --git a/src/components/project-cookie-sync.test.tsx b/src/components/project-cookie-sync.test.tsxnew file mode 100644index 00000000..ba245bf1--- /dev/null+++ b/src/components/project-cookie-sync.test.tsx@@ -0,0 +1,47 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, cleanup } from "@testing-library/react";++const switchProjectAction = vi.fn();++vi.mock("@/server/actions/projects", () => ({+ switchProjectAction: (...args: unknown[]) => switchProjectAction(...args),+}));++import { ProjectCookieSync } from "./project-cookie-sync";++beforeEach(() => {+ switchProjectAction.mockReset();+ switchProjectAction.mockResolvedValue({ ok: true });+});++afterEach(() => {+ cleanup();+});++describe("ProjectCookieSync", () => {+ it("calls switchProjectAction with the slug on first mount", () => {+ render(<ProjectCookieSync slug="alpha" />);+ expect(switchProjectAction).toHaveBeenCalledTimes(1);+ expect(switchProjectAction).toHaveBeenCalledWith("alpha");+ });++ it("renders nothing visible", () => {+ const { container } = render(<ProjectCookieSync slug="alpha" />);+ expect(container.firstChild).toBeNull();+ });++ it("does not re-fire when the same slug is re-rendered", () => {+ const { rerender } = render(<ProjectCookieSync slug="alpha" />);+ expect(switchProjectAction).toHaveBeenCalledTimes(1);+ rerender(<ProjectCookieSync slug="alpha" />);+ expect(switchProjectAction).toHaveBeenCalledTimes(1);+ });++ it("fires again when the slug changes", () => {+ const { rerender } = render(<ProjectCookieSync slug="alpha" />);+ rerender(<ProjectCookieSync slug="beta" />);+ expect(switchProjectAction).toHaveBeenCalledTimes(2);+ expect(switchProjectAction).toHaveBeenLastCalledWith("beta");+ });+});diff --git a/src/components/project-rename-card.test.tsx b/src/components/project-rename-card.test.tsxnew file mode 100644index 00000000..5f768eec--- /dev/null+++ b/src/components/project-rename-card.test.tsx@@ -0,0 +1,142 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const router = {+ push: vi.fn(),+ refresh: vi.fn(),+};+const renameProjectFullAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("next/navigation", () => ({+ useRouter: () => router,+}));++vi.mock("@/server/actions/projects", () => ({+ renameProjectFullAction: (...args: unknown[]) => renameProjectFullAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++import { ProjectRenameCard } from "./project-rename-card";++beforeEach(() => {+ router.refresh.mockReset();+ router.push.mockReset();+ renameProjectFullAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("ProjectRenameCard", () => {+ it("seeds the input with the current display name", () => {+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ expect(screen.getByLabelText(/display name/i)).toHaveValue("Alpha");+ });++ it("disables Save when name is unchanged", () => {+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ expect(screen.getByRole("button", { name: /save name/i })).toBeDisabled();+ });++ it("flips the button to 'Rename project' when the slug changes", () => {+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "Bravo" } });+ expect(+ screen.getByRole("button", { name: /rename project/i }),+ ).toBeInTheDocument();+ expect(screen.getByText(/slug changes from/i)).toBeInTheDocument();+ });++ it("shows invalid-name error and disables save on bad input", () => {+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "@@@" } });+ expect(screen.getByText(/invalid name/i)).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /save name|rename project/i }),+ ).toBeDisabled();+ });++ it("calls renameProjectFullAction and toasts on partial-success (failures present)", async () => {+ renameProjectFullAction.mockResolvedValue({+ ok: true,+ data: {+ full_rename: true,+ display_name: "Bravo",+ agents_relocated: ["a", "b"],+ agents_failed: ["c"],+ },+ });+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "Bravo" } });+ fireEvent.click(screen.getByRole("button", { name: /rename project/i }));+ await waitFor(() =>+ expect(renameProjectFullAction).toHaveBeenCalledWith({+ current_slug: "alpha",+ new_display_name: "Bravo",+ }),+ );+ await waitFor(() =>+ expect(toast.success.mock.calls[0][0]).toMatch(/2 agents moved, 1 failed/),+ );+ await waitFor(() => expect(router.refresh).toHaveBeenCalled());+ });++ it("toasts a clean success when no agents failed", async () => {+ renameProjectFullAction.mockResolvedValue({+ ok: true,+ data: {+ full_rename: true,+ display_name: "Bravo",+ agents_relocated: ["a"],+ agents_failed: [],+ },+ });+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "Bravo" } });+ fireEvent.click(screen.getByRole("button", { name: /rename project/i }));+ await waitFor(() =>+ expect(toast.success.mock.calls[0][0]).toMatch(/1 agents moved/),+ );+ });++ it("uses the display-name-only success toast when full_rename is false", async () => {+ renameProjectFullAction.mockResolvedValue({+ ok: true,+ data: { full_rename: false, display_name: "ALPHA" },+ });+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "ALPHA" } });+ fireEvent.click(screen.getByRole("button", { name: /save name/i }));+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith('Renamed to "ALPHA"'),+ );+ });++ it("toasts the server error when rename fails", async () => {+ renameProjectFullAction.mockResolvedValue({ ok: false, error: "boom" });+ render(<ProjectRenameCard currentSlug="alpha" currentDisplayName="Alpha" />);+ const input = screen.getByLabelText(/display name/i);+ fireEvent.change(input, { target: { value: "Bravo" } });+ fireEvent.click(screen.getByRole("button", { name: /rename project/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("boom"));+ });+});diff --git a/src/components/project-switcher.test.tsx b/src/components/project-switcher.test.tsxnew file mode 100644index 00000000..eafbaf09--- /dev/null+++ b/src/components/project-switcher.test.tsx@@ -0,0 +1,132 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const pathnameRef: { current: string } = { current: "/proj-a/agents/cmo/tasks" };+const router = {+ push: vi.fn(),+ refresh: vi.fn(),+};++vi.mock("next/navigation", () => ({+ useRouter: () => router,+ usePathname: () => pathnameRef.current,+}));++const switchProjectAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("@/server/actions/projects", () => ({+ switchProjectAction: (...args: unknown[]) => switchProjectAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++vi.mock("@/components/ui/sidebar", () => ({+ SidebarMenuButton: ({ children, ...rest }: { children: React.ReactNode }) => (+ <button type="button" {...rest}>+ {children}+ </button>+ ),+}));++import { ProjectSwitcher } from "./project-switcher";++function openMenu() {+ const trigger = screen.getByRole("button");+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });+ fireEvent.click(trigger);+}++const projects = [+ { id: "1", slug: "proj-a", display_name: "Alpha", created_at: "", archived_at: null, google_ads_account_id: null },+ { id: "2", slug: "proj-b", display_name: "Beta", created_at: "", archived_at: null, google_ads_account_id: null },+];++beforeEach(() => {+ switchProjectAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+ router.push.mockReset();+ router.refresh.mockReset();+ pathnameRef.current = "/proj-a/agents/cmo/tasks";+});++afterEach(() => {+ cleanup();+});++describe("ProjectSwitcher", () => {+ it("shows the active project display name and slug", () => {+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ expect(screen.getByText("Alpha")).toBeInTheDocument();+ expect(screen.getByText("proj-a")).toBeInTheDocument();+ });++ it("falls back to placeholder text when no project is active", () => {+ render(<ProjectSwitcher projects={[]} activeSlug={null} />);+ expect(screen.getByText("No project")).toBeInTheDocument();+ expect(screen.getByText("Create one to get started")).toBeInTheDocument();+ });++ it("shows the project initials in the avatar", () => {+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ expect(screen.getAllByText("AL").length).toBeGreaterThan(0);+ });++ it("renders a 'New project' link to /onboarding", () => {+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ openMenu();+ expect(screen.getByText("New project")).toBeInTheDocument();+ });++ it("opens the menu and lists all projects", () => {+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ openMenu();+ expect(screen.getAllByText("Alpha").length).toBeGreaterThan(0);+ expect(screen.getByText("Beta")).toBeInTheDocument();+ });++ it("switches projects when picking a non-active item", async () => {+ switchProjectAction.mockResolvedValue({ ok: true });+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ openMenu();+ fireEvent.click(screen.getByText("Beta"));+ await waitFor(() => expect(switchProjectAction).toHaveBeenCalledWith("proj-b"));+ await waitFor(() =>+ expect(router.push).toHaveBeenCalledWith("/proj-b/agents/cmo/tasks"),+ );+ });++ it("does not call switchProject when picking the active project", () => {+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ openMenu();+ const items = screen.getAllByText("Alpha");+ const item = items[items.length - 1];+ fireEvent.click(item);+ expect(switchProjectAction).not.toHaveBeenCalled();+ });++ it("toasts the error when switchProjectAction fails", async () => {+ switchProjectAction.mockResolvedValue({ ok: false, error: "nope" });+ render(<ProjectSwitcher projects={projects} activeSlug="proj-a" />);+ openMenu();+ fireEvent.click(screen.getByText("Beta"));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("nope"));+ expect(router.push).not.toHaveBeenCalled();+ });++ it("shows 'No projects yet' when projects list is empty", () => {+ render(<ProjectSwitcher projects={[]} activeSlug={null} />);+ openMenu();+ expect(screen.getByText("No projects yet")).toBeInTheDocument();+ });+});diff --git a/src/components/reprovision-button.test.tsx b/src/components/reprovision-button.test.tsxnew file mode 100644index 00000000..2a146e64--- /dev/null+++ b/src/components/reprovision-button.test.tsx@@ -0,0 +1,112 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const { toastFns } = vi.hoisted(() => ({+ toastFns: {+ success: vi.fn(),+ error: vi.fn(),+ },+}));++vi.mock("sonner", () => ({+ toast: toastFns,+}));++import { ReprovisionButton } from "./reprovision-button";++beforeEach(() => {+ toastFns.success.mockReset();+ toastFns.error.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("ReprovisionButton", () => {+ it("renders the idle label by default", () => {+ const action = vi.fn();+ render(<ReprovisionButton action={action} />);+ expect(+ screen.getByRole("button", { name: /reprovision agents/i }),+ ).toBeInTheDocument();+ expect(screen.queryByText(/provisioning/i)).not.toBeInTheDocument();+ });++ it("toasts a success message when new agents are provisioned", async () => {+ const action = vi.fn().mockResolvedValue({+ ok: true,+ created: ["cmo", "google_ads"],+ existed: [],+ });+ render(<ReprovisionButton action={action} />);+ fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));+ await waitFor(() =>+ expect(toastFns.success).toHaveBeenCalledWith("Provisioned 2 new agents."),+ );+ expect(toastFns.error).not.toHaveBeenCalled();+ });++ it("uses singular agent in success copy when exactly one is created", async () => {+ const action = vi.fn().mockResolvedValue({+ ok: true,+ created: ["cmo"],+ existed: [],+ });+ render(<ReprovisionButton action={action} />);+ fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));+ await waitFor(() =>+ expect(toastFns.success).toHaveBeenCalledWith("Provisioned 1 new agent."),+ );+ });++ it("toasts a no-op message when all agents already exist", async () => {+ const action = vi.fn().mockResolvedValue({+ ok: true,+ created: [],+ existed: ["cmo", "google_ads"],+ });+ render(<ReprovisionButton action={action} />);+ fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));+ await waitFor(() =>+ expect(toastFns.success).toHaveBeenCalledWith("All 2 agents already exist."),+ );+ });++ it("toasts the server error when action returns ok=false", async () => {+ const action = vi+ .fn()+ .mockResolvedValue({ ok: false, error: "openclaw exploded" });+ render(<ReprovisionButton action={action} />);+ fireEvent.click(screen.getByRole("button", { name: /reprovision agents/i }));+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("openclaw exploded"),+ );+ expect(toastFns.success).not.toHaveBeenCalled();+ });++ it("disables the button and swaps the label while the transition is pending", async () => {+ let resolveAction: (v: { ok: true; created: string[]; existed: string[] }) => void = () => {};+ const action = vi.fn(+ () =>+ new Promise<{ ok: true; created: string[]; existed: string[] }>((resolve) => {+ resolveAction = resolve;+ }),+ );+ render(<ReprovisionButton action={action} />);+ const button = screen.getByRole("button", { name: /reprovision agents/i });+ fireEvent.click(button);+ await waitFor(() => {+ expect(+ screen.getByRole("button", { name: /provisioning/i }),+ ).toBeDisabled();+ });+ resolveAction({ ok: true, created: [], existed: [] });+ await waitFor(() =>+ expect(+ screen.getByRole("button", { name: /reprovision agents/i }),+ ).not.toBeDisabled(),+ );+ });+});diff --git a/src/components/running-dot.test.tsx b/src/components/running-dot.test.tsxnew file mode 100644index 00000000..3bc5ac61--- /dev/null+++ b/src/components/running-dot.test.tsx@@ -0,0 +1,53 @@+// @vitest-environment jsdom+import { afterEach, describe, it, expect } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";++import { RunningDot } from "./running-dot";++afterEach(() => cleanup());++describe("RunningDot", () => {+ it("renders a status role with the default 'Running' aria-label", () => {+ render(<RunningDot />);+ const status = screen.getByRole("status");+ expect(status).toBeInTheDocument();+ expect(status).toHaveAccessibleName("Running");+ });++ it("uses the small sizing class by default", () => {+ render(<RunningDot />);+ const status = screen.getByRole("status");+ expect(status.className).toMatch(/\bh-2\b/);+ expect(status.className).toMatch(/\bw-2\b/);+ expect(status.className).not.toMatch(/h-2\.5/);+ });++ it("uses the larger sizing class when size='md'", () => {+ render(<RunningDot size="md" />);+ const status = screen.getByRole("status");+ expect(status.className).toMatch(/h-2\.5/);+ expect(status.className).toMatch(/w-2\.5/);+ });++ it("forwards a caller-supplied className alongside the size classes", () => {+ render(<RunningDot className="extra-thing" />);+ const status = screen.getByRole("status");+ expect(status.className).toMatch(/extra-thing/);+ expect(status.className).toMatch(/inline-flex/);+ });++ it("overrides the aria-label when one is supplied", () => {+ render(<RunningDot aria-label="Task in flight" />);+ expect(screen.getByRole("status")).toHaveAccessibleName("Task in flight");+ });++ it("includes the pulsing ping layer underneath the solid dot", () => {+ const { container } = render(<RunningDot />);+ const inner = container.querySelectorAll("span span");+ expect(inner.length).toBe(2);+ const [ping, solid] = inner;+ expect(ping.className).toMatch(/animate-ping/);+ expect(ping.className).toMatch(/bg-sky-400/);+ expect(solid.className).toMatch(/bg-sky-500/);+ });+});diff --git a/src/components/schedule-cron-dialog.test.tsx b/src/components/schedule-cron-dialog.test.tsxnew file mode 100644index 00000000..30be687a--- /dev/null+++ b/src/components/schedule-cron-dialog.test.tsx@@ -0,0 +1,207 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++if (typeof Element !== "undefined") {+ // @ts-expect-error - jsdom shim+ Element.prototype.hasPointerCapture ??= () => false;+ // @ts-expect-error - jsdom shim+ Element.prototype.setPointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.releasePointerCapture ??= () => {};+ // @ts-expect-error - jsdom shim+ Element.prototype.scrollIntoView ??= () => {};+}++const scheduleCronAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("@/server/actions/crons", () => ({+ scheduleCronAction: (...args: unknown[]) => scheduleCronAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++import { ScheduleCronDialog } from "./schedule-cron-dialog";++function openDialog() {+ const trigger = screen.getAllByRole("button").find((b) => b.textContent?.includes("New cron"));+ if (!trigger) throw new Error("Trigger not found");+ fireEvent.pointerDown(trigger, { button: 0 });+ fireEvent.click(trigger);+}++beforeEach(() => {+ scheduleCronAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => cleanup());++describe("ScheduleCronDialog", () => {+ it("renders the default 'button' trigger with 'New cron' label", () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ expect(screen.getByRole("button", { name: /new cron/i })).toBeInTheDocument();+ });++ it("renders an icon trigger with sr-only label when variant='icon'", () => {+ render(<ScheduleCronDialog projectSlug="acme" variant="icon" />);+ expect(screen.getByText(/schedule recurring work/i)).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "New cron" })).not.toBeInTheDocument();+ });++ it("opens the dialog when the trigger is clicked", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ await waitFor(() => {+ expect(screen.getByText("Schedule recurring work")).toBeInTheDocument();+ });+ expect(screen.getByLabelText(/Agent/i)).toBeInTheDocument();+ expect(screen.getByLabelText(/Name/i)).toBeInTheDocument();+ expect(screen.getByLabelText(/Brief/i)).toBeInTheDocument();+ });++ it("defaults the specialist to google_ads when no override is provided", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ const select = (await screen.findByLabelText(/Agent/i)) as HTMLSelectElement;+ expect(select.value).toBe("google_ads");+ });++ it("honors defaultSpecialist", async () => {+ render(<ScheduleCronDialog projectSlug="acme" defaultSpecialist="seo" />);+ openDialog();+ const select = (await screen.findByLabelText(/Agent/i)) as HTMLSelectElement;+ expect(select.value).toBe("seo");+ });++ it("starts with 'every 1h' schedule and no timezone input visible", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ const scheduleInput = (await screen.findByPlaceholderText("1h")) as HTMLInputElement;+ expect(scheduleInput.value).toBe("1h");+ expect(screen.queryByPlaceholderText(/Timezone/i)).not.toBeInTheDocument();+ });++ it("shows the timezone input when schedule kind switches to 'cron'", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ const kindSelect = (await screen.findByDisplayValue("Every")) as HTMLSelectElement;+ fireEvent.change(kindSelect, { target: { value: "cron" } });+ expect(screen.getByPlaceholderText(/Timezone/i)).toBeInTheDocument();+ });++ it("disables the Schedule button until name and brief are filled", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ const submit = await screen.findByRole("button", { name: /^schedule$/i });+ expect(submit).toBeDisabled();+ fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: "daily-opt" } });+ expect(submit).toBeDisabled();+ fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "do the thing" } });+ expect(submit).not.toBeDisabled();+ });++ it("treats whitespace-only name and brief as empty (still disabled)", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: " " } });+ fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: " " } });+ const submit = await screen.findByRole("button", { name: /^schedule$/i });+ expect(submit).toBeDisabled();+ });++ it("submits with current 'every' values and toasts success on ok", async () => {+ scheduleCronAction.mockResolvedValue({ ok: true, cron_id: "c1", cron_name: "acme-google_ads-daily-opt" });+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ fireEvent.change(await screen.findByLabelText(/Name/i), { target: { value: "daily-opt" } });+ fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "do the thing" } });+ fireEvent.click(screen.getByRole("button", { name: /^schedule$/i }));+ await waitFor(() =>+ expect(scheduleCronAction).toHaveBeenCalledWith({+ project_slug: "acme",+ specialist: "google_ads",+ name: "daily-opt",+ schedule_kind: "every",+ schedule_value: "1h",+ tz: undefined,+ brief: "do the thing",+ }),+ );+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith("Scheduled acme-google_ads-daily-opt"),+ );+ });++ it("includes tz only when schedule_kind is 'cron'", async () => {+ scheduleCronAction.mockResolvedValue({ ok: true, cron_id: "c1", cron_name: "x" });+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ const kindSelect = (await screen.findByDisplayValue("Every")) as HTMLSelectElement;+ fireEvent.change(kindSelect, { target: { value: "cron" } });+ fireEvent.change(screen.getByLabelText(/Name/i), { target: { value: "cron-job" } });+ fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "tick" } });+ fireEvent.change(screen.getAllByDisplayValue("1h")[0]!, { target: { value: "0 9 * * *" } });+ fireEvent.change(screen.getByPlaceholderText(/Timezone/i), {+ target: { value: "America/New_York" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^schedule$/i }));+ await waitFor(() =>+ expect(scheduleCronAction).toHaveBeenCalledWith(+ expect.objectContaining({+ schedule_kind: "cron",+ schedule_value: "0 9 * * *",+ tz: "America/New_York",+ }),+ ),+ );+ });++ it("toasts the server error when the action returns ok=false and keeps the dialog open", async () => {+ scheduleCronAction.mockResolvedValue({ ok: false, error: "invalid cron" });+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ fireEvent.change(await screen.findByLabelText(/Name/i), { target: { value: "x" } });+ fireEvent.change(screen.getByLabelText(/Brief/i), { target: { value: "y" } });+ fireEvent.click(screen.getByRole("button", { name: /^schedule$/i }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("invalid cron"));+ expect(toast.success).not.toHaveBeenCalled();+ // Dialog still visible+ expect(screen.getByText("Schedule recurring work")).toBeInTheDocument();+ });++ it("Cancel button closes the dialog without invoking the action", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ fireEvent.click(await screen.findByRole("button", { name: /cancel/i }));+ expect(scheduleCronAction).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(screen.queryByText("Schedule recurring work")).not.toBeInTheDocument(),+ );+ });++ it("preset menu items apply their schedule kind, value, and timezone", async () => {+ render(<ScheduleCronDialog projectSlug="acme" />);+ openDialog();+ const presetsBtn = await screen.findByRole("button", { name: /presets/i });+ fireEvent.pointerDown(presetsBtn, { button: 0 });+ fireEvent.click(presetsBtn);+ const preset = await screen.findByText("Daily at 9am (Los Angeles)");+ fireEvent.click(preset);+ // schedule kind select should now be "cron" (i.e. show "Cron expr")+ const kindSelect = screen.getByDisplayValue("Cron expr") as HTMLSelectElement;+ expect(kindSelect.value).toBe("cron");+ expect(screen.getByDisplayValue("0 9 * * *")).toBeInTheDocument();+ expect(screen.getByDisplayValue("America/Los_Angeles")).toBeInTheDocument();+ });+});diff --git a/src/components/skills-list.test.tsx b/src/components/skills-list.test.tsxnew file mode 100644index 00000000..60ffe65d--- /dev/null+++ b/src/components/skills-list.test.tsx@@ -0,0 +1,165 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";++const setSkillEnabledAction = vi.fn();+const toast = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("@/server/actions/skills", () => ({+ setSkillEnabledAction: (...args: unknown[]) => setSkillEnabledAction(...args),+}));++vi.mock("sonner", () => ({+ toast: {+ success: (...args: unknown[]) => toast.success(...args),+ error: (...args: unknown[]) => toast.error(...args),+ },+}));++import { SkillsList } from "./skills-list";++type Skill = Parameters<typeof SkillsList>[0]["skills"][number];++function skill(over: Partial<Skill> = {}): Skill {+ return {+ name: "test-skill",+ description: "A test skill",+ source: "user",+ bundled: false,+ filePath: "/x",+ baseDir: "/x",+ skillKey: "test-skill",+ emoji: "🧪",+ always: false,+ disabled: false,+ eligible: true,+ blockedByAllowlist: false,+ blockedByAgentFilter: false,+ userInvocable: true,+ commandVisible: true,+ ...over,+ } as Skill;+}++const skills: Skill[] = [+ skill({ skillKey: "enabled-a", name: "enabled-a", disabled: false }),+ skill({ skillKey: "enabled-b", name: "enabled-b", disabled: false, bundled: true }),+ skill({ skillKey: "disabled-a", name: "disabled-a", disabled: true }),+ skill({+ skillKey: "init",+ name: "init",+ always: true,+ disabled: false,+ }),+ skill({+ skillKey: "needs-setup",+ name: "needs-setup",+ disabled: false,+ eligible: false,+ }),+];++beforeEach(() => {+ setSkillEnabledAction.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("SkillsList", () => {+ it("renders one row per skill in the 'all' filter (default)", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ for (const s of skills) {+ expect(screen.getByText(s.name)).toBeInTheDocument();+ }+ });++ it("shows filter tabs with per-bucket counts", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ expect(screen.getByRole("tab", { name: /All\s*5/i })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Enabled\s*4/i })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Disabled\s*1/i })).toBeInTheDocument();+ });++ it("narrows to enabled skills when the Enabled tab is clicked", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ fireEvent.click(screen.getByRole("tab", { name: /Enabled\s*4/i }));+ expect(screen.queryByText("disabled-a")).not.toBeInTheDocument();+ expect(screen.getByText("enabled-a")).toBeInTheDocument();+ });++ it("narrows to disabled skills when the Disabled tab is clicked", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ fireEvent.click(screen.getByRole("tab", { name: /Disabled\s*1/i }));+ expect(screen.getByText("disabled-a")).toBeInTheDocument();+ expect(screen.queryByText("enabled-a")).not.toBeInTheDocument();+ });++ it("shows the empty-state when a filter yields no skills", () => {+ render(<SkillsList skills={[]} agentSlug="cmo" />);+ expect(screen.getByText(/no skills match this filter/i)).toBeInTheDocument();+ });++ it("renders the 'bundled' badge on bundled skills", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ expect(screen.getByText("bundled")).toBeInTheDocument();+ });++ it("renders the 'always-on' badge and disables the toggle on always skills", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ expect(screen.getByText("always-on")).toBeInTheDocument();+ const row = screen.getByText("init").closest("li");+ const btn = row?.querySelector("button");+ expect(btn).toBeDisabled();+ });++ it("renders the 'needs setup' badge when enabled but not eligible", () => {+ render(<SkillsList skills={skills} agentSlug="cmo" />);+ expect(screen.getByText("needs setup")).toBeInTheDocument();+ });++ it("toggles a skill off when the user clicks Enabled and toasts success", async () => {+ setSkillEnabledAction.mockResolvedValue({ ok: true });+ render(<SkillsList skills={[skill({ skillKey: "k", name: "k" })]} agentSlug="cmo" />);+ const btn = screen.getByRole("button", { name: /enabled/i });+ fireEvent.click(btn);+ await waitFor(() =>+ expect(setSkillEnabledAction).toHaveBeenCalledWith("k", false, "cmo"),+ );+ await waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith("Disabled k"),+ );+ });++ it("toggles a disabled skill on and toasts success", async () => {+ setSkillEnabledAction.mockResolvedValue({ ok: true });+ render(+ <SkillsList+ skills={[skill({ skillKey: "k", name: "k", disabled: true })]}+ agentSlug="cmo"+ />,+ );+ const btn = screen.getByRole("button", { name: /enable/i });+ fireEvent.click(btn);+ await waitFor(() =>+ expect(setSkillEnabledAction).toHaveBeenCalledWith("k", true, "cmo"),+ );+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith("Enabled k"));+ });++ it("reverts the optimistic state and toasts an error on failure", async () => {+ setSkillEnabledAction.mockResolvedValue({ ok: false, error: "no" });+ render(<SkillsList skills={[skill({ skillKey: "k", name: "k" })]} agentSlug="cmo" />);+ const btn = screen.getByRole("button", { name: /enabled/i });+ fireEvent.click(btn);+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith("no"));+ // After revert: still in the "Enabled" visual state.+ expect(screen.getByRole("button", { name: /enabled/i })).toBeInTheDocument();+ });+});diff --git a/src/components/slash-command-popover.test.tsx b/src/components/slash-command-popover.test.tsxnew file mode 100644index 00000000..9d4116f2--- /dev/null+++ b/src/components/slash-command-popover.test.tsx@@ -0,0 +1,162 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";++import { SlashCommandPopover } from "./slash-command-popover";+import {+ SLASH_COMMANDS,+ filterSlashCommands,+ type SlashCommand,+} from "@/lib/slash-commands";++// jsdom doesn't implement scrollIntoView; the popover calls it on every render.+beforeEach(() => {+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ writable: true,+ value: vi.fn(),+ });+});++describe("SlashCommandPopover", () => {+ it("renders the empty state when no commands match", () => {+ render(+ <SlashCommandPopover+ commands={[]}+ selectedIndex={0}+ onSelect={() => {}}+ onHover={() => {}}+ />,+ );+ expect(screen.getByText("No matching slash commands.")).toBeInTheDocument();+ // Empty-state container is still a listbox.+ const empty = screen.getByRole("listbox", { name: "Slash commands" });+ expect(empty).toBeInTheDocument();+ });++ it("renders every command name with category label", () => {+ render(+ <SlashCommandPopover+ commands={SLASH_COMMANDS}+ selectedIndex={0}+ onSelect={() => {}}+ onHover={() => {}}+ />,+ );+ expect(screen.getByRole("listbox", { name: "Slash commands" })).toBeInTheDocument();+ // Each command shows up as an option with its `/name` displayed.+ for (const cmd of SLASH_COMMANDS) {+ const matches = screen.getAllByText((_, node) => {+ if (!node) return false;+ return node.tagName === "SPAN" && node.textContent?.startsWith(`/${cmd.name}`) === true;+ });+ expect(matches.length).toBeGreaterThan(0);+ }+ // Category labels are surfaced.+ expect(screen.getAllByText("Session").length).toBeGreaterThan(0);+ expect(screen.getAllByText("Model").length).toBeGreaterThan(0);+ });++ it("marks the selected row with aria-selected and styles it active", () => {+ render(+ <SlashCommandPopover+ commands={SLASH_COMMANDS.slice(0, 3)}+ selectedIndex={1}+ onSelect={() => {}}+ onHover={() => {}}+ />,+ );+ const options = screen.getAllByRole("option");+ expect(options).toHaveLength(3);+ expect(options[0]).toHaveAttribute("aria-selected", "false");+ expect(options[1]).toHaveAttribute("aria-selected", "true");+ expect(options[1].className).toContain("bg-accent");+ });++ it("calls onSelect with the clicked command", () => {+ const onSelect = vi.fn();+ const subset: SlashCommand[] = SLASH_COMMANDS.slice(0, 2);+ render(+ <SlashCommandPopover+ commands={subset}+ selectedIndex={0}+ onSelect={onSelect}+ onHover={() => {}}+ />,+ );+ fireEvent.click(screen.getAllByRole("option")[1]);+ expect(onSelect).toHaveBeenCalledTimes(1);+ expect(onSelect).toHaveBeenCalledWith(subset[1]);+ });++ it("calls onHover with the row index on mouse enter", () => {+ const onHover = vi.fn();+ render(+ <SlashCommandPopover+ commands={SLASH_COMMANDS.slice(0, 3)}+ selectedIndex={0}+ onSelect={() => {}}+ onHover={onHover}+ />,+ );+ fireEvent.mouseEnter(screen.getAllByRole("option")[2]);+ expect(onHover).toHaveBeenCalledWith(2);+ });++ it("renders a 'local' badge for executeLocal commands and omits it otherwise", () => {+ const local = SLASH_COMMANDS.find((c) => c.executeLocal)!;+ const remote = SLASH_COMMANDS.find((c) => !c.executeLocal)!;+ render(+ <SlashCommandPopover+ commands={[local, remote]}+ selectedIndex={0}+ onSelect={() => {}}+ onHover={() => {}}+ />,+ );+ const localBadges = screen.getAllByText("local");+ expect(localBadges).toHaveLength(1);+ });++ it("shows the args hint next to commands that declare one", () => {+ const withArgs = SLASH_COMMANDS.find((c) => c.args)!;+ render(+ <SlashCommandPopover+ commands={[withArgs]}+ selectedIndex={0}+ onSelect={() => {}}+ onHover={() => {}}+ />,+ );+ expect(screen.getByText(withArgs.args!)).toBeInTheDocument();+ });++ it("filterSlashCommands prefix-matches /cl to /clear", () => {+ // Sanity-check on the filter that drives the popover.+ const filtered = filterSlashCommands("/cl");+ expect(filtered.map((c) => c.name)).toContain("clear");+ });++ it("filterSlashCommands falls back to substring match", () => {+ const filtered = filterSlashCommands("/ace"); // no prefix; substring "ace" → trace+ expect(filtered.map((c) => c.name)).toContain("trace");+ });++ it("calls scrollIntoView on the selected row after mount", () => {+ const scrollIntoView = vi.fn();+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ writable: true,+ value: scrollIntoView,+ });+ render(+ <SlashCommandPopover+ commands={SLASH_COMMANDS.slice(0, 4)}+ selectedIndex={2}+ onSelect={() => {}}+ onHover={() => {}}+ />,+ );+ expect(scrollIntoView).toHaveBeenCalled();+ });+});diff --git a/src/components/start-all-tasks-button.test.tsx b/src/components/start-all-tasks-button.test.tsxnew file mode 100644index 00000000..99ba1969--- /dev/null+++ b/src/components/start-all-tasks-button.test.tsx@@ -0,0 +1,113 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";++const refreshMock = vi.fn();+vi.mock("next/navigation", () => ({+ useRouter: () => ({ refresh: refreshMock }),+}));++const startAllMock = vi.fn();+vi.mock("@/server/actions/tasks", () => ({+ startAllProposedTasksAction: (...a: unknown[]) => startAllMock(...a),+}));++const toastErrorMock = vi.fn();+const toastSuccessMock = vi.fn();+const toastInfoMock = vi.fn();+vi.mock("sonner", () => ({+ toast: {+ error: (...a: unknown[]) => toastErrorMock(...a),+ success: (...a: unknown[]) => toastSuccessMock(...a),+ info: (...a: unknown[]) => toastInfoMock(...a),+ },+}));++import { StartAllTasksButton } from "./start-all-tasks-button";++beforeEach(() => {+ refreshMock.mockReset();+ startAllMock.mockReset();+ toastErrorMock.mockReset();+ toastSuccessMock.mockReset();+ toastInfoMock.mockReset();+});++afterEach(() => {+ vi.useRealTimers();+});++describe("StartAllTasksButton", () => {+ it("renders the count and is disabled when proposedCount is 0", () => {+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={0} />);+ const btn = screen.getByRole("button");+ expect(btn).toBeDisabled();+ expect(btn.textContent).toContain("Start all 0 tasks");+ });++ it("renders singular noun for count == 1", () => {+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={1} />);+ expect(screen.getByRole("button").textContent).toContain("Start all 1 task");+ expect(screen.getByRole("button").textContent).not.toContain("tasks");+ });++ it("renders plural noun for count > 1", () => {+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={3} />);+ expect(screen.getByRole("button").textContent).toContain("Start all 3 tasks");+ });++ it("shows an error toast when the action fails", async () => {+ startAllMock.mockResolvedValue({ ok: false, error: "no project" });+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);+ fireEvent.click(screen.getByRole("button"));+ await waitFor(() => {+ expect(toastErrorMock).toHaveBeenCalledWith("no project");+ });+ expect(refreshMock).not.toHaveBeenCalled();+ });++ it("shows an info toast and skips polling when started == 0", async () => {+ startAllMock.mockResolvedValue({ ok: true, data: { started: 0, task_ids: [] } });+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);+ fireEvent.click(screen.getByRole("button"));+ await waitFor(() => {+ expect(toastInfoMock).toHaveBeenCalledWith("No proposed tasks to start.");+ });+ expect(refreshMock).not.toHaveBeenCalled();+ });++ it("toasts singular when only one task was started", async () => {+ startAllMock.mockResolvedValue({ ok: true, data: { started: 1, task_ids: ["t-1"] } });+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);+ fireEvent.click(screen.getByRole("button"));+ await waitFor(() => {+ expect(toastSuccessMock).toHaveBeenCalledWith("Started 1 task.");+ });+ });++ it("toasts plural and triggers refresh and entries polling on success", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ startAllMock.mockResolvedValue({ ok: true, data: { started: 2, task_ids: ["t-1", "t-2"] } });+ render(<StartAllTasksButton agentId="demo-cmo" proposedCount={2} />);+ fireEvent.click(screen.getByRole("button"));+ await waitFor(() => {+ expect(toastSuccessMock).toHaveBeenCalledWith("Started 2 tasks.");+ });+ // First refresh is the immediate one from the action's success branch.+ expect(refreshMock.mock.calls.length).toBeGreaterThanOrEqual(1);+ // Advance 3s — one polling interval — to trigger another refresh.+ const before = refreshMock.mock.calls.length;+ vi.advanceTimersByTime(3_000);+ expect(refreshMock.mock.calls.length).toBeGreaterThan(before);+ // While polling, the button stays disabled and the label is "Working…".+ await waitFor(() => {+ expect(screen.getByRole("button")).toBeDisabled();+ expect(screen.getByRole("button").textContent).toContain("Working…");+ });+ // After the 2-minute timeout, polling stops and button re-enables.+ vi.advanceTimersByTime(120_000);+ await waitFor(() => {+ expect(screen.getByRole("button")).not.toBeDisabled();+ });+ });+});diff --git a/src/components/thread-selector.test.tsx b/src/components/thread-selector.test.tsxnew file mode 100644index 00000000..8e7bf587--- /dev/null+++ b/src/components/thread-selector.test.tsx@@ -0,0 +1,230 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";++const pushMock = vi.fn();+vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: pushMock }),+}));++import { ThreadSelector, type SessionLite } from "./thread-selector";++function openTrigger() {+ const trigger = screen.getByRole("button");+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false });+ fireEvent.click(trigger);+}++beforeEach(() => {+ pushMock.mockReset();+ // jsdom + radix dropdown rely on these primitives that older jsdom is missing.+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ writable: true,+ value: vi.fn(),+ });+ // Radix uses pointer events; jsdom lacks hasPointerCapture/setPointerCapture/releasePointerCapture+ Object.defineProperty(HTMLElement.prototype, "hasPointerCapture", {+ configurable: true,+ writable: true,+ value: () => false,+ });+ Object.defineProperty(HTMLElement.prototype, "setPointerCapture", {+ configurable: true,+ writable: true,+ value: () => {},+ });+ Object.defineProperty(HTMLElement.prototype, "releasePointerCapture", {+ configurable: true,+ writable: true,+ value: () => {},+ });+});++function makeSession(overrides: Partial<SessionLite> = {}): SessionLite {+ return {+ sessionId: "s-1",+ sessionKey: "agent:demo-cmo:s-1",+ label: "main",+ lastInteractionAt: Date.now() - 30_000,+ pending: false,+ ...overrides,+ };+}++describe("ThreadSelector trigger label", () => {+ it("renders 'Main thread' when active session.label is main", () => {+ const sessions = [makeSession({ label: "main" })];+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={sessions}+ activeSessionId="s-1"+ />,+ );+ expect(+ screen.getByRole("button", { name: /Main thread/ }),+ ).toBeInTheDocument();+ });++ it("renders 'New thread · <prefix>' for pending sessions", () => {+ const sessions = [+ makeSession({ pending: true, sessionId: "1234567890abcdef", label: "ignored" }),+ ];+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={sessions}+ activeSessionId="1234567890abcdef"+ />,+ );+ expect(+ screen.getByRole("button", { name: /New thread · 12345678/ }),+ ).toBeInTheDocument();+ });++ it("truncates long labels at 32 chars with an ellipsis", () => {+ const longLabel = "this-is-a-very-long-thread-label-that-exceeds-32-characters";+ const sessions = [makeSession({ label: longLabel })];+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={sessions}+ activeSessionId="s-1"+ />,+ );+ const trigger = screen.getByRole("button");+ expect(trigger.textContent).toContain(`${longLabel.slice(0, 32)}...`);+ expect(trigger.textContent).not.toContain(longLabel);+ });++ it("shows 'Pick a thread' when no active session matches", () => {+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={[makeSession()]}+ activeSessionId="not-here"+ />,+ );+ expect(+ screen.getByRole("button", { name: /Pick a thread/ }),+ ).toBeInTheDocument();+ });+});++describe("ThreadSelector dropdown interactions", () => {+ it("opens the menu and lists sessions including counts", async () => {+ const sessions = [+ makeSession({ sessionId: "s-1", label: "main" }),+ makeSession({+ sessionId: "s-2-other",+ label: "feature branch",+ lastInteractionAt: Date.now() - 3_600_000,+ }),+ ];+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={sessions}+ activeSessionId="s-1"+ />,+ );+ openTrigger();+ await waitFor(() => {+ expect(screen.getByText(/Threads \(2\)/)).toBeInTheDocument();+ expect(screen.getByText("feature branch")).toBeInTheDocument();+ // session id prefix appears in the menu line.+ expect(screen.getAllByText(/s-1/).length).toBeGreaterThan(0);+ });+ });++ it("shows 'No threads yet' when sessions array is empty", async () => {+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={[]}+ activeSessionId=""+ />,+ );+ openTrigger();+ await waitFor(() => {+ expect(screen.getByText("No threads yet")).toBeInTheDocument();+ expect(screen.getByText(/Threads \(0\)/)).toBeInTheDocument();+ });+ });++ it("clicking a non-active session pushes to its chat URL", async () => {+ const sessions = [+ makeSession({ sessionId: "s-1", label: "main" }),+ makeSession({ sessionId: "s-2", label: "draft" }),+ ];+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={sessions}+ activeSessionId="s-1"+ />,+ );+ openTrigger();+ await waitFor(() => {+ expect(screen.getByText("draft")).toBeInTheDocument();+ });+ fireEvent.click(screen.getByText("draft"));+ await waitFor(() => {+ expect(pushMock).toHaveBeenCalledWith("/demo/agents/cmo/chat/s-2");+ });+ });++ it("clicking the active session is a no-op (no router.push)", async () => {+ const sessions = [makeSession({ sessionId: "s-1", label: "main" })];+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={sessions}+ activeSessionId="s-1"+ />,+ );+ openTrigger();+ let menuitem: HTMLElement | null = null;+ await waitFor(() => {+ menuitem = screen.getByRole("menuitem", { name: /Main thread/ });+ expect(menuitem).toBeInTheDocument();+ });+ fireEvent.click(menuitem!);+ await new Promise((r) => setTimeout(r, 10));+ expect(pushMock).not.toHaveBeenCalled();+ });++ it("clicking 'New thread' navigates to a fresh uuid", async () => {+ // Stub crypto.randomUUID for determinism.+ const uuid = "11111111-2222-3333-4444-555555555555";+ Object.defineProperty(globalThis, "crypto", {+ configurable: true,+ value: { randomUUID: () => uuid },+ });+ render(+ <ThreadSelector+ projectSlug="demo"+ agentSlug="cmo"+ sessions={[makeSession()]}+ activeSessionId="s-1"+ />,+ );+ openTrigger();+ await waitFor(() => {+ expect(screen.getByText("New thread")).toBeInTheDocument();+ });+ fireEvent.click(screen.getByText("New thread"));+ await waitFor(() => {+ expect(pushMock).toHaveBeenCalledWith(`/demo/agents/cmo/chat/${uuid}`);+ });+ });+});diff --git a/src/lib/agent-colors.test.ts b/src/lib/agent-colors.test.tsnew file mode 100644index 00000000..c3200549--- /dev/null+++ b/src/lib/agent-colors.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from "vitest";+import { colorForAgentSlug } from "./agent-colors";++describe("colorForAgentSlug", () => {+ it("returns the reserved blue palette for cmo", () => {+ const c = colorForAgentSlug("cmo");+ expect(c.dot).toBe("bg-blue-500");+ expect(c.chip).toContain("bg-blue-100");+ expect(c.label).toContain("text-blue-700");+ });++ it("returns the amber palette for google-ads (hyphenated slug)", () => {+ const c = colorForAgentSlug("google-ads");+ expect(c.dot).toBe("bg-amber-500");+ expect(c.chip).toContain("bg-amber-100");+ expect(c.label).toContain("text-amber-700");+ });++ it("returns the amber palette for google_ads (underscored key)", () => {+ const c = colorForAgentSlug("google_ads");+ expect(c.dot).toBe("bg-amber-500");+ });++ it("returns the emerald palette for seo", () => {+ const c = colorForAgentSlug("seo");+ expect(c.dot).toBe("bg-emerald-500");+ expect(c.label).toContain("text-emerald-700");+ });++ it("returns a non-template color for custom slugs", () => {+ const c = colorForAgentSlug("growth-engineer");+ // Custom slugs must never land on a template dot color (they would clash+ // with the reserved cmo/google_ads/seo legend swatches).+ expect(c.dot).not.toBe("bg-blue-500");+ expect(c.dot).not.toBe("bg-amber-500");+ expect(c.dot).not.toBe("bg-emerald-500");+ });++ it("maps the same custom slug to the same color across calls", () => {+ const a = colorForAgentSlug("growth-engineer");+ const b = colorForAgentSlug("growth-engineer");+ expect(a).toEqual(b);+ });++ it("returns a color from the extras palette for an empty slug", () => {+ const c = colorForAgentSlug("");+ const extraDots = [+ "bg-violet-500",+ "bg-rose-500",+ "bg-cyan-500",+ "bg-fuchsia-500",+ "bg-teal-500",+ "bg-orange-500",+ "bg-indigo-500",+ "bg-lime-500",+ ];+ expect(extraDots).toContain(c.dot);+ });++ it("returns chip/dot/label fields for every input", () => {+ for (const slug of ["cmo", "seo", "custom-1", "custom-2", "another"]) {+ const c = colorForAgentSlug(slug);+ expect(typeof c.chip).toBe("string");+ expect(typeof c.dot).toBe("string");+ expect(typeof c.label).toBe("string");+ expect(c.chip.length).toBeGreaterThan(0);+ expect(c.dot.length).toBeGreaterThan(0);+ expect(c.label.length).toBeGreaterThan(0);+ }+ });++ it("distributes different custom slugs across more than one extras bucket", () => {+ const dots = new Set<string>();+ for (const slug of [+ "alpha",+ "beta",+ "gamma",+ "delta",+ "epsilon",+ "zeta",+ "eta",+ "theta",+ "iota",+ "kappa",+ "lambda",+ "mu",+ "nu",+ "xi",+ "omicron",+ "pi",+ ]) {+ dots.add(colorForAgentSlug(slug).dot);+ }+ expect(dots.size).toBeGreaterThan(1);+ });+});diff --git a/src/lib/slash-commands.test.ts b/src/lib/slash-commands.test.tsnew file mode 100644index 00000000..408e3cfa--- /dev/null+++ b/src/lib/slash-commands.test.ts@@ -0,0 +1,169 @@+import { describe, expect, it } from "vitest";+import {+ SLASH_COMMANDS,+ executeLocalSlashCommand,+ filterSlashCommands,+ findCommand,+ parseSlashMessage,+} from "./slash-commands";++describe("SLASH_COMMANDS catalog", () => {+ it("has unique command keys", () => {+ const keys = SLASH_COMMANDS.map((c) => c.key);+ expect(new Set(keys).size).toBe(keys.length);+ });++ it("has unique command names", () => {+ const names = SLASH_COMMANDS.map((c) => c.name);+ expect(new Set(names).size).toBe(names.length);+ });++ it("marks clear/new/stop/help as executeLocal", () => {+ for (const name of ["clear", "new", "stop", "help"]) {+ const cmd = findCommand(name);+ expect(cmd?.executeLocal).toBe(true);+ }+ });++ it("does not mark pass-through commands as executeLocal", () => {+ for (const name of ["status", "compact", "model", "think", "elevated"]) {+ const cmd = findCommand(name);+ expect(cmd?.executeLocal).toBeFalsy();+ }+ });+});++describe("filterSlashCommands", () => {+ it("returns all commands for empty query", () => {+ expect(filterSlashCommands("")).toEqual(SLASH_COMMANDS);+ expect(filterSlashCommands(" ")).toEqual(SLASH_COMMANDS);+ });++ it("returns all commands for a bare slash", () => {+ expect(filterSlashCommands("/")).toEqual(SLASH_COMMANDS);+ });++ it("prefix-matches with or without leading slash", () => {+ const a = filterSlashCommands("cl");+ const b = filterSlashCommands("/cl");+ expect(a).toEqual(b);+ expect(a.some((c) => c.name === "clear")).toBe(true);+ });++ it("is case-insensitive", () => {+ const lower = filterSlashCommands("CL");+ expect(lower.some((c) => c.name === "clear")).toBe(true);+ });++ it("falls back to substring match when no prefix hits", () => {+ // "mp" does not prefix any command name, but `compact` contains it,+ // so the substring fallback should surface it.+ const r = filterSlashCommands("mp");+ const names = r.map((c) => c.name);+ expect(names).toContain("compact");+ expect(names.every((n) => n.toLowerCase().startsWith("mp"))).toBe(false);+ });++ it("returns empty list when nothing matches", () => {+ expect(filterSlashCommands("zzzzzz")).toEqual([]);+ });++ it("prefers prefix matches over substring matches", () => {+ // "co" prefix-matches commands starting with co (`compact`, `commands`).+ // It should NOT fall back to substring, so e.g. `reasoning` (no "co") is+ // excluded — and the result must contain only prefix hits.+ const r = filterSlashCommands("co");+ expect(r.every((c) => c.name.toLowerCase().startsWith("co"))).toBe(true);+ expect(r.length).toBeGreaterThan(0);+ });+});++describe("parseSlashMessage", () => {+ it("returns null for plain text", () => {+ expect(parseSlashMessage("hello")).toBeNull();+ expect(parseSlashMessage("")).toBeNull();+ });++ it("returns null for whitespace-only", () => {+ expect(parseSlashMessage(" ")).toBeNull();+ });++ it("parses a bare slash command", () => {+ expect(parseSlashMessage("/clear")).toEqual({ command: "clear", args: "" });+ });++ it("parses a slash command with args", () => {+ expect(parseSlashMessage("/skill audit ads")).toEqual({+ command: "skill",+ args: "audit ads",+ });+ });++ it("trims trailing whitespace from args", () => {+ expect(parseSlashMessage("/model gpt-5 ")).toEqual({+ command: "model",+ args: "gpt-5",+ });+ });++ it("trims leading whitespace from the message", () => {+ expect(parseSlashMessage(" /help")).toEqual({ command: "help", args: "" });+ });++ it("treats a lone slash as an empty command", () => {+ expect(parseSlashMessage("/")).toEqual({ command: "", args: "" });+ });+});++describe("findCommand", () => {+ it("finds a known command by name", () => {+ const cmd = findCommand("status");+ expect(cmd).toBeDefined();+ expect(cmd?.key).toBe("status");+ });++ it("returns undefined for an unknown command", () => {+ expect(findCommand("nope")).toBeUndefined();+ });++ it("is case-sensitive on the canonical name", () => {+ expect(findCommand("CLEAR")).toBeUndefined();+ });+});++describe("executeLocalSlashCommand", () => {+ it("returns a clear action for /clear", () => {+ expect(executeLocalSlashCommand("clear")).toEqual({ kind: "clear" });+ });++ it("returns a new-session action for /new", () => {+ expect(executeLocalSlashCommand("new")).toEqual({ kind: "new-session" });+ });++ it("returns a stop action for /stop", () => {+ expect(executeLocalSlashCommand("stop")).toEqual({ kind: "stop" });+ });++ it("returns a help action with rendered markdown content", () => {+ const r = executeLocalSlashCommand("help");+ expect(r?.kind).toBe("help");+ if (r?.kind !== "help") return;+ expect(r.content).toContain("Available commands");+ expect(r.content).toContain("/clear");+ expect(r.content).toContain("/status");+ // Local commands marked, pass-through commands marked differently.+ expect(r.content).toContain("local");+ expect(r.content).toContain("sent to agent");+ // Commands that declare args render them.+ expect(r.content).toContain("/skill <name>");+ });++ it("returns null for a pass-through command", () => {+ expect(executeLocalSlashCommand("status")).toBeNull();+ expect(executeLocalSlashCommand("compact")).toBeNull();+ });++ it("returns null for an unknown command", () => {+ expect(executeLocalSlashCommand("nope")).toBeNull();+ });+});diff --git a/src/lib/utils.test.ts b/src/lib/utils.test.tsnew file mode 100644index 00000000..7ea3f069--- /dev/null+++ b/src/lib/utils.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { cn } from "./utils";++describe("cn", () => {+ it("joins simple class strings", () => {+ expect(cn("a", "b")).toBe("a b");+ });++ it("returns an empty string for no inputs", () => {+ expect(cn()).toBe("");+ });++ it("filters out falsy values", () => {+ expect(cn("a", false, null, undefined, "", "b")).toBe("a b");+ });++ it("supports conditional object syntax via clsx", () => {+ expect(cn("a", { b: true, c: false, d: true })).toBe("a b d");+ });++ it("supports nested arrays via clsx", () => {+ expect(cn(["a", ["b", "c"]], "d")).toBe("a b c d");+ });++ it("dedupes conflicting tailwind utilities via twMerge (last wins)", () => {+ expect(cn("p-2", "p-4")).toBe("p-4");+ expect(cn("text-sm", "text-lg")).toBe("text-lg");+ });++ it("keeps non-conflicting tailwind utilities", () => {+ expect(cn("p-2", "text-sm")).toBe("p-2 text-sm");+ });++ it("merges variant prefixes correctly", () => {+ // sm:p-2 and p-4 are different variants → both kept.+ expect(cn("sm:p-2", "p-4")).toBe("sm:p-2 p-4");+ // Same variant → last wins.+ expect(cn("sm:p-2", "sm:p-4")).toBe("sm:p-4");+ });++ it("handles a mix of conditional + tailwind merge inputs", () => {+ expect(cn("p-2", { "p-4": true }, ["text-sm", { "text-lg": false }]))+ .toBe("p-4 text-sm");+ });+});diff --git a/src/server/actions/agents.test.ts b/src/server/actions/agents.test.tsnew file mode 100644index 00000000..c908790c--- /dev/null+++ b/src/server/actions/agents.test.ts@@ -0,0 +1,878 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),+}));++const getActiveProjectMock = vi.fn();+vi.mock("@/server/active-project", () => ({+ getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),+}));++const disableCronMock = vi.fn();+const listCronsForProjectMock = vi.fn();+const removeCronMock = vi.fn();+vi.mock("@/server/openclaw/crons", () => ({+ disableCron: (...args: unknown[]) => disableCronMock(...args),+ listCronsForProject: (...args: unknown[]) => listCronsForProjectMock(...args),+ removeCron: (...args: unknown[]) => removeCronMock(...args),+}));++const createAgentViaRpcMock = vi.fn();+const deleteAgentMock = vi.fn();+const listAllAgentsMock = vi.fn();+vi.mock("@/server/openclaw/gateway-rpc", () => ({+ createAgentViaRpc: (...args: unknown[]) => createAgentViaRpcMock(...args),+ deleteAgent: (...args: unknown[]) => deleteAgentMock(...args),+ listAllAgents: (...args: unknown[]) => listAllAgentsMock(...args),+}));++const agentExistsInProjectMock = vi.fn();+const cloneAgentMock = vi.fn();+vi.mock("@/server/openclaw/clone-agent", () => ({+ agentExistsInProject: (...args: unknown[]) => agentExistsInProjectMock(...args),+ cloneAgent: (...args: unknown[]) => cloneAgentMock(...args),+}));++const readAgentMetaMock = vi.fn();+const writeAgentMetaMock = vi.fn();+const workspaceDirForMock = vi.fn();+const listProjectAgentsMock = vi.fn();+vi.mock("@/server/agent-meta", () => ({+ readAgentMeta: (...args: unknown[]) => readAgentMetaMock(...args),+ writeAgentMeta: (...args: unknown[]) => writeAgentMetaMock(...args),+ workspaceDirFor: (...args: unknown[]) => workspaceDirForMock(...args),+ listProjectAgents: (...args: unknown[]) => listProjectAgentsMock(...args),+}));++const listSessionsForAgentMock = vi.fn();+vi.mock("@/server/openclaw/sessions", () => ({+ listSessionsForAgent: (...args: unknown[]) => listSessionsForAgentMock(...args),+}));++const existsSyncMock = vi.fn();+const rmMock = vi.fn();+vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs")>();+ return {+ ...actual,+ existsSync: (...args: unknown[]) => existsSyncMock(...args),+ };+});+vi.mock("node:fs/promises", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs/promises")>();+ return {+ ...actual,+ rm: (...args: unknown[]) => rmMock(...args),+ };+});++import {+ cascadeDeleteAgent,+ cloneAgentAction,+ createAgentAction,+ deleteAgentCascadeAction,+ disableCronsAction,+ getAgentDeletionSummaryAction,+ listOpenClawAgentsAction,+ listProjectAgentsAction,+ relocateAgent,+ removeCronsAction,+ renameAgentAction,+} from "./agents";++function project(slug = "acme") {+ return {+ id: "uuid",+ slug,+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ };+}++beforeEach(() => {+ revalidatePathMock.mockReset();+ getActiveProjectMock.mockReset();+ disableCronMock.mockReset();+ listCronsForProjectMock.mockReset();+ removeCronMock.mockReset();+ createAgentViaRpcMock.mockReset();+ deleteAgentMock.mockReset();+ listAllAgentsMock.mockReset();+ agentExistsInProjectMock.mockReset();+ cloneAgentMock.mockReset();+ readAgentMetaMock.mockReset();+ writeAgentMetaMock.mockReset();+ workspaceDirForMock.mockReset();+ listProjectAgentsMock.mockReset();+ listSessionsForAgentMock.mockReset();+ existsSyncMock.mockReset();+ rmMock.mockReset();++ workspaceDirForMock.mockImplementation((id: string) => `/ws/${id}`);+});++describe("listOpenClawAgentsAction", () => {+ it("merges openclaw list with project agent ids and marks membership", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ listProjectAgentsMock.mockResolvedValueOnce([+ { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },+ ]);+ listAllAgentsMock.mockResolvedValueOnce({+ agents: [+ { id: "acme-cmo", name: "fallback", identity: { name: "CMO" } },+ { id: "other-agent", name: "Other Agent" },+ ],+ });+ const r = await listOpenClawAgentsAction();+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data).toHaveLength(2);+ const cmo = r.data.find((a) => a.agent_id === "acme-cmo")!;+ expect(cmo.in_current_project).toBe(true);+ expect(cmo.display_name).toBe("CMO");+ const other = r.data.find((a) => a.agent_id === "other-agent")!;+ expect(other.in_current_project).toBe(false);+ expect(other.display_name).toBe("Other Agent");+ });++ it("falls back to id when no identity name or name present", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ listAllAgentsMock.mockResolvedValueOnce({+ agents: [{ id: "raw-id" }],+ });+ const r = await listOpenClawAgentsAction();+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data[0]!.display_name).toBe("raw-id");+ expect(r.data[0]!.in_current_project).toBe(false);+ });++ it("returns error result when listAllAgents throws", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ listAllAgentsMock.mockRejectedValueOnce(new Error("gateway down"));+ const r = await listOpenClawAgentsAction();+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/gateway down/);+ });++ it("returns error result with stringified non-Error", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ listAllAgentsMock.mockRejectedValueOnce("boom");+ const r = await listOpenClawAgentsAction();+ expect(r.ok).toBe(false);+ });+});++describe("listProjectAgentsAction", () => {+ it("returns error when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await listProjectAgentsAction();+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/No active project/);+ });++ it("returns project agents on happy path", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ listProjectAgentsMock.mockResolvedValueOnce([+ { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },+ ]);+ const r = await listProjectAgentsAction();+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data).toHaveLength(1);+ });++ it("returns error when listProjectAgents throws", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ listProjectAgentsMock.mockRejectedValueOnce(new Error("disk fail"));+ const r = await listProjectAgentsAction();+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/disk fail/);+ });+});++describe("createAgentAction", () => {+ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await createAgentAction({ display_name: "Foo" });+ expect(r.ok).toBe(false);+ });++ it("rejects when display_name is empty (slugify fails)", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ const r = await createAgentAction({ display_name: "" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Invalid name/);+ });++ it("rejects when an agent with the same slug already exists in the project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ agentExistsInProjectMock.mockReturnValueOnce(true);+ const r = await createAgentAction({ display_name: "Supa" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/already exists/);+ });++ it("creates the agent, writes meta, revalidates layout on success", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ agentExistsInProjectMock.mockReturnValueOnce(false);+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ writeAgentMetaMock.mockResolvedValueOnce(undefined);+ const r = await createAgentAction({ display_name: "Supa Agent" });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.agent_id).toBe("acme-supa-agent");+ expect(r.data.slug).toBe("supa-agent");+ expect(createAgentViaRpcMock).toHaveBeenCalledWith({+ name: "acme-supa-agent",+ workspace: "/ws/acme-supa-agent",+ });+ expect(writeAgentMetaMock).toHaveBeenCalled();+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns error when createAgentViaRpc throws", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ agentExistsInProjectMock.mockReturnValueOnce(false);+ createAgentViaRpcMock.mockRejectedValueOnce(new Error("rpc failed"));+ const r = await createAgentAction({ display_name: "Supa" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/rpc failed/);+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });+});++describe("cloneAgentAction", () => {+ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await cloneAgentAction({+ source_agent_id: "acme-cmo",+ new_display_name: "Clone",+ });+ expect(r.ok).toBe(false);+ });++ it("rejects when both new_display_name and new_slug are empty/whitespace", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ const r = await cloneAgentAction({+ source_agent_id: "acme-cmo",+ new_display_name: " ",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/provide a name/);+ });++ it("calls cloneAgent with overridden new_slug and revalidates", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ cloneAgentMock.mockResolvedValueOnce({+ new_agent_id: "acme-shortie",+ new_slug: "shortie",+ files_copied: 1,+ sessions_copied: 0,+ source_crons: [],+ new_cron_ids: [],+ });+ const r = await cloneAgentAction({+ source_agent_id: "acme-cmo",+ new_display_name: "Long Name",+ new_slug: "shortie",+ });+ expect(r.ok).toBe(true);+ expect(cloneAgentMock).toHaveBeenCalledWith({+ source_agent_id: "acme-cmo",+ project_slug: "acme",+ new_slug: "shortie",+ display_name: "Long Name",+ });+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("falls back to new_display_name when new_slug is undefined", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ cloneAgentMock.mockResolvedValueOnce({+ new_agent_id: "acme-clone-name",+ new_slug: "clone-name",+ files_copied: 0,+ sessions_copied: 0,+ source_crons: [],+ new_cron_ids: [],+ });+ const r = await cloneAgentAction({+ source_agent_id: "acme-cmo",+ new_display_name: "Clone Name",+ });+ expect(r.ok).toBe(true);+ expect(cloneAgentMock).toHaveBeenCalledWith({+ source_agent_id: "acme-cmo",+ project_slug: "acme",+ new_slug: "Clone Name",+ display_name: "Clone Name",+ });+ });++ it("returns error on cloneAgent failure (no revalidate)", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ cloneAgentMock.mockRejectedValueOnce(new Error("clone exploded"));+ const r = await cloneAgentAction({+ source_agent_id: "acme-cmo",+ new_display_name: "Clone Name",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/clone exploded/);+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });+});++describe("disableCronsAction", () => {+ it("counts each disable success/failure independently", async () => {+ disableCronMock+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("bad"))+ .mockResolvedValueOnce(undefined);+ const r = await disableCronsAction(["a", "b", "c"]);+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.disabled).toBe(2);+ expect(r.data.failed).toBe(1);+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("handles empty list without throwing", async () => {+ const r = await disableCronsAction([]);+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data).toEqual({ disabled: 0, failed: 0 });+ });+});++describe("removeCronsAction", () => {+ it("counts each remove success/failure independently", async () => {+ removeCronMock+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("bad"));+ const r = await removeCronsAction(["a", "b"]);+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data).toEqual({ removed: 1, failed: 1 });+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });+});++describe("renameAgentAction", () => {+ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "Bar",+ });+ expect(r.ok).toBe(false);+ });++ it("rejects when new display name is blank", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: " ",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Name cannot be empty/);+ });++ it("rejects when slugify fails (e.g. all symbols)", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "@@@",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Invalid name/);+ });++ it("rejects when meta sidecar is missing", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce(null);+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "Bar",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/no meta on disk/);+ });++ it("rejects when meta says agent belongs to a different project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project("acme"));+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "other-foo",+ project_slug: "other",+ slug: "foo",+ display_name: "Foo",+ created_at: "now",+ });+ const r = await renameAgentAction({+ agent_id: "other-foo",+ new_display_name: "Bar",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/different project/);+ });++ it("display-name-only change returns full_rename:false and rewrites meta", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-foo",+ project_slug: "acme",+ slug: "foo",+ display_name: "Foo",+ created_at: "now",+ });+ // "FOO!" slugifies back to "foo" so the slug is unchanged → display-only.+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "FOO!",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.full_rename).toBe(false);+ expect(r.data.display_name).toBe("FOO!");+ expect(writeAgentMetaMock).toHaveBeenCalled();+ expect(revalidatePathMock).toHaveBeenCalled();+ });++ it("no-op rename (same slug AND same display name) returns full_rename:false without writing meta", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-foo",+ project_slug: "acme",+ slug: "foo",+ display_name: "Foo",+ created_at: "now",+ });+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "Foo",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.full_rename).toBe(false);+ expect(writeAgentMetaMock).not.toHaveBeenCalled();+ });++ it("full rename rejected when destination slug already exists", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-foo",+ project_slug: "acme",+ slug: "foo",+ display_name: "Foo",+ created_at: "now",+ });+ agentExistsInProjectMock.mockReturnValueOnce(true);+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "Bar",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/already exists/);+ });++ it("full rename calls relocateAgent (clone + delete) and returns new ids", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-foo",+ project_slug: "acme",+ slug: "foo",+ display_name: "Foo",+ template_key: "google_ads",+ created_at: "2024-01-01T00:00:00Z",+ });+ agentExistsInProjectMock.mockReturnValueOnce(false);+ // relocateAgent's call to cloneAgent+ cloneAgentMock.mockResolvedValueOnce({+ new_agent_id: "acme-bar",+ new_slug: "bar",+ files_copied: 0,+ sessions_copied: 0,+ source_crons: [],+ new_cron_ids: [],+ });+ // relocateAgent calls writeAgentMeta + cascadeDeleteAgent (which calls deleteAgent, listCronsForProject, rm, etc.)+ writeAgentMetaMock.mockResolvedValue(undefined);+ listCronsForProjectMock.mockResolvedValue({ groups: [] });+ deleteAgentMock.mockResolvedValue(undefined);+ existsSyncMock.mockReturnValue(false);++ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "Bar",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.full_rename).toBe(true);+ expect(r.data.agent_id).toBe("acme-bar");+ expect(r.data.slug).toBe("bar");+ expect(cloneAgentMock).toHaveBeenCalledWith(+ expect.objectContaining({+ source_agent_id: "acme-foo",+ project_slug: "acme",+ new_slug: "bar",+ display_name: "Bar",+ slug_is_canonical: true,+ }),+ );+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("full rename surfaces relocate failures with a 'Rename failed' message", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-foo",+ project_slug: "acme",+ slug: "foo",+ display_name: "Foo",+ created_at: "now",+ });+ agentExistsInProjectMock.mockReturnValueOnce(false);+ cloneAgentMock.mockRejectedValueOnce(new Error("clone failed"));+ const r = await renameAgentAction({+ agent_id: "acme-foo",+ new_display_name: "Bar",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Rename failed/);+ expect(r.error).toMatch(/clone failed/);+ });+});++describe("relocateAgent", () => {+ it("clones, writes meta with preserved fields, then cascade-deletes source (best-effort)", async () => {+ cloneAgentMock.mockResolvedValueOnce({+ new_agent_id: "newproj-foo",+ new_slug: "foo",+ files_copied: 0,+ sessions_copied: 0,+ source_crons: [],+ new_cron_ids: [],+ });+ writeAgentMetaMock.mockResolvedValue(undefined);+ listCronsForProjectMock.mockResolvedValue({ groups: [] });+ deleteAgentMock.mockResolvedValue(undefined);+ existsSyncMock.mockReturnValue(false);++ const r = await relocateAgent({+ old_agent_id: "oldproj-foo",+ source_project_slug: "oldproj",+ new_project_slug: "newproj",+ new_slug: "foo",+ new_display_name: "Foo",+ preserve_template_key: "google_ads",+ preserve_source_agent_id: "src-id",+ preserve_created_at: "2024-01-01T00:00:00Z",+ });+ expect(r).toEqual({ new_agent_id: "newproj-foo", new_slug: "foo" });+ expect(writeAgentMetaMock).toHaveBeenCalledWith(+ expect.objectContaining({+ agent_id: "newproj-foo",+ project_slug: "newproj",+ slug: "foo",+ display_name: "Foo",+ template_key: "google_ads",+ source_agent_id: "src-id",+ created_at: "2024-01-01T00:00:00Z",+ }),+ );+ });++ it("swallows cascadeDeleteAgent failures so the relocate still resolves", async () => {+ cloneAgentMock.mockResolvedValueOnce({+ new_agent_id: "newproj-foo",+ new_slug: "foo",+ files_copied: 0,+ sessions_copied: 0,+ source_crons: [],+ new_cron_ids: [],+ });+ writeAgentMetaMock.mockResolvedValue(undefined);+ // make cascade fail by having deleteAgent throw unrelated error+ listCronsForProjectMock.mockResolvedValue({ groups: [] });+ deleteAgentMock.mockRejectedValue(new Error("opclaw broken"));+ existsSyncMock.mockReturnValue(false);++ const r = await relocateAgent({+ old_agent_id: "oldproj-foo",+ source_project_slug: "oldproj",+ new_project_slug: "newproj",+ new_slug: "foo",+ new_display_name: "Foo",+ });+ expect(r.new_agent_id).toBe("newproj-foo");+ });++ it("throws when cloneAgent fails (source is left intact)", async () => {+ cloneAgentMock.mockRejectedValueOnce(new Error("clone failed"));+ await expect(+ relocateAgent({+ old_agent_id: "oldproj-foo",+ source_project_slug: "oldproj",+ new_project_slug: "newproj",+ new_slug: "foo",+ new_display_name: "Foo",+ }),+ ).rejects.toThrow(/clone failed/);+ });++ it("uses new Date().toISOString() when no preserve_created_at is provided", async () => {+ cloneAgentMock.mockResolvedValueOnce({+ new_agent_id: "newproj-foo",+ new_slug: "foo",+ files_copied: 0,+ sessions_copied: 0,+ source_crons: [],+ new_cron_ids: [],+ });+ writeAgentMetaMock.mockResolvedValue(undefined);+ listCronsForProjectMock.mockResolvedValue({ groups: [] });+ deleteAgentMock.mockResolvedValue(undefined);+ existsSyncMock.mockReturnValue(false);++ await relocateAgent({+ old_agent_id: "oldproj-foo",+ source_project_slug: "oldproj",+ new_project_slug: "newproj",+ new_slug: "foo",+ new_display_name: "Foo",+ });+ const writeCall = writeAgentMetaMock.mock.calls[0]![0] as { created_at: string };+ expect(Date.parse(writeCall.created_at)).toBeGreaterThan(0);+ });+});++describe("getAgentDeletionSummaryAction", () => {+ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await getAgentDeletionSummaryAction("acme-foo");+ expect(r.ok).toBe(false);+ });++ it("returns summary with threads + crons + meta info", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-foo",+ project_slug: "acme",+ slug: "foo",+ display_name: "Foo Agent",+ template_key: "google_ads",+ source_agent_id: "src",+ created_at: "now",+ });+ existsSyncMock.mockReturnValue(true);+ listSessionsForAgentMock.mockReturnValueOnce([+ { sessionId: "s1", label: "T1", lastInteractionAt: 12345 },+ { sessionId: "s2", label: "T2", lastInteractionAt: 67890 },+ ]);+ listCronsForProjectMock.mockResolvedValueOnce({+ groups: [+ {+ agent: "acme-foo",+ crons: [+ { id: "c1", name: "acme/foo/job", short_name: "job", agent_id: "acme-foo", disabled: false },+ { id: "c2", name: "n2", short_name: "", agent_id: "acme-other", disabled: false },+ ],+ },+ ],+ });+ const r = await getAgentDeletionSummaryAction("acme-foo");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.exists_in_openclaw).toBe(true);+ expect(r.data.threads).toHaveLength(2);+ expect(r.data.crons).toEqual([+ { id: "c1", name: "job", disabled: false },+ ]);+ expect(r.data.template_key).toBe("google_ads");+ expect(r.data.source_agent_id).toBe("src");+ });++ it("returns summary with empty crons when listCronsForProject throws", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce(null);+ existsSyncMock.mockReturnValue(false);+ listCronsForProjectMock.mockRejectedValueOnce(new Error("cron down"));+ const r = await getAgentDeletionSummaryAction("acme-foo");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.crons).toEqual([]);+ expect(r.data.threads).toEqual([]);+ expect(r.data.exists_in_openclaw).toBe(false);+ // missing meta: display_name falls back to agent_id+ expect(r.data.display_name).toBe("acme-foo");+ });++ it("falls back name to agent_id when openclaw doesn't have the agent dir", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ readAgentMetaMock.mockReturnValueOnce(null);+ existsSyncMock.mockReturnValue(false);+ listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });+ const r = await getAgentDeletionSummaryAction("acme-foo");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ // sessions never called when dir missing+ expect(listSessionsForAgentMock).not.toHaveBeenCalled();+ });+});++describe("cascadeDeleteAgent", () => {+ it("removes crons from explicit cronIds, deletes agent, cleans meta + openclaw dir", async () => {+ removeCronMock.mockResolvedValueOnce(undefined).mockResolvedValueOnce(undefined);+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(true);+ rmMock.mockResolvedValue(undefined);++ const r = await cascadeDeleteAgent({+ agent_id: "acme-foo",+ cronIds: ["c1", "c2"],+ });+ expect(r).toMatchObject({+ agent_id: "acme-foo",+ crons_removed: 2,+ crons_failed: 0,+ openclaw_deleted: true,+ meta_removed: true,+ });+ expect(listCronsForProjectMock).not.toHaveBeenCalled();+ });++ it("looks up cronIds via project when not supplied", async () => {+ listCronsForProjectMock.mockResolvedValueOnce({+ groups: [+ {+ agent: "acme-foo",+ crons: [+ { id: "c1", agent_id: "acme-foo" },+ { id: "c2", agent_id: "acme-other" },+ { id: "c3", agent_id: "acme-foo" },+ ],+ },+ ],+ });+ removeCronMock.mockResolvedValue(undefined);+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(false);++ const r = await cascadeDeleteAgent({+ agent_id: "acme-foo",+ projectSlug: "acme",+ });+ expect(r.crons_removed).toBe(2);+ expect(removeCronMock).toHaveBeenCalledTimes(2);+ });++ it("treats listCronsForProject failure as empty list (no crons removed)", async () => {+ listCronsForProjectMock.mockRejectedValueOnce(new Error("cron down"));+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(false);+ const r = await cascadeDeleteAgent({+ agent_id: "acme-foo",+ projectSlug: "acme",+ });+ expect(r.crons_removed).toBe(0);+ expect(r.crons_failed).toBe(0);+ });++ it("counts failed cron removals separately", async () => {+ removeCronMock+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("nope"));+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(false);+ const r = await cascadeDeleteAgent({+ agent_id: "acme-foo",+ cronIds: ["c1", "c2"],+ });+ expect(r.crons_removed).toBe(1);+ expect(r.crons_failed).toBe(1);+ });++ it("treats 'unknown agent' from deleteAgent as success", async () => {+ deleteAgentMock.mockRejectedValueOnce(new Error("unknown agent foo"));+ existsSyncMock.mockReturnValue(false);+ const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });+ expect(r.openclaw_deleted).toBe(true);+ });++ it("treats 'not found' from deleteAgent as success", async () => {+ deleteAgentMock.mockRejectedValueOnce(new Error("agent not found"));+ existsSyncMock.mockReturnValue(false);+ const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });+ expect(r.openclaw_deleted).toBe(true);+ });++ it("rethrows other deleteAgent errors", async () => {+ deleteAgentMock.mockRejectedValueOnce(new Error("network exploded"));+ await expect(+ cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] }),+ ).rejects.toThrow(/network exploded/);+ });++ it("meta_removed is false when workspace dir doesn't exist", async () => {+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(false);+ const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });+ expect(r.meta_removed).toBe(false);+ });++ it("non-fatal when rm of workspace fails", async () => {+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(true);+ rmMock.mockRejectedValueOnce(new Error("perm denied"));+ const r = await cascadeDeleteAgent({ agent_id: "acme-foo", cronIds: [] });+ expect(r.openclaw_deleted).toBe(true);+ expect(r.meta_removed).toBe(false);+ });+});++describe("deleteAgentCascadeAction", () => {+ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await deleteAgentCascadeAction("acme-foo");+ expect(r.ok).toBe(false);+ });++ it("returns ok + revalidates layout on successful cascade", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });+ deleteAgentMock.mockResolvedValueOnce(undefined);+ existsSyncMock.mockReturnValue(false);+ const r = await deleteAgentCascadeAction("acme-foo");+ expect(r.ok).toBe(true);+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("wraps cascade errors with 'OpenClaw refused' prefix", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });+ deleteAgentMock.mockRejectedValueOnce(new Error("network down"));+ const r = await deleteAgentCascadeAction("acme-foo");+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/OpenClaw refused/);+ expect(r.error).toMatch(/network down/);+ });+});diff --git a/src/server/actions/approvals.test.ts b/src/server/actions/approvals.test.tsnew file mode 100644index 00000000..83a5efec--- /dev/null+++ b/src/server/actions/approvals.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),+}));++const resolveApprovalMock = vi.fn();+vi.mock("@/server/db/approvals", () => ({+ resolveApproval: (...a: unknown[]) => resolveApprovalMock(...a),+}));++import { approveAction, rejectAction } from "./approvals";++function makeApproval(overrides: Record<string, unknown> = {}) {+ return {+ id: "ap-1",+ project_slug: "demo",+ agent_id: "demo-cmo",+ action_summary: "raise bid",+ action_type: "bid_change",+ cost_estimate_usd: 0,+ reasoning: null,+ payload_json: "{}",+ status: "approved",+ created_at: "2026-05-01T00:00:00Z",+ resolved_at: "2026-05-02T00:00:00Z",+ ...overrides,+ };+}++describe("approveAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("calls resolveApproval with 'approved' and revalidates layout on success", async () => {+ resolveApprovalMock.mockReturnValue(makeApproval({ status: "approved" }));+ const out = await approveAction("ap-1");+ expect(out).toEqual({ ok: true });+ expect(resolveApprovalMock).toHaveBeenCalledWith("ap-1", "approved");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns ok:false with descriptive error when resolveApproval returns null", async () => {+ resolveApprovalMock.mockReturnValue(null);+ const out = await approveAction("missing");+ expect(out).toEqual({+ ok: false,+ error: "Approval not found or already resolved.",+ });+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });+});++describe("rejectAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("calls resolveApproval with 'rejected' and revalidates layout on success", async () => {+ resolveApprovalMock.mockReturnValue(makeApproval({ status: "rejected" }));+ const out = await rejectAction("ap-1");+ expect(out).toEqual({ ok: true });+ expect(resolveApprovalMock).toHaveBeenCalledWith("ap-1", "rejected");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns ok:false with descriptive error when resolveApproval returns null", async () => {+ resolveApprovalMock.mockReturnValue(null);+ const out = await rejectAction("missing");+ expect(out).toEqual({+ ok: false,+ error: "Approval not found or already resolved.",+ });+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });+});diff --git a/src/server/actions/cron-runs.test.ts b/src/server/actions/cron-runs.test.tsnew file mode 100644index 00000000..955fbe68--- /dev/null+++ b/src/server/actions/cron-runs.test.ts@@ -0,0 +1,125 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const loadCronRunsMock = vi.fn();+vi.mock("@/server/openclaw/crons", () => ({+ loadCronRuns: (...a: unknown[]) => loadCronRunsMock(...a),+}));++const tickAtOrBeforeMock = vi.fn();+vi.mock("@/server/openclaw/cron-schedule", () => ({+ tickAtOrBefore: (...a: unknown[]) => tickAtOrBeforeMock(...a),+}));++import { getCronRunsAction } from "./cron-runs";++function makeRun(overrides: Record<string, unknown> = {}) {+ return {+ run_at_ms: 1_700_000_000_000,+ finished_at_ms: 1_700_000_001_000,+ status: "ok",+ summary: "ran fine",+ error: undefined,+ duration_ms: 1000,+ session_id: "s-1",+ model: undefined,+ provider: undefined,+ usage: undefined,+ ...overrides,+ };+}++describe("getCronRunsAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns runs with owning_occurrence_at_ms from tickAtOrBefore when a schedule is provided", async () => {+ const runA = makeRun({ run_at_ms: 1000 });+ const runB = makeRun({ run_at_ms: 2000 });+ loadCronRunsMock.mockReturnValue([runA, runB]);+ tickAtOrBeforeMock.mockImplementation((_s: unknown, at: number) => at - 100);++ const schedule = { kind: "cron" as const, expr: "0 9 * * *", tz: "UTC" };+ const out = await getCronRunsAction("cron-1", schedule, 50);++ expect(out.ok).toBe(true);+ if (!out.ok) return;+ expect(out.runs).toHaveLength(2);+ expect(out.runs[0]!.owning_occurrence_at_ms).toBe(900);+ expect(out.runs[1]!.owning_occurrence_at_ms).toBe(1900);+ expect(loadCronRunsMock).toHaveBeenCalledWith("cron-1", 50);+ expect(tickAtOrBeforeMock).toHaveBeenNthCalledWith(1, schedule, 1000);+ expect(tickAtOrBeforeMock).toHaveBeenNthCalledWith(2, schedule, 2000);+ });++ it("sets owning_occurrence_at_ms to undefined when schedule is null", async () => {+ loadCronRunsMock.mockReturnValue([makeRun()]);+ const out = await getCronRunsAction("cron-1", null);+ expect(out.ok).toBe(true);+ if (!out.ok) return;+ expect(out.runs[0]!.owning_occurrence_at_ms).toBeUndefined();+ expect(tickAtOrBeforeMock).not.toHaveBeenCalled();+ });++ it("returns empty list when loadCronRuns has no entries", async () => {+ loadCronRunsMock.mockReturnValue([]);+ const out = await getCronRunsAction("cron-1", null);+ expect(out).toEqual({ ok: true, runs: [] });+ });++ it("uses default limit of 100 when not specified", async () => {+ loadCronRunsMock.mockReturnValue([]);+ await getCronRunsAction("cron-1", null);+ expect(loadCronRunsMock).toHaveBeenCalledWith("cron-1", 100);+ });++ it("supports 'every' schedule shape end-to-end", async () => {+ loadCronRunsMock.mockReturnValue([makeRun({ run_at_ms: 5000 })]);+ tickAtOrBeforeMock.mockReturnValue(4500);+ const schedule = { kind: "every" as const, everyMs: 60_000, anchorMs: 0 };+ const out = await getCronRunsAction("cron-1", schedule);+ expect(out.ok).toBe(true);+ if (!out.ok) return;+ expect(out.runs[0]!.owning_occurrence_at_ms).toBe(4500);+ expect(tickAtOrBeforeMock).toHaveBeenCalledWith(schedule, 5000);+ });++ it("returns ok:false with the Error message when loadCronRuns throws", async () => {+ loadCronRunsMock.mockImplementation(() => {+ throw new Error("disk read failed");+ });+ const out = await getCronRunsAction("cron-1", null);+ expect(out).toEqual({ ok: false, error: "disk read failed" });+ });++ it("stringifies non-Error throws into the error field", async () => {+ loadCronRunsMock.mockImplementation(() => {+ throw "string-reason";+ });+ const out = await getCronRunsAction("cron-1", null);+ expect(out).toEqual({ ok: false, error: "string-reason" });+ });++ it("preserves all CronRun fields from loadCronRuns in the enriched output", async () => {+ const run = makeRun({+ status: "error",+ summary: "boom",+ error: "timeout",+ session_id: "sess-xyz",+ model: "claude-opus-4-7",+ usage: { input_tokens: 100, output_tokens: 50 },+ });+ loadCronRunsMock.mockReturnValue([run]);+ const out = await getCronRunsAction("cron-1", null);+ expect(out.ok).toBe(true);+ if (!out.ok) return;+ expect(out.runs[0]).toMatchObject({+ status: "error",+ summary: "boom",+ error: "timeout",+ session_id: "sess-xyz",+ model: "claude-opus-4-7",+ usage: { input_tokens: 100, output_tokens: 50 },+ });+ });+});diff --git a/src/server/actions/crons.test.ts b/src/server/actions/crons.test.tsnew file mode 100644index 00000000..28569364--- /dev/null+++ b/src/server/actions/crons.test.ts@@ -0,0 +1,313 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),+}));++const createCronMock = vi.fn();+const disableCronMock = vi.fn();+const enableCronMock = vi.fn();+const removeCronMock = vi.fn();+const invalidateCronCacheMock = vi.fn();+vi.mock("@/server/openclaw/crons", () => ({+ createCron: (...a: unknown[]) => createCronMock(...a),+ disableCron: (...a: unknown[]) => disableCronMock(...a),+ enableCron: (...a: unknown[]) => enableCronMock(...a),+ removeCron: (...a: unknown[]) => removeCronMock(...a),+ invalidateCronCache: () => invalidateCronCacheMock(),+}));++const updateCronMessageMock = vi.fn();+vi.mock("@/server/openclaw/gateway-rpc", () => ({+ updateCronMessage: (...a: unknown[]) => updateCronMessageMock(...a),+}));++const logAgentActionMock = vi.fn();+vi.mock("@/server/db/agent-actions", () => ({+ logAgentAction: (...a: unknown[]) => logAgentActionMock(...a),+}));++import {+ deleteCronAction,+ pauseCronAction,+ resumeCronAction,+ scheduleCronAction,+ updateCronPromptAction,+} from "./crons";++describe("scheduleCronAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ createCronMock.mockResolvedValue({ id: "cron-1", name: "demo/google-ads/morning" });+ });++ it("creates a cron with kind=cron, logs the action, and revalidates", async () => {+ const out = await scheduleCronAction({+ project_slug: "demo",+ specialist: "google_ads",+ name: "Morning Audit",+ schedule_kind: "cron",+ schedule_value: "0 9 * * *",+ tz: "UTC",+ brief: "Run a daily account health check.",+ });++ expect(out).toEqual({ ok: true, cron_id: "cron-1", cron_name: "demo/google-ads/morning" });+ expect(createCronMock).toHaveBeenCalledWith({+ project_slug: "demo",+ agent_slug: "google-ads",+ agent_full_id: "demo-google-ads",+ cron_name: "morning-audit",+ schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },+ message: "Run a daily account health check.",+ });+ expect(logAgentActionMock).toHaveBeenCalledWith({+ project_slug: "demo",+ agent_id: "demo-google-ads",+ action_type: "cron_created",+ summary: "Scheduled 'morning-audit' (cron 0 9 * * *)",+ payload: {+ cron_id: "cron-1",+ cron_name: "demo/google-ads/morning",+ brief: "Run a daily account health check.",+ },+ });+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("creates a cron with kind=every (no tz passthrough)", async () => {+ await scheduleCronAction({+ project_slug: "demo",+ specialist: "seo",+ name: "Hourly Audit",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: "Hourly SEO scan.",+ });+ expect(createCronMock).toHaveBeenCalledWith(+ expect.objectContaining({+ agent_slug: "seo",+ agent_full_id: "demo-seo",+ schedule: { kind: "every", duration: "1h" },+ }),+ );+ });++ it("converts underscore specialist key to hyphenated agent_slug", async () => {+ await scheduleCronAction({+ project_slug: "demo",+ specialist: "google_ads",+ name: "X",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: "x",+ });+ const call = createCronMock.mock.calls[0]?.[0] as Record<string, unknown>;+ expect(call.agent_slug).toBe("google-ads");+ expect(call.agent_full_id).toBe("demo-google-ads");+ });++ it("trims brief whitespace before sending and logging", async () => {+ await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: "hello",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: " actual prompt ",+ });+ expect(createCronMock.mock.calls[0]?.[0].message).toBe("actual prompt");+ });++ it("trims schedule_value whitespace", async () => {+ await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: "hello",+ schedule_kind: "cron",+ schedule_value: " 0 9 * * * ",+ brief: "b",+ });+ expect(createCronMock.mock.calls[0]?.[0].schedule).toEqual({+ kind: "cron",+ expr: "0 9 * * *",+ tz: undefined,+ });+ });++ it("returns ok:false when the name cannot be slugified", async () => {+ const out = await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: " ",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: "b",+ });+ expect(out.ok).toBe(false);+ if (out.ok) return;+ expect(out.error).toMatch(/Invalid name/);+ expect(createCronMock).not.toHaveBeenCalled();+ });++ it("returns ok:false when brief is empty after trimming", async () => {+ const out = await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: "valid",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: " ",+ });+ expect(out).toEqual({ ok: false, error: "Brief is required." });+ expect(createCronMock).not.toHaveBeenCalled();+ });++ it("returns ok:false when schedule_value is empty after trimming", async () => {+ const out = await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: "valid",+ schedule_kind: "every",+ schedule_value: " ",+ brief: "brief",+ });+ expect(out).toEqual({ ok: false, error: "Schedule is required." });+ expect(createCronMock).not.toHaveBeenCalled();+ });++ it("returns ok:false with Error message when createCron throws", async () => {+ createCronMock.mockRejectedValue(new Error("openclaw down"));+ const out = await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: "valid",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: "b",+ });+ expect(out).toEqual({ ok: false, error: "openclaw down" });+ expect(logAgentActionMock).not.toHaveBeenCalled();+ });++ it("stringifies non-Error rejections from createCron", async () => {+ createCronMock.mockRejectedValue("rope-burn");+ const out = await scheduleCronAction({+ project_slug: "demo",+ specialist: "cmo",+ name: "valid",+ schedule_kind: "every",+ schedule_value: "1h",+ brief: "b",+ });+ expect(out).toEqual({ ok: false, error: "rope-burn" });+ });+});++describe("pauseCronAction", () => {+ beforeEach(() => vi.clearAllMocks());++ it("disables the cron and revalidates layout", async () => {+ disableCronMock.mockResolvedValue(undefined);+ const out = await pauseCronAction("cron-1");+ expect(out).toEqual({ ok: true });+ expect(disableCronMock).toHaveBeenCalledWith("cron-1");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns ok:false with the Error message when disableCron throws", async () => {+ disableCronMock.mockRejectedValue(new Error("nope"));+ const out = await pauseCronAction("cron-1");+ expect(out).toEqual({ ok: false, error: "nope" });+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });++ it("stringifies non-Error rejections", async () => {+ disableCronMock.mockRejectedValue(42);+ const out = await pauseCronAction("cron-1");+ expect(out).toEqual({ ok: false, error: "42" });+ });+});++describe("resumeCronAction", () => {+ beforeEach(() => vi.clearAllMocks());++ it("enables the cron and revalidates layout", async () => {+ enableCronMock.mockResolvedValue(undefined);+ const out = await resumeCronAction("cron-1");+ expect(out).toEqual({ ok: true });+ expect(enableCronMock).toHaveBeenCalledWith("cron-1");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns ok:false with the Error message when enableCron throws", async () => {+ enableCronMock.mockRejectedValue(new Error("auth"));+ const out = await resumeCronAction("cron-1");+ expect(out).toEqual({ ok: false, error: "auth" });+ });++ it("stringifies non-Error rejections", async () => {+ enableCronMock.mockRejectedValue("disconnected");+ const out = await resumeCronAction("cron-1");+ expect(out).toEqual({ ok: false, error: "disconnected" });+ });+});++describe("deleteCronAction", () => {+ beforeEach(() => vi.clearAllMocks());++ it("removes the cron and revalidates layout", async () => {+ removeCronMock.mockResolvedValue(undefined);+ const out = await deleteCronAction("cron-1");+ expect(out).toEqual({ ok: true });+ expect(removeCronMock).toHaveBeenCalledWith("cron-1");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns ok:false with the Error message when removeCron throws", async () => {+ removeCronMock.mockRejectedValue(new Error("missing"));+ const out = await deleteCronAction("cron-1");+ expect(out).toEqual({ ok: false, error: "missing" });+ });++ it("stringifies non-Error rejections", async () => {+ removeCronMock.mockRejectedValue("io-err");+ const out = await deleteCronAction("cron-1");+ expect(out).toEqual({ ok: false, error: "io-err" });+ });+});++describe("updateCronPromptAction", () => {+ beforeEach(() => vi.clearAllMocks());++ it("rejects empty (whitespace-only) messages without calling the gateway", async () => {+ const out = await updateCronPromptAction("cron-1", " \n\t");+ expect(out).toEqual({ ok: false, error: "Prompt cannot be empty." });+ expect(updateCronMessageMock).not.toHaveBeenCalled();+ expect(invalidateCronCacheMock).not.toHaveBeenCalled();+ });++ it("trims the message before sending to the gateway", async () => {+ updateCronMessageMock.mockResolvedValue(undefined);+ const out = await updateCronPromptAction("cron-1", " hello world ");+ expect(out).toEqual({ ok: true });+ expect(updateCronMessageMock).toHaveBeenCalledWith("cron-1", "hello world");+ expect(invalidateCronCacheMock).toHaveBeenCalledTimes(1);+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns the Error message when updateCronMessage throws (and skips cache invalidation)", async () => {+ updateCronMessageMock.mockRejectedValue(new Error("rpc error"));+ const out = await updateCronPromptAction("cron-1", "valid");+ expect(out).toEqual({ ok: false, error: "rpc error" });+ expect(invalidateCronCacheMock).not.toHaveBeenCalled();+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });++ it("stringifies non-Error rejections", async () => {+ updateCronMessageMock.mockRejectedValue("string-err");+ const out = await updateCronPromptAction("cron-1", "valid");+ expect(out).toEqual({ ok: false, error: "string-err" });+ });+});diff --git a/src/server/actions/mcp.test.ts b/src/server/actions/mcp.test.tsnew file mode 100644index 00000000..fc86fa7c--- /dev/null+++ b/src/server/actions/mcp.test.ts@@ -0,0 +1,378 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),+}));++const headerGetMock = vi.fn();+vi.mock("next/headers", () => ({+ headers: async () => ({+ get: (...args: unknown[]) => headerGetMock(...args),+ }),+}));++const getActiveProjectMock = vi.fn();+vi.mock("@/server/active-project", () => ({+ getActiveProject: (...args: unknown[]) => getActiveProjectMock(...args),+}));++const setPendingMock = vi.fn();+vi.mock("@/server/mcp-pending", () => ({+ setPending: (...args: unknown[]) => setPendingMock(...args),+}));++const runDisconnectMock = vi.fn();+vi.mock("@/server/mcp-state", () => ({+ disconnectMcp: (...args: unknown[]) => runDisconnectMock(...args),+}));++// Use the real mcp-catalog so storedMcpKey + mcpSpecByKey work.++import { disconnectMcpAction, startMcpConnect } from "./mcp";++function project(slug = "acme") {+ return {+ id: "uuid",+ slug,+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ // Default header values; individual tests override as needed.+ headerGetMock.mockImplementation((name: string) => {+ if (name === "host") return "localhost:3326";+ return null;+ });+});++describe("startMcpConnect", () => {+ let fetchMock: ReturnType<typeof vi.fn>;+ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ });++ it("rejects unknown mcp_key", async () => {+ const r = await startMcpConnect({ mcp_key: "not-a-real-mcp" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Unknown MCP key/);+ });++ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/No active project/);+ });++ it("surfaces discovery failures", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock.mockResolvedValueOnce({+ ok: false,+ status: 404,+ json: async () => ({}),+ });+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Discovery failed/);+ expect(r.error).toMatch(/HTTP 404/);+ });++ it("surfaces missing authorization_servers in protected-resource doc", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock.mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/no authorization_servers/);+ });++ it("surfaces incomplete AS metadata", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com/"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ // missing token_endpoint + registration_endpoint+ }),+ });+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/AS metadata missing endpoints/);+ });++ it("surfaces DCR failures with status code + text snippet", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ })+ .mockResolvedValueOnce({+ ok: false,+ status: 400,+ text: async () => "bad payload",+ });+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Registration failed/);+ expect(r.error).toMatch(/DCR 400/);+ });++ it("surfaces DCR response missing client_id", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({}),+ });+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/missing client_id/);+ });++ it("happy path: stashes pending flow and returns authorize URL with PKCE", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com/"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ client_id: "client-xyz", client_secret: "shh" }),+ });+ const r = await startMcpConnect({+ mcp_key: "notfair-googleads",+ return_to: "/chat/foo",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ const url = new URL(r.authorize_url);+ expect(url.origin).toBe("https://as.example.com");+ expect(url.pathname).toBe("/authorize");+ expect(url.searchParams.get("response_type")).toBe("code");+ expect(url.searchParams.get("client_id")).toBe("client-xyz");+ expect(url.searchParams.get("redirect_uri")).toBe(+ "http://localhost:3326/api/mcp-oauth/callback",+ );+ expect(url.searchParams.get("code_challenge_method")).toBe("S256");+ expect(url.searchParams.get("code_challenge")).toMatch(/^[A-Za-z0-9_-]+$/);+ expect(url.searchParams.get("state")).toMatch(/^[A-Za-z0-9_-]+$/);+ expect(url.searchParams.get("resource")).toBe(+ "https://notfair.co/api/mcp/google_ads",+ );++ expect(setPendingMock).toHaveBeenCalledTimes(1);+ const [state, flow] = setPendingMock.mock.calls[0]! as [+ string,+ Record<string, unknown>,+ ];+ expect(state).toBe(url.searchParams.get("state"));+ expect(flow).toMatchObject({+ catalog_key: "notfair-googleads",+ stored_key: "acme-notfair-googleads",+ issuer: "https://as.example.com",+ token_endpoint: "https://as.example.com/token",+ client_id: "client-xyz",+ client_secret: "shh",+ redirect_uri: "http://localhost:3326/api/mcp-oauth/callback",+ project_slug: "acme",+ return_to: "/chat/foo",+ });+ expect(typeof flow.code_verifier).toBe("string");+ expect((flow.code_verifier as string).length).toBeGreaterThan(50);+ });++ it("uses x-forwarded-proto + x-forwarded-host when behind a proxy", async () => {+ headerGetMock.mockImplementation((name: string) => {+ if (name === "x-forwarded-proto") return "https";+ if (name === "x-forwarded-host") return "app.example.com";+ if (name === "host") return "internal-host";+ return null;+ });+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ client_id: "c" }),+ });+ const r = await startMcpConnect({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.authorize_url).toMatch(/redirect_uri=https%3A%2F%2Fapp\.example\.com/);+ });++ it("throws-as-error path: missing host header surfaces as discovery error", async () => {+ headerGetMock.mockImplementation(() => null);+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ });+ await expect(+ startMcpConnect({ mcp_key: "notfair-googleads" }),+ ).rejects.toThrow(/Could not derive origin/);+ });++ it("rejects open-redirect return_to (absolute URL)", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ client_id: "c" }),+ });+ await startMcpConnect({+ mcp_key: "notfair-googleads",+ return_to: "https://evil.example.com/steal",+ });+ const [, flow] = setPendingMock.mock.calls[0]!;+ expect((flow as { return_to: string | undefined }).return_to).toBeUndefined();+ });++ it("rejects open-redirect return_to (protocol-relative)", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ fetchMock+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ authorization_servers: ["https://as.example.com"] }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({+ authorization_endpoint: "https://as.example.com/authorize",+ token_endpoint: "https://as.example.com/token",+ registration_endpoint: "https://as.example.com/register",+ }),+ })+ .mockResolvedValueOnce({+ ok: true,+ json: async () => ({ client_id: "c" }),+ });+ await startMcpConnect({+ mcp_key: "notfair-googleads",+ return_to: "//evil.example.com/x",+ });+ const [, flow] = setPendingMock.mock.calls[0]!;+ expect((flow as { return_to: string | undefined }).return_to).toBeUndefined();+ });+});++describe("disconnectMcpAction", () => {+ it("rejects when no active project", async () => {+ getActiveProjectMock.mockResolvedValueOnce(null);+ const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/No active project/);+ });++ it("calls disconnectMcp with project-scoped key and revalidates layout", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ runDisconnectMock.mockResolvedValueOnce(undefined);+ const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(true);+ expect(runDisconnectMock).toHaveBeenCalledWith("acme-notfair-googleads");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("returns error string when disconnect throws an Error", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ runDisconnectMock.mockRejectedValueOnce(new Error("openclaw blew up"));+ const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/openclaw blew up/);+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });++ it("returns error string when disconnect throws a non-Error", async () => {+ getActiveProjectMock.mockResolvedValueOnce(project());+ runDisconnectMock.mockRejectedValueOnce("string thrown");+ const r = await disconnectMcpAction({ mcp_key: "notfair-googleads" });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/string thrown/);+ });+});diff --git a/src/server/actions/projects.test.ts b/src/server/actions/projects.test.tsnew file mode 100644index 00000000..d4228485--- /dev/null+++ b/src/server/actions/projects.test.ts@@ -0,0 +1,683 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),+}));++const redirectMock = vi.fn((_target: string) => {+ // Mimic Next.js: redirect() throws an internal signal so callers stop.+ throw new Error("NEXT_REDIRECT");+});+vi.mock("next/navigation", () => ({+ redirect: (...args: unknown[]) => redirectMock(...(args as [string])),+}));++const cookieGetMock = vi.fn();+const cookieSetMock = vi.fn();+const cookieDeleteMock = vi.fn();+vi.mock("next/headers", () => ({+ cookies: async () => ({+ get: (...args: unknown[]) => cookieGetMock(...args),+ set: (...args: unknown[]) => cookieSetMock(...args),+ delete: (...args: unknown[]) => cookieDeleteMock(...args),+ }),+}));++const archiveProjectMock = vi.fn();+const changeProjectSlugMock = vi.fn();+const createProjectMock = vi.fn();+const deleteProjectRowMock = vi.fn();+const getProjectMock = vi.fn();+const renameProjectMock = vi.fn();+vi.mock("@/server/db/projects", () => ({+ archiveProject: (...args: unknown[]) => archiveProjectMock(...args),+ changeProjectSlug: (...args: unknown[]) => changeProjectSlugMock(...args),+ createProject: (...args: unknown[]) => createProjectMock(...args),+ deleteProjectRow: (...args: unknown[]) => deleteProjectRowMock(...args),+ getProject: (...args: unknown[]) => getProjectMock(...args),+ renameProject: (...args: unknown[]) => renameProjectMock(...args),+}));++const clearActiveProjectMock = vi.fn();+const setActiveProjectMock = vi.fn();+vi.mock("@/server/active-project", () => ({+ clearActiveProject: (...args: unknown[]) => clearActiveProjectMock(...args),+ setActiveProject: (...args: unknown[]) => setActiveProjectMock(...args),+}));++const ensureProjectAgentsMock = vi.fn();+vi.mock("@/server/agent-templates", () => ({+ ensureProjectAgents: (...args: unknown[]) => ensureProjectAgentsMock(...args),+}));++const startProvisioningMock = vi.fn();+const clearProvisioningMock = vi.fn();+vi.mock("@/server/onboarding/provisioning-state", () => ({+ startProvisioning: (...args: unknown[]) => startProvisioningMock(...args),+ clearProvisioning: (...args: unknown[]) => clearProvisioningMock(...args),+}));++const listProjectAgentsMock = vi.fn();+const readAgentMetaMock = vi.fn();+vi.mock("@/server/agent-meta", () => ({+ listProjectAgents: (...args: unknown[]) => listProjectAgentsMock(...args),+ readAgentMeta: (...args: unknown[]) => readAgentMetaMock(...args),+}));++const cascadeDeleteAgentMock = vi.fn();+const relocateAgentMock = vi.fn();+vi.mock("@/server/actions/agents", () => ({+ cascadeDeleteAgent: (...args: unknown[]) => cascadeDeleteAgentMock(...args),+ relocateAgent: (...args: unknown[]) => relocateAgentMock(...args),+}));++const listCronsForProjectMock = vi.fn();+const disableCronMock = vi.fn();+vi.mock("@/server/openclaw/crons", () => ({+ listCronsForProject: (...args: unknown[]) => listCronsForProjectMock(...args),+ disableCron: (...args: unknown[]) => disableCronMock(...args),+}));++const logAgentActionMock = vi.fn();+vi.mock("@/server/db/agent-actions", () => ({+ logAgentAction: (...args: unknown[]) => logAgentActionMock(...args),+}));++const getProjectDeletionSummaryMock = vi.fn();+vi.mock("@/server/openclaw/project-delete", () => ({+ getProjectDeletionSummary: (...args: unknown[]) =>+ getProjectDeletionSummaryMock(...args),+}));++const disconnectMcpMock = vi.fn();+vi.mock("@/server/mcp-state", () => ({+ disconnectMcp: (...args: unknown[]) => disconnectMcpMock(...args),+}));++// mcp-catalog: keep real implementation so storedMcpKey works.++import {+ archiveProjectAction,+ createProjectAction,+ createProjectForOnboardingAction,+ deleteProjectAction,+ getProjectDeletionSummaryAction,+ renameProjectAction,+ renameProjectFullAction,+ reprovisionAgentsAction,+ switchProjectAction,+} from "./projects";++function project(overrides: Partial<{ slug: string; display_name: string }> = {}) {+ return {+ id: "uuid",+ slug: "acme",+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ ...overrides,+ };+}++function fd(obj: Record<string, string>): FormData {+ const f = new FormData();+ for (const [k, v] of Object.entries(obj)) f.append(k, v);+ return f;+}++beforeEach(() => {+ vi.clearAllMocks();+ ensureProjectAgentsMock.mockResolvedValue({+ created: ["acme-cmo"],+ existed: [],+ failed: [],+ });+});++describe("createProjectAction", () => {+ it("throws when display_name is empty", async () => {+ await expect(createProjectAction(fd({ display_name: " " }))).rejects.toThrow(+ /Please enter a project name/,+ );+ });++ it("throws when createProject returns !ok", async () => {+ createProjectMock.mockReturnValueOnce({ ok: false, reason: "slug reserved" });+ await expect(createProjectAction(fd({ display_name: "api" }))).rejects.toThrow(+ /slug reserved/,+ );+ });++ it("redirects to / on success and triggers async provisioning", async () => {+ createProjectMock.mockReturnValueOnce({ ok: true, project: project() });+ await expect(+ createProjectAction(fd({ display_name: "Acme" })),+ ).rejects.toThrow(/NEXT_REDIRECT/);+ expect(redirectMock).toHaveBeenCalledWith("/");+ expect(ensureProjectAgentsMock).toHaveBeenCalledWith("acme", ["cmo", "google_ads"]);+ expect(startProvisioningMock).toHaveBeenCalled();+ expect(setActiveProjectMock).toHaveBeenCalledWith("acme");+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("logs project_created after provisioning resolves", async () => {+ createProjectMock.mockReturnValueOnce({ ok: true, project: project() });+ ensureProjectAgentsMock.mockResolvedValueOnce({+ created: ["acme-cmo", "acme-google-ads"],+ existed: [],+ failed: [],+ });+ await createProjectAction(fd({ display_name: "Acme" })).catch(() => {});+ // Wait for any microtask-queued .then() to drain.+ await new Promise((r) => setTimeout(r, 0));+ expect(logAgentActionMock).toHaveBeenCalledWith(+ expect.objectContaining({+ project_slug: "acme",+ agent_id: "system",+ action_type: "project_created",+ }),+ );+ });++ it("provisioning rejection is swallowed (console.error)", async () => {+ createProjectMock.mockReturnValueOnce({ ok: true, project: project() });+ ensureProjectAgentsMock.mockRejectedValueOnce(new Error("rpc down"));+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ await createProjectAction(fd({ display_name: "Acme" })).catch(() => {});+ await new Promise((r) => setTimeout(r, 0));+ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });+});++describe("createProjectForOnboardingAction", () => {+ it("returns error result when display_name blank", async () => {+ const r = await createProjectForOnboardingAction(fd({ display_name: "" }));+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Please enter a project name/);+ });++ it("returns error result when createProject fails", async () => {+ createProjectMock.mockReturnValueOnce({ ok: false, reason: "slug taken" });+ const r = await createProjectForOnboardingAction(fd({ display_name: "X" }));+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/slug taken/);+ });++ it("returns slug + display_name on success without redirecting", async () => {+ createProjectMock.mockReturnValueOnce({ ok: true, project: project() });+ const r = await createProjectForOnboardingAction(+ fd({ display_name: "Acme" }),+ );+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data).toEqual({ slug: "acme", display_name: "Acme" });+ expect(redirectMock).not.toHaveBeenCalled();+ expect(startProvisioningMock).toHaveBeenCalled();+ });+});++describe("reprovisionAgentsAction", () => {+ it("returns ok+result on success and revalidates", async () => {+ ensureProjectAgentsMock.mockResolvedValueOnce({+ created: ["a"],+ existed: ["b"],+ failed: [],+ });+ const r = await reprovisionAgentsAction("acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.created).toEqual(["a"]);+ expect(r.existed).toEqual(["b"]);+ expect(revalidatePathMock).toHaveBeenCalled();+ });++ it("returns error on rejection", async () => {+ ensureProjectAgentsMock.mockRejectedValueOnce(new Error("boom"));+ const r = await reprovisionAgentsAction("acme");+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/boom/);+ });+});++describe("switchProjectAction", () => {+ it("sets active project + revalidates", async () => {+ const r = await switchProjectAction("acme");+ expect(r.ok).toBe(true);+ expect(setActiveProjectMock).toHaveBeenCalledWith("acme");+ expect(revalidatePathMock).toHaveBeenCalled();+ });+});++describe("archiveProjectAction", () => {+ it("returns error when archiveProject returns null", async () => {+ archiveProjectMock.mockReturnValueOnce(null);+ const r = await archiveProjectAction("missing");+ expect(r.ok).toBe(false);+ });++ it("halts every enabled cron and counts disabled successes", async () => {+ archiveProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({+ groups: [+ {+ agent: "acme-foo",+ crons: [+ { id: "c1", disabled: false },+ { id: "c2", disabled: true },+ { id: "c3", disabled: false },+ ],+ },+ ],+ });+ disableCronMock.mockResolvedValueOnce(undefined).mockResolvedValueOnce(undefined);+ const r = await archiveProjectAction("acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.halted_crons).toBe(2);+ expect(disableCronMock).toHaveBeenCalledTimes(2);+ expect(logAgentActionMock).toHaveBeenCalled();+ });++ it("tolerates listCronsForProject failure (no crons halted)", async () => {+ archiveProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockRejectedValueOnce(new Error("cron down"));+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ const r = await archiveProjectAction("acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.halted_crons).toBe(0);+ spy.mockRestore();+ });++ it("tolerates individual disable failures and counts the rest", async () => {+ archiveProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({+ groups: [+ {+ agent: "acme-foo",+ crons: [+ { id: "c1", disabled: false },+ { id: "c2", disabled: false },+ ],+ },+ ],+ });+ disableCronMock+ .mockRejectedValueOnce(new Error("nope"))+ .mockResolvedValueOnce(undefined);+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ const r = await archiveProjectAction("acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.halted_crons).toBe(1);+ spy.mockRestore();+ });+});++describe("renameProjectAction", () => {+ it("returns error when renameProject returns null", async () => {+ renameProjectMock.mockReturnValueOnce(null);+ const r = await renameProjectAction("acme", "");+ expect(r.ok).toBe(false);+ });++ it("returns ok + revalidates on success", async () => {+ renameProjectMock.mockReturnValueOnce(project({ display_name: "Renamed" }));+ const r = await renameProjectAction("acme", "Renamed");+ expect(r.ok).toBe(true);+ expect(revalidatePathMock).toHaveBeenCalled();+ });+});++describe("renameProjectFullAction", () => {+ it("rejects when project not found", async () => {+ getProjectMock.mockReturnValueOnce(null);+ const r = await renameProjectFullAction({+ current_slug: "missing",+ new_display_name: "X",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/not found/);+ });++ it("rejects empty new display_name", async () => {+ getProjectMock.mockReturnValueOnce(project());+ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: " ",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/empty/);+ });++ it("rejects when slugify fails", async () => {+ getProjectMock.mockReturnValueOnce(project());+ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "@@@",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Invalid name/);+ });++ it("no-op when slug+display name are unchanged", async () => {+ getProjectMock.mockReturnValueOnce(project({ display_name: "Acme" }));+ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "Acme",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.full_rename).toBe(false);+ expect(renameProjectMock).not.toHaveBeenCalled();+ });++ it("display-name-only path when slug stays the same", async () => {+ getProjectMock.mockReturnValueOnce(project({ display_name: "Acme" }));+ // "ACME!" → "acme"+ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "ACME!",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.full_rename).toBe(false);+ expect(r.data.display_name).toBe("ACME!");+ expect(renameProjectMock).toHaveBeenCalledWith("acme", "ACME!");+ });++ it("rejects when destination slug exists", async () => {+ getProjectMock+ .mockReturnValueOnce(project())+ .mockReturnValueOnce(project({ slug: "newslug" }));+ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "Newslug",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/already exists/);+ });++ it("full rename relocates each agent and migrates DB rows + repoints cookie", async () => {+ getProjectMock+ .mockReturnValueOnce(project()) // current lookup+ .mockReturnValueOnce(null); // destination uniqueness check+ listProjectAgentsMock.mockResolvedValueOnce([+ {+ agent_id: "acme-cmo",+ slug: "cmo",+ display_name: "CMO",+ template_key: "cmo",+ is_template_default: true,+ },+ ]);+ readAgentMetaMock.mockReturnValueOnce({+ agent_id: "acme-cmo",+ project_slug: "acme",+ slug: "cmo",+ display_name: "CMO",+ created_at: "now",+ source_agent_id: "src",+ });+ relocateAgentMock.mockResolvedValueOnce({+ new_agent_id: "newslug-cmo",+ new_slug: "cmo",+ });+ changeProjectSlugMock.mockReturnValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce({ value: "acme" });++ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "Newslug",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.full_rename).toBe(true);+ expect(r.data.slug).toBe("newslug");+ expect(r.data.agents_relocated).toEqual(["acme-cmo"]);+ expect(r.data.agents_failed).toEqual([]);+ expect(changeProjectSlugMock).toHaveBeenCalledWith("acme", "newslug", "Newslug");+ expect(setActiveProjectMock).toHaveBeenCalledWith("newslug");+ });++ it("does NOT repoint cookie when it wasn't pointing at this project", async () => {+ getProjectMock.mockReturnValueOnce(project()).mockReturnValueOnce(null);+ listProjectAgentsMock.mockResolvedValueOnce([]);+ changeProjectSlugMock.mockReturnValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce({ value: "other" });++ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "Newslug",+ });+ expect(r.ok).toBe(true);+ expect(setActiveProjectMock).not.toHaveBeenCalled();+ });++ it("collects per-agent failures rather than aborting", async () => {+ getProjectMock.mockReturnValueOnce(project()).mockReturnValueOnce(null);+ listProjectAgentsMock.mockResolvedValueOnce([+ {+ agent_id: "acme-cmo",+ slug: "cmo",+ display_name: "CMO",+ is_template_default: true,+ },+ {+ agent_id: "acme-ga",+ slug: "ga",+ display_name: "GA",+ is_template_default: true,+ },+ ]);+ readAgentMetaMock.mockReturnValue(null);+ relocateAgentMock+ .mockResolvedValueOnce({ new_agent_id: "newslug-cmo", new_slug: "cmo" })+ .mockRejectedValueOnce(new Error("relocate failed"));+ changeProjectSlugMock.mockReturnValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce(undefined);++ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "Newslug",+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.agents_relocated).toEqual(["acme-cmo"]);+ expect(r.data.agents_failed).toEqual([+ { agent_id: "acme-ga", error: "relocate failed" },+ ]);+ });++ it("surfaces changeProjectSlug failure with cleanup-needed messaging", async () => {+ getProjectMock.mockReturnValueOnce(project()).mockReturnValueOnce(null);+ listProjectAgentsMock.mockResolvedValueOnce([]);+ changeProjectSlugMock.mockImplementationOnce(() => {+ throw new Error("FK violation");+ });+ const r = await renameProjectFullAction({+ current_slug: "acme",+ new_display_name: "Newslug",+ });+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/DB migration failed/);+ expect(r.error).toMatch(/FK violation/);+ });+});++describe("getProjectDeletionSummaryAction", () => {+ it("rejects when project not found", async () => {+ getProjectMock.mockReturnValueOnce(null);+ const r = await getProjectDeletionSummaryAction("missing");+ expect(r.ok).toBe(false);+ });++ it("returns the summary on success", async () => {+ getProjectMock.mockReturnValueOnce(project());+ getProjectDeletionSummaryMock.mockResolvedValueOnce({+ project_slug: "acme",+ agents: [],+ mcps: [],+ totals: { agents: 0, threads: 0, crons: 0, mcps: 0 },+ });+ const r = await getProjectDeletionSummaryAction("acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.project_slug).toBe("acme");+ });++ it("surfaces summary errors", async () => {+ getProjectMock.mockReturnValueOnce(project());+ getProjectDeletionSummaryMock.mockRejectedValueOnce(new Error("inventory failed"));+ const r = await getProjectDeletionSummaryAction("acme");+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/inventory failed/);+ });+});++describe("deleteProjectAction", () => {+ it("rejects when confirmation slug mismatches", async () => {+ const r = await deleteProjectAction("acme", "other");+ expect(r.ok).toBe(false);+ if (r.ok) return;+ expect(r.error).toMatch(/Confirmation slug/);+ });++ it("rejects when project not found", async () => {+ getProjectMock.mockReturnValueOnce(null);+ const r = await deleteProjectAction("acme", "acme");+ expect(r.ok).toBe(false);+ });++ it("cascades agents, mcps, db row, clears cookie when active", async () => {+ getProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({+ groups: [+ {+ agent: "acme-cmo",+ crons: [+ { id: "c1", agent_id: "acme-cmo" },+ { id: "c2", agent_id: "acme-cmo" },+ ],+ },+ ],+ });+ listProjectAgentsMock.mockResolvedValueOnce([+ { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },+ ]);+ cascadeDeleteAgentMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ crons_removed: 2,+ crons_failed: 0,+ openclaw_deleted: true,+ meta_removed: true,+ });+ disconnectMcpMock.mockResolvedValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce({ value: "acme" });++ const r = await deleteProjectAction("acme", "acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.agents).toEqual(["acme-cmo"]);+ expect(r.data.agentsFailed).toEqual([]);+ expect(r.data.crons).toBe(2);+ expect(r.data.mcps).toBe(1);+ expect(deleteProjectRowMock).toHaveBeenCalledWith("acme");+ expect(clearProvisioningMock).toHaveBeenCalledWith("acme");+ expect(clearActiveProjectMock).toHaveBeenCalled();+ expect(cascadeDeleteAgentMock).toHaveBeenCalledWith({+ agent_id: "acme-cmo",+ cronIds: ["c1", "c2"],+ });+ });++ it("does NOT clear active-project cookie when it points elsewhere", async () => {+ getProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });+ listProjectAgentsMock.mockResolvedValueOnce([]);+ disconnectMcpMock.mockResolvedValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce({ value: "other" });+ const r = await deleteProjectAction("acme", "acme");+ expect(r.ok).toBe(true);+ expect(clearActiveProjectMock).not.toHaveBeenCalled();+ });++ it("collects failed agents into agentsFailed and continues", async () => {+ getProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });+ listProjectAgentsMock.mockResolvedValueOnce([+ { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },+ { agent_id: "acme-ga", slug: "ga", display_name: "GA", is_template_default: true },+ ]);+ cascadeDeleteAgentMock+ .mockResolvedValueOnce({+ agent_id: "acme-cmo",+ crons_removed: 0,+ crons_failed: 0,+ openclaw_deleted: true,+ meta_removed: true,+ })+ .mockRejectedValueOnce(new Error("delete exploded"));+ disconnectMcpMock.mockResolvedValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce(undefined);++ const r = await deleteProjectAction("acme", "acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.agents).toEqual(["acme-cmo"]);+ expect(r.data.agentsFailed).toEqual([+ { agentId: "acme-ga", error: "delete exploded" },+ ]);+ });++ it("counts MCP disconnect failures into mcpsFailed", async () => {+ getProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockResolvedValueOnce({ groups: [] });+ listProjectAgentsMock.mockResolvedValueOnce([]);+ disconnectMcpMock.mockRejectedValueOnce(new Error("can't reach openclaw"));+ cookieGetMock.mockReturnValueOnce(undefined);+ const spy = vi.spyOn(console, "warn").mockImplementation(() => {});+ const r = await deleteProjectAction("acme", "acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.data.mcps).toBe(0);+ expect(r.data.mcpsFailed).toBe(1);+ spy.mockRestore();+ });++ it("continues when listCronsForProject fails (cronsByAgent empty)", async () => {+ getProjectMock.mockReturnValueOnce(project());+ listCronsForProjectMock.mockRejectedValueOnce(new Error("cron service down"));+ listProjectAgentsMock.mockResolvedValueOnce([+ { agent_id: "acme-cmo", slug: "cmo", display_name: "CMO", is_template_default: true },+ ]);+ cascadeDeleteAgentMock.mockResolvedValueOnce({+ agent_id: "acme-cmo",+ crons_removed: 0,+ crons_failed: 0,+ openclaw_deleted: true,+ meta_removed: true,+ });+ disconnectMcpMock.mockResolvedValueOnce(undefined);+ cookieGetMock.mockReturnValueOnce(undefined);+ const r = await deleteProjectAction("acme", "acme");+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(cascadeDeleteAgentMock).toHaveBeenCalledWith({+ agent_id: "acme-cmo",+ cronIds: [],+ });+ });+});diff --git a/src/server/actions/skills.test.ts b/src/server/actions/skills.test.tsnew file mode 100644index 00000000..b686abd9--- /dev/null+++ b/src/server/actions/skills.test.ts@@ -0,0 +1,61 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),+}));++const setSkillEnabledMock = vi.fn();+vi.mock("@/server/openclaw/gateway-rpc", () => ({+ setSkillEnabled: (...a: unknown[]) => setSkillEnabledMock(...a),+}));++import { setSkillEnabledAction } from "./skills";++describe("setSkillEnabledAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns ok:false when skillKey is empty (no gateway call)", async () => {+ const out = await setSkillEnabledAction("", true, "demo-google-ads");+ expect(out).toEqual({ ok: false, error: "skillKey is required" });+ expect(setSkillEnabledMock).not.toHaveBeenCalled();+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });++ it("calls setSkillEnabled with the provided key + enabled flag and revalidates layout", async () => {+ setSkillEnabledMock.mockResolvedValue(undefined);+ const out = await setSkillEnabledAction("toprank:google-ads", true, "demo-google-ads");+ expect(out).toEqual({ ok: true });+ expect(setSkillEnabledMock).toHaveBeenCalledWith("toprank:google-ads", true);+ expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");+ });++ it("passes enabled=false through to the gateway when disabling a skill", async () => {+ setSkillEnabledMock.mockResolvedValue(undefined);+ const out = await setSkillEnabledAction("toprank:meta-ads", false, "demo-meta");+ expect(out).toEqual({ ok: true });+ expect(setSkillEnabledMock).toHaveBeenCalledWith("toprank:meta-ads", false);+ });++ it("captures gateway Error and surfaces its message (no revalidate)", async () => {+ setSkillEnabledMock.mockRejectedValue(new Error("gateway down"));+ const out = await setSkillEnabledAction("k", true, "a");+ expect(out).toEqual({ ok: false, error: "gateway down" });+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });++ it("stringifies non-Error rejections into the error field", async () => {+ setSkillEnabledMock.mockRejectedValue("plain-string-reason");+ const out = await setSkillEnabledAction("k", true, "a");+ expect(out).toEqual({ ok: false, error: "plain-string-reason" });+ });++ it("ignores agentSlug (workspace-wide config) but still succeeds", async () => {+ setSkillEnabledMock.mockResolvedValue(undefined);+ const out = await setSkillEnabledAction("k", true, "literally-any-agent");+ expect(out).toEqual({ ok: true });+ expect(setSkillEnabledMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/server/actions/tasks.test.ts b/src/server/actions/tasks.test.tsnew file mode 100644index 00000000..5293b548--- /dev/null+++ b/src/server/actions/tasks.test.ts@@ -0,0 +1,258 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Project, Task } from "@/types";++const revalidatePathMock = vi.fn();+vi.mock("next/cache", () => ({+ revalidatePath: (...a: unknown[]) => revalidatePathMock(...a),+}));++const getActiveProjectMock = vi.fn();+vi.mock("@/server/active-project", () => ({+ getActiveProject: () => getActiveProjectMock(),+}));++const claimProposedTaskMock = vi.fn();+const getTaskMock = vi.fn();+const listTasksByAgentMock = vi.fn();+const updateTaskMock = vi.fn();+vi.mock("@/server/db/tasks", () => ({+ claimProposedTask: (...a: unknown[]) => claimProposedTaskMock(...a),+ getTask: (...a: unknown[]) => getTaskMock(...a),+ listTasksByAgent: (...a: unknown[]) => listTasksByAgentMock(...a),+ updateTask: (...a: unknown[]) => updateTaskMock(...a),+}));++const runTaskKickoffServerSideMock = vi.fn();+vi.mock("@/server/orchestration/run-task", () => ({+ runTaskKickoffServerSide: (...a: unknown[]) => runTaskKickoffServerSideMock(...a),+}));++import { cancelTaskAction, startAllProposedTasksAction } from "./tasks";++function makeProject(overrides: Partial<Project> = {}): Project {+ return {+ id: "p-1",+ slug: "demo",+ display_name: "Demo",+ created_at: "2026-01-01T00:00:00.000Z",+ archived_at: null,+ google_ads_account_id: null,+ ...overrides,+ };+}++function makeTask(overrides: Partial<Task> = {}): Task {+ return {+ id: "task-1",+ display_id: "demo-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ title: "T",+ brief: "b",+ success_criteria: null,+ deadline_iso: null,+ status: "proposed",+ result_json: null,+ error_message: null,+ thread_id: null,+ assigner_agent_id: "demo-cmo",+ created_at: "2026-05-19T00:00:00Z",+ updated_at: "2026-05-19T00:00:00Z",+ ...overrides,+ };+}++describe("startAllProposedTasksAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ runTaskKickoffServerSideMock.mockResolvedValue(undefined);+ });++ it("returns ok:false when agentId is whitespace-only", async () => {+ const out = await startAllProposedTasksAction(" ");+ expect(out).toEqual({ ok: false, error: "agentId is required" });+ expect(getActiveProjectMock).not.toHaveBeenCalled();+ });++ it("returns ok:false when no active project is set", async () => {+ getActiveProjectMock.mockResolvedValue(null);+ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out).toEqual({ ok: false, error: "No active project." });+ expect(listTasksByAgentMock).not.toHaveBeenCalled();+ });++ it("returns started=0 when the agent has no proposed tasks", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ listTasksByAgentMock.mockReturnValue([]);+ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out).toEqual({ ok: true, data: { started: 0, task_ids: [] } });+ expect(claimProposedTaskMock).not.toHaveBeenCalled();+ expect(revalidatePathMock).not.toHaveBeenCalled();+ });++ it("returns ok:false when none of the proposed tasks belong to the active project (cookie drift guard)", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject({ slug: "demo" }));+ listTasksByAgentMock.mockReturnValue([+ makeTask({ id: "t-other", project_slug: "other-project" }),+ ]);+ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out.ok).toBe(false);+ if (out.ok) return;+ expect(out.error).toMatch(/no proposed tasks in the active project/);+ expect(claimProposedTaskMock).not.toHaveBeenCalled();+ });++ it("claims every valid task atomically and fires kickoffs in the background", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ const t1 = makeTask({ id: "t1" });+ const t2 = makeTask({ id: "t2" });+ listTasksByAgentMock.mockReturnValue([t1, t2]);+ claimProposedTaskMock.mockImplementation((id: string) => {+ if (id === "t1") return { ...t1, status: "running" };+ if (id === "t2") return { ...t2, status: "running" };+ return null;+ });++ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out.ok).toBe(true);+ if (!out.ok) return;+ expect(out.data.started).toBe(2);+ expect(out.data.task_ids.sort()).toEqual(["t1", "t2"]);+ expect(claimProposedTaskMock).toHaveBeenCalledTimes(2);++ // Let fire-and-forget kickoffs schedule.+ await new Promise((r) => setImmediate(r));+ expect(runTaskKickoffServerSideMock).toHaveBeenCalledTimes(2);+ expect(revalidatePathMock).toHaveBeenCalledWith("/agents", "layout");+ expect(revalidatePathMock).toHaveBeenCalledWith("/tasks", "layout");+ });++ it("silently skips tasks whose claim fails (race already-running/terminal)", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ const t1 = makeTask({ id: "t1" });+ const t2 = makeTask({ id: "t2" });+ listTasksByAgentMock.mockReturnValue([t1, t2]);+ claimProposedTaskMock.mockImplementation((id: string) => {+ if (id === "t1") return { ...t1, status: "running" };+ return null;+ });++ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out.ok).toBe(true);+ if (!out.ok) return;+ expect(out.data.started).toBe(1);+ expect(out.data.task_ids).toEqual(["t1"]);++ await new Promise((r) => setImmediate(r));+ expect(runTaskKickoffServerSideMock).toHaveBeenCalledTimes(1);+ });++ it("filters tasks belonging to other projects before claiming", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject({ slug: "demo" }));+ const tMine = makeTask({ id: "t-mine", project_slug: "demo" });+ const tOther = makeTask({ id: "t-other", project_slug: "other" });+ listTasksByAgentMock.mockReturnValue([tMine, tOther]);+ claimProposedTaskMock.mockReturnValue({ ...tMine, status: "running" });++ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out.ok).toBe(true);+ expect(claimProposedTaskMock).toHaveBeenCalledTimes(1);+ expect(claimProposedTaskMock).toHaveBeenCalledWith("t-mine");+ });++ it("logs but does not rethrow when a background kickoff rejects", async () => {+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ getActiveProjectMock.mockResolvedValue(makeProject());+ const t = makeTask({ id: "t1" });+ listTasksByAgentMock.mockReturnValue([t]);+ claimProposedTaskMock.mockReturnValue({ ...t, status: "running" });+ runTaskKickoffServerSideMock.mockRejectedValue(new Error("kickoff boom"));++ const out = await startAllProposedTasksAction("demo-google-ads");+ expect(out.ok).toBe(true);++ // Drain microtasks twice to let the rejection propagate to .catch.+ await new Promise((r) => setImmediate(r));+ await new Promise((r) => setImmediate(r));+ expect(errSpy).toHaveBeenCalledWith(+ expect.stringContaining("[start-all] kickoff failed for t1:"),+ expect.any(Error),+ );+ errSpy.mockRestore();+ });++ it("passes the agentId and status='proposed' filter to listTasksByAgent", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ listTasksByAgentMock.mockReturnValue([]);+ await startAllProposedTasksAction("demo-google-ads");+ expect(listTasksByAgentMock).toHaveBeenCalledWith("demo-google-ads", "proposed");+ });+});++describe("cancelTaskAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns ok:false when no active project is set", async () => {+ getActiveProjectMock.mockResolvedValue(null);+ const out = await cancelTaskAction("demo-1");+ expect(out).toEqual({ ok: false, error: "No active project." });+ expect(getTaskMock).not.toHaveBeenCalled();+ });++ it("returns ok:false when the task is not found", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ getTaskMock.mockReturnValue(null);+ const out = await cancelTaskAction("demo-1");+ expect(out).toEqual({ ok: false, error: "Task not found." });+ expect(updateTaskMock).not.toHaveBeenCalled();+ });++ it("returns ok:false when the task belongs to a different project (active-project mismatch)", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject({ slug: "demo" }));+ getTaskMock.mockReturnValue(makeTask({ project_slug: "other" }));+ const out = await cancelTaskAction("other-1");+ expect(out).toEqual({ ok: false, error: "Task isn't in the active project." });+ expect(updateTaskMock).not.toHaveBeenCalled();+ });++ it.each(["succeeded", "failed", "cancelled"] as const)(+ "returns ok:false when the task is already %s",+ async (status) => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ getTaskMock.mockReturnValue(makeTask({ status }));+ const out = await cancelTaskAction("demo-1");+ expect(out).toEqual({ ok: false, error: `Task is already ${status}.` });+ expect(updateTaskMock).not.toHaveBeenCalled();+ },+ );++ it.each(["proposed", "approved", "running"] as const)(+ "cancels the task when it is in non-terminal state %s",+ async (status) => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ getTaskMock.mockReturnValue(makeTask({ id: "task-1", status }));+ updateTaskMock.mockReturnValue(makeTask({ id: "task-1", status: "cancelled" }));++ const out = await cancelTaskAction("demo-1");+ expect(out).toEqual({ ok: true });+ expect(updateTaskMock).toHaveBeenCalledWith("task-1", {+ status: "cancelled",+ error_message: "Cancelled by user",+ });+ expect(revalidatePathMock).toHaveBeenCalledWith("/agents", "layout");+ expect(revalidatePathMock).toHaveBeenCalledWith("/tasks", "layout");+ },+ );++ it("accepts a display_id and forwards it to getTask", async () => {+ getActiveProjectMock.mockResolvedValue(makeProject());+ getTaskMock.mockReturnValue(makeTask({ id: "uuid-xyz", status: "running" }));+ await cancelTaskAction("demo-7");+ expect(getTaskMock).toHaveBeenCalledWith("demo-7");+ // updateTask is keyed by the row PK, not the display_id input.+ expect(updateTaskMock).toHaveBeenCalledWith("uuid-xyz", expect.any(Object));+ });+});diff --git a/src/server/active-project.test.ts b/src/server/active-project.test.tsnew file mode 100644index 00000000..985a2e2e--- /dev/null+++ b/src/server/active-project.test.ts@@ -0,0 +1,157 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Project } from "@/types";++// ── Mocks ──────────────────────────────────────────────────────────++const cookieGetMock = vi.fn();+const cookieSetMock = vi.fn();+const cookieDeleteMock = vi.fn();++vi.mock("next/headers", () => ({+ cookies: async () => ({+ get: (...args: unknown[]) => cookieGetMock(...args),+ set: (...args: unknown[]) => cookieSetMock(...args),+ delete: (...args: unknown[]) => cookieDeleteMock(...args),+ }),+}));++const getProjectMock = vi.fn();+const listProjectsMock = vi.fn();+vi.mock("./db/projects", () => ({+ getProject: (...args: unknown[]) => getProjectMock(...args),+ listProjects: (...args: unknown[]) => listProjectsMock(...args),+}));++import {+ clearActiveProject,+ getActiveProject,+ setActiveProject,+} from "./active-project";++// ── Fixtures ───────────────────────────────────────────────────────++function makeProject(overrides: Partial<Project> = {}): Project {+ return {+ id: "uuid",+ slug: "acme",+ display_name: "Acme",+ created_at: "now",+ archived_at: null,+ google_ads_account_id: null,+ ...overrides,+ };+}++// ── Tests ──────────────────────────────────────────────────────────++describe("getActiveProject", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("returns the cookie-pinned project when it exists and is not archived", async () => {+ cookieGetMock.mockReturnValueOnce({ value: "acme" });+ const acme = makeProject({ slug: "acme" });+ getProjectMock.mockReturnValueOnce(acme);++ const r = await getActiveProject();+ expect(r).toEqual(acme);+ expect(getProjectMock).toHaveBeenCalledWith("acme");+ expect(listProjectsMock).not.toHaveBeenCalled();+ });++ it("falls back to first listProjects result when cookie absent", async () => {+ cookieGetMock.mockReturnValueOnce(undefined);+ const first = makeProject({ slug: "first" });+ listProjectsMock.mockReturnValueOnce([first, makeProject({ slug: "other" })]);++ const r = await getActiveProject();+ expect(r).toEqual(first);+ expect(getProjectMock).not.toHaveBeenCalled();+ });++ it("falls back when cookie present but project no longer exists", async () => {+ cookieGetMock.mockReturnValueOnce({ value: "ghost" });+ getProjectMock.mockReturnValueOnce(null);+ const fallback = makeProject({ slug: "fallback" });+ listProjectsMock.mockReturnValueOnce([fallback]);++ const r = await getActiveProject();+ expect(r).toEqual(fallback);+ });++ it("falls back when cookie-pinned project is archived", async () => {+ cookieGetMock.mockReturnValueOnce({ value: "old" });+ const archived = makeProject({+ slug: "old",+ archived_at: "2025-01-01T00:00:00Z",+ });+ getProjectMock.mockReturnValueOnce(archived);+ const fallback = makeProject({ slug: "fresh" });+ listProjectsMock.mockReturnValueOnce([fallback]);++ const r = await getActiveProject();+ expect(r).toEqual(fallback);+ });++ it("returns null when cookie absent and no projects exist", async () => {+ cookieGetMock.mockReturnValueOnce(undefined);+ listProjectsMock.mockReturnValueOnce([]);++ const r = await getActiveProject();+ expect(r).toBeNull();+ });++ it("returns null when cookie present but no projects exist", async () => {+ cookieGetMock.mockReturnValueOnce({ value: "ghost" });+ getProjectMock.mockReturnValueOnce(null);+ listProjectsMock.mockReturnValueOnce([]);++ const r = await getActiveProject();+ expect(r).toBeNull();+ });+});++describe("setActiveProject", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("writes the cookie with the notfair_active_project name and httpOnly options", async () => {+ await setActiveProject("acme");+ expect(cookieSetMock).toHaveBeenCalledTimes(1);+ const [name, value, opts] = cookieSetMock.mock.calls[0]!;+ expect(name).toBe("notfair_active_project");+ expect(value).toBe("acme");+ expect(opts).toMatchObject({+ httpOnly: true,+ sameSite: "lax",+ path: "/",+ });+ expect(opts.maxAge).toBeGreaterThan(0);+ });++ it("persists the maxAge as one year in seconds", async () => {+ await setActiveProject("acme");+ const [, , opts] = cookieSetMock.mock.calls[0]!;+ expect(opts.maxAge).toBe(60 * 60 * 24 * 365);+ });++ it("accepts a different slug verbatim", async () => {+ await setActiveProject("acme-q4");+ const [, value] = cookieSetMock.mock.calls[0]!;+ expect(value).toBe("acme-q4");+ });+});++describe("clearActiveProject", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("deletes the notfair_active_project cookie", async () => {+ await clearActiveProject();+ expect(cookieDeleteMock).toHaveBeenCalledWith("notfair_active_project");+ });+});diff --git a/src/server/agent-meta.test.ts b/src/server/agent-meta.test.tsnew file mode 100644index 00000000..57fe7ec9--- /dev/null+++ b/src/server/agent-meta.test.ts@@ -0,0 +1,335 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { AgentMeta } from "./agent-meta";++// ── Mocks ──────────────────────────────────────────────────────────++// In-memory "filesystem" backing both node:fs (sync) and node:fs/promises.+type FsState = {+ files: Map<string, string>;+ dirs: Set<string>;+ /** When set, readdir throws ENOENT for this root. */+ missingDirs: Set<string>;+};++const fsState: FsState = {+ files: new Map(),+ dirs: new Set(),+ missingDirs: new Set(),+};++vi.mock("node:fs", () => ({+ existsSync: (p: string) => fsState.files.has(p),+ readFileSync: (p: string) => {+ const v = fsState.files.get(p);+ if (v === undefined) throw new Error(`ENOENT: ${p}`);+ return v;+ },+}));++vi.mock("node:fs/promises", () => ({+ mkdir: async (p: string, _opts?: unknown) => {+ fsState.dirs.add(p);+ },+ writeFile: async (p: string, content: string, _enc?: string) => {+ fsState.files.set(p, content);+ },+ readdir: async (p: string) => {+ if (fsState.missingDirs.has(p)) {+ const err = new Error(`ENOENT: ${p}`) as NodeJS.ErrnoException;+ err.code = "ENOENT";+ throw err;+ }+ // Return directory names under p that are direct children.+ const out = new Set<string>();+ const prefix = p.endsWith("/") ? p : `${p}/`;+ for (const file of fsState.files.keys()) {+ if (file.startsWith(prefix)) {+ const rest = file.slice(prefix.length);+ const first = rest.split("/")[0];+ if (first) out.add(first);+ }+ }+ for (const dir of fsState.dirs) {+ if (dir.startsWith(prefix)) {+ const rest = dir.slice(prefix.length);+ const first = rest.split("/")[0];+ if (first) out.add(first);+ }+ }+ return Array.from(out);+ },+}));++// homedir → deterministic path so tests don't depend on the runner's $HOME.+vi.mock("node:os", () => ({+ homedir: () => "/home/test",+}));++// Stub TEMPLATES so we don't depend on real prompt-edit churn. listProjectAgents+// only uses { key, display_name, description } from each entry + the helpers+// imported alongside.+vi.mock("./agent-templates", () => ({+ TEMPLATES: [+ {+ key: "cmo",+ display_name: "CMO",+ description: "Chief Marketing Officer.",+ },+ {+ key: "google_ads",+ display_name: "Google Ads",+ description: "Google Ads specialist.",+ },+ {+ key: "seo",+ display_name: "SEO",+ description: "SEO specialist.",+ },+ ],+ agentNameFor: (slug: string, key: string) =>+ `${slug}-${key.replace(/_/g, "-")}`,+ urlSlugForTemplate: (key: string) => key.replace(/_/g, "-"),+}));++import {+ listProjectAgents,+ readAgentMeta,+ resolveAgentBySlug,+ workspaceDirFor,+ writeAgentMeta,+} from "./agent-meta";++// ── Helpers ────────────────────────────────────────────────────────++function resetFs() {+ fsState.files.clear();+ fsState.dirs.clear();+ fsState.missingDirs.clear();+}++function makeMeta(overrides: Partial<AgentMeta> = {}): AgentMeta {+ return {+ agent_id: "acme-cmo",+ project_slug: "acme",+ slug: "cmo",+ display_name: "CMO",+ template_key: "cmo",+ created_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++beforeEach(() => {+ resetFs();+ // Set deterministic data dir so paths are predictable.+ process.env.NOTFAIR_CMO_DATA_DIR = "/data";+});++// ── Tests ──────────────────────────────────────────────────────────++describe("workspaceDirFor", () => {+ it("returns <DATA_DIR>/agents/<agentId>", () => {+ expect(workspaceDirFor("acme-cmo")).toBe("/data/agents/acme-cmo");+ });++ it("falls back to homedir when env unset", () => {+ delete process.env.NOTFAIR_CMO_DATA_DIR;+ expect(workspaceDirFor("acme-cmo")).toBe(+ "/home/test/.notfair-cmo/agents/acme-cmo",+ );+ });+});++describe("writeAgentMeta + readAgentMeta", () => {+ it("writes JSON to <DATA_DIR>/agents/<agentId>/notfair-meta.json", async () => {+ const meta = makeMeta();+ await writeAgentMeta(meta);+ const written = fsState.files.get("/data/agents/acme-cmo/notfair-meta.json");+ expect(written).toBeDefined();+ expect(JSON.parse(written!)).toEqual(meta);+ });++ it("creates the parent directory recursively before writing", async () => {+ await writeAgentMeta(makeMeta());+ expect(fsState.dirs.has("/data/agents/acme-cmo")).toBe(true);+ });++ it("readAgentMeta returns the parsed object after a writeAgentMeta", async () => {+ const meta = makeMeta();+ await writeAgentMeta(meta);+ expect(readAgentMeta("acme-cmo")).toEqual(meta);+ });++ it("readAgentMeta returns null when the file does not exist", () => {+ expect(readAgentMeta("ghost-agent")).toBeNull();+ });++ it("readAgentMeta returns null when the file is malformed JSON", () => {+ fsState.files.set(+ "/data/agents/broken/notfair-meta.json",+ "{ not valid json",+ );+ expect(readAgentMeta("broken")).toBeNull();+ });++ it("round-trips an entry with optional source_agent_id (clone case)", async () => {+ const meta = makeMeta({+ agent_id: "acme-supa-clone",+ slug: "supa-clone",+ display_name: "Supabase Clone",+ source_agent_id: "acme-cmo",+ });+ await writeAgentMeta(meta);+ expect(readAgentMeta("acme-supa-clone")).toEqual(meta);+ });+});++describe("listProjectAgents", () => {+ it("returns templates-only when agents dir is missing", async () => {+ fsState.missingDirs.add("/data/agents");+ const r = await listProjectAgents("acme");+ expect(r).toHaveLength(3);+ expect(r.map((e) => e.agent_id)).toEqual([+ "acme-cmo",+ "acme-google-ads",+ "acme-seo",+ ]);+ expect(r.every((e) => e.is_template_default)).toBe(true);+ });++ it("returns templates-only when agents dir exists but has no entries for the project", async () => {+ // Empty dir: readdir resolves to [], no entries match.+ const r = await listProjectAgents("acme");+ expect(r.map((e) => e.agent_id)).toEqual([+ "acme-cmo",+ "acme-google-ads",+ "acme-seo",+ ]);+ });++ it("overlays a meta sidecar so is_template_default flips to false", async () => {+ await writeAgentMeta(makeMeta()); // /data/agents/acme-cmo/notfair-meta.json+ const r = await listProjectAgents("acme");+ const cmo = r.find((e) => e.agent_id === "acme-cmo");+ expect(cmo?.is_template_default).toBe(false);+ expect(cmo?.display_name).toBe("CMO");+ });++ it("includes a cloned/custom agent with its source_agent_id surfaced", async () => {+ await writeAgentMeta(+ makeMeta({+ agent_id: "acme-supa-clone",+ slug: "supa-clone",+ display_name: "Supa Clone",+ template_key: undefined,+ source_agent_id: "acme-cmo",+ }),+ );+ const r = await listProjectAgents("acme");+ const clone = r.find((e) => e.agent_id === "acme-supa-clone");+ expect(clone).toMatchObject({+ agent_id: "acme-supa-clone",+ slug: "supa-clone",+ display_name: "Supa Clone",+ source_agent_id: "acme-cmo",+ is_template_default: false,+ });+ });++ it("orders templates by declared order, then custom by slug", async () => {+ await writeAgentMeta(+ makeMeta({+ agent_id: "acme-z-tool",+ slug: "z-tool",+ display_name: "Z Tool",+ template_key: undefined,+ }),+ );+ await writeAgentMeta(+ makeMeta({+ agent_id: "acme-a-tool",+ slug: "a-tool",+ display_name: "A Tool",+ template_key: undefined,+ }),+ );+ const r = await listProjectAgents("acme");+ // Templates first in declared order, then custom alphabetically by slug.+ expect(r.map((e) => e.slug)).toEqual([+ "cmo",+ "google-ads",+ "seo",+ "a-tool",+ "z-tool",+ ]);+ });++ it("ignores entries from other projects (different slug prefix)", async () => {+ await writeAgentMeta(+ makeMeta({+ agent_id: "globex-cmo",+ project_slug: "globex",+ slug: "cmo",+ display_name: "Globex CMO",+ }),+ );+ const r = await listProjectAgents("acme");+ expect(r.find((e) => e.agent_id === "globex-cmo")).toBeUndefined();+ // Still has the 3 templates for acme.+ expect(r.filter((e) => e.is_template_default)).toHaveLength(3);+ });++ it("skips entries with a matching prefix but no meta sidecar", async () => {+ // Create a phantom agent dir without a notfair-meta.json — simulates an+ // OpenClaw workspace dir without the sidecar (e.g., pre-sidecar agents).+ fsState.dirs.add("/data/agents/acme-orphan");+ const r = await listProjectAgents("acme");+ // Should not include acme-orphan; just the templates.+ expect(r.find((e) => e.agent_id === "acme-orphan")).toBeUndefined();+ expect(r).toHaveLength(3);+ });+});++describe("resolveAgentBySlug", () => {+ it("resolves a template URL slug to its agent_id", async () => {+ fsState.missingDirs.add("/data/agents");+ const r = await resolveAgentBySlug("acme", "google-ads");+ expect(r).toEqual({+ agent_id: "acme-google-ads",+ display_name: "Google Ads",+ slug: "google-ads",+ template_key: "google_ads",+ });+ });++ it("resolves the bare 'cmo' slug", async () => {+ fsState.missingDirs.add("/data/agents");+ const r = await resolveAgentBySlug("acme", "cmo");+ expect(r?.agent_id).toBe("acme-cmo");+ });++ it("resolves a custom (non-template) agent by its meta slug", async () => {+ await writeAgentMeta(+ makeMeta({+ agent_id: "acme-supa-clone",+ slug: "supa-clone",+ display_name: "Supa Clone",+ template_key: undefined,+ }),+ );+ const r = await resolveAgentBySlug("acme", "supa-clone");+ expect(r).toEqual({+ agent_id: "acme-supa-clone",+ display_name: "Supa Clone",+ slug: "supa-clone",+ template_key: undefined,+ });+ });++ it("returns null when slug doesn't match any agent in the project", async () => {+ fsState.missingDirs.add("/data/agents");+ const r = await resolveAgentBySlug("acme", "nonexistent");+ expect(r).toBeNull();+ });+});diff --git a/src/server/db/agent-actions.test.ts b/src/server/db/agent-actions.test.tsnew file mode 100644index 00000000..c5337ed4--- /dev/null+++ b/src/server/db/agent-actions.test.ts@@ -0,0 +1,223 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "./migrations";++let testDb: Database.Database;++vi.mock("./db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import { listAgentActions, logAgentAction } from "./agent-actions";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) {+ db.exec(migration.sql);+ }+}++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ applyMigrations(db);+ return db;+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("logAgentAction", () => {+ it("persists a minimal action with sensible defaults", () => {+ seedProject();+ const before = Date.now();+ const action = logAgentAction({+ project_slug: "acme",+ agent_id: "acme-google-ads",+ action_type: "audit",+ summary: "ran nightly audit",+ });+ const after = Date.now();++ expect(action.id).toMatch(/[0-9a-f-]{36}/);+ expect(action.project_slug).toBe("acme");+ expect(action.agent_id).toBe("acme-google-ads");+ expect(action.action_type).toBe("audit");+ expect(action.summary).toBe("ran nightly audit");+ expect(action.task_id).toBeNull();+ expect(action.reasoning).toBeNull();+ expect(action.payload_json).toBeNull();+ const t = Date.parse(action.occurred_at);+ expect(t).toBeGreaterThanOrEqual(before);+ expect(t).toBeLessThanOrEqual(after);++ // Round-trip via the DB to confirm the insert actually landed.+ const row = testDb+ .prepare("SELECT * FROM agent_actions WHERE id = ?")+ .get(action.id) as Record<string, unknown>;+ expect(row).toMatchObject({+ id: action.id,+ project_slug: "acme",+ agent_id: "acme-google-ads",+ action_type: "audit",+ summary: "ran nightly audit",+ task_id: null,+ reasoning: null,+ payload_json: null,+ });+ });++ it("stores reasoning, task_id, and JSON-encoded payload when provided", () => {+ seedProject();+ const payload = { keyword: "shoes", bid_usd: 1.25, nested: { tag: "x" } };+ const action = logAgentAction({+ project_slug: "acme",+ agent_id: "acme-cmo",+ action_type: "bid_change",+ summary: "raised bid",+ reasoning: "below target ROAS",+ task_id: "task-123",+ payload,+ });+ expect(action.reasoning).toBe("below target ROAS");+ expect(action.task_id).toBe("task-123");+ expect(action.payload_json).toBe(JSON.stringify(payload));+ expect(JSON.parse(action.payload_json!)).toEqual(payload);+ });++ it("treats null reasoning / null task_id distinctly from undefined", () => {+ seedProject();+ const action = logAgentAction({+ project_slug: "acme",+ agent_id: "acme-cmo",+ action_type: "x",+ summary: "y",+ reasoning: null,+ task_id: null,+ });+ expect(action.reasoning).toBeNull();+ expect(action.task_id).toBeNull();+ });++ it("serializes payload === null as the JSON string 'null' (distinct from omitted)", () => {+ seedProject();+ // input.payload === null → not undefined → JSON.stringify(null) === "null"+ const action = logAgentAction({+ project_slug: "acme",+ agent_id: "acme-cmo",+ action_type: "x",+ summary: "y",+ payload: null,+ });+ expect(action.payload_json).toBe("null");+ });++ it("throws when project_slug FK is violated", () => {+ // No project seeded — insert should trip the FK.+ expect(() =>+ logAgentAction({+ project_slug: "missing",+ agent_id: "x",+ action_type: "y",+ summary: "z",+ }),+ ).toThrow(/FOREIGN KEY/i);+ });+});++describe("listAgentActions", () => {+ it("returns rows ordered by occurred_at DESC (newest first)", () => {+ seedProject();+ testDb+ .prepare(+ `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run("a1", "acme", "x", "t", "first", "2026-01-01T00:00:00.000Z");+ testDb+ .prepare(+ `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run("a2", "acme", "x", "t", "second", "2026-01-02T00:00:00.000Z");+ testDb+ .prepare(+ `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run("a3", "acme", "x", "t", "third", "2026-01-03T00:00:00.000Z");+ const rows = listAgentActions("acme");+ expect(rows.map((r) => r.summary)).toEqual(["third", "second", "first"]);+ });++ it("filters by project_slug", () => {+ seedProject("acme");+ seedProject("other");+ logAgentAction({+ project_slug: "acme",+ agent_id: "x",+ action_type: "t",+ summary: "for acme",+ });+ logAgentAction({+ project_slug: "other",+ agent_id: "x",+ action_type: "t",+ summary: "for other",+ });+ const rows = listAgentActions("acme");+ expect(rows).toHaveLength(1);+ expect(rows[0]!.summary).toBe("for acme");+ });++ it("honors the limit parameter", () => {+ seedProject();+ for (let i = 0; i < 5; i++) {+ testDb+ .prepare(+ `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run(`a${i}`, "acme", "x", "t", `s${i}`, `2026-01-0${i + 1}T00:00:00.000Z`);+ }+ expect(listAgentActions("acme", 3)).toHaveLength(3);+ expect(listAgentActions("acme", 100)).toHaveLength(5);+ });++ it("defaults to limit=50", () => {+ seedProject();+ const insert = testDb.prepare(+ `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ );+ for (let i = 0; i < 60; i++) {+ // pad the timestamp so they sort cleanly+ const ts = `2026-01-01T00:${String(i).padStart(2, "0")}:00.000Z`;+ insert.run(`a${i}`, "acme", "x", "t", `s${i}`, ts);+ }+ expect(listAgentActions("acme")).toHaveLength(50);+ });++ it("returns empty array when project has no actions", () => {+ seedProject();+ expect(listAgentActions("acme")).toEqual([]);+ });++ it("returns empty array for unknown project slug", () => {+ expect(listAgentActions("does-not-exist")).toEqual([]);+ });+});diff --git a/src/server/db/approvals.test.ts b/src/server/db/approvals.test.tsnew file mode 100644index 00000000..b562e788--- /dev/null+++ b/src/server/db/approvals.test.ts@@ -0,0 +1,331 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "./migrations";++let testDb: Database.Database;++vi.mock("./db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import {+ createApproval,+ listPendingApprovals,+ pendingApprovalCount,+ resolveApproval,+} from "./approvals";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) {+ db.exec(migration.sql);+ }+}++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ applyMigrations(db);+ return db;+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("createApproval", () => {+ it("persists a pending approval with a generated id and serialized payload", () => {+ seedProject();+ const payload = { campaign_id: "123", new_bid: 2.5 };+ const approval = createApproval({+ project_slug: "acme",+ agent_id: "acme-google-ads",+ action_summary: "raise bid on shoes",+ action_type: "bid_change",+ cost_estimate_usd: 10,+ reasoning: "below target ROAS",+ payload,+ });++ expect(approval.id).toMatch(/[0-9a-f-]{36}/);+ expect(approval.status).toBe("pending");+ expect(approval.resolved_at).toBeNull();+ expect(approval.payload_json).toBe(JSON.stringify(payload));+ expect(approval.reasoning).toBe("below target ROAS");+ expect(approval.cost_estimate_usd).toBe(10);+ expect(approval.action_type).toBe("bid_change");++ // Round-trip via DB+ const row = testDb+ .prepare("SELECT * FROM approvals WHERE id = ?")+ .get(approval.id) as Record<string, unknown>;+ expect(row.status).toBe("pending");+ expect(row.resolved_at).toBeNull();+ });++ it("defaults reasoning to null when omitted", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "acme-cmo",+ action_summary: "x",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ expect(a.reasoning).toBeNull();+ });++ it("serializes an undefined payload as {}", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "acme-cmo",+ action_summary: "x",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: undefined,+ });+ expect(a.payload_json).toBe("{}");+ });++ it("serializes a null payload as {} (?? operator coerces null too)", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "acme-cmo",+ action_summary: "x",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: null,+ });+ // Behaviorally: `?? {}` replaces null with {}, then JSON.stringify({}) === "{}".+ expect(a.payload_json).toBe("{}");+ });++ it("throws on invalid action_type (CHECK constraint)", () => {+ seedProject();+ expect(() =>+ createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "y",+ // @ts-expect-error invalid on purpose+ action_type: "invalid_type",+ cost_estimate_usd: 0,+ payload: {},+ }),+ ).toThrow(/CHECK/i);+ });++ it("throws on missing project FK", () => {+ expect(() =>+ createApproval({+ project_slug: "no-such-project",+ agent_id: "x",+ action_summary: "y",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ }),+ ).toThrow(/FOREIGN KEY/i);+ });+});++describe("listPendingApprovals", () => {+ it("returns only pending approvals for the given project", () => {+ seedProject("acme");+ seedProject("other");+ const a1 = createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "pending1",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "pending2",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ // Resolve one so it's filtered out.+ resolveApproval(a1.id, "approved");+ createApproval({+ project_slug: "other",+ agent_id: "x",+ action_summary: "from other project",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });++ const rows = listPendingApprovals("acme");+ expect(rows.map((r) => r.action_summary)).toEqual(["pending2"]);+ expect(rows.every((r) => r.status === "pending")).toBe(true);+ });++ it("orders by created_at DESC", () => {+ seedProject();+ testDb+ .prepare(+ `INSERT INTO approvals+ (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,+ )+ .run("a1", "acme", "x", "old", "other", 0, "{}", "2026-01-01T00:00:00.000Z");+ testDb+ .prepare(+ `INSERT INTO approvals+ (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)`,+ )+ .run("a2", "acme", "x", "newer", "other", 0, "{}", "2026-01-02T00:00:00.000Z");+ expect(listPendingApprovals("acme").map((r) => r.action_summary)).toEqual([+ "newer",+ "old",+ ]);+ });++ it("returns empty array when project has no pending approvals", () => {+ seedProject();+ expect(listPendingApprovals("acme")).toEqual([]);+ });+});++describe("pendingApprovalCount", () => {+ it("returns 0 when there are no approvals", () => {+ seedProject();+ expect(pendingApprovalCount("acme")).toBe(0);+ });++ it("counts only pending approvals", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p1",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p2",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p3",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ expect(pendingApprovalCount("acme")).toBe(3);+ resolveApproval(a.id, "approved");+ expect(pendingApprovalCount("acme")).toBe(2);+ });++ it("isolates count by project", () => {+ seedProject("a");+ seedProject("b");+ createApproval({+ project_slug: "a",+ agent_id: "x",+ action_summary: "p",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ expect(pendingApprovalCount("a")).toBe(1);+ expect(pendingApprovalCount("b")).toBe(0);+ });+});++describe("resolveApproval", () => {+ it("flips pending → approved and stamps resolved_at", async () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ const out = resolveApproval(a.id, "approved");+ expect(out).not.toBeNull();+ expect(out!.status).toBe("approved");+ expect(out!.resolved_at).not.toBeNull();+ expect(Date.parse(out!.resolved_at!)).toBeGreaterThan(0);+ });++ it("flips pending → rejected", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ const out = resolveApproval(a.id, "rejected");+ expect(out!.status).toBe("rejected");+ });++ it("flips pending → expired", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ const out = resolveApproval(a.id, "expired");+ expect(out!.status).toBe("expired");+ });++ it("is a no-op when the approval is not pending (returns current row)", () => {+ seedProject();+ const a = createApproval({+ project_slug: "acme",+ agent_id: "x",+ action_summary: "p",+ action_type: "other",+ cost_estimate_usd: 0,+ payload: {},+ });+ const first = resolveApproval(a.id, "approved")!;+ const second = resolveApproval(a.id, "rejected")!;+ // Still approved — the WHERE status='pending' clause prevents re-resolution.+ expect(second.status).toBe("approved");+ expect(second.resolved_at).toBe(first.resolved_at);+ });++ it("returns null when the approval id doesn't exist", () => {+ expect(resolveApproval("missing-id", "approved")).toBeNull();+ });+});diff --git a/src/server/db/cost.test.ts b/src/server/db/cost.test.tsnew file mode 100644index 00000000..a6150b2d--- /dev/null+++ b/src/server/db/cost.test.ts@@ -0,0 +1,188 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "./migrations";++let testDb: Database.Database;++vi.mock("./db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import { costToday, recordCost } from "./cost";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) {+ db.exec(migration.sql);+ }+}++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ applyMigrations(db);+ return db;+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("recordCost", () => {+ it("inserts a cost event and returns the row", () => {+ seedProject();+ const event = recordCost({+ project_slug: "acme",+ agent_id: "acme-google-ads",+ source: "llm",+ amount_usd: 0.42,+ ref: "openai:gpt-4o:msg-1",+ });+ expect(event.id).toMatch(/[0-9a-f-]{36}/);+ expect(event.project_slug).toBe("acme");+ expect(event.agent_id).toBe("acme-google-ads");+ expect(event.source).toBe("llm");+ expect(event.amount_usd).toBe(0.42);+ expect(event.ref).toBe("openai:gpt-4o:msg-1");+ expect(Date.parse(event.occurred_at)).toBeGreaterThan(0);++ const row = testDb+ .prepare("SELECT * FROM cost_events WHERE id = ?")+ .get(event.id);+ expect(row).toMatchObject({ project_slug: "acme", source: "llm" });+ });++ it("defaults agent_id and ref to null when omitted", () => {+ seedProject();+ const event = recordCost({+ project_slug: "acme",+ source: "google_ads",+ amount_usd: 1.0,+ });+ expect(event.agent_id).toBeNull();+ expect(event.ref).toBeNull();+ });++ it("explicit null agent_id / null ref also persist as null", () => {+ seedProject();+ const event = recordCost({+ project_slug: "acme",+ agent_id: null,+ source: "gsc",+ amount_usd: 0,+ ref: null,+ });+ expect(event.agent_id).toBeNull();+ expect(event.ref).toBeNull();+ });++ it("honors an explicit occurred_at timestamp", () => {+ seedProject();+ const event = recordCost({+ project_slug: "acme",+ source: "other",+ amount_usd: 0.01,+ occurred_at: "2020-06-01T12:34:56.000Z",+ });+ expect(event.occurred_at).toBe("2020-06-01T12:34:56.000Z");+ });++ it("rejects invalid source via CHECK constraint", () => {+ seedProject();+ expect(() =>+ recordCost({+ project_slug: "acme",+ // @ts-expect-error invalid on purpose+ source: "bogus",+ amount_usd: 0,+ }),+ ).toThrow(/CHECK/i);+ });++ it("trips FK constraint when project_slug is missing", () => {+ expect(() =>+ recordCost({+ project_slug: "no-such",+ source: "llm",+ amount_usd: 0.01,+ }),+ ).toThrow(/FOREIGN KEY/i);+ });+});++describe("costToday", () => {+ it("returns zeros when there are no cost events", () => {+ seedProject();+ expect(costToday("acme")).toEqual({+ total_usd: 0,+ by_source: { llm: 0, google_ads: 0, gsc: 0, other: 0 },+ });+ });++ it("groups today's spend by source and sums total", () => {+ seedProject();+ // Use 'now' as the occurred_at so the >= startOfDay filter passes regardless of TZ.+ const now = new Date().toISOString();+ recordCost({ project_slug: "acme", source: "llm", amount_usd: 0.10, occurred_at: now });+ recordCost({ project_slug: "acme", source: "llm", amount_usd: 0.20, occurred_at: now });+ recordCost({ project_slug: "acme", source: "google_ads", amount_usd: 5.0, occurred_at: now });+ recordCost({ project_slug: "acme", source: "gsc", amount_usd: 1.5, occurred_at: now });+ recordCost({ project_slug: "acme", source: "other", amount_usd: 0.05, occurred_at: now });+ const out = costToday("acme");+ expect(out.by_source.llm).toBeCloseTo(0.3, 6);+ expect(out.by_source.google_ads).toBe(5.0);+ expect(out.by_source.gsc).toBe(1.5);+ expect(out.by_source.other).toBe(0.05);+ expect(out.total_usd).toBeCloseTo(0.3 + 5.0 + 1.5 + 0.05, 6);+ });++ it("excludes events from yesterday", () => {+ seedProject();+ const yesterday = new Date();+ yesterday.setDate(yesterday.getDate() - 1);+ // Pin yesterday to early morning UTC so we are definitely before today's+ // 00:00 local even for tests run shortly after midnight in any TZ.+ yesterday.setHours(0, 5, 0, 0);+ yesterday.setDate(yesterday.getDate() - 1); // 2 days back for safety+ recordCost({+ project_slug: "acme",+ source: "llm",+ amount_usd: 99,+ occurred_at: yesterday.toISOString(),+ });+ expect(costToday("acme").total_usd).toBe(0);+ });++ it("isolates spend by project", () => {+ seedProject("a");+ seedProject("b");+ const now = new Date().toISOString();+ recordCost({ project_slug: "a", source: "llm", amount_usd: 1, occurred_at: now });+ recordCost({ project_slug: "b", source: "llm", amount_usd: 10, occurred_at: now });+ expect(costToday("a").total_usd).toBe(1);+ expect(costToday("b").total_usd).toBe(10);+ });++ it("returns the zero shape (does not mutate the shared ZERO_BY_SOURCE)", () => {+ seedProject();+ const first = costToday("acme");+ const now = new Date().toISOString();+ recordCost({ project_slug: "acme", source: "llm", amount_usd: 42, occurred_at: now });+ const second = costToday("acme");+ expect(first.by_source.llm).toBe(0); // first snapshot wasn't mutated+ expect(second.by_source.llm).toBe(42);+ });+});diff --git a/src/server/db/db.test.ts b/src/server/db/db.test.tsnew file mode 100644index 00000000..0424f128--- /dev/null+++ b/src/server/db/db.test.ts@@ -0,0 +1,192 @@+import { existsSync, mkdtempSync, rmSync, statSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// Each test re-imports the module after tweaking env so the module-scoped+// DEFAULT_DATA_DIR / DB_PATH constants pick up our tmpdir override. The+// connection is cached at module level — vi.resetModules() between tests+// ensures we get a fresh `cached: null` every time.+type DbModule = typeof import("./db");++async function loadDb(): Promise<DbModule> {+ return (await import("./db")) as DbModule;+}++let tmpDir: string;+const ORIGINAL_ENV = process.env.NOTFAIR_CMO_DATA_DIR;++beforeEach(() => {+ vi.resetModules();+ tmpDir = mkdtempSync(join(tmpdir(), "notfair-cmo-db-test-"));+ process.env.NOTFAIR_CMO_DATA_DIR = tmpDir;+});++afterEach(() => {+ // Restore env so other tests don't pick up our tmpdir.+ if (ORIGINAL_ENV === undefined) {+ delete process.env.NOTFAIR_CMO_DATA_DIR;+ } else {+ process.env.NOTFAIR_CMO_DATA_DIR = ORIGINAL_ENV;+ }+ if (tmpDir && existsSync(tmpDir)) {+ rmSync(tmpDir, { recursive: true, force: true });+ }+});++describe("getDbPath", () => {+ it("returns the path inside NOTFAIR_CMO_DATA_DIR", async () => {+ const { getDbPath } = await loadDb();+ expect(getDbPath()).toBe(join(tmpDir, "db.sqlite"));+ });++ it("falls back to ~/.notfair-cmo when env var is unset", async () => {+ delete process.env.NOTFAIR_CMO_DATA_DIR;+ vi.resetModules();+ const fakeHome = mkdtempSync(join(tmpdir(), "notfair-cmo-fake-home-"));+ try {+ vi.doMock("node:os", async () => {+ const actual = await vi.importActual<typeof import("node:os")>("node:os");+ return { ...actual, homedir: () => fakeHome };+ });+ const { getDbPath } = await loadDb();+ expect(getDbPath()).toBe(join(fakeHome, ".notfair-cmo", "db.sqlite"));+ } finally {+ vi.doUnmock("node:os");+ rmSync(fakeHome, { recursive: true, force: true });+ }+ });+});++describe("getDb", () => {+ it("creates the data dir if it doesn't exist", async () => {+ const nested = join(tmpDir, "nested", "deeper");+ process.env.NOTFAIR_CMO_DATA_DIR = nested;+ vi.resetModules();+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ expect(existsSync(nested)).toBe(true);+ } finally {+ db.close();+ }+ });++ it("creates the data dir with mode 0o700", async () => {+ const nested = join(tmpDir, "secure");+ process.env.NOTFAIR_CMO_DATA_DIR = nested;+ vi.resetModules();+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ const stat = statSync(nested);+ // On POSIX systems we expect 0o700. Skip on Windows-y environments.+ if (process.platform !== "win32") {+ // Mask with 0o777 to strip the file-type bits.+ expect(stat.mode & 0o777).toBe(0o700);+ }+ } finally {+ db.close();+ }+ });++ it("opens the SQLite file at the expected path", async () => {+ const { getDb, getDbPath } = await loadDb();+ const db = getDb();+ try {+ expect(existsSync(getDbPath())).toBe(true);+ } finally {+ db.close();+ }+ });++ it("returns a cached instance on subsequent calls", async () => {+ const { getDb } = await loadDb();+ const a = getDb();+ const b = getDb();+ try {+ expect(a).toBe(b);+ } finally {+ a.close();+ }+ });++ it("enables foreign_keys pragma", async () => {+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ const row = db.pragma("foreign_keys", { simple: true });+ expect(row).toBe(1);+ } finally {+ db.close();+ }+ });++ it("sets WAL journal mode", async () => {+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ const mode = db.pragma("journal_mode", { simple: true });+ expect(String(mode).toLowerCase()).toBe("wal");+ } finally {+ db.close();+ }+ });++ it("sets busy_timeout to 5000", async () => {+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ const ms = db.pragma("busy_timeout", { simple: true });+ expect(ms).toBe(5000);+ } finally {+ db.close();+ }+ });++ it("applies migrations on first open", async () => {+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ // Every migration from MIGRATIONS should be recorded.+ const { MIGRATIONS } = await import("./migrations");+ const applied = db+ .prepare("SELECT name FROM _migrations ORDER BY name")+ .all() as { name: string }[];+ expect(applied.map((r) => r.name).sort()).toEqual(+ MIGRATIONS.map((m) => m.name).sort(),+ );++ // Spot-check that the schema is real (table from 001_init).+ const tables = db+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'projects'")+ .all();+ expect(tables).toHaveLength(1);+ } finally {+ db.close();+ }+ });++ it("does not re-apply migrations on a second open", async () => {+ {+ const { getDb } = await loadDb();+ const db = getDb();+ db.close();+ }++ // Reset module so cached=null but the file at NOTFAIR_CMO_DATA_DIR remains.+ vi.resetModules();+ const { getDb } = await loadDb();+ const db = getDb();+ try {+ const { MIGRATIONS } = await import("./migrations");+ const rows = db+ .prepare("SELECT COUNT(*) AS n FROM _migrations")+ .get() as { n: number };+ // Should NOT have duplicated.+ expect(rows.n).toBe(MIGRATIONS.length);+ } finally {+ db.close();+ }+ });+});diff --git a/src/server/db/oauth.test.ts b/src/server/db/oauth.test.tsnew file mode 100644index 00000000..61cb671d--- /dev/null+++ b/src/server/db/oauth.test.ts@@ -0,0 +1,315 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "./migrations";++let testDb: Database.Database;++vi.mock("./db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++// Stub the cipher so the tests don't require a working OS keychain. The+// "encrypted" representation is just a length-prefixed marker that we can+// round-trip deterministically.+vi.mock("@/server/secrets/cipher", () => ({+ encrypt: async (plaintext: string) => `enc:${plaintext}`,+ decrypt: async (blob: string) => blob.replace(/^enc:/, ""),+}));++import {+ decryptToken,+ getOAuthTokenRecord,+ listOAuthTokens,+ storeOAuthToken,+} from "./oauth";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) {+ db.exec(migration.sql);+ }+}++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ applyMigrations(db);+ return db;+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("storeOAuthToken", () => {+ it("encrypts and persists a new token row", async () => {+ seedProject();+ const out = await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "access-1",+ refresh_token: "refresh-1",+ expires_at: "2027-01-01T00:00:00.000Z",+ scope: "https://www.googleapis.com/auth/adwords",+ });+ expect(out.id).toMatch(/[0-9a-f-]{36}/);+ expect(out.project_slug).toBe("acme");+ expect(out.provider).toBe("google_ads");+ expect(out.account_label).toBe("main");+ expect(out.access_token_enc).toBe("enc:access-1");+ expect(out.refresh_token_enc).toBe("enc:refresh-1");+ expect(out.expires_at).toBe("2027-01-01T00:00:00.000Z");+ expect(out.scope).toBe("https://www.googleapis.com/auth/adwords");++ // Round-trip via DB.+ const row = testDb+ .prepare(+ "SELECT * FROM oauth_tokens WHERE project_slug=? AND provider=? AND account_label=?",+ )+ .get("acme", "google_ads", "main");+ expect(row).toMatchObject({ access_token_enc: "enc:access-1" });+ });++ it("upserts on (project_slug, provider, account_label) conflict", async () => {+ seedProject();+ const a = await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "a1",+ refresh_token: "r1",+ expires_at: "2027-01-01T00:00:00.000Z",+ scope: "scope",+ });+ // Force a different time so we can verify updated_at advanced.+ await new Promise((r) => setTimeout(r, 5));+ const b = await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "a2",+ refresh_token: "r2",+ expires_at: "2028-01-01T00:00:00.000Z",+ scope: "scope2",+ });++ // ON CONFLICT keeps the original primary key id (excluded.id is not set).+ expect(b.id).toBe(a.id);+ expect(b.access_token_enc).toBe("enc:a2");+ expect(b.refresh_token_enc).toBe("enc:r2");+ expect(b.expires_at).toBe("2028-01-01T00:00:00.000Z");+ expect(b.scope).toBe("scope2");+ // created_at unchanged; updated_at advanced.+ expect(b.created_at).toBe(a.created_at);+ expect(Date.parse(b.updated_at)).toBeGreaterThanOrEqual(Date.parse(a.updated_at));++ const count = testDb+ .prepare("SELECT COUNT(*) AS n FROM oauth_tokens")+ .get() as { n: number };+ expect(count.n).toBe(1);+ });++ it("allows multiple account_labels per (project, provider)", async () => {+ seedProject();+ await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "secondary",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ expect(listOAuthTokens("acme")).toHaveLength(2);+ });++ it("throws on invalid provider via CHECK constraint", async () => {+ seedProject();+ await expect(+ storeOAuthToken({+ project_slug: "acme",+ // @ts-expect-error invalid on purpose+ provider: "twitter",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ }),+ ).rejects.toThrow(/CHECK/i);+ });++ it("trips FK on missing project", async () => {+ await expect(+ storeOAuthToken({+ project_slug: "no-such",+ provider: "gsc",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ }),+ ).rejects.toThrow(/FOREIGN KEY/i);+ });+});++describe("listOAuthTokens", () => {+ it("orders by provider, account_label and isolates by project", async () => {+ seedProject("a");+ seedProject("b");+ await storeOAuthToken({+ project_slug: "a",+ provider: "gsc",+ account_label: "z",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ await storeOAuthToken({+ project_slug: "a",+ provider: "google_ads",+ account_label: "z",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ await storeOAuthToken({+ project_slug: "a",+ provider: "google_ads",+ account_label: "a",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ await storeOAuthToken({+ project_slug: "b",+ provider: "google_ads",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });++ const rows = listOAuthTokens("a");+ expect(rows.map((r) => `${r.provider}:${r.account_label}`)).toEqual([+ "google_ads:a",+ "google_ads:z",+ "gsc:z",+ ]);+ });++ it("returns empty array for projects with no tokens", () => {+ seedProject();+ expect(listOAuthTokens("acme")).toEqual([]);+ });+});++describe("getOAuthTokenRecord", () => {+ it("returns the matching row when account_label is provided", async () => {+ seedProject();+ await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ const row = getOAuthTokenRecord("acme", "google_ads", "main");+ expect(row).not.toBeNull();+ expect(row!.account_label).toBe("main");+ });++ it("returns null when account_label is provided but doesn't match", async () => {+ seedProject();+ await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ expect(getOAuthTokenRecord("acme", "google_ads", "missing")).toBeNull();+ });++ it("falls back to LIMIT 1 when account_label is omitted", async () => {+ seedProject();+ await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "secondary",+ access_token: "a",+ refresh_token: "r",+ expires_at: "x",+ scope: "s",+ });+ const row = getOAuthTokenRecord("acme", "google_ads");+ expect(row).not.toBeNull();+ expect(["main", "secondary"]).toContain(row!.account_label);+ });++ it("returns null when no rows match (no account_label)", () => {+ seedProject();+ expect(getOAuthTokenRecord("acme", "google_ads")).toBeNull();+ });+});++describe("decryptToken", () => {+ it("decrypts both access and refresh tokens", async () => {+ seedProject();+ const stored = await storeOAuthToken({+ project_slug: "acme",+ provider: "google_ads",+ account_label: "main",+ access_token: "the-access",+ refresh_token: "the-refresh",+ expires_at: "x",+ scope: "s",+ });+ const decoded = await decryptToken(stored);+ expect(decoded).toEqual({+ access_token: "the-access",+ refresh_token: "the-refresh",+ });+ });+});diff --git a/src/server/db/projects.test.ts b/src/server/db/projects.test.tsindex 727902db..62aa869c 100644--- a/src/server/db/projects.test.ts+++ b/src/server/db/projects.test.ts@@ -13,7 +13,17 @@ vi.mock("./db", () => ({getDbPath: () => ":memory:",}));-import { createProject, deleteProjectRow } from "./projects";+import {+ archiveProject,+ changeProjectSlug,+ createProject,+ deleteProjectRow,+ getProject,+ listProjects,+ renameProject,+ setProjectGoogleAdsAccount,+ unarchiveProject,+} from "./projects";function applyMigrations(db: Database.Database): void {for (const migration of MIGRATIONS) {@@ -36,6 +46,343 @@ afterEach(() => {testDb.close();});+describe("createProject", () => {+ it("creates a new project from display_name and returns the row", () => {+ const result = createProject({ display_name: "Acme Inc." });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.project.slug).toBe("acme-inc");+ expect(result.project.display_name).toBe("Acme Inc.");+ expect(result.project.archived_at).toBeNull();+ expect(result.project.google_ads_account_id).toBeNull();+ expect(result.project.id).toMatch(/[0-9a-f-]{36}/);+ expect(Date.parse(result.project.created_at)).toBeGreaterThan(0);++ // Round-trip via DB.+ const row = testDb+ .prepare("SELECT * FROM projects WHERE slug = ?")+ .get("acme-inc");+ expect(row).toMatchObject({ slug: "acme-inc", display_name: "Acme Inc." });+ });++ it("respects an explicit slug override", () => {+ const result = createProject({+ display_name: "Long Pretty Name",+ slug: "shortie",+ });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.project.slug).toBe("shortie");+ expect(result.project.display_name).toBe("Long Pretty Name");+ });++ it("trims display_name", () => {+ const result = createProject({ display_name: " Acme " });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.project.display_name).toBe("Acme");+ });++ it("returns { ok: false } when slugify fails (empty input)", () => {+ const result = createProject({ display_name: "" });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.reason).toMatch(/empty/i);+ });++ it("returns { ok: false } when slug is reserved", () => {+ const result = createProject({ display_name: "api" });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.reason).toMatch(/reserved/i);+ });++ it("returns { ok: false } when slug already exists", () => {+ const first = createProject({ display_name: "Acme" });+ expect(first.ok).toBe(true);+ const dup = createProject({ display_name: "Acme" });+ expect(dup.ok).toBe(false);+ if (dup.ok) return;+ expect(dup.reason).toMatch(/already exists/i);+ });+});++describe("listProjects", () => {+ it("returns empty array when no projects exist", () => {+ expect(listProjects()).toEqual([]);+ });++ it("orders by created_at DESC", () => {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p1", "old", "Old", "2026-01-01T00:00:00.000Z");+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p2", "new", "New", "2026-02-01T00:00:00.000Z");+ const rows = listProjects();+ expect(rows.map((r) => r.slug)).toEqual(["new", "old"]);+ });++ it("filters archived by default", () => {+ createProject({ display_name: "Live" });+ const archived = createProject({ display_name: "Dead" });+ expect(archived.ok).toBe(true);+ if (!archived.ok) return;+ archiveProject(archived.project.slug);++ const rows = listProjects();+ expect(rows.map((r) => r.slug)).toEqual(["live"]);+ });++ it("includes archived when includeArchived: true", () => {+ createProject({ display_name: "Live" });+ const archived = createProject({ display_name: "Dead" });+ expect(archived.ok).toBe(true);+ if (!archived.ok) return;+ archiveProject(archived.project.slug);++ const rows = listProjects({ includeArchived: true });+ expect(rows.map((r) => r.slug).sort()).toEqual(["dead", "live"]);+ });+});++describe("getProject", () => {+ it("returns the project when found", () => {+ createProject({ display_name: "Acme" });+ const out = getProject("acme");+ expect(out).not.toBeNull();+ expect(out!.slug).toBe("acme");+ });++ it("returns null when no project matches", () => {+ expect(getProject("nope")).toBeNull();+ });+});++describe("setProjectGoogleAdsAccount", () => {+ it("persists the customer id and returns the updated row", () => {+ createProject({ display_name: "Acme" });+ const out = setProjectGoogleAdsAccount("acme", "123-456-7890");+ expect(out).not.toBeNull();+ expect(out!.google_ads_account_id).toBe("123-456-7890");+ });++ it("can clear the customer id by passing null", () => {+ createProject({ display_name: "Acme" });+ setProjectGoogleAdsAccount("acme", "123");+ const cleared = setProjectGoogleAdsAccount("acme", null);+ expect(cleared!.google_ads_account_id).toBeNull();+ });++ it("is idempotent (re-set same value)", () => {+ createProject({ display_name: "Acme" });+ setProjectGoogleAdsAccount("acme", "abc");+ const again = setProjectGoogleAdsAccount("acme", "abc");+ expect(again!.google_ads_account_id).toBe("abc");+ });++ it("returns null when project doesn't exist", () => {+ expect(setProjectGoogleAdsAccount("nope", "x")).toBeNull();+ });+});++describe("renameProject", () => {+ it("changes display_name and returns the updated row", () => {+ createProject({ display_name: "Acme" });+ const out = renameProject("acme", "Acme Corp");+ expect(out!.display_name).toBe("Acme Corp");+ // Slug must NOT change here — renameProject only edits the label.+ expect(out!.slug).toBe("acme");+ });++ it("trims the new display_name", () => {+ createProject({ display_name: "Acme" });+ const out = renameProject("acme", " Trimmed ");+ expect(out!.display_name).toBe("Trimmed");+ });++ it("returns null when display_name is empty after trimming", () => {+ createProject({ display_name: "Acme" });+ expect(renameProject("acme", " ")).toBeNull();+ expect(getProject("acme")!.display_name).toBe("Acme");+ });++ it("returns null when project doesn't exist (no row, no update)", () => {+ // No row in projects — UPDATE affects 0 rows; getProject returns null.+ expect(renameProject("nope", "X")).toBeNull();+ });+});++describe("changeProjectSlug", () => {+ it("renames slug and migrates child rows", () => {+ createProject({ display_name: "Old" });+ // Seed a row in each child table so we can verify the migration touches them all.+ testDb+ .prepare(+ `INSERT INTO tasks (id, project_slug, agent_id, brief, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("t1", "old", "old-cmo", "b", "proposed", "now", "now");+ testDb+ .prepare(+ `INSERT INTO approvals+ (id, project_slug, agent_id, action_summary, action_type, cost_estimate_usd, payload_json, status, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("ap1", "old", "old-cmo", "s", "other", 0, "{}", "pending", "now");+ testDb+ .prepare(+ `INSERT INTO cost_events (id, project_slug, agent_id, source, amount_usd, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run("c1", "old", null, "llm", 0.01, "now");+ testDb+ .prepare(+ `INSERT INTO oauth_tokens+ (id, project_slug, provider, account_label, access_token_enc, refresh_token_enc, expires_at, scope, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("o1", "old", "google_ads", "main", "x", "y", "later", "s", "now", "now");+ testDb+ .prepare(+ `INSERT INTO agent_actions (id, project_slug, agent_id, action_type, summary, occurred_at)+ VALUES (?, ?, ?, ?, ?, ?)`,+ )+ .run("a1", "old", "x", "t", "s", "now");+ testDb+ .prepare(+ `INSERT INTO sequence_runs+ (id, project_slug, agent_id, sequence_kind, cursor, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("s1", "old", "x", "k", "0", "pending", "now", "now");++ const out = changeProjectSlug("old", "renamed");+ expect(out).not.toBeNull();+ expect(out!.slug).toBe("renamed");++ // Every child table's row should now live under the new slug.+ for (const table of [+ "tasks",+ "approvals",+ "cost_events",+ "oauth_tokens",+ "agent_actions",+ "sequence_runs",+ ]) {+ const row = testDb+ .prepare(`SELECT project_slug FROM ${table} LIMIT 1`)+ .get() as { project_slug: string };+ expect(row.project_slug, table).toBe("renamed");+ }+ expect(getProject("old")).toBeNull();+ });++ it("also updates display_name when provided", () => {+ createProject({ display_name: "Old" });+ const out = changeProjectSlug("old", "new", "New Display");+ expect(out!.slug).toBe("new");+ expect(out!.display_name).toBe("New Display");+ });++ it("trims new display_name", () => {+ createProject({ display_name: "Old" });+ const out = changeProjectSlug("old", "new", " Padded ");+ expect(out!.display_name).toBe("Padded");+ });++ it("when old === new and display_name is provided, updates only display_name", () => {+ createProject({ display_name: "Acme" });+ const out = changeProjectSlug("acme", "acme", "Renamed");+ expect(out!.slug).toBe("acme");+ expect(out!.display_name).toBe("Renamed");+ });++ it("when old === new and no display_name, returns the current row (no-op)", () => {+ createProject({ display_name: "Acme" });+ const out = changeProjectSlug("acme", "acme");+ expect(out!.slug).toBe("acme");+ expect(out!.display_name).toBe("Acme");+ });++ it("returns null when the source slug doesn't exist", () => {+ expect(changeProjectSlug("missing", "new")).toBeNull();+ });++ it("throws when the destination slug already exists", () => {+ createProject({ display_name: "A" });+ createProject({ display_name: "B" });+ expect(() => changeProjectSlug("a", "b")).toThrow(/already exists/i);+ });++ it("restores foreign_keys = ON after the rename (even on failure)", () => {+ createProject({ display_name: "A" });+ // Pre-condition.+ expect(testDb.pragma("foreign_keys", { simple: true })).toBe(1);+ changeProjectSlug("a", "renamed");+ expect(testDb.pragma("foreign_keys", { simple: true })).toBe(1);+ });++ it("BUG: does not actually restore prior FK state (always leaves FK = ON)", () => {+ // Documenting current behavior. The implementation captures+ // const fkWasOn = db.pragma("foreign_keys = OFF", { simple: true });+ // expecting fkWasOn to be the previous value, but better-sqlite3's pragma+ // returns undefined for SET-style PRAGMAs. So the ternary always falls+ // through to "ON" regardless of prior state. Not a regression for our+ // single-user CLI (which always runs with FK=ON) but worth flagging.+ createProject({ display_name: "Acme" });+ testDb.pragma("foreign_keys = OFF");+ changeProjectSlug("acme", "new");+ // After the rename, FK ends up ON even though we started with FK=OFF.+ expect(testDb.pragma("foreign_keys", { simple: true })).toBe(1);+ });+});++describe("archiveProject", () => {+ it("sets archived_at and returns the row", () => {+ createProject({ display_name: "Acme" });+ const out = archiveProject("acme");+ expect(out!.archived_at).not.toBeNull();+ expect(Date.parse(out!.archived_at!)).toBeGreaterThan(0);+ });++ it("is a no-op when already archived (preserves first archived_at)", async () => {+ createProject({ display_name: "Acme" });+ const first = archiveProject("acme")!;+ await new Promise((r) => setTimeout(r, 5));+ const second = archiveProject("acme")!;+ expect(second.archived_at).toBe(first.archived_at);+ });++ it("returns null when project doesn't exist", () => {+ expect(archiveProject("nope")).toBeNull();+ });+});++describe("unarchiveProject", () => {+ it("clears archived_at and returns the row", () => {+ createProject({ display_name: "Acme" });+ archiveProject("acme");+ expect(getProject("acme")!.archived_at).not.toBeNull();+ const out = unarchiveProject("acme");+ expect(out!.archived_at).toBeNull();+ });++ it("is a no-op when project is not archived", () => {+ createProject({ display_name: "Acme" });+ const out = unarchiveProject("acme");+ expect(out!.archived_at).toBeNull();+ });++ it("returns null when project doesn't exist", () => {+ expect(unarchiveProject("nope")).toBeNull();+ });+});+describe("deleteProjectRow", () => {it("cleans the project row when no child rows exist", () => {const result = createProject({ display_name: "Acme" });@@ -44,12 +391,16 @@ describe("deleteProjectRow", () => {expect(testDb.prepare("SELECT 1 FROM projects WHERE slug = ?").get("acme")).toBeUndefined();});+ it("is a no-op when project doesn't exist", () => {+ expect(() => deleteProjectRow("missing")).not.toThrow();+ });+describe("regression: FOREIGN KEY constraint failure on delete", () => {// The bug: deleteProjectRow's childTables list was stale — it deleted- // from guardrails/approvals/agent_actions/cost_snapshots/connections- // (the last two don't even exist in our migrations), missing tasks,- // cost_events, oauth_tokens, sequence_runs. With orchestration adding- // task rows aggressively, deletes started tripping the FK constraint.+ // from approvals/agent_actions/cost_snapshots/connections (the last+ // two don't even exist in our migrations), missing tasks, cost_events,+ // oauth_tokens, sequence_runs. With orchestration adding task rows+ // aggressively, deletes started tripping the FK constraint.// This block populates every FK-bearing table and asserts the delete// succeeds + nothing is left behind.@@ -102,12 +453,6 @@ describe("deleteProjectRow", () => {VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,).run("o1", "acme", "google_ads", "acme", "x", "y", "later", "scope", "now", "now");- testDb- .prepare(- `INSERT INTO guardrails (project_slug, config_json, updated_at)- VALUES (?, ?, ?)`,- )- .run("acme", "{}", "now");testDb.prepare(`INSERT INTO agent_actions@@ -129,7 +474,6 @@ describe("deleteProjectRow", () => {"approvals","cost_events","oauth_tokens",- "guardrails","agent_actions","sequence_runs",]) {@@ -151,7 +495,6 @@ describe("deleteProjectRow", () => {"approvals","cost_events","oauth_tokens",- "guardrails","agent_actions","sequence_runs",]) {diff --git a/src/server/db/tasks.test.ts b/src/server/db/tasks.test.tsnew file mode 100644index 00000000..c7993904--- /dev/null+++ b/src/server/db/tasks.test.ts@@ -0,0 +1,441 @@+import Database from "better-sqlite3";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { MIGRATIONS } from "./migrations";++let testDb: Database.Database;++vi.mock("./db", () => ({+ getDb: () => testDb,+ getDbPath: () => ":memory:",+}));++import {+ claimProposedTask,+ createTask,+ getTask,+ inFlightCountsByAgent,+ listTasks,+ listTasksByAgent,+ setTaskThreadIfMissing,+ updateTask,+} from "./tasks";++function applyMigrations(db: Database.Database): void {+ for (const migration of MIGRATIONS) {+ db.exec(migration.sql);+ }+}++function createDb(): Database.Database {+ const db = new Database(":memory:");+ db.pragma("foreign_keys = ON");+ applyMigrations(db);+ return db;+}++function seedProject(slug = "acme"): void {+ testDb+ .prepare(+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",+ )+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");+}++beforeEach(() => {+ testDb = createDb();+});++afterEach(() => {+ testDb.close();+});++describe("createTask", () => {+ it("creates a proposed task with sensible defaults", () => {+ seedProject();+ const t = createTask({+ project_slug: "acme",+ agent_id: "acme-cmo",+ brief: "do the thing",+ });+ expect(t.id).toMatch(/[0-9a-f-]{36}/);+ expect(t.display_id).toBe("acme-1");+ expect(t.status).toBe("proposed");+ expect(t.title).toBeNull();+ expect(t.success_criteria).toBeNull();+ expect(t.deadline_iso).toBeNull();+ expect(t.thread_id).toBeNull();+ expect(t.assigner_agent_id).toBeNull();+ expect(t.result_json).toBeNull();+ expect(t.error_message).toBeNull();+ expect(Date.parse(t.created_at)).toBeGreaterThan(0);+ expect(t.updated_at).toBe(t.created_at);+ });++ it("stores optional fields when provided", () => {+ seedProject();+ const t = createTask({+ project_slug: "acme",+ agent_id: "acme-google-ads",+ title: "Raise bid",+ brief: "Raise bid to $2.50 on shoes",+ success_criteria: "CPA stays < $30",+ deadline_iso: "2026-12-31T23:59:59.000Z",+ assigner_agent_id: "acme-cmo",+ status: "approved",+ });+ expect(t.title).toBe("Raise bid");+ expect(t.success_criteria).toBe("CPA stays < $30");+ expect(t.deadline_iso).toBe("2026-12-31T23:59:59.000Z");+ expect(t.assigner_agent_id).toBe("acme-cmo");+ expect(t.status).toBe("approved");+ });++ it("allocates monotonically increasing display_ids per project", () => {+ seedProject("acme");+ seedProject("other");+ const a1 = createTask({ project_slug: "acme", agent_id: "x", brief: "1" });+ const a2 = createTask({ project_slug: "acme", agent_id: "x", brief: "2" });+ const a3 = createTask({ project_slug: "acme", agent_id: "x", brief: "3" });+ const o1 = createTask({ project_slug: "other", agent_id: "x", brief: "1" });+ const o2 = createTask({ project_slug: "other", agent_id: "x", brief: "2" });+ expect(a1.display_id).toBe("acme-1");+ expect(a2.display_id).toBe("acme-2");+ expect(a3.display_id).toBe("acme-3");+ expect(o1.display_id).toBe("other-1");+ expect(o2.display_id).toBe("other-2");+ });++ it("display_id allocator picks up after manually inserted high N", () => {+ seedProject();+ // Insert a row with display_id "acme-7" so the next createTask picks acme-8.+ testDb+ .prepare(+ `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("u1", "acme-7", "acme", "x", "b", "proposed", "now", "now");+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "next" });+ expect(t.display_id).toBe("acme-8");+ });++ it("display_id is unique (UNIQUE INDEX from migration 004)", () => {+ seedProject();+ createTask({ project_slug: "acme", agent_id: "x", brief: "a" });+ // Manually attempting to insert another acme-1 must fail at the DB layer.+ expect(() =>+ testDb+ .prepare(+ `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("dupe", "acme-1", "acme", "x", "b", "proposed", "now", "now"),+ ).toThrow(/UNIQUE/i);+ });++ it("trips FK on missing project", () => {+ expect(() =>+ createTask({ project_slug: "no-such", agent_id: "x", brief: "b" }),+ ).toThrow(/FOREIGN KEY/i);+ });++ it("rejects invalid status via CHECK constraint", () => {+ seedProject();+ expect(() =>+ createTask({+ project_slug: "acme",+ agent_id: "x",+ brief: "b",+ // @ts-expect-error invalid on purpose+ status: "bogus",+ }),+ ).toThrow(/CHECK/i);+ });+});++describe("getTask", () => {+ it("finds a task by UUID", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ const out = getTask(t.id);+ expect(out).not.toBeNull();+ expect(out!.id).toBe(t.id);+ });++ it("finds a task by display_id", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ const out = getTask(t.display_id);+ expect(out).not.toBeNull();+ expect(out!.id).toBe(t.id);+ });++ it("returns null when neither match", () => {+ expect(getTask("not-there")).toBeNull();+ });+});++describe("listTasks", () => {+ it("returns all tasks for project ordered by created_at DESC", () => {+ seedProject();+ testDb+ .prepare(+ `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("t1", "acme-1", "acme", "x", "first", "proposed", "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z");+ testDb+ .prepare(+ `INSERT INTO tasks (id, display_id, project_slug, agent_id, brief, status, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run("t2", "acme-2", "acme", "x", "second", "running", "2026-01-02T00:00:00.000Z", "2026-01-02T00:00:00.000Z");++ const rows = listTasks("acme");+ expect(rows.map((r) => r.brief)).toEqual(["second", "first"]);+ });++ it("filters by status when provided", () => {+ seedProject();+ createTask({ project_slug: "acme", agent_id: "x", brief: "p" });+ createTask({ project_slug: "acme", agent_id: "x", brief: "r", status: "running" });+ expect(listTasks("acme", "proposed")).toHaveLength(1);+ expect(listTasks("acme", "running")).toHaveLength(1);+ expect(listTasks("acme", "succeeded")).toHaveLength(0);+ });++ it("isolates by project", () => {+ seedProject("a");+ seedProject("b");+ createTask({ project_slug: "a", agent_id: "x", brief: "1" });+ createTask({ project_slug: "b", agent_id: "x", brief: "1" });+ expect(listTasks("a")).toHaveLength(1);+ expect(listTasks("b")).toHaveLength(1);+ });+});++describe("listTasksByAgent", () => {+ it("returns tasks for the agent across projects", () => {+ seedProject("a");+ seedProject("b");+ createTask({ project_slug: "a", agent_id: "specialist", brief: "1" });+ createTask({ project_slug: "b", agent_id: "specialist", brief: "2" });+ createTask({ project_slug: "a", agent_id: "other-agent", brief: "x" });+ expect(listTasksByAgent("specialist")).toHaveLength(2);+ expect(listTasksByAgent("other-agent")).toHaveLength(1);+ });++ it("filters by status", () => {+ seedProject();+ createTask({ project_slug: "acme", agent_id: "a1", brief: "p" });+ createTask({+ project_slug: "acme",+ agent_id: "a1",+ brief: "r",+ status: "running",+ });+ expect(listTasksByAgent("a1", "running")).toHaveLength(1);+ expect(listTasksByAgent("a1", "proposed")).toHaveLength(1);+ });++ it("returns empty array when no tasks assigned", () => {+ expect(listTasksByAgent("nobody")).toEqual([]);+ });+});++describe("inFlightCountsByAgent", () => {+ it("counts only proposed/approved/running per agent", () => {+ seedProject();+ createTask({ project_slug: "acme", agent_id: "ads", brief: "1" }); // proposed+ createTask({+ project_slug: "acme",+ agent_id: "ads",+ brief: "2",+ status: "approved",+ });+ createTask({+ project_slug: "acme",+ agent_id: "ads",+ brief: "3",+ status: "running",+ });+ createTask({+ project_slug: "acme",+ agent_id: "ads",+ brief: "4",+ status: "succeeded",+ });+ createTask({+ project_slug: "acme",+ agent_id: "seo",+ brief: "1",+ status: "running",+ });+ createTask({+ project_slug: "acme",+ agent_id: "seo",+ brief: "2",+ status: "failed",+ });+ createTask({+ project_slug: "acme",+ agent_id: "seo",+ brief: "3",+ status: "cancelled",+ });++ const map = inFlightCountsByAgent("acme");+ expect(map.get("ads")).toBe(3);+ expect(map.get("seo")).toBe(1);+ });++ it("returns an empty map when no in-flight tasks exist", () => {+ seedProject();+ createTask({ project_slug: "acme", agent_id: "x", brief: "1", status: "succeeded" });+ const map = inFlightCountsByAgent("acme");+ expect(map.size).toBe(0);+ });++ it("isolates by project", () => {+ seedProject("a");+ seedProject("b");+ createTask({ project_slug: "a", agent_id: "ads", brief: "1" });+ createTask({ project_slug: "b", agent_id: "ads", brief: "1" });+ expect(inFlightCountsByAgent("a").get("ads")).toBe(1);+ expect(inFlightCountsByAgent("b").get("ads")).toBe(1);+ });+});++describe("setTaskThreadIfMissing", () => {+ it("sets thread_id when null and bumps updated_at", async () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ // sleep so updated_at can advance+ await new Promise((r) => setTimeout(r, 5));+ const out = setTaskThreadIfMissing(t.id, "thread-1");+ expect(out).not.toBeNull();+ expect(out!.thread_id).toBe("thread-1");+ expect(Date.parse(out!.updated_at)).toBeGreaterThanOrEqual(+ Date.parse(t.updated_at),+ );+ });++ it("is a no-op when thread_id is already set (returns current row)", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ setTaskThreadIfMissing(t.id, "first");+ const after = setTaskThreadIfMissing(t.id, "second");+ expect(after!.thread_id).toBe("first");+ });++ it("returns null when the task doesn't exist", () => {+ expect(setTaskThreadIfMissing("nope", "t")).toBeNull();+ });++ it("works via display_id (getTask accepts either)", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ // Pass display_id; setTaskThreadIfMissing -> getTask first resolves the+ // current row, but the UPDATE itself uses the PK from the input which is+ // the display_id here. The function signature says "id" — confirm what+ // actually happens. The UPDATE uses WHERE id = ?, and display_id won't+ // match the PK, so no row gets updated. The function returns the row+ // unchanged (getTask resolves display_id).+ const out = setTaskThreadIfMissing(t.display_id, "ignored");+ // Documenting current behavior: the lookup succeeds, the UPDATE filter+ // misses, and we return getTask(display_id) which still has null thread_id.+ expect(out).not.toBeNull();+ expect(out!.thread_id).toBeNull();+ });+});++describe("updateTask", () => {+ it("updates status, result, error_message and bumps updated_at", async () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ await new Promise((r) => setTimeout(r, 5));+ const out = updateTask(t.id, {+ status: "succeeded",+ result: { hello: "world" },+ error_message: null,+ });+ expect(out).not.toBeNull();+ expect(out!.status).toBe("succeeded");+ expect(out!.result_json).toBe(JSON.stringify({ hello: "world" }));+ expect(out!.error_message).toBeNull();+ expect(Date.parse(out!.updated_at)).toBeGreaterThanOrEqual(+ Date.parse(t.updated_at),+ );+ });++ it("keeps existing values when fields are omitted (status defaults to current)", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ updateTask(t.id, { result: { a: 1 } });+ const fetched = getTask(t.id);+ expect(fetched!.status).toBe("proposed"); // unchanged+ expect(fetched!.result_json).toBe(JSON.stringify({ a: 1 }));+ });++ it("explicit null error_message clears error", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ updateTask(t.id, { error_message: "boom" });+ expect(getTask(t.id)!.error_message).toBe("boom");+ updateTask(t.id, { error_message: null });+ expect(getTask(t.id)!.error_message).toBeNull();+ });++ it("returns null when task doesn't exist", () => {+ expect(updateTask("missing", { status: "running" })).toBeNull();+ });++ it("rejects invalid status via CHECK constraint", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ expect(() =>+ // @ts-expect-error invalid on purpose+ updateTask(t.id, { status: "bogus" }),+ ).toThrow(/CHECK/i);+ });+});++describe("claimProposedTask", () => {+ it("flips proposed → running and returns the post-flip row", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ const out = claimProposedTask(t.id);+ expect(out).not.toBeNull();+ expect(out!.status).toBe("running");+ });++ it("returns null when the task is already past proposed", () => {+ seedProject();+ const t = createTask({+ project_slug: "acme",+ agent_id: "x",+ brief: "b",+ status: "running",+ });+ expect(claimProposedTask(t.id)).toBeNull();+ });++ it("returns null when the task is terminal (succeeded)", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ updateTask(t.id, { status: "succeeded" });+ expect(claimProposedTask(t.id)).toBeNull();+ expect(getTask(t.id)!.status).toBe("succeeded"); // not regressed+ });++ it("returns null when the task doesn't exist", () => {+ expect(claimProposedTask("missing")).toBeNull();+ });++ it("is single-shot: a second call after a successful claim returns null", () => {+ seedProject();+ const t = createTask({ project_slug: "acme", agent_id: "x", brief: "b" });+ expect(claimProposedTask(t.id)!.status).toBe("running");+ expect(claimProposedTask(t.id)).toBeNull();+ });+});diff --git a/src/server/mcp-catalog.test.ts b/src/server/mcp-catalog.test.tsnew file mode 100644index 00000000..7231ecd2--- /dev/null+++ b/src/server/mcp-catalog.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest";++import { MCP_CATALOG, mcpSpecByKey, storedMcpKey } from "./mcp-catalog";++describe("MCP_CATALOG", () => {+ it("contains at least one spec", () => {+ expect(MCP_CATALOG.length).toBeGreaterThan(0);+ });++ it("includes the notfair-googleads spec with all required fields", () => {+ const ga = MCP_CATALOG.find((m) => m.key === "notfair-googleads");+ expect(ga).toBeDefined();+ expect(ga).toMatchObject({+ key: "notfair-googleads",+ display_name: expect.any(String),+ description: expect.any(String),+ resource_url: expect.stringMatching(/^https:\/\//),+ discovery_url: expect.stringMatching(/^https:\/\//),+ });+ });++ it("every spec has all required fields populated", () => {+ for (const spec of MCP_CATALOG) {+ expect(typeof spec.key).toBe("string");+ expect(spec.key.length).toBeGreaterThan(0);+ expect(typeof spec.display_name).toBe("string");+ expect(typeof spec.description).toBe("string");+ expect(typeof spec.resource_url).toBe("string");+ expect(typeof spec.discovery_url).toBe("string");+ }+ });++ it("every spec key is unique", () => {+ const keys = MCP_CATALOG.map((m) => m.key);+ const uniq = new Set(keys);+ expect(uniq.size).toBe(keys.length);+ });+});++describe("mcpSpecByKey", () => {+ it("returns the spec when key matches", () => {+ const spec = mcpSpecByKey("notfair-googleads");+ expect(spec).toBeDefined();+ expect(spec?.key).toBe("notfair-googleads");+ });++ it("returns undefined for an unknown key", () => {+ expect(mcpSpecByKey("does-not-exist")).toBeUndefined();+ });++ it("returns undefined for an empty key", () => {+ expect(mcpSpecByKey("")).toBeUndefined();+ });++ it("is case-sensitive — uppercase variant does not match", () => {+ expect(mcpSpecByKey("NOTFAIR-GOOGLEADS")).toBeUndefined();+ });+});++describe("storedMcpKey", () => {+ it("concatenates project slug + catalog key with a hyphen", () => {+ expect(storedMcpKey("acme", "notfair-googleads")).toBe(+ "acme-notfair-googleads",+ );+ });++ it("preserves multi-segment project slugs", () => {+ expect(storedMcpKey("acme-q4", "notfair-googleads")).toBe(+ "acme-q4-notfair-googleads",+ );+ });++ it("works with arbitrary catalog keys (not just ones in the catalog)", () => {+ expect(storedMcpKey("proj", "arbitrary-thing")).toBe("proj-arbitrary-thing");+ });++ it("handles empty project slug (no validation here — that's the caller's job)", () => {+ expect(storedMcpKey("", "notfair-googleads")).toBe("-notfair-googleads");+ });++ it("handles empty catalog key", () => {+ expect(storedMcpKey("acme", "")).toBe("acme-");+ });+});diff --git a/src/server/mcp-pending.test.ts b/src/server/mcp-pending.test.tsnew file mode 100644index 00000000..59694b1c--- /dev/null+++ b/src/server/mcp-pending.test.ts@@ -0,0 +1,130 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ consumePending,+ setPending,+ type PendingMcpFlow,+} from "./mcp-pending";++function makeFlow(overrides: Partial<PendingMcpFlow> = {}): PendingMcpFlow {+ return {+ catalog_key: "notfair-googleads",+ stored_key: "acme-notfair-googleads",+ display_name: "NotFair Google Ads",+ resource_url: "https://notfair.co/api/mcp/google_ads",+ issuer: "https://issuer.example",+ token_endpoint: "https://issuer.example/token",+ client_id: "client-abc",+ client_secret: "secret-xyz",+ code_verifier: "verifier-123",+ redirect_uri: "http://localhost:3326/callback",+ project_slug: "acme",+ return_to: "/chat",+ created_at: Date.now(),+ ...overrides,+ };+}++// Each test starts from a clean store — drain any leftovers from prior tests+// (the store hangs off globalThis, so state survives across files).+function drain() {+ // setPending+consumePending is the only public surface; we use a unique+ // sentinel state and then drain by reading globalThis directly to flush.+ type Slot = { store?: Map<string, unknown> };+ const slot = globalThis as unknown as Slot;+ slot.store?.clear();+}++describe("setPending / consumePending", () => {+ beforeEach(() => {+ drain();+ vi.useRealTimers();+ });++ afterEach(() => {+ drain();+ });++ it("stores a flow and returns it once on consume", () => {+ const flow = makeFlow();+ setPending("state-1", flow);+ expect(consumePending("state-1")).toEqual(flow);+ });++ it("a second consume returns null (pop semantics, not peek)", () => {+ setPending("state-2", makeFlow());+ consumePending("state-2");+ expect(consumePending("state-2")).toBeNull();+ });++ it("returns null for an unknown state", () => {+ expect(consumePending("never-set")).toBeNull();+ });++ it("isolates two different state keys", () => {+ const f1 = makeFlow({ project_slug: "acme" });+ const f2 = makeFlow({ project_slug: "globex" });+ setPending("s1", f1);+ setPending("s2", f2);+ expect(consumePending("s1")).toEqual(f1);+ expect(consumePending("s2")).toEqual(f2);+ });++ it("overwrites an existing flow when the same state is set twice", () => {+ setPending("dup", makeFlow({ project_slug: "first" }));+ setPending("dup", makeFlow({ project_slug: "second" }));+ const r = consumePending("dup");+ expect(r?.project_slug).toBe("second");+ });++ it("supports a flow without optional client_secret + return_to", () => {+ const minimal: PendingMcpFlow = {+ catalog_key: "notfair-googleads",+ stored_key: "acme-notfair-googleads",+ display_name: "NotFair Google Ads",+ resource_url: "https://notfair.co/api/mcp/google_ads",+ issuer: "https://issuer.example",+ token_endpoint: "https://issuer.example/token",+ client_id: "public-client",+ code_verifier: "v",+ redirect_uri: "http://localhost:3326/cb",+ project_slug: "acme",+ created_at: Date.now(),+ };+ setPending("public", minimal);+ expect(consumePending("public")).toEqual(minimal);+ });+});++describe("TTL eviction", () => {+ beforeEach(() => {+ drain();+ });++ afterEach(() => {+ drain();+ });++ it("evicts entries older than the 10-minute TTL on setPending", () => {+ // Flow created 11 minutes ago — older than TTL.+ const oldFlow = makeFlow({ created_at: Date.now() - 11 * 60 * 1000 });+ setPending("stale", oldFlow);+ // Touch via a fresh set call — eviction runs at the top of setPending too.+ setPending("fresh", makeFlow());+ expect(consumePending("stale")).toBeNull();+ expect(consumePending("fresh")).not.toBeNull();+ });++ it("evicts entries older than the 10-minute TTL on consumePending", () => {+ const stale = makeFlow({ created_at: Date.now() - 11 * 60 * 1000 });+ setPending("evict-me", stale);+ // consume itself should evict before the lookup.+ expect(consumePending("evict-me")).toBeNull();+ });++ it("keeps entries newer than TTL — exactly-9-minute-old flow survives", () => {+ const recent = makeFlow({ created_at: Date.now() - 9 * 60 * 1000 });+ setPending("recent", recent);+ expect(consumePending("recent")).toEqual(recent);+ });+});diff --git a/src/server/mcp-state.test.ts b/src/server/mcp-state.test.tsnew file mode 100644index 00000000..6ea1919e--- /dev/null+++ b/src/server/mcp-state.test.ts@@ -0,0 +1,336 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { OpenClawError } from "@/server/openclaw/cli";++// ── Mocks ──────────────────────────────────────────────────────────++const openclawMock = vi.fn();+vi.mock("@/server/openclaw/cli", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/server/openclaw/cli")>();+ return {+ ...actual,+ openclaw: (...args: unknown[]) => openclawMock(...args),+ };+});++const readMcpConfigRowMock = vi.fn();+const bearerFromHeadersMock = vi.fn();+const mcpRpcMock = vi.fn();+vi.mock("@/server/mcp/rpc", () => ({+ readMcpConfigRow: (...args: unknown[]) => readMcpConfigRowMock(...args),+ bearerFromHeaders: (...args: unknown[]) => bearerFromHeadersMock(...args),+ mcpRpc: (...args: unknown[]) => mcpRpcMock(...args),+}));++import { disconnectMcp, getMcpStatus, setMcpBearer } from "./mcp-state";++describe("getMcpStatus", () => {+ beforeEach(() => {+ readMcpConfigRowMock.mockReset();+ bearerFromHeadersMock.mockReset();+ mcpRpcMock.mockReset();+ });++ it("returns not_configured when no row", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce(null);+ await expect(getMcpStatus("k")).resolves.toEqual({ state: "not_configured" });+ expect(mcpRpcMock).not.toHaveBeenCalled();+ });++ it("returns not_configured when row has no url", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({ transport: "streamable-http" });+ await expect(getMcpStatus("k")).resolves.toEqual({ state: "not_configured" });+ });++ it("returns configured_no_token when row has url but no bearer", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({ url: "https://x", headers: {} });+ bearerFromHeadersMock.mockReturnValueOnce(null);+ await expect(getMcpStatus("k")).resolves.toEqual({+ state: "configured_no_token",+ url: "https://x",+ });+ expect(mcpRpcMock).not.toHaveBeenCalled();+ });++ it("returns connected with tools_count when probe succeeds with array of tools", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: true,+ result: { tools: [{ name: "a" }, { name: "b" }, { name: "c" }] },+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({+ state: "connected",+ url: "https://x",+ tools_count: 3,+ });+ if (r.state === "connected") {+ expect(typeof r.last_checked_at).toBe("string");+ expect(new Date(r.last_checked_at).toString()).not.toBe("Invalid Date");+ }+ });++ it("returns connected with tools_count=null when result has no tools field", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({ ok: true, result: { something: "else" } });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "connected", tools_count: null });+ });++ it("returns connected with tools_count=null when tools is not an array", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: true,+ result: { tools: "not-an-array" },+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "connected", tools_count: null });+ });++ it("returns connected with tools_count=null when result is undefined", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({ ok: true, result: undefined });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "connected", tools_count: null });+ });++ it("returns stale_token on 401", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: false,+ kind: "http_error",+ status: 401,+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({+ state: "stale_token",+ url: "https://x",+ http_status: 401,+ });+ });++ it("returns stale_token on 403", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: false,+ kind: "http_error",+ status: 403,+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "stale_token", http_status: 403 });+ });++ it("returns unreachable HTTP 500 on other http_error", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: false,+ kind: "http_error",+ status: 500,+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "unreachable", error: "HTTP 500" });+ });++ it("returns unreachable on timeout", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({ ok: false, kind: "timeout" });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "unreachable", error: "timed out" });+ });++ it("returns unreachable on aborted", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({ ok: false, kind: "aborted" });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "unreachable", error: "aborted" });+ });++ it("returns unreachable on rpc_error with code + message", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: false,+ kind: "rpc_error",+ code: -32601,+ message: "Method not found",+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({+ state: "unreachable",+ error: "rpc error -32601: Method not found",+ });+ });++ it("returns unreachable on malformed_response", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: false,+ kind: "malformed_response",+ message: "empty body",+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({+ state: "unreachable",+ error: "malformed response: empty body",+ });+ });++ it("returns unreachable on network_error using the raw message", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({+ ok: false,+ kind: "network_error",+ message: "ECONNREFUSED",+ });+ const r = await getMcpStatus("k");+ expect(r).toMatchObject({ state: "unreachable", error: "ECONNREFUSED" });+ });++ it("passes the configured 2s timeout to mcpRpc", async () => {+ readMcpConfigRowMock.mockResolvedValueOnce({+ url: "https://x",+ headers: { Authorization: "Bearer t" },+ });+ bearerFromHeadersMock.mockReturnValueOnce("t");+ mcpRpcMock.mockResolvedValueOnce({ ok: true, result: { tools: [] } });+ await getMcpStatus("k");+ expect(mcpRpcMock).toHaveBeenCalledWith(+ "https://x",+ "t",+ "tools/list",+ {},+ { timeoutMs: 2000 },+ );+ });+});++describe("disconnectMcp", () => {+ beforeEach(() => {+ openclawMock.mockReset();+ });++ it("calls `openclaw mcp unset <key>` with json:false", async () => {+ openclawMock.mockResolvedValueOnce(undefined);+ await disconnectMcp("acme-notfair-googleads");+ expect(openclawMock).toHaveBeenCalledWith(+ ["mcp", "unset", "acme-notfair-googleads"],+ { json: false },+ );+ });++ it("swallows OpenClawError when stderr says 'not found' (idempotent)", async () => {+ openclawMock.mockRejectedValueOnce(+ new OpenClawError("exited", "key not found in config", 1),+ );+ await expect(disconnectMcp("missing")).resolves.toBeUndefined();+ });++ it("swallows OpenClawError when stderr says 'unknown' (idempotent)", async () => {+ openclawMock.mockRejectedValueOnce(+ new OpenClawError("exited", "unknown mcp key", 1),+ );+ await expect(disconnectMcp("missing")).resolves.toBeUndefined();+ });++ it("re-throws OpenClawError with unrelated stderr", async () => {+ openclawMock.mockRejectedValueOnce(+ new OpenClawError("exited", "permission denied", 1),+ );+ await expect(disconnectMcp("k")).rejects.toBeInstanceOf(OpenClawError);+ });++ it("re-throws OpenClawError when stderr is empty", async () => {+ openclawMock.mockRejectedValueOnce(new OpenClawError("exited", "", 1));+ await expect(disconnectMcp("k")).rejects.toBeInstanceOf(OpenClawError);+ });++ it("re-throws non-OpenClawError errors unchanged", async () => {+ openclawMock.mockRejectedValueOnce(new TypeError("nope"));+ await expect(disconnectMcp("k")).rejects.toBeInstanceOf(TypeError);+ });++ it("is case-insensitive on 'not found' matching", async () => {+ openclawMock.mockRejectedValueOnce(+ new OpenClawError("exited", "Key NOT FOUND in openclaw.json", 1),+ );+ await expect(disconnectMcp("k")).resolves.toBeUndefined();+ });+});++describe("setMcpBearer", () => {+ beforeEach(() => {+ openclawMock.mockReset();+ });++ it("calls `openclaw mcp set <key> <json>` with streamable-http transport + bearer", async () => {+ openclawMock.mockResolvedValueOnce(undefined);+ await setMcpBearer("acme-notfair-googleads", "https://x/mcp", "tok-abc");+ expect(openclawMock).toHaveBeenCalledWith(+ [+ "mcp",+ "set",+ "acme-notfair-googleads",+ JSON.stringify({+ url: "https://x/mcp",+ transport: "streamable-http",+ headers: { Authorization: "Bearer tok-abc" },+ }),+ ],+ { json: false },+ );+ });++ it("propagates errors from the underlying openclaw call", async () => {+ openclawMock.mockRejectedValueOnce(new Error("disk full"));+ await expect(+ setMcpBearer("k", "https://x", "t"),+ ).rejects.toThrow("disk full");+ });+});diff --git a/src/server/onboarding/accounts.test.ts b/src/server/onboarding/accounts.test.tsindex 74c774ba..e86e12d7 100644--- a/src/server/onboarding/accounts.test.ts+++ b/src/server/onboarding/accounts.test.ts@@ -52,6 +52,14 @@ vi.mock("@/server/agent-templates", () => ({agentNameFor: (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,}));+// setOnboardingAccountAction lazy-imports startTaskIfProposed to kick off the+// audit task at creation time. Stub it as a pass-through — the real kickoff+// path would spin up the gateway client, which has no place in this test.+const startTaskIfProposedMock = vi.fn((task: unknown) => task);+vi.mock("@/server/orchestration/run-task", () => ({+ startTaskIfProposed: (task: unknown) => startTaskIfProposedMock(task),+}));+import {listGoogleAdsAccounts,setOnboardingAccountAction,diff --git a/src/server/openclaw/agent-turn.test.ts b/src/server/openclaw/agent-turn.test.tsnew file mode 100644index 00000000..e0a216b9--- /dev/null+++ b/src/server/openclaw/agent-turn.test.ts@@ -0,0 +1,214 @@+import { EventEmitter } from "node:events";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const spawnMock = vi.fn();+vi.mock("node:child_process", () => ({+ spawn: (cmd: string, args: string[], opts?: unknown) => spawnMock(cmd, args, opts),+}));++import { streamAgentTurn } from "./agent-turn";++type FakeChild = EventEmitter & {+ stdout: EventEmitter;+ stderr: EventEmitter;+ kill: ReturnType<typeof vi.fn>;+};++function makeChild(): FakeChild {+ const proc = new EventEmitter() as FakeChild;+ proc.stdout = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.kill = vi.fn(() => true);+ return proc;+}++async function collect(gen: AsyncGenerator<string, void, void>): Promise<string[]> {+ const out: string[] = [];+ for await (const chunk of gen) out.push(chunk);+ return out;+}++describe("streamAgentTurn", () => {+ beforeEach(() => {+ spawnMock.mockReset();+ });++ afterEach(() => {+ spawnMock.mockReset();+ });++ it("spawns openclaw with --agent and --message args", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ await collect(streamAgentTurn({ agent: "demo-cmo", message: "hi" }));+ expect(spawnMock).toHaveBeenCalledTimes(1);+ const [cmd, args] = spawnMock.mock.calls[0]!;+ expect(cmd).toBe("openclaw");+ expect(args).toEqual(["agent", "--agent", "demo-cmo", "--message", "hi"]);+ });++ it("includes --session-id when provided", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ await collect(streamAgentTurn({ agent: "a", message: "m", sessionId: "sess-1" }));+ const args = spawnMock.mock.calls[0]![1] as string[];+ expect(args).toContain("--session-id");+ expect(args[args.indexOf("--session-id") + 1]).toBe("sess-1");+ });++ it("includes --thinking flag when provided", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ await collect(streamAgentTurn({ agent: "a", message: "m", thinking: "high" }));+ const args = spawnMock.mock.calls[0]![1] as string[];+ expect(args).toContain("--thinking");+ expect(args[args.indexOf("--thinking") + 1]).toBe("high");+ });++ it("yields stdout chunks as they arrive", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("data", Buffer.from("hello "));+ child.stdout.emit("data", Buffer.from("world"));+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ const chunks = await collect(streamAgentTurn({ agent: "a", message: "m" }));+ expect(chunks.join("")).toBe("hello world");+ });++ it("throws when openclaw exits non-zero, including stderr in error message", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stderr.emit("data", Buffer.from("auth failed: token expired"));+ child.stdout.emit("end");+ child.emit("close", 7);+ });+ await expect(+ collect(streamAgentTurn({ agent: "a", message: "m" })),+ ).rejects.toThrow(/exited with code 7/);+ });++ it("includes stderr snippet in the thrown error", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stderr.emit("data", Buffer.from("boom!"));+ child.stdout.emit("end");+ child.emit("close", 1);+ });+ let caught: unknown;+ try {+ await collect(streamAgentTurn({ agent: "a", message: "m" }));+ } catch (err) {+ caught = err;+ }+ expect((caught as Error).message).toMatch(/boom!/);+ });++ it("truncates very long stderr to 500 chars in the error message", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ const longErr = "x".repeat(2000);+ setImmediate(() => {+ child.stderr.emit("data", Buffer.from(longErr));+ child.stdout.emit("end");+ child.emit("close", 1);+ });+ let caught: unknown;+ try {+ await collect(streamAgentTurn({ agent: "a", message: "m" }));+ } catch (err) {+ caught = err;+ }+ const msg = (caught as Error).message;+ expect(msg.length).toBeLessThan(longErr.length);+ expect(msg).toMatch(/x{200,500}/);+ });++ it("propagates process 'error' events", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ // Don't emit close — emit error to trigger rejectErr path.+ child.emit("error", new Error("ENOENT openclaw"));+ // After throwing, also emit close so any internal waiters resolve.+ child.stdout.emit("end");+ child.emit("close", null);+ });+ await expect(+ collect(streamAgentTurn({ agent: "a", message: "m" })),+ ).rejects.toThrow(/ENOENT openclaw/);+ });++ it("clears the kill timer on success (timeout never fires)", async () => {+ vi.useFakeTimers();+ try {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ // Schedule end on the next macrotask under fake timers.+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ const p = collect(streamAgentTurn({ agent: "a", message: "m", timeoutMs: 1000 }));+ // Advance to drain queued setImmediates.+ await vi.advanceTimersByTimeAsync(0);+ await p;+ // Advance well past the timeout — kill should NOT have been called.+ vi.advanceTimersByTime(60_000);+ expect(child.kill).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it("uses default 300s timeout when none provided", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ await collect(streamAgentTurn({ agent: "a", message: "m" }));+ // No assertion error means default timeout was set without crashing.+ expect(child.kill).not.toHaveBeenCalled();+ });++ it("yields nothing when the process emits no stdout but exits cleanly", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ const chunks = await collect(streamAgentTurn({ agent: "a", message: "m" }));+ expect(chunks).toEqual([]);+ });++ it("passes the right stdio config to spawn", async () => {+ const child = makeChild();+ spawnMock.mockImplementationOnce(() => child);+ setImmediate(() => {+ child.stdout.emit("end");+ child.emit("close", 0);+ });+ await collect(streamAgentTurn({ agent: "a", message: "m" }));+ const opts = spawnMock.mock.calls[0]![2] as { stdio: [string, string, string] };+ expect(opts.stdio).toEqual(["ignore", "pipe", "pipe"]);+ });+});diff --git a/src/server/openclaw/cli.test.ts b/src/server/openclaw/cli.test.tsindex f3262130..5e75b7b8 100644--- a/src/server/openclaw/cli.test.ts+++ b/src/server/openclaw/cli.test.ts@@ -8,7 +8,14 @@ vi.mock("node:child_process", () => ({spawn: (cmd: string, args: string[]) => spawnMock(cmd, args),}));-import { OpenClawError, openclaw } from "./cli";+import {+ OpenClawError,+ getHealth,+ isOpenClawAvailable,+ listAgents,+ listCrons,+ openclaw,+} from "./cli";type SpawnResult = {stdout?: string;@@ -260,4 +267,165 @@ describe("openclaw cli", () => {await expect(succeeding).resolves.toEqual({ ok: true });});});++ describe("spawn-level errors", () => {+ it("maps ENOENT (openclaw not installed) into a friendly message", async () => {+ spawnMock.mockImplementationOnce(() => {+ const proc = new EventEmitter() as FakeChild;+ proc.stdout = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.kill = () => true;+ // No close — the 'error' handler is the terminal event for this case.+ setImmediate(() => {+ const err = new Error("spawn openclaw ENOENT") as NodeJS.ErrnoException;+ err.code = "ENOENT";+ proc.emit("error", err);+ });+ return proc;+ });++ let caught: unknown;+ try {+ await openclaw(["agents", "list"]);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(OpenClawError);+ const e = caught as OpenClawError;+ expect(e.message).toMatch(/openclaw not found on PATH/i);+ expect(e.exitCode).toBeNull();+ });++ it("maps a generic spawn error into an OpenClawError", async () => {+ spawnMock.mockImplementationOnce(() => {+ const proc = new EventEmitter() as FakeChild;+ proc.stdout = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.kill = () => true;+ setImmediate(() => {+ proc.stderr.emit("data", Buffer.from("buffered stderr"));+ proc.emit("error", new Error("something exploded"));+ });+ return proc;+ });++ let caught: unknown;+ try {+ await openclaw(["foo"]);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(OpenClawError);+ const e = caught as OpenClawError;+ expect(e.message).toMatch(/something exploded/);+ expect(e.stderr).toMatch(/buffered stderr/);+ expect(e.exitCode).toBeNull();+ });+ });++ describe("convenience wrappers", () => {+ it("listAgents spawns `agents list --json` and returns parsed JSON", async () => {+ spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "[]", exitCode: 0 }));+ const r = await listAgents();+ expect(r).toEqual([]);+ expect(spawnMock).toHaveBeenCalledWith("openclaw", ["agents", "list", "--json"]);+ });++ it("listCrons spawns `cron list --json` and returns parsed JSON", async () => {+ spawnMock.mockImplementationOnce(() => fakeChild({ stdout: '[{"id":"x"}]', exitCode: 0 }));+ const r = await listCrons();+ expect(r).toEqual([{ id: "x" }]);+ expect(spawnMock).toHaveBeenCalledWith("openclaw", ["cron", "list", "--json"]);+ });++ it("getHealth spawns `health` without --json and returns raw stdout", async () => {+ spawnMock.mockImplementationOnce(() =>+ fakeChild({ stdout: "ok\n", exitCode: 0 }),+ );+ const r = await getHealth();+ expect(r).toBe("ok\n");+ expect(spawnMock).toHaveBeenCalledWith("openclaw", ["health"]);+ });++ it("isOpenClawAvailable returns true when --version exits 0", async () => {+ spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "v1.0.0\n", exitCode: 0 }));+ const ok = await isOpenClawAvailable();+ expect(ok).toBe(true);+ expect(spawnMock).toHaveBeenCalledWith("openclaw", ["--version"]);+ });++ it("isOpenClawAvailable returns false when the spawn fails", async () => {+ spawnMock.mockImplementationOnce(() => {+ const proc = new EventEmitter() as FakeChild;+ proc.stdout = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.kill = () => true;+ setImmediate(() => {+ const err = new Error("spawn openclaw ENOENT") as NodeJS.ErrnoException;+ err.code = "ENOENT";+ proc.emit("error", err);+ });+ return proc;+ });+ const ok = await isOpenClawAvailable();+ expect(ok).toBe(false);+ });+ });++ describe("timeout", () => {+ it("kills the subprocess and rejects when the process never closes", async () => {+ vi.useFakeTimers();+ try {+ let killed = false;+ spawnMock.mockImplementationOnce(() => {+ const proc = new EventEmitter() as FakeChild;+ proc.stdout = new EventEmitter();+ proc.stderr = new EventEmitter();+ proc.kill = () => {+ killed = true;+ return true;+ };+ // Never emit 'close' — let the internal timer fire.+ return proc;+ });++ const p = openclaw(["slow"], { timeout: 50 });+ // Attach a no-op catch so vitest doesn't warn about unhandled rejection.+ const observed = p.catch((err) => err);+ // Run the queue + spawn microtasks before advancing the fake clock.+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(50);+ const err = (await observed) as OpenClawError;+ expect(err).toBeInstanceOf(OpenClawError);+ expect(err.message).toMatch(/timed out after 50ms/);+ expect(killed).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });+ });++ describe("JSON parsing edge cases", () => {+ it("resolves to null when stdout is empty + json:true (default)", async () => {+ spawnMock.mockImplementationOnce(() => fakeChild({ stdout: "", exitCode: 0 }));+ const r = await openclaw(["empty"]);+ expect(r).toBeNull();+ });++ it("resolves to null when stdout is whitespace-only", async () => {+ spawnMock.mockImplementationOnce(() => fakeChild({ stdout: " \n ", exitCode: 0 }));+ const r = await openclaw(["whitespace"]);+ expect(r).toBeNull();+ });++ it("does not append --json when caller already included it explicitly", async () => {+ spawnMock.mockImplementationOnce(() =>+ fakeChild({ stdout: "{}", exitCode: 0 }),+ );+ await openclaw(["foo", "--json"]);+ // --json must appear exactly once.+ const args = spawnMock.mock.calls[0]![1] as string[];+ expect(args.filter((a) => a === "--json").length).toBe(1);+ });+ });});diff --git a/src/server/openclaw/clone-agent.test.ts b/src/server/openclaw/clone-agent.test.tsnew file mode 100644index 00000000..fab0f5fa--- /dev/null+++ b/src/server/openclaw/clone-agent.test.ts@@ -0,0 +1,493 @@+import { mkdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";+import { join } from "node:path";+import {+ afterAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++const { tmpHome, tmpData, ORIGINAL_HOME, ORIGINAL_DATA } = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { tmpdir } = require("node:os") as typeof import("node:os");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { join: joinPath } = require("node:path") as typeof import("node:path");+ const origHome = process.env.OPENCLAW_HOME;+ const origData = process.env.NOTFAIR_CMO_DATA_DIR;+ const home = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-clone-home-"));+ const data = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-clone-data-"));+ process.env.OPENCLAW_HOME = home;+ process.env.NOTFAIR_CMO_DATA_DIR = data;+ return {+ tmpHome: home,+ tmpData: data,+ ORIGINAL_HOME: origHome,+ ORIGINAL_DATA: origData,+ };+});++// Mock openclaw CLI subprocess.+const openclawMock = vi.fn();+vi.mock("./cli", () => ({+ openclaw: (...args: unknown[]) => openclawMock(...args),+}));++// Mock gateway-rpc methods used by clone-agent.+const createAgentViaRpcMock = vi.fn();+const listAgentFilesMock = vi.fn();+const getAgentFileMock = vi.fn();+const setAgentFileMock = vi.fn();+vi.mock("./gateway-rpc", () => ({+ createAgentViaRpc: (...args: unknown[]) => createAgentViaRpcMock(...args),+ listAgentFiles: (...args: unknown[]) => listAgentFilesMock(...args),+ getAgentFile: (...args: unknown[]) => getAgentFileMock(...args),+ setAgentFile: (...args: unknown[]) => setAgentFileMock(...args),+}));++import { agentExistsInProject, cloneAgent } from "./clone-agent";++function writeSourceSessionsDir(+ sourceAgent: string,+ sessionsJson: Record<string, unknown>,+ extras: Record<string, string> = {},+): void {+ const dir = join(tmpHome, "agents", sourceAgent, "sessions");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "sessions.json"), JSON.stringify(sessionsJson), "utf8");+ for (const [name, content] of Object.entries(extras)) {+ writeFileSync(join(dir, name), content, "utf8");+ }+}++beforeEach(() => {+ openclawMock.mockReset();+ createAgentViaRpcMock.mockReset();+ listAgentFilesMock.mockReset();+ getAgentFileMock.mockReset();+ setAgentFileMock.mockReset();+});++afterAll(() => {+ if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;+ else delete process.env.OPENCLAW_HOME;+ if (ORIGINAL_DATA) process.env.NOTFAIR_CMO_DATA_DIR = ORIGINAL_DATA;+ else delete process.env.NOTFAIR_CMO_DATA_DIR;+});++describe("agentExistsInProject", () => {+ it("returns false when neither dir exists", () => {+ expect(agentExistsInProject("none", "missing")).toBe(false);+ });++ it("returns true when notfair data dir has content", () => {+ const dir = join(tmpData, "agents", "p1-foo");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "meta"), "x", "utf8");+ expect(agentExistsInProject("p1", "foo")).toBe(true);+ });++ it("returns true when openclaw agent dir has content", () => {+ const dir = join(tmpHome, "agents", "p2-bar");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "marker"), "x", "utf8");+ expect(agentExistsInProject("p2", "bar")).toBe(true);+ });++ it("returns false when the dir exists but is empty (deleted remnant)", () => {+ const dir = join(tmpHome, "agents", "p3-empty");+ mkdirSync(dir, { recursive: true });+ expect(agentExistsInProject("p3", "empty")).toBe(false);+ });+});++describe("cloneAgent", () => {+ it("rejects an invalid user slug", async () => {+ await expect(+ cloneAgent({+ source_agent_id: "demo-cmo",+ project_slug: "demo",+ new_slug: "###",+ }),+ ).rejects.toThrow(/Invalid agent slug/);+ });++ it("rejects an invalid canonical slug when slug_is_canonical=true", async () => {+ await expect(+ cloneAgent({+ source_agent_id: "demo-cmo",+ project_slug: "demo",+ new_slug: "BAD SLUG",+ slug_is_canonical: true,+ }),+ ).rejects.toThrow(/Invalid canonical slug/);+ });++ it("allows reserved slugs when slug_is_canonical=true (relocate path)", async () => {+ // `cmo` is reserved in slugify but allowed as a canonical slug.+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ listAgentFilesMock.mockRejectedValueOnce(new Error("list down")); // exercise outer catch+ // No jobs.json so loadAllCrons returns [].+ const result = await cloneAgent({+ source_agent_id: "demo-cmo",+ project_slug: "fresh-proj-1",+ new_slug: "cmo",+ slug_is_canonical: true,+ });+ expect(result.new_slug).toBe("cmo");+ expect(result.new_agent_id).toBe("fresh-proj-1-cmo");+ expect(result.files_copied).toBe(0);+ expect(result.sessions_copied).toBe(0);+ expect(result.source_crons).toEqual([]);+ });++ it("throws when an agent at the target slug already exists in the project", async () => {+ // Pre-create the notfair sidecar dir to trigger agentExistsInProject.+ const dir = join(tmpData, "agents", "collide-cmo");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "x"), "1", "utf8");++ await expect(+ cloneAgent({+ source_agent_id: "demo-cmo",+ project_slug: "collide",+ new_slug: "cmo",+ slug_is_canonical: true,+ }),+ ).rejects.toThrow(/already exists in this project/);+ });++ it("copies workspace files via the gateway, skipping missing/erroring files", async () => {+ listAgentFilesMock.mockResolvedValueOnce({+ agentId: "src-cmo",+ workspace: "/ws",+ files: [+ { name: "REM.md", path: "/ws/REM.md", missing: false },+ { name: "GONE.md", path: "/ws/GONE.md", missing: true },+ { name: "BAD.md", path: "/ws/BAD.md", missing: false },+ { name: "OK.md", path: "/ws/OK.md", missing: false },+ ],+ });+ getAgentFileMock.mockImplementation(async (_id: string, name: string) => {+ if (name === "BAD.md") throw new Error("permission denied");+ return { agentId: "src-cmo", workspace: "/ws", file: { name, content: `body of ${name}` } };+ });+ setAgentFileMock.mockResolvedValue(undefined);+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);++ // Silence the SUT's console.error on the BAD.md skip.+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ const result = await cloneAgent({+ source_agent_id: "src-cmo",+ project_slug: "proj1",+ new_slug: "custom-clone",+ });+ // 2 files copied (REM.md, OK.md). GONE.md was missing, BAD.md errored.+ expect(result.files_copied).toBe(2);+ expect(setAgentFileMock).toHaveBeenCalledWith(+ "proj1-custom-clone",+ "REM.md",+ "body of REM.md",+ );+ expect(setAgentFileMock).toHaveBeenCalledWith(+ "proj1-custom-clone",+ "OK.md",+ "body of OK.md",+ );+ } finally {+ errSpy.mockRestore();+ }+ });++ it("copies sessions dir and rewrites sessions.json keys with the new agent prefix", async () => {+ const src = "srcproj-cmo";+ writeSourceSessionsDir(+ src,+ {+ "agent:srcproj-cmo:thread-1": { sessionId: "s1", updatedAt: 1 },+ "agent:srcproj-cmo:thread-2": { sessionId: "s2", updatedAt: 2 },+ // A key without our prefix is left untouched.+ "alien-key": { sessionId: "alien", updatedAt: 3 },+ },+ { "thread-1.jsonl": "log-line\n" },+ );++ listAgentFilesMock.mockResolvedValueOnce({ agentId: src, workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);++ const result = await cloneAgent({+ source_agent_id: src,+ project_slug: "dst",+ new_slug: "clone",+ });+ const dstSessionsDir = join(tmpHome, "agents", "dst-clone", "sessions");+ expect(existsSync(dstSessionsDir)).toBe(true);+ expect(existsSync(join(dstSessionsDir, "thread-1.jsonl"))).toBe(true);+ const rewritten = JSON.parse(+ readFileSync(join(dstSessionsDir, "sessions.json"), "utf8"),+ );+ expect(rewritten["agent:dst-clone:thread-1"]).toEqual({+ sessionId: "s1",+ updatedAt: 1,+ });+ expect(rewritten["agent:dst-clone:thread-2"]).toEqual({+ sessionId: "s2",+ updatedAt: 2,+ });+ // Alien keys are preserved as-is.+ expect(rewritten["alien-key"]).toEqual({ sessionId: "alien", updatedAt: 3 });+ expect(result.sessions_copied).toBe(3);+ });++ it("tolerates broken sessions.json by logging and reporting 0 sessions copied", async () => {+ const src = "broken-src";+ const dir = join(tmpHome, "agents", src, "sessions");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "sessions.json"), "{ not json", "utf8");++ listAgentFilesMock.mockResolvedValueOnce({ agentId: src, workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);++ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ const result = await cloneAgent({+ source_agent_id: src,+ project_slug: "broken-dst",+ new_slug: "clone",+ });+ // sessions.json existed but couldn't be parsed — 0 sessions copied, no throw.+ expect(result.sessions_copied).toBe(0);+ } finally {+ errSpy.mockRestore();+ }+ });++ it("recreates source crons under the new agent + project naming convention", async () => {+ // Write jobs.json with two crons assigned to the source agent + one+ // unrelated to a different agent (should be ignored).+ const cronDir = join(tmpHome, "cron");+ mkdirSync(cronDir, { recursive: true });+ writeFileSync(+ join(cronDir, "jobs.json"),+ JSON.stringify([+ {+ id: "c1",+ name: "src/agent/morning-job",+ agentId: "cron-src-cmo",+ description: "morning",+ schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },+ payload: { kind: "agentTurn", message: "do work" },+ },+ {+ id: "c2",+ name: "every-five",+ agentId: "cron-src-cmo",+ schedule: { kind: "every", everyMs: 5 * 60_000 },+ payload: { message: "tick" },+ enabled: false,+ },+ {+ id: "skip",+ name: "x",+ agentId: "other-agent",+ schedule: { kind: "cron", expr: "* * * * *" },+ },+ ]),+ "utf8",+ );++ listAgentFilesMock.mockResolvedValueOnce({ agentId: "cron-src-cmo", workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ // openclaw cron add — should be called twice, return ids.+ openclawMock+ .mockResolvedValueOnce({ id: "new-1" })+ .mockResolvedValueOnce({ id: "new-2" });++ const result = await cloneAgent({+ source_agent_id: "cron-src-cmo",+ project_slug: "destproj",+ new_slug: "destslug",+ });++ expect(result.new_cron_ids).toEqual(["new-1", "new-2"]);+ expect(result.source_crons.length).toBe(2);+ expect(result.source_crons.map((c) => c.id).sort()).toEqual(["c1", "c2"]);+ // c2 was enabled:false → disabled:true.+ const c2 = result.source_crons.find((c) => c.id === "c2")!;+ expect(c2.disabled).toBe(true);++ // First cron: cron expr + tz, --description + --message, --no-deliver.+ const firstArgs = openclawMock.mock.calls[0]![0] as string[];+ expect(firstArgs.slice(0, 2)).toEqual(["cron", "add"]);+ expect(firstArgs).toContain("--name");+ // Name = `<project>/<new-slug>/<last-segment-as-cron-slug>`. Source name+ // was "src/agent/morning-job" so last segment is "morning-job".+ const nameIdx = firstArgs.indexOf("--name");+ expect(firstArgs[nameIdx + 1]).toBe("destproj/destslug/morning-job");+ expect(firstArgs).toContain("--cron");+ expect(firstArgs).toContain("--tz");+ expect(firstArgs).toContain("--description");+ expect(firstArgs).toContain("--message");+ expect(firstArgs).toContain("--no-deliver");+ expect(firstArgs[firstArgs.indexOf("--message") + 1]).toBe("do work");+ // Agent target should be the NEW full id.+ expect(firstArgs[firstArgs.indexOf("--agent") + 1]).toBe("destproj-destslug");++ // Second cron: 'every' schedule + no description.+ const secondArgs = openclawMock.mock.calls[1]![0] as string[];+ expect(secondArgs).toContain("--every");+ expect(secondArgs[secondArgs.indexOf("--every") + 1]).toBe("5m");+ expect(secondArgs).not.toContain("--cron");+ expect(secondArgs).not.toContain("--description");+ });++ it("falls back to disabled hourly schedule when source has an unknown kind", async () => {+ const cronDir = join(tmpHome, "cron");+ mkdirSync(cronDir, { recursive: true });+ writeFileSync(+ join(cronDir, "jobs.json"),+ JSON.stringify([+ {+ id: "weird",+ name: "src/agent/weird",+ agentId: "weird-src-cmo",+ schedule: { kind: "moon-cycle" },+ },+ ]),+ "utf8",+ );++ listAgentFilesMock.mockResolvedValueOnce({ agentId: "weird-src-cmo", workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ openclawMock.mockResolvedValueOnce({ id: "new-weird" });++ await cloneAgent({+ source_agent_id: "weird-src-cmo",+ project_slug: "weirdproj",+ new_slug: "weirdslug",+ });+ const args = openclawMock.mock.calls[0]![0] as string[];+ expect(args).toContain("--every");+ expect(args[args.indexOf("--every") + 1]).toBe("1h");+ });++ it("handles jobs.json wrapped in {jobs: [...]}", async () => {+ const cronDir = join(tmpHome, "cron");+ mkdirSync(cronDir, { recursive: true });+ writeFileSync(+ join(cronDir, "jobs.json"),+ JSON.stringify({+ jobs: [+ {+ id: "j1",+ name: "src/agent/job",+ agentId: "wrap-src-cmo",+ schedule: { kind: "cron", expr: "0 9 * * *" },+ },+ ],+ }),+ "utf8",+ );++ listAgentFilesMock.mockResolvedValueOnce({ agentId: "wrap-src-cmo", workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ openclawMock.mockResolvedValueOnce({ id: "ok" });++ const r = await cloneAgent({+ source_agent_id: "wrap-src-cmo",+ project_slug: "wproj",+ new_slug: "wslug",+ });+ expect(r.new_cron_ids).toEqual(["ok"]);+ });++ it("continues when openclaw cron add fails on one cron", async () => {+ const cronDir = join(tmpHome, "cron");+ mkdirSync(cronDir, { recursive: true });+ writeFileSync(+ join(cronDir, "jobs.json"),+ JSON.stringify([+ {+ id: "p1",+ name: "src/agent/a",+ agentId: "partial-src-cmo",+ schedule: { kind: "cron", expr: "0 9 * * *" },+ },+ {+ id: "p2",+ name: "src/agent/b",+ agentId: "partial-src-cmo",+ schedule: { kind: "cron", expr: "0 9 * * *" },+ },+ ]),+ "utf8",+ );+ listAgentFilesMock.mockResolvedValueOnce({ agentId: "partial-src-cmo", workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ openclawMock+ .mockRejectedValueOnce(new Error("transient"))+ .mockResolvedValueOnce({ id: "ok-2" });++ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ const r = await cloneAgent({+ source_agent_id: "partial-src-cmo",+ project_slug: "pproj",+ new_slug: "pslug",+ });+ // source_crons still records BOTH; new_cron_ids only the one that succeeded.+ expect(r.source_crons.length).toBe(2);+ expect(r.new_cron_ids).toEqual(["ok-2"]);+ } finally {+ errSpy.mockRestore();+ }+ });++ it("writes the notfair-meta sidecar after a successful clone", async () => {+ listAgentFilesMock.mockResolvedValueOnce({ agentId: "meta-src", workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);++ await cloneAgent({+ source_agent_id: "meta-src",+ project_slug: "metaproj",+ new_slug: "metaclone",+ display_name: "Custom Display",+ });++ const metaPath = join(+ tmpData,+ "agents",+ "metaproj-metaclone",+ "notfair-meta.json",+ );+ expect(existsSync(metaPath)).toBe(true);+ const meta = JSON.parse(readFileSync(metaPath, "utf8"));+ expect(meta.agent_id).toBe("metaproj-metaclone");+ expect(meta.project_slug).toBe("metaproj");+ expect(meta.slug).toBe("metaclone");+ expect(meta.display_name).toBe("Custom Display");+ expect(meta.source_agent_id).toBe("meta-src");+ expect(typeof meta.created_at).toBe("string");+ });++ it("defaults display_name to the source agent id when not provided", async () => {+ listAgentFilesMock.mockResolvedValueOnce({ agentId: "no-display-src", workspace: "/ws", files: [] });+ createAgentViaRpcMock.mockResolvedValueOnce(undefined);+ await cloneAgent({+ source_agent_id: "no-display-src",+ project_slug: "ndproj",+ new_slug: "ndclone",+ });+ const meta = JSON.parse(+ readFileSync(+ join(tmpData, "agents", "ndproj-ndclone", "notfair-meta.json"),+ "utf8",+ ),+ );+ expect(meta.display_name).toBe("no-display-src");+ });+});diff --git a/src/server/openclaw/cron-schedule.test.ts b/src/server/openclaw/cron-schedule.test.tsnew file mode 100644index 00000000..0169a775--- /dev/null+++ b/src/server/openclaw/cron-schedule.test.ts@@ -0,0 +1,399 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const loadCronRunsMock = vi.fn();+vi.mock("./crons", () => ({+ loadCronRuns: (...args: unknown[]) => loadCronRunsMock(...args),+}));++import {+ annotateOccurrencesWithRunStatus,+ expandSchedule,+ groupOccurrencesByDay,+ tickAtOrBefore,+ type CronOccurrence,+} from "./cron-schedule";++const META = {+ name: "demo/agent/cron",+ short_name: "cron",+ agent_id: "demo-agent",+ agent_slug: "agent",+ schedule_text: "every 1m",+};++describe("expandSchedule", () => {+ it("returns [] when schedule is undefined", () => {+ expect(expandSchedule("c1", undefined, { from: 0, until: 1000 }, META)).toEqual([]);+ });++ it("returns [] when schedule.kind is unknown", () => {+ expect(+ expandSchedule(+ "c1",+ { kind: "weird", foo: "bar" } as never,+ { from: 0, until: 1000 },+ META,+ ),+ ).toEqual([]);+ });++ it("expands cron expression to multiple occurrences within window", () => {+ const from = new Date("2026-01-01T00:00:00Z").getTime();+ const until = from + 5 * 60 * 1000;+ const occs = expandSchedule(+ "c1",+ { kind: "cron", expr: "* * * * *", tz: "UTC" },+ { from, until },+ META,+ );+ expect(occs.length).toBeGreaterThan(0);+ expect(occs[0]?.cron_id).toBe("c1");+ expect(occs[0]?.cron_name).toBe(META.name);+ expect(occs[0]?.agent_slug).toBe(META.agent_slug);+ });++ it("respects maxPerCron cap on cron schedules", () => {+ const from = new Date("2026-01-01T00:00:00Z").getTime();+ const until = from + 1000 * 60 * 60;+ const occs = expandSchedule(+ "c1",+ { kind: "cron", expr: "* * * * *", tz: "UTC" },+ { from, until },+ META,+ 3,+ );+ expect(occs.length).toBe(3);+ });++ it("returns [] on invalid cron expression", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "cron", expr: "not a cron" },+ { from: 0, until: 100000 },+ META,+ );+ expect(occs).toEqual([]);+ });++ it("returns [] when cron.expr is not a string", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "cron", expr: 42 as unknown as string },+ { from: 0, until: 100000 },+ META,+ );+ expect(occs).toEqual([]);+ });++ it("expands 'every' schedule starting from `from` when no anchor", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "every", everyMs: 1000 },+ { from: 0, until: 3000 },+ META,+ );+ expect(occs.map((o) => o.at)).toEqual([0, 1000, 2000, 3000]);+ });++ it("expands 'every' schedule advancing past `from` from earlier anchor", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "every", everyMs: 1000, anchorMs: -500 },+ { from: 0, until: 2500 },+ META,+ );+ expect(occs.map((o) => o.at)).toEqual([500, 1500, 2500]);+ });++ it("expands 'every' schedule with anchor at exactly `from`", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "every", everyMs: 1000, anchorMs: 0 },+ { from: 0, until: 2000 },+ META,+ );+ expect(occs.map((o) => o.at)).toEqual([0, 1000, 2000]);+ });++ it("uses future anchor as the first occurrence", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "every", everyMs: 1000, anchorMs: 5000 },+ { from: 0, until: 7000 },+ META,+ );+ expect(occs.map((o) => o.at)).toEqual([5000, 6000, 7000]);+ });++ it("returns [] when everyMs <= 0", () => {+ expect(+ expandSchedule(+ "c1",+ { kind: "every", everyMs: 0 },+ { from: 0, until: 1000 },+ META,+ ),+ ).toEqual([]);+ expect(+ expandSchedule(+ "c1",+ { kind: "every", everyMs: -5 },+ { from: 0, until: 1000 },+ META,+ ),+ ).toEqual([]);+ });++ it("returns [] when every.everyMs is not a number", () => {+ expect(+ expandSchedule(+ "c1",+ { kind: "every", everyMs: "10" as unknown as number },+ { from: 0, until: 1000 },+ META,+ ),+ ).toEqual([]);+ });++ it("caps 'every' expansion at maxPerCron", () => {+ const occs = expandSchedule(+ "c1",+ { kind: "every", everyMs: 1 },+ { from: 0, until: 1_000_000 },+ META,+ 5,+ );+ expect(occs.length).toBe(5);+ });+});++describe("tickAtOrBefore", () => {+ it("returns undefined for undefined schedule", () => {+ expect(tickAtOrBefore(undefined, 1000)).toBeUndefined();+ });++ it("returns undefined for unknown kind", () => {+ expect(tickAtOrBefore({ kind: "weird" } as never, 1000)).toBeUndefined();+ });++ it("returns nearest tick at-or-before `at` for cron expr", () => {+ const at = new Date("2026-01-01T00:10:30Z").getTime();+ // Use a 1h lookback so we don't blow the 10k iteration cap inside.+ const tick = tickAtOrBefore(+ { kind: "cron", expr: "* * * * *", tz: "UTC" },+ at,+ 60 * 60 * 1000,+ );+ expect(tick).toBeDefined();+ expect(tick!).toBeLessThanOrEqual(at);+ expect(at - tick!).toBeLessThan(60_000);+ });++ it("returns undefined on invalid cron expr", () => {+ expect(tickAtOrBefore({ kind: "cron", expr: "garbage" }, 1000)).toBeUndefined();+ });++ it("returns undefined when cron.expr is not a string", () => {+ expect(+ tickAtOrBefore({ kind: "cron", expr: 5 as unknown as string }, 1000),+ ).toBeUndefined();+ });++ it("returns undefined when no tick exists in lookback window for cron", () => {+ const at = new Date("2026-01-01T00:00:00Z").getTime();+ // Lookback is 1ms; cron fires every minute so no tick in that window unless on boundary.+ const tick = tickAtOrBefore(+ { kind: "cron", expr: "*/30 * * * *", tz: "UTC" },+ at + 1,+ 1,+ );+ // Could be undefined or exactly `at`; either is acceptable per spec.+ if (tick !== undefined) {+ expect(tick).toBeLessThanOrEqual(at + 1);+ }+ });++ it("returns floor(k) tick for every schedule with anchor", () => {+ expect(tickAtOrBefore({ kind: "every", everyMs: 1000, anchorMs: 0 }, 3500)).toBe(3000);+ });++ it("returns the anchor when at == anchor", () => {+ expect(tickAtOrBefore({ kind: "every", everyMs: 1000, anchorMs: 1000 }, 1000)).toBe(1000);+ });++ it("returns undefined when anchor is in the future of `at`", () => {+ expect(tickAtOrBefore({ kind: "every", everyMs: 1000, anchorMs: 5000 }, 3000)).toBeUndefined();+ });++ it("returns undefined when every.everyMs <= 0", () => {+ expect(tickAtOrBefore({ kind: "every", everyMs: 0 }, 1000)).toBeUndefined();+ expect(tickAtOrBefore({ kind: "every", everyMs: -5 }, 1000)).toBeUndefined();+ });++ it("returns undefined when every.everyMs is not a number", () => {+ expect(+ tickAtOrBefore({ kind: "every", everyMs: "10" as unknown as number }, 1000),+ ).toBeUndefined();+ });++ it("defaults anchor to `at` when no anchorMs provided", () => {+ expect(tickAtOrBefore({ kind: "every", everyMs: 1000 }, 1234)).toBe(1234);+ });+});++describe("annotateOccurrencesWithRunStatus", () => {+ beforeEach(() => {+ loadCronRunsMock.mockReset();+ });++ it("annotates occurrences whose tick matches a run's owning tick", () => {+ const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;+ const occs: CronOccurrence[] = [+ {+ at: 1000,+ cron_id: "c1",+ cron_name: "n",+ short_name: "n",+ agent_id: "a",+ agent_slug: "a",+ schedule_text: "every 1s",+ },+ {+ at: 2000,+ cron_id: "c1",+ cron_name: "n",+ short_name: "n",+ agent_id: "a",+ agent_slug: "a",+ schedule_text: "every 1s",+ },+ ];+ loadCronRunsMock.mockReturnValueOnce([+ { run_at_ms: 1050, status: "ok" },+ { run_at_ms: 2100, status: "error" },+ ]);+ const out = annotateOccurrencesWithRunStatus(+ occs,+ new Map([["c1", schedule]]),+ );+ expect(out[0]!.run_status).toBe("ok");+ expect(out[1]!.run_status).toBe("error");+ expect(loadCronRunsMock).toHaveBeenCalledWith("c1", 200);+ });++ it("skips crons missing from the schedules map", () => {+ const occs: CronOccurrence[] = [+ {+ at: 1000,+ cron_id: "no-sched",+ cron_name: "n",+ short_name: "n",+ agent_id: "a",+ agent_slug: "a",+ schedule_text: "?",+ },+ ];+ const out = annotateOccurrencesWithRunStatus(occs, new Map());+ expect(out[0]!.run_status).toBeUndefined();+ expect(loadCronRunsMock).not.toHaveBeenCalled();+ });++ it("does not overwrite first-seen status when a later run has same owning tick", () => {+ const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;+ const occs: CronOccurrence[] = [+ {+ at: 1000,+ cron_id: "c1",+ cron_name: "n",+ short_name: "n",+ agent_id: "a",+ agent_slug: "a",+ schedule_text: "?",+ },+ ];+ loadCronRunsMock.mockReturnValueOnce([+ { run_at_ms: 1010, status: "ok" },+ { run_at_ms: 1500, status: "error" },+ ]);+ const out = annotateOccurrencesWithRunStatus(occs, new Map([["c1", schedule]]));+ expect(out[0]!.run_status).toBe("ok");+ });++ it("groups by cron id and only fetches each cron's runs once", () => {+ const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;+ const occs: CronOccurrence[] = [+ { at: 1000, cron_id: "c1", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: 2000, cron_id: "c1", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: 3000, cron_id: "c2", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ ];+ loadCronRunsMock.mockReturnValue([]);+ annotateOccurrencesWithRunStatus(+ occs,+ new Map([+ ["c1", schedule],+ ["c2", schedule],+ ]),+ );+ expect(loadCronRunsMock).toHaveBeenCalledTimes(2);+ });++ it("returns runs with no matching occurrence as unaffected", () => {+ const schedule = { kind: "every", everyMs: 1000, anchorMs: 0 } as const;+ const occs: CronOccurrence[] = [+ { at: 1000, cron_id: "c1", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ ];+ loadCronRunsMock.mockReturnValueOnce([+ { run_at_ms: 5050, status: "ok" }, // owning tick is 5000, not 1000+ ]);+ const out = annotateOccurrencesWithRunStatus(occs, new Map([["c1", schedule]]));+ expect(out[0]!.run_status).toBeUndefined();+ });+});++describe("groupOccurrencesByDay", () => {+ it("buckets occurrences into the correct day index", () => {+ const dayMs = 24 * 60 * 60 * 1000;+ const start = 0;+ const occs: CronOccurrence[] = [+ { at: 0, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: dayMs + 1, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: 2 * dayMs + 100, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ ];+ const days = groupOccurrencesByDay(occs, start, 3);+ expect(days.length).toBe(3);+ expect(days[0]!.length).toBe(1);+ expect(days[1]!.length).toBe(1);+ expect(days[2]!.length).toBe(1);+ });++ it("drops occurrences before the first day or beyond the last", () => {+ const dayMs = 24 * 60 * 60 * 1000;+ const start = dayMs;+ const occs: CronOccurrence[] = [+ { at: 0, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: dayMs, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: 10 * dayMs, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ ];+ const days = groupOccurrencesByDay(occs, start, 2);+ expect(days[0]!.length).toBe(1);+ expect(days[1]!.length).toBe(0);+ });++ it("sorts each day's occurrences ascending by `at`", () => {+ const dayMs = 24 * 60 * 60 * 1000;+ const occs: CronOccurrence[] = [+ { at: 300, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: 100, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ { at: 200, cron_id: "c", cron_name: "n", short_name: "n", agent_id: "a", agent_slug: "a", schedule_text: "?" },+ ];+ const days = groupOccurrencesByDay(occs, 0, 1);+ expect(days[0]!.map((o) => o.at)).toEqual([100, 200, 300]);+ expect(dayMs).toBeGreaterThan(0);+ });++ it("returns numDays empty buckets when occurrences list is empty", () => {+ const days = groupOccurrencesByDay([], 0, 5);+ expect(days.length).toBe(5);+ expect(days.every((d) => d.length === 0)).toBe(true);+ });+});diff --git a/src/server/openclaw/crons.test.ts b/src/server/openclaw/crons.test.tsnew file mode 100644index 00000000..8f1b5a47--- /dev/null+++ b/src/server/openclaw/crons.test.ts@@ -0,0 +1,596 @@+import { writeFileSync, mkdirSync } from "node:fs";+import { join } from "node:path";+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {+ // Hoisted so it runs before any imports — must be set BEFORE crons.ts+ // module-evaluates and captures OPENCLAW_HOME.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { tmpdir } = require("node:os") as typeof import("node:os");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { join: joinPath } = require("node:path") as typeof import("node:path");+ const original = process.env.OPENCLAW_HOME;+ const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-crons-"));+ process.env.OPENCLAW_HOME = tmp;+ return { tmpHome: tmp, ORIGINAL_HOME: original };+});++const openclawMock = vi.fn();+vi.mock("./cli", () => ({+ openclaw: (...args: unknown[]) => openclawMock(...args),+}));++import {+ createCron,+ disableCron,+ enableCron,+ invalidateCronCache,+ listCronsForProject,+ loadCronRuns,+ removeCron,+} from "./crons";++describe("crons module", () => {+ beforeEach(() => {+ openclawMock.mockReset();+ invalidateCronCache();+ });++ afterEach(() => {+ invalidateCronCache();+ });++ describe("listCronsForProject", () => {+ it("matches crons by 'project<sep>...' name with no surrounding spaces", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/google-ads/morning", agentId: "demo-google-ads" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.project_slug).toBe("demo");+ expect(view.groups.length).toBe(1);+ expect(view.groups[0]!.agent).toBe("google-ads");+ expect(view.groups[0]!.crons[0]!.id).toBe("1");+ });++ it("matches crons by 'project <sep>...' name with surrounding spaces", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo / seo / weekly", agentId: "demo-seo" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.agent).toBe("seo");+ });++ it("matches crons by agentId starting with '<project>-' even with unrelated name", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "anonymous-cron", agentId: "demo-cmo" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups.length).toBe(1);+ expect(view.groups[0]!.agent).toBe("cmo");+ });++ it("skips crons that don't match the project", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "other/seo/x", agentId: "other-seo" },+ { id: "2", name: "demo/google-ads/x", agentId: "demo-google-ads" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups.length).toBe(1);+ expect(view.groups[0]!.crons.length).toBe(1);+ expect(view.groups[0]!.crons[0]!.id).toBe("2");+ });++ it("normalizes a jobs:[] wrapper from openclaw", async () => {+ openclawMock.mockResolvedValueOnce({+ jobs: [{ id: "1", name: "demo/cmo/x", agentId: "demo-cmo" }],+ });+ const view = await listCronsForProject("demo");+ expect(view.groups.length).toBe(1);+ });++ it("normalizes a crons:[] wrapper from openclaw", async () => {+ openclawMock.mockResolvedValueOnce({+ crons: [{ id: "1", name: "demo/cmo/x", agentId: "demo-cmo" }],+ });+ const view = await listCronsForProject("demo");+ expect(view.groups.length).toBe(1);+ });++ it("returns empty groups when openclaw returns garbage", async () => {+ openclawMock.mockResolvedValueOnce("not an array");+ const view = await listCronsForProject("demo");+ expect(view.groups).toEqual([]);+ });++ it("derives agent slug from cron name when agentId is missing", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/google-ads/morning" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups.length).toBe(1);+ expect(view.groups[0]!.agent).toBe("google-ads");+ });++ it("groups multiple crons by agent and sorts groups alphabetically", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/seo/a", agentId: "demo-seo" },+ { id: "2", name: "demo/google-ads/a", agentId: "demo-google-ads" },+ { id: "3", name: "demo/google-ads/b", agentId: "demo-google-ads" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups.map((g) => g.agent)).toEqual(["google-ads", "seo"]);+ expect(view.groups[0]!.crons.length).toBe(2);+ });++ it("formats cron expression schedule with tz suffix", async () => {+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/x",+ agentId: "demo-cmo",+ schedule: { kind: "cron", expr: "0 9 * * *", tz: "America/Los_Angeles" },+ },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.schedule_text).toBe(+ "0 9 * * * · America/Los_Angeles",+ );+ });++ it("formats cron expression schedule without tz", async () => {+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/x",+ agentId: "demo-cmo",+ schedule: { kind: "cron", expr: "0 9 * * *" },+ },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.schedule_text).toBe("0 9 * * *");+ });++ it("formats every schedule in seconds/minutes/hours/days", async () => {+ const cases: Array<[number, string]> = [+ [30_000, "every 30s"],+ [5 * 60_000, "every 5m"],+ [3 * 60 * 60_000, "every 3h"],+ [2 * 24 * 60 * 60_000, "every 2d"],+ ];+ for (const [everyMs, expected] of cases) {+ openclawMock.mockReset();+ invalidateCronCache();+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/x",+ agentId: "demo-cmo",+ schedule: { kind: "every", everyMs },+ },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.schedule_text).toBe(expected);+ }+ });++ it("dash-formats schedule for missing/unknown shapes", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/cmo/a", agentId: "demo-cmo" },+ {+ id: "2",+ name: "demo/cmo/b",+ agentId: "demo-cmo",+ schedule: { kind: "weird" },+ },+ ]);+ const view = await listCronsForProject("demo");+ const crons = view.groups[0]!.crons;+ const byId = Object.fromEntries(crons.map((c) => [c.id, c]));+ expect(byId["1"]!.schedule_text).toBe("—");+ expect(byId["2"]!.schedule_text).toBe(JSON.stringify({ kind: "weird" }));+ });++ it("status_text falls back to 'idle' when no state on enabled cron", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/cmo/x", agentId: "demo-cmo" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.status_text).toBe("idle");+ expect(view.groups[0]!.crons[0]!.disabled).toBe(false);+ });++ it("status_text uses lastStatus then falls back to lastRunStatus", async () => {+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/a",+ agentId: "demo-cmo",+ state: { lastStatus: "ok" },+ },+ {+ id: "2",+ name: "demo/cmo/b",+ agentId: "demo-cmo",+ state: { lastRunStatus: "error" },+ },+ ]);+ const view = await listCronsForProject("demo");+ const byId = Object.fromEntries(view.groups[0]!.crons.map((c) => [c.id, c]));+ expect(byId["1"]!.status_text).toBe("ok");+ expect(byId["2"]!.status_text).toBe("error");+ });++ it("marks disabled crons (either disabled:true OR enabled:false)", async () => {+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/a",+ agentId: "demo-cmo",+ disabled: true,+ state: { lastStatus: "ok" },+ },+ {+ id: "2",+ name: "demo/cmo/b",+ agentId: "demo-cmo",+ enabled: false,+ },+ ]);+ const view = await listCronsForProject("demo");+ const byId = Object.fromEntries(view.groups[0]!.crons.map((c) => [c.id, c]));+ expect(byId["1"]!.disabled).toBe(true);+ expect(byId["1"]!.status_text).toBe("disabled");+ expect(byId["2"]!.disabled).toBe(true);+ });++ it("derives short_name from last segment of name", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/google-ads/morning-budget", agentId: "demo-google-ads" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.short_name).toBe("morning-budget");+ });++ it("propagates message + description + last_error fields", async () => {+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/x",+ agentId: "demo-cmo",+ description: "a job",+ payload: { kind: "agentTurn", message: "hi" },+ state: { lastError: "blew up" },+ },+ ]);+ const view = await listCronsForProject("demo");+ const d = view.groups[0]!.crons[0]!;+ expect(d.description).toBe("a job");+ expect(d.message).toBe("hi");+ expect(d.last_error).toBe("blew up");+ });++ it("falls back to lastErrorReason when lastError missing", async () => {+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/x",+ agentId: "demo-cmo",+ state: { lastErrorReason: "no creds" },+ },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.last_error).toBe("no creds");+ });++ it("formats next/last run as relative seconds/minutes/hours/days", async () => {+ const now = Date.now();+ openclawMock.mockResolvedValueOnce([+ {+ id: "1",+ name: "demo/cmo/x",+ agentId: "demo-cmo",+ state: {+ nextRunAtMs: now + 30_000,+ lastRunAtMs: now - 5 * 60_000,+ },+ },+ {+ id: "2",+ name: "demo/cmo/y",+ agentId: "demo-cmo",+ state: {+ nextRunAtMs: now + 2 * 60 * 60_000,+ lastRunAtMs: now - 3 * 24 * 60 * 60_000,+ },+ },+ ]);+ const view = await listCronsForProject("demo");+ const byId = Object.fromEntries(view.groups[0]!.crons.map((c) => [c.id, c]));+ expect(byId["1"]!.next_run_text).toMatch(/^in 30s$/);+ expect(byId["1"]!.last_run_text).toMatch(/5m ago/);+ expect(byId["2"]!.next_run_text).toMatch(/in 2h/);+ expect(byId["2"]!.last_run_text).toMatch(/3d ago/);+ });++ it("renders '—' for missing run timestamps", async () => {+ openclawMock.mockResolvedValueOnce([+ { id: "1", name: "demo/cmo/x", agentId: "demo-cmo" },+ ]);+ const view = await listCronsForProject("demo");+ expect(view.groups[0]!.crons[0]!.next_run_text).toBe("—");+ expect(view.groups[0]!.crons[0]!.last_run_text).toBe("—");+ });+ });++ describe("subprocess cache", () => {+ it("caches openclaw output within the TTL window", async () => {+ openclawMock.mockResolvedValue([{ id: "1", name: "demo/cmo/x", agentId: "demo-cmo" }]);+ // Two back-to-back calls; cache key is project_slug-agnostic.+ await listCronsForProject("demo");+ await listCronsForProject("other-project");+ expect(openclawMock).toHaveBeenCalledTimes(1);+ });++ it("invalidateCronCache forces a refetch", async () => {+ openclawMock.mockResolvedValue([]);+ await listCronsForProject("demo");+ invalidateCronCache();+ await listCronsForProject("demo");+ expect(openclawMock).toHaveBeenCalledTimes(2);+ });++ it("invalidates the cache when openclaw rejects", async () => {+ openclawMock.mockRejectedValueOnce(new Error("transient"));+ await expect(listCronsForProject("demo")).rejects.toThrow("transient");+ openclawMock.mockResolvedValueOnce([]);+ await expect(listCronsForProject("demo")).resolves.toBeTruthy();+ expect(openclawMock).toHaveBeenCalledTimes(2);+ });+ });++ describe("mutators invalidate cache + call openclaw", () => {+ beforeEach(() => {+ openclawMock.mockResolvedValue(undefined);+ });++ it("disableCron calls 'cron disable <id>' without json", async () => {+ await disableCron("c1");+ expect(openclawMock).toHaveBeenCalledWith(["cron", "disable", "c1"], { json: false });+ });++ it("enableCron calls 'cron enable <id>' without json", async () => {+ await enableCron("c1");+ expect(openclawMock).toHaveBeenCalledWith(["cron", "enable", "c1"], { json: false });+ });++ it("removeCron calls 'cron rm <id>' without json", async () => {+ await removeCron("c1");+ expect(openclawMock).toHaveBeenCalledWith(["cron", "rm", "c1"], { json: false });+ });++ it("mutators invalidate the cron list cache", async () => {+ openclawMock.mockReset();+ openclawMock.mockResolvedValueOnce([]); // first listCronsForProject+ await listCronsForProject("demo");+ openclawMock.mockResolvedValueOnce(undefined); // disable+ await disableCron("c1");+ openclawMock.mockResolvedValueOnce([]); // refetch after invalidate+ await listCronsForProject("demo");+ // 3 calls total = list + disable + list-after-disable+ expect(openclawMock).toHaveBeenCalledTimes(3);+ });+ });++ describe("createCron", () => {+ it("builds full name and passes cron schedule + tz", async () => {+ openclawMock.mockResolvedValueOnce({ id: "cron-id-1", name: "demo/cmo/morning" });+ const r = await createCron({+ project_slug: "demo",+ agent_slug: "cmo",+ agent_full_id: "demo-cmo",+ cron_name: "morning",+ schedule: { kind: "cron", expr: "0 9 * * *", tz: "UTC" },+ message: "hello",+ });+ expect(r).toEqual({ id: "cron-id-1", name: "demo/cmo/morning" });+ expect(openclawMock).toHaveBeenCalledWith([+ "cron",+ "add",+ "--name",+ "demo/cmo/morning",+ "--agent",+ "demo-cmo",+ "--message",+ "hello",+ "--no-deliver",+ "--cron",+ "0 9 * * *",+ "--tz",+ "UTC",+ ]);+ });++ it("omits --tz when not provided", async () => {+ openclawMock.mockResolvedValueOnce({});+ await createCron({+ project_slug: "demo",+ agent_slug: "cmo",+ agent_full_id: "demo-cmo",+ cron_name: "morning",+ schedule: { kind: "cron", expr: "0 9 * * *" },+ message: "hello",+ });+ const args = openclawMock.mock.calls[0]![0] as string[];+ expect(args).not.toContain("--tz");+ });++ it("uses --every for duration-based schedules", async () => {+ openclawMock.mockResolvedValueOnce({ id: "abc" });+ await createCron({+ project_slug: "demo",+ agent_slug: "cmo",+ agent_full_id: "demo-cmo",+ cron_name: "ping",+ schedule: { kind: "every", duration: "5m" },+ message: "tick",+ });+ const args = openclawMock.mock.calls[0]![0] as string[];+ expect(args).toContain("--every");+ expect(args).toContain("5m");+ expect(args).not.toContain("--cron");+ });++ it("includes --description when provided", async () => {+ openclawMock.mockResolvedValueOnce({});+ await createCron({+ project_slug: "demo",+ agent_slug: "cmo",+ agent_full_id: "demo-cmo",+ cron_name: "x",+ schedule: { kind: "cron", expr: "* * * * *" },+ message: "m",+ description: "this is the desc",+ });+ const args = openclawMock.mock.calls[0]![0] as string[];+ const idx = args.indexOf("--description");+ expect(idx).toBeGreaterThan(-1);+ expect(args[idx + 1]).toBe("this is the desc");+ });++ it("coerces missing id/name to empty string / fullName", async () => {+ openclawMock.mockResolvedValueOnce(null);+ const r = await createCron({+ project_slug: "demo",+ agent_slug: "cmo",+ agent_full_id: "demo-cmo",+ cron_name: "ping",+ schedule: { kind: "every", duration: "5m" },+ message: "m",+ });+ expect(r.id).toBe("");+ expect(r.name).toBe("demo/cmo/ping");+ });+ });++ describe("loadCronRuns", () => {+ function runsPath(cronId: string): string {+ const dir = join(tmpHome, "cron", "runs");+ mkdirSync(dir, { recursive: true });+ return join(dir, `${cronId}.jsonl`);+ }++ it("returns [] when the run log file doesn't exist", () => {+ expect(loadCronRuns("nonexistent-cron", 10)).toEqual([]);+ });++ it("parses finished entries newest-first", () => {+ const p = runsPath("cron-a");+ const lines = [+ JSON.stringify({ action: "started", runAtMs: 1000 }),+ JSON.stringify({+ action: "finished",+ runAtMs: 1000,+ ts: 1100,+ status: "ok",+ summary: "did it",+ durationMs: 100,+ }),+ JSON.stringify({+ action: "finished",+ runAtMs: 2000,+ ts: 2200,+ status: "error",+ summary: "",+ error: "kaboom",+ sessionId: "sess-1",+ model: "m",+ provider: "p",+ usage: { input_tokens: 5 },+ }),+ ];+ writeFileSync(p, lines.join("\n") + "\n", "utf8");+ const runs = loadCronRuns("cron-a", 10);+ expect(runs.length).toBe(2);+ // Newest first.+ expect(runs[0]!.status).toBe("error");+ expect(runs[0]!.run_at_ms).toBe(2000);+ expect(runs[0]!.finished_at_ms).toBe(2200);+ expect(runs[0]!.error).toBe("kaboom");+ expect(runs[0]!.session_id).toBe("sess-1");+ expect(runs[0]!.model).toBe("m");+ expect(runs[0]!.provider).toBe("p");+ expect(runs[0]!.usage).toEqual({ input_tokens: 5 });+ expect(runs[1]!.status).toBe("ok");+ expect(runs[1]!.duration_ms).toBe(100);+ });++ it("respects limit cap", () => {+ const p = runsPath("cron-b");+ const lines = Array.from({ length: 5 }, (_, i) =>+ JSON.stringify({ action: "finished", runAtMs: 1000 + i, ts: 1000 + i, status: "ok" }),+ );+ writeFileSync(p, lines.join("\n") + "\n", "utf8");+ const runs = loadCronRuns("cron-b", 2);+ expect(runs.length).toBe(2);+ // Newest two are runAtMs 1004 then 1003.+ expect(runs.map((r) => r.run_at_ms)).toEqual([1004, 1003]);+ });++ it("skips non-finished entries", () => {+ const p = runsPath("cron-c");+ writeFileSync(+ p,+ [+ JSON.stringify({ action: "started", runAtMs: 1000 }),+ JSON.stringify({ action: "skipped", runAtMs: 1500 }),+ JSON.stringify({ action: "finished", runAtMs: 2000, ts: 2100, status: "ok" }),+ ].join("\n") + "\n",+ "utf8",+ );+ const runs = loadCronRuns("cron-c", 10);+ expect(runs.length).toBe(1);+ expect(runs[0]!.run_at_ms).toBe(2000);+ });++ it("skips entries missing runAtMs or with invalid JSON", () => {+ const p = runsPath("cron-d");+ writeFileSync(+ p,+ [+ "not json at all",+ JSON.stringify({ action: "finished" }), // no runAtMs+ JSON.stringify({ action: "finished", runAtMs: 0 }),+ JSON.stringify({ action: "finished", runAtMs: 5000, status: "ok" }),+ "",+ ].join("\n"),+ "utf8",+ );+ const runs = loadCronRuns("cron-d", 10);+ expect(runs.length).toBe(1);+ expect(runs[0]!.run_at_ms).toBe(5000);+ });++ it("provides sensible defaults for missing fields", () => {+ const p = runsPath("cron-e");+ writeFileSync(+ p,+ JSON.stringify({ action: "finished", runAtMs: 1000 }) + "\n",+ "utf8",+ );+ const runs = loadCronRuns("cron-e", 10);+ expect(runs[0]!.finished_at_ms).toBe(1000); // ts missing -> falls back to runAtMs+ expect(runs[0]!.status).toBe("unknown");+ expect(runs[0]!.summary).toBe("");+ expect(runs[0]!.error).toBeUndefined();+ expect(runs[0]!.usage).toBeUndefined();+ });+ });+});++// Restore env for downstream tests sharing the process.+afterAll(() => {+ if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;+ else delete process.env.OPENCLAW_HOME;+});diff --git a/src/server/openclaw/gateway-client.test.ts b/src/server/openclaw/gateway-client.test.tsnew file mode 100644index 00000000..68d9d10e--- /dev/null+++ b/src/server/openclaw/gateway-client.test.ts@@ -0,0 +1,893 @@+import {+ mkdtempSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++// ---------------------------------------------------------------------------+// Fake WebSocket implementation (hoisted so vi.mock can reference it)+// ---------------------------------------------------------------------------+//+// gateway-client only exercises a small slice of `ws`'s surface:+// - constructor(url, opts)+// - .once("open" | "error", fn)+// - .removeListener("error", fn)+// - .on("message" | "close" | "error", fn)+// - .send(string)+// - .close()+// - .readyState (compared against the static `OPEN` constant)+//+// We back the fake with EventEmitter so .on / .once / .removeListener all+// behave correctly without re-implementing them.++const { FakeWS } = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { EventEmitter: EE } = require("node:events") as typeof import("node:events");++ class FakeWSImpl extends EE {+ static readonly OPEN = 1;+ static readonly CLOSED = 3;++ readyState: number = 0;+ readonly url: string;+ readonly opts: Record<string, unknown>;+ readonly sent: string[] = [];+ closed = false;++ constructor(url: string, opts: Record<string, unknown> = {}) {+ super();+ this.url = url;+ this.opts = opts;+ FakeWSImpl.instances.push(this);+ }++ send(data: string): void {+ this.sent.push(data);+ }++ close(): void {+ this.closed = true;+ this.readyState = FakeWSImpl.CLOSED;+ setImmediate(() => this.emit("close"));+ }++ fireOpen(): void {+ this.readyState = FakeWSImpl.OPEN;+ this.emit("open");+ }+ fireMessage(frame: unknown): void {+ this.emit("message", JSON.stringify(frame));+ }+ fireError(err: Error): void {+ this.emit("error", err);+ }+ fireClose(): void {+ this.readyState = FakeWSImpl.CLOSED;+ this.emit("close");+ }++ static instances: FakeWSImpl[] = [];+ static reset(): void {+ FakeWSImpl.instances = [];+ }+ static latest(): FakeWSImpl {+ return FakeWSImpl.instances[FakeWSImpl.instances.length - 1]!;+ }+ }++ return { FakeWS: FakeWSImpl };+});++type FakeWST = InstanceType<typeof FakeWS>;++vi.mock("ws", () => ({+ default: FakeWS,+ WebSocket: FakeWS,+}));++// ---------------------------------------------------------------------------+// Set up a fake OPENCLAW_HOME with a discovery file so discoverGateway()+// returns a known URL + token.+// ---------------------------------------------------------------------------++const { tmpHome, ORIGINAL_HOME, ORIGINAL_STATE } = ((): {+ tmpHome: string;+ ORIGINAL_HOME: string | undefined;+ ORIGINAL_STATE: string | undefined;+} => {+ const origHome = process.env.OPENCLAW_HOME;+ const origState = process.env.OPENCLAW_STATE_DIR;+ const tmp = mkdtempSync(join(tmpdir(), "notfair-cmo-gateway-"));+ process.env.OPENCLAW_HOME = tmp;+ delete process.env.OPENCLAW_STATE_DIR;+ return { tmpHome: tmp, ORIGINAL_HOME: origHome, ORIGINAL_STATE: origState };+})();++function writeConfig(parsed: unknown): void {+ writeFileSync(join(tmpHome, "openclaw.json"), JSON.stringify(parsed), "utf8");+}++// Default config used by most tests.+beforeAll(() => {+ writeConfig({+ gateway: {+ port: 7799,+ bind: "loopback",+ auth: { token: "tok-abc" },+ },+ });+});++afterAll(() => {+ try {+ rmSync(tmpHome, { recursive: true, force: true });+ } catch {}+ if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;+ else delete process.env.OPENCLAW_HOME;+ if (ORIGINAL_STATE) process.env.OPENCLAW_STATE_DIR = ORIGINAL_STATE;+});++// Late import so the env + mocks are in place.+import {+ discoverGateway,+ GatewayClient,+ streamChatViaGateway,+} from "./gateway-client";++beforeEach(() => {+ // Don't reset between every test — the streamChatViaGateway singleton+ // retains a ws reference across tests. Individual GatewayClient tests+ // construct a fresh client + ws each time, so a stale instances list+ // is fine for them too (they call FakeWS.latest() after constructing).+});++// ---------------------------------------------------------------------------+// discoverGateway+// ---------------------------------------------------------------------------++describe("discoverGateway", () => {+ it("reads port + token from openclaw.json (loopback default)", () => {+ const cfg = discoverGateway();+ expect(cfg.url).toBe("ws://127.0.0.1:7799");+ expect(cfg.token).toBe("tok-abc");+ expect(cfg.password).toBeUndefined();+ expect(cfg.configFile).toBe(join(tmpHome, "openclaw.json"));+ });++ it("prefers gateway.remote.url when present", () => {+ writeConfig({+ gateway: {+ port: 1,+ remote: { url: "wss://my-tailnet:9999 " },+ auth: { token: "remote-tok" },+ },+ });+ const cfg = discoverGateway();+ expect(cfg.url).toBe("wss://my-tailnet:9999");+ // Restore default config for downstream tests.+ writeConfig({+ gateway: { port: 7799, bind: "loopback", auth: { token: "tok-abc" } },+ });+ });++ it("uses 127.0.0.1 even on bind='lan' when remote.url is not set", () => {+ writeConfig({+ gateway: { port: 1234, bind: "lan", auth: { password: "pw" } },+ });+ const cfg = discoverGateway();+ expect(cfg.url).toBe("ws://127.0.0.1:1234");+ expect(cfg.token).toBeUndefined();+ expect(cfg.password).toBe("pw");+ writeConfig({+ gateway: { port: 7799, bind: "loopback", auth: { token: "tok-abc" } },+ });+ });++ it("throws when the config file does not exist", () => {+ const prev = process.env.OPENCLAW_HOME;+ const missing = mkdtempSync(join(tmpdir(), "notfair-cmo-missing-"));+ rmSync(missing, { recursive: true, force: true });+ process.env.OPENCLAW_HOME = missing;+ try {+ expect(() => discoverGateway()).toThrow(/OpenClaw config not found/);+ } finally {+ process.env.OPENCLAW_HOME = prev;+ }+ });++ it("throws when the config file is not JSON", () => {+ const bad = mkdtempSync(join(tmpdir(), "notfair-cmo-bad-"));+ process.env.OPENCLAW_HOME = bad;+ writeFileSync(join(bad, "openclaw.json"), "{ not valid", "utf8");+ try {+ expect(() => discoverGateway()).toThrow(/Could not parse/);+ } finally {+ process.env.OPENCLAW_HOME = tmpHome;+ rmSync(bad, { recursive: true, force: true });+ }+ });++ it("throws when gateway.port is missing/invalid and no remote.url", () => {+ writeConfig({ gateway: { bind: "loopback" } });+ try {+ expect(() => discoverGateway()).toThrow(/Could not read gateway\.port/);+ } finally {+ writeConfig({+ gateway: { port: 7799, bind: "loopback", auth: { token: "tok-abc" } },+ });+ }+ });++ it("respects OPENCLAW_STATE_DIR over OPENCLAW_HOME", () => {+ const state = mkdtempSync(join(tmpdir(), "notfair-cmo-state-"));+ writeFileSync(+ join(state, "openclaw.json"),+ JSON.stringify({+ gateway: { port: 5555, bind: "loopback", auth: {} },+ }),+ "utf8",+ );+ process.env.OPENCLAW_STATE_DIR = state;+ try {+ const cfg = discoverGateway();+ expect(cfg.url).toBe("ws://127.0.0.1:5555");+ expect(cfg.configFile).toBe(join(state, "openclaw.json"));+ } finally {+ delete process.env.OPENCLAW_STATE_DIR;+ rmSync(state, { recursive: true, force: true });+ }+ });+});++// ---------------------------------------------------------------------------+// GatewayClient: open / connect handshake+// ---------------------------------------------------------------------------++describe("GatewayClient.open", () => {+ /**+ * Helper: drive a GatewayClient through the open handshake.+ * Returns the connected client + the underlying FakeWS so the test can+ * push more frames after.+ */+ async function openAndAck(): Promise<{ client: GatewayClient; ws: FakeWST }> {+ const client = new GatewayClient();+ const openP = client.open();+ // After microtasks, the constructor + ws creation should have happened.+ await tick();+ const ws = FakeWS.latest();+ ws.fireOpen();+ // Now the client sends the `connect` req frame. Pull it + ack.+ await tick();+ const reqRaw = ws.sent[0];+ expect(reqRaw).toBeDefined();+ const req = JSON.parse(reqRaw!) as { id: string; method: string };+ expect(req.method).toBe("connect");+ ws.fireMessage({ type: "res", id: req.id, ok: true, payload: { protocol: 4 } });+ await openP;+ return { client, ws };+ }++ it("constructs a WebSocket with the discovered URL", async () => {+ const { client, ws } = await openAndAck();+ expect(ws.url).toBe("ws://127.0.0.1:7799");+ // perMessageDeflate disabled + 5s handshake timeout (loopback is fast).+ expect(ws.opts.perMessageDeflate).toBe(false);+ expect(ws.opts.handshakeTimeout).toBe(5_000);+ expect(client.isOpen()).toBe(true);+ client.close();+ });++ it("uses opts.url / opts.token over discovery values", async () => {+ const client = new GatewayClient({+ url: "ws://override:1234",+ token: "ovr-tok",+ scopes: ["operator.read"],+ });+ const p = client.open();+ await tick();+ const ws = FakeWS.latest();+ expect(ws.url).toBe("ws://override:1234");+ ws.fireOpen();+ await tick();+ const req = JSON.parse(ws.sent[0]!) as {+ params: { auth?: { token?: string }; scopes?: string[] };+ };+ expect(req.params.auth?.token).toBe("ovr-tok");+ expect(req.params.scopes).toEqual(["operator.read"]);+ ws.fireMessage({+ type: "res",+ id: (JSON.parse(ws.sent[0]!) as { id: string }).id,+ ok: true,+ });+ await p;+ client.close();+ });++ it("open() is idempotent — second call resolves without a new socket", async () => {+ const { client, ws } = await openAndAck();+ const before = FakeWS.instances.length;+ await client.open();+ expect(FakeWS.instances.length).toBe(before);+ client.close();+ });++ it("concurrent open() calls share the same in-flight promise", async () => {+ const baseline = FakeWS.instances.length;+ const client = new GatewayClient();+ const a = client.open();+ const b = client.open();+ await tick();+ // Only one new socket should have been constructed.+ expect(FakeWS.instances.length - baseline).toBe(1);+ const ws = FakeWS.latest();+ ws.fireOpen();+ await tick();+ const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: true });+ await Promise.all([a, b]);+ expect(client.isOpen()).toBe(true);+ client.close();+ });++ it("rejects when the socket errors before opening", async () => {+ const client = new GatewayClient();+ const p = client.open();+ await tick();+ const ws = FakeWS.latest();+ ws.fireError(new Error("conn refused"));+ await expect(p).rejects.toThrow(/conn refused/);+ expect(client.isOpen()).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// GatewayClient.request — pending / response routing+// ---------------------------------------------------------------------------++describe("GatewayClient.request", () => {+ async function openAndAck(): Promise<{ client: GatewayClient; ws: FakeWST }> {+ const client = new GatewayClient();+ const openP = client.open();+ await tick();+ const ws = FakeWS.latest();+ ws.fireOpen();+ await tick();+ const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: true });+ await openP;+ return { client, ws };+ }++ it("resolves with payload when server returns ok:true", async () => {+ const { client, ws } = await openAndAck();+ const p = client.request("foo.bar", { x: 1 });+ await tick();+ const req = JSON.parse(ws.sent[ws.sent.length - 1]!) as {+ id: string;+ method: string;+ params: unknown;+ };+ expect(req.method).toBe("foo.bar");+ expect(req.params).toEqual({ x: 1 });+ ws.fireMessage({ type: "res", id: req.id, ok: true, payload: { hello: "world" } });+ await expect(p).resolves.toEqual({ hello: "world" });+ client.close();+ });++ it("rejects with formatted error message when ok:false", async () => {+ const { client, ws } = await openAndAck();+ const p = client.request("foo.bar");+ await tick();+ const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;+ ws.fireMessage({+ type: "res",+ id,+ ok: false,+ error: { code: "FORBIDDEN", message: "no", details: { why: "scope" } },+ });+ await expect(p).rejects.toThrow(/gateway error \(FORBIDDEN\): no/);+ await expect(p.catch((e) => (e as Error).message)).resolves.toMatch(+ /details=.*scope/,+ );+ client.close();+ });++ it("rejects with default UNKNOWN code when error envelope is missing fields", async () => {+ const { client, ws } = await openAndAck();+ const p = client.request("foo.bar");+ await tick();+ const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: false });+ await expect(p).rejects.toThrow(/gateway error \(UNKNOWN\): request failed/);+ client.close();+ });++ it("rejects request when socket is closed", async () => {+ const client = new GatewayClient();+ await expect(client.request("foo")).rejects.toThrow(/gateway not connected/);+ });++ it("rejects all pending requests on close event", async () => {+ const { client, ws } = await openAndAck();+ const a = client.request("a");+ const b = client.request("b");+ await tick();+ ws.fireClose();+ await Promise.all([+ expect(a).rejects.toThrow(/gateway connection closed/),+ expect(b).rejects.toThrow(/gateway connection closed/),+ ]);+ client.close();+ });++ it("ignores response frames for unknown ids (no crash)", async () => {+ const { client, ws } = await openAndAck();+ // Unmatched id — should silently noop.+ ws.fireMessage({ type: "res", id: "no-such-id", ok: true });+ // Subsequent legit request still works.+ const p = client.request("foo");+ await tick();+ const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: true, payload: 42 });+ await expect(p).resolves.toBe(42);+ client.close();+ });++ it("ignores frames that aren't valid JSON", async () => {+ const { client, ws } = await openAndAck();+ ws.emit("message", "{not json"); // direct emit bypasses fireMessage's stringify+ const p = client.request("foo");+ await tick();+ const id = (JSON.parse(ws.sent[ws.sent.length - 1]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: true });+ await expect(p).resolves.toBeUndefined();+ client.close();+ });+});++// ---------------------------------------------------------------------------+// Event listener dispatch+// ---------------------------------------------------------------------------++describe("GatewayClient.addEventListener", () => {+ async function openAndAck(): Promise<{ client: GatewayClient; ws: FakeWST }> {+ const client = new GatewayClient();+ const p = client.open();+ await tick();+ const ws = FakeWS.latest();+ ws.fireOpen();+ await tick();+ const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: true });+ await p;+ return { client, ws };+ }++ it("dispatches event-typed frames to subscribers", async () => {+ const { client, ws } = await openAndAck();+ const received: unknown[] = [];+ const off = client.addEventListener((evt) => received.push(evt));+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: { hi: 1 },+ });+ expect(received).toHaveLength(1);+ off();+ ws.fireMessage({ type: "event", event: "chat", payload: { hi: 2 } });+ expect(received).toHaveLength(1);+ client.close();+ });++ it("swallows listener throws so other listeners still see the frame", async () => {+ const { client, ws } = await openAndAck();+ const a = vi.fn().mockImplementation(() => {+ throw new Error("listener exploded");+ });+ const b = vi.fn();+ client.addEventListener(a);+ client.addEventListener(b);+ // Silence the console.error call from the SUT's catch block.+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ ws.fireMessage({ type: "event", event: "chat", payload: {} });+ } finally {+ spy.mockRestore();+ }+ expect(a).toHaveBeenCalled();+ expect(b).toHaveBeenCalled();+ client.close();+ });++ it("filters out connect.challenge events (device-auth, not for loopback)", async () => {+ const { client, ws } = await openAndAck();+ const seen: unknown[] = [];+ client.addEventListener((e) => seen.push(e.event));+ ws.fireMessage({ type: "event", event: "connect.challenge", payload: {} });+ ws.fireMessage({ type: "event", event: "chat", payload: {} });+ expect(seen).toEqual(["chat"]);+ client.close();+ });+});++// ---------------------------------------------------------------------------+// close() cleanup+// ---------------------------------------------------------------------------++describe("GatewayClient.close", () => {+ it("clears listeners + pending + nulls out ws", async () => {+ const client = new GatewayClient();+ const p = client.open();+ await tick();+ const ws = FakeWS.latest();+ ws.fireOpen();+ await tick();+ const id = (JSON.parse(ws.sent[0]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id, ok: true });+ await p;++ expect(client.isOpen()).toBe(true);+ client.close();+ expect(client.isOpen()).toBe(false);+ // After close, request rejects.+ await expect(client.request("x")).rejects.toThrow(/not connected/);+ });++ it("close() is safe to call before open()", () => {+ const client = new GatewayClient();+ expect(() => client.close()).not.toThrow();+ expect(client.isOpen()).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// streamChatViaGateway (high-level helper)+// ---------------------------------------------------------------------------++describe("streamChatViaGateway", () => {+ // The streaming helper uses a process-singleton client. Tests must NOT+ // assume a clean slate between runs — but since each test issues its own+ // chat.send and aborts shortly after, the shared client just gets reused.+ //+ // To exercise the singleton end-to-end without timing flakes, each test+ // here aborts immediately after a few frames so the generator terminates.++ /**+ * Returns an iteration wrapper that handles the gotcha of starting an+ * async generator: gen.next() must be called to begin execution, but+ * its returned value is the first yielded event. We capture it and+ * surface it via `events()` so tests see ALL events.+ */+ async function bootstrapStream(input: {+ sessionKey: string;+ message: string;+ signal?: AbortSignal;+ }): Promise<{+ ws: FakeWST;+ /** Drains the generator and returns all yielded events. */+ drain: () => Promise<unknown[]>;+ sendReqId: string;+ }> {+ const baselineCount = FakeWS.instances.length;+ const gen = streamChatViaGateway(input) as AsyncGenerator<unknown, void, void>;+ // Start the generator (this also triggers the chat.send req). We hold the+ // promise so the first yielded event isn't dropped.+ const firstResultPromise = gen.next();+ // Allow the singleton bootstrap to run if needed.+ await tick();+ let ws: FakeWST;+ if (FakeWS.instances.length > baselineCount) {+ ws = FakeWS.latest();+ ws.fireOpen();+ await tick();+ const connectId = (JSON.parse(ws.sent[0]!) as { id: string }).id;+ ws.fireMessage({ type: "res", id: connectId, ok: true });+ await tick();+ } else {+ ws = FakeWS.latest();+ }+ const lastSent = ws.sent[ws.sent.length - 1]!;+ const sendReqId = (JSON.parse(lastSent) as { id: string }).id;++ const drain = async (): Promise<unknown[]> => {+ const out: unknown[] = [];+ const first = await firstResultPromise;+ if (!first.done) out.push(first.value);+ // Now iterate the rest.+ for (;;) {+ const r = await gen.next();+ if (r.done) break;+ out.push(r.value);+ }+ return out;+ };+ return { ws, drain, sendReqId };+ }++ it("yields delta + final events when chat state goes final", async () => {+ const ac = new AbortController();+ const { ws, drain, sendReqId } = await bootstrapStream({+ sessionKey: "session-A",+ message: "hi",+ signal: ac.signal,+ });+ ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "session-A",+ state: "delta",+ message: { content: [{ type: "text", text: "hello" }] },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "session-A",+ state: "final",+ message: { content: [{ type: "text", text: "hello world" }] },+ },+ });++ const out = await drain();+ const kinds = out.map((e) => (e as { kind: string }).kind);+ expect(kinds).toContain("delta");+ expect(kinds).toContain("final");+ const finalEv = out.find((e) => (e as { kind: string }).kind === "final") as {+ text: string;+ };+ expect(finalEv.text).toBe("hello world");+ });++ it("ignores events for a different sessionKey", async () => {+ const { ws, drain, sendReqId } = await bootstrapStream({+ sessionKey: "session-B",+ message: "hi",+ });+ ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "other-session",+ state: "delta",+ message: { content: [{ type: "text", text: "should be ignored" }] },+ },+ });+ // Final for our session with content (so we don't hit the chat.history+ // fallback that retries for ~640ms).+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "session-B",+ state: "final",+ message: { content: [{ type: "text", text: "ours" }] },+ },+ });++ const out = await drain();+ const finalEv = out.find((e) => (e as { kind: string }).kind === "final") as {+ text: string;+ };+ expect(finalEv).toBeDefined();+ expect(finalEv.text).toBe("ours");+ // None of the deltas should contain "should be ignored".+ const deltas = out+ .filter((e) => (e as { kind: string }).kind === "delta")+ .map((e) => (e as { text: string }).text)+ .join("");+ expect(deltas).not.toContain("should be ignored");+ });++ it("emits tool events with phase + name + label", async () => {+ const { ws, drain, sendReqId } = await bootstrapStream({+ sessionKey: "session-C",+ message: "hi",+ });+ ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });++ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-C",+ stream: "tool",+ data: {+ phase: "start",+ name: "exec",+ toolCallId: "tc-1",+ args: { command: "pnpm test" },+ },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-C",+ stream: "tool",+ data: { phase: "result", name: "exec", toolCallId: "tc-1" },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "session-C",+ state: "final",+ message: { content: [{ type: "text", text: "done" }] },+ },+ });++ const out = await drain();+ const toolEvs = out.filter((e) => (e as { kind: string }).kind === "tool") as Array<{+ phase: string;+ label?: string;+ }>;+ expect(toolEvs.length).toBe(2);+ expect(toolEvs[0]!.phase).toBe("start");+ expect(toolEvs[0]!.label).toBe("pnpm test");+ expect(toolEvs[1]!.phase).toBe("result");+ });++ it("emits lifecycle events from data.phase and payload.state", async () => {+ const { ws, drain, sendReqId } = await bootstrapStream({+ sessionKey: "session-D",+ message: "hi",+ });+ ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });++ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-D",+ stream: "lifecycle",+ data: { phase: "start" },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-D",+ stream: "lifecycle",+ state: "end",+ },+ });+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "session-D",+ state: "final",+ message: { content: [{ type: "text", text: "done" }] },+ },+ });++ const out = await drain();+ const lifecycle = (out.filter((e) => (e as { kind: string }).kind === "lifecycle") as Array<{+ phase: string;+ }>).map((e) => e.phase);+ expect(lifecycle).toEqual(["start", "end"]);+ });++ it("coalesces assistant deltas + replace into a monotonic stream", async () => {+ const { ws, drain, sendReqId } = await bootstrapStream({+ sessionKey: "session-E",+ message: "hi",+ });+ ws.fireMessage({ type: "res", id: sendReqId, ok: true, payload: {} });++ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-E",+ stream: "assistant",+ data: { delta: "Hel" },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-E",+ stream: "assistant",+ data: { delta: "lo" },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "agent",+ payload: {+ sessionKey: "session-E",+ stream: "assistant",+ data: { replace: true, text: "Hello world" },+ },+ });+ ws.fireMessage({+ type: "event",+ event: "chat",+ payload: {+ sessionKey: "session-E",+ state: "final",+ message: { content: [{ type: "text", text: "Hello world" }] },+ },+ });++ const out = await drain();+ const text = (out.filter((e) => (e as { kind: string }).kind === "delta") as Array<{+ text: string;+ }>)+ .map((e) => e.text)+ .join("");+ expect(text).toBe("Hello world");+ });++ it("aborts via signal: fires chat.abort and terminates", async () => {+ const ac = new AbortController();+ const { ws, drain } = await bootstrapStream({+ sessionKey: "session-F",+ message: "hi",+ signal: ac.signal,+ });+ const sentBefore = ws.sent.length;+ ac.abort();+ const out = await drain();+ expect(out).toBeDefined();+ // The abort path sends a chat.abort request (we don't bother to ack it).+ expect(ws.sent.length).toBeGreaterThan(sentBefore);+ const lastSent = JSON.parse(ws.sent[ws.sent.length - 1]!) as { method: string };+ expect(lastSent.method).toBe("chat.abort");+ });++ it("emits error event when chat.send is rejected by the gateway", async () => {+ const { ws, drain, sendReqId } = await bootstrapStream({+ sessionKey: "session-G",+ message: "hi",+ });+ ws.fireMessage({+ type: "res",+ id: sendReqId,+ ok: false,+ error: { code: "RATE_LIMITED", message: "slow down" },+ });++ const out = await drain();+ const errEv = out.find((e) => (e as { kind: string }).kind === "error") as {+ message: string;+ };+ expect(errEv).toBeDefined();+ expect(errEv.message).toMatch(/RATE_LIMITED/);+ });+});++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/** Advance microtasks + immediate timers. */+function tick(): Promise<void> {+ return new Promise((r) => setImmediate(r));+}++afterEach(() => {+ // Nothing to clean up beyond resetting fake WS — singleton from+ // streamChatViaGateway is intentionally retained.+});diff --git a/src/server/openclaw/gateway-rpc.test.ts b/src/server/openclaw/gateway-rpc.test.tsnew file mode 100644index 00000000..711f6946--- /dev/null+++ b/src/server/openclaw/gateway-rpc.test.ts@@ -0,0 +1,169 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++type MockedClient = {+ open: ReturnType<typeof vi.fn>;+ request: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+};++const clientInstances: MockedClient[] = [];++let nextRequestImpl: ((method: string, params?: unknown) => unknown) | null = null;++vi.mock("./gateway-client", () => {+ class FakeGatewayClient {+ open: ReturnType<typeof vi.fn>;+ request: ReturnType<typeof vi.fn>;+ close: ReturnType<typeof vi.fn>;+ constructor() {+ const impl = nextRequestImpl ?? (async () => undefined);+ nextRequestImpl = null;+ this.open = vi.fn().mockResolvedValue(undefined);+ this.request = vi.fn().mockImplementation(impl);+ this.close = vi.fn();+ clientInstances.push(this);+ }+ }+ return { GatewayClient: FakeGatewayClient };+});++import {+ createAgentViaRpc,+ deleteAgent,+ getAgentFile,+ getSkillStatus,+ listAgentFiles,+ listAllAgents,+ setAgentFile,+ setSkillEnabled,+ updateCronMessage,+} from "./gateway-rpc";++function latest(): MockedClient {+ return clientInstances[clientInstances.length - 1]!;+}++function nextRequestReturns(value: unknown): void {+ nextRequestImpl = async () => value;+}++function nextRequestThrows(err: Error): void {+ nextRequestImpl = async () => {+ throw err;+ };+}++describe("gateway-rpc", () => {+ beforeEach(() => {+ clientInstances.length = 0;+ nextRequestImpl = null;+ });++ it("listAgentFiles opens, requests agents.files.list, returns payload, then closes", async () => {+ const expected = {+ agentId: "demo-agent",+ workspace: "/ws",+ files: [{ name: "REM.md", path: "/ws/REM.md", missing: false, size: 10 }],+ };+ nextRequestReturns(expected);++ await expect(listAgentFiles("demo-agent")).resolves.toEqual(expected);+ const c = latest();+ expect(c.open).toHaveBeenCalledTimes(1);+ expect(c.request).toHaveBeenCalledWith("agents.files.list", { agentId: "demo-agent" });+ expect(c.close).toHaveBeenCalledTimes(1);+ });++ it("closes the client even when the request throws", async () => {+ nextRequestThrows(new Error("boom"));+ await expect(listAgentFiles("a")).rejects.toThrow("boom");+ expect(latest().close).toHaveBeenCalled();+ });++ it("getAgentFile requests agents.files.get with agentId + name", async () => {+ const out = {+ agentId: "a",+ workspace: "/w",+ file: { name: "TODO.md", path: "/w/TODO.md", missing: false, content: "hi" },+ };+ nextRequestReturns(out);+ await expect(getAgentFile("a", "TODO.md")).resolves.toEqual(out);+ expect(latest().request).toHaveBeenCalledWith("agents.files.get", {+ agentId: "a",+ name: "TODO.md",+ });+ });++ it("setAgentFile requests agents.files.set and resolves void", async () => {+ await setAgentFile("a", "n", "content");+ expect(latest().request).toHaveBeenCalledWith("agents.files.set", {+ agentId: "a",+ name: "n",+ content: "content",+ });+ });++ it("getSkillStatus requests skills.status with agentId", async () => {+ const out = {+ workspaceDir: "/w",+ managedSkillsDir: "/w/skills",+ agentId: "a",+ skills: [],+ };+ nextRequestReturns(out);+ await expect(getSkillStatus("a")).resolves.toEqual(out);+ expect(latest().request).toHaveBeenCalledWith("skills.status", { agentId: "a" });+ });++ it("setSkillEnabled requests skills.update with skillKey + enabled flag", async () => {+ await setSkillEnabled("my-skill", true);+ expect(latest().request).toHaveBeenCalledWith("skills.update", {+ skillKey: "my-skill",+ enabled: true,+ });+ await setSkillEnabled("my-skill", false);+ expect(latest().request).toHaveBeenCalledWith("skills.update", {+ skillKey: "my-skill",+ enabled: false,+ });+ });++ it("deleteAgent requests agents.delete with deleteFiles:true", async () => {+ await deleteAgent("a");+ expect(latest().request).toHaveBeenCalledWith("agents.delete", {+ agentId: "a",+ deleteFiles: true,+ });+ });++ it("listAllAgents requests agents.list with empty params", async () => {+ const out = { defaultId: "a", mainKey: "main", agents: [] };+ nextRequestReturns(out);+ await expect(listAllAgents()).resolves.toEqual(out);+ expect(latest().request).toHaveBeenCalledWith("agents.list", {});+ });++ it("createAgentViaRpc forwards the full input as params", async () => {+ const input = { name: "demo-cmo", workspace: "/ws", model: "claude-opus-4", emoji: "🎯" };+ await createAgentViaRpc(input);+ expect(latest().request).toHaveBeenCalledWith("agents.create", input);+ });++ it("updateCronMessage wraps the new message in a payload patch", async () => {+ await updateCronMessage("cron-id", "fresh prompt");+ expect(latest().request).toHaveBeenCalledWith("cron.update", {+ id: "cron-id",+ patch: { payload: { kind: "agentTurn", message: "fresh prompt" } },+ });+ });++ it("each call opens a fresh GatewayClient instance and closes it", async () => {+ await setAgentFile("a", "f", "");+ await setAgentFile("a", "g", "");+ expect(clientInstances.length).toBe(2);+ for (const c of clientInstances) {+ expect(c.open).toHaveBeenCalledTimes(1);+ expect(c.close).toHaveBeenCalledTimes(1);+ }+ });+});diff --git a/src/server/openclaw/project-delete.test.ts b/src/server/openclaw/project-delete.test.tsnew file mode 100644index 00000000..8e0926d7--- /dev/null+++ b/src/server/openclaw/project-delete.test.ts@@ -0,0 +1,207 @@+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import {+ afterAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { tmpdir } = require("node:os") as typeof import("node:os");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { join: joinPath } = require("node:path") as typeof import("node:path");+ const original = process.env.OPENCLAW_HOME;+ const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-project-delete-"));+ process.env.OPENCLAW_HOME = tmp;+ return { tmpHome: tmp, ORIGINAL_HOME: original };+});++// Mock all dependencies the SUT pulls in.+const listProjectAgentsMock = vi.fn();+vi.mock("@/server/agent-meta", () => ({+ listProjectAgents: (...args: unknown[]) => listProjectAgentsMock(...args),+}));++const listSessionsMock = vi.fn();+vi.mock("@/server/openclaw/sessions", () => ({+ listSessionsForAgent: (...args: unknown[]) => listSessionsMock(...args),+}));++const listCronsMock = vi.fn();+vi.mock("@/server/openclaw/crons", () => ({+ listCronsForProject: (...args: unknown[]) => listCronsMock(...args),+}));++const readMcpConfigRowMock = vi.fn();+vi.mock("@/server/mcp/rpc", () => ({+ readMcpConfigRow: (...args: unknown[]) => readMcpConfigRowMock(...args),+}));++// mcp-catalog provides MCP_CATALOG + storedMcpKey. We use the real impl+// because it's just data + a pure helper.++import { getProjectDeletionSummary } from "./project-delete";+import { MCP_CATALOG } from "@/server/mcp-catalog";++function ensureAgentDir(agentId: string): void {+ // The SUT does `existsSync(<OPENCLAW_HOME>/agents/<agentId>)` to decide+ // if `exists` is true and if it should list sessions.+ mkdirSync(join(tmpHome, "agents", agentId), { recursive: true });+ writeFileSync(join(tmpHome, "agents", agentId, "marker"), "x", "utf8");+}++beforeEach(() => {+ listProjectAgentsMock.mockReset();+ listSessionsMock.mockReset();+ listCronsMock.mockReset();+ readMcpConfigRowMock.mockReset();+});++afterAll(() => {+ if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;+ else delete process.env.OPENCLAW_HOME;+});++describe("getProjectDeletionSummary", () => {+ it("returns empty totals when no agents / crons / mcps are configured", async () => {+ listProjectAgentsMock.mockResolvedValueOnce([]);+ listCronsMock.mockResolvedValueOnce({ groups: [] });+ readMcpConfigRowMock.mockResolvedValue(null);++ const summary = await getProjectDeletionSummary("empty-project");+ expect(summary.project_slug).toBe("empty-project");+ expect(summary.agents).toEqual([]);+ expect(summary.totals).toEqual({+ agents: 0,+ threads: 0,+ crons: 0,+ mcps: 0,+ });+ // mcps array is one entry per catalog spec, all marked unconfigured.+ expect(summary.mcps.length).toBe(MCP_CATALOG.length);+ expect(summary.mcps.every((m) => !m.configured)).toBe(true);+ });++ it("counts threads from listSessionsForAgent for agents that exist on disk", async () => {+ ensureAgentDir("demo-cmo");+ ensureAgentDir("demo-google-ads");++ listProjectAgentsMock.mockResolvedValueOnce([+ {+ agent_id: "demo-cmo",+ slug: "cmo",+ display_name: "CMO",+ template_key: "cmo",+ is_template_default: true,+ },+ {+ agent_id: "demo-google-ads",+ slug: "google-ads",+ display_name: "Google Ads",+ template_key: "google_ads",+ is_template_default: true,+ },+ // Agent listed in meta but not on disk — exists:false, threads:0.+ {+ agent_id: "demo-ghost",+ slug: "ghost",+ display_name: "Ghost",+ is_template_default: false,+ },+ ]);+ // Two threads in CMO, none in google-ads.+ listSessionsMock.mockImplementation((id: string) => {+ if (id === "demo-cmo")+ return [+ { sessionId: "s1", label: "main", sessionKey: "x", lastInteractionAt: 0, pending: false },+ { sessionId: "s2", label: "alt", sessionKey: "y", lastInteractionAt: 0, pending: false },+ ];+ return [];+ });+ listCronsMock.mockResolvedValueOnce({+ groups: [+ { agent: "cmo", crons: [{ id: "c1" }, { id: "c2" }] },+ { agent: "google-ads", crons: [{ id: "c3" }] },+ ],+ });+ readMcpConfigRowMock.mockResolvedValue(null);++ const summary = await getProjectDeletionSummary("demo");+ expect(summary.totals.agents).toBe(2); // only the two that exist on disk+ expect(summary.totals.threads).toBe(2);+ expect(summary.totals.crons).toBe(3);++ const byId = Object.fromEntries(summary.agents.map((a) => [a.agentId, a]));+ expect(byId["demo-cmo"]!.exists).toBe(true);+ expect(byId["demo-cmo"]!.threadCount).toBe(2);+ expect(byId["demo-google-ads"]!.threadCount).toBe(0);+ expect(byId["demo-ghost"]!.exists).toBe(false);+ expect(byId["demo-ghost"]!.threadCount).toBe(0);+ // listSessionsMock should not have been called for the ghost agent.+ expect(listSessionsMock).not.toHaveBeenCalledWith("demo-ghost");+ });++ it("counts MCPs as configured when readMcpConfigRow returns a truthy row", async () => {+ listProjectAgentsMock.mockResolvedValueOnce([]);+ listCronsMock.mockResolvedValueOnce({ groups: [] });+ // Configure the first catalog entry; leave the rest unconfigured.+ const firstKey = MCP_CATALOG[0]!.key;+ readMcpConfigRowMock.mockImplementation(async (stored_key: string) => {+ if (stored_key === `demo-${firstKey}`) {+ return { url: "https://x", headers: { Authorization: "Bearer y" } };+ }+ return null;+ });++ const summary = await getProjectDeletionSummary("demo");+ expect(summary.totals.mcps).toBe(1);+ const m = summary.mcps.find((x) => x.catalog_key === firstKey);+ expect(m?.configured).toBe(true);+ expect(m?.stored_key).toBe(`demo-${firstKey}`);+ });++ it("treats listCronsForProject errors as 0 crons (best-effort)", async () => {+ listProjectAgentsMock.mockResolvedValueOnce([]);+ listCronsMock.mockRejectedValueOnce(new Error("openclaw down"));+ readMcpConfigRowMock.mockResolvedValue(null);++ const summary = await getProjectDeletionSummary("demo");+ expect(summary.totals.crons).toBe(0);+ });++ it("treats readMcpConfigRow errors as unconfigured (best-effort)", async () => {+ listProjectAgentsMock.mockResolvedValueOnce([]);+ listCronsMock.mockResolvedValueOnce({ groups: [] });+ readMcpConfigRowMock.mockRejectedValue(new Error("subprocess fail"));++ const summary = await getProjectDeletionSummary("demo");+ expect(summary.totals.mcps).toBe(0);+ expect(summary.mcps.every((m) => !m.configured)).toBe(true);+ });++ it("propagates template + display fields onto the agent summary", async () => {+ ensureAgentDir("demo-cmo");+ listProjectAgentsMock.mockResolvedValueOnce([+ {+ agent_id: "demo-cmo",+ slug: "cmo",+ display_name: "Chief Marketing Officer",+ template_key: "cmo",+ is_template_default: true,+ },+ ]);+ listSessionsMock.mockReturnValue([]);+ listCronsMock.mockResolvedValueOnce({ groups: [] });+ readMcpConfigRowMock.mockResolvedValue(null);++ const summary = await getProjectDeletionSummary("demo");+ expect(summary.agents[0]!.template).toBe("cmo");+ expect(summary.agents[0]!.display_name).toBe("Chief Marketing Officer");+ });+});diff --git a/src/server/openclaw/sessions.test.ts b/src/server/openclaw/sessions.test.tsnew file mode 100644index 00000000..3a6030ee--- /dev/null+++ b/src/server/openclaw/sessions.test.ts@@ -0,0 +1,263 @@+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";++const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { tmpdir } = require("node:os") as typeof import("node:os");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { join: joinPath } = require("node:path") as typeof import("node:path");+ const original = process.env.OPENCLAW_HOME;+ const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-sessions-"));+ process.env.OPENCLAW_HOME = tmp;+ return { tmpHome: tmp, ORIGINAL_HOME: original };+});++// Mock next/headers cookies API. Each test sets the cookie state via the+// `cookieStore` helper below.+type CookieMap = Map<string, string>;+const cookieStore: CookieMap = new Map();+let setCalls: Array<{ name: string; value: string; opts: unknown }> = [];++vi.mock("next/headers", () => ({+ cookies: async () => ({+ get: (name: string) => {+ const v = cookieStore.get(name);+ return v === undefined ? undefined : { value: v };+ },+ set: (name: string, value: string, opts: unknown) => {+ cookieStore.set(name, value);+ setCalls.push({ name, value, opts });+ },+ }),+}));++import {+ buildPendingSessionKey,+ findSessionBySessionId,+ getSessionsView,+ listSessionsForAgent,+ newSessionId,+ setActiveSession,+} from "./sessions";++function sessionsPath(agentFullId: string): string {+ return join(tmpHome, "agents", agentFullId, "sessions", "sessions.json");+}++function writeSessions(+ agentFullId: string,+ parsed: Record<string, unknown>,+): void {+ const path = sessionsPath(agentFullId);+ mkdirSync(join(tmpHome, "agents", agentFullId, "sessions"), {+ recursive: true,+ });+ writeFileSync(path, JSON.stringify(parsed), "utf8");+}++beforeEach(() => {+ cookieStore.clear();+ setCalls = [];+});++afterAll(() => {+ if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;+ else delete process.env.OPENCLAW_HOME;+});++describe("listSessionsForAgent", () => {+ it("returns [] when the sessions.json file doesn't exist", () => {+ expect(listSessionsForAgent("nobody-cmo")).toEqual([]);+ });++ it("returns [] when the file is not valid JSON", () => {+ const agent = "broken-cmo";+ const p = sessionsPath(agent);+ mkdirSync(join(tmpHome, "agents", agent, "sessions"), { recursive: true });+ writeFileSync(p, "{ not json", "utf8");+ expect(listSessionsForAgent(agent)).toEqual([]);+ });++ it("parses sessions with the agent: prefix and strips it from label", () => {+ const agent = "demo-cmo";+ writeSessions(agent, {+ "agent:demo-cmo:main": { sessionId: "s1", updatedAt: 100 },+ "agent:demo-cmo:0xabc": { sessionId: "s2", lastInteractionAt: 200 },+ });+ const out = listSessionsForAgent(agent);+ expect(out.map((s) => s.label).sort()).toEqual(["0xabc", "main"]);+ // Newest-first: s2's lastInteractionAt is 200, larger than s1's 100.+ expect(out[0]!.sessionId).toBe("s2");+ expect(out[0]!.lastInteractionAt).toBe(200);+ expect(out[0]!.pending).toBe(false);+ expect(out[1]!.lastInteractionAt).toBe(100);+ });++ it("keeps the raw key as label when the prefix doesn't match", () => {+ const agent = "demo-cmo";+ writeSessions(agent, {+ "unusual-key-without-prefix": { sessionId: "s3", updatedAt: 1 },+ });+ const out = listSessionsForAgent(agent);+ expect(out[0]!.label).toBe("unusual-key-without-prefix");+ });++ it("skips entries with no sessionId", () => {+ const agent = "demo-cmo";+ writeSessions(agent, {+ "agent:demo-cmo:bad": { updatedAt: 1 },+ "agent:demo-cmo:good": { sessionId: "s-good", updatedAt: 5 },+ });+ const out = listSessionsForAgent(agent);+ expect(out.length).toBe(1);+ expect(out[0]!.sessionId).toBe("s-good");+ });++ it("falls back to updatedAt when lastInteractionAt missing, then to 0", () => {+ const agent = "demo-cmo";+ writeSessions(agent, {+ "agent:demo-cmo:a": { sessionId: "a", updatedAt: 50 },+ "agent:demo-cmo:b": { sessionId: "b" },+ });+ const out = listSessionsForAgent(agent);+ const byId = Object.fromEntries(out.map((s) => [s.sessionId, s]));+ expect(byId["a"]!.lastInteractionAt).toBe(50);+ expect(byId["b"]!.lastInteractionAt).toBe(0);+ });+});++describe("buildPendingSessionKey", () => {+ it("joins agent + sessionId with the `agent:` prefix", () => {+ expect(buildPendingSessionKey("demo-cmo", "uuid-1")).toBe(+ "agent:demo-cmo:uuid-1",+ );+ });+});++describe("findSessionBySessionId", () => {+ const agent = "demo-cmo";+ beforeEach(() => {+ writeSessions(agent, {+ "agent:demo-cmo:thread-label": {+ sessionId: "internal-uuid-1",+ updatedAt: 1,+ },+ "agent:demo-cmo:another": {+ sessionId: "internal-uuid-2",+ updatedAt: 2,+ },+ });+ });++ it("matches by label first", () => {+ const r = findSessionBySessionId(agent, "thread-label");+ expect(r?.sessionId).toBe("internal-uuid-1");+ });++ it("falls back to matching by internal sessionId", () => {+ const r = findSessionBySessionId(agent, "internal-uuid-2");+ expect(r?.sessionId).toBe("internal-uuid-2");+ expect(r?.label).toBe("another");+ });++ it("returns null when nothing matches", () => {+ expect(findSessionBySessionId(agent, "no-such-thread")).toBeNull();+ });+});++describe("newSessionId", () => {+ it("returns a UUID-shaped string", () => {+ const id = newSessionId();+ expect(id).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,+ );+ // Reasonably unique.+ expect(newSessionId()).not.toBe(id);+ });+});++describe("getSessionsView", () => {+ // The template `cmo` resolves to `<project>-cmo`.+ it("uses the existing top session when no cookie is set", async () => {+ writeSessions("alpha-cmo", {+ "agent:alpha-cmo:m1": { sessionId: "s1", updatedAt: 100 },+ "agent:alpha-cmo:m2": { sessionId: "s2", updatedAt: 200 },+ });+ const view = await getSessionsView("alpha", "cmo");+ expect(view.active.sessionId).toBe("s2");+ expect(view.all.length).toBe(2);+ expect(view.active.pending).toBe(false);+ });++ it("synthesizes a fresh pending session when no sessions exist + no cookie", async () => {+ const view = await getSessionsView("beta", "cmo");+ expect(view.active.pending).toBe(true);+ expect(view.active.label).toBe("main");+ expect(view.active.sessionKey).toBe(+ `agent:beta-cmo:${view.active.sessionId}`,+ );+ // The synthetic active is prepended to `all`.+ expect(view.all.length).toBe(1);+ expect(view.all[0]).toBe(view.active);+ });++ it("uses the cookie's sessionId when it matches an existing session", async () => {+ writeSessions("gamma-cmo", {+ "agent:gamma-cmo:t-old": { sessionId: "old", updatedAt: 1 },+ "agent:gamma-cmo:t-new": { sessionId: "cookie-id", updatedAt: 2 },+ });+ cookieStore.set("notfair_active_session_gamma_cmo", "cookie-id");+ const view = await getSessionsView("gamma", "cmo");+ expect(view.active.sessionId).toBe("cookie-id");+ expect(view.active.pending).toBe(false);+ // All sessions returned in newest-first order.+ expect(view.all.map((s) => s.sessionId)).toEqual(["cookie-id", "old"]);+ });++ it("treats unknown cookie sessionId as a pending session and prepends it", async () => {+ writeSessions("delta-cmo", {+ "agent:delta-cmo:t-real": { sessionId: "real-id", updatedAt: 1 },+ });+ cookieStore.set("notfair_active_session_delta_cmo", "imaginary-id");+ const view = await getSessionsView("delta", "cmo");+ expect(view.active.sessionId).toBe("imaginary-id");+ expect(view.active.pending).toBe(true);+ // Label is the first 8 chars of the cookie id.+ expect(view.active.label).toBe("imaginar");+ // The pending entry shows up at the front of `all`, with existing kept.+ expect(view.all[0]!.sessionId).toBe("imaginary-id");+ expect(view.all.find((s) => s.sessionId === "real-id")).toBeDefined();+ });+});++describe("setActiveSession", () => {+ it("writes the cookie with the expected name + opts", async () => {+ await setActiveSession("epsilon", "cmo", "fresh-uuid");+ expect(cookieStore.get("notfair_active_session_epsilon_cmo")).toBe(+ "fresh-uuid",+ );+ expect(setCalls.length).toBe(1);+ const opts = setCalls[0]!.opts as {+ httpOnly: boolean;+ sameSite: string;+ path: string;+ maxAge: number;+ };+ expect(opts.httpOnly).toBe(true);+ expect(opts.sameSite).toBe("lax");+ expect(opts.path).toBe("/");+ // 1 year (365d) approx.+ expect(opts.maxAge).toBe(60 * 60 * 24 * 365);+ });+});diff --git a/src/server/openclaw/transcript-tail.test.ts b/src/server/openclaw/transcript-tail.test.tsnew file mode 100644index 00000000..61eaefb1--- /dev/null+++ b/src/server/openclaw/transcript-tail.test.ts@@ -0,0 +1,629 @@+import { mkdirSync, writeFileSync, rmSync } from "node:fs";+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";++const { tmpHome, ORIGINAL_HOME } = vi.hoisted(() => {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { tmpdir } = require("node:os") as typeof import("node:os");+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { join: joinPath } = require("node:path") as typeof import("node:path");+ const original = process.env.OPENCLAW_HOME;+ const tmp = mkdtempSync(joinPath(tmpdir(), "notfair-cmo-transcript-"));+ process.env.OPENCLAW_HOME = tmp;+ return { tmpHome: tmp, ORIGINAL_HOME: original };+});++const findSessionMock = vi.fn();+vi.mock("@/server/openclaw/sessions", () => ({+ findSessionBySessionId: (...args: unknown[]) => findSessionMock(...args),+}));++import { resolveTranscriptPath, readTranscriptTail } from "./transcript-tail";+import { join } from "node:path";++function transcriptPath(agentFullId: string, sessionId: string): string {+ return join(tmpHome, "agents", agentFullId, "sessions", `${sessionId}.jsonl`);+}++function writeTranscript(agentFullId: string, sessionId: string, lines: string[]): string {+ const p = transcriptPath(agentFullId, sessionId);+ mkdirSync(join(tmpHome, "agents", agentFullId, "sessions"), { recursive: true });+ writeFileSync(p, lines.join("\n") + (lines.length ? "\n" : ""), "utf8");+ return p;+}++function setSession(sessionId: string, label = sessionId): void {+ findSessionMock.mockReturnValue({+ sessionId,+ label,+ sessionKey: `agent:demo:${label}`,+ lastInteractionAt: 0,+ pending: false,+ });+}++describe("resolveTranscriptPath", () => {+ beforeEach(() => {+ findSessionMock.mockReset();+ });++ it("returns null when session not found", () => {+ findSessionMock.mockReturnValue(null);+ expect(resolveTranscriptPath("demo", "missing")).toBeNull();+ });++ it("returns null when file does not exist on disk", () => {+ setSession("sess-no-file");+ expect(resolveTranscriptPath("demo", "sess-no-file")).toBeNull();+ });++ it("returns the absolute path when session exists and file is on disk", () => {+ writeTranscript("demo", "sess-1", []);+ setSession("sess-1");+ expect(resolveTranscriptPath("demo", "sess-1")).toBe(transcriptPath("demo", "sess-1"));+ });+});++describe("readTranscriptTail", () => {+ beforeEach(() => {+ findSessionMock.mockReset();+ });++ it("returns empty events + same byteOffset when the file does not exist", () => {+ findSessionMock.mockReturnValue(null);+ const r = readTranscriptTail("demo", "x", 42);+ expect(r).toEqual({ events: [], byteOffset: 42, fileSize: 0 });+ });++ it("returns empty when byteOffset === fileSize (no new bytes)", () => {+ const lines = [JSON.stringify({ type: "message", id: "m1" })];+ writeTranscript("demo", "sess-2", lines);+ setSession("sess-2");+ const first = readTranscriptTail("demo", "sess-2", 0);+ expect(first.events.length).toBeGreaterThanOrEqual(0);+ const second = readTranscriptTail("demo", "sess-2", first.byteOffset);+ expect(second.events).toEqual([]);+ expect(second.byteOffset).toBe(first.byteOffset);+ });++ it("resets the byteOffset when it's beyond fileSize (rotation/truncation)", () => {+ writeTranscript("demo", "sess-3", [JSON.stringify({ type: "x" })]);+ setSession("sess-3");+ const r = readTranscriptTail("demo", "sess-3", 1_000_000);+ expect(r.events.length).toBe(1);+ });++ it("emits a user_message for role:user with string content", () => {+ writeTranscript("demo", "sess-4", [+ JSON.stringify({+ type: "message",+ id: "u1",+ timestamp: 1700000000,+ message: { role: "user", content: "hello there" },+ }),+ ]);+ setSession("sess-4");+ const r = readTranscriptTail("demo", "sess-4", 0);+ expect(r.events.length).toBe(1);+ const e = r.events[0]!;+ expect(e.kind).toBe("user_message");+ if (e.kind === "user_message") {+ expect(e.body).toBe("hello there");+ expect(e.ts).toBe(1700000000);+ }+ });++ it("strips a timestamp prefix from user messages", () => {+ writeTranscript("demo", "sess-5", [+ JSON.stringify({+ type: "message",+ id: "u1",+ message: {+ role: "user",+ content: "[Mon 2026-05-19 09:00 PDT] real body",+ },+ }),+ ]);+ setSession("sess-5");+ const r = readTranscriptTail("demo", "sess-5", 0);+ const e = r.events[0]!;+ if (e.kind === "user_message") {+ expect(e.body).toBe("real body");+ }+ });++ it("emits user_message with array-of-text content joined", () => {+ writeTranscript("demo", "sess-6", [+ JSON.stringify({+ type: "message",+ id: "u1",+ message: {+ role: "user",+ content: [+ { type: "text", text: "first" },+ "raw-string-part",+ { type: "text", text: "second" },+ ],+ },+ }),+ ]);+ setSession("sess-6");+ const r = readTranscriptTail("demo", "sess-6", 0);+ const e = r.events[0]!;+ if (e.kind === "user_message") {+ expect(e.body).toContain("first");+ expect(e.body).toContain("raw-string-part");+ expect(e.body).toContain("second");+ }+ });++ it("skips user messages whose body is empty after extraction", () => {+ writeTranscript("demo", "sess-empty-user", [+ JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "" } }),+ ]);+ setSession("sess-empty-user");+ const r = readTranscriptTail("demo", "sess-empty-user", 0);+ expect(r.events).toEqual([]);+ });++ it("emits tool_result for top-level role:toolResult messages", () => {+ writeTranscript("demo", "sess-7", [+ JSON.stringify({+ type: "message",+ id: "tr1",+ timestamp: 1000,+ message: {+ role: "toolResult",+ toolCallId: "call-1",+ toolName: "exec",+ isError: false,+ content: "stdout: ok",+ },+ }),+ ]);+ setSession("sess-7");+ const r = readTranscriptTail("demo", "sess-7", 0);+ expect(r.events.length).toBe(1);+ const e = r.events[0]!;+ expect(e.kind).toBe("tool_result");+ if (e.kind === "tool_result") {+ expect(e.tool_call_id).toBe("call-1");+ expect(e.ok).toBe(true);+ expect(e.summary).toBe("stdout: ok");+ expect(e.name).toBe("exec");+ }+ });++ it("marks isError:true toolResults as ok:false", () => {+ writeTranscript("demo", "sess-7-err", [+ JSON.stringify({+ type: "message",+ id: "tr1",+ message: {+ role: "toolResult",+ toolCallId: "call-1",+ isError: true,+ content: "boom",+ },+ }),+ ]);+ setSession("sess-7-err");+ const r = readTranscriptTail("demo", "sess-7-err", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_result") {+ expect(e.ok).toBe(false);+ expect(e.name).toBe("tool");+ }+ });++ it("skips toolResult messages without a toolCallId", () => {+ writeTranscript("demo", "sess-7-no-id", [+ JSON.stringify({+ type: "message",+ id: "tr1",+ message: { role: "toolResult", content: "x" },+ }),+ ]);+ setSession("sess-7-no-id");+ const r = readTranscriptTail("demo", "sess-7-no-id", 0);+ expect(r.events).toEqual([]);+ });++ it("emits assistant_text for assistant text-part content", () => {+ writeTranscript("demo", "sess-8", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ { type: "text", text: "Sure, here we go." },+ ],+ },+ }),+ ]);+ setSession("sess-8");+ const r = readTranscriptTail("demo", "sess-8", 0);+ expect(r.events.length).toBe(1);+ const e = r.events[0]!;+ expect(e.kind).toBe("assistant_text");+ if (e.kind === "assistant_text") expect(e.body).toBe("Sure, here we go.");+ });++ it("emits assistant_text for string parts in assistant content", () => {+ writeTranscript("demo", "sess-8-str", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: { role: "assistant", content: ["raw string body"] },+ }),+ ]);+ setSession("sess-8-str");+ const r = readTranscriptTail("demo", "sess-8-str", 0);+ expect(r.events[0]!.kind).toBe("assistant_text");+ });++ it("skips empty/whitespace text parts in assistant content", () => {+ writeTranscript("demo", "sess-8-blank", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ { type: "text", text: " " },+ " ",+ { type: "text", text: "real" },+ ],+ },+ }),+ ]);+ setSession("sess-8-blank");+ const r = readTranscriptTail("demo", "sess-8-blank", 0);+ expect(r.events.length).toBe(1);+ });++ it("emits tool_call with command label for exec-shaped args", () => {+ writeTranscript("demo", "sess-9", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolCall",+ id: "call-1",+ name: "exec",+ arguments: { command: "pnpm test\nfoo" },+ },+ ],+ },+ }),+ ]);+ setSession("sess-9");+ const r = readTranscriptTail("demo", "sess-9", 0);+ const e = r.events[0]!;+ expect(e.kind).toBe("tool_call");+ if (e.kind === "tool_call") {+ expect(e.label).toContain("pnpm test");+ expect(e.tool_call_id).toBe("call-1");+ expect(e.name).toBe("exec");+ }+ });++ it("falls back to JSON preview label when no known arg shape matches", () => {+ writeTranscript("demo", "sess-10", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolCall",+ id: "call-x",+ name: "unknown",+ arguments: { random: { nested: 1 } },+ },+ ],+ },+ }),+ ]);+ setSession("sess-10");+ const r = readTranscriptTail("demo", "sess-10", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_call") expect(e.label).toContain("random");+ });++ it("returns null label when toolCall has no args", () => {+ writeTranscript("demo", "sess-noargs", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [{ type: "toolCall", id: "call-x", name: "x" }],+ },+ }),+ ]);+ setSession("sess-noargs");+ const r = readTranscriptTail("demo", "sess-noargs", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_call") expect(e.label).toBeNull();+ });++ it("uses input field when arguments missing on toolCall", () => {+ writeTranscript("demo", "sess-input", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolCall",+ id: "c1",+ name: "read",+ input: { path: "/foo/bar.ts" },+ },+ ],+ },+ }),+ ]);+ setSession("sess-input");+ const r = readTranscriptTail("demo", "sess-input", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_call") expect(e.label).toBe("/foo/bar.ts");+ });++ it("emits inline toolResult inside assistant content", () => {+ writeTranscript("demo", "sess-11", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolResult",+ toolCallId: "call-1",+ name: "exec",+ isError: false,+ content: [{ text: "result text" }],+ },+ ],+ },+ }),+ ]);+ setSession("sess-11");+ const r = readTranscriptTail("demo", "sess-11", 0);+ const e = r.events[0]!;+ expect(e.kind).toBe("tool_result");+ if (e.kind === "tool_result") {+ expect(e.tool_call_id).toBe("call-1");+ expect(e.summary).toBe("result text");+ expect(e.ok).toBe(true);+ }+ });++ it("uses tool_call_id (snake) and is_error (snake) as fallbacks", () => {+ writeTranscript("demo", "sess-snake", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolResult",+ tool_call_id: "snake-id",+ name: "x",+ is_error: true,+ output: "x output",+ },+ ],+ },+ }),+ ]);+ setSession("sess-snake");+ const r = readTranscriptTail("demo", "sess-snake", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_result") {+ expect(e.tool_call_id).toBe("snake-id");+ expect(e.ok).toBe(false);+ expect(e.summary).toBe("x output");+ }+ });++ it("emits an unknown event for non-message rows", () => {+ writeTranscript("demo", "sess-12", [+ JSON.stringify({ type: "session-meta", id: "m1", foo: "bar" }),+ ]);+ setSession("sess-12");+ const r = readTranscriptTail("demo", "sess-12", 0);+ const e = r.events[0]!;+ expect(e.kind).toBe("unknown");+ if (e.kind === "unknown") expect(e.raw_type).toBe("session-meta");+ });++ it("skips non-message entries with missing type (raw_type defaults to ?)", () => {+ writeTranscript("demo", "sess-noType", [JSON.stringify({ id: "m1", foo: 1 })]);+ setSession("sess-noType");+ const r = readTranscriptTail("demo", "sess-noType", 0);+ const e = r.events[0]!;+ if (e.kind === "unknown") expect(e.raw_type).toBe("?");+ });++ it("skips lines that are not valid JSON", () => {+ writeTranscript("demo", "sess-bad", [+ "not json",+ JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "hi" } }),+ ]);+ setSession("sess-bad");+ const r = readTranscriptTail("demo", "sess-bad", 0);+ expect(r.events.length).toBe(1);+ expect(r.events[0]!.kind).toBe("user_message");+ });++ it("only consumes up to the last newline (leaves partial line unconsumed)", () => {+ const p = transcriptPath("demo", "sess-partial");+ mkdirSync(join(tmpHome, "agents", "demo", "sessions"), { recursive: true });+ const completeLine =+ JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "hello" } }) ++ "\n";+ const partial =+ JSON.stringify({ type: "message", id: "u2", message: { role: "user", content: "world" } });+ writeFileSync(p, completeLine + partial, "utf8");+ setSession("sess-partial");+ const r = readTranscriptTail("demo", "sess-partial", 0);+ expect(r.events.length).toBe(1);+ expect(r.byteOffset).toBe(Buffer.byteLength(completeLine, "utf8"));+ expect(r.byteOffset).toBeLessThan(r.fileSize);+ });++ it("returns events:[] when buffer has no newline at all", () => {+ const p = transcriptPath("demo", "sess-noNL");+ mkdirSync(join(tmpHome, "agents", "demo", "sessions"), { recursive: true });+ writeFileSync(p, "no newline here", "utf8");+ setSession("sess-noNL");+ const r = readTranscriptTail("demo", "sess-noNL", 0);+ expect(r.events).toEqual([]);+ expect(r.byteOffset).toBe(0);+ });++ it("parses string timestamps via Date.parse", () => {+ writeTranscript("demo", "sess-tsstr", [+ JSON.stringify({+ type: "message",+ id: "u1",+ timestamp: "2026-01-01T00:00:00Z",+ message: { role: "user", content: "hi" },+ }),+ ]);+ setSession("sess-tsstr");+ const r = readTranscriptTail("demo", "sess-tsstr", 0);+ expect(r.events[0]!.ts).toBe(Date.parse("2026-01-01T00:00:00Z"));+ });++ it("ts defaults to 0 when timestamp is missing", () => {+ writeTranscript("demo", "sess-nots", [+ JSON.stringify({ type: "message", id: "u1", message: { role: "user", content: "hi" } }),+ ]);+ setSession("sess-nots");+ const r = readTranscriptTail("demo", "sess-nots", 0);+ expect(r.events[0]!.ts).toBe(0);+ });++ it("skips messages with role other than user/assistant/toolResult", () => {+ writeTranscript("demo", "sess-role", [+ JSON.stringify({ type: "message", id: "x", message: { role: "system", content: "noise" } }),+ ]);+ setSession("sess-role");+ const r = readTranscriptTail("demo", "sess-role", 0);+ expect(r.events).toEqual([]);+ });++ it("skips message entries with no message body", () => {+ writeTranscript("demo", "sess-nobody", [JSON.stringify({ type: "message", id: "x" })]);+ setSession("sess-nobody");+ const r = readTranscriptTail("demo", "sess-nobody", 0);+ expect(r.events).toEqual([]);+ });++ it("uses url label when toolCall has url arg", () => {+ writeTranscript("demo", "sess-url", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolCall",+ id: "c1",+ name: "fetch",+ arguments: { url: "https://example.com/api" },+ },+ ],+ },+ }),+ ]);+ setSession("sess-url");+ const r = readTranscriptTail("demo", "sess-url", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_call") expect(e.label).toBe("https://example.com/api");+ });++ it("summarizes string content for inline toolResult", () => {+ writeTranscript("demo", "sess-strsum", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolResult",+ toolCallId: "c1",+ content: "single string output",+ },+ ],+ },+ }),+ ]);+ setSession("sess-strsum");+ const r = readTranscriptTail("demo", "sess-strsum", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_result") expect(e.summary).toBe("single string output");+ });++ it("returns null summary when toolResult content is null/empty array", () => {+ writeTranscript("demo", "sess-nullsum", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [{ type: "toolResult", toolCallId: "c1", content: [] }],+ },+ }),+ ]);+ setSession("sess-nullsum");+ const r = readTranscriptTail("demo", "sess-nullsum", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_result") expect(e.summary).toBeNull();+ });++ it("summarizes object content as JSON preview", () => {+ writeTranscript("demo", "sess-objsum", [+ JSON.stringify({+ type: "message",+ id: "a1",+ message: {+ role: "assistant",+ content: [+ {+ type: "toolResult",+ toolCallId: "c1",+ content: { ok: true, lines: 42 },+ },+ ],+ },+ }),+ ]);+ setSession("sess-objsum");+ const r = readTranscriptTail("demo", "sess-objsum", 0);+ const e = r.events[0]!;+ if (e.kind === "tool_result") expect(e.summary).toMatch(/ok/);+ });+});++afterAll(() => {+ try {+ rmSync(tmpHome, { recursive: true, force: true });+ } catch {}+ if (ORIGINAL_HOME) process.env.OPENCLAW_HOME = ORIGINAL_HOME;+ else delete process.env.OPENCLAW_HOME;+});diff --git a/src/server/orchestration/process-blocks.test.ts b/src/server/orchestration/process-blocks.test.tsindex 95677558..4b9a71a0 100644--- a/src/server/orchestration/process-blocks.test.ts+++ b/src/server/orchestration/process-blocks.test.ts@@ -12,10 +12,14 @@ vi.mock("@/server/agent-templates", () => ({const createTaskMock = vi.fn();const getTaskMock = vi.fn();const updateTaskMock = vi.fn();+const claimProposedTaskMock = vi.fn();+const setTaskThreadIfMissingMock = vi.fn();vi.mock("@/server/db/tasks", () => ({createTask: (...a: unknown[]) => createTaskMock(...a),getTask: (...a: unknown[]) => getTaskMock(...a),updateTask: (...a: unknown[]) => updateTaskMock(...a),+ claimProposedTask: (...a: unknown[]) => claimProposedTaskMock(...a),+ setTaskThreadIfMissing: (...a: unknown[]) => setTaskThreadIfMissingMock(...a),}));const logAgentActionMock = vi.fn();@@ -23,7 +27,12 @@ vi.mock("@/server/db/agent-actions", () => ({logAgentAction: (...a: unknown[]) => logAgentActionMock(...a),}));-import { processOrchestrationBlocks } from "./process-blocks";+const createApprovalMock = vi.fn();+vi.mock("@/server/db/approvals", () => ({+ createApproval: (...a: unknown[]) => createApprovalMock(...a),+}));++import { generateTaskThreadId, processOrchestrationBlocks } from "./process-blocks";const CMO_ID = "demo-cmo";@@ -229,4 +238,471 @@ status: done});expect(outcome.errors[0]?.message).toMatch(/Unknown task_id/);});++ it("maps status=working to running", async () => {+ const text = `<task_status>+task_id: task-1+status: working+summary: still on it+</task_status>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({ status: "running" }),+ );+ expect(outcome.task_status_updates[0]).toEqual({+ task_id: "task-1",+ status: "running",+ });+ });++ it("maps status=blocked to running (still active, just stalled)", async () => {+ const text = `<task_status>+task_id: task-1+status: blocked+summary: waiting on user+</task_status>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({ status: "running" }),+ );+ expect(outcome.task_status_updates[0]?.status).toBe("running");+ });++ it("maps status=failed to failed and surfaces summary into error_message", async () => {+ const text = `<task_status>+task_id: task-1+status: failed+summary: tag fetch returned 500+</task_status>`;+ await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({+ status: "failed",+ error_message: "tag fetch returned 500",+ }),+ );+ });++ it("uses default error_message when failed status has no summary", async () => {+ const text = `<task_status>+task_id: task-1+status: failed+</task_status>`;+ await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({+ status: "failed",+ error_message: "agent reported failure",+ }),+ );+ });++ it.each(["cancelled", "failed", "succeeded"] as const)(+ "skips writes when task is already terminal (%s)",+ async (terminal) => {+ getTaskMock.mockReturnValueOnce({+ id: "task-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ status: terminal,+ });+ const text = `<task_status>+task_id: task-1+status: done+summary: late+</task_status>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ // No write happens — the existing terminal status is preserved.+ expect(updateTaskMock).not.toHaveBeenCalled();+ // Outcome still reports the existing status for observability.+ expect(outcome.task_status_updates[0]).toEqual({+ task_id: "task-1",+ status: terminal,+ });+ expect(outcome.errors).toHaveLength(0);+ },+ );++ it("captures thrown errors from getTask as task_status errors (not exceptions)", async () => {+ getTaskMock.mockImplementationOnce(() => {+ throw new Error("db boom");+ });+ const text = `<task_status>+task_id: task-1+status: done+</task_status>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.errors).toEqual([+ { kind: "task_status", message: "db boom" },+ ]);+ });+});++describe("processOrchestrationBlocks — add_comment", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getTaskMock.mockReturnValue({+ id: "task-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ });++ it("logs a task_comment agent_action on success", async () => {+ const text = `<add_comment>+task_id: task-1+body: Picked up; running the audit now.+</add_comment>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.comments_added).toEqual([{ task_id: "task-1" }]);+ expect(logAgentActionMock).toHaveBeenCalledWith(+ expect.objectContaining({+ action_type: "task_comment",+ summary: "Picked up; running the audit now.",+ payload: { task_id: "task-1" },+ }),+ );+ expect(outcome.errors).toHaveLength(0);+ });++ it("rejects comments on unknown task_id", async () => {+ getTaskMock.mockReturnValueOnce(null);+ const text = `<add_comment>+task_id: missing+body: hi+</add_comment>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.comments_added).toHaveLength(0);+ expect(outcome.errors[0]).toEqual({+ kind: "add_comment",+ message: expect.stringMatching(/Unknown task_id/),+ });+ });++ it("rejects cross-project comments", async () => {+ getTaskMock.mockReturnValueOnce({+ id: "task-1",+ project_slug: "OTHER",+ agent_id: "demo-google-ads",+ });+ const text = `<add_comment>+task_id: task-1+body: hi+</add_comment>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.errors[0]?.message).toMatch(/Cross-project comment/);+ });+});++describe("processOrchestrationBlocks — ask_user", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getTaskMock.mockReturnValue({+ id: "task-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ });++ it("logs an ask_user agent_action anchored to a task", async () => {+ const text = `<ask_user>+task_id: task-1+question: What's the daily budget cap?+options: 50, 100, 250+</ask_user>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.ask_user).toEqual([+ { task_id: "task-1", question: "What's the daily budget cap?" },+ ]);+ expect(logAgentActionMock).toHaveBeenCalledWith(+ expect.objectContaining({+ action_type: "ask_user",+ summary: "What's the daily budget cap?",+ payload: { task_id: "task-1", options: "50, 100, 250" },+ }),+ );+ });++ it("allows an ask_user with no task_id (unanchored)", async () => {+ const text = `<ask_user>+question: General preference question?+</ask_user>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-cmo",+ });+ expect(getTaskMock).not.toHaveBeenCalled();+ expect(outcome.ask_user[0]).toEqual({+ task_id: undefined,+ question: "General preference question?",+ });+ expect(logAgentActionMock).toHaveBeenCalledWith(+ expect.objectContaining({+ action_type: "ask_user",+ payload: { task_id: null, options: null },+ }),+ );+ });++ it("rejects ask_user on unknown task_id", async () => {+ getTaskMock.mockReturnValueOnce(null);+ const text = `<ask_user>+task_id: missing+question: hi?+</ask_user>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.errors[0]?.message).toMatch(/Unknown task_id/);+ });++ it("rejects cross-project ask_user", async () => {+ getTaskMock.mockReturnValueOnce({+ id: "task-1",+ project_slug: "OTHER",+ agent_id: "demo-google-ads",+ });+ const text = `<ask_user>+task_id: task-1+question: hi?+</ask_user>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.errors[0]?.message).toMatch(/Cross-project ask_user/);+ });+});++describe("processOrchestrationBlocks — request_approval", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getTaskMock.mockReturnValue({+ id: "task-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ createApprovalMock.mockImplementation((input) => ({+ id: "approval-1",+ project_slug: input.project_slug,+ agent_id: input.agent_id,+ action_summary: input.action_summary,+ action_type: input.action_type,+ cost_estimate_usd: input.cost_estimate_usd,+ reasoning: input.reasoning ?? null,+ payload_json: JSON.stringify(input.payload ?? {}),+ status: "pending",+ created_at: "now",+ resolved_at: null,+ }));+ });++ it("creates an approval row and reports it on the outcome", async () => {+ const text = `<request_approval>+task_id: task-1+action_summary: Raise the daily cap on Brand to $200.+action_type: bid_change+cost_estimate_usd: 200+reasoning: Brand is throttled; observed CPC stable.+</request_approval>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(createApprovalMock).toHaveBeenCalledWith(+ expect.objectContaining({+ project_slug: "demo",+ agent_id: "demo-google-ads",+ action_type: "bid_change",+ cost_estimate_usd: 200,+ reasoning: "Brand is throttled; observed CPC stable.",+ payload: { task_id: "task-1" },+ }),+ );+ expect(outcome.approvals_requested).toEqual([+ { approval_id: "approval-1", action_type: "bid_change" },+ ]);+ });++ it("defaults cost_estimate_usd to 0 when not provided", async () => {+ const text = `<request_approval>+action_summary: Publish a new blog post.+action_type: content_publishing+</request_approval>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-cmo",+ });+ expect(createApprovalMock).toHaveBeenCalledWith(+ expect.objectContaining({+ cost_estimate_usd: 0,+ reasoning: null,+ payload: { task_id: null },+ }),+ );+ expect(outcome.approvals_requested).toHaveLength(1);+ });++ it("rejects request_approval on unknown task_id", async () => {+ getTaskMock.mockReturnValueOnce(null);+ const text = `<request_approval>+task_id: missing+action_summary: x+action_type: spend+</request_approval>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.errors[0]).toEqual({+ kind: "request_approval",+ message: expect.stringMatching(/Unknown task_id/),+ });+ expect(createApprovalMock).not.toHaveBeenCalled();+ });++ it("rejects cross-project request_approval", async () => {+ getTaskMock.mockReturnValueOnce({+ id: "task-1",+ project_slug: "OTHER",+ agent_id: "demo-google-ads",+ });+ const text = `<request_approval>+task_id: task-1+action_summary: x+action_type: spend+</request_approval>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ expect(outcome.errors[0]?.message).toMatch(/Cross-project approval/);+ });++ it("captures unexpected createApproval errors as request_approval errors", async () => {+ createApprovalMock.mockImplementationOnce(() => {+ throw new Error("db down");+ });+ const text = `<request_approval>+action_summary: x+action_type: spend+</request_approval>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-cmo",+ });+ expect(outcome.errors).toEqual([+ { kind: "request_approval", message: "db down" },+ ]);+ expect(outcome.approvals_requested).toHaveLength(0);+ });++ /**+ * Known open issue: when a specialist emits <request_approval> without a+ * corresponding <task_status status: blocked>, the task stays "running"+ * forever (see MEMORY.md). This test documents the current behavior —+ * processing the approval does NOT also flip the task's status. Marked+ * `.fails` so when the bug is fixed, the test breaks and someone has to+ * decide whether to delete or invert the assertion.+ */+ it.fails(+ "BUG: emitting request_approval alone does not flip the task to blocked",+ async () => {+ const text = `<request_approval>+task_id: task-1+action_summary: Raise budget+action_type: spend+</request_approval>`;+ await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: "demo-google-ads",+ });+ // We *expect* the task to be marked blocked/paused once the bug is+ // fixed. Today, no task update happens at all.+ expect(updateTaskMock).toHaveBeenCalled();+ },+ );+});++describe("processOrchestrationBlocks — create_task error capture", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ templateForKeyMock.mockReturnValue({+ key: "google_ads",+ display_name: "Google Ads",+ });+ agentNameForMock.mockImplementation(+ (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,+ );+ agentExistsMock.mockResolvedValue(true);+ });++ it("captures thrown errors from createTask as create_task errors", async () => {+ createTaskMock.mockImplementationOnce(() => {+ throw new Error("constraint violation");+ });+ const text = `<create_task>+title: A+assignee: google_ads+brief: do the thing+</create_task>`;+ const outcome = await processOrchestrationBlocks(text, {+ project_slug: "demo",+ agent_id: CMO_ID,+ });+ expect(outcome.tasks_created).toHaveLength(0);+ expect(outcome.errors).toEqual([+ { kind: "create_task", message: "constraint violation" },+ ]);+ });+});++describe("generateTaskThreadId", () => {+ it("returns a UUID-shaped string", () => {+ const id = generateTaskThreadId();+ expect(id).toMatch(+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,+ );+ });++ it("returns a new UUID on each call", () => {+ const a = generateTaskThreadId();+ const b = generateTaskThreadId();+ expect(a).not.toBe(b);+ });});diff --git a/src/server/orchestration/run-task.test.ts b/src/server/orchestration/run-task.test.tsnew file mode 100644index 00000000..bf61fc37--- /dev/null+++ b/src/server/orchestration/run-task.test.ts@@ -0,0 +1,290 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Task } from "@/types";++// --- Module mocks (must be set up before importing the SUT). ---++const claimProposedTaskMock = vi.fn();+const setTaskThreadIfMissingMock = vi.fn();+const updateTaskMock = vi.fn();+vi.mock("@/server/db/tasks", () => ({+ claimProposedTask: (...a: unknown[]) => claimProposedTaskMock(...a),+ setTaskThreadIfMissing: (...a: unknown[]) => setTaskThreadIfMissingMock(...a),+ updateTask: (...a: unknown[]) => updateTaskMock(...a),+}));++const streamChatViaGatewayMock = vi.fn();+vi.mock("@/server/openclaw/gateway-client", () => ({+ streamChatViaGateway: (...a: unknown[]) => streamChatViaGatewayMock(...a),+}));++vi.mock("@/server/openclaw/sessions", () => ({+ buildPendingSessionKey: (agent: string, thread: string) =>+ `agent:${agent}:${thread}`,+}));++const processOrchestrationBlocksMock = vi.fn();+const generateTaskThreadIdMock = vi.fn(() => "thread-fresh");+vi.mock("./process-blocks", () => ({+ processOrchestrationBlocks: (...a: unknown[]) =>+ processOrchestrationBlocksMock(...a),+ generateTaskThreadId: () => generateTaskThreadIdMock(),+}));++// task-kickoff is small + pure — let the real implementation run so we don't+// silently mask a contract change between run-task and the kickoff message.++import { runTaskKickoffServerSide, startTaskIfProposed } from "./run-task";++function makeTask(overrides: Partial<Task> = {}): Task {+ return {+ id: "task-1",+ display_id: "demo-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ title: "Install conversion tracking",+ brief: "Add the Google Ads conversion tag.",+ success_criteria: "Tag fires on /thanks; conv appears in Google Ads.",+ deadline_iso: null,+ status: "proposed",+ result_json: null,+ error_message: null,+ thread_id: "thread-existing",+ assigner_agent_id: "demo-cmo",+ created_at: "2026-05-19T00:00:00Z",+ updated_at: "2026-05-19T00:00:00Z",+ ...overrides,+ };+}++// Helper: build an async-iterable matching the StreamChatInput contract.+async function* eventStream(+ events: Array<{ kind: "delta"; text: string } | { kind: "error"; message: string }>,+): AsyncGenerator<unknown, void, void> {+ for (const evt of events) yield evt;+}++describe("startTaskIfProposed", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Default: streaming returns no text so the kickoff is a no-op past the+ // claim. Individual tests override.+ streamChatViaGatewayMock.mockImplementation(() => eventStream([]));+ });++ it("returns the input task untouched when the claim fails (already running)", () => {+ claimProposedTaskMock.mockReturnValue(null);+ const task = makeTask({ status: "running" });+ const result = startTaskIfProposed(task);+ expect(result).toBe(task);+ // Kickoff must not be triggered when the claim doesn't succeed.+ expect(streamChatViaGatewayMock).not.toHaveBeenCalled();+ });++ it("returns the claimed task and fires kickoff in the background when claim succeeds", async () => {+ const claimed = makeTask({ status: "running" });+ claimProposedTaskMock.mockReturnValue(claimed);++ const result = startTaskIfProposed(makeTask({ status: "proposed" }));+ expect(result).toBe(claimed);+ expect(claimProposedTaskMock).toHaveBeenCalledWith("task-1");++ // The kickoff is fire-and-forget; let microtasks drain so it actually runs.+ await new Promise((r) => setImmediate(r));+ expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);+ });++ it("swallows kickoff errors so the caller (synchronous) never throws", async () => {+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const claimed = makeTask({ status: "running", thread_id: null });+ claimProposedTaskMock.mockReturnValue(claimed);+ // Force the kickoff to throw — thread assignment will fail because both+ // claim + setTaskThreadIfMissing return null.+ setTaskThreadIfMissingMock.mockReturnValue(null);++ expect(() =>+ startTaskIfProposed(makeTask({ status: "proposed", thread_id: null })),+ ).not.toThrow();++ // Wait for the background error to surface via console.error.+ await new Promise((r) => setImmediate(r));+ await new Promise((r) => setImmediate(r));+ expect(errSpy).toHaveBeenCalledWith(+ "[start-task] kickoff failed:",+ expect.any(Error),+ );+ errSpy.mockRestore();+ });+});++describe("runTaskKickoffServerSide", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ processOrchestrationBlocksMock.mockResolvedValue({+ tasks_created: [],+ task_status_updates: [],+ comments_added: [],+ ask_user: [],+ approvals_requested: [],+ errors: [],+ });+ });++ it("consumes the gateway stream, accumulates deltas, and forwards them to orchestration", async () => {+ streamChatViaGatewayMock.mockImplementation(() =>+ eventStream([+ { kind: "delta", text: "On it. " },+ { kind: "delta", text: "Wrapping up.\n" },+ { kind: "delta", text: "<task_status>\ntask_id: task-1\nstatus: done\n</task_status>" },+ ]),+ );++ await runTaskKickoffServerSide(makeTask());++ expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);+ const [call] = streamChatViaGatewayMock.mock.calls;+ expect(call?.[0]).toEqual(+ expect.objectContaining({+ sessionKey: "agent:demo-google-ads:thread-existing",+ sessionId: "thread-existing",+ // The kickoff message is built by buildTaskKickoffMessage — sanity-check+ // it carries the brief without locking the prose to a snapshot.+ message: expect.stringContaining("Add the Google Ads conversion tag."),+ }),+ );+ expect(call?.[0].message).toContain("Task ID: task-1");++ // Orchestration sees the full accumulated buffer and the correct context.+ expect(processOrchestrationBlocksMock).toHaveBeenCalledWith(+ "On it. Wrapping up.\n<task_status>\ntask_id: task-1\nstatus: done\n</task_status>",+ { project_slug: "demo", agent_id: "demo-google-ads" },+ );++ expect(updateTaskMock).not.toHaveBeenCalled();+ });++ it("lazily assigns a fresh thread_id when the task has none yet", async () => {+ const refreshed = makeTask({ thread_id: "thread-fresh" });+ setTaskThreadIfMissingMock.mockReturnValue(refreshed);+ streamChatViaGatewayMock.mockImplementation(() => eventStream([]));++ await runTaskKickoffServerSide(makeTask({ thread_id: null }));++ expect(setTaskThreadIfMissingMock).toHaveBeenCalledWith(+ "task-1",+ "thread-fresh",+ );+ expect(streamChatViaGatewayMock).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: "thread-fresh",+ sessionKey: "agent:demo-google-ads:thread-fresh",+ }),+ );+ });++ it("throws when no thread_id can be assigned (and does not call the gateway)", async () => {+ setTaskThreadIfMissingMock.mockReturnValue(null);+ await expect(+ runTaskKickoffServerSide(makeTask({ thread_id: null })),+ ).rejects.toThrow(/Failed to assign thread_id/);+ expect(streamChatViaGatewayMock).not.toHaveBeenCalled();+ });++ it("on gateway error event: marks task failed and skips orchestration", async () => {+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ streamChatViaGatewayMock.mockImplementation(() =>+ eventStream([+ { kind: "delta", text: "partial..." },+ { kind: "error", message: "gateway exploded" },+ ]),+ );++ await runTaskKickoffServerSide(makeTask());++ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({+ status: "failed",+ error_message: "gateway exploded",+ }),+ );+ expect(processOrchestrationBlocksMock).not.toHaveBeenCalled();+ errSpy.mockRestore();+ });++ it("on gateway iterator throw: marks task failed with the thrown message", async () => {+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ streamChatViaGatewayMock.mockImplementation(async function* () {+ yield { kind: "delta", text: "starting..." };+ throw new Error("socket closed");+ });++ await runTaskKickoffServerSide(makeTask());++ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({+ status: "failed",+ error_message: "socket closed",+ }),+ );+ errSpy.mockRestore();+ });++ it("on non-Error throw from gateway: stringifies the value into error_message", async () => {+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ streamChatViaGatewayMock.mockImplementation(async function* () {+ // Some libraries reject with non-Error sentinels (e.g. plain strings).+ // eslint-disable-next-line @typescript-eslint/only-throw-error+ throw "string-reason";+ yield { kind: "delta", text: "" }; // keep async generator type happy+ });++ await runTaskKickoffServerSide(makeTask());++ expect(updateTaskMock).toHaveBeenCalledWith(+ "task-1",+ expect.objectContaining({+ status: "failed",+ error_message: "string-reason",+ }),+ );+ errSpy.mockRestore();+ });++ it("skips orchestration entirely when the buffered text is blank", async () => {+ streamChatViaGatewayMock.mockImplementation(() =>+ eventStream([+ { kind: "delta", text: " " },+ { kind: "delta", text: "\n\n" },+ ]),+ );+ await runTaskKickoffServerSide(makeTask());+ expect(processOrchestrationBlocksMock).not.toHaveBeenCalled();+ expect(updateTaskMock).not.toHaveBeenCalled();+ });++ it("logs but does not rethrow when orchestration processing itself fails", async () => {+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ streamChatViaGatewayMock.mockImplementation(() =>+ eventStream([{ kind: "delta", text: "hello" }]),+ );+ processOrchestrationBlocksMock.mockRejectedValue(new Error("parse boom"));++ await expect(runTaskKickoffServerSide(makeTask())).resolves.toBeUndefined();+ expect(errSpy).toHaveBeenCalledWith(+ expect.stringContaining("orchestration processing failed"),+ expect.any(Error),+ );+ errSpy.mockRestore();+ });++ it("keeps the existing thread_id when the task already has one (no lazy mint)", async () => {+ streamChatViaGatewayMock.mockImplementation(() => eventStream([]));+ await runTaskKickoffServerSide(makeTask({ thread_id: "thread-existing" }));+ expect(setTaskThreadIfMissingMock).not.toHaveBeenCalled();+ expect(streamChatViaGatewayMock).toHaveBeenCalledWith(+ expect.objectContaining({ sessionId: "thread-existing" }),+ );+ });+});diff --git a/src/server/orchestration/task-kickoff.test.ts b/src/server/orchestration/task-kickoff.test.tsnew file mode 100644index 00000000..1ad9f496--- /dev/null+++ b/src/server/orchestration/task-kickoff.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from "vitest";++import type { Task } from "@/types";++import { buildTaskKickoffMessage } from "./task-kickoff";++function makeTask(overrides: Partial<Task> = {}): Task {+ return {+ id: "task-123",+ display_id: "demo-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ title: "Install conversion tracking",+ brief: "Add the Google Ads conversion tag to /thanks.",+ success_criteria: "Tag fires on /thanks and a test conv lands in Google Ads.",+ deadline_iso: null,+ status: "running",+ result_json: null,+ error_message: null,+ thread_id: "thread-1",+ assigner_agent_id: "demo-cmo",+ created_at: "2026-05-19T00:00:00Z",+ updated_at: "2026-05-19T00:00:00Z",+ ...overrides,+ };+}++describe("buildTaskKickoffMessage", () => {+ it("opens with the (task assignment) header so the agent recognizes the system-injected turn", () => {+ const msg = buildTaskKickoffMessage(makeTask());+ expect(msg.startsWith("(task assignment)")).toBe(true);+ });++ it("includes the canonical task fields in a stable order", () => {+ const msg = buildTaskKickoffMessage(makeTask());+ // Each piece appears, and the brief comes before success criteria.+ expect(msg).toContain("Task ID: task-123");+ expect(msg).toContain("Title: Install conversion tracking");+ expect(msg).toContain("Brief:");+ expect(msg).toContain("Add the Google Ads conversion tag to /thanks.");+ expect(msg).toContain("Success criteria:");+ expect(msg).toContain(+ "Tag fires on /thanks and a test conv lands in Google Ads.",+ );+ expect(msg.indexOf("Brief:")).toBeLessThan(msg.indexOf("Success criteria:"));+ });++ it("falls back to '(untitled)' when title is null", () => {+ const msg = buildTaskKickoffMessage(makeTask({ title: null }));+ expect(msg).toContain("Title: (untitled)");+ });++ it("omits the Success criteria section entirely when success_criteria is null", () => {+ const msg = buildTaskKickoffMessage(+ makeTask({ success_criteria: null }),+ );+ expect(msg).not.toContain("Success criteria:");+ // Still has the trailing instructions block.+ expect(msg).toContain("Acknowledge this task");+ });++ it("teaches the agent the <task_status> done emission contract with the right task_id", () => {+ const msg = buildTaskKickoffMessage(makeTask({ id: "task-xyz" }));+ expect(msg).toContain("<task_status>");+ expect(msg).toContain("task_id: task-xyz");+ expect(msg).toContain("status: done");+ expect(msg).toContain("</task_status>");+ });++ it("mentions the blocked/ask_user/request_approval escape hatches so agents know how to bail", () => {+ const msg = buildTaskKickoffMessage(makeTask());+ expect(msg).toMatch(/status:\s*blocked/);+ expect(msg).toContain("<ask_user>");+ expect(msg).toContain("<add_comment>");+ expect(msg).toContain("<request_approval>");+ });++ it("tells the agent to actually use its tools, not just describe", () => {+ const msg = buildTaskKickoffMessage(makeTask());+ expect(msg).toContain("Use your tools");+ expect(msg).toContain("don't just describe what you'd do");+ });++ it("returns a multi-line string (joined with \\n, not \\r\\n)", () => {+ const msg = buildTaskKickoffMessage(makeTask());+ expect(msg).not.toContain("\r");+ expect(msg.split("\n").length).toBeGreaterThan(10);+ });++ it("preserves multi-line brief content verbatim", () => {+ const brief = "Step 1: import GA4.\nStep 2: map conv to lead.\nStep 3: verify.";+ const msg = buildTaskKickoffMessage(makeTask({ brief }));+ expect(msg).toContain(brief);+ });+});diff --git a/src/server/secrets/cipher.test.ts b/src/server/secrets/cipher.test.tsnew file mode 100644index 00000000..6dbdb8a0--- /dev/null+++ b/src/server/secrets/cipher.test.ts@@ -0,0 +1,111 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const KEY_A = Buffer.alloc(32, 0xab);+const KEY_B = Buffer.alloc(32, 0xcd);++const getMasterKeyMock = vi.fn();++vi.mock("./master-key", () => ({+ getMasterKey: () => getMasterKeyMock(),+}));++import { decrypt, encrypt } from "./cipher";++describe("cipher", () => {+ beforeEach(() => {+ getMasterKeyMock.mockReset();+ getMasterKeyMock.mockResolvedValue(KEY_A);+ });++ describe("encrypt", () => {+ it("returns a base64 string distinct from plaintext", async () => {+ const out = await encrypt("hello world");+ expect(typeof out).toBe("string");+ expect(out).not.toContain("hello world");+ const buf = Buffer.from(out, "base64");+ // 12-byte IV + ciphertext("hello world" = 11 bytes) + 16-byte tag+ expect(buf.length).toBe(12 + 11 + 16);+ });++ it("produces different output for the same plaintext on each call (random IV)", async () => {+ const a = await encrypt("same input");+ const b = await encrypt("same input");+ expect(a).not.toBe(b);+ });++ it("handles empty string plaintext", async () => {+ const out = await encrypt("");+ const buf = Buffer.from(out, "base64");+ expect(buf.length).toBe(12 + 0 + 16);+ const round = await decrypt(out);+ expect(round).toBe("");+ });++ it("handles unicode plaintext", async () => {+ const text = "héllo 世界 🚀";+ const out = await encrypt(text);+ const round = await decrypt(out);+ expect(round).toBe(text);+ });+ });++ describe("decrypt — round trip", () => {+ it("round-trips plaintext through encrypt → decrypt", async () => {+ const text = "the quick brown fox jumps over the lazy dog";+ const blob = await encrypt(text);+ const round = await decrypt(blob);+ expect(round).toBe(text);+ });++ it("round-trips longer plaintext", async () => {+ const text = "x".repeat(10_000);+ const blob = await encrypt(text);+ const round = await decrypt(blob);+ expect(round).toBe(text);+ });+ });++ describe("decrypt — failure modes", () => {+ it("throws on a blob shorter than IV + tag", async () => {+ const tooShort = Buffer.alloc(12 + 16 - 1).toString("base64");+ await expect(decrypt(tooShort)).rejects.toThrow(/malformed/);+ });++ it("throws on an empty blob", async () => {+ await expect(decrypt("")).rejects.toThrow(/malformed/);+ });++ it("throws when decrypting with the wrong key", async () => {+ const blob = await encrypt("secret payload");+ getMasterKeyMock.mockResolvedValue(KEY_B);+ await expect(decrypt(blob)).rejects.toThrow();+ });++ it("throws when the auth tag has been tampered with", async () => {+ const blob = await encrypt("secret payload");+ const buf = Buffer.from(blob, "base64");+ // Flip a bit in the tag (last 16 bytes).+ buf[buf.length - 1] = buf[buf.length - 1]! ^ 0x01;+ const tampered = buf.toString("base64");+ await expect(decrypt(tampered)).rejects.toThrow();+ });++ it("throws when the ciphertext has been tampered with", async () => {+ const blob = await encrypt("secret payload");+ const buf = Buffer.from(blob, "base64");+ // Flip a bit somewhere in the ciphertext region (after IV, before tag).+ const idx = 12 + 2;+ buf[idx] = buf[idx]! ^ 0x01;+ const tampered = buf.toString("base64");+ await expect(decrypt(tampered)).rejects.toThrow();+ });++ it("throws when the IV has been tampered with", async () => {+ const blob = await encrypt("secret payload");+ const buf = Buffer.from(blob, "base64");+ buf[0] = buf[0]! ^ 0x01;+ const tampered = buf.toString("base64");+ await expect(decrypt(tampered)).rejects.toThrow();+ });+ });+});diff --git a/src/server/secrets/master-key.test.ts b/src/server/secrets/master-key.test.tsnew file mode 100644index 00000000..32a534f6--- /dev/null+++ b/src/server/secrets/master-key.test.ts@@ -0,0 +1,135 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++async function loadFreshMasterKey() {+ vi.resetModules();+ return await import("./master-key");+}++describe("getMasterKey", () => {+ beforeEach(() => {+ vi.resetModules();+ });++ afterEach(() => {+ vi.doUnmock("keytar");+ });++ it("returns existing key from keychain as a 32-byte Buffer", async () => {+ const existing = Buffer.alloc(32, 7).toString("base64");+ const getPassword = vi.fn().mockResolvedValueOnce(existing);+ const setPassword = vi.fn();+ vi.doMock("keytar", () => ({+ default: { getPassword, setPassword },+ getPassword,+ setPassword,+ }));++ const mod = await loadFreshMasterKey();+ const key = await mod.getMasterKey();++ expect(Buffer.isBuffer(key)).toBe(true);+ expect(key.length).toBe(32);+ expect(key.equals(Buffer.alloc(32, 7))).toBe(true);+ expect(getPassword).toHaveBeenCalledWith("notfair-cmo", "master-key");+ expect(setPassword).not.toHaveBeenCalled();+ });++ it("generates and persists a fresh 32-byte key when none stored", async () => {+ const getPassword = vi.fn().mockResolvedValueOnce(null);+ const setPassword = vi.fn().mockResolvedValueOnce(undefined);+ vi.doMock("keytar", () => ({+ default: { getPassword, setPassword },+ getPassword,+ setPassword,+ }));++ const mod = await loadFreshMasterKey();+ const key = await mod.getMasterKey();++ expect(key.length).toBe(32);+ expect(setPassword).toHaveBeenCalledTimes(1);+ const [service, account, stored] = setPassword.mock.calls[0]!;+ expect(service).toBe("notfair-cmo");+ expect(account).toBe("master-key");+ expect(typeof stored).toBe("string");+ const decoded = Buffer.from(stored as string, "base64");+ expect(decoded.length).toBe(32);+ expect(key.equals(decoded)).toBe(true);+ });++ it("caches the key across calls — only reads keychain once", async () => {+ const getPassword = vi+ .fn()+ .mockResolvedValueOnce(Buffer.alloc(32, 1).toString("base64"));+ const setPassword = vi.fn();+ vi.doMock("keytar", () => ({+ default: { getPassword, setPassword },+ getPassword,+ setPassword,+ }));++ const mod = await loadFreshMasterKey();+ const k1 = await mod.getMasterKey();+ const k2 = await mod.getMasterKey();++ expect(k1).toBe(k2);+ expect(getPassword).toHaveBeenCalledTimes(1);+ });++ it("throws when keytar import fails", async () => {+ vi.doMock("keytar", () => {+ throw new Error("module not installed");+ });++ const mod = await loadFreshMasterKey();+ await expect(mod.getMasterKey()).rejects.toThrow(+ /OS keychain \(keytar\) not available/,+ );+ });++ it("throws a follow-up error on subsequent calls after load failure", async () => {+ vi.doMock("keytar", () => {+ throw new Error("module not installed");+ });++ const mod = await loadFreshMasterKey();+ await expect(mod.getMasterKey()).rejects.toThrow(+ /OS keychain \(keytar\) not available/,+ );+ await expect(mod.getMasterKey()).rejects.toThrow(+ /Master key unavailable \(keytar not loadable\)/,+ );+ });++ it("uses the default export when keytar exposes one", async () => {+ const getPassword = vi+ .fn()+ .mockResolvedValueOnce(Buffer.alloc(32, 9).toString("base64"));+ const setPassword = vi.fn();+ vi.doMock("keytar", () => ({+ default: { getPassword, setPassword },+ }));++ const mod = await loadFreshMasterKey();+ const key = await mod.getMasterKey();+ expect(key.equals(Buffer.alloc(32, 9))).toBe(true);+ expect(getPassword).toHaveBeenCalledWith("notfair-cmo", "master-key");+ });++ it("falls back to namespace export when default is null", async () => {+ const getPassword = vi+ .fn()+ .mockResolvedValueOnce(Buffer.alloc(32, 3).toString("base64"));+ const setPassword = vi.fn();+ vi.doMock("keytar", () => ({+ default: null,+ getPassword,+ setPassword,+ }));++ const mod = await loadFreshMasterKey();+ const key = await mod.getMasterKey();+ expect(key.equals(Buffer.alloc(32, 3))).toBe(true);+ expect(getPassword).toHaveBeenCalledWith("notfair-cmo", "master-key");+ });+});diff --git a/vitest.config.ts b/vitest.config.tsindex f7c1c689..647d7637 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -20,5 +20,24 @@ export default defineConfig({globals: false,include: ["src/**/*.test.ts", "src/**/*.test.tsx"],setupFiles: ["./vitest.setup.ts"],+ coverage: {+ provider: "v8",+ reporter: ["text-summary", "text", "json-summary"],+ include: ["src/**/*.{ts,tsx}"],+ exclude: [+ "src/**/*.test.{ts,tsx}",+ "src/types/**",+ // Server-component pages: data-fetch + render. Better covered by E2E.+ "src/app/**/page.tsx",+ "src/app/**/layout.tsx",+ // shadcn UI primitives: thin wrappers around radix-ui. Testing them+ // tests radix-ui, not our code.+ "src/components/ui/**",+ // Prompt-template strings — covered by the eval harness, not unit tests.+ "src/server/agent-templates.ts",+ // Trivial DOM-resize hook — low value to unit-test in isolation.+ "src/hooks/use-mobile.ts",+ ],+ },},});diff --git a/vitest.setup.ts b/vitest.setup.tsindex f149f27a..c5dee9b0 100644--- a/vitest.setup.ts+++ b/vitest.setup.ts@@ -1 +1,10 @@import "@testing-library/jest-dom/vitest";+import { afterEach } from "vitest";+import { cleanup } from "@testing-library/react";++// vitest 4 disabled globals by default; React Testing Library's auto-cleanup+// hook (which relies on globals like `afterEach`) no longer fires, so two+// tests in the same file end up sharing the same DOM. Run cleanup explicitly.+afterEach(() => {+ cleanup();+});