Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: update ui and add integration tests
Gusc62c87198ee9
diff --git a/Makefile b/Makefileindex d3c3ff3ae..36e9aa1c4 100644--- a/Makefile+++ b/Makefile@@ -1,4 +1,4 @@-.PHONY: setup start stop build test typecheck check daemon cli migrate-up migrate-down db-up db-down+.PHONY: setup start stop build test test-unit test-integration typecheck check daemon cli migrate-up migrate-down db-up db-downsetup: ## First-time setuppnpm install@@ -22,13 +22,19 @@ build: ## Build Next.js + CLIcd src/web && pnpm buildcd src/cli && pnpm build-test: ## Run Vitest+test-unit: ## Run unit tests only (no DB required)pnpm vitest run+test: test-unit test-integration ## Run all tests+typecheck: ## TypeScript type checkpnpm tsc --noEmit -p src/web/tsconfig.jsonpnpm tsc --noEmit -p src/cli/tsconfig.json+test-integration: ## Run integration tests (requires PostgreSQL)+ bash scripts/setup-test-db.sh+ pnpm vitest run --config vitest.integration.config.ts+check: typecheck build test ## CI gatedaemon: ## Start local daemondiff --git a/scripts/setup-test-db.sh b/scripts/setup-test-db.shnew file mode 100755index 000000000..04a70cb83--- /dev/null+++ b/scripts/setup-test-db.sh@@ -0,0 +1,33 @@+#!/usr/bin/env bash+set -euo pipefail++# Idempotent test DB setup: ensures alook_test exists and schema is current.+# Uses docker compose exec to run commands inside the postgres container,+# so no local pg client tools are required.++PGUSER="${PGUSER:-postgres}"+PGPASSWORD="${PGPASSWORD:-postgres}"+PGHOST="${PGHOST:-localhost}"+PGPORT="${PGPORT:-5432}"+TEST_DB="alook_test"++echo "Waiting for PostgreSQL to be ready..."+until docker compose exec postgres pg_isready -U "$PGUSER" -q 2>/dev/null; do+ sleep 1+done+echo "PostgreSQL is ready."++# Create test database if it doesn't exist+if ! docker compose exec postgres psql -U "$PGUSER" -lqt | cut -d \| -f 1 | grep -qw "$TEST_DB"; then+ echo "Creating database $TEST_DB..."+ docker compose exec postgres createdb -U "$PGUSER" "$TEST_DB"+else+ echo "Database $TEST_DB already exists."+fi++# Push schema to test database+echo "Pushing Drizzle schema to $TEST_DB..."+cd src/web && DATABASE_URL="postgres://$PGUSER:$PGPASSWORD@$PGHOST:$PGPORT/$TEST_DB?sslmode=disable" \+ pnpm drizzle-kit push --force++echo "Test database setup complete."diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 83245239d..554a0478f 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -93,7 +93,7 @@ export async function startDaemon(runtimes,});- const runtimeIds = resp.runtimes.map((r) => r.id);+ const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);workspaceStates.push({ workspaceId: ws.id, runtimeIds });for (let i = 0; i < runtimeIds.length; i++) {diff --git a/src/cli/lib/logger.test.ts b/src/cli/lib/logger.test.tsindex 54adb475a..2322bb159 100644--- a/src/cli/lib/logger.test.ts+++ b/src/cli/lib/logger.test.ts@@ -1,8 +1,10 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { Logger } from "./logger.js";-let stdoutSpy: ReturnType<typeof vi.spyOn>;-let stderrSpy: ReturnType<typeof vi.spyOn>;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+let stdoutSpy: any;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+let stderrSpy: any;beforeEach(() => {stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);diff --git a/src/web/app/api/agents/[id]/conversations/route.test.ts b/src/web/app/api/agents/[id]/conversations/route.test.tsindex 73bc73300..142605e82 100644--- a/src/web/app/api/agents/[id]/conversations/route.test.ts+++ b/src/web/app/api/agents/[id]/conversations/route.test.ts@@ -50,7 +50,7 @@ describe("GET /api/agents/[id]/conversations", () => {});it("returns 404 for non-existent agent", async () => {- mockGetAgent.mockResolvedValue(null);+ mockGetAgent.mockResolvedValue(null as any);const { GET } = await import("./route");const res = await GET(new NextRequest("http://localhost/api/agents/nope/conversations"),diff --git a/src/web/app/api/conversations/[id]/messages/route.test.ts b/src/web/app/api/conversations/[id]/messages/route.test.tsindex 1d8e263be..24c9a5bcf 100644--- a/src/web/app/api/conversations/[id]/messages/route.test.ts+++ b/src/web/app/api/conversations/[id]/messages/route.test.ts@@ -57,7 +57,7 @@ describe("POST /api/conversations/[id]/messages", () => {it("sends message and enqueues task, returns 201", async () => {mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1", agentId: "a1" } as any);mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- mockUpdateTitle.mockResolvedValue(null);+ mockUpdateTitle.mockResolvedValue(null as any);const { POST } = await import("./route");const res = await POST(new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {@@ -100,7 +100,7 @@ describe("POST /api/conversations/[id]/messages", () => {it("auto-title does not fail if update returns null (title already set)", async () => {mockGetConv.mockResolvedValue({ id: "c1", workspaceId: "w1", agentId: "a1" } as any);mockCreateMessage.mockResolvedValue({ id: "m1" } as any);- mockUpdateTitle.mockResolvedValue(null); // title already set+ mockUpdateTitle.mockResolvedValue(null as any); // title already setconst { POST } = await import("./route");const res = await POST(new NextRequest("http://localhost/api/conversations/c1/messages?workspace_id=w1", {diff --git a/src/web/app/api/daemon/heartbeat/route.test.ts b/src/web/app/api/daemon/heartbeat/route.test.tsindex cb12cee63..71383a6b9 100644--- a/src/web/app/api/daemon/heartbeat/route.test.ts+++ b/src/web/app/api/daemon/heartbeat/route.test.ts@@ -53,7 +53,7 @@ describe("POST /api/daemon/heartbeat", () => {it("returns 404 when runtime not in caller's workspace", async () => {setupMocks();const { getAgentRuntimeForWorkspace } = await import("@/lib/db/queries/runtime");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null);+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null as any);const { POST } = await import("./route");const res = await POST(makeReq({ runtime_id: "rt-other" }));@@ -63,7 +63,7 @@ describe("POST /api/daemon/heartbeat", () => {it("returns 404 when runtime ID doesn't exist at all", async () => {setupMocks();const { getAgentRuntimeForWorkspace } = await import("@/lib/db/queries/runtime");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null);+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null as any);const { POST } = await import("./route");const res = await POST(makeReq({ runtime_id: "nonexistent" }));@@ -82,7 +82,7 @@ describe("POST /api/daemon/heartbeat", () => {const { getAgentRuntimeForWorkspace, updateAgentRuntimeHeartbeat, markStaleRuntimesOffline } =await import("@/lib/db/queries/runtime");const { failStaleDispatchedTasks } = await import("@/lib/db/queries/task");- vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null);+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null as any);const { POST } = await import("./route");await POST(makeReq({ runtime_id: "rt-other" }));diff --git a/src/web/lib/db/queries/agent.integration.test.ts b/src/web/lib/db/queries/agent.integration.test.tsnew file mode 100644index 000000000..f40a9b7c7--- /dev/null+++ b/src/web/lib/db/queries/agent.integration.test.ts@@ -0,0 +1,71 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+ seedRuntime,+ seedAgent,+ seedConversation,+} from "../test-utils";+import { deleteAgent, getAgent } from "./agent";+import { createTask, getTask } from "./task";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++describe("deleteAgent", () => {+ it("removes agent and its tasks in a transaction", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);+ const conv = await seedConversation(tx, ws.id, agent.id, user.id);++ // Create a task for this agent+ const task = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "orphan check",+ });++ const deleted = await deleteAgent(tx, agent.id, ws.id);+ expect(deleted).not.toBeNull();+ expect(deleted!.id).toBe(agent.id);++ // Agent should be gone+ const fetchedAgent = await getAgent(tx, agent.id);+ expect(fetchedAgent).toBeNull();++ // Task should also be gone (deleted in the transaction)+ const fetchedTask = await getTask(tx, task.id);+ expect(fetchedTask).toBeNull();+ });+ });++ it("returns null for non-matching workspace", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ const ws2 = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ // Try to delete with wrong workspace+ const result = await deleteAgent(tx, agent.id, ws2.id);+ expect(result).toBeNull();++ // Agent should still exist+ const fetched = await getAgent(tx, agent.id);+ expect(fetched).not.toBeNull();+ });+ });+});diff --git a/src/web/lib/db/queries/conversation.integration.test.ts b/src/web/lib/db/queries/conversation.integration.test.tsnew file mode 100644index 000000000..d8fb2f030--- /dev/null+++ b/src/web/lib/db/queries/conversation.integration.test.ts@@ -0,0 +1,297 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+ seedRuntime,+ seedAgent,+ seedConversation,+} from "../test-utils";+import {+ createConversation,+ getConversation,+ listConversationsByAgent,+ updateConversationTitle,+ deleteConversation,+} from "./conversation";+import { createMessage } from "./message";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++describe("listConversationsByAgent", () => {+ it("returns correct message_count for conversations with messages", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, {+ workspaceId: ws.id,+ agentId: agent.id,+ userId: user.id,+ title: "",+ });++ await createMessage(tx, { conversationId: conv.id, role: "user", content: "hello" });+ await createMessage(tx, { conversationId: conv.id, role: "assistant", content: "hi" });+ await createMessage(tx, { conversationId: conv.id, role: "user", content: "bye" });++ const result = await listConversationsByAgent(tx, ws.id, user.id, agent.id);+ expect(result).toHaveLength(1);+ expect(result[0].messageCount).toBe(3);+ });+ });++ it("returns 0 message_count for empty conversations", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ await createConversation(tx, {+ workspaceId: ws.id,+ agentId: agent.id,+ userId: user.id,+ title: "",+ });++ const result = await listConversationsByAgent(tx, ws.id, user.id, agent.id);+ expect(result).toHaveLength(1);+ expect(result[0].messageCount).toBe(0);+ });+ });++ it("filters by agent, workspace, and user correctly", async () => {+ await withTestTransaction(db, async (tx) => {+ const user1 = await seedUser(tx);+ const user2 = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user1.id);+ await seedMember(tx, ws.id, user2.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent1 = await seedAgent(tx, ws.id, rt.id, user1.id);+ const agent2 = await seedAgent(tx, ws.id, rt.id, user2.id);++ // Create conversations for different agents/users+ await createConversation(tx, { workspaceId: ws.id, agentId: agent1.id, userId: user1.id, title: "" });+ await createConversation(tx, { workspaceId: ws.id, agentId: agent2.id, userId: user1.id, title: "" });+ await createConversation(tx, { workspaceId: ws.id, agentId: agent1.id, userId: user2.id, title: "" });++ const result = await listConversationsByAgent(tx, ws.id, user1.id, agent1.id);+ expect(result).toHaveLength(1);+ });+ });++ it("orders by newest first", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ // Insert with explicit createdAt since now() is fixed within a transaction+ const earlier = new Date("2024-01-01T00:00:00Z");+ const later = new Date("2024-01-02T00:00:00Z");++ const conv1 = await seedConversation(tx, ws.id, agent.id, user.id, { title: "first", createdAt: earlier });+ const conv2 = await seedConversation(tx, ws.id, agent.id, user.id, { title: "second", createdAt: later });++ const result = await listConversationsByAgent(tx, ws.id, user.id, agent.id);+ expect(result).toHaveLength(2);+ // Newest first+ expect(result[0].id).toBe(conv2.id);+ expect(result[1].id).toBe(conv1.id);+ });+ });++ it("returns empty array for non-existent agent", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);++ const result = await listConversationsByAgent(tx, ws.id, user.id, "00000000-0000-0000-0000-000000000000");+ expect(result).toEqual([]);+ });+ });+});++describe("updateConversationTitle", () => {+ it("sets title when current title is empty", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "" });++ const updated = await updateConversationTitle(tx, conv.id, "New Title");+ expect(updated).not.toBeNull();+ expect(updated!.title).toBe("New Title");+ });+ });++ it("returns null when title is already non-empty (no overwrite)", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "Existing" });++ const result = await updateConversationTitle(tx, conv.id, "Overwrite Attempt");+ expect(result).toBeNull();++ // Verify title unchanged+ const fetched = await getConversation(tx, conv.id);+ expect(fetched!.title).toBe("Existing");+ });+ });++ it("concurrent calls — only first one wins", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "" });++ const [r1, r2] = await Promise.all([+ updateConversationTitle(tx, conv.id, "Title A"),+ updateConversationTitle(tx, conv.id, "Title B"),+ ]);++ // Exactly one should succeed+ const successes = [r1, r2].filter((r) => r !== null);+ expect(successes).toHaveLength(1);++ const fetched = await getConversation(tx, conv.id);+ expect(["Title A", "Title B"]).toContain(fetched!.title);+ });+ });+});++describe("deleteConversation", () => {+ it("removes the conversation row", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "" });++ const deleted = await deleteConversation(tx, conv.id);+ expect(deleted).not.toBeNull();+ expect(deleted!.id).toBe(conv.id);++ const fetched = await getConversation(tx, conv.id);+ expect(fetched).toBeNull();+ });+ });++ it("returns null for non-existent ID", async () => {+ await withTestTransaction(db, async (tx) => {+ const result = await deleteConversation(tx, "00000000-0000-0000-0000-000000000000");+ expect(result).toBeNull();+ });+ });+});++describe("createConversation", () => {+ it("inserts and returns with generated UUID", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, {+ workspaceId: ws.id,+ agentId: agent.id,+ userId: user.id,+ title: "My Conversation",+ });++ expect(conv.id).toBeDefined();+ expect(conv.title).toBe("My Conversation");+ expect(conv.workspaceId).toBe(ws.id);+ expect(conv.agentId).toBe(agent.id);+ });+ });+});++describe("getConversation", () => {+ it("returns row by ID", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "Test" });++ const fetched = await getConversation(tx, conv.id);+ expect(fetched).not.toBeNull();+ expect(fetched!.id).toBe(conv.id);+ expect(fetched!.title).toBe("Test");+ });+ });++ it("returns null for non-existent ID", async () => {+ await withTestTransaction(db, async (tx) => {+ const result = await getConversation(tx, "00000000-0000-0000-0000-000000000000");+ expect(result).toBeNull();+ });+ });+});++describe("transaction rollback isolation", () => {+ it("data inserted in one test is not visible in the next test", async () => {+ let insertedId: string | undefined;++ // First transaction: insert a conversation+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);++ const conv = await createConversation(tx, { workspaceId: ws.id, agentId: agent.id, userId: user.id, title: "ephemeral" });+ insertedId = conv.id;++ // Visible inside the transaction+ const fetched = await getConversation(tx, conv.id);+ expect(fetched).not.toBeNull();+ });++ // Second transaction: that ID should not exist+ await withTestTransaction(db, async (tx) => {+ const fetched = await getConversation(tx, insertedId!);+ expect(fetched).toBeNull();+ });+ });+});diff --git a/src/web/lib/db/queries/machine-token.integration.test.ts b/src/web/lib/db/queries/machine-token.integration.test.tsnew file mode 100644index 000000000..3b2f157bf--- /dev/null+++ b/src/web/lib/db/queries/machine-token.integration.test.ts@@ -0,0 +1,48 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+} from "../test-utils";+import { createMachineToken, getMachineTokenByHash } from "./machine-token";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++describe("getMachineTokenByHash", () => {+ it("returns token with joined userEmail", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx, { email: "[email protected]" });+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);++ const token = await createMachineToken(tx, {+ userId: user.id,+ workspaceId: ws.id,+ tokenHash: "hash-abc-123",+ name: "My Token",+ });++ const result = await getMachineTokenByHash(tx, "hash-abc-123");+ expect(result).not.toBeNull();+ expect(result!.id).toBe(token.id);+ expect(result!.userEmail).toBe("[email protected]");+ expect(result!.name).toBe("My Token");+ expect(result!.workspaceId).toBe(ws.id);+ });+ });++ it("returns null for non-existent hash", async () => {+ await withTestTransaction(db, async (tx) => {+ const result = await getMachineTokenByHash(tx, "nonexistent-hash");+ expect(result).toBeNull();+ });+ });+});diff --git a/src/web/lib/db/queries/runtime.integration.test.ts b/src/web/lib/db/queries/runtime.integration.test.tsnew file mode 100644index 000000000..aa3320f53--- /dev/null+++ b/src/web/lib/db/queries/runtime.integration.test.ts@@ -0,0 +1,218 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+ seedRuntime,+ seedAgent,+ seedConversation,+} from "../test-utils";+import {+ upsertAgentRuntime,+ getAgentRuntime,+ deleteRuntimesByDaemonId,+ markStaleRuntimesOffline,+} from "./runtime";+import { getAgent } from "./agent";+import { createTask, getTask } from "./task";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++describe("upsertAgentRuntime", () => {+ it("inserts new runtime on first call", async () => {+ await withTestTransaction(db, async (tx) => {+ const ws = await seedWorkspace(tx);++ const rt = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "daemon-1",+ name: "My Runtime",+ runtimeMode: "local",+ provider: "claude",+ status: "online",+ deviceInfo: "macOS",+ });++ expect(rt.id).toBeDefined();+ expect(rt.name).toBe("My Runtime");+ expect(rt.status).toBe("online");+ expect(rt.provider).toBe("claude");+ });+ });++ it("updates existing runtime on conflict (same workspace+daemon+provider)", async () => {+ await withTestTransaction(db, async (tx) => {+ const ws = await seedWorkspace(tx);++ const rt1 = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "daemon-1",+ name: "Original",+ runtimeMode: "local",+ provider: "claude",+ status: "online",+ deviceInfo: "macOS",+ });++ const rt2 = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "daemon-1",+ name: "Updated",+ runtimeMode: "remote",+ provider: "claude",+ status: "offline",+ deviceInfo: "Linux",+ });++ // Same ID (upsert, not new row)+ expect(rt2.id).toBe(rt1.id);+ // Fields updated+ expect(rt2.name).toBe("Updated");+ expect(rt2.status).toBe("offline");+ expect(rt2.deviceInfo).toBe("Linux");+ });+ });+});++describe("deleteRuntimesByDaemonId", () => {+ it("nulls agent.runtimeId, deletes tasks, deletes runtimes", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);+ const conv = await seedConversation(tx, ws.id, agent.id, user.id);++ const task = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "will be deleted",+ });++ await deleteRuntimesByDaemonId(tx, rt.daemonId, ws.id);++ // Runtime should be gone+ const fetchedRt = await getAgentRuntime(tx, rt.id);+ expect(fetchedRt).toBeNull();++ // Agent should still exist but runtimeId nulled+ const fetchedAgent = await getAgent(tx, agent.id);+ expect(fetchedAgent).not.toBeNull();+ expect(fetchedAgent!.runtimeId).toBeNull();++ // Task should be gone+ const fetchedTask = await getTask(tx, task.id);+ expect(fetchedTask).toBeNull();+ });+ });++ it("is a no-op when no runtimes match", async () => {+ await withTestTransaction(db, async (tx) => {+ const ws = await seedWorkspace(tx);++ // Should not throw+ await deleteRuntimesByDaemonId(tx, "nonexistent-daemon", ws.id);+ });+ });+});++describe("markStaleRuntimesOffline", () => {+ it("marks online runtimes with old lastSeenAt as offline", async () => {+ await withTestTransaction(db, async (tx) => {+ const ws = await seedWorkspace(tx);++ // Create a runtime that was last seen 2 minutes ago+ const rt = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "stale-daemon",+ name: "Stale",+ runtimeMode: "local",+ provider: "claude",+ status: "online",+ deviceInfo: "macOS",+ });++ // Manually backdate lastSeenAt by updating it+ // We need to use the raw DB to set an old timestamp+ const { agentRuntime } = await import("../schema");+ const { eq } = await import("drizzle-orm");+ const oldDate = new Date(Date.now() - 120 * 1000); // 2 minutes ago+ await (tx as any).update(agentRuntime).set({ lastSeenAt: oldDate }).where(eq(agentRuntime.id, rt.id));++ await markStaleRuntimesOffline(tx, ws.id);++ const fetched = await getAgentRuntime(tx, rt.id);+ expect(fetched!.status).toBe("offline");+ });+ });++ it("marks online runtimes with null lastSeenAt as offline", async () => {+ await withTestTransaction(db, async (tx) => {+ const ws = await seedWorkspace(tx);++ const rt = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "null-heartbeat",+ name: "No Heartbeat",+ runtimeMode: "local",+ provider: "claude",+ status: "online",+ deviceInfo: "macOS",+ });++ // Set lastSeenAt to null+ const { agentRuntime } = await import("../schema");+ const { eq } = await import("drizzle-orm");+ await (tx as any).update(agentRuntime).set({ lastSeenAt: null }).where(eq(agentRuntime.id, rt.id));++ await markStaleRuntimesOffline(tx, ws.id);++ const fetched = await getAgentRuntime(tx, rt.id);+ expect(fetched!.status).toBe("offline");+ });+ });++ it("does not affect recently seen or already offline runtimes", async () => {+ await withTestTransaction(db, async (tx) => {+ const ws = await seedWorkspace(tx);++ // Recently seen online runtime+ const rtOnline = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "fresh-daemon",+ name: "Fresh",+ runtimeMode: "local",+ provider: "claude",+ status: "online",+ deviceInfo: "macOS",+ });++ // Already offline runtime+ const rtOffline = await upsertAgentRuntime(tx, {+ workspaceId: ws.id,+ daemonId: "offline-daemon",+ name: "Offline",+ runtimeMode: "local",+ provider: "claude",+ status: "offline",+ deviceInfo: "macOS",+ });++ await markStaleRuntimesOffline(tx, ws.id);++ const fetchedOnline = await getAgentRuntime(tx, rtOnline.id);+ expect(fetchedOnline!.status).toBe("online"); // still online (recent heartbeat)++ const fetchedOffline = await getAgentRuntime(tx, rtOffline.id);+ expect(fetchedOffline!.status).toBe("offline"); // unchanged+ });+ });+});diff --git a/src/web/lib/db/queries/task-extended.integration.test.ts b/src/web/lib/db/queries/task-extended.integration.test.tsnew file mode 100644index 000000000..27ce71b91--- /dev/null+++ b/src/web/lib/db/queries/task-extended.integration.test.ts@@ -0,0 +1,269 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+ seedRuntime,+ seedAgent,+ seedConversation,+} from "../test-utils";+import {+ createTask,+ claimTask,+ startTask,+ completeTask,+ failTask,+ cancelTask,+ failStaleDispatchedTasks,+ getLastTaskSession,+ listPendingTasksByRuntime,+} from "./task";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++async function seedFullChain(tx: any) {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);+ const conv = await seedConversation(tx, ws.id, agent.id, user.id);+ return { user, ws, rt, agent, conv };+}++describe("claimTask", () => {+ it("claims the highest-priority queued task", async () => {+ await withTestTransaction(db, async (tx) => {+ const { user, ws, rt, agent, conv } = await seedFullChain(tx);+ const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);+ const conv3 = await seedConversation(tx, ws.id, agent.id, user.id);++ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "low priority", priority: 1,+ });+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv2.id, prompt: "high priority", priority: 10,+ });+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv3.id, prompt: "medium priority", priority: 5,+ });++ const claimed = await claimTask(tx, agent.id);+ expect(claimed).not.toBeNull();+ expect(claimed!.prompt).toBe("high priority");+ expect(claimed!.status).toBe("dispatched");+ });+ });++ it("skips conversations that already have dispatched/running tasks", async () => {+ await withTestTransaction(db, async (tx) => {+ const { user, ws, rt, agent, conv } = await seedFullChain(tx);+ const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);++ // Create and claim task in conv (now dispatched)+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "already active",+ });+ await claimTask(tx, agent.id);++ // Create queued task in conv2+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv2.id, prompt: "should be claimed",+ });++ const claimed = await claimTask(tx, agent.id);+ expect(claimed).not.toBeNull();+ expect(claimed!.prompt).toBe("should be claimed");+ });+ });++ it("returns null when no queued tasks exist", async () => {+ await withTestTransaction(db, async (tx) => {+ const { agent } = await seedFullChain(tx);+ const result = await claimTask(tx, agent.id);+ expect(result).toBeNull();+ });+ });+});++describe("failTask", () => {+ it("transitions dispatched/running task to failed with error message", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "will fail",+ });++ const claimed = await claimTask(tx, agent.id);+ const failed = await failTask(tx, claimed!.id, "something broke");+ expect(failed).not.toBeNull();+ expect(failed!.status).toBe("failed");+ expect(failed!.error).toBe("something broke");+ expect(failed!.completedAt).not.toBeNull();+ });+ });++ it("returns null for queued/completed tasks (wrong state)", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ const task = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "queued task",+ });++ // Can't fail a queued task (must be dispatched or running)+ const result = await failTask(tx, task.id, "nope");+ expect(result).toBeNull();+ });+ });+});++describe("cancelTask", () => {+ it("transitions queued/dispatched/running task to cancelled", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ const task = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "cancel me",+ });++ const cancelled = await cancelTask(tx, task.id);+ expect(cancelled).not.toBeNull();+ expect(cancelled!.status).toBe("cancelled");+ expect(cancelled!.completedAt).not.toBeNull();+ });+ });++ it("returns null for already completed/failed tasks", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "will complete",+ });++ const claimed = await claimTask(tx, agent.id);+ await startTask(tx, claimed!.id);+ await completeTask(tx, claimed!.id, { result: {}, sessionId: null, workDir: null });++ const result = await cancelTask(tx, claimed!.id);+ expect(result).toBeNull();+ });+ });+});++describe("failStaleDispatchedTasks", () => {+ it("fails tasks dispatched more than N seconds ago", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "stale task",+ });++ // Claim to get it dispatched+ const claimed = await claimTask(tx, agent.id);+ expect(claimed).not.toBeNull();++ // Use a very short staleSeconds (0) so the just-dispatched task is already stale+ const failed = await failStaleDispatchedTasks(tx, 0);+ expect(failed.length).toBe(1);+ expect(failed[0].agentId).toBe(agent.id);+ });+ });++ it("does not fail recently dispatched tasks", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "fresh task",+ });++ await claimTask(tx, agent.id);++ // Use a long staleSeconds so nothing is stale+ const failed = await failStaleDispatchedTasks(tx, 9999);+ expect(failed).toHaveLength(0);+ });+ });+});++describe("getLastTaskSession", () => {+ it("returns sessionId/workDir from most recent completed task", async () => {+ await withTestTransaction(db, async (tx) => {+ const { user, ws, rt, agent, conv } = await seedFullChain(tx);++ // Create, claim, start, complete a task with session info+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "task with session",+ });+ const claimed = await claimTask(tx, agent.id);+ await startTask(tx, claimed!.id);+ await completeTask(tx, claimed!.id, {+ result: { ok: true },+ sessionId: "sess-123",+ workDir: "/tmp/work",+ });++ const session = await getLastTaskSession(tx, agent.id, conv.id);+ expect(session).not.toBeNull();+ expect(session!.sessionId).toBe("sess-123");+ expect(session!.workDir).toBe("/tmp/work");+ });+ });++ it("returns null when no completed tasks with sessionId exist", async () => {+ await withTestTransaction(db, async (tx) => {+ const { agent, conv } = await seedFullChain(tx);++ const session = await getLastTaskSession(tx, agent.id, conv.id);+ expect(session).toBeNull();+ });+ });+});++describe("listPendingTasksByRuntime", () => {+ it("returns queued/dispatched tasks ordered by priority desc, createdAt asc", async () => {+ await withTestTransaction(db, async (tx) => {+ const { user, ws, rt, agent, conv } = await seedFullChain(tx);+ const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);+ const conv3 = await seedConversation(tx, ws.id, agent.id, user.id);++ const t1 = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "low", priority: 1,+ });+ const t2 = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv2.id, prompt: "high", priority: 10,+ });+ const t3 = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv3.id, prompt: "medium", priority: 5,+ });++ const pending = await listPendingTasksByRuntime(tx, rt.id);+ expect(pending).toHaveLength(3);+ // Ordered by priority desc+ expect(pending[0].id).toBe(t2.id);+ expect(pending[1].id).toBe(t3.id);+ expect(pending[2].id).toBe(t1.id);+ });+ });+});diff --git a/src/web/lib/db/queries/task.integration.test.ts b/src/web/lib/db/queries/task.integration.test.tsnew file mode 100644index 000000000..91e6f25ec--- /dev/null+++ b/src/web/lib/db/queries/task.integration.test.ts@@ -0,0 +1,251 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+ seedRuntime,+ seedAgent,+ seedConversation,+} from "../test-utils";+import {+ createTask,+ getTask,+ getTaskStatus,+ deleteTasksByConversation,+ hasPendingTaskForConversation,+ countRunningTasks,+ claimTask,+ startTask,+ completeTask,+} from "./task";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++/** Shared helper: seeds the full FK chain and returns all entities. */+async function seedFullChain(tx: Parameters<Parameters<typeof withTestTransaction>[1]>[0]) {+ const user = await seedUser(tx);+ const ws = await seedWorkspace(tx);+ await seedMember(tx, ws.id, user.id);+ const rt = await seedRuntime(tx, ws.id);+ const agent = await seedAgent(tx, ws.id, rt.id, user.id);+ const conv = await seedConversation(tx, ws.id, agent.id, user.id);+ return { user, ws, rt, agent, conv };+}++describe("createTask", () => {+ it("inserts task with correct fields", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);++ const task = await createTask(tx, {+ agentId: agent.id,+ runtimeId: rt.id,+ workspaceId: ws.id,+ conversationId: conv.id,+ prompt: "Do the thing",+ priority: 5,+ });++ expect(task.id).toBeDefined();+ expect(task.prompt).toBe("Do the thing");+ expect(task.priority).toBe(5);+ expect(task.status).toBe("queued");+ expect(task.agentId).toBe(agent.id);+ expect(task.conversationId).toBe(conv.id);+ });+ });+});++describe("getTask", () => {+ it("returns task by ID", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ const task = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "test",+ });++ const fetched = await getTask(tx, task.id);+ expect(fetched).not.toBeNull();+ expect(fetched!.id).toBe(task.id);+ });+ });++ it("returns null for non-existent ID", async () => {+ await withTestTransaction(db, async (tx) => {+ const result = await getTask(tx, "00000000-0000-0000-0000-000000000000");+ expect(result).toBeNull();+ });+ });+});++describe("getTaskStatus", () => {+ it("returns status of existing task", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);+ const task = await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "test",+ });++ const status = await getTaskStatus(tx, task.id);+ expect(status).toBe("queued");+ });+ });++ it("returns null for non-existent ID", async () => {+ await withTestTransaction(db, async (tx) => {+ const status = await getTaskStatus(tx, "00000000-0000-0000-0000-000000000000");+ expect(status).toBeNull();+ });+ });+});++describe("deleteTasksByConversation", () => {+ it("removes all tasks for a conversation", async () => {+ await withTestTransaction(db, async (tx) => {+ const { user, ws, rt, agent, conv } = await seedFullChain(tx);++ // Need separate conversations for multiple queued tasks (partial unique index)+ const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);++ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "task 1",+ });+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv2.id, prompt: "task 2",+ });++ const deleted = await deleteTasksByConversation(tx, conv.id);+ expect(deleted).toHaveLength(1);++ // conv2 task still exists+ const pending = await hasPendingTaskForConversation(tx, conv2.id);+ expect(pending).toBe(true);+ });+ });++ it("returns empty array when no tasks exist", async () => {+ await withTestTransaction(db, async (tx) => {+ const { conv } = await seedFullChain(tx);+ const deleted = await deleteTasksByConversation(tx, conv.id);+ expect(deleted).toEqual([]);+ });+ });+});++describe("hasPendingTaskForConversation", () => {+ it("returns true when queued tasks exist", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);++ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "pending task",+ });++ const result = await hasPendingTaskForConversation(tx, conv.id);+ expect(result).toBe(true);+ });+ });++ it("returns false when only completed/failed tasks exist", async () => {+ await withTestTransaction(db, async (tx) => {+ const { ws, rt, agent, conv } = await seedFullChain(tx);++ // Create a task and transition it to completed: queued -> dispatched -> running -> completed+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "done task",+ });++ const claimed = await claimTask(tx, agent.id);+ expect(claimed).not.toBeNull();++ const started = await startTask(tx, claimed!.id);+ expect(started).not.toBeNull();++ const completed = await completeTask(tx, started!.id, {+ result: { output: "done" },+ sessionId: null,+ workDir: null,+ });+ expect(completed).not.toBeNull();++ // Now only a completed task exists — should return false+ const result = await hasPendingTaskForConversation(tx, conv.id);+ expect(result).toBe(false);+ });+ });++ it("returns false when no tasks exist", async () => {+ await withTestTransaction(db, async (tx) => {+ const { conv } = await seedFullChain(tx);+ const result = await hasPendingTaskForConversation(tx, conv.id);+ expect(result).toBe(false);+ });+ });+});++describe("countRunningTasks", () => {+ it("returns correct count of dispatched+running tasks", async () => {+ await withTestTransaction(db, async (tx) => {+ const { user, ws, rt, agent, conv } = await seedFullChain(tx);++ // Create tasks in separate conversations (partial unique index constraint)+ const conv2 = await seedConversation(tx, ws.id, agent.id, user.id);+ const conv3 = await seedConversation(tx, ws.id, agent.id, user.id);++ // Create queued tasks+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv.id, prompt: "task 1",+ });+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv2.id, prompt: "task 2",+ });+ await createTask(tx, {+ agentId: agent.id, runtimeId: rt.id, workspaceId: ws.id,+ conversationId: conv3.id, prompt: "task 3",+ });++ // queued tasks should not be counted+ expect(await countRunningTasks(tx, agent.id)).toBe(0);++ // Claim one task (queued -> dispatched) — dispatched counts+ const claimed1 = await claimTask(tx, agent.id);+ expect(claimed1).not.toBeNull();+ expect(await countRunningTasks(tx, agent.id)).toBe(1);++ // Start it (dispatched -> running) — running also counts+ await startTask(tx, claimed1!.id);+ expect(await countRunningTasks(tx, agent.id)).toBe(1);++ // Claim another (now 1 running + 1 dispatched = 2)+ const claimed2 = await claimTask(tx, agent.id);+ expect(claimed2).not.toBeNull();+ expect(await countRunningTasks(tx, agent.id)).toBe(2);+ });+ });++ it("returns 0 when all tasks are completed", async () => {+ await withTestTransaction(db, async (tx) => {+ const { agent } = await seedFullChain(tx);++ // No tasks at all+ const count = await countRunningTasks(tx, agent.id);+ expect(count).toBe(0);+ });+ });+});diff --git a/src/web/lib/db/queries/verification-code.integration.test.ts b/src/web/lib/db/queries/verification-code.integration.test.tsnew file mode 100644index 000000000..84405bb03--- /dev/null+++ b/src/web/lib/db/queries/verification-code.integration.test.ts@@ -0,0 +1,107 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+} from "../test-utils";+import {+ createVerificationCode,+ getLatestVerificationCode,+ incrementVerificationCodeAttempts,+} from "./verification-code";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++describe("getLatestVerificationCode", () => {+ it("returns valid code (unused, unexpired, under attempt limit)", async () => {+ await withTestTransaction(db, async (tx) => {+ const code = await createVerificationCode(tx, {+ email: "[email protected]",+ code: "123456",+ expiresAt: new Date(Date.now() + 10 * 60 * 1000), // 10 min from now+ });++ const result = await getLatestVerificationCode(tx, "[email protected]");+ expect(result).not.toBeNull();+ expect(result!.id).toBe(code.id);+ expect(result!.code).toBe("123456");+ });+ });++ it("returns null for used code", async () => {+ await withTestTransaction(db, async (tx) => {+ const { markVerificationCodeUsed } = await import("./verification-code");++ await createVerificationCode(tx, {+ email: "[email protected]",+ code: "111111",+ expiresAt: new Date(Date.now() + 10 * 60 * 1000),+ });++ const fetched = await getLatestVerificationCode(tx, "[email protected]");+ await markVerificationCodeUsed(tx, fetched!.id);++ const result = await getLatestVerificationCode(tx, "[email protected]");+ expect(result).toBeNull();+ });+ });++ it("returns null for expired code", async () => {+ await withTestTransaction(db, async (tx) => {+ await createVerificationCode(tx, {+ email: "[email protected]",+ code: "222222",+ expiresAt: new Date(Date.now() - 1000), // already expired+ });++ const result = await getLatestVerificationCode(tx, "[email protected]");+ expect(result).toBeNull();+ });+ });++ it("returns null for code at attempt limit", async () => {+ await withTestTransaction(db, async (tx) => {+ const code = await createVerificationCode(tx, {+ email: "[email protected]",+ code: "333333",+ expiresAt: new Date(Date.now() + 10 * 60 * 1000),+ });++ // Increment attempts to 5 (the limit)+ for (let i = 0; i < 5; i++) {+ await incrementVerificationCodeAttempts(tx, code.id);+ }++ const result = await getLatestVerificationCode(tx, "[email protected]");+ expect(result).toBeNull();+ });+ });+});++describe("incrementVerificationCodeAttempts", () => {+ it("atomically increments the attempts counter", async () => {+ await withTestTransaction(db, async (tx) => {+ const { getLatestCodeByEmail } = await import("./verification-code");++ const code = await createVerificationCode(tx, {+ email: "[email protected]",+ code: "444444",+ expiresAt: new Date(Date.now() + 10 * 60 * 1000),+ });++ expect(code.attempts).toBe(0);++ await incrementVerificationCodeAttempts(tx, code.id);+ await incrementVerificationCodeAttempts(tx, code.id);+ await incrementVerificationCodeAttempts(tx, code.id);++ const fetched = await getLatestCodeByEmail(tx, "[email protected]");+ expect(fetched!.attempts).toBe(3);+ });+ });+});diff --git a/src/web/lib/db/queries/workspace.integration.test.ts b/src/web/lib/db/queries/workspace.integration.test.tsnew file mode 100644index 000000000..0c7ff8a43--- /dev/null+++ b/src/web/lib/db/queries/workspace.integration.test.ts@@ -0,0 +1,45 @@+import { afterAll, describe, it, expect } from "vitest";+import {+ getTestClient,+ getTestDb,+ withTestTransaction,+ seedUser,+ seedWorkspace,+ seedMember,+} from "../test-utils";+import { listWorkspaces } from "./workspace";++const client = getTestClient();+const db = getTestDb(client);++afterAll(async () => {+ await client.end();+});++describe("listWorkspaces", () => {+ it("returns only workspaces the user is a member of", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ const ws1 = await seedWorkspace(tx, { name: "Joined" });+ const ws2 = await seedWorkspace(tx, { name: "Not Joined" });++ // User is only a member of ws1+ await seedMember(tx, ws1.id, user.id);++ const result = await listWorkspaces(tx, user.id);+ expect(result).toHaveLength(1);+ expect(result[0].id).toBe(ws1.id);+ expect(result[0].name).toBe("Joined");+ });+ });++ it("returns empty array for user with no memberships", async () => {+ await withTestTransaction(db, async (tx) => {+ const user = await seedUser(tx);+ await seedWorkspace(tx); // exists but user isn't a member++ const result = await listWorkspaces(tx, user.id);+ expect(result).toEqual([]);+ });+ });+});diff --git a/src/web/lib/db/test-utils.ts b/src/web/lib/db/test-utils.tsnew file mode 100644index 000000000..e573096ec--- /dev/null+++ b/src/web/lib/db/test-utils.ts@@ -0,0 +1,133 @@+import { drizzle } from "drizzle-orm/postgres-js";+import postgres from "postgres";+import * as schema from "./schema";+import type { Database } from "./index";++const TEST_DATABASE_URL =+ process.env.DATABASE_TEST_URL ||+ "postgres://postgres:postgres@localhost:5432/alook_test?sslmode=disable";++/**+ * Creates a postgres client pointing at alook_test.+ * Caller must call `client.end()` in afterAll.+ */+export function getTestClient() {+ return postgres(TEST_DATABASE_URL);+}++/**+ * Wraps a postgres client in a Drizzle instance with schema.+ */+export function getTestDb(client: postgres.Sql) {+ return drizzle(client, { schema });+}++/**+ * Runs `fn(tx)` inside a transaction, always rolls back after.+ * Casts `tx` to `Database` for type compatibility with query functions.+ */+export async function withTestTransaction(+ db: ReturnType<typeof getTestDb>,+ fn: (tx: Database) => Promise<void>+) {+ await db+ .transaction(async (tx) => {+ await fn(tx as unknown as Database);+ // Always rollback — throw a sentinel error+ throw new RollbackError();+ })+ .catch((err) => {+ if (err instanceof RollbackError) return;+ throw err;+ });+}++class RollbackError extends Error {+ constructor() {+ super("__test_rollback__");+ }+}++// --------------- Fixture Factories ---------------++export async function seedUser(tx: Database, overrides?: { email?: string; name?: string }) {+ const rows = await (tx as any)+ .insert(schema.user)+ .values({+ email: overrides?.email ?? `test-${crypto.randomUUID()}@test.com`,+ name: overrides?.name ?? "Test User",+ })+ .returning();+ return rows[0]!;+}++export async function seedWorkspace(tx: Database, overrides?: { name?: string; slug?: string }) {+ const slug = overrides?.slug ?? `ws-${crypto.randomUUID().slice(0, 8)}`;+ const rows = await (tx as any)+ .insert(schema.workspace)+ .values({+ name: overrides?.name ?? "Test Workspace",+ slug,+ })+ .returning();+ return rows[0]!;+}++export async function seedMember(tx: Database, workspaceId: string, userId: string) {+ const rows = await (tx as any)+ .insert(schema.member)+ .values({ workspaceId, userId })+ .returning();+ return rows[0]!;+}++export async function seedRuntime(tx: Database, workspaceId: string) {+ const rows = await (tx as any)+ .insert(schema.agentRuntime)+ .values({+ workspaceId,+ daemonId: `daemon-${crypto.randomUUID().slice(0, 8)}`,+ provider: "test",+ name: "Test Runtime",+ })+ .returning();+ return rows[0]!;+}++export async function seedAgent(+ tx: Database,+ workspaceId: string,+ runtimeId: string,+ ownerId?: string+) {+ const rows = await (tx as any)+ .insert(schema.agent)+ .values({+ workspaceId,+ name: "Test Agent",+ runtimeId,+ ownerId: ownerId ?? null,+ })+ .returning();+ return rows[0]!;+}++export async function seedConversation(+ tx: Database,+ workspaceId: string,+ agentId: string,+ userId: string,+ overrides?: { title?: string; createdAt?: Date }+) {+ const rows = await (tx as any)+ .insert(schema.conversation)+ .values({+ workspaceId,+ agentId,+ userId,+ title: overrides?.title ?? "",+ ...(overrides?.createdAt ? { createdAt: overrides.createdAt } : {}),+ })+ .returning();+ return rows[0]!;+}diff --git a/src/web/lib/logger.test.ts b/src/web/lib/logger.test.tsindex 33ef7c9bc..94f3b4ca5 100644--- a/src/web/lib/logger.test.ts+++ b/src/web/lib/logger.test.ts@@ -1,8 +1,10 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { Logger } from "./logger";-let stdoutSpy: ReturnType<typeof vi.spyOn>;-let stderrSpy: ReturnType<typeof vi.spyOn>;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+let stdoutSpy: any;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+let stderrSpy: any;beforeEach(() => {stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);@@ -13,7 +15,8 @@ afterEach(() => {vi.restoreAllMocks();});-function parseLine(spy: ReturnType<typeof vi.spyOn>): Record<string, unknown> {+// eslint-disable-next-line @typescript-eslint/no-explicit-any+function parseLine(spy: any): Record<string, unknown> {const raw = spy.mock.calls[0][0] as string;return JSON.parse(raw);}diff --git a/src/web/lib/middleware/request-logger.test.ts b/src/web/lib/middleware/request-logger.test.tsindex 30d927d9e..684a35442 100644--- a/src/web/lib/middleware/request-logger.test.ts+++ b/src/web/lib/middleware/request-logger.test.ts@@ -1,8 +1,10 @@import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { logRequest } from "./request-logger";-let stdoutSpy: ReturnType<typeof vi.spyOn>;-let stderrSpy: ReturnType<typeof vi.spyOn>;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+let stdoutSpy: any;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+let stderrSpy: any;beforeEach(() => {stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);@@ -13,8 +15,9 @@ afterEach(() => {vi.restoreAllMocks();});-function parseLines(spy: ReturnType<typeof vi.spyOn>): Record<string, unknown>[] {- return spy.mock.calls.map((c) => JSON.parse(c[0] as string));+// eslint-disable-next-line @typescript-eslint/no-explicit-any+function parseLines(spy: any): Record<string, unknown>[] {+ return spy.mock.calls.map((c: any) => JSON.parse(c[0] as string));}describe("logRequest", () => {diff --git a/vitest.config.ts b/vitest.config.tsindex de5bb0992..2c4010bb2 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -6,7 +6,7 @@ export default defineConfig({globals: true,environment: "node",include: ["src/**/*.test.ts", "src/**/*.spec.ts"],- exclude: ["**/node_modules/**"],+ exclude: ["**/node_modules/**", "**/*.integration.test.ts"],},resolve: {alias: {diff --git a/vitest.integration.config.ts b/vitest.integration.config.tsnew file mode 100644index 000000000..3e0986aa4--- /dev/null+++ b/vitest.integration.config.ts@@ -0,0 +1,22 @@+import { defineConfig } from "vitest/config";+import path from "path";++export default defineConfig({+ test: {+ globals: true,+ environment: "node",+ include: ["src/**/*.integration.test.ts"],+ pool: "forks",+ poolOptions: {+ forks: {+ singleFork: true,+ },+ },+ fileParallelism: false,+ },+ resolve: {+ alias: {+ "@": path.resolve(__dirname, "src/web"),+ },+ },+});