Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

test(shared): improve coverage for lib utilities and db queries (#217)

Gener3961afc91f7c
diff --git a/src/shared/test/constants.test.ts b/src/shared/test/constants.test.ts
index 96b3a42fc..ba27a78cf 100644
--- a/src/shared/test/constants.test.ts
+++ b/src/shared/test/constants.test.ts
@@ -2,6 +2,8 @@ import { describe, it, expect } from "vitest"
import {
POLL_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH,
TaskStatus, TERMINAL_TASK_STATUSES, isTerminalTaskStatus,
+ IssueStatus, ACTIVE_ISSUE_STATUSES, TERMINAL_ISSUE_STATUSES, isTerminalIssueStatus,
+ MeetingStatus, TERMINAL_MEETING_STATUSES,
} from "../src/constants"
describe("constants", () => {
@@ -41,3 +43,59 @@ describe("TaskStatus", () => {
expect(isTerminalTaskStatus("running")).toBe(false)
})
})
+
+describe("IssueStatus", () => {
+ it("has all expected status values", () => {
+ expect(IssueStatus.TODO).toBe("todo")
+ expect(IssueStatus.IN_PROGRESS).toBe("in_progress")
+ expect(IssueStatus.REVIEW).toBe("review")
+ expect(IssueStatus.DONE).toBe("done")
+ expect(IssueStatus.CLOSED).toBe("closed")
+ expect(IssueStatus.CANCELED).toBe("canceled")
+ expect(IssueStatus.FAILED).toBe("failed")
+ })
+
+ it("ACTIVE_ISSUE_STATUSES contains non-terminal statuses", () => {
+ expect(ACTIVE_ISSUE_STATUSES).toContain("todo")
+ expect(ACTIVE_ISSUE_STATUSES).toContain("in_progress")
+ expect(ACTIVE_ISSUE_STATUSES).toContain("review")
+ expect(ACTIVE_ISSUE_STATUSES).not.toContain("done")
+ })
+
+ it("TERMINAL_ISSUE_STATUSES contains terminal statuses", () => {
+ expect(TERMINAL_ISSUE_STATUSES).toContain("done")
+ expect(TERMINAL_ISSUE_STATUSES).toContain("closed")
+ expect(TERMINAL_ISSUE_STATUSES).toContain("canceled")
+ expect(TERMINAL_ISSUE_STATUSES).toContain("failed")
+ })
+
+ it("isTerminalIssueStatus returns true for terminal statuses", () => {
+ expect(isTerminalIssueStatus("done")).toBe(true)
+ expect(isTerminalIssueStatus("closed")).toBe(true)
+ expect(isTerminalIssueStatus("canceled")).toBe(true)
+ expect(isTerminalIssueStatus("failed")).toBe(true)
+ })
+
+ it("isTerminalIssueStatus returns false for active statuses", () => {
+ expect(isTerminalIssueStatus("todo")).toBe(false)
+ expect(isTerminalIssueStatus("in_progress")).toBe(false)
+ expect(isTerminalIssueStatus("review")).toBe(false)
+ })
+})
+
+describe("MeetingStatus", () => {
+ it("has expected status values", () => {
+ expect(MeetingStatus.PENDING).toBe("pending")
+ expect(MeetingStatus.SCHEDULED).toBe("scheduled")
+ expect(MeetingStatus.JOINING).toBe("joining")
+ expect(MeetingStatus.RECORDING).toBe("recording")
+ expect(MeetingStatus.COMPLETED).toBe("completed")
+ expect(MeetingStatus.FAILED).toBe("failed")
+ })
+
+ it("TERMINAL_MEETING_STATUSES contains only completed and failed", () => {
+ expect(TERMINAL_MEETING_STATUSES).toHaveLength(2)
+ expect(TERMINAL_MEETING_STATUSES).toContain("completed")
+ expect(TERMINAL_MEETING_STATUSES).toContain("failed")
+ })
+})
diff --git a/src/shared/test/lib/mime.test.ts b/src/shared/test/lib/mime.test.ts
new file mode 100644
index 000000000..b1faa738c
--- /dev/null
+++ b/src/shared/test/lib/mime.test.ts
@@ -0,0 +1,229 @@
+import { describe, it, expect } from "vitest";
+import {
+ extractAttachmentMeta,
+ filterDownloadableAttachments,
+ buildMimeMessage,
+} from "../../src/lib/mime";
+
+describe("extractAttachmentMeta", () => {
+ it("returns empty array for no attachments", () => {
+ expect(extractAttachmentMeta([])).toEqual([]);
+ });
+
+ it("extracts meta for disposition=attachment", () => {
+ const result = extractAttachmentMeta([
+ {
+ disposition: "attachment",
+ filename: "report.pdf",
+ mimeType: "application/pdf",
+ content: "aGVsbG8=",
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ key: "inline:0",
+ filename: "report.pdf",
+ size: 8,
+ contentType: "application/pdf",
+ },
+ ]);
+ });
+
+ it("extracts meta when filename is present even without disposition", () => {
+ const result = extractAttachmentMeta([
+ {
+ disposition: null,
+ filename: "image.png",
+ mimeType: "image/png",
+ content: new ArrayBuffer(1024),
+ },
+ ]);
+ expect(result).toEqual([
+ {
+ key: "inline:0",
+ filename: "image.png",
+ size: 1024,
+ contentType: "image/png",
+ },
+ ]);
+ });
+
+ it("filters out inline attachments without filename", () => {
+ const result = extractAttachmentMeta([
+ { disposition: "inline", filename: null, mimeType: "text/plain", content: "hello" },
+ ]);
+ expect(result).toEqual([]);
+ });
+
+ it("uses fallback filename when filename is null but disposition is attachment", () => {
+ const result = extractAttachmentMeta([
+ { disposition: "attachment", filename: null, mimeType: "text/plain", content: "data" },
+ ]);
+ expect(result[0].filename).toBe("attachment-0");
+ });
+
+ it("uses fallback contentType when mimeType is empty", () => {
+ const result = extractAttachmentMeta([
+ { disposition: "attachment", filename: "file.bin", mimeType: "", content: "x" },
+ ]);
+ expect(result[0].contentType).toBe("application/octet-stream");
+ });
+
+ it("handles Uint8Array content size as 0 (no byteLength on content check)", () => {
+ const content = new Uint8Array([1, 2, 3]);
+ const result = extractAttachmentMeta([
+ { disposition: "attachment", filename: "data.bin", mimeType: "application/octet-stream", content },
+ ]);
+ // Uint8Array is not ArrayBuffer and not string, so size = 0
+ expect(result[0].size).toBe(0);
+ });
+
+ it("handles multiple attachments with sequential indices after filtering", () => {
+ const result = extractAttachmentMeta([
+ { disposition: "attachment", filename: "a.txt", mimeType: "text/plain", content: "aaa" },
+ { disposition: "inline", filename: null, mimeType: "text/html", content: "<p>hi</p>" },
+ { disposition: "attachment", filename: "b.txt", mimeType: "text/plain", content: "bb" },
+ ]);
+ expect(result).toHaveLength(2);
+ // After filter, map uses post-filter indices
+ expect(result[0].key).toBe("inline:0");
+ expect(result[0].filename).toBe("a.txt");
+ expect(result[1].key).toBe("inline:1");
+ expect(result[1].filename).toBe("b.txt");
+ });
+});
+
+describe("filterDownloadableAttachments", () => {
+ it("returns empty array for empty input", () => {
+ expect(filterDownloadableAttachments([])).toEqual([]);
+ });
+
+ it("includes attachments with disposition=attachment", () => {
+ const atts = [
+ { disposition: "attachment", filename: null },
+ { disposition: "inline", filename: null },
+ ];
+ const result = filterDownloadableAttachments(atts);
+ expect(result).toHaveLength(1);
+ expect(result[0].disposition).toBe("attachment");
+ });
+
+ it("includes attachments with a filename regardless of disposition", () => {
+ const atts = [
+ { disposition: "inline", filename: "image.png" },
+ { disposition: null, filename: null },
+ ];
+ const result = filterDownloadableAttachments(atts);
+ expect(result).toHaveLength(1);
+ expect(result[0].filename).toBe("image.png");
+ });
+
+ it("preserves original object references", () => {
+ const original = { disposition: "attachment" as const, filename: "f.txt", extra: 42 };
+ const result = filterDownloadableAttachments([original]);
+ expect(result[0]).toBe(original);
+ });
+});
+
+describe("buildMimeMessage", () => {
+ it("builds a simple text/html message without attachments", () => {
+ const msg = buildMimeMessage({
+ subject: "Hello",
+ date: "Mon, 01 Jan 2026 00:00:00 GMT",
+ body: "<p>Hi there</p>",
+ });
+ expect(msg).toContain("From: [email protected]");
+ expect(msg).toContain("To: [email protected]");
+ expect(msg).toContain("Subject: Hello");
+ expect(msg).toContain("Date: Mon, 01 Jan 2026 00:00:00 GMT");
+ expect(msg).toContain("MIME-Version: 1.0");
+ expect(msg).toContain("Content-Type: text/html; charset=utf-8");
+ expect(msg).toContain("<p>Hi there</p>");
+ expect(msg).not.toContain("boundary");
+ });
+
+ it("builds a text/plain message when bodyType is specified", () => {
+ const msg = buildMimeMessage({
+ subject: "Plain",
+ date: "Mon, 01 Jan 2026 00:00:00 GMT",
+ body: "Hello plain",
+ bodyType: "text/plain",
+ });
+ expect(msg).toContain("Content-Type: text/plain; charset=utf-8");
+ });
+
+ it("includes threading headers when provided", () => {
+ const msg = buildMimeMessage({
+ subject: "Re: Thread",
+ date: "Mon, 01 Jan 2026 00:00:00 GMT",
+ body: "reply",
+ messageId: "<[email protected]>",
+ inReplyTo: "<[email protected]>",
+ });
+ expect(msg).toContain("Message-ID: <[email protected]>");
+ expect(msg).toContain("In-Reply-To: <[email protected]>");
+ expect(msg).toContain("References: <[email protected]> <[email protected]>");
+ });
+
+ it("builds multipart/mixed message with attachments", () => {
+ const msg = buildMimeMessage({
+ subject: "With attachment",
+ date: "Mon, 01 Jan 2026 00:00:00 GMT",
+ body: "<p>See attached</p>",
+ attachments: [
+ {
+ filename: "doc.pdf",
+ contentType: "application/pdf",
+ base64: "SGVsbG8gV29ybGQ=",
+ },
+ ],
+ });
+ expect(msg).toContain("Content-Type: multipart/mixed; boundary=");
+ expect(msg).toContain('Content-Disposition: attachment; filename="doc.pdf"');
+ expect(msg).toContain("Content-Transfer-Encoding: base64");
+ expect(msg).toContain("SGVsbG8gV29ybGQ=");
+ });
+
+ it("wraps long base64 content at 76 characters", () => {
+ const longBase64 = "A".repeat(200);
+ const msg = buildMimeMessage({
+ subject: "Long",
+ date: "Mon, 01 Jan 2026 00:00:00 GMT",
+ body: "body",
+ attachments: [{ filename: "big.bin", contentType: "application/octet-stream", base64: longBase64 }],
+ });
+ const lines = msg.split("\r\n");
+ const base64Lines = lines.filter(l => /^A+$/.test(l));
+ expect(base64Lines.length).toBeGreaterThan(1);
+ expect(base64Lines[0].length).toBe(76);
+ });
+
+ it("includes multiple attachments", () => {
+ const msg = buildMimeMessage({
+ subject: "Multi",
+ date: "Mon, 01 Jan 2026 00:00:00 GMT",
+ body: "body",
+ attachments: [
+ { filename: "a.txt", contentType: "text/plain", base64: "YQ==" },
+ { filename: "b.txt", contentType: "text/plain", base64: "Yg==" },
+ ],
+ });
+ expect(msg).toContain('filename="a.txt"');
+ expect(msg).toContain('filename="b.txt"');
+ // Should end with boundary terminator
+ expect(msg).toMatch(/--.*--$/);
+ });
+});
diff --git a/src/shared/test/queries/agent-access.test.ts b/src/shared/test/queries/agent-access.test.ts
new file mode 100644
index 000000000..3b7d2f33e
--- /dev/null
+++ b/src/shared/test/queries/agent-access.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect, vi } from "vitest";
+import * as agentAccessQueries from "../../src/db/queries/agent-access";
+
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.delete = vi.fn(() => chain);
+ return chain;
+}
+
+describe("agent-access query module exports", () => {
+ it("exports listAgentAccess", () => {
+ expect(typeof agentAccessQueries.listAgentAccess).toBe("function");
+ });
+
+ it("exports grantAgentAccess", () => {
+ expect(typeof agentAccessQueries.grantAgentAccess).toBe("function");
+ });
+
+ it("exports revokeAgentAccess", () => {
+ expect(typeof agentAccessQueries.revokeAgentAccess).toBe("function");
+ });
+
+ it("exports hasAgentAccess", () => {
+ expect(typeof agentAccessQueries.hasAgentAccess).toBe("function");
+ });
+
+ it("exports getAllAgentAccessForWorkspace", () => {
+ expect(typeof agentAccessQueries.getAllAgentAccessForWorkspace).toBe("function");
+ });
+});
+
+describe("hasAgentAccess", () => {
+ it("returns true when access row exists", async () => {
+ const mockDb = createMockDb([{ id: "aa_1" }]);
+ const result = await agentAccessQueries.hasAgentAccess(mockDb, "ag_1", "ws_1", "usr_1");
+ expect(result).toBe(true);
+ });
+
+ it("returns false when no access row exists", async () => {
+ const mockDb = createMockDb([]);
+ const result = await agentAccessQueries.hasAgentAccess(mockDb, "ag_1", "ws_1", "usr_1");
+ expect(result).toBe(false);
+ });
+});
+
+describe("revokeAgentAccess", () => {
+ it("returns null when no row deleted", async () => {
+ const chain: any = {};
+ chain.delete = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([]));
+ const result = await agentAccessQueries.revokeAgentAccess(chain, "ag_1", "ws_1", "usr_1");
+ expect(result).toBeNull();
+ });
+});
diff --git a/src/shared/test/queries/agent-skill.test.ts b/src/shared/test/queries/agent-skill.test.ts
index 2d279a543..f8264d44d 100644
--- a/src/shared/test/queries/agent-skill.test.ts
+++ b/src/shared/test/queries/agent-skill.test.ts
@@ -1,6 +1,14 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import * as agentSkillQueries from "../../src/db/queries/agent-skill";
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ return chain;
+}
+
describe("agent-skill query module exports", () => {
it("exports syncGlobalSkills", () => {
expect(typeof agentSkillQueries.syncGlobalSkills).toBe("function");
@@ -24,3 +32,35 @@ describe("agent-skill query function signatures", () => {
expect(agentSkillQueries.getSkills.length).toBe(4);
});
});
+
+describe("getSkills", () => {
+ it("returns empty array when no skills found", async () => {
+ const mockDb = createMockDb([]);
+ const result = await agentSkillQueries.getSkills(mockDb, "ag_1", "local", "ws_1");
+ expect(result).toEqual([]);
+ });
+
+ it("returns skills and deduplicates global skills by name", async () => {
+ const rows = [
+ { name: "code-review", description: "Reviews code", isGlobal: true },
+ { name: "code-review", description: "Reviews code (dup)", isGlobal: true },
+ { name: "deploy", description: "Deploys apps", isGlobal: false },
+ ];
+ const mockDb = createMockDb(rows);
+ const result = await agentSkillQueries.getSkills(mockDb, "ag_1", "local", "ws_1");
+ expect(result).toHaveLength(2);
+ expect(result[0].name).toBe("code-review");
+ expect(result[0].description).toBe("Reviews code");
+ expect(result[1].name).toBe("deploy");
+ });
+
+ it("does not deduplicate across global and agent scopes", async () => {
+ const rows = [
+ { name: "review", description: "Global review", isGlobal: true },
+ { name: "review", description: "Agent review", isGlobal: false },
+ ];
+ const mockDb = createMockDb(rows);
+ const result = await agentSkillQueries.getSkills(mockDb, "ag_1", "local", "ws_1");
+ expect(result).toHaveLength(2);
+ });
+});
diff --git a/src/shared/test/queries/artifact.test.ts b/src/shared/test/queries/artifact.test.ts
new file mode 100644
index 000000000..09b199d92
--- /dev/null
+++ b/src/shared/test/queries/artifact.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect, vi } from "vitest";
+import * as artifactQueries from "../../src/db/queries/artifact";
+
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.orderBy = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ return chain;
+}
+
+describe("artifact query module exports", () => {
+ it("exports createArtifact", () => {
+ expect(typeof artifactQueries.createArtifact).toBe("function");
+ });
+
+ it("exports listArtifactsByConversation", () => {
+ expect(typeof artifactQueries.listArtifactsByConversation).toBe("function");
+ });
+
+ it("exports getArtifact", () => {
+ expect(typeof artifactQueries.getArtifact).toBe("function");
+ });
+
+ it("exports artifactToResponse", () => {
+ expect(typeof artifactQueries.artifactToResponse).toBe("function");
+ });
+});
+
+describe("artifactToResponse", () => {
+ it("maps DB row to API response shape", () => {
+ const row = {
+ id: "art_123",
+ conversationId: "conv_456",
+ agentId: "ag_789",
+ workspaceId: "ws_001",
+ filename: "report.pdf",
+ contentType: "application/pdf",
+ size: 2048,
+ r2Key: "uploads/report.pdf",
+ source: "upload",
+ createdAt: "2026-01-15T10:00:00.000Z",
+ };
+
+ const result = artifactQueries.artifactToResponse(row as any);
+
+ expect(result).toEqual({
+ id: "art_123",
+ conversation_id: "conv_456",
+ agent_id: "ag_789",
+ filename: "report.pdf",
+ content_type: "application/pdf",
+ size: 2048,
+ source: "upload",
+ created_at: "2026-01-15T10:00:00.000Z",
+ });
+ });
+
+ it("excludes internal fields like r2Key and workspaceId", () => {
+ const row = {
+ id: "art_1",
+ conversationId: "conv_1",
+ agentId: "ag_1",
+ workspaceId: "ws_1",
+ filename: "file.txt",
+ contentType: "text/plain",
+ size: 100,
+ r2Key: "secret/key",
+ source: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+
+ const result = artifactQueries.artifactToResponse(row as any);
+
+ expect(result).not.toHaveProperty("r2Key");
+ expect(result).not.toHaveProperty("workspace_id");
+ expect(result).not.toHaveProperty("workspaceId");
+ });
+
+ it("handles null source", () => {
+ const row = {
+ id: "art_1",
+ conversationId: "conv_1",
+ agentId: "ag_1",
+ workspaceId: "ws_1",
+ filename: "file.txt",
+ contentType: "text/plain",
+ size: 0,
+ r2Key: "key",
+ source: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ };
+
+ const result = artifactQueries.artifactToResponse(row as any);
+ expect(result.source).toBeNull();
+ });
+});
+
+describe("getArtifact", () => {
+ it("returns null when no artifact found", async () => {
+ const mockDb = createMockDb([]);
+ mockDb.limit = vi.fn(() => Promise.resolve([]));
+ mockDb.where = vi.fn(() => Promise.resolve([]));
+ const result = await artifactQueries.getArtifact(mockDb, "art_missing", "ws_1");
+ expect(result).toBeNull();
+ });
+});
diff --git a/src/shared/test/queries/calendar-event.test.ts b/src/shared/test/queries/calendar-event.test.ts
index 5a58bb5fd..d670d291a 100644
--- a/src/shared/test/queries/calendar-event.test.ts
+++ b/src/shared/test/queries/calendar-event.test.ts
@@ -219,6 +219,44 @@ describe("computeNextScheduledAt", () => {
});
});
+describe("getOccurrencesPerDay", () => {
+ it("returns 1 for daily interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("1day")).toBe(1);
+ });
+
+ it("returns 1 for weekly interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("1week")).toBe(1);
+ });
+
+ it("returns 1 for monthly interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("1month")).toBe(1);
+ });
+
+ it("returns 24 for hourly interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("1hour")).toBe(24);
+ });
+
+ it("returns 12 for 2-hour interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("2hour")).toBe(12);
+ });
+
+ it("returns 48 for 30-minute interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("30min")).toBe(48);
+ });
+
+ it("returns 96 for 15-minute interval", () => {
+ expect(calendarQueries.getOccurrencesPerDay("15min")).toBe(96);
+ });
+
+ it("returns 1 for invalid format", () => {
+ expect(calendarQueries.getOccurrencesPerDay("invalid")).toBe(1);
+ });
+
+ it("returns 1 for 0-amount (division guard)", () => {
+ expect(calendarQueries.getOccurrencesPerDay("0min")).toBe(1);
+ });
+});
+
describe("expandOccurrences", () => {
it("returns one entry per occurrence within [from, to] for a daily event", () => {
const out = calendarQueries.expandOccurrences(
diff --git a/src/shared/test/queries/conversation-map.test.ts b/src/shared/test/queries/conversation-map.test.ts
new file mode 100644
index 000000000..dc1d19326
--- /dev/null
+++ b/src/shared/test/queries/conversation-map.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect, vi } from "vitest";
+import * as conversationMapQueries from "../../src/db/queries/conversation-map";
+
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.onConflictDoNothing = vi.fn(() => Promise.resolve());
+ return chain;
+}
+
+describe("conversation-map query module exports", () => {
+ it("exports findByKey", () => {
+ expect(typeof conversationMapQueries.findByKey).toBe("function");
+ });
+
+ it("exports createMapping", () => {
+ expect(typeof conversationMapQueries.createMapping).toBe("function");
+ });
+});
+
+describe("findByKey", () => {
+ it("returns conversationId when mapping exists", async () => {
+ const mockDb = createMockDb([{ conversationId: "conv_123" }]);
+ const result = await conversationMapQueries.findByKey(mockDb, "email:ag_1:thread", "ws_1");
+ expect(result).toBe("conv_123");
+ expect(mockDb.select).toHaveBeenCalledOnce();
+ expect(mockDb.from).toHaveBeenCalledOnce();
+ expect(mockDb.where).toHaveBeenCalledOnce();
+ expect(mockDb.limit).toHaveBeenCalledWith(1);
+ });
+
+ it("returns null when no mapping exists", async () => {
+ const mockDb = createMockDb([]);
+ const result = await conversationMapQueries.findByKey(mockDb, "email:ag_1:unknown", "ws_1");
+ expect(result).toBeNull();
+ });
+});
diff --git a/src/shared/test/queries/conversation.test.ts b/src/shared/test/queries/conversation.test.ts
index b47b7266b..a14718050 100644
--- a/src/shared/test/queries/conversation.test.ts
+++ b/src/shared/test/queries/conversation.test.ts
@@ -1,6 +1,24 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import * as conversationQueries from "../../src/db/queries/conversation";
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ chain.orderBy = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.delete = vi.fn(() => chain);
+ chain.leftJoin = vi.fn(() => chain);
+ chain.groupBy = vi.fn(() => chain);
+ return chain;
+}
+
describe("conversation query module exports", () => {
it("exports createConversation", () => {
expect(typeof conversationQueries.createConversation).toBe("function");
@@ -10,6 +28,10 @@ describe("conversation query module exports", () => {
expect(typeof conversationQueries.getConversation).toBe("function");
});
+ it("exports getConversationsByIds", () => {
+ expect(typeof conversationQueries.getConversationsByIds).toBe("function");
+ });
+
it("exports listConversations", () => {
expect(typeof conversationQueries.listConversations).toBe("function");
});
@@ -18,6 +40,10 @@ describe("conversation query module exports", () => {
expect(typeof conversationQueries.listConversationsByAgent).toBe("function");
});
+ it("exports updateConversationTitle", () => {
+ expect(typeof conversationQueries.updateConversationTitle).toBe("function");
+ });
+
it("exports getOrCreateAgentConversation", () => {
expect(typeof conversationQueries.getOrCreateAgentConversation).toBe("function");
});
@@ -29,6 +55,10 @@ describe("conversation query module exports", () => {
it("exports listPreviousConversations", () => {
expect(typeof conversationQueries.listPreviousConversations).toBe("function");
});
+
+ it("exports hasPreviousConversations", () => {
+ expect(typeof conversationQueries.hasPreviousConversations).toBe("function");
+ });
});
describe("conversation query function signatures (with optional channel param)", () => {
@@ -48,3 +78,70 @@ describe("conversation query function signatures (with optional channel param)",
expect(conversationQueries.listPreviousConversations.length).toBeGreaterThanOrEqual(5);
});
});
+
+describe("getConversationsByIds", () => {
+ it("returns empty array for empty ids without querying DB", async () => {
+ const result = await conversationQueries.getConversationsByIds(null as any, [], "ws_1");
+ expect(result).toEqual([]);
+ });
+});
+
+describe("getConversation", () => {
+ it("returns null when not found", async () => {
+ const mockDb = createMockDb([]);
+ const result = await conversationQueries.getConversation(mockDb, "conv_missing", "ws_1");
+ expect(result).toBeNull();
+ });
+
+ it("returns conversation when found", async () => {
+ const conv = { id: "conv_1", title: "Test" };
+ const mockDb = createMockDb([conv]);
+ const result = await conversationQueries.getConversation(mockDb, "conv_1", "ws_1");
+ expect(result).toEqual(conv);
+ });
+});
+
+describe("updateConversationTitle", () => {
+ it("returns null when no row updated", async () => {
+ const chain: any = {};
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([]));
+ const result = await conversationQueries.updateConversationTitle(chain, "conv_1", "New Title");
+ expect(result).toBeNull();
+ });
+});
+
+describe("deleteConversation", () => {
+ it("returns null when conversation does not exist", async () => {
+ const chain: any = {};
+ chain.delete = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([]));
+ const result = await conversationQueries.deleteConversation(chain, "conv_missing", "ws_1");
+ expect(result).toBeNull();
+ });
+});
+
+describe("hasPreviousConversations", () => {
+ it("returns true when previous conversations exist", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve([{ exists: 1 }]));
+ const result = await conversationQueries.hasPreviousConversations(chain, "ws_1", "usr_1", "ag_1", "conv_current");
+ expect(result).toBe(true);
+ });
+
+ it("returns false when no previous conversations exist", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve([]));
+ const result = await conversationQueries.hasPreviousConversations(chain, "ws_1", "usr_1", "ag_1", "conv_current");
+ expect(result).toBe(false);
+ });
+});
diff --git a/src/shared/test/queries/email.test.ts b/src/shared/test/queries/email.test.ts
index e016d4eca..fa738489b 100644
--- a/src/shared/test/queries/email.test.ts
+++ b/src/shared/test/queries/email.test.ts
@@ -1,6 +1,23 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import * as emailQueries from "../../src/db/queries/email";
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ chain.orderBy = vi.fn(() => chain);
+ chain.limit = vi.fn(() => chain);
+ chain.offset = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.delete = vi.fn(() => chain);
+ return chain;
+}
+
describe("email query module exports", () => {
it("exports getInboxEmails", () => {
expect(typeof emailQueries.getInboxEmails).toBe("function");
@@ -63,3 +80,50 @@ describe("email query function signatures", () => {
expect(emailQueries.updateEmailStatus.length).toBe(4);
});
});
+
+describe("getEmailById", () => {
+ it("returns null when email not found", async () => {
+ const mockDb = createMockDb([]);
+ const result = await emailQueries.getEmailById(mockDb, "em_missing", "ws_1");
+ expect(result).toBeNull();
+ });
+
+ it("returns email when found", async () => {
+ const email = { id: "em_1", subject: "Hello" };
+ const mockDb = createMockDb([email]);
+ const result = await emailQueries.getEmailById(mockDb, "em_1", "ws_1");
+ expect(result).toEqual(email);
+ });
+});
+
+describe("getEmailByMessageId", () => {
+ it("returns null for empty messageId without querying DB", async () => {
+ const result = await emailQueries.getEmailByMessageId(null as any, "", "ws_1");
+ expect(result).toBeNull();
+ });
+
+ it("returns null when no email matches", async () => {
+ const mockDb = createMockDb([]);
+ const result = await emailQueries.getEmailByMessageId(mockDb, "<[email protected]>", "ws_1");
+ expect(result).toBeNull();
+ });
+
+ it("returns email when messageId matches", async () => {
+ const email = { id: "em_1", messageId: "<[email protected]>" };
+ const mockDb = createMockDb([email]);
+ const result = await emailQueries.getEmailByMessageId(mockDb, "<[email protected]>", "ws_1");
+ expect(result).toEqual(email);
+ });
+});
+
+describe("updateEmailStatus", () => {
+ it("returns null when email not found for update", async () => {
+ const chain: any = {};
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([]));
+ const result = await emailQueries.updateEmailStatus(chain, "em_missing", "ws_1", "read");
+ expect(result).toBeNull();
+ });
+});
diff --git a/src/shared/test/queries/issue-comment.test.ts b/src/shared/test/queries/issue-comment.test.ts
new file mode 100644
index 000000000..3d51c5e16
--- /dev/null
+++ b/src/shared/test/queries/issue-comment.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from "vitest";
+import * as issueCommentQueries from "../../src/db/queries/issue-comment";
+
+describe("issue-comment query module exports", () => {
+ it("exports createComment", () => {
+ expect(typeof issueCommentQueries.createComment).toBe("function");
+ });
+
+ it("exports listComments", () => {
+ expect(typeof issueCommentQueries.listComments).toBe("function");
+ });
+
+ it("exports deleteComment", () => {
+ expect(typeof issueCommentQueries.deleteComment).toBe("function");
+ });
+
+ it("exports commentToResponse", () => {
+ expect(typeof issueCommentQueries.commentToResponse).toBe("function");
+ });
+});
+
+describe("commentToResponse", () => {
+ it("maps DB row to API response shape with snake_case keys", () => {
+ const row = {
+ id: "ic_001",
+ issueId: "iss_123",
+ workspaceId: "ws_456",
+ authorType: "agent",
+ authorId: "ag_789",
+ content: "This looks good!",
+ createdAt: "2026-03-10T14:30:00.000Z",
+ };
+
+ const result = issueCommentQueries.commentToResponse(row as any);
+
+ expect(result).toEqual({
+ id: "ic_001",
+ issue_id: "iss_123",
+ workspace_id: "ws_456",
+ author_type: "agent",
+ author_id: "ag_789",
+ content: "This looks good!",
+ created_at: "2026-03-10T14:30:00.000Z",
+ });
+ });
+
+ it("preserves user author type", () => {
+ const row = {
+ id: "ic_002",
+ issueId: "iss_100",
+ workspaceId: "ws_1",
+ authorType: "user",
+ authorId: "usr_1",
+ content: "Fixed in latest commit",
+ createdAt: "2026-04-01T09:00:00.000Z",
+ };
+
+ const result = issueCommentQueries.commentToResponse(row as any);
+ expect(result.author_type).toBe("user");
+ });
+});
diff --git a/src/shared/test/queries/meeting-session.test.ts b/src/shared/test/queries/meeting-session.test.ts
index 238883230..ec5b02cad 100644
--- a/src/shared/test/queries/meeting-session.test.ts
+++ b/src/shared/test/queries/meeting-session.test.ts
@@ -1,6 +1,20 @@
-import { describe, it, expect } from "vitest"
+import { describe, it, expect, vi } from "vitest"
import * as meetingQueries from "../../src/db/queries/meeting-session"
+function createMockDb(rows: any[]) {
+ const chain: any = {}
+ chain.select = vi.fn(() => chain)
+ chain.from = vi.fn(() => chain)
+ chain.where = vi.fn(() => Promise.resolve(rows))
+ chain.orderBy = vi.fn(() => chain)
+ chain.update = vi.fn(() => chain)
+ chain.set = vi.fn(() => chain)
+ chain.returning = vi.fn(() => Promise.resolve(rows))
+ chain.delete = vi.fn(() => chain)
+ chain.leftJoin = vi.fn(() => chain)
+ return chain
+}
+
describe("meeting-session query module exports", () => {
it("exports createMeetingSession", () => {
expect(typeof meetingQueries.createMeetingSession).toBe("function")
@@ -56,3 +70,68 @@ describe("meeting-session query function signatures", () => {
expect(meetingQueries.deleteMeetingSession.length).toBe(3)
})
})
+
+describe("getMeetingSession", () => {
+ it("returns null when meeting not found", async () => {
+ const mockDb = createMockDb([])
+ const result = await meetingQueries.getMeetingSession(mockDb, "ms_missing", "ws_1")
+ expect(result).toBeNull()
+ })
+
+ it("returns meeting when found", async () => {
+ const meeting = { id: "ms_1", title: "Standup", status: "scheduled" }
+ const mockDb = createMockDb([meeting])
+ const result = await meetingQueries.getMeetingSession(mockDb, "ms_1", "ws_1")
+ expect(result).toEqual(meeting)
+ })
+})
+
+describe("getMeetingSessionById", () => {
+ it("returns null when meeting not found", async () => {
+ const mockDb = createMockDb([])
+ const result = await meetingQueries.getMeetingSessionById(mockDb, "ms_missing")
+ expect(result).toBeNull()
+ })
+})
+
+describe("updateMeetingSession", () => {
+ it("returns null when no row updated", async () => {
+ const chain: any = {}
+ chain.update = vi.fn(() => chain)
+ chain.set = vi.fn(() => chain)
+ chain.where = vi.fn(() => chain)
+ chain.returning = vi.fn(() => Promise.resolve([]))
+ const result = await meetingQueries.updateMeetingSession(chain, "ms_1", "ws_1", { title: "New" })
+ expect(result).toBeNull()
+ })
+})
+
+describe("claimMeetingSession", () => {
+ it("returns null when session not in scheduled state", async () => {
+ const chain: any = {}
+ chain.update = vi.fn(() => chain)
+ chain.set = vi.fn(() => chain)
+ chain.where = vi.fn(() => chain)
+ chain.returning = vi.fn(() => Promise.resolve([]))
+ const result = await meetingQueries.claimMeetingSession(chain, "ms_1", "ws_1", "2026-01-01T00:00:00Z")
+ expect(result).toBeNull()
+ })
+})
+
+describe("claimMeetingSessions", () => {
+ it("returns empty array for empty ids", async () => {
+ const result = await meetingQueries.claimMeetingSessions(null as any, [], "ws_1", "2026-01-01T00:00:00Z")
+ expect(result).toEqual([])
+ })
+})
+
+describe("deleteMeetingSession", () => {
+ it("returns null when session not found", async () => {
+ const chain: any = {}
+ chain.delete = vi.fn(() => chain)
+ chain.where = vi.fn(() => chain)
+ chain.returning = vi.fn(() => Promise.resolve([]))
+ const result = await meetingQueries.deleteMeetingSession(chain, "ms_missing", "ws_1")
+ expect(result).toBeNull()
+ })
+})
diff --git a/src/shared/test/queries/message.test.ts b/src/shared/test/queries/message.test.ts
new file mode 100644
index 000000000..44d4faa14
--- /dev/null
+++ b/src/shared/test/queries/message.test.ts
@@ -0,0 +1,147 @@
+import { describe, it, expect, vi } from "vitest";
+import * as messageQueries from "../../src/db/queries/message";
+
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.orderBy = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.delete = vi.fn(() => chain);
+ return chain;
+}
+
+describe("message query module exports", () => {
+ it("exports createMessage", () => {
+ expect(typeof messageQueries.createMessage).toBe("function");
+ });
+
+ it("exports getNewestMessageId", () => {
+ expect(typeof messageQueries.getNewestMessageId).toBe("function");
+ });
+
+ it("exports getActiveMessageCount", () => {
+ expect(typeof messageQueries.getActiveMessageCount).toBe("function");
+ });
+
+ it("exports listMessages", () => {
+ expect(typeof messageQueries.listMessages).toBe("function");
+ });
+
+ it("exports getMessage", () => {
+ expect(typeof messageQueries.getMessage).toBe("function");
+ });
+
+ it("exports createBufferedMessage", () => {
+ expect(typeof messageQueries.createBufferedMessage).toBe("function");
+ });
+
+ it("exports listBufferedMessages", () => {
+ expect(typeof messageQueries.listBufferedMessages).toBe("function");
+ });
+
+ it("exports activateNextBufferedMessage", () => {
+ expect(typeof messageQueries.activateNextBufferedMessage).toBe("function");
+ });
+
+ it("exports revertToBuffered", () => {
+ expect(typeof messageQueries.revertToBuffered).toBe("function");
+ });
+
+ it("exports deleteBufferedMessage", () => {
+ expect(typeof messageQueries.deleteBufferedMessage).toBe("function");
+ });
+
+ it("exports deleteAllBufferedMessages", () => {
+ expect(typeof messageQueries.deleteAllBufferedMessages).toBe("function");
+ });
+
+ it("exports countBufferedMessages", () => {
+ expect(typeof messageQueries.countBufferedMessages).toBe("function");
+ });
+
+ it("exports updateMessageTaskId", () => {
+ expect(typeof messageQueries.updateMessageTaskId).toBe("function");
+ });
+
+ it("exports listMessagesAroundTask", () => {
+ expect(typeof messageQueries.listMessagesAroundTask).toBe("function");
+ });
+});
+
+describe("getNewestMessageId", () => {
+ it("returns message id when messages exist", async () => {
+ const mockDb = createMockDb([{ id: "msg_latest" }]);
+ const result = await messageQueries.getNewestMessageId(mockDb, "conv_1");
+ expect(result).toBe("msg_latest");
+ });
+
+ it("returns null when no messages exist", async () => {
+ const mockDb = createMockDb([]);
+ const result = await messageQueries.getNewestMessageId(mockDb, "conv_empty");
+ expect(result).toBeNull();
+ });
+});
+
+describe("getActiveMessageCount", () => {
+ it("returns count from query result", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([{ cnt: 42 }]));
+ const result = await messageQueries.getActiveMessageCount(chain, "conv_1");
+ expect(result).toBe(42);
+ });
+
+ it("returns 0 when no rows returned", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([]));
+ const result = await messageQueries.getActiveMessageCount(chain, "conv_empty");
+ expect(result).toBe(0);
+ });
+});
+
+describe("getMessage", () => {
+ it("returns null when message not found", async () => {
+ const mockDb = createMockDb([]);
+ mockDb.where = vi.fn(() => Promise.resolve([]));
+ const result = await messageQueries.getMessage(mockDb, "msg_missing");
+ expect(result).toBeNull();
+ });
+
+ it("returns message when found", async () => {
+ const msg = { id: "msg_1", content: "hello", role: "user" };
+ const mockDb = createMockDb([msg]);
+ mockDb.where = vi.fn(() => Promise.resolve([msg]));
+ const result = await messageQueries.getMessage(mockDb, "msg_1");
+ expect(result).toEqual(msg);
+ });
+});
+
+describe("countBufferedMessages", () => {
+ it("returns count value", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([{ count: 5 }]));
+ const result = await messageQueries.countBufferedMessages(chain, "conv_1");
+ expect(result).toBe(5);
+ });
+
+ it("returns 0 when no results", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([]));
+ const result = await messageQueries.countBufferedMessages(chain, "conv_1");
+ expect(result).toBe(0);
+ });
+});
diff --git a/src/shared/test/queries/overview.test.ts b/src/shared/test/queries/overview.test.ts
new file mode 100644
index 000000000..2ea47963e
--- /dev/null
+++ b/src/shared/test/queries/overview.test.ts
@@ -0,0 +1,38 @@
+import { describe, it, expect } from "vitest";
+import * as overviewQueries from "../../src/db/queries/overview";
+
+describe("overview query module exports", () => {
+ it("exports getEmailStatsByWorkspace", () => {
+ expect(typeof overviewQueries.getEmailStatsByWorkspace).toBe("function");
+ });
+
+ it("exports getEmailAccountsByWorkspace", () => {
+ expect(typeof overviewQueries.getEmailAccountsByWorkspace).toBe("function");
+ });
+
+ it("exports getTaskStatsByWorkspace", () => {
+ expect(typeof overviewQueries.getTaskStatsByWorkspace).toBe("function");
+ });
+
+ it("exports getRecentTerminalTasks", () => {
+ expect(typeof overviewQueries.getRecentTerminalTasks).toBe("function");
+ });
+
+ it("exports getConversationCountsByAgent", () => {
+ expect(typeof overviewQueries.getConversationCountsByAgent).toBe("function");
+ });
+});
+
+describe("getRecentTerminalTasks", () => {
+ it("returns empty array for empty visibleAgentIds without querying DB", async () => {
+ const result = await overviewQueries.getRecentTerminalTasks(null as any, "ws_1", []);
+ expect(result).toEqual([]);
+ });
+});
+
+describe("getConversationCountsByAgent", () => {
+ it("returns empty array for empty visibleAgentIds without querying DB", async () => {
+ const result = await overviewQueries.getConversationCountsByAgent(null as any, "ws_1", []);
+ expect(result).toEqual([]);
+ });
+});
diff --git a/src/shared/test/queries/task.test.ts b/src/shared/test/queries/task.test.ts
index ca0d31ca2..c4526ee13 100644
--- a/src/shared/test/queries/task.test.ts
+++ b/src/shared/test/queries/task.test.ts
@@ -1,6 +1,24 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import * as taskQueries from "../../src/db/queries/task";
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.orderBy = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.delete = vi.fn(() => chain);
+ chain.groupBy = vi.fn(() => chain);
+ chain.leftJoin = vi.fn(() => chain);
+ return chain;
+}
+
describe("task query module exports", () => {
it("exports listActiveTaskCountsByWorkspace", () => {
expect(typeof taskQueries.listActiveTaskCountsByWorkspace).toBe("function");
@@ -32,3 +50,128 @@ describe("task query function signatures", () => {
expect(taskQueries.listActiveTasksByAgent.length).toBe(3);
});
});
+
+describe("listPendingTasksByRuntimes", () => {
+ it("returns empty array for empty runtimeIds without querying DB", async () => {
+ const result = await taskQueries.listPendingTasksByRuntimes(null as any, [], "ws_1");
+ expect(result).toEqual([]);
+ });
+});
+
+describe("claimKillTasks", () => {
+ it("returns empty array for empty runtimeIds without querying DB", async () => {
+ const result = await taskQueries.claimKillTasks(null as any, [], "ws_1", 10);
+ expect(result).toEqual([]);
+ });
+
+ it("returns empty array for zero limit without querying DB", async () => {
+ const result = await taskQueries.claimKillTasks(null as any, ["rt_1"], "ws_1", 0);
+ expect(result).toEqual([]);
+ });
+});
+
+describe("countTasksByTrace", () => {
+ it("returns count from query", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([{ value: 7 }]));
+ const result = await taskQueries.countTasksByTrace(chain, "trace_1");
+ expect(result).toBe(7);
+ });
+
+ it("returns 0 when no results", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([]));
+ const result = await taskQueries.countTasksByTrace(chain, "trace_empty");
+ expect(result).toBe(0);
+ });
+});
+
+describe("getLatestTaskForConversation", () => {
+ it("returns null when no tasks exist", async () => {
+ const mockDb = createMockDb([]);
+ const result = await taskQueries.getLatestTaskForConversation(mockDb, "conv_empty");
+ expect(result).toBeNull();
+ });
+
+ it("returns latest task when found", async () => {
+ const task = { id: "task_1", traceId: "trace_1" };
+ const mockDb = createMockDb([task]);
+ const result = await taskQueries.getLatestTaskForConversation(mockDb, "conv_1");
+ expect(result).toEqual(task);
+ });
+});
+
+describe("getTask", () => {
+ it("returns null when task not found", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([]));
+ const result = await taskQueries.getTask(chain, "task_missing");
+ expect(result).toBeNull();
+ });
+
+ it("returns task when found", async () => {
+ const task = { id: "task_1", status: "running" };
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([task]));
+ const result = await taskQueries.getTask(chain, "task_1");
+ expect(result).toEqual(task);
+ });
+});
+
+describe("getTaskStatus", () => {
+ it("returns null when task not found", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([]));
+ const result = await taskQueries.getTaskStatus(chain, "task_missing");
+ expect(result).toBeNull();
+ });
+
+ it("returns status when found", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve([{ status: "completed" }]));
+ const result = await taskQueries.getTaskStatus(chain, "task_1");
+ expect(result).toBe("completed");
+ });
+});
+
+describe("hasPendingTaskForConversation", () => {
+ it("returns true when pending tasks exist", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve([{ id: "task_1" }]));
+ const result = await taskQueries.hasPendingTaskForConversation(chain, "conv_1");
+ expect(result).toBe(true);
+ });
+
+ it("returns false when no pending tasks", async () => {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve([]));
+ const result = await taskQueries.hasPendingTaskForConversation(chain, "conv_empty");
+ expect(result).toBe(false);
+ });
+});
+
+describe("getTraceAgentsByTaskIds", () => {
+ it("returns empty map for empty taskIds", async () => {
+ const result = await taskQueries.getTraceAgentsByTaskIds(null as any, [], "ws_1");
+ expect(result).toBeInstanceOf(Map);
+ expect(result.size).toBe(0);
+ });
+});
diff --git a/src/shared/test/queries/whitelist.test.ts b/src/shared/test/queries/whitelist.test.ts
new file mode 100644
index 000000000..4a86e1903
--- /dev/null
+++ b/src/shared/test/queries/whitelist.test.ts
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi } from "vitest";
+import * as whitelistQueries from "../../src/db/queries/whitelist";
+
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.limit = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.onConflictDoNothing = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.delete = vi.fn(() => chain);
+ return chain;
+}
+
+describe("whitelist query module exports", () => {
+ it("exports getWhitelist", () => {
+ expect(typeof whitelistQueries.getWhitelist).toBe("function");
+ });
+
+ it("exports addWhitelist", () => {
+ expect(typeof whitelistQueries.addWhitelist).toBe("function");
+ });
+
+ it("exports removeWhitelist", () => {
+ expect(typeof whitelistQueries.removeWhitelist).toBe("function");
+ });
+
+ it("exports removeWhitelistByEmail", () => {
+ expect(typeof whitelistQueries.removeWhitelistByEmail).toBe("function");
+ });
+
+ it("exports isWhitelisted", () => {
+ expect(typeof whitelistQueries.isWhitelisted).toBe("function");
+ });
+
+ it("exports buildWhitelistSet", () => {
+ expect(typeof whitelistQueries.buildWhitelistSet).toBe("function");
+ });
+});
+
+describe("addWhitelist", () => {
+ it("returns null when insert conflicts (no row returned)", async () => {
+ const mockDb = createMockDb([]);
+ mockDb.returning = vi.fn(() => Promise.resolve([]));
+ const result = await whitelistQueries.addWhitelist(mockDb, "ag_1", "ws_1", "[email protected]");
+ expect(result).toBeNull();
+ });
+});
+
+describe("removeWhitelist", () => {
+ it("returns null when no row deleted", async () => {
+ const mockDb = createMockDb([]);
+ mockDb.returning = vi.fn(() => Promise.resolve([]));
+ const result = await whitelistQueries.removeWhitelist(mockDb, "wl_1", "ag_1", "ws_1");
+ expect(result).toBeNull();
+ });
+});
diff --git a/src/shared/test/queries/workspace-file-request.test.ts b/src/shared/test/queries/workspace-file-request.test.ts
new file mode 100644
index 000000000..38b3b2876
--- /dev/null
+++ b/src/shared/test/queries/workspace-file-request.test.ts
@@ -0,0 +1,75 @@
+import { describe, it, expect, vi } from "vitest";
+import * as wfrQueries from "../../src/db/queries/workspace-file-request";
+
+function createMockDb(rows: any[]) {
+ const chain: any = {};
+ chain.select = vi.fn(() => chain);
+ chain.from = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(rows));
+ chain.insert = vi.fn(() => chain);
+ chain.values = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve(rows));
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.delete = vi.fn(() => chain);
+ return chain;
+}
+
+describe("workspace-file-request query module exports", () => {
+ it("exports createRequest", () => {
+ expect(typeof wfrQueries.createRequest).toBe("function");
+ });
+
+ it("exports getPendingByWorkspace", () => {
+ expect(typeof wfrQueries.getPendingByWorkspace).toBe("function");
+ });
+
+ it("exports markDispatched", () => {
+ expect(typeof wfrQueries.markDispatched).toBe("function");
+ });
+
+ it("exports completeRequest", () => {
+ expect(typeof wfrQueries.completeRequest).toBe("function");
+ });
+
+ it("exports getRequest", () => {
+ expect(typeof wfrQueries.getRequest).toBe("function");
+ });
+
+ it("exports expireStale", () => {
+ expect(typeof wfrQueries.expireStale).toBe("function");
+ });
+});
+
+describe("markDispatched", () => {
+ it("does nothing for empty ids array (early return)", async () => {
+ await wfrQueries.markDispatched(null as any, []);
+ });
+});
+
+describe("getRequest", () => {
+ it("returns null when request not found", async () => {
+ const mockDb = createMockDb([]);
+ const result = await wfrQueries.getRequest(mockDb, "wfr_missing");
+ expect(result).toBeNull();
+ });
+
+ it("returns request when found", async () => {
+ const row = { id: "wfr_1", status: "pending", path: "/test" };
+ const mockDb = createMockDb([row]);
+ const result = await wfrQueries.getRequest(mockDb, "wfr_1");
+ expect(result).toEqual(row);
+ });
+});
+
+describe("completeRequest", () => {
+ it("returns null when no row updated", async () => {
+ const chain: any = {};
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.where = vi.fn(() => chain);
+ chain.returning = vi.fn(() => Promise.resolve([]));
+ const result = await wfrQueries.completeRequest(chain, "wfr_missing", { ok: true });
+ expect(result).toBeNull();
+ });
+});
diff --git a/src/shared/test/utils/db-errors.test.ts b/src/shared/test/utils/db-errors.test.ts
new file mode 100644
index 000000000..f99e65640
--- /dev/null
+++ b/src/shared/test/utils/db-errors.test.ts
@@ -0,0 +1,43 @@
+import { describe, it, expect } from "vitest";
+import { isUniqueConstraintError } from "../../src/utils/db-errors";
+
+describe("isUniqueConstraintError", () => {
+ it("returns true for error with SQLITE_CONSTRAINT_UNIQUE code", () => {
+ const err = Object.assign(new Error("constraint failed"), {
+ code: "SQLITE_CONSTRAINT_UNIQUE",
+ });
+ expect(isUniqueConstraintError(err)).toBe(true);
+ });
+
+ it("returns true for error with UNIQUE in message", () => {
+ const err = new Error("UNIQUE constraint failed: table.column");
+ expect(isUniqueConstraintError(err)).toBe(true);
+ });
+
+ it("returns true for DrizzleQueryError wrapping a UNIQUE error as cause", () => {
+ const inner = Object.assign(new Error("constraint"), {
+ code: "SQLITE_CONSTRAINT_UNIQUE",
+ });
+ const outer = Object.assign(new Error("Query failed"), { cause: inner });
+ expect(isUniqueConstraintError(outer)).toBe(true);
+ });
+
+ it("returns true for nested cause chain", () => {
+ const innermost = new Error("UNIQUE constraint failed");
+ const middle = Object.assign(new Error("wrapped"), { cause: innermost });
+ const outer = Object.assign(new Error("top level"), { cause: middle });
+ expect(isUniqueConstraintError(outer)).toBe(true);
+ });
+
+ it("returns false for non-Error values", () => {
+ expect(isUniqueConstraintError(null)).toBe(false);
+ expect(isUniqueConstraintError(undefined)).toBe(false);
+ expect(isUniqueConstraintError("some string")).toBe(false);
+ expect(isUniqueConstraintError(42)).toBe(false);
+ });
+
+ it("returns false for unrelated errors", () => {
+ expect(isUniqueConstraintError(new Error("connection timeout"))).toBe(false);
+ expect(isUniqueConstraintError(new Error("FOREIGN KEY constraint"))).toBe(false);
+ });
+});
diff --git a/src/shared/test/utils/slug.test.ts b/src/shared/test/utils/slug.test.ts
new file mode 100644
index 000000000..4d587caf5
--- /dev/null
+++ b/src/shared/test/utils/slug.test.ts
@@ -0,0 +1,19 @@
+import { describe, it, expect } from "vitest";
+import { generateWorkspaceSlug } from "../../src/utils/slug";
+
+describe("generateWorkspaceSlug", () => {
+ it("starts with 'studio-' prefix", () => {
+ const slug = generateWorkspaceSlug();
+ expect(slug.startsWith("studio-")).toBe(true);
+ });
+
+ it("has correct total length (studio- prefix + 8 char nanoid)", () => {
+ const slug = generateWorkspaceSlug();
+ expect(slug.length).toBe("studio-".length + 8);
+ });
+
+ it("generates unique slugs", () => {
+ const slugs = new Set(Array.from({ length: 100 }, () => generateWorkspaceSlug()));
+ expect(slugs.size).toBe(100);
+ });
+});