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
refactor: switch cache to workspace-wide keys for agents, emails, colleagues
Gus3ec8884b952b
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.tsindex 956bcd82f..028cd40f8 100644--- a/src/cli/daemon/execenv/context.test.ts+++ b/src/cli/daemon/execenv/context.test.ts@@ -144,12 +144,12 @@ describe("buildInstructionContent email tool injection", () => {});const content = buildInstructionContent(task);- expect(content).toContain("## Your Colleagues");+ expect(content).toContain("## YOUR COLLEAGUES");expect(content).toContain("### Scout ([email protected])");expect(content).toContain("A researcher agent");- expect(content).toContain("**When to involve:** Share findings with YOU");+ expect(content).toContain("**DELEGATE when:** Share findings with YOU");expect(content).toContain("### Writer ([email protected])");- expect(content).toContain("**When to involve:** Draft blog posts");+ expect(content).toContain("**DELEGATE when:** Draft blog posts");});it("omits colleagues section when no colleagues", () => {@@ -158,7 +158,7 @@ describe("buildInstructionContent email tool injection", () => {});const content = buildInstructionContent(task);- expect(content).not.toContain("## Your Colleagues");+ expect(content).not.toContain("## YOUR COLLEAGUES");});it("omits colleagues section when colleagues undefined", () => {@@ -167,7 +167,7 @@ describe("buildInstructionContent email tool injection", () => {});const content = buildInstructionContent(task);- expect(content).not.toContain("## Your Colleagues");+ expect(content).not.toContain("## YOUR COLLEAGUES");});it("omits description line for colleague with empty description", () => {@@ -183,7 +183,7 @@ describe("buildInstructionContent email tool injection", () => {const content = buildInstructionContent(task);expect(content).toContain("### Scout ([email protected])");- expect(content).toContain("**When to involve:** Share data");+ expect(content).toContain("**DELEGATE when:** Share data");// Only the header + relationship, no blank description lineconst scoutSection = content.split("### Scout")[1].split("##")[0];expect(scoutSection).not.toMatch(/\n\n\n/);diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex 274798c78..62e6c0d48 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -108,21 +108,25 @@ ${task.agent.instructions}}if (task.agent?.colleagues?.length) {- content += `\n## Your Colleagues-Below are your direct colleagues. You can reach them via email.+ content += `\n## YOUR COLLEAGUES — CHECK BEFORE ACTING+> **STOP. Before you start ANY task, scan the colleague list below.**+> If a colleague's delegation criteria match the current task, you MUST delegate to them via email **instead of doing it yourself**.+> Do NOT attempt work that belongs to a colleague. Delegate first, then wait for their response or coordinate.-**Important:**-- When communicating with a colleague on the **same topic** as an existing email thread, reply to that thread (use --in-reply-to) to keep context together.-- **When starting a NEW topic or task that is unrelated to any previous email thread, you MUST compose a brand new email (do NOT use --in-reply-to). Never hijack an unrelated thread just because you recently emailed that colleague.** Judge by topic/task relevance, not by recency of communication.- - Make sure to send follow-up emails to your colleagues to stop the previous wrong directions or instructions you sent before, don't make your colleague running for nothing.`;for (let i = 0; i < task.agent.colleagues.length; i++) {const c = task.agent.colleagues[i];content += `### ${c.name}${c.email ? ` (${c.email})` : ""}\n`;if (c.description) content += `${c.description}\n`;- if (c.instruction) content += `**When to involve:** ${resolveInstruction(c.instruction, task.agentId)}\n`;+ if (c.instruction) content += `**DELEGATE when:** ${resolveInstruction(c.instruction, task.agentId)}\n`;if (i < task.agent.colleagues.length - 1) content += "\n";}+ content += `+**Email threading rules:**+- When communicating with a colleague on the **same topic** as an existing email thread, reply to that thread (use --in-reply-to) to keep context together.+- **When starting a NEW topic or task that is unrelated to any previous email thread, you MUST compose a brand new email (do NOT use --in-reply-to). Never hijack an unrelated thread just because you recently emailed that colleague.** Judge by topic/task relevance, not by recency of communication.+ - Make sure to send follow-up emails to your colleagues to stop the previous wrong directions or instructions you sent before, don't make your colleague running for nothing.+`;}content += `\n## Alook CLI Toolsdiff --git a/src/shared/src/db/queries/agent-link.ts b/src/shared/src/db/queries/agent-link.tsindex eaa7905ef..c6477b734 100644--- a/src/shared/src/db/queries/agent-link.ts+++ b/src/shared/src/db/queries/agent-link.ts@@ -177,3 +177,40 @@ export async function getColleaguesForAgents(return [...asSource, ...asTarget];}++export async function getAllColleaguesForWorkspace(+ db: Database,+ workspaceId: string,+) {+ const asSource = await db+ .select({+ agentId: agentLink.sourceAgentId,+ name: agent.name,+ emailHandle: agent.emailHandle,+ description: agent.description,+ instruction: agentLink.instruction,+ })+ .from(agentLink)+ .innerJoin(+ agent,+ and(eq(agent.id, agentLink.targetAgentId), eq(agent.workspaceId, agentLink.workspaceId)),+ )+ .where(eq(agentLink.workspaceId, workspaceId));++ const asTarget = await db+ .select({+ agentId: agentLink.targetAgentId,+ name: agent.name,+ emailHandle: agent.emailHandle,+ description: agent.description,+ instruction: agentLink.instruction,+ })+ .from(agentLink)+ .innerJoin(+ agent,+ and(eq(agent.id, agentLink.sourceAgentId), eq(agent.workspaceId, agentLink.workspaceId)),+ )+ .where(eq(agentLink.workspaceId, workspaceId));++ return [...asSource, ...asTarget];+}diff --git a/src/shared/src/db/queries/agent.ts b/src/shared/src/db/queries/agent.tsindex 06a235c07..d0d6da52c 100644--- a/src/shared/src/db/queries/agent.ts+++ b/src/shared/src/db/queries/agent.ts@@ -155,3 +155,14 @@ export async function getAgentsByIds(db: Database, ids: string[], workspaceId: s.from(agent).where(and(inArray(agent.id, ids), eq(agent.workspaceId, workspaceId)));}++export async function getAllAgentsForWorkspace(db: Database, workspaceId: string) {+ return db.select().from(agent).where(eq(agent.workspaceId, workspaceId));+}++export async function getAllHandlesForWorkspace(db: Database, workspaceId: string) {+ return db+ .select({ id: agent.id, emailHandle: agent.emailHandle })+ .from(agent)+ .where(eq(agent.workspaceId, workspaceId));+}diff --git a/src/shared/src/db/queries/channel.ts b/src/shared/src/db/queries/channel.tsindex 850911058..8ce0e96b9 100644--- a/src/shared/src/db/queries/channel.ts+++ b/src/shared/src/db/queries/channel.ts@@ -1,4 +1,4 @@-import { eq, and } from "drizzle-orm";+import { eq, and, asc, sql } from "drizzle-orm";import { channel, conversation } from "../schema";import type { Database } from "../index";@@ -6,11 +6,17 @@ export async function createChannel(db: Database,data: { workspaceId: string; name: string }) {+ const [maxRow] = await db+ .select({ maxPos: sql<number>`COALESCE(MAX(${channel.position}), -1)` })+ .from(channel)+ .where(eq(channel.workspaceId, data.workspaceId));+ const nextPos = (maxRow?.maxPos ?? -1) + 1;const rows = await db.insert(channel).values({workspaceId: data.workspaceId,name: data.name,+ position: nextPos,}).returning();return rows[0]!;@@ -20,7 +26,8 @@ export async function listChannels(db: Database, workspaceId: string) {return db.select().from(channel)- .where(eq(channel.workspaceId, workspaceId));+ .where(eq(channel.workspaceId, workspaceId))+ .orderBy(asc(channel.position));}export async function getChannelByName(@@ -101,3 +108,23 @@ export async function renameChannel(return { ...row, name: newName };}++export async function reorderChannels(+ db: Database,+ workspaceId: string,+ orderedChannelIds: string[],+) {+ await (db as any).batch(+ orderedChannelIds.map((id, i) =>+ db+ .update(channel)+ .set({ position: i })+ .where(+ and(+ eq(channel.id, id),+ eq(channel.workspaceId, workspaceId),+ )+ )+ )+ );+}diff --git a/src/shared/src/db/queries/email-account.ts b/src/shared/src/db/queries/email-account.tsindex a6199bb65..907edf044 100644--- a/src/shared/src/db/queries/email-account.ts+++ b/src/shared/src/db/queries/email-account.ts@@ -108,3 +108,10 @@ export async function getEmailAccountsByAgents(db: Database, agentIds: string[],.from(agentEmailAccount).where(and(inArray(agentEmailAccount.agentId, agentIds), eq(agentEmailAccount.workspaceId, workspaceId)));}++export async function getAllEmailAccountsForWorkspace(db: Database, workspaceId: string) {+ return db+ .select()+ .from(agentEmailAccount)+ .where(eq(agentEmailAccount.workspaceId, workspaceId));+}diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex eae458583..e5658ee16 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -280,6 +280,7 @@ export const channel = sqliteTable(.notNull().references(() => workspace.id, { onDelete: "cascade" }),name: text("name").notNull(),+ position: integer("position").notNull().default(0),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),},(t) => [diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 862adeae1..07bde4aa6 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -75,6 +75,7 @@ export interface Channel {id: string;workspace_id: string;name: string;+ position: number;created_at: string;}diff --git a/src/shared/test/queries/channel.test.ts b/src/shared/test/queries/channel.test.tsindex 97c1a79ea..56def31e5 100644--- a/src/shared/test/queries/channel.test.ts+++ b/src/shared/test/queries/channel.test.ts@@ -25,6 +25,10 @@ describe("channel query module exports", () => {it("exports renameChannel", () => {expect(typeof channelQueries.renameChannel).toBe("function");});++ it("exports reorderChannels", () => {+ expect(typeof channelQueries.reorderChannels).toBe("function");+ });});describe("channel query function signatures", () => {@@ -51,4 +55,8 @@ describe("channel query function signatures", () => {it("renameChannel accepts (db, id, workspaceId, newName)", () => {expect(channelQueries.renameChannel.length).toBe(4);});++ it("reorderChannels accepts (db, workspaceId, orderedChannelIds)", () => {+ expect(channelQueries.reorderChannels.length).toBe(3);+ });});diff --git a/src/web/src/app/api/agent-links/[id]/route.ts b/src/web/src/app/api/agent-links/[id]/route.tsindex 96bd70c1e..533831057 100644--- a/src/web/src/app/api/agent-links/[id]/route.ts+++ b/src/web/src/app/api/agent-links/[id]/route.ts@@ -5,7 +5,7 @@ import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { agentLinkToResponse } from "@/lib/api/responses";-import { invalidateMany, cacheKeys } from "@/lib/cache";+import { invalidate, cacheKeys } from "@/lib/cache";export const PATCH = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -25,10 +25,7 @@ export const PATCH = withAuth(async (req, ctx) => {});if (!updated) return writeError("agent link not found", 404);- await invalidateMany([- cacheKeys.colleaguesByAgent(ws.workspaceId, updated.sourceAgentId),- cacheKeys.colleaguesByAgent(ws.workspaceId, updated.targetAgentId),- ]);+ await invalidate(cacheKeys.allColleagues(ws.workspaceId));return writeJSON(agentLinkToResponse(updated));});@@ -46,10 +43,7 @@ export const DELETE = withAuth(async (req, ctx) => {const deleted = await queries.agentLink.remove(db, id, ws.workspaceId);if (!deleted) return writeError("agent link not found", 404);- await invalidateMany([- cacheKeys.colleaguesByAgent(ws.workspaceId, deleted.sourceAgentId),- cacheKeys.colleaguesByAgent(ws.workspaceId, deleted.targetAgentId),- ]);+ await invalidate(cacheKeys.allColleagues(ws.workspaceId));return writeJSON(agentLinkToResponse(deleted));});diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.tsindex ff8d97c0a..370c50f89 100644--- a/src/web/src/app/api/agent-links/route.ts+++ b/src/web/src/app/api/agent-links/route.ts@@ -10,7 +10,7 @@ import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { agentLinkToResponse } from "@/lib/api/responses";-import { invalidateMany, cacheKeys } from "@/lib/cache";+import { invalidate, cacheKeys } from "@/lib/cache";export const GET = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -55,10 +55,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {targetAgentId: body.target_agent_id,instruction: body.instruction,});- await invalidateMany([- cacheKeys.colleaguesByAgent(ws.workspaceId, body.source_agent_id),- cacheKeys.colleaguesByAgent(ws.workspaceId, body.target_agent_id),- ]);+ await invalidate(cacheKeys.allColleagues(ws.workspaceId));return writeJSON(agentLinkToResponse(created), 201);} catch (e) {if (isUniqueConstraintError(e)) {diff --git a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts b/src/web/src/app/api/agents/[id]/access/[userId]/route.tsindex ea965e67b..3b5a0ddb2 100644--- a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts+++ b/src/web/src/app/api/agents/[id]/access/[userId]/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeError } from "@/lib/middleware/helpers";+import { invalidate, cacheKeys } from "@/lib/cache";export const DELETE = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -23,5 +24,6 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {if (removeWhitelist && member?.userEmail) {await queries.whitelist.removeWhitelistByEmail(db, agentId, ws.workspaceId, member.userEmail);}+ await invalidate(cacheKeys.allAgents(ws.workspaceId));return new Response(null, { status: 204 });});diff --git a/src/web/src/app/api/agents/[id]/access/route.ts b/src/web/src/app/api/agents/[id]/access/route.tsindex 9dc04da70..ccf88e9e5 100644--- a/src/web/src/app/api/agents/[id]/access/route.ts+++ b/src/web/src/app/api/agents/[id]/access/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";+import { invalidate, cacheKeys } from "@/lib/cache";async function requireAgentOwner(db: Database, agentId: string, workspaceId: string, userId: string) {const ag = await queries.agent.getAgent(db, agentId, workspaceId, userId);@@ -43,5 +44,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (member?.userEmail) {await queries.whitelist.addWhitelist(db, id, ws.workspaceId, member.userEmail);}+ await invalidate(cacheKeys.allAgents(ws.workspaceId));return writeJSON({ id: access.id, user_id: access.userId }, 201);});diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.tsindex dd1cb59fe..af73c29a3 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts@@ -78,7 +78,7 @@ export const PATCH = withAuth(async (req, ctx) => {const updated = await queries.emailAccount.updateEmailAccount(db, accountId, ws.workspaceId, data)if (!updated) return writeError("update failed", 500)- await invalidate(cacheKeys.emailAccountsByAgent(ws.workspaceId, agentId));+ await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));const hasCredentialChange = body.imapUsername || body.imapPassword || body.smtpUsername || body.smtpPassword || body.imapHost || body.smtpHostif (hasCredentialChange) {@@ -109,7 +109,7 @@ export const DELETE = withAuth(async (req, ctx) => {const deleted = await queries.emailAccount.deleteEmailAccount(db, accountId, ws.workspaceId)if (!deleted) return writeError("delete failed", 500)- await invalidate(cacheKeys.emailAccountsByAgent(ws.workspaceId, agentId));+ await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));return writeJSON({ ok: true })})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.tsindex 4b9106d9b..d94931aec 100644--- a/src/web/src/app/api/agents/[id]/email-accounts/route.ts+++ b/src/web/src/app/api/agents/[id]/email-accounts/route.ts@@ -86,6 +86,8 @@ export const POST = withAuth(async (req, ctx) => {pollIntervalSeconds: body.pollIntervalSeconds,})+ await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));+try {await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/start?accountId=${account.id}`, {method: "POST",@@ -96,7 +98,7 @@ export const POST = withAuth(async (req, ctx) => {}).catch(() => {})}- await invalidate(cacheKeys.emailAccountsByAgent(ws.workspaceId, agentId));+ await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));return writeJSON(accountToResponse(account), 201)})diff --git a/src/web/src/app/api/agents/[id]/route.ts b/src/web/src/app/api/agents/[id]/route.tsindex 2b317b43f..47366c6b9 100644--- a/src/web/src/app/api/agents/[id]/route.ts+++ b/src/web/src/app/api/agents/[id]/route.ts@@ -73,7 +73,11 @@ export const PATCH = withAuth(async (req, ctx) => {return writeError("agent not found", 404);}- await invalidate(cacheKeys.agent(ws.workspaceId, id));+ await Promise.all([+ invalidate(cacheKeys.agent(ws.workspaceId, id)),+ invalidate(cacheKeys.allAgents(ws.workspaceId)),+ invalidate(cacheKeys.allHandles(ws.workspaceId)),+ ]);return writeJSON(agentToResponse(updated));});@@ -99,7 +103,11 @@ export const DELETE = withAuth(async (req, ctx) => {return writeError("agent not found", 404);}- await invalidate(cacheKeys.agent(ws.workspaceId, id));+ await Promise.all([+ invalidate(cacheKeys.agent(ws.workspaceId, id)),+ invalidate(cacheKeys.allAgents(ws.workspaceId)),+ invalidate(cacheKeys.allHandles(ws.workspaceId)),+ ]);return new Response(null, { status: 204 });});diff --git a/src/web/src/app/api/agents/route.ts b/src/web/src/app/api/agents/route.tsindex d53d88253..6ea252b9d 100644--- a/src/web/src/app/api/agents/route.ts+++ b/src/web/src/app/api/agents/route.ts@@ -8,6 +8,7 @@ import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { agentToResponse } from "@/lib/api/responses";import { TaskService } from "@/lib/services/task";import { sweepStaleState } from "@/lib/services/sweep";+import { invalidate, cacheKeys } from "@/lib/cache";export const GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -83,6 +84,11 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, ctx.email.toLowerCase());}+ await Promise.all([+ invalidate(cacheKeys.allAgents(ws.workspaceId)),+ invalidate(cacheKeys.allHandles(ws.workspaceId)),+ ]);+// Send welcome email to ownerif (newAgent.runtimeId && newAgent.emailHandle && ctx.email && isOnline(runtime.machineLastSeenAt)) {try {diff --git a/src/web/src/app/api/agents/sidebar/reorder/route.ts b/src/web/src/app/api/agents/sidebar/reorder/route.tsindex ab5698b30..cf1eb60b3 100644--- a/src/web/src/app/api/agents/sidebar/reorder/route.ts+++ b/src/web/src/app/api/agents/sidebar/reorder/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeError } from "@/lib/middleware/helpers";+import { cached, cacheKeys } from "@/lib/cache";export const PUT = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -26,7 +27,7 @@ export const PUT = withAuth(async (req: NextRequest, ctx) => {const db = getDb((env as Env).DB);const [agents, existingPins] = await Promise.all([- queries.agent.listAgents(db, ws.workspaceId),+ cached(cacheKeys.allAgents(ws.workspaceId), 300, () => queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId)),queries.agentPin.listPins(db, ws.workspaceId, ctx.userId),]);const agentIds = new Set(agents.map((a) => a.id));diff --git a/src/web/src/app/api/channels/route.test.ts b/src/web/src/app/api/channels/route.test.tsindex d74796a48..3f0780f7c 100644--- a/src/web/src/app/api/channels/route.test.ts+++ b/src/web/src/app/api/channels/route.test.ts@@ -7,6 +7,7 @@ const mockChannelToResponse = vi.fn((c: any) => ({id: c.id,workspace_id: c.workspaceId,name: c.name,+ position: c.position ?? 0,created_at: c.createdAt,}));@@ -76,6 +77,7 @@ describe("GET /api/channels", () => {expect(body).toHaveLength(2);expect(body[0].name).toBe("default");expect(body[0].id).toBe("ch_default");+ expect(body[0].position).toBe(0);expect(body[1].name).toBe("work");});diff --git a/src/web/src/app/api/channels/route.ts b/src/web/src/app/api/channels/route.tsindex a9706a47f..45315202c 100644--- a/src/web/src/app/api/channels/route.ts+++ b/src/web/src/app/api/channels/route.ts@@ -24,6 +24,7 @@ export const GET = withAuth(async (req, ctx) => {id: "ch_default",workspaceId: ws.workspaceId,name: "default",+ position: 0,createdAt: new Date().toISOString(),},...channels,diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex d8cfd3913..af05ceb00 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -14,7 +14,7 @@ import { log } from "@/lib/logger";export const POST = withAuth(async (req: NextRequest, ctx) => {const { env } = getCloudflareContext();const db = getDb((env as Env).DB);- const { cached, cachedBatch, cacheKeys, throttled } = await import("@/lib/cache");+ const { cached, cacheKeys, throttled } = await import("@/lib/cache");const [body, err] = await parseBody(req, PollRequestSchema);if (err) return err;@@ -107,37 +107,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const nonKillTasks = claimed.filter((t) => t.type !== "kill_task");const agentIds = [...new Set(nonKillTasks.map((t) => t.agentId))];- const [allAgents, allEmailAccounts, allColleagues] = agentIds.length > 0- ? await Promise.all([- cachedBatch(- agentIds.map((id) => cacheKeys.agent(ctx.workspaceId!, id)),- 300,- async (missingKeys) => {- const missingIds = missingKeys.map((k) => k.split(":").pop()!);- const agents = await withD1Retry(() => queries.agent.getAgentsByIds(db, missingIds, ctx.workspaceId!));- const result = new Map<string, (typeof agents)[number]>();- for (const a of agents) {- result.set(cacheKeys.agent(ctx.workspaceId!, a.id), a);- }- return result;- },- ).then((m) => [...m.values()]),- Promise.all(- agentIds.map((id) =>- cached(cacheKeys.emailAccountsByAgent(ctx.workspaceId!, id), 900, () =>- queries.emailAccount.getEmailAccountsByAgents(db, [id], ctx.workspaceId!),- ),- ),- ).then((arrays) => arrays.flat()),- Promise.all(- agentIds.map((id) =>- cached(cacheKeys.colleaguesByAgent(ctx.workspaceId!, id), 300, () =>- queries.agentLink.getColleaguesForAgents(db, [id], ctx.workspaceId!),- ).catch(() => [] as Awaited<ReturnType<typeof queries.agentLink.getColleaguesForAgents>>),- ),- ).then((arrays) => arrays.flat()),- ])- : [[], [], [] as Awaited<ReturnType<typeof queries.agentLink.getColleaguesForAgents>>];+ const [cachedAgents, cachedEmailAccounts, cachedColleagues] = await Promise.all([+ cached(cacheKeys.allAgents(ctx.workspaceId!), 300, () => queries.agent.getAllAgentsForWorkspace(db, ctx.workspaceId!)),+ cached(cacheKeys.allEmailAccounts(ctx.workspaceId!), 600, () => queries.emailAccount.getAllEmailAccountsForWorkspace(db, ctx.workspaceId!)),+ cached(cacheKeys.allColleagues(ctx.workspaceId!), 600, () => queries.agentLink.getAllColleaguesForWorkspace(db, ctx.workspaceId!)).catch(() => [] as Awaited<ReturnType<typeof queries.agentLink.getAllColleaguesForWorkspace>>),+ ]);++ const agentIdSet = new Set(agentIds);+ const allAgents = cachedAgents.filter((a) => agentIdSet.has(a.id));+ const allEmailAccounts = cachedEmailAccounts.filter((a) => agentIdSet.has(a.agentId));+ const allColleagues = cachedColleagues.filter((c) => agentIdSet.has(c.agentId));const agentMap = new Map(allAgents.map((a) => [a.id, a]));const emailAccountsByAgent = new Map<string, string[]>();diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex 862c0f014..8a45c5ef1 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -8,6 +8,7 @@ import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { emailToResponse } from "@/lib/api/responses";import { broadcastToUser } from "@/lib/broadcast";+import { cached, cacheKeys } from "@/lib/cache";async function broadcastEmailSentEvent(db: Parameters<typeof queries.message.createMessage>[0],@@ -65,8 +66,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (body.from === alookAddr) {fromAddress = alookAddr;} else {- const accounts = await queries.emailAccount.getEmailAccountsByAgent(db, body.agentId, ws.workspaceId);- const match = accounts.find((a) => a.emailAddress === body.from);+ const allAccounts = await cached(cacheKeys.allEmailAccounts(ws.workspaceId), 600, () => queries.emailAccount.getAllEmailAccountsForWorkspace(db, ws.workspaceId));+ const match = allAccounts.find((a) => a.agentId === body.agentId && a.emailAddress === body.from);if (!match) {return writeError(`email address '${body.from}' is not configured for this agent`, 400);}diff --git a/src/web/src/app/api/studios/route.ts b/src/web/src/app/api/studios/route.tsindex 38e963e1b..bcc5922e4 100644--- a/src/web/src/app/api/studios/route.ts+++ b/src/web/src/app/api/studios/route.ts@@ -9,6 +9,7 @@ import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { agentToResponse, workspaceToResponse, agentLinkToResponse } from "@/lib/api/responses";import { TaskService } from "@/lib/services/task";+import { invalidate, cached, cacheKeys } from "@/lib/cache";function slugify(name: string): string {return name@@ -18,23 +19,27 @@ function slugify(name: string): string {.slice(0, 60);}-async function generateUniqueHandle(- db: ReturnType<typeof getDb>,+function generateUniqueHandleFromSet(+ handleSet: Set<string>,baseName: string,-): Promise<string> {+): string {const base = baseName.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);- if (isValidHandle(base)) {- const existing = await queries.agent.getAgentByHandle(db, base);- if (!existing) return base;+ if (isValidHandle(base) && !handleSet.has(base)) {+ handleSet.add(base);+ return base;}for (let i = 0; i < 5; i++) {const suffix = uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "lowerCase" });const candidate = `${base}-${suffix}`.slice(0, 30);if (!isValidHandle(candidate)) continue;- const existing = await queries.agent.getAgentByHandle(db, candidate);- if (!existing) return candidate;+ if (!handleSet.has(candidate)) {+ handleSet.add(candidate);+ return candidate;+ }}- return `${base}-${nanoid(6)}`;+ const fallback = `${base}-${nanoid(6)}`;+ handleSet.add(fallback);+ return fallback;}type LinkInstruction = { fromLeader: string; toLeader: string };@@ -166,11 +171,14 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// Create agentsconst createdAgents: Array<{ id: string; role: string; name: string; emailHandle: string | null; runtimeId: string | null }> = [];+ const allHandles = await cached(cacheKeys.allHandles(ws.workspaceId), 120, () => queries.agent.getAllHandlesForWorkspace(db, ws.workspaceId));+ const handleSet = new Set(allHandles.map((h) => h.emailHandle).filter(Boolean) as string[]);+for (const member of body.members) {const agentName = member.name || `Agent-${nanoid(4)}`;- const handle = member.email_handle && isValidHandle(member.email_handle)- ? member.email_handle- : await generateUniqueHandle(db, agentName);+ const handle = member.email_handle && isValidHandle(member.email_handle) && !handleSet.has(member.email_handle)+ ? (handleSet.add(member.email_handle), member.email_handle)+ : generateUniqueHandleFromSet(handleSet, agentName);const rc = member.runtime_config;const sanitizedRc: Record<string, unknown> | null = rc@@ -228,6 +236,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}}+ await Promise.all([+ invalidate(cacheKeys.allAgents(ws.workspaceId)),+ invalidate(cacheKeys.allHandles(ws.workspaceId)),+ invalidate(cacheKeys.allColleagues(ws.workspaceId)),+ ]);+// Pin leader agent by defaulttry {await queries.agentPin.pinAgent(db, {diff --git a/src/web/src/components/channel-bar.tsx b/src/web/src/components/channel-bar.tsxindex a636c153f..36375a9f1 100644--- a/src/web/src/components/channel-bar.tsx+++ b/src/web/src/components/channel-bar.tsx@@ -2,6 +2,22 @@import { useState, useRef, useEffect, useCallback } from "react";import { Plus, Pencil, Trash2 } from "lucide-react";+import {+ DndContext,+ closestCenter,+ PointerSensor,+ useSensor,+ useSensors,+ type DragEndEvent,+} from "@dnd-kit/core";+import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";+import {+ SortableContext,+ horizontalListSortingStrategy,+ useSortable,+ arrayMove,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";import { useChannel } from "@/contexts/channel-context";import { cn } from "@/lib/utils";import {@@ -29,12 +45,35 @@ export function ChannelBar() {createChannel,renameChannel,deleteChannel,+ reorderChannels,} = useChannel();const [creating, setCreating] = useState(false);const [renamingId, setRenamingId] = useState<string | null>(null);const [deletingId, setDeletingId] = useState<string | null>(null);+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),+ );++ const defaultChannel = channels.find((c) => c.name === "default");+ const nonDefaultChannels = channels.filter((c) => c.name !== "default");++ const handleDragEnd = useCallback(+ (event: DragEndEvent) => {+ const { active, over } = event;+ if (!over || active.id === over.id) return;++ const oldIndex = nonDefaultChannels.findIndex((c) => c.id === active.id);+ const newIndex = nonDefaultChannels.findIndex((c) => c.id === over.id);+ if (oldIndex === -1 || newIndex === -1) return;++ const reordered = arrayMove(nonDefaultChannels, oldIndex, newIndex);+ reorderChannels(reordered.map((c) => c.id));+ },+ [nonDefaultChannels, reorderChannels],+ );+if (loading) {return (<div className="h-8 flex items-center gap-1.5 px-2 mb-1 shrink-0">@@ -47,44 +86,71 @@ export function ChannelBar() {return (<div className="h-8 flex items-center gap-1.5 px-2 mb-1 overflow-x-auto thin-scrollbar shrink-0">- {channels.map((ch) =>- renamingId === ch.id ? (- <RenameInput- key={ch.id}- currentName={ch.name}- onSave={async (name) => {- try {- await renameChannel(ch.id, name);- } catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to rename");- }- setRenamingId(null);- }}- onCancel={() => setRenamingId(null)}- />- ) : (- <ChannelPill- key={ch.id}- id={ch.id}- name={ch.name}- active={ch.name === activeChannel}- deleting={deletingId === ch.id}- onSelect={() => setActiveChannel(ch.name)}- onRename={() => setRenamingId(ch.id)}- onDeleteRequest={() => setDeletingId(ch.id)}- onDeleteCancel={() => setDeletingId(null)}- onDeleteConfirm={async () => {- try {- await deleteChannel(ch.id);- } catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to delete");- }- setDeletingId(null);- }}- />- )+ {defaultChannel && (+ <ChannelPill+ id={defaultChannel.id}+ name={defaultChannel.name}+ active={defaultChannel.name === activeChannel}+ deleting={false}+ onSelect={() => setActiveChannel(defaultChannel.name)}+ onRename={() => {}}+ onDeleteRequest={() => {}}+ onDeleteCancel={() => {}}+ onDeleteConfirm={() => {}}+ />)}+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[restrictToHorizontalAxis]}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={nonDefaultChannels.map((c) => c.id)}+ strategy={horizontalListSortingStrategy}+ >+ {nonDefaultChannels.map((ch) =>+ renamingId === ch.id ? (+ <RenameInput+ key={ch.id}+ currentName={ch.name}+ onSave={async (name) => {+ try {+ await renameChannel(ch.id, name);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to rename");+ }+ setRenamingId(null);+ }}+ onCancel={() => setRenamingId(null)}+ />+ ) : (+ <SortableChannelPill+ key={ch.id}+ id={ch.id}+ name={ch.name}+ active={ch.name === activeChannel}+ deleting={deletingId === ch.id}+ disabled={renamingId !== null}+ onSelect={() => setActiveChannel(ch.name)}+ onRename={() => setRenamingId(ch.id)}+ onDeleteRequest={() => setDeletingId(ch.id)}+ onDeleteCancel={() => setDeletingId(null)}+ onDeleteConfirm={async () => {+ try {+ await deleteChannel(ch.id);+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Failed to delete");+ }+ setDeletingId(null);+ }}+ />+ ),+ )}+ </SortableContext>+ </DndContext>+{creating ? (<CreateInputonSave={async (name) => {@@ -119,6 +185,49 @@ export function ChannelBar() {);}+function SortableChannelPill({+ id,+ disabled,+ ...props+}: {+ id: string;+ name: string;+ active: boolean;+ deleting: boolean;+ disabled: boolean;+ onSelect: () => void;+ onRename: () => void;+ onDeleteRequest: () => void;+ onDeleteCancel: () => void;+ onDeleteConfirm: () => void;+}) {+ const {+ attributes,+ listeners,+ setNodeRef,+ transform,+ transition,+ isDragging,+ } = useSortable({ id, disabled });++ const style = {+ transform: CSS.Transform.toString(transform),+ transition,+ opacity: isDragging ? 0.5 : 1,+ };++ return (+ <div+ ref={setNodeRef}+ style={style}+ {...attributes}+ {...listeners}+ >+ <ChannelPill id={id} {...props} />+ </div>+ );+}+function ChannelPill({name,active,@@ -264,7 +373,6 @@ function RenameInput({const [value, setValue] = useState(currentName);useEffect(() => {- // Delay focus so the ContextMenu finishes its close transition firstconst id = requestAnimationFrame(() => {ref.current?.focus();ref.current?.select();@@ -297,4 +405,3 @@ function RenameInput({/>);}-diff --git a/src/web/src/contexts/channel-context.tsx b/src/web/src/contexts/channel-context.tsxindex 098f96572..96c696d7f 100644--- a/src/web/src/contexts/channel-context.tsx+++ b/src/web/src/contexts/channel-context.tsx@@ -14,7 +14,9 @@ import {createChannelApi,renameChannelApi,deleteChannelApi,+ reorderChannelsApi,} from "@/lib/api";+import { toast } from "sonner";interface ChannelContextValue {channels: Channel[];@@ -25,6 +27,7 @@ interface ChannelContextValue {createChannel: (name: string) => Promise<Channel>;renameChannel: (id: string, name: string) => Promise<void>;deleteChannel: (id: string) => Promise<void>;+ reorderChannels: (orderedIds: string[]) => Promise<void>;refresh: () => Promise<void>;}@@ -116,6 +119,27 @@ export function ChannelProvider({[workspaceId, channels, activeChannel, setActiveChannel, fetchChannels]);+ const reorderChannels = useCallback(+ async (orderedIds: string[]) => {+ setChannels((current) => {+ const idToChannel = new Map(current.map((c) => [c.id, c]));+ const reordered = orderedIds+ .map((id) => idToChannel.get(id))+ .filter((c): c is Channel => c !== undefined);+ const reorderedSet = new Set(orderedIds);+ const preserved = current.filter((c) => !reorderedSet.has(c.id));+ return [...preserved, ...reordered];+ });+ try {+ await reorderChannelsApi(workspaceId, orderedIds);+ } catch {+ await fetchChannels();+ toast.error("Failed to reorder channels");+ }+ },+ [workspaceId, fetchChannels]+ );+return (<ChannelContext.Providervalue={{@@ -127,6 +151,7 @@ export function ChannelProvider({createChannel,renameChannel,deleteChannel,+ reorderChannels,refresh: fetchChannels,}}>diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 9139e64e0..6f53c1b9d 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -211,6 +211,12 @@ export const deleteChannelApi = (id: string, workspaceId: string) =>method: "DELETE",});+export const reorderChannelsApi = (workspaceId: string, orderedChannelIds: string[]) =>+ apiFetch<void>(`/api/channels/reorder${wsQuery(workspaceId)}`, {+ method: "PUT",+ body: JSON.stringify({ ordered_channel_ids: orderedChannelIds }),+ });+// Conversationsexport const listConversations = (workspaceId: string, channel?: string) =>apiFetch<Conversation[]>(`/api/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tsindex 6e09ffe4d..043f9ef5c 100644--- a/src/web/src/lib/api/responses.test.ts+++ b/src/web/src/lib/api/responses.test.ts@@ -382,18 +382,19 @@ describe("ConversationResponse shape", () => {describe("channelToResponse", () => {it("maps DB fields to API response format", () => {- const res = channelToResponse({ id: "ch_1", workspaceId: "w1", name: "work", createdAt: ts });+ const res = channelToResponse({ id: "ch_1", workspaceId: "w1", name: "work", position: 0, createdAt: ts });expect(res).toEqual({id: "ch_1",workspace_id: "w1",name: "work",+ position: 0,created_at: tsFormatted,});});it("has expected keys: id, workspace_id, name, created_at", () => {- const res = channelToResponse({ id: "ch_1", workspaceId: "w1", name: "personal", createdAt: ts });- expect(Object.keys(res).sort()).toEqual(["created_at", "id", "name", "workspace_id"]);+ const res = channelToResponse({ id: "ch_1", workspaceId: "w1", name: "personal", position: 1, createdAt: ts });+ expect(Object.keys(res).sort()).toEqual(["created_at", "id", "name", "position", "workspace_id"]);});});diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex 031b9d821..882a8b596 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -135,6 +135,7 @@ export function channelToResponse(c: any) {id: c.id,workspace_id: c.workspaceId,name: c.name,+ position: c.position ?? 0,created_at: formatTimestamp(c.createdAt),};}diff --git a/src/web/src/lib/cache.test.ts b/src/web/src/lib/cache.test.tsindex f342c73e7..58719fd0b 100644--- a/src/web/src/lib/cache.test.ts+++ b/src/web/src/lib/cache.test.ts@@ -227,8 +227,10 @@ describe("cache", () => {expect(cacheKeys.agent("ws1", "ag1")).toBe("ag:ws1:ag1");expect(cacheKeys.member("ws1", "usr1")).toBe("mem:ws1:usr1");expect(cacheKeys.user("usr1")).toBe("usr:usr1");- expect(cacheKeys.emailAccountsByAgent("ws1", "ag1")).toBe("ea:ws1:ag1");- expect(cacheKeys.colleaguesByAgent("ws1", "ag1")).toBe("col:ws1:ag1");+ expect(cacheKeys.allEmailAccounts("ws1")).toBe("ea:ws1");+ expect(cacheKeys.allColleagues("ws1")).toBe("col:ws1");+ expect(cacheKeys.allAgents("ws1")).toBe("agents:ws1");+ expect(cacheKeys.allHandles("ws1")).toBe("handles:ws1");expect(cacheKeys.heartbeat("ws1", "d1")).toBe("hb:ws1:d1");expect(cacheKeys.machineToken("al_1234567890abcdefghij_rest")).toBe("mt:al_1234567890abcdefg");expect(cacheKeys.machineTokenLastUsed("al_1234567890abcdefghij_rest")).toBe("mt_lu:al_1234567890abcdefg");diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.tsindex 27d2b3a65..617ea90cd 100644--- a/src/web/src/lib/cache.ts+++ b/src/web/src/lib/cache.ts@@ -140,6 +140,8 @@ export const cacheKeys = {agent: (workspaceId: string, agentId: string) => `ag:${workspaceId}:${agentId}`,heartbeat: (workspaceId: string, daemonId: string) => `hb:${workspaceId}:${daemonId}`,user: (userId: string) => `usr:${userId}`,- emailAccountsByAgent: (workspaceId: string, agentId: string) => `ea:${workspaceId}:${agentId}`,- colleaguesByAgent: (workspaceId: string, agentId: string) => `col:${workspaceId}:${agentId}`,+ allAgents: (workspaceId: string) => `agents:${workspaceId}`,+ allEmailAccounts: (workspaceId: string) => `ea:${workspaceId}`,+ allColleagues: (workspaceId: string) => `col:${workspaceId}`,+ allHandles: (workspaceId: string) => `handles:${workspaceId}`,};