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
import Sqlite from "better-sqlite3";
import { drizzle } from "drizzle-orm/better-sqlite3";
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import type { Database } from "../../src/db";
import {
createThreadChannel, listChildChannelsByParentMessageIds,
} from "../../src/db/queries/community/channel";
/**
* `createThreadChannel` mixes two `db.select()` round trips (parent-channel
* lookup, parent-message lookup, run via `Promise.all`) with one `db.insert()`
* and a final `db.select()` re-fetch (via `getChannel`). The thenable-chain
* trick from `community-agent-inbox.test.ts` covers the selects (FIFO by
* call order); `insert` is mocked separately since its shape
* (`.values().returning()`) never varies here.
*/
function createMockDb(opts: {
selectResponses: unknown[][];
insertedId: string;
}) {
let call = 0;
const methods = ["from", "where"];
const select = vi.fn(() => {
const idx = call++;
const chain: any = {};
for (const m of methods) chain[m] = vi.fn(() => chain);
chain.then = (resolve: any, reject: any) =>
Promise.resolve(opts.selectResponses[idx] ?? []).then(resolve, reject);
return chain;
});
const insertValues = vi.fn();
const insert = vi.fn(() => ({
values: vi.fn((v: any) => {
insertValues(v);
return { returning: vi.fn(() => Promise.resolve([{ id: opts.insertedId }])) };
}),
}));
return { select, insert, __insertValues: insertValues } as any;
}
describe("createThreadChannel", () => {
it("derives the thread name from the parent message's first 40 chars, trimmed", async () => {
const longContent = " " + "x".repeat(60) + " ";
const db = createMockDb({
selectResponses: [
[{ serverId: "srv_1" }], // parent channel lookup
[{ content: longContent }], // parent message lookup
[{ id: "thread_1", serverId: "srv_1", name: "x".repeat(40), type: "thread" }], // getChannel re-fetch
],
insertedId: "thread_1",
});
await createThreadChannel(db, "ch_parent", "m_root", "u_1");
expect(db.__insertValues).toHaveBeenCalledWith(
expect.objectContaining({ name: "x".repeat(40), type: "thread" })
);
});
it("falls back to the literal 'Thread' when the parent message has no usable text", async () => {
const db = createMockDb({
selectResponses: [
[{ serverId: "srv_1" }],
[{ content: " " }], // whitespace-only → trims to empty
[{ id: "thread_1", serverId: "srv_1", name: "Thread", type: "thread" }],
],
insertedId: "thread_1",
});
await createThreadChannel(db, "ch_parent", "m_root", "u_1");
expect(db.__insertValues).toHaveBeenCalledWith(expect.objectContaining({ name: "Thread" }));
});
it("always sets type: 'thread' — never inherits the parent's own type", async () => {
const db = createMockDb({
selectResponses: [
[{ serverId: "srv_1" }],
[{ content: "hello" }],
[{ id: "thread_1", serverId: "srv_1", name: "hello", type: "thread" }],
],
insertedId: "thread_1",
});
await createThreadChannel(db, "ch_parent", "m_root", "u_1");
expect(db.__insertValues).toHaveBeenCalledWith(expect.objectContaining({ type: "thread" }));
});
it("sets parentChannelId/parentMessageId/creatorId on the insert, and returns the re-fetched channel", async () => {
const db = createMockDb({
selectResponses: [
[{ serverId: "srv_1" }],
[{ content: "hello" }],
[{ id: "thread_1", serverId: "srv_1", name: "hello", type: "thread" }],
],
insertedId: "thread_1",
});
const created = await createThreadChannel(db, "ch_parent", "m_root", "u_creator");
expect(db.__insertValues).toHaveBeenCalledWith(
expect.objectContaining({
parentChannelId: "ch_parent",
parentMessageId: "m_root",
creatorId: "u_creator",
serverId: "srv_1",
})
);
expect(created).toMatchObject({ id: "thread_1", serverId: "srv_1" });
});
it("throws if the parent channel can't be found (defensive — resolver should never call it this way)", async () => {
const db = createMockDb({ selectResponses: [[], [{ content: "hi" }]], insertedId: "x" });
await expect(createThreadChannel(db, "ch_missing", "m_root", "u_1")).rejects.toThrow(/not found/);
});
it("throws when the parent is itself a child channel (forum post / thread) — no grandchild threads, closes the private-forum leak", async () => {
const db = createMockDb({
// parent-channel lookup returns a row whose own parentChannelId is set →
// it's a child thread, not a top-level channel.
selectResponses: [[{ serverId: "srv_1", parentChannelId: "forum_1" }], [{ content: "hi" }]],
insertedId: "x",
});
await expect(createThreadChannel(db, "forum_post_1", "m_root", "u_1")).rejects.toThrow(/child channel/);
expect(db.__insertValues).not.toHaveBeenCalled();
});
});
describe("createThreadChannel against real SQLite", () => {
let sqlite: Sqlite.Database;
let db: Database;
beforeEach(() => {
sqlite = new Sqlite(":memory:");
sqlite.exec(`
CREATE TABLE community_channel (
id TEXT PRIMARY KEY,
server_id TEXT,
category_id TEXT,
name TEXT,
type TEXT NOT NULL DEFAULT 'text',
topic TEXT DEFAULT '',
position INTEGER DEFAULT 0,
parent_channel_id TEXT,
creator_id TEXT,
message_count INTEGER DEFAULT 0,
archived INTEGER DEFAULT 0,
parent_message_id TEXT,
last_message_at TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE community_message (
id TEXT PRIMARY KEY,
content TEXT NOT NULL
);
INSERT INTO community_channel
(id, server_id, name, type, created_at)
VALUES
('parent_1', 'server_1', 'general', 'text', '2026-08-14T00:00:00.000Z');
INSERT INTO community_message (id, content)
VALUES ('message_1', 'Thread from a real query');
`);
db = drizzle(sqlite) as unknown as Database;
});
afterEach(() => sqlite.close());
it("projects the parent server from the joined query table and creates the child", async () => {
const created = await createThreadChannel(
db,
"parent_1",
"message_1",
"creator_1",
);
expect(created).toMatchObject({
serverId: "server_1",
parentChannelId: "parent_1",
parentMessageId: "message_1",
creatorId: "creator_1",
type: "thread",
name: "Thread from a real query",
});
});
it("bounds message enrichment to parent and page IDs while retaining ordinary legacy types and archived indicators", async () => {
const insert = sqlite.prepare("INSERT INTO community_channel (id, server_id, type, parent_channel_id, parent_message_id, archived, last_message_at, created_at) VALUES (?, 'server_1', ?, ?, ?, ?, ?, 'now')");
insert.run("current", "thread", "parent_1", "page_1", 0, "3");
insert.run("archived", "thread", "parent_1", "page_1", 1, "1");
insert.run("legacy", "text", "parent_1", "page_2", 0, "2");
insert.run("off_page", "thread", "parent_1", "other_message", 0, "4");
insert.run("foreign_parent", "thread", "another_parent", "page_1", 0, "5");
const rows = await listChildChannelsByParentMessageIds(db, "parent_1", ["page_1", "page_2"], null);
expect(rows.map(row => row.id)).toEqual(["current", "legacy", "archived"]);
expect((await listChildChannelsByParentMessageIds(db, "parent_1", ["page_1", "page_2"])).map(row => row.id).sort()).toEqual(["archived", "current"]);
const select = vi.spyOn(db, "select");
expect(await listChildChannelsByParentMessageIds(db, "parent_1", [], null)).toEqual([]);
expect(select).not.toHaveBeenCalled();
});
});